source: src/SymTab/Validate.cc @ 437b8b5

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since 437b8b5 was 92538ab, checked in by JiadaL <j82liang@…>, 2 years ago

Resolve conflict

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