source: src/SymTab/Validate.cc @ 095b99a

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 095b99a was 095b99a, checked in by Andrew Beach <ajbeach@…>, 4 years ago

Added TimeCall? as a more flexible alternative to TimeBlock?. TimeBlock? remains for when you create a block like lambda.

  • Property mode set to 100644
File size: 69.6 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Validate.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:50:04 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Dec 13 23:43:34 2019
13// Update Count     : 363
14//
15
16// The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be
17// as regular in structure as possible.  Some assumptions can be made regarding the state of the tree after this pass is
18// complete, including:
19//
20// - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or
21//   union.
22//
23// - All enumeration constants have type EnumInstType.
24//
25// - The type "void" never occurs in lists of function parameter or return types.  A function
26//   taking no arguments has no argument types.
27//
28// - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated
29//   by the particular set of type arguments.
30//
31// - Every declaration is assigned a unique id.
32//
33// - No typedef declarations or instances exist; the actual type is substituted for each instance.
34//
35// - Each type, struct, and union definition is followed by an appropriate assignment operator.
36//
37// - Each use of a struct or union is connected to a complete definition of that struct or union, even if that
38//   definition occurs later in the input.
39
40#include "Validate.h"
41
42#include <cassert>                     // for assertf, assert
43#include <cstddef>                     // for size_t
44#include <list>                        // for list
45#include <string>                      // for string
46#include <unordered_map>               // for unordered_map
47#include <utility>                     // for pair
48
49#include "AST/Chain.hpp"
50#include "AST/Decl.hpp"
51#include "AST/Node.hpp"
52#include "AST/Pass.hpp"
53#include "AST/SymbolTable.hpp"
54#include "AST/Type.hpp"
55#include "AST/TypeSubstitution.hpp"
56#include "CodeGen/CodeGenerator.h"     // for genName
57#include "CodeGen/OperatorTable.h"     // for isCtorDtor, isCtorDtorAssign
58#include "ControlStruct/Mutate.h"      // for ForExprMutator
59#include "Common/CodeLocation.h"       // for CodeLocation
60#include "Common/Stats.h"              // for Stats::Heap
61#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
62#include "Common/ScopedMap.h"          // for ScopedMap
63#include "Common/SemanticError.h"      // for SemanticError
64#include "Common/UniqueName.h"         // for UniqueName
65#include "Common/utility.h"            // for operator+, cloneAll, deleteAll
66#include "Concurrency/Keywords.h"      // for applyKeywords
67#include "FixFunction.h"               // for FixFunction
68#include "Indexer.h"                   // for Indexer
69#include "InitTweak/GenInit.h"         // for fixReturnStatements
70#include "InitTweak/InitTweak.h"       // for isCtorDtorAssign
71#include "ResolvExpr/typeops.h"        // for typesCompatible
72#include "ResolvExpr/Resolver.h"       // for findSingleExpression
73#include "ResolvExpr/ResolveTypeof.h"  // for resolveTypeof
74#include "SymTab/Autogen.h"            // for SizeType
75#include "SynTree/LinkageSpec.h"       // for C
76#include "SynTree/Attribute.h"         // for noAttributes, Attribute
77#include "SynTree/Constant.h"          // for Constant
78#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
79#include "SynTree/Expression.h"        // for CompoundLiteralExpr, Expressio...
80#include "SynTree/Initializer.h"       // for ListInit, Initializer
81#include "SynTree/Label.h"             // for operator==, Label
82#include "SynTree/Mutator.h"           // for Mutator
83#include "SynTree/Type.h"              // for Type, TypeInstType, EnumInstType
84#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
85#include "SynTree/Visitor.h"           // for Visitor
86#include "Validate/HandleAttributes.h" // for handleAttributes
87#include "Validate/FindSpecialDecls.h" // for FindSpecialDecls
88
89class CompoundStmt;
90class ReturnStmt;
91class SwitchStmt;
92
93#define debugPrint( x ) if ( doDebug ) x
94
95namespace SymTab {
96        /// hoists declarations that are difficult to hoist while parsing
97        struct HoistTypeDecls final : public WithDeclsToAdd {
98                void previsit( SizeofExpr * );
99                void previsit( AlignofExpr * );
100                void previsit( UntypedOffsetofExpr * );
101                void previsit( CompoundLiteralExpr * );
102                void handleType( Type * );
103        };
104
105        struct FixQualifiedTypes final : public WithIndexer {
106                Type * postmutate( QualifiedType * );
107        };
108
109        struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
110                /// Flattens nested struct types
111                static void hoistStruct( std::list< Declaration * > &translationUnit );
112
113                void previsit( StructDecl * aggregateDecl );
114                void previsit( UnionDecl * aggregateDecl );
115                void previsit( StaticAssertDecl * assertDecl );
116                void previsit( StructInstType * type );
117                void previsit( UnionInstType * type );
118                void previsit( EnumInstType * type );
119
120          private:
121                template< typename AggDecl > void handleAggregate( AggDecl * aggregateDecl );
122
123                AggregateDecl * parentAggr = nullptr;
124        };
125
126        /// Fix return types so that every function returns exactly one value
127        struct ReturnTypeFixer {
128                static void fix( std::list< Declaration * > &translationUnit );
129
130                void postvisit( FunctionDecl * functionDecl );
131                void postvisit( FunctionType * ftype );
132        };
133
134        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
135        struct EnumAndPointerDecay_old {
136                void previsit( EnumDecl * aggregateDecl );
137                void previsit( FunctionType * func );
138        };
139
140        /// Associates forward declarations of aggregates with their definitions
141        struct LinkReferenceToTypes_old final : public WithIndexer, public WithGuards, public WithVisitorRef<LinkReferenceToTypes_old>, public WithShortCircuiting {
142                LinkReferenceToTypes_old( const Indexer * indexer );
143                void postvisit( TypeInstType * typeInst );
144
145                void postvisit( EnumInstType * enumInst );
146                void postvisit( StructInstType * structInst );
147                void postvisit( UnionInstType * unionInst );
148                void postvisit( TraitInstType * traitInst );
149                void previsit( QualifiedType * qualType );
150                void postvisit( QualifiedType * qualType );
151
152                void postvisit( EnumDecl * enumDecl );
153                void postvisit( StructDecl * structDecl );
154                void postvisit( UnionDecl * unionDecl );
155                void postvisit( TraitDecl * traitDecl );
156
157                void previsit( StructDecl * structDecl );
158                void previsit( UnionDecl * unionDecl );
159
160                void renameGenericParams( std::list< TypeDecl * > & params );
161
162          private:
163                const Indexer * local_indexer;
164
165                typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
166                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
167                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
168                ForwardEnumsType forwardEnums;
169                ForwardStructsType forwardStructs;
170                ForwardUnionsType forwardUnions;
171                /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
172                bool inGeneric = false;
173        };
174
175        /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
176        struct ForallPointerDecay_old final {
177                void previsit( ObjectDecl * object );
178                void previsit( FunctionDecl * func );
179                void previsit( FunctionType * ftype );
180                void previsit( StructDecl * aggrDecl );
181                void previsit( UnionDecl * aggrDecl );
182        };
183
184        struct ReturnChecker : public WithGuards {
185                /// Checks that return statements return nothing if their return type is void
186                /// and return something if the return type is non-void.
187                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
188
189                void previsit( FunctionDecl * functionDecl );
190                void previsit( ReturnStmt * returnStmt );
191
192                typedef std::list< DeclarationWithType * > ReturnVals;
193                ReturnVals returnVals;
194        };
195
196        struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd {
197                ReplaceTypedef() : scopeLevel( 0 ) {}
198                /// Replaces typedefs by forward declarations
199                static void replaceTypedef( std::list< Declaration * > &translationUnit );
200
201                void premutate( QualifiedType * );
202                Type * postmutate( QualifiedType * qualType );
203                Type * postmutate( TypeInstType * aggregateUseType );
204                Declaration * postmutate( TypedefDecl * typeDecl );
205                void premutate( TypeDecl * typeDecl );
206                void premutate( FunctionDecl * funcDecl );
207                void premutate( ObjectDecl * objDecl );
208                DeclarationWithType * postmutate( ObjectDecl * objDecl );
209
210                void premutate( CastExpr * castExpr );
211
212                void premutate( CompoundStmt * compoundStmt );
213
214                void premutate( StructDecl * structDecl );
215                void premutate( UnionDecl * unionDecl );
216                void premutate( EnumDecl * enumDecl );
217                void premutate( TraitDecl * );
218
219                void premutate( FunctionType * ftype );
220
221          private:
222                template<typename AggDecl>
223                void addImplicitTypedef( AggDecl * aggDecl );
224                template< typename AggDecl >
225                void handleAggregate( AggDecl * aggr );
226
227                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
228                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
229                typedef ScopedMap< std::string, TypeDecl * > TypeDeclMap;
230                TypedefMap typedefNames;
231                TypeDeclMap typedeclNames;
232                int scopeLevel;
233                bool inFunctionType = false;
234        };
235
236        struct EliminateTypedef {
237                /// removes TypedefDecls from the AST
238                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
239
240                template<typename AggDecl>
241                void handleAggregate( AggDecl * aggregateDecl );
242
243                void previsit( StructDecl * aggregateDecl );
244                void previsit( UnionDecl * aggregateDecl );
245                void previsit( CompoundStmt * compoundStmt );
246        };
247
248        struct VerifyCtorDtorAssign {
249                /// ensure that constructors, destructors, and assignment have at least one
250                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
251                /// return values.
252                static void verify( std::list< Declaration * > &translationUnit );
253
254                void previsit( FunctionDecl * funcDecl );
255        };
256
257        /// ensure that generic types have the correct number of type arguments
258        struct ValidateGenericParameters {
259                void previsit( StructInstType * inst );
260                void previsit( UnionInstType * inst );
261        };
262
263        struct FixObjectType : public WithIndexer {
264                /// resolves typeof type in object, function, and type declarations
265                static void fix( std::list< Declaration * > & translationUnit );
266
267                void previsit( ObjectDecl * );
268                void previsit( FunctionDecl * );
269                void previsit( TypeDecl * );
270        };
271
272        struct ArrayLength : public WithIndexer {
273                /// for array types without an explicit length, compute the length and store it so that it
274                /// is known to the rest of the phases. For example,
275                ///   int x[] = { 1, 2, 3 };
276                ///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
277                /// here x and y are known at compile-time to have length 3, so change this into
278                ///   int x[3] = { 1, 2, 3 };
279                ///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
280                static void computeLength( std::list< Declaration * > & translationUnit );
281
282                void previsit( ObjectDecl * objDecl );
283                void previsit( ArrayType * arrayType );
284        };
285
286        struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
287                Type::StorageClasses storageClasses;
288
289                void premutate( ObjectDecl * objectDecl );
290                Expression * postmutate( CompoundLiteralExpr * compLitExpr );
291        };
292
293        struct LabelAddressFixer final : public WithGuards {
294                std::set< Label > labels;
295
296                void premutate( FunctionDecl * funcDecl );
297                Expression * postmutate( AddressExpr * addrExpr );
298        };
299
300        void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
301                PassVisitor<EnumAndPointerDecay_old> epc;
302                PassVisitor<LinkReferenceToTypes_old> lrt( nullptr );
303                PassVisitor<ForallPointerDecay_old> fpd;
304                PassVisitor<CompoundLiteral> compoundliteral;
305                PassVisitor<ValidateGenericParameters> genericParams;
306                PassVisitor<LabelAddressFixer> labelAddrFixer;
307                PassVisitor<HoistTypeDecls> hoistDecls;
308                PassVisitor<FixQualifiedTypes> fixQual;
309
310                {
311                        Stats::Heap::newPass("validate-A");
312                        Stats::Time::BlockGuard guard("validate-A");
313                        acceptAll( translationUnit, hoistDecls );
314                        ReplaceTypedef::replaceTypedef( translationUnit );
315                        ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
316                        acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes_old because it is an indexer and needs correct types for mangling
317                }
318                {
319                        Stats::Heap::newPass("validate-B");
320                        Stats::Time::BlockGuard guard("validate-B");
321                        Stats::Time::TimeBlock("Link Reference To Types", [&]() {
322                                acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
323                        });
324                        Stats::Time::TimeBlock("Fix Qualified Types", [&]() {
325                                mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes_old, because aggregate members are accessed
326                        });
327                        Stats::Time::TimeBlock("Hoist Structs", [&]() {
328                                HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order
329                        });
330                        Stats::Time::TimeBlock("Eliminate Typedefs", [&]() {
331                                EliminateTypedef::eliminateTypedef( translationUnit ); //
332                        });
333                }
334                {
335                        Stats::Heap::newPass("validate-C");
336                        Stats::Time::BlockGuard guard("validate-C");
337                        acceptAll( translationUnit, genericParams );  // check as early as possible - can't happen before LinkReferenceToTypes_old
338                        VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
339                        ReturnChecker::checkFunctionReturns( translationUnit );
340                        InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
341                }
342                {
343                        Stats::Heap::newPass("validate-D");
344                        Stats::Time::BlockGuard guard("validate-D");
345                        Stats::Time::TimeBlock("Apply Concurrent Keywords", [&]() {
346                                Concurrency::applyKeywords( translationUnit );
347                        });
348                        Stats::Time::TimeBlock("Forall Pointer Decay", [&]() {
349                                acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
350                        });
351                        Stats::Time::TimeBlock("Hoist Control Declarations", [&]() {
352                                ControlStruct::hoistControlDecls( translationUnit );  // hoist initialization out of for statements; must happen before autogenerateRoutines
353                        });
354                        Stats::Time::TimeBlock("Generate Autogen routines", [&]() {
355                                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay_old
356                        });
357                }
358                {
359                        Stats::Heap::newPass("validate-E");
360                        Stats::Time::BlockGuard guard("validate-E");
361                        Stats::Time::TimeBlock("Implement Mutex Func", [&]() {
362                                Concurrency::implementMutexFuncs( translationUnit );
363                        });
364                        Stats::Time::TimeBlock("Implement Thread Start", [&]() {
365                                Concurrency::implementThreadStarter( translationUnit );
366                        });
367                        Stats::Time::TimeBlock("Compound Literal", [&]() {
368                                mutateAll( translationUnit, compoundliteral );
369                        });
370                        Stats::Time::TimeBlock("Resolve With Expressions", [&]() {
371                                ResolvExpr::resolveWithExprs( translationUnit ); // must happen before FixObjectType because user-code is resolved and may contain with variables
372                        });
373                }
374                {
375                        Stats::Heap::newPass("validate-F");
376                        Stats::Time::BlockGuard guard("validate-F");
377                        Stats::Time::TimeCall("Fix Object Type",
378                                FixObjectType::fix, translationUnit);
379                        Stats::Time::TimeCall("Array Length",
380                                ArrayLength::computeLength, translationUnit);
381                        Stats::Time::TimeCall("Find Special Declarations",
382                                Validate::findSpecialDecls, translationUnit);
383                        Stats::Time::TimeCall("Fix Label Address",
384                                mutateAll<LabelAddressFixer>, translationUnit, labelAddrFixer);
385                        Stats::Time::TimeCall("Handle Attributes",
386                                Validate::handleAttributes, translationUnit);
387                }
388        }
389
390        void validateType( Type * type, const Indexer * indexer ) {
391                PassVisitor<EnumAndPointerDecay_old> epc;
392                PassVisitor<LinkReferenceToTypes_old> lrt( indexer );
393                PassVisitor<ForallPointerDecay_old> fpd;
394                type->accept( epc );
395                type->accept( lrt );
396                type->accept( fpd );
397        }
398
399
400        void HoistTypeDecls::handleType( Type * type ) {
401                // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here
402                AggregateDecl * aggr = nullptr;
403                if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) {
404                        aggr = inst->baseStruct;
405                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) {
406                        aggr = inst->baseUnion;
407                } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) {
408                        aggr = inst->baseEnum;
409                }
410                if ( aggr && aggr->body ) {
411                        declsToAddBefore.push_front( aggr );
412                }
413        }
414
415        void HoistTypeDecls::previsit( SizeofExpr * expr ) {
416                handleType( expr->type );
417        }
418
419        void HoistTypeDecls::previsit( AlignofExpr * expr ) {
420                handleType( expr->type );
421        }
422
423        void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) {
424                handleType( expr->type );
425        }
426
427        void HoistTypeDecls::previsit( CompoundLiteralExpr * expr ) {
428                handleType( expr->result );
429        }
430
431
432        Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) {
433                Type * parent = qualType->parent;
434                Type * child = qualType->child;
435                if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) {
436                        // .T => lookup T at global scope
437                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
438                                auto td = indexer.globalLookupType( inst->name );
439                                if ( ! td ) {
440                                        SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) );
441                                }
442                                auto base = td->base;
443                                assert( base );
444                                Type * ret = base->clone();
445                                ret->get_qualifiers() = qualType->get_qualifiers();
446                                return ret;
447                        } else {
448                                // .T => T is not a type name
449                                assertf( false, "unhandled global qualified child type: %s", toCString(child) );
450                        }
451                } else {
452                        // S.T => S must be an aggregate type, find the declaration for T in S.
453                        AggregateDecl * aggr = nullptr;
454                        if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) {
455                                aggr = inst->baseStruct;
456                        } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) {
457                                aggr = inst->baseUnion;
458                        } else {
459                                SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) );
460                        }
461                        assert( aggr ); // TODO: need to handle forward declarations
462                        for ( Declaration * member : aggr->members ) {
463                                if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
464                                        // name on the right is a typedef
465                                        if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) {
466                                                if ( aggr->name == inst->name ) {
467                                                        assert( aggr->base );
468                                                        Type * ret = aggr->base->clone();
469                                                        ret->get_qualifiers() = qualType->get_qualifiers();
470                                                        TypeSubstitution sub = parent->genericSubstitution();
471                                                        sub.apply(ret);
472                                                        return ret;
473                                                }
474                                        }
475                                } else {
476                                        // S.T - S is not an aggregate => error
477                                        assertf( false, "unhandled qualified child type: %s", toCString(qualType) );
478                                }
479                        }
480                        // failed to find a satisfying definition of type
481                        SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) );
482                }
483
484                // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup?
485        }
486
487
488        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
489                PassVisitor<HoistStruct> hoister;
490                acceptAll( translationUnit, hoister );
491        }
492
493        bool shouldHoist( Declaration * decl ) {
494                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl );
495        }
496
497        namespace {
498                void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) {
499                        if ( aggr->parent ) qualifiedName( aggr->parent, ss );
500                        ss << "__" << aggr->name;
501                }
502
503                // mangle nested type names using entire parent chain
504                std::string qualifiedName( AggregateDecl * aggr ) {
505                        std::ostringstream ss;
506                        qualifiedName( aggr, ss );
507                        return ss.str();
508                }
509        }
510
511        template< typename AggDecl >
512        void HoistStruct::handleAggregate( AggDecl * aggregateDecl ) {
513                if ( parentAggr ) {
514                        aggregateDecl->parent = parentAggr;
515                        aggregateDecl->name = qualifiedName( aggregateDecl );
516                        // Add elements in stack order corresponding to nesting structure.
517                        declsToAddBefore.push_front( aggregateDecl );
518                } else {
519                        GuardValue( parentAggr );
520                        parentAggr = aggregateDecl;
521                } // if
522                // Always remove the hoisted aggregate from the inner structure.
523                GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } );
524        }
525
526        void HoistStruct::previsit( StaticAssertDecl * assertDecl ) {
527                if ( parentAggr ) {
528                        declsToAddBefore.push_back( assertDecl );
529                }
530        }
531
532        void HoistStruct::previsit( StructDecl * aggregateDecl ) {
533                handleAggregate( aggregateDecl );
534        }
535
536        void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
537                handleAggregate( aggregateDecl );
538        }
539
540        void HoistStruct::previsit( StructInstType * type ) {
541                // need to reset type name after expanding to qualified name
542                assert( type->baseStruct );
543                type->name = type->baseStruct->name;
544        }
545
546        void HoistStruct::previsit( UnionInstType * type ) {
547                assert( type->baseUnion );
548                type->name = type->baseUnion->name;
549        }
550
551        void HoistStruct::previsit( EnumInstType * type ) {
552                assert( type->baseEnum );
553                type->name = type->baseEnum->name;
554        }
555
556
557        bool isTypedef( Declaration * decl ) {
558                return dynamic_cast< TypedefDecl * >( decl );
559        }
560
561        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
562                PassVisitor<EliminateTypedef> eliminator;
563                acceptAll( translationUnit, eliminator );
564                filter( translationUnit, isTypedef, true );
565        }
566
567        template< typename AggDecl >
568        void EliminateTypedef::handleAggregate( AggDecl * aggregateDecl ) {
569                filter( aggregateDecl->members, isTypedef, true );
570        }
571
572        void EliminateTypedef::previsit( StructDecl * aggregateDecl ) {
573                handleAggregate( aggregateDecl );
574        }
575
576        void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) {
577                handleAggregate( aggregateDecl );
578        }
579
580        void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) {
581                // remove and delete decl stmts
582                filter( compoundStmt->kids, [](Statement * stmt) {
583                        if ( DeclStmt * declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
584                                if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) {
585                                        return true;
586                                } // if
587                        } // if
588                        return false;
589                }, true);
590        }
591
592        void EnumAndPointerDecay_old::previsit( EnumDecl * enumDecl ) {
593                // Set the type of each member of the enumeration to be EnumConstant
594                for ( std::list< Declaration * >::iterator i = enumDecl->members.begin(); i != enumDecl->members.end(); ++i ) {
595                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( * i );
596                        assert( obj );
597                        obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->name ) );
598                } // for
599        }
600
601        namespace {
602                template< typename DWTList >
603                void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
604                        auto nvals = dwts.size();
605                        bool containsVoid = false;
606                        for ( auto & dwt : dwts ) {
607                                // fix each DWT and record whether a void was found
608                                containsVoid |= fixFunction( dwt );
609                        }
610
611                        // the only case in which "void" is valid is where it is the only one in the list
612                        if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
613                                SemanticError( func, "invalid type void in function type " );
614                        }
615
616                        // one void is the only thing in the list; remove it.
617                        if ( containsVoid ) {
618                                delete dwts.front();
619                                dwts.clear();
620                        }
621                }
622        }
623
624        void EnumAndPointerDecay_old::previsit( FunctionType * func ) {
625                // Fix up parameters and return types
626                fixFunctionList( func->parameters, func->isVarArgs, func );
627                fixFunctionList( func->returnVals, false, func );
628        }
629
630        LinkReferenceToTypes_old::LinkReferenceToTypes_old( const Indexer * other_indexer ) {
631                if ( other_indexer ) {
632                        local_indexer = other_indexer;
633                } else {
634                        local_indexer = &indexer;
635                } // if
636        }
637
638        void LinkReferenceToTypes_old::postvisit( EnumInstType * enumInst ) {
639                const EnumDecl * st = local_indexer->lookupEnum( enumInst->name );
640                // it's not a semantic error if the enum is not found, just an implicit forward declaration
641                if ( st ) {
642                        enumInst->baseEnum = const_cast<EnumDecl *>(st); // Just linking in the node
643                } // if
644                if ( ! st || ! st->body ) {
645                        // use of forward declaration
646                        forwardEnums[ enumInst->name ].push_back( enumInst );
647                } // if
648        }
649
650        void checkGenericParameters( ReferenceToType * inst ) {
651                for ( Expression * param : inst->parameters ) {
652                        if ( ! dynamic_cast< TypeExpr * >( param ) ) {
653                                SemanticError( inst, "Expression parameters for generic types are currently unsupported: " );
654                        }
655                }
656        }
657
658        void LinkReferenceToTypes_old::postvisit( StructInstType * structInst ) {
659                const StructDecl * st = local_indexer->lookupStruct( structInst->name );
660                // it's not a semantic error if the struct is not found, just an implicit forward declaration
661                if ( st ) {
662                        structInst->baseStruct = const_cast<StructDecl *>(st); // Just linking in the node
663                } // if
664                if ( ! st || ! st->body ) {
665                        // use of forward declaration
666                        forwardStructs[ structInst->name ].push_back( structInst );
667                } // if
668                checkGenericParameters( structInst );
669        }
670
671        void LinkReferenceToTypes_old::postvisit( UnionInstType * unionInst ) {
672                const UnionDecl * un = local_indexer->lookupUnion( unionInst->name );
673                // it's not a semantic error if the union is not found, just an implicit forward declaration
674                if ( un ) {
675                        unionInst->baseUnion = const_cast<UnionDecl *>(un); // Just linking in the node
676                } // if
677                if ( ! un || ! un->body ) {
678                        // use of forward declaration
679                        forwardUnions[ unionInst->name ].push_back( unionInst );
680                } // if
681                checkGenericParameters( unionInst );
682        }
683
684        void LinkReferenceToTypes_old::previsit( QualifiedType * ) {
685                visit_children = false;
686        }
687
688        void LinkReferenceToTypes_old::postvisit( QualifiedType * qualType ) {
689                // linking only makes sense for the 'oldest ancestor' of the qualified type
690                qualType->parent->accept( * visitor );
691        }
692
693        template< typename Decl >
694        void normalizeAssertions( std::list< Decl * > & assertions ) {
695                // ensure no duplicate trait members after the clone
696                auto pred = [](Decl * d1, Decl * d2) {
697                        // only care if they're equal
698                        DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
699                        DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
700                        if ( dwt1 && dwt2 ) {
701                                if ( dwt1->name == dwt2->name && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
702                                        // std::cerr << "=========== equal:" << std::endl;
703                                        // std::cerr << "d1: " << d1 << std::endl;
704                                        // std::cerr << "d2: " << d2 << std::endl;
705                                        return false;
706                                }
707                        }
708                        return d1 < d2;
709                };
710                std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
711                // if ( unique_members.size() != assertions.size() ) {
712                //      std::cerr << "============different" << std::endl;
713                //      std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
714                // }
715
716                std::list< Decl * > order;
717                order.splice( order.end(), assertions );
718                std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
719                        return unique_members.count( decl );
720                });
721        }
722
723        // expand assertions from trait instance, performing the appropriate type variable substitutions
724        template< typename Iterator >
725        void expandAssertions( TraitInstType * inst, Iterator out ) {
726                assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
727                std::list< DeclarationWithType * > asserts;
728                for ( Declaration * decl : inst->baseTrait->members ) {
729                        asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
730                }
731                // substitute trait decl parameters for instance parameters
732                applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
733        }
734
735        void LinkReferenceToTypes_old::postvisit( TraitDecl * traitDecl ) {
736                if ( traitDecl->name == "sized" ) {
737                        // "sized" is a special trait - flick the sized status on for the type variable
738                        assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
739                        TypeDecl * td = traitDecl->parameters.front();
740                        td->set_sized( true );
741                }
742
743                // move assertions from type parameters into the body of the trait
744                for ( TypeDecl * td : traitDecl->parameters ) {
745                        for ( DeclarationWithType * assert : td->assertions ) {
746                                if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
747                                        expandAssertions( inst, back_inserter( traitDecl->members ) );
748                                } else {
749                                        traitDecl->members.push_back( assert->clone() );
750                                }
751                        }
752                        deleteAll( td->assertions );
753                        td->assertions.clear();
754                } // for
755        }
756
757        void LinkReferenceToTypes_old::postvisit( TraitInstType * traitInst ) {
758                // handle other traits
759                const TraitDecl * traitDecl = local_indexer->lookupTrait( traitInst->name );
760                if ( ! traitDecl ) {
761                        SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
762                } // if
763                if ( traitDecl->parameters.size() != traitInst->parameters.size() ) {
764                        SemanticError( traitInst, "incorrect number of trait parameters: " );
765                } // if
766                traitInst->baseTrait = const_cast<TraitDecl *>(traitDecl); // Just linking in the node
767
768                // need to carry over the 'sized' status of each decl in the instance
769                for ( auto p : group_iterate( traitDecl->parameters, traitInst->parameters ) ) {
770                        TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
771                        if ( ! expr ) {
772                                SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
773                        }
774                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
775                                TypeDecl * formalDecl = std::get<0>(p);
776                                TypeDecl * instDecl = inst->baseType;
777                                if ( formalDecl->get_sized() ) instDecl->set_sized( true );
778                        }
779                }
780                // normalizeAssertions( traitInst->members );
781        }
782
783        void LinkReferenceToTypes_old::postvisit( EnumDecl * enumDecl ) {
784                // visit enum members first so that the types of self-referencing members are updated properly
785                if ( enumDecl->body ) {
786                        ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->name );
787                        if ( fwds != forwardEnums.end() ) {
788                                for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
789                                        (* inst)->baseEnum = enumDecl;
790                                } // for
791                                forwardEnums.erase( fwds );
792                        } // if
793
794                        for ( Declaration * member : enumDecl->members ) {
795                                ObjectDecl * field = strict_dynamic_cast<ObjectDecl *>( member );
796                                if ( field->init ) {
797                                        // need to resolve enumerator initializers early so that other passes that determine if an expression is constexpr have the appropriate information.
798                                        SingleInit * init = strict_dynamic_cast<SingleInit *>( field->init );
799                                        ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer );
800                                }
801                        }
802                } // if
803        }
804
805        void LinkReferenceToTypes_old::renameGenericParams( std::list< TypeDecl * > & params ) {
806                // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
807                //   forall(otype T)
808                //   struct Box {
809                //     T x;
810                //   };
811                //   forall(otype T)
812                //   void f(Box(T) b) {
813                //     ...
814                //   }
815                // The T in Box and the T in f are different, so internally the naming must reflect that.
816                GuardValue( inGeneric );
817                inGeneric = ! params.empty();
818                for ( TypeDecl * td : params ) {
819                        td->name = "__" + td->name + "_generic_";
820                }
821        }
822
823        void LinkReferenceToTypes_old::previsit( StructDecl * structDecl ) {
824                renameGenericParams( structDecl->parameters );
825        }
826
827        void LinkReferenceToTypes_old::previsit( UnionDecl * unionDecl ) {
828                renameGenericParams( unionDecl->parameters );
829        }
830
831        void LinkReferenceToTypes_old::postvisit( StructDecl * structDecl ) {
832                // visit struct members first so that the types of self-referencing members are updated properly
833                // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
834                if ( structDecl->body ) {
835                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->name );
836                        if ( fwds != forwardStructs.end() ) {
837                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
838                                        (* inst)->baseStruct = structDecl;
839                                } // for
840                                forwardStructs.erase( fwds );
841                        } // if
842                } // if
843        }
844
845        void LinkReferenceToTypes_old::postvisit( UnionDecl * unionDecl ) {
846                if ( unionDecl->body ) {
847                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->name );
848                        if ( fwds != forwardUnions.end() ) {
849                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
850                                        (* inst)->baseUnion = unionDecl;
851                                } // for
852                                forwardUnions.erase( fwds );
853                        } // if
854                } // if
855        }
856
857        void LinkReferenceToTypes_old::postvisit( TypeInstType * typeInst ) {
858                // ensure generic parameter instances are renamed like the base type
859                if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
860                if ( const NamedTypeDecl * namedTypeDecl = local_indexer->lookupType( typeInst->name ) ) {
861                        if ( const TypeDecl * typeDecl = dynamic_cast< const TypeDecl * >( namedTypeDecl ) ) {
862                                typeInst->set_isFtype( typeDecl->kind == TypeDecl::Ftype );
863                        } // if
864                } // if
865        }
866
867        /// Fix up assertions - flattens assertion lists, removing all trait instances
868        void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
869                for ( TypeDecl * type : forall ) {
870                        std::list< DeclarationWithType * > asserts;
871                        asserts.splice( asserts.end(), type->assertions );
872                        // expand trait instances into their members
873                        for ( DeclarationWithType * assertion : asserts ) {
874                                if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
875                                        // expand trait instance into all of its members
876                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
877                                        delete traitInst;
878                                } else {
879                                        // pass other assertions through
880                                        type->assertions.push_back( assertion );
881                                } // if
882                        } // for
883                        // apply FixFunction to every assertion to check for invalid void type
884                        for ( DeclarationWithType *& assertion : type->assertions ) {
885                                bool isVoid = fixFunction( assertion );
886                                if ( isVoid ) {
887                                        SemanticError( node, "invalid type void in assertion of function " );
888                                } // if
889                        } // for
890                        // normalizeAssertions( type->assertions );
891                } // for
892        }
893
894        void ForallPointerDecay_old::previsit( ObjectDecl * object ) {
895                // ensure that operator names only apply to functions or function pointers
896                if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
897                        SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." )  );
898                }
899                object->fixUniqueId();
900        }
901
902        void ForallPointerDecay_old::previsit( FunctionDecl * func ) {
903                func->fixUniqueId();
904        }
905
906        void ForallPointerDecay_old::previsit( FunctionType * ftype ) {
907                forallFixer( ftype->forall, ftype );
908        }
909
910        void ForallPointerDecay_old::previsit( StructDecl * aggrDecl ) {
911                forallFixer( aggrDecl->parameters, aggrDecl );
912        }
913
914        void ForallPointerDecay_old::previsit( UnionDecl * aggrDecl ) {
915                forallFixer( aggrDecl->parameters, aggrDecl );
916        }
917
918        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
919                PassVisitor<ReturnChecker> checker;
920                acceptAll( translationUnit, checker );
921        }
922
923        void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
924                GuardValue( returnVals );
925                returnVals = functionDecl->get_functionType()->get_returnVals();
926        }
927
928        void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
929                // Previously this also checked for the existence of an expr paired with no return values on
930                // the  function return type. This is incorrect, since you can have an expression attached to
931                // a return statement in a void-returning function in C. The expression is treated as if it
932                // were cast to void.
933                if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
934                        SemanticError( returnStmt, "Non-void function returns no values: " );
935                }
936        }
937
938
939        void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) {
940                PassVisitor<ReplaceTypedef> eliminator;
941                mutateAll( translationUnit, eliminator );
942                if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
943                        // grab and remember declaration of size_t
944                        Validate::SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone();
945                } else {
946                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
947                        // eventually should have a warning for this case.
948                        Validate::SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
949                }
950        }
951
952        void ReplaceTypedef::premutate( QualifiedType * ) {
953                visit_children = false;
954        }
955
956        Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) {
957                // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type
958                qualType->parent = qualType->parent->acceptMutator( * visitor );
959                return qualType;
960        }
961
962        Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) {
963                // instances of typedef types will come here. If it is an instance
964                // of a typdef type, link the instance to its actual type.
965                TypedefMap::const_iterator def = typedefNames.find( typeInst->name );
966                if ( def != typedefNames.end() ) {
967                        Type * ret = def->second.first->base->clone();
968                        ret->location = typeInst->location;
969                        ret->get_qualifiers() |= typeInst->get_qualifiers();
970                        // attributes are not carried over from typedef to function parameters/return values
971                        if ( ! inFunctionType ) {
972                                ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
973                        } else {
974                                deleteAll( ret->attributes );
975                                ret->attributes.clear();
976                        }
977                        // place instance parameters on the typedef'd type
978                        if ( ! typeInst->parameters.empty() ) {
979                                ReferenceToType * rtt = dynamic_cast<ReferenceToType *>(ret);
980                                if ( ! rtt ) {
981                                        SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
982                                }
983                                rtt->parameters.clear();
984                                cloneAll( typeInst->parameters, rtt->parameters );
985                                mutateAll( rtt->parameters, * visitor );  // recursively fix typedefs on parameters
986                        } // if
987                        delete typeInst;
988                        return ret;
989                } else {
990                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name );
991                        if ( base == typedeclNames.end() ) {
992                                SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) );
993                        }
994                        typeInst->set_baseType( base->second );
995                        return typeInst;
996                } // if
997                assert( false );
998        }
999
1000        struct VarLenChecker : WithShortCircuiting {
1001                void previsit( FunctionType * ) { visit_children = false; }
1002                void previsit( ArrayType * at ) {
1003                        isVarLen |= at->isVarLen;
1004                }
1005                bool isVarLen = false;
1006        };
1007
1008        bool isVariableLength( Type * t ) {
1009                PassVisitor<VarLenChecker> varLenChecker;
1010                maybeAccept( t, varLenChecker );
1011                return varLenChecker.pass.isVarLen;
1012        }
1013
1014        Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) {
1015                if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) {
1016                        // typedef to the same name from the same scope
1017                        // must be from the same type
1018
1019                        Type * t1 = tyDecl->base;
1020                        Type * t2 = typedefNames[ tyDecl->name ].first->base;
1021                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
1022                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
1023                        }
1024                        // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
1025                        // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
1026                        // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
1027                        // to fix this corner case likely outweighs the utility of allowing it.
1028                        if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
1029                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
1030                        }
1031                } else {
1032                        typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
1033                } // if
1034
1035                // When a typedef is a forward declaration:
1036                //    typedef struct screen SCREEN;
1037                // the declaration portion must be retained:
1038                //    struct screen;
1039                // because the expansion of the typedef is:
1040                //    void rtn( SCREEN * p ) => void rtn( struct screen * p )
1041                // hence the type-name "screen" must be defined.
1042                // Note, qualifiers on the typedef are superfluous for the forward declaration.
1043
1044                Type * designatorType = tyDecl->base->stripDeclarator();
1045                if ( StructInstType * aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
1046                        declsToAddBefore.push_back( new StructDecl( aggDecl->name, AggregateDecl::Struct, noAttributes, tyDecl->linkage ) );
1047                } else if ( UnionInstType * aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
1048                        declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) );
1049                } else if ( EnumInstType * enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
1050                        declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, tyDecl->linkage ) );
1051                } // if
1052                return tyDecl->clone();
1053        }
1054
1055        void ReplaceTypedef::premutate( TypeDecl * typeDecl ) {
1056                TypedefMap::iterator i = typedefNames.find( typeDecl->name );
1057                if ( i != typedefNames.end() ) {
1058                        typedefNames.erase( i ) ;
1059                } // if
1060
1061                typedeclNames.insert( typeDecl->name, typeDecl );
1062        }
1063
1064        void ReplaceTypedef::premutate( FunctionDecl * ) {
1065                GuardScope( typedefNames );
1066                GuardScope( typedeclNames );
1067        }
1068
1069        void ReplaceTypedef::premutate( ObjectDecl * ) {
1070                GuardScope( typedefNames );
1071                GuardScope( typedeclNames );
1072        }
1073
1074        DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) {
1075                if ( FunctionType * funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type?
1076                        // replace the current object declaration with a function declaration
1077                        FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() );
1078                        objDecl->attributes.clear();
1079                        objDecl->set_type( nullptr );
1080                        delete objDecl;
1081                        return newDecl;
1082                } // if
1083                return objDecl;
1084        }
1085
1086        void ReplaceTypedef::premutate( CastExpr * ) {
1087                GuardScope( typedefNames );
1088                GuardScope( typedeclNames );
1089        }
1090
1091        void ReplaceTypedef::premutate( CompoundStmt * ) {
1092                GuardScope( typedefNames );
1093                GuardScope( typedeclNames );
1094                scopeLevel += 1;
1095                GuardAction( [this](){ scopeLevel -= 1; } );
1096        }
1097
1098        template<typename AggDecl>
1099        void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
1100                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
1101                        Type * type = nullptr;
1102                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
1103                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
1104                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
1105                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
1106                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
1107                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
1108                        } // if
1109                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
1110                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
1111                        // add the implicit typedef to the AST
1112                        declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) );
1113                } // if
1114        }
1115
1116        template< typename AggDecl >
1117        void ReplaceTypedef::handleAggregate( AggDecl * aggr ) {
1118                SemanticErrorException errors;
1119
1120                ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore );
1121                ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter  );
1122                declsToAddBefore.clear();
1123                declsToAddAfter.clear();
1124
1125                GuardScope( typedefNames );
1126                GuardScope( typedeclNames );
1127                mutateAll( aggr->parameters, * visitor );
1128
1129                // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body.
1130                for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) {
1131                        if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); }
1132
1133                        try {
1134                                * i = maybeMutate( * i, * visitor );
1135                        } catch ( SemanticErrorException &e ) {
1136                                errors.append( e );
1137                        }
1138
1139                        if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); }
1140                }
1141
1142                if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); }
1143                if ( !errors.isEmpty() ) { throw errors; }
1144        }
1145
1146        void ReplaceTypedef::premutate( StructDecl * structDecl ) {
1147                visit_children = false;
1148                addImplicitTypedef( structDecl );
1149                handleAggregate( structDecl );
1150        }
1151
1152        void ReplaceTypedef::premutate( UnionDecl * unionDecl ) {
1153                visit_children = false;
1154                addImplicitTypedef( unionDecl );
1155                handleAggregate( unionDecl );
1156        }
1157
1158        void ReplaceTypedef::premutate( EnumDecl * enumDecl ) {
1159                addImplicitTypedef( enumDecl );
1160        }
1161
1162        void ReplaceTypedef::premutate( FunctionType * ) {
1163                GuardValue( inFunctionType );
1164                inFunctionType = true;
1165        }
1166
1167        void ReplaceTypedef::premutate( TraitDecl * ) {
1168                GuardScope( typedefNames );
1169                GuardScope( typedeclNames);
1170        }
1171
1172        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
1173                PassVisitor<VerifyCtorDtorAssign> verifier;
1174                acceptAll( translationUnit, verifier );
1175        }
1176
1177        void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
1178                FunctionType * funcType = funcDecl->get_functionType();
1179                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
1180                std::list< DeclarationWithType * > &params = funcType->get_parameters();
1181
1182                if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
1183                        if ( params.size() == 0 ) {
1184                                SemanticError( funcDecl, "Constructors, destructors, and assignment functions require at least one parameter " );
1185                        }
1186                        ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
1187                        if ( ! refType ) {
1188                                SemanticError( funcDecl, "First parameter of a constructor, destructor, or assignment function must be a reference " );
1189                        }
1190                        if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
1191                                SemanticError( funcDecl, "Constructors and destructors cannot have explicit return values " );
1192                        }
1193                }
1194        }
1195
1196        template< typename Aggr >
1197        void validateGeneric( Aggr * inst ) {
1198                std::list< TypeDecl * > * params = inst->get_baseParameters();
1199                if ( params ) {
1200                        std::list< Expression * > & args = inst->get_parameters();
1201
1202                        // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
1203                        // A substitution is used to ensure that defaults are replaced correctly, e.g.,
1204                        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
1205                        //   vector(int) v;
1206                        // after insertion of default values becomes
1207                        //   vector(int, heap_allocator(T))
1208                        // and the substitution is built with T=int so that after substitution, the result is
1209                        //   vector(int, heap_allocator(int))
1210                        TypeSubstitution sub;
1211                        auto paramIter = params->begin();
1212                        for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) {
1213                                if ( i < args.size() ) {
1214                                        TypeExpr * expr = strict_dynamic_cast< TypeExpr * >( * std::next( args.begin(), i ) );
1215                                        sub.add( (* paramIter)->get_name(), expr->get_type()->clone() );
1216                                } else if ( i == args.size() ) {
1217                                        Type * defaultType = (* paramIter)->get_init();
1218                                        if ( defaultType ) {
1219                                                args.push_back( new TypeExpr( defaultType->clone() ) );
1220                                                sub.add( (* paramIter)->get_name(), defaultType->clone() );
1221                                        }
1222                                }
1223                        }
1224
1225                        sub.apply( inst );
1226                        if ( args.size() < params->size() ) SemanticError( inst, "Too few type arguments in generic type " );
1227                        if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
1228                }
1229        }
1230
1231        void ValidateGenericParameters::previsit( StructInstType * inst ) {
1232                validateGeneric( inst );
1233        }
1234
1235        void ValidateGenericParameters::previsit( UnionInstType * inst ) {
1236                validateGeneric( inst );
1237        }
1238
1239        void CompoundLiteral::premutate( ObjectDecl * objectDecl ) {
1240                storageClasses = objectDecl->get_storageClasses();
1241        }
1242
1243        Expression * CompoundLiteral::postmutate( CompoundLiteralExpr * compLitExpr ) {
1244                // transform [storage_class] ... (struct S){ 3, ... };
1245                // into [storage_class] struct S temp =  { 3, ... };
1246                static UniqueName indexName( "_compLit" );
1247
1248                ObjectDecl * tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
1249                compLitExpr->set_result( nullptr );
1250                compLitExpr->set_initializer( nullptr );
1251                delete compLitExpr;
1252                declsToAddBefore.push_back( tempvar );                                  // add modified temporary to current block
1253                return new VariableExpr( tempvar );
1254        }
1255
1256        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
1257                PassVisitor<ReturnTypeFixer> fixer;
1258                acceptAll( translationUnit, fixer );
1259        }
1260
1261        void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
1262                FunctionType * ftype = functionDecl->get_functionType();
1263                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1264                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
1265                if ( retVals.size() == 1 ) {
1266                        // ensure all function return values have a name - use the name of the function to disambiguate (this also provides a nice bit of help for debugging).
1267                        // ensure other return values have a name.
1268                        DeclarationWithType * ret = retVals.front();
1269                        if ( ret->get_name() == "" ) {
1270                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1271                        }
1272                        ret->get_attributes().push_back( new Attribute( "unused" ) );
1273                }
1274        }
1275
1276        void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
1277                // xxx - need to handle named return values - this information needs to be saved somehow
1278                // so that resolution has access to the names.
1279                // Note that this pass needs to happen early so that other passes which look for tuple types
1280                // find them in all of the right places, including function return types.
1281                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1282                if ( retVals.size() > 1 ) {
1283                        // generate a single return parameter which is the tuple of all of the return values
1284                        TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
1285                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
1286                        ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer *>(), noDesignators, false ) );
1287                        deleteAll( retVals );
1288                        retVals.clear();
1289                        retVals.push_back( newRet );
1290                }
1291        }
1292
1293        void FixObjectType::fix( std::list< Declaration * > & translationUnit ) {
1294                PassVisitor<FixObjectType> fixer;
1295                acceptAll( translationUnit, fixer );
1296        }
1297
1298        void FixObjectType::previsit( ObjectDecl * objDecl ) {
1299                Type * new_type = ResolvExpr::resolveTypeof( objDecl->get_type(), indexer );
1300                objDecl->set_type( new_type );
1301        }
1302
1303        void FixObjectType::previsit( FunctionDecl * funcDecl ) {
1304                Type * new_type = ResolvExpr::resolveTypeof( funcDecl->type, indexer );
1305                funcDecl->set_type( new_type );
1306        }
1307
1308        void FixObjectType::previsit( TypeDecl * typeDecl ) {
1309                if ( typeDecl->get_base() ) {
1310                        Type * new_type = ResolvExpr::resolveTypeof( typeDecl->get_base(), indexer );
1311                        typeDecl->set_base( new_type );
1312                } // if
1313        }
1314
1315        void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
1316                PassVisitor<ArrayLength> len;
1317                acceptAll( translationUnit, len );
1318        }
1319
1320        void ArrayLength::previsit( ObjectDecl * objDecl ) {
1321                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) {
1322                        if ( at->dimension ) return;
1323                        if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) {
1324                                at->dimension = new ConstantExpr( Constant::from_ulong( init->initializers.size() ) );
1325                        }
1326                }
1327        }
1328
1329        void ArrayLength::previsit( ArrayType * type ) {
1330                if ( type->dimension ) {
1331                        // need to resolve array dimensions early so that constructor code can correctly determine
1332                        // if a type is a VLA (and hence whether its elements need to be constructed)
1333                        ResolvExpr::findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
1334
1335                        // must re-evaluate whether a type is a VLA, now that more information is available
1336                        // (e.g. the dimension may have been an enumerator, which was unknown prior to this step)
1337                        type->isVarLen = ! InitTweak::isConstExpr( type->dimension );
1338                }
1339        }
1340
1341        struct LabelFinder {
1342                std::set< Label > & labels;
1343                LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1344                void previsit( Statement * stmt ) {
1345                        for ( Label & l : stmt->labels ) {
1346                                labels.insert( l );
1347                        }
1348                }
1349        };
1350
1351        void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1352                GuardValue( labels );
1353                PassVisitor<LabelFinder> finder( labels );
1354                funcDecl->accept( finder );
1355        }
1356
1357        Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1358                // convert &&label into label address
1359                if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1360                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1361                                if ( labels.count( nameExpr->name ) ) {
1362                                        Label name = nameExpr->name;
1363                                        delete addrExpr;
1364                                        return new LabelAddressExpr( name );
1365                                }
1366                        }
1367                }
1368                return addrExpr;
1369        }
1370
1371namespace {
1372        /// Replaces enum types by int, and function/array types in function parameter and return
1373        /// lists by appropriate pointers
1374        struct EnumAndPointerDecay_new {
1375                const ast::EnumDecl * previsit( const ast::EnumDecl * enumDecl ) {
1376                        // set the type of each member of the enumeration to be EnumConstant
1377                        for ( unsigned i = 0; i < enumDecl->members.size(); ++i ) {
1378                                // build new version of object with EnumConstant
1379                                ast::ptr< ast::ObjectDecl > obj =
1380                                        enumDecl->members[i].strict_as< ast::ObjectDecl >();
1381                                obj.get_and_mutate()->type =
1382                                        new ast::EnumInstType{ enumDecl->name, ast::CV::Const };
1383
1384                                // set into decl
1385                                ast::EnumDecl * mut = mutate( enumDecl );
1386                                mut->members[i] = obj.get();
1387                                enumDecl = mut;
1388                        }
1389                        return enumDecl;
1390                }
1391
1392                static const ast::FunctionType * fixFunctionList(
1393                        const ast::FunctionType * func,
1394                        std::vector< ast::ptr< ast::DeclWithType > > ast::FunctionType::* field,
1395                        ast::ArgumentFlag isVarArgs = ast::FixedArgs
1396                ) {
1397                        const auto & dwts = func->* field;
1398                        unsigned nvals = dwts.size();
1399                        bool hasVoid = false;
1400                        for ( unsigned i = 0; i < nvals; ++i ) {
1401                                func = ast::mutate_field_index( func, field, i, fixFunction( dwts[i], hasVoid ) );
1402                        }
1403
1404                        // the only case in which "void" is valid is where it is the only one in the list
1405                        if ( hasVoid && ( nvals > 1 || isVarArgs ) ) {
1406                                SemanticError(
1407                                        dwts.front()->location, func, "invalid type void in function type" );
1408                        }
1409
1410                        // one void is the only thing in the list, remove it
1411                        if ( hasVoid ) {
1412                                func = ast::mutate_field(
1413                                        func, field, std::vector< ast::ptr< ast::DeclWithType > >{} );
1414                        }
1415
1416                        return func;
1417                }
1418
1419                const ast::FunctionType * previsit( const ast::FunctionType * func ) {
1420                        func = fixFunctionList( func, &ast::FunctionType::params, func->isVarArgs );
1421                        return fixFunctionList( func, &ast::FunctionType::returns );
1422                }
1423        };
1424
1425        /// expand assertions from a trait instance, performing appropriate type variable substitutions
1426        void expandAssertions(
1427                const ast::TraitInstType * inst, std::vector< ast::ptr< ast::DeclWithType > > & out
1428        ) {
1429                assertf( inst->base, "Trait instance not linked to base trait: %s", toCString( inst ) );
1430
1431                // build list of trait members, substituting trait decl parameters for instance parameters
1432                ast::TypeSubstitution sub{
1433                        inst->base->params.begin(), inst->base->params.end(), inst->params.begin() };
1434                // deliberately take ast::ptr by-value to ensure this does not mutate inst->base
1435                for ( ast::ptr< ast::Decl > decl : inst->base->members ) {
1436                        auto member = decl.strict_as< ast::DeclWithType >();
1437                        sub.apply( member );
1438                        out.emplace_back( member );
1439                }
1440        }
1441
1442        /// Associates forward declarations of aggregates with their definitions
1443        class LinkReferenceToTypes_new final
1444        : public ast::WithSymbolTable, public ast::WithGuards, public
1445          ast::WithVisitorRef<LinkReferenceToTypes_new>, public ast::WithShortCircuiting {
1446
1447                // these maps of uses of forward declarations of types need to have the actual type
1448                // declaration switched in * after * they have been traversed. To enable this in the
1449                // ast::Pass framework, any node that needs to be so mutated has mutate() called on it
1450                // before it is placed in the map, properly updating its parents in the usual traversal,
1451                // then can have the actual mutation applied later
1452                using ForwardEnumsType = std::unordered_multimap< std::string, ast::EnumInstType * >;
1453                using ForwardStructsType = std::unordered_multimap< std::string, ast::StructInstType * >;
1454                using ForwardUnionsType = std::unordered_multimap< std::string, ast::UnionInstType * >;
1455
1456                const CodeLocation & location;
1457                const ast::SymbolTable * localSymtab;
1458
1459                ForwardEnumsType forwardEnums;
1460                ForwardStructsType forwardStructs;
1461                ForwardUnionsType forwardUnions;
1462
1463                /// true if currently in a generic type body, so that type parameter instances can be
1464                /// renamed appropriately
1465                bool inGeneric = false;
1466
1467        public:
1468                /// contstruct using running symbol table
1469                LinkReferenceToTypes_new( const CodeLocation & loc )
1470                : location( loc ), localSymtab( &symtab ) {}
1471
1472                /// construct using provided symbol table
1473                LinkReferenceToTypes_new( const CodeLocation & loc, const ast::SymbolTable & syms )
1474                : location( loc ), localSymtab( &syms ) {}
1475
1476                const ast::Type * postvisit( const ast::TypeInstType * typeInst ) {
1477                        // ensure generic parameter instances are renamed like the base type
1478                        if ( inGeneric && typeInst->base ) {
1479                                typeInst = ast::mutate_field(
1480                                        typeInst, &ast::TypeInstType::name, typeInst->base->name );
1481                        }
1482
1483                        if (
1484                                auto typeDecl = dynamic_cast< const ast::TypeDecl * >(
1485                                        localSymtab->lookupType( typeInst->name ) )
1486                        ) {
1487                                typeInst = ast::mutate_field( typeInst, &ast::TypeInstType::kind, typeDecl->kind );
1488                        }
1489
1490                        return typeInst;
1491                }
1492
1493                const ast::Type * postvisit( const ast::EnumInstType * inst ) {
1494                        const ast::EnumDecl * decl = localSymtab->lookupEnum( inst->name );
1495                        // not a semantic error if the enum is not found, just an implicit forward declaration
1496                        if ( decl ) {
1497                                inst = ast::mutate_field( inst, &ast::EnumInstType::base, decl );
1498                        }
1499                        if ( ! decl || ! decl->body ) {
1500                                // forward declaration
1501                                auto mut = mutate( inst );
1502                                forwardEnums.emplace( inst->name, mut );
1503                                inst = mut;
1504                        }
1505                        return inst;
1506                }
1507
1508                void checkGenericParameters( const ast::ReferenceToType * inst ) {
1509                        for ( const ast::Expr * param : inst->params ) {
1510                                if ( ! dynamic_cast< const ast::TypeExpr * >( param ) ) {
1511                                        SemanticError(
1512                                                location, inst, "Expression parameters for generic types are currently "
1513                                                "unsupported: " );
1514                                }
1515                        }
1516                }
1517
1518                const ast::StructInstType * postvisit( const ast::StructInstType * inst ) {
1519                        const ast::StructDecl * decl = localSymtab->lookupStruct( inst->name );
1520                        // not a semantic error if the struct is not found, just an implicit forward declaration
1521                        if ( decl ) {
1522                                inst = ast::mutate_field( inst, &ast::StructInstType::base, decl );
1523                        }
1524                        if ( ! decl || ! decl->body ) {
1525                                // forward declaration
1526                                auto mut = mutate( inst );
1527                                forwardStructs.emplace( inst->name, mut );
1528                                inst = mut;
1529                        }
1530                        checkGenericParameters( inst );
1531                        return inst;
1532                }
1533
1534                const ast::UnionInstType * postvisit( const ast::UnionInstType * inst ) {
1535                        const ast::UnionDecl * decl = localSymtab->lookupUnion( inst->name );
1536                        // not a semantic error if the struct is not found, just an implicit forward declaration
1537                        if ( decl ) {
1538                                inst = ast::mutate_field( inst, &ast::UnionInstType::base, decl );
1539                        }
1540                        if ( ! decl || ! decl->body ) {
1541                                // forward declaration
1542                                auto mut = mutate( inst );
1543                                forwardUnions.emplace( inst->name, mut );
1544                                inst = mut;
1545                        }
1546                        checkGenericParameters( inst );
1547                        return inst;
1548                }
1549
1550                const ast::Type * postvisit( const ast::TraitInstType * traitInst ) {
1551                        // handle other traits
1552                        const ast::TraitDecl * traitDecl = localSymtab->lookupTrait( traitInst->name );
1553                        if ( ! traitDecl )       {
1554                                SemanticError( location, "use of undeclared trait " + traitInst->name );
1555                        }
1556                        if ( traitDecl->params.size() != traitInst->params.size() ) {
1557                                SemanticError( location, traitInst, "incorrect number of trait parameters: " );
1558                        }
1559                        traitInst = ast::mutate_field( traitInst, &ast::TraitInstType::base, traitDecl );
1560
1561                        // need to carry over the "sized" status of each decl in the instance
1562                        for ( unsigned i = 0; i < traitDecl->params.size(); ++i ) {
1563                                auto expr = traitInst->params[i].as< ast::TypeExpr >();
1564                                if ( ! expr ) {
1565                                        SemanticError(
1566                                                traitInst->params[i].get(), "Expression parameters for trait instances "
1567                                                "are currently unsupported: " );
1568                                }
1569
1570                                if ( auto inst = expr->type.as< ast::TypeInstType >() ) {
1571                                        if ( traitDecl->params[i]->sized && ! inst->base->sized ) {
1572                                                // traitInst = ast::mutate_field_index(
1573                                                //      traitInst, &ast::TraitInstType::params, i,
1574                                                //      ...
1575                                                // );
1576                                                ast::TraitInstType * mut = ast::mutate( traitInst );
1577                                                ast::chain_mutate( mut->params[i] )
1578                                                        ( &ast::TypeExpr::type )
1579                                                                ( &ast::TypeInstType::base )->sized = true;
1580                                                traitInst = mut;
1581                                        }
1582                                }
1583                        }
1584
1585                        return traitInst;
1586                }
1587
1588                void previsit( const ast::QualifiedType * ) { visit_children = false; }
1589
1590                const ast::Type * postvisit( const ast::QualifiedType * qualType ) {
1591                        // linking only makes sense for the "oldest ancestor" of the qualified type
1592                        return ast::mutate_field(
1593                                qualType, &ast::QualifiedType::parent, qualType->parent->accept( * visitor ) );
1594                }
1595
1596                const ast::Decl * postvisit( const ast::EnumDecl * enumDecl ) {
1597                        // visit enum members first so that the types of self-referencing members are updated
1598                        // properly
1599                        if ( ! enumDecl->body ) return enumDecl;
1600
1601                        // update forward declarations to point here
1602                        auto fwds = forwardEnums.equal_range( enumDecl->name );
1603                        if ( fwds.first != fwds.second ) {
1604                                auto inst = fwds.first;
1605                                do {
1606                                        // forward decl is stored * mutably * in map, can thus be updated
1607                                        inst->second->base = enumDecl;
1608                                } while ( ++inst != fwds.second );
1609                                forwardEnums.erase( fwds.first, fwds.second );
1610                        }
1611
1612                        // ensure that enumerator initializers are properly set
1613                        for ( unsigned i = 0; i < enumDecl->members.size(); ++i ) {
1614                                auto field = enumDecl->members[i].strict_as< ast::ObjectDecl >();
1615                                if ( field->init ) {
1616                                        // need to resolve enumerator initializers early so that other passes that
1617                                        // determine if an expression is constexpr have appropriate information
1618                                        auto init = field->init.strict_as< ast::SingleInit >();
1619
1620                                        enumDecl = ast::mutate_field_index(
1621                                                enumDecl, &ast::EnumDecl::members, i,
1622                                                ast::mutate_field( field, &ast::ObjectDecl::init,
1623                                                        ast::mutate_field( init, &ast::SingleInit::value,
1624                                                                ResolvExpr::findSingleExpression(
1625                                                                        init->value, new ast::BasicType{ ast::BasicType::SignedInt },
1626                                                                        symtab ) ) ) );
1627                                }
1628                        }
1629
1630                        return enumDecl;
1631                }
1632
1633                /// rename generic type parameters uniquely so that they do not conflict with user defined
1634                /// function forall parameters, e.g. the T in Box and the T in f, below
1635                ///   forall(otype T)
1636                ///   struct Box {
1637                ///     T x;
1638                ///   };
1639                ///   forall(otype T)
1640                ///   void f(Box(T) b) {
1641                ///     ...
1642                ///   }
1643                template< typename AggrDecl >
1644                const AggrDecl * renameGenericParams( const AggrDecl * aggr ) {
1645                        GuardValue( inGeneric );
1646                        inGeneric = ! aggr->params.empty();
1647
1648                        for ( unsigned i = 0; i < aggr->params.size(); ++i ) {
1649                                const ast::TypeDecl * td = aggr->params[i];
1650
1651                                aggr = ast::mutate_field_index(
1652                                        aggr, &AggrDecl::params, i,
1653                                        ast::mutate_field( td, &ast::TypeDecl::name, "__" + td->name + "_generic_" ) );
1654                        }
1655                        return aggr;
1656                }
1657
1658                const ast::StructDecl * previsit( const ast::StructDecl * structDecl ) {
1659                        return renameGenericParams( structDecl );
1660                }
1661
1662                void postvisit( const ast::StructDecl * structDecl ) {
1663                        // visit struct members first so that the types of self-referencing members are
1664                        // updated properly
1665                        if ( ! structDecl->body ) return;
1666
1667                        // update forward declarations to point here
1668                        auto fwds = forwardStructs.equal_range( structDecl->name );
1669                        if ( fwds.first != fwds.second ) {
1670                                auto inst = fwds.first;
1671                                do {
1672                                        // forward decl is stored * mutably * in map, can thus be updated
1673                                        inst->second->base = structDecl;
1674                                } while ( ++inst != fwds.second );
1675                                forwardStructs.erase( fwds.first, fwds.second );
1676                        }
1677                }
1678
1679                const ast::UnionDecl * previsit( const ast::UnionDecl * unionDecl ) {
1680                        return renameGenericParams( unionDecl );
1681                }
1682
1683                void postvisit( const ast::UnionDecl * unionDecl ) {
1684                        // visit union members first so that the types of self-referencing members are updated
1685                        // properly
1686                        if ( ! unionDecl->body ) return;
1687
1688                        // update forward declarations to point here
1689                        auto fwds = forwardUnions.equal_range( unionDecl->name );
1690                        if ( fwds.first != fwds.second ) {
1691                                auto inst = fwds.first;
1692                                do {
1693                                        // forward decl is stored * mutably * in map, can thus be updated
1694                                        inst->second->base = unionDecl;
1695                                } while ( ++inst != fwds.second );
1696                                forwardUnions.erase( fwds.first, fwds.second );
1697                        }
1698                }
1699
1700                const ast::Decl * postvisit( const ast::TraitDecl * traitDecl ) {
1701                        // set the "sized" status for the special "sized" trait
1702                        if ( traitDecl->name == "sized" ) {
1703                                assertf( traitDecl->params.size() == 1, "Built-in trait 'sized' has incorrect "
1704                                        "number of parameters: %zd", traitDecl->params.size() );
1705
1706                                traitDecl = ast::mutate_field_index(
1707                                        traitDecl, &ast::TraitDecl::params, 0,
1708                                        ast::mutate_field(
1709                                                traitDecl->params.front().get(), &ast::TypeDecl::sized, true ) );
1710                        }
1711
1712                        // move assertions from type parameters into the body of the trait
1713                        std::vector< ast::ptr< ast::DeclWithType > > added;
1714                        for ( const ast::TypeDecl * td : traitDecl->params ) {
1715                                for ( const ast::DeclWithType * assn : td->assertions ) {
1716                                        auto inst = dynamic_cast< const ast::TraitInstType * >( assn->get_type() );
1717                                        if ( inst ) {
1718                                                expandAssertions( inst, added );
1719                                        } else {
1720                                                added.emplace_back( assn );
1721                                        }
1722                                }
1723                        }
1724                        if ( ! added.empty() ) {
1725                                auto mut = mutate( traitDecl );
1726                                for ( const ast::DeclWithType * decl : added ) {
1727                                        mut->members.emplace_back( decl );
1728                                }
1729                                traitDecl = mut;
1730                        }
1731
1732                        return traitDecl;
1733                }
1734        };
1735
1736        /// Replaces array and function types in forall lists by appropriate pointer type and assigns
1737        /// each object and function declaration a unique ID
1738        class ForallPointerDecay_new {
1739                const CodeLocation & location;
1740        public:
1741                ForallPointerDecay_new( const CodeLocation & loc ) : location( loc ) {}
1742
1743                const ast::ObjectDecl * previsit( const ast::ObjectDecl * obj ) {
1744                        // ensure that operator names only apply to functions or function pointers
1745                        if (
1746                                CodeGen::isOperator( obj->name )
1747                                && ! dynamic_cast< const ast::FunctionType * >( obj->type->stripDeclarator() )
1748                        ) {
1749                                SemanticError( obj->location, toCString( "operator ", obj->name.c_str(), " is not "
1750                                        "a function or function pointer." )  );
1751                        }
1752
1753                        // ensure object has unique ID
1754                        if ( obj->uniqueId ) return obj;
1755                        auto mut = mutate( obj );
1756                        mut->fixUniqueId();
1757                        return mut;
1758                }
1759
1760                const ast::FunctionDecl * previsit( const ast::FunctionDecl * func ) {
1761                        // ensure function has unique ID
1762                        if ( func->uniqueId ) return func;
1763                        auto mut = mutate( func );
1764                        mut->fixUniqueId();
1765                        return mut;
1766                }
1767
1768                /// Fix up assertions -- flattens assertion lists, removing all trait instances
1769                template< typename node_t, typename parent_t >
1770                static const node_t * forallFixer(
1771                        const CodeLocation & loc, const node_t * node,
1772                        ast::ParameterizedType::ForallList parent_t::* forallField
1773                ) {
1774                        for ( unsigned i = 0; i < (node->* forallField).size(); ++i ) {
1775                                const ast::TypeDecl * type = (node->* forallField)[i];
1776                                if ( type->assertions.empty() ) continue;
1777
1778                                std::vector< ast::ptr< ast::DeclWithType > > asserts;
1779                                asserts.reserve( type->assertions.size() );
1780
1781                                // expand trait instances into their members
1782                                for ( const ast::DeclWithType * assn : type->assertions ) {
1783                                        auto traitInst =
1784                                                dynamic_cast< const ast::TraitInstType * >( assn->get_type() );
1785                                        if ( traitInst ) {
1786                                                // expand trait instance to all its members
1787                                                expandAssertions( traitInst, asserts );
1788                                        } else {
1789                                                // pass other assertions through
1790                                                asserts.emplace_back( assn );
1791                                        }
1792                                }
1793
1794                                // apply FixFunction to every assertion to check for invalid void type
1795                                for ( ast::ptr< ast::DeclWithType > & assn : asserts ) {
1796                                        bool isVoid = false;
1797                                        assn = fixFunction( assn, isVoid );
1798                                        if ( isVoid ) {
1799                                                SemanticError( loc, node, "invalid type void in assertion of function " );
1800                                        }
1801                                }
1802
1803                                // place mutated assertion list in node
1804                                auto mut = mutate( type );
1805                                mut->assertions = move( asserts );
1806                                node = ast::mutate_field_index( node, forallField, i, mut );
1807                        }
1808                        return node;
1809                }
1810
1811                const ast::FunctionType * previsit( const ast::FunctionType * ftype ) {
1812                        return forallFixer( location, ftype, &ast::FunctionType::forall );
1813                }
1814
1815                const ast::StructDecl * previsit( const ast::StructDecl * aggrDecl ) {
1816                        return forallFixer( aggrDecl->location, aggrDecl, &ast::StructDecl::params );
1817                }
1818
1819                const ast::UnionDecl * previsit( const ast::UnionDecl * aggrDecl ) {
1820                        return forallFixer( aggrDecl->location, aggrDecl, &ast::UnionDecl::params );
1821                }
1822        };
1823} // anonymous namespace
1824
1825const ast::Type * validateType(
1826                const CodeLocation & loc, const ast::Type * type, const ast::SymbolTable & symtab ) {
1827        ast::Pass< EnumAndPointerDecay_new > epc;
1828        ast::Pass< LinkReferenceToTypes_new > lrt{ loc, symtab };
1829        ast::Pass< ForallPointerDecay_new > fpd{ loc };
1830
1831        return type->accept( epc )->accept( lrt )->accept( fpd );
1832}
1833
1834} // namespace SymTab
1835
1836// Local Variables: //
1837// tab-width: 4 //
1838// mode: c++ //
1839// compile-command: "make install" //
1840// End: //
Note: See TracBrowser for help on using the repository browser.