source: src/SymTab/Validate.cc @ 75f6a5f

ADTast-experimental
Last change on this file since 75f6a5f was 5408b59, checked in by JiadaL <j82liang@…>, 19 months ago

Remove var in QualifiedNameExpr?

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