source: src/SymTab/Validate.cc @ d7af839

ADTast-experimentalpthread-emulationqualifiedEnum
Last change on this file since d7af839 was 72e76fd, checked in by Andrew Beach <ajbeach@…>, 21 months ago

Converted the last pass in validate B (linkReferenceToTypes). Cleaned up a related test.

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