source: src/SymTab/Validate.cc @ cde3891

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since cde3891 was cde3891, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Merge branch 'master' into cleanup-dtors

  • Property mode set to 100644
File size: 51.3 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Validate.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:50:04 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Mon Aug 28 13:47:23 2017
13// Update Count     : 359
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 <utility>                     // for pair
47
48#include "CodeGen/CodeGenerator.h"     // for genName
49#include "CodeGen/OperatorTable.h"     // for isCtorDtor, isCtorDtorAssign
50#include "ControlStruct/Mutate.h"      // for ForExprMutator
51#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
52#include "Common/ScopedMap.h"          // for ScopedMap
53#include "Common/SemanticError.h"      // for SemanticError
54#include "Common/UniqueName.h"         // for UniqueName
55#include "Common/utility.h"            // for operator+, cloneAll, deleteAll
56#include "Concurrency/Keywords.h"      // for applyKeywords
57#include "FixFunction.h"               // for FixFunction
58#include "Indexer.h"                   // for Indexer
59#include "InitTweak/GenInit.h"         // for fixReturnStatements
60#include "InitTweak/InitTweak.h"       // for isCtorDtorAssign
61#include "Parser/LinkageSpec.h"        // for C
62#include "ResolvExpr/typeops.h"        // for typesCompatible
63#include "ResolvExpr/Resolver.h"       // for findSingleExpression
64#include "ResolvExpr/ResolveTypeof.h"  // for resolveTypeof
65#include "SymTab/Autogen.h"            // for SizeType
66#include "SynTree/Attribute.h"         // for noAttributes, Attribute
67#include "SynTree/Constant.h"          // for Constant
68#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
69#include "SynTree/Expression.h"        // for CompoundLiteralExpr, Expressio...
70#include "SynTree/Initializer.h"       // for ListInit, Initializer
71#include "SynTree/Label.h"             // for operator==, Label
72#include "SynTree/Mutator.h"           // for Mutator
73#include "SynTree/Type.h"              // for Type, TypeInstType, EnumInstType
74#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
75#include "SynTree/Visitor.h"           // for Visitor
76#include "Validate/HandleAttributes.h" // for handleAttributes
77#include "Validate/FindSpecialDecls.h" // for FindSpecialDecls
78
79class CompoundStmt;
80class ReturnStmt;
81class SwitchStmt;
82
83#define debugPrint( x ) if ( doDebug ) x
84
85namespace SymTab {
86        /// hoists declarations that are difficult to hoist while parsing
87        struct HoistTypeDecls final : public WithDeclsToAdd {
88                void previsit( SizeofExpr * );
89                void previsit( AlignofExpr * );
90                void previsit( UntypedOffsetofExpr * );
91                void previsit( CompoundLiteralExpr * );
92                void handleType( Type * );
93        };
94
95        struct FixQualifiedTypes final : public WithIndexer {
96                Type * postmutate( QualifiedType * );
97        };
98
99        struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
100                /// Flattens nested struct types
101                static void hoistStruct( std::list< Declaration * > &translationUnit );
102
103                void previsit( StructDecl * aggregateDecl );
104                void previsit( UnionDecl * aggregateDecl );
105                void previsit( StaticAssertDecl * assertDecl );
106                void previsit( StructInstType * type );
107                void previsit( UnionInstType * type );
108                void previsit( EnumInstType * type );
109
110          private:
111                template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
112
113                AggregateDecl * parentAggr = nullptr;
114        };
115
116        /// Fix return types so that every function returns exactly one value
117        struct ReturnTypeFixer {
118                static void fix( std::list< Declaration * > &translationUnit );
119
120                void postvisit( FunctionDecl * functionDecl );
121                void postvisit( FunctionType * ftype );
122        };
123
124        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
125        struct EnumAndPointerDecay {
126                void previsit( EnumDecl *aggregateDecl );
127                void previsit( FunctionType *func );
128        };
129
130        /// Associates forward declarations of aggregates with their definitions
131        struct LinkReferenceToTypes final : public WithIndexer, public WithGuards, public WithVisitorRef<LinkReferenceToTypes>, public WithShortCircuiting {
132                LinkReferenceToTypes( const Indexer *indexer );
133                void postvisit( TypeInstType *typeInst );
134
135                void postvisit( EnumInstType *enumInst );
136                void postvisit( StructInstType *structInst );
137                void postvisit( UnionInstType *unionInst );
138                void postvisit( TraitInstType *traitInst );
139                void previsit( QualifiedType * qualType );
140                void postvisit( QualifiedType * qualType );
141
142                void postvisit( EnumDecl *enumDecl );
143                void postvisit( StructDecl *structDecl );
144                void postvisit( UnionDecl *unionDecl );
145                void postvisit( TraitDecl * traitDecl );
146
147                void previsit( StructDecl *structDecl );
148                void previsit( UnionDecl *unionDecl );
149
150                void renameGenericParams( std::list< TypeDecl * > & params );
151
152          private:
153                const Indexer *local_indexer;
154
155                typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
156                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
157                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
158                ForwardEnumsType forwardEnums;
159                ForwardStructsType forwardStructs;
160                ForwardUnionsType forwardUnions;
161                /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
162                bool inGeneric = false;
163        };
164
165        /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
166        struct ForallPointerDecay final {
167                void previsit( ObjectDecl * object );
168                void previsit( FunctionDecl * func );
169                void previsit( FunctionType * ftype );
170                void previsit( StructDecl * aggrDecl );
171                void previsit( UnionDecl * aggrDecl );
172        };
173
174        struct ReturnChecker : public WithGuards {
175                /// Checks that return statements return nothing if their return type is void
176                /// and return something if the return type is non-void.
177                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
178
179                void previsit( FunctionDecl * functionDecl );
180                void previsit( ReturnStmt * returnStmt );
181
182                typedef std::list< DeclarationWithType * > ReturnVals;
183                ReturnVals returnVals;
184        };
185
186        struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd {
187                ReplaceTypedef() : scopeLevel( 0 ) {}
188                /// Replaces typedefs by forward declarations
189                static void replaceTypedef( std::list< Declaration * > &translationUnit );
190
191                void premutate( QualifiedType * );
192                Type * postmutate( QualifiedType * qualType );
193                Type * postmutate( TypeInstType * aggregateUseType );
194                Declaration * postmutate( TypedefDecl * typeDecl );
195                void premutate( TypeDecl * typeDecl );
196                void premutate( FunctionDecl * funcDecl );
197                void premutate( ObjectDecl * objDecl );
198                DeclarationWithType * postmutate( ObjectDecl * objDecl );
199
200                void premutate( CastExpr * castExpr );
201
202                void premutate( CompoundStmt * compoundStmt );
203
204                void premutate( StructDecl * structDecl );
205                void premutate( UnionDecl * unionDecl );
206                void premutate( EnumDecl * enumDecl );
207                void premutate( TraitDecl * );
208
209                void premutate( FunctionType * ftype );
210
211          private:
212                template<typename AggDecl>
213                void addImplicitTypedef( AggDecl * aggDecl );
214                template< typename AggDecl >
215                void handleAggregate( AggDecl * aggr );
216
217                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
218                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
219                typedef ScopedMap< std::string, TypeDecl * > TypeDeclMap;
220                TypedefMap typedefNames;
221                TypeDeclMap typedeclNames;
222                int scopeLevel;
223                bool inFunctionType = false;
224        };
225
226        struct EliminateTypedef {
227                /// removes TypedefDecls from the AST
228                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
229
230                template<typename AggDecl>
231                void handleAggregate( AggDecl *aggregateDecl );
232
233                void previsit( StructDecl * aggregateDecl );
234                void previsit( UnionDecl * aggregateDecl );
235                void previsit( CompoundStmt * compoundStmt );
236        };
237
238        struct VerifyCtorDtorAssign {
239                /// ensure that constructors, destructors, and assignment have at least one
240                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
241                /// return values.
242                static void verify( std::list< Declaration * > &translationUnit );
243
244                void previsit( FunctionDecl *funcDecl );
245        };
246
247        /// ensure that generic types have the correct number of type arguments
248        struct ValidateGenericParameters {
249                void previsit( StructInstType * inst );
250                void previsit( UnionInstType * inst );
251        };
252
253        struct FixObjectType : public WithIndexer {
254                /// resolves typeof type in object, function, and type declarations
255                static void fix( std::list< Declaration * > & translationUnit );
256
257                void previsit( ObjectDecl * );
258                void previsit( FunctionDecl * );
259                void previsit( TypeDecl * );
260        };
261
262        struct ArrayLength : public WithIndexer {
263                /// for array types without an explicit length, compute the length and store it so that it
264                /// is known to the rest of the phases. For example,
265                ///   int x[] = { 1, 2, 3 };
266                ///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
267                /// here x and y are known at compile-time to have length 3, so change this into
268                ///   int x[3] = { 1, 2, 3 };
269                ///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
270                static void computeLength( std::list< Declaration * > & translationUnit );
271
272                void previsit( ObjectDecl * objDecl );
273                void previsit( ArrayType * arrayType );
274        };
275
276        struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
277                Type::StorageClasses storageClasses;
278
279                void premutate( ObjectDecl *objectDecl );
280                Expression * postmutate( CompoundLiteralExpr *compLitExpr );
281        };
282
283        struct LabelAddressFixer final : public WithGuards {
284                std::set< Label > labels;
285
286                void premutate( FunctionDecl * funcDecl );
287                Expression * postmutate( AddressExpr * addrExpr );
288        };
289
290        void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
291                PassVisitor<EnumAndPointerDecay> epc;
292                PassVisitor<LinkReferenceToTypes> lrt( nullptr );
293                PassVisitor<ForallPointerDecay> fpd;
294                PassVisitor<CompoundLiteral> compoundliteral;
295                PassVisitor<ValidateGenericParameters> genericParams;
296                PassVisitor<LabelAddressFixer> labelAddrFixer;
297                PassVisitor<HoistTypeDecls> hoistDecls;
298                PassVisitor<FixQualifiedTypes> fixQual;
299
300                acceptAll( translationUnit, hoistDecls );
301                ReplaceTypedef::replaceTypedef( translationUnit );
302                ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
303                acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes because it is an indexer and needs correct types for mangling
304                acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
305                mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes, because aggregate members are accessed
306                HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order
307                EliminateTypedef::eliminateTypedef( translationUnit ); //
308                acceptAll( translationUnit, genericParams );  // check as early as possible - can't happen before LinkReferenceToTypes
309                VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
310                ReturnChecker::checkFunctionReturns( translationUnit );
311                InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
312                Concurrency::applyKeywords( translationUnit );
313                acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
314                ControlStruct::hoistControlDecls( translationUnit );  // hoist initialization out of for statements; must happen before autogenerateRoutines
315                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay
316                Concurrency::implementMutexFuncs( translationUnit );
317                Concurrency::implementThreadStarter( translationUnit );
318                mutateAll( translationUnit, compoundliteral );
319                ResolvExpr::resolveWithExprs( translationUnit ); // must happen before FixObjectType because user-code is resolved and may contain with variables
320                FixObjectType::fix( translationUnit );
321                ArrayLength::computeLength( translationUnit );
322                Validate::findSpecialDecls( translationUnit );
323                mutateAll( translationUnit, labelAddrFixer );
324                Validate::handleAttributes( translationUnit );
325        }
326
327        void validateType( Type *type, const Indexer *indexer ) {
328                PassVisitor<EnumAndPointerDecay> epc;
329                PassVisitor<LinkReferenceToTypes> lrt( indexer );
330                PassVisitor<ForallPointerDecay> fpd;
331                type->accept( epc );
332                type->accept( lrt );
333                type->accept( fpd );
334        }
335
336
337        void HoistTypeDecls::handleType( Type * type ) {
338                // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here
339                AggregateDecl * aggr = nullptr;
340                if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) {
341                        aggr = inst->baseStruct;
342                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) {
343                        aggr = inst->baseUnion;
344                } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) {
345                        aggr = inst->baseEnum;
346                }
347                if ( aggr && aggr->body ) {
348                        declsToAddBefore.push_front( aggr );
349                }
350        }
351
352        void HoistTypeDecls::previsit( SizeofExpr * expr ) {
353                handleType( expr->type );
354        }
355
356        void HoistTypeDecls::previsit( AlignofExpr * expr ) {
357                handleType( expr->type );
358        }
359
360        void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) {
361                handleType( expr->type );
362        }
363
364        void HoistTypeDecls::previsit( CompoundLiteralExpr * expr ) {
365                handleType( expr->result );
366        }
367
368
369        Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) {
370                Type * parent = qualType->parent;
371                Type * child = qualType->child;
372                if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) {
373                        // .T => lookup T at global scope
374                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
375                                auto td = indexer.globalLookupType( inst->name );
376                                if ( ! td ) {
377                                        SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) );
378                                }
379                                auto base = td->base;
380                                assert( base );
381                                Type * ret = base->clone();
382                                ret->get_qualifiers() = qualType->get_qualifiers();
383                                return ret;
384                        } else {
385                                // .T => T is not a type name
386                                assertf( false, "unhandled global qualified child type: %s", toCString(child) );
387                        }
388                } else {
389                        // S.T => S must be an aggregate type, find the declaration for T in S.
390                        AggregateDecl * aggr = nullptr;
391                        if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) {
392                                aggr = inst->baseStruct;
393                        } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) {
394                                aggr = inst->baseUnion;
395                        } else {
396                                SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) );
397                        }
398                        assert( aggr ); // TODO: need to handle forward declarations
399                        for ( Declaration * member : aggr->members ) {
400                                if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
401                                        // name on the right is a typedef
402                                        if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) {
403                                                if ( aggr->name == inst->name ) {
404                                                        assert( aggr->base );
405                                                        Type * ret = aggr->base->clone();
406                                                        ret->get_qualifiers() = qualType->get_qualifiers();
407                                                        TypeSubstitution sub = parent->genericSubstitution();
408                                                        sub.apply(ret);
409                                                        return ret;
410                                                }
411                                        }
412                                } else {
413                                        // S.T - S is not an aggregate => error
414                                        assertf( false, "unhandled qualified child type: %s", toCString(qualType) );
415                                }
416                        }
417                        // failed to find a satisfying definition of type
418                        SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) );
419                }
420
421                // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup?
422        }
423
424
425        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
426                PassVisitor<HoistStruct> hoister;
427                acceptAll( translationUnit, hoister );
428        }
429
430        bool shouldHoist( Declaration *decl ) {
431                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl );
432        }
433
434        namespace {
435                void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) {
436                        if ( aggr->parent ) qualifiedName( aggr->parent, ss );
437                        ss << "__" << aggr->name;
438                }
439
440                // mangle nested type names using entire parent chain
441                std::string qualifiedName( AggregateDecl * aggr ) {
442                        std::ostringstream ss;
443                        qualifiedName( aggr, ss );
444                        return ss.str();
445                }
446        }
447
448        template< typename AggDecl >
449        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
450                if ( parentAggr ) {
451                        aggregateDecl->parent = parentAggr;
452                        aggregateDecl->name = qualifiedName( aggregateDecl );
453                        // Add elements in stack order corresponding to nesting structure.
454                        declsToAddBefore.push_front( aggregateDecl );
455                } else {
456                        GuardValue( parentAggr );
457                        parentAggr = aggregateDecl;
458                } // if
459                // Always remove the hoisted aggregate from the inner structure.
460                GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } );
461        }
462
463        void HoistStruct::previsit( StaticAssertDecl * assertDecl ) {
464                if ( parentAggr ) {
465                        declsToAddBefore.push_back( assertDecl );
466                }
467        }
468
469        void HoistStruct::previsit( StructDecl * aggregateDecl ) {
470                handleAggregate( aggregateDecl );
471        }
472
473        void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
474                handleAggregate( aggregateDecl );
475        }
476
477        void HoistStruct::previsit( StructInstType * type ) {
478                // need to reset type name after expanding to qualified name
479                assert( type->baseStruct );
480                type->name = type->baseStruct->name;
481        }
482
483        void HoistStruct::previsit( UnionInstType * type ) {
484                assert( type->baseUnion );
485                type->name = type->baseUnion->name;
486        }
487
488        void HoistStruct::previsit( EnumInstType * type ) {
489                assert( type->baseEnum );
490                type->name = type->baseEnum->name;
491        }
492
493
494        bool isTypedef( Declaration *decl ) {
495                return dynamic_cast< TypedefDecl * >( decl );
496        }
497
498        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
499                PassVisitor<EliminateTypedef> eliminator;
500                acceptAll( translationUnit, eliminator );
501                filter( translationUnit, isTypedef, true );
502        }
503
504        template< typename AggDecl >
505        void EliminateTypedef::handleAggregate( AggDecl *aggregateDecl ) {
506                filter( aggregateDecl->members, isTypedef, true );
507        }
508
509        void EliminateTypedef::previsit( StructDecl * aggregateDecl ) {
510                handleAggregate( aggregateDecl );
511        }
512
513        void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) {
514                handleAggregate( aggregateDecl );
515        }
516
517        void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) {
518                // remove and delete decl stmts
519                filter( compoundStmt->kids, [](Statement * stmt) {
520                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
521                                if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) {
522                                        return true;
523                                } // if
524                        } // if
525                        return false;
526                }, true);
527        }
528
529        void EnumAndPointerDecay::previsit( EnumDecl *enumDecl ) {
530                // Set the type of each member of the enumeration to be EnumConstant
531                for ( std::list< Declaration * >::iterator i = enumDecl->members.begin(); i != enumDecl->members.end(); ++i ) {
532                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
533                        assert( obj );
534                        obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->name ) );
535                } // for
536        }
537
538        namespace {
539                template< typename DWTList >
540                void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
541                        auto nvals = dwts.size();
542                        bool containsVoid = false;
543                        for ( auto & dwt : dwts ) {
544                                // fix each DWT and record whether a void was found
545                                containsVoid |= fixFunction( dwt );
546                        }
547
548                        // the only case in which "void" is valid is where it is the only one in the list
549                        if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
550                                SemanticError( func, "invalid type void in function type " );
551                        }
552
553                        // one void is the only thing in the list; remove it.
554                        if ( containsVoid ) {
555                                delete dwts.front();
556                                dwts.clear();
557                        }
558                }
559        }
560
561        void EnumAndPointerDecay::previsit( FunctionType *func ) {
562                // Fix up parameters and return types
563                fixFunctionList( func->parameters, func->isVarArgs, func );
564                fixFunctionList( func->returnVals, false, func );
565        }
566
567        LinkReferenceToTypes::LinkReferenceToTypes( const Indexer *other_indexer ) {
568                if ( other_indexer ) {
569                        local_indexer = other_indexer;
570                } else {
571                        local_indexer = &indexer;
572                } // if
573        }
574
575        void LinkReferenceToTypes::postvisit( EnumInstType *enumInst ) {
576                EnumDecl *st = local_indexer->lookupEnum( enumInst->name );
577                // it's not a semantic error if the enum is not found, just an implicit forward declaration
578                if ( st ) {
579                        enumInst->baseEnum = st;
580                } // if
581                if ( ! st || ! st->body ) {
582                        // use of forward declaration
583                        forwardEnums[ enumInst->name ].push_back( enumInst );
584                } // if
585        }
586
587        void checkGenericParameters( ReferenceToType * inst ) {
588                for ( Expression * param : inst->parameters ) {
589                        if ( ! dynamic_cast< TypeExpr * >( param ) ) {
590                                SemanticError( inst, "Expression parameters for generic types are currently unsupported: " );
591                        }
592                }
593        }
594
595        void LinkReferenceToTypes::postvisit( StructInstType *structInst ) {
596                StructDecl *st = local_indexer->lookupStruct( structInst->name );
597                // it's not a semantic error if the struct is not found, just an implicit forward declaration
598                if ( st ) {
599                        structInst->baseStruct = st;
600                } // if
601                if ( ! st || ! st->body ) {
602                        // use of forward declaration
603                        forwardStructs[ structInst->name ].push_back( structInst );
604                } // if
605                checkGenericParameters( structInst );
606        }
607
608        void LinkReferenceToTypes::postvisit( UnionInstType *unionInst ) {
609                UnionDecl *un = local_indexer->lookupUnion( unionInst->name );
610                // it's not a semantic error if the union is not found, just an implicit forward declaration
611                if ( un ) {
612                        unionInst->baseUnion = un;
613                } // if
614                if ( ! un || ! un->body ) {
615                        // use of forward declaration
616                        forwardUnions[ unionInst->name ].push_back( unionInst );
617                } // if
618                checkGenericParameters( unionInst );
619        }
620
621        void LinkReferenceToTypes::previsit( QualifiedType * ) {
622                visit_children = false;
623        }
624
625        void LinkReferenceToTypes::postvisit( QualifiedType * qualType ) {
626                // linking only makes sense for the 'oldest ancestor' of the qualified type
627                qualType->parent->accept( *visitor );
628        }
629
630        template< typename Decl >
631        void normalizeAssertions( std::list< Decl * > & assertions ) {
632                // ensure no duplicate trait members after the clone
633                auto pred = [](Decl * d1, Decl * d2) {
634                        // only care if they're equal
635                        DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
636                        DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
637                        if ( dwt1 && dwt2 ) {
638                                if ( dwt1->name == dwt2->name && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
639                                        // std::cerr << "=========== equal:" << std::endl;
640                                        // std::cerr << "d1: " << d1 << std::endl;
641                                        // std::cerr << "d2: " << d2 << std::endl;
642                                        return false;
643                                }
644                        }
645                        return d1 < d2;
646                };
647                std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
648                // if ( unique_members.size() != assertions.size() ) {
649                //      std::cerr << "============different" << std::endl;
650                //      std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
651                // }
652
653                std::list< Decl * > order;
654                order.splice( order.end(), assertions );
655                std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
656                        return unique_members.count( decl );
657                });
658        }
659
660        // expand assertions from trait instance, performing the appropriate type variable substitutions
661        template< typename Iterator >
662        void expandAssertions( TraitInstType * inst, Iterator out ) {
663                assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
664                std::list< DeclarationWithType * > asserts;
665                for ( Declaration * decl : inst->baseTrait->members ) {
666                        asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
667                }
668                // substitute trait decl parameters for instance parameters
669                applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
670        }
671
672        void LinkReferenceToTypes::postvisit( TraitDecl * traitDecl ) {
673                if ( traitDecl->name == "sized" ) {
674                        // "sized" is a special trait - flick the sized status on for the type variable
675                        assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
676                        TypeDecl * td = traitDecl->parameters.front();
677                        td->set_sized( true );
678                }
679
680                // move assertions from type parameters into the body of the trait
681                for ( TypeDecl * td : traitDecl->parameters ) {
682                        for ( DeclarationWithType * assert : td->assertions ) {
683                                if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
684                                        expandAssertions( inst, back_inserter( traitDecl->members ) );
685                                } else {
686                                        traitDecl->members.push_back( assert->clone() );
687                                }
688                        }
689                        deleteAll( td->assertions );
690                        td->assertions.clear();
691                } // for
692        }
693
694        void LinkReferenceToTypes::postvisit( TraitInstType * traitInst ) {
695                // handle other traits
696                TraitDecl *traitDecl = local_indexer->lookupTrait( traitInst->name );
697                if ( ! traitDecl ) {
698                        SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
699                } // if
700                if ( traitDecl->parameters.size() != traitInst->parameters.size() ) {
701                        SemanticError( traitInst, "incorrect number of trait parameters: " );
702                } // if
703                traitInst->baseTrait = traitDecl;
704
705                // need to carry over the 'sized' status of each decl in the instance
706                for ( auto p : group_iterate( traitDecl->parameters, traitInst->parameters ) ) {
707                        TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
708                        if ( ! expr ) {
709                                SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
710                        }
711                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
712                                TypeDecl * formalDecl = std::get<0>(p);
713                                TypeDecl * instDecl = inst->baseType;
714                                if ( formalDecl->get_sized() ) instDecl->set_sized( true );
715                        }
716                }
717                // normalizeAssertions( traitInst->members );
718        }
719
720        void LinkReferenceToTypes::postvisit( EnumDecl *enumDecl ) {
721                // visit enum members first so that the types of self-referencing members are updated properly
722                if ( enumDecl->body ) {
723                        ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->name );
724                        if ( fwds != forwardEnums.end() ) {
725                                for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
726                                        (*inst)->baseEnum = enumDecl;
727                                } // for
728                                forwardEnums.erase( fwds );
729                        } // if
730
731                        for ( Declaration * member : enumDecl->members ) {
732                                ObjectDecl * field = strict_dynamic_cast<ObjectDecl *>( member );
733                                if ( field->init ) {
734                                        // need to resolve enumerator initializers early so that other passes that determine if an expression is constexpr have the appropriate information.
735                                        SingleInit * init = strict_dynamic_cast<SingleInit *>( field->init );
736                                        ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer );
737                                }
738                        }
739                } // if
740        }
741
742        void LinkReferenceToTypes::renameGenericParams( std::list< TypeDecl * > & params ) {
743                // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
744                //   forall(otype T)
745                //   struct Box {
746                //     T x;
747                //   };
748                //   forall(otype T)
749                //   void f(Box(T) b) {
750                //     ...
751                //   }
752                // The T in Box and the T in f are different, so internally the naming must reflect that.
753                GuardValue( inGeneric );
754                inGeneric = ! params.empty();
755                for ( TypeDecl * td : params ) {
756                        td->name = "__" + td->name + "_generic_";
757                }
758        }
759
760        void LinkReferenceToTypes::previsit( StructDecl * structDecl ) {
761                renameGenericParams( structDecl->parameters );
762        }
763
764        void LinkReferenceToTypes::previsit( UnionDecl * unionDecl ) {
765                renameGenericParams( unionDecl->parameters );
766        }
767
768        void LinkReferenceToTypes::postvisit( StructDecl *structDecl ) {
769                // visit struct members first so that the types of self-referencing members are updated properly
770                // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
771                if ( structDecl->body ) {
772                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->name );
773                        if ( fwds != forwardStructs.end() ) {
774                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
775                                        (*inst)->baseStruct = structDecl;
776                                } // for
777                                forwardStructs.erase( fwds );
778                        } // if
779                } // if
780        }
781
782        void LinkReferenceToTypes::postvisit( UnionDecl *unionDecl ) {
783                if ( unionDecl->body ) {
784                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->name );
785                        if ( fwds != forwardUnions.end() ) {
786                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
787                                        (*inst)->baseUnion = unionDecl;
788                                } // for
789                                forwardUnions.erase( fwds );
790                        } // if
791                } // if
792        }
793
794        void LinkReferenceToTypes::postvisit( TypeInstType *typeInst ) {
795                // ensure generic parameter instances are renamed like the base type
796                if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
797                if ( NamedTypeDecl *namedTypeDecl = local_indexer->lookupType( typeInst->name ) ) {
798                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
799                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
800                        } // if
801                } // if
802        }
803
804        /// Fix up assertions - flattens assertion lists, removing all trait instances
805        void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
806                for ( TypeDecl * type : forall ) {
807                        std::list< DeclarationWithType * > asserts;
808                        asserts.splice( asserts.end(), type->assertions );
809                        // expand trait instances into their members
810                        for ( DeclarationWithType * assertion : asserts ) {
811                                if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
812                                        // expand trait instance into all of its members
813                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
814                                        delete traitInst;
815                                } else {
816                                        // pass other assertions through
817                                        type->assertions.push_back( assertion );
818                                } // if
819                        } // for
820                        // apply FixFunction to every assertion to check for invalid void type
821                        for ( DeclarationWithType *& assertion : type->assertions ) {
822                                bool isVoid = fixFunction( assertion );
823                                if ( isVoid ) {
824                                        SemanticError( node, "invalid type void in assertion of function " );
825                                } // if
826                        } // for
827                        // normalizeAssertions( type->assertions );
828                } // for
829        }
830
831        void ForallPointerDecay::previsit( ObjectDecl *object ) {
832                // ensure that operator names only apply to functions or function pointers
833                if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
834                        SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." )  );
835                }
836                object->fixUniqueId();
837        }
838
839        void ForallPointerDecay::previsit( FunctionDecl *func ) {
840                func->fixUniqueId();
841        }
842
843        void ForallPointerDecay::previsit( FunctionType * ftype ) {
844                forallFixer( ftype->forall, ftype );
845        }
846
847        void ForallPointerDecay::previsit( StructDecl * aggrDecl ) {
848                forallFixer( aggrDecl->parameters, aggrDecl );
849        }
850
851        void ForallPointerDecay::previsit( UnionDecl * aggrDecl ) {
852                forallFixer( aggrDecl->parameters, aggrDecl );
853        }
854
855        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
856                PassVisitor<ReturnChecker> checker;
857                acceptAll( translationUnit, checker );
858        }
859
860        void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
861                GuardValue( returnVals );
862                returnVals = functionDecl->get_functionType()->get_returnVals();
863        }
864
865        void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
866                // Previously this also checked for the existence of an expr paired with no return values on
867                // the  function return type. This is incorrect, since you can have an expression attached to
868                // a return statement in a void-returning function in C. The expression is treated as if it
869                // were cast to void.
870                if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
871                        SemanticError( returnStmt, "Non-void function returns no values: " );
872                }
873        }
874
875
876        void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) {
877                PassVisitor<ReplaceTypedef> eliminator;
878                mutateAll( translationUnit, eliminator );
879                if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
880                        // grab and remember declaration of size_t
881                        Validate::SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone();
882                } else {
883                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
884                        // eventually should have a warning for this case.
885                        Validate::SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
886                }
887        }
888
889        void ReplaceTypedef::premutate( QualifiedType * ) {
890                visit_children = false;
891        }
892
893        Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) {
894                // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type
895                qualType->parent = qualType->parent->acceptMutator( *visitor );
896                return qualType;
897        }
898
899        Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) {
900                // instances of typedef types will come here. If it is an instance
901                // of a typdef type, link the instance to its actual type.
902                TypedefMap::const_iterator def = typedefNames.find( typeInst->name );
903                if ( def != typedefNames.end() ) {
904                        Type *ret = def->second.first->base->clone();
905                        ret->location = typeInst->location;
906                        ret->get_qualifiers() |= typeInst->get_qualifiers();
907                        // attributes are not carried over from typedef to function parameters/return values
908                        if ( ! inFunctionType ) {
909                                ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
910                        } else {
911                                deleteAll( ret->attributes );
912                                ret->attributes.clear();
913                        }
914                        // place instance parameters on the typedef'd type
915                        if ( ! typeInst->parameters.empty() ) {
916                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
917                                if ( ! rtt ) {
918                                        SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
919                                }
920                                rtt->parameters.clear();
921                                cloneAll( typeInst->parameters, rtt->parameters );
922                                mutateAll( rtt->parameters, *visitor );  // recursively fix typedefs on parameters
923                        } // if
924                        delete typeInst;
925                        return ret;
926                } else {
927                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name );
928                        if ( base == typedeclNames.end() ) {
929                                SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) );
930                        }
931                        typeInst->set_baseType( base->second );
932                        return typeInst;
933                } // if
934                assert( false );
935        }
936
937        struct VarLenChecker : WithShortCircuiting {
938                void previsit( FunctionType * ) { visit_children = false; }
939                void previsit( ArrayType * at ) {
940                        isVarLen |= at->isVarLen;
941                }
942                bool isVarLen = false;
943        };
944
945        bool isVariableLength( Type * t ) {
946                PassVisitor<VarLenChecker> varLenChecker;
947                maybeAccept( t, varLenChecker );
948                return varLenChecker.pass.isVarLen;
949        }
950
951        Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) {
952                if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) {
953                        // typedef to the same name from the same scope
954                        // must be from the same type
955
956                        Type * t1 = tyDecl->base;
957                        Type * t2 = typedefNames[ tyDecl->name ].first->base;
958                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
959                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
960                        }
961                        // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
962                        // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
963                        // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
964                        // to fix this corner case likely outweighs the utility of allowing it.
965                        if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
966                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
967                        }
968                } else {
969                        typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
970                } // if
971
972                // When a typedef is a forward declaration:
973                //    typedef struct screen SCREEN;
974                // the declaration portion must be retained:
975                //    struct screen;
976                // because the expansion of the typedef is:
977                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
978                // hence the type-name "screen" must be defined.
979                // Note, qualifiers on the typedef are superfluous for the forward declaration.
980
981                Type *designatorType = tyDecl->base->stripDeclarator();
982                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
983                        declsToAddBefore.push_back( new StructDecl( aggDecl->name, DeclarationNode::Struct, noAttributes, tyDecl->linkage ) );
984                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
985                        declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) );
986                } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
987                        declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, tyDecl->linkage ) );
988                } // if
989                return tyDecl->clone();
990        }
991
992        void ReplaceTypedef::premutate( TypeDecl * typeDecl ) {
993                TypedefMap::iterator i = typedefNames.find( typeDecl->name );
994                if ( i != typedefNames.end() ) {
995                        typedefNames.erase( i ) ;
996                } // if
997
998                typedeclNames.insert( typeDecl->name, typeDecl );
999        }
1000
1001        void ReplaceTypedef::premutate( FunctionDecl * ) {
1002                GuardScope( typedefNames );
1003                GuardScope( typedeclNames );
1004        }
1005
1006        void ReplaceTypedef::premutate( ObjectDecl * ) {
1007                GuardScope( typedefNames );
1008                GuardScope( typedeclNames );
1009        }
1010
1011        DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) {
1012                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type?
1013                        // replace the current object declaration with a function declaration
1014                        FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() );
1015                        objDecl->attributes.clear();
1016                        objDecl->set_type( nullptr );
1017                        delete objDecl;
1018                        return newDecl;
1019                } // if
1020                return objDecl;
1021        }
1022
1023        void ReplaceTypedef::premutate( CastExpr * ) {
1024                GuardScope( typedefNames );
1025                GuardScope( typedeclNames );
1026        }
1027
1028        void ReplaceTypedef::premutate( CompoundStmt * ) {
1029                GuardScope( typedefNames );
1030                GuardScope( typedeclNames );
1031                scopeLevel += 1;
1032                GuardAction( [this](){ scopeLevel -= 1; } );
1033        }
1034
1035        template<typename AggDecl>
1036        void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
1037                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
1038                        Type *type = nullptr;
1039                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
1040                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
1041                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
1042                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
1043                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
1044                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
1045                        } // if
1046                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
1047                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
1048                        // add the implicit typedef to the AST
1049                        declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) );
1050                } // if
1051        }
1052
1053        template< typename AggDecl >
1054        void ReplaceTypedef::handleAggregate( AggDecl * aggr ) {
1055                SemanticErrorException errors;
1056
1057                ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore );
1058                ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter  );
1059                declsToAddBefore.clear();
1060                declsToAddAfter.clear();
1061
1062                GuardScope( typedefNames );
1063                GuardScope( typedeclNames );
1064                mutateAll( aggr->parameters, *visitor );
1065
1066                // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body.
1067                for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) {
1068                        if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); }
1069
1070                        try {
1071                                *i = maybeMutate( *i, *visitor );
1072                        } catch ( SemanticErrorException &e ) {
1073                                errors.append( e );
1074                        }
1075
1076                        if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); }
1077                }
1078
1079                if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); }
1080                if ( !errors.isEmpty() ) { throw errors; }
1081        }
1082
1083        void ReplaceTypedef::premutate( StructDecl * structDecl ) {
1084                visit_children = false;
1085                addImplicitTypedef( structDecl );
1086                handleAggregate( structDecl );
1087        }
1088
1089        void ReplaceTypedef::premutate( UnionDecl * unionDecl ) {
1090                visit_children = false;
1091                addImplicitTypedef( unionDecl );
1092                handleAggregate( unionDecl );
1093        }
1094
1095        void ReplaceTypedef::premutate( EnumDecl * enumDecl ) {
1096                addImplicitTypedef( enumDecl );
1097        }
1098
1099        void ReplaceTypedef::premutate( FunctionType * ) {
1100                GuardValue( inFunctionType );
1101                inFunctionType = true;
1102        }
1103
1104        void ReplaceTypedef::premutate( TraitDecl * ) {
1105                GuardScope( typedefNames );
1106                GuardScope( typedeclNames);
1107        }
1108
1109        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
1110                PassVisitor<VerifyCtorDtorAssign> verifier;
1111                acceptAll( translationUnit, verifier );
1112        }
1113
1114        void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
1115                FunctionType * funcType = funcDecl->get_functionType();
1116                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
1117                std::list< DeclarationWithType * > &params = funcType->get_parameters();
1118
1119                if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
1120                        if ( params.size() == 0 ) {
1121                                SemanticError( funcDecl, "Constructors, destructors, and assignment functions require at least one parameter " );
1122                        }
1123                        ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
1124                        if ( ! refType ) {
1125                                SemanticError( funcDecl, "First parameter of a constructor, destructor, or assignment function must be a reference " );
1126                        }
1127                        if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
1128                                SemanticError( funcDecl, "Constructors and destructors cannot have explicit return values " );
1129                        }
1130                }
1131        }
1132
1133        template< typename Aggr >
1134        void validateGeneric( Aggr * inst ) {
1135                std::list< TypeDecl * > * params = inst->get_baseParameters();
1136                if ( params ) {
1137                        std::list< Expression * > & args = inst->get_parameters();
1138
1139                        // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
1140                        // A substitution is used to ensure that defaults are replaced correctly, e.g.,
1141                        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
1142                        //   vector(int) v;
1143                        // after insertion of default values becomes
1144                        //   vector(int, heap_allocator(T))
1145                        // and the substitution is built with T=int so that after substitution, the result is
1146                        //   vector(int, heap_allocator(int))
1147                        TypeSubstitution sub;
1148                        auto paramIter = params->begin();
1149                        for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) {
1150                                if ( i < args.size() ) {
1151                                        TypeExpr * expr = strict_dynamic_cast< TypeExpr * >( *std::next( args.begin(), i ) );
1152                                        sub.add( (*paramIter)->get_name(), expr->get_type()->clone() );
1153                                } else if ( i == args.size() ) {
1154                                        Type * defaultType = (*paramIter)->get_init();
1155                                        if ( defaultType ) {
1156                                                args.push_back( new TypeExpr( defaultType->clone() ) );
1157                                                sub.add( (*paramIter)->get_name(), defaultType->clone() );
1158                                        }
1159                                }
1160                        }
1161
1162                        sub.apply( inst );
1163                        if ( args.size() < params->size() ) SemanticError( inst, "Too few type arguments in generic type " );
1164                        if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
1165                }
1166        }
1167
1168        void ValidateGenericParameters::previsit( StructInstType * inst ) {
1169                validateGeneric( inst );
1170        }
1171
1172        void ValidateGenericParameters::previsit( UnionInstType * inst ) {
1173                validateGeneric( inst );
1174        }
1175
1176        void CompoundLiteral::premutate( ObjectDecl *objectDecl ) {
1177                storageClasses = objectDecl->get_storageClasses();
1178        }
1179
1180        Expression *CompoundLiteral::postmutate( CompoundLiteralExpr *compLitExpr ) {
1181                // transform [storage_class] ... (struct S){ 3, ... };
1182                // into [storage_class] struct S temp =  { 3, ... };
1183                static UniqueName indexName( "_compLit" );
1184
1185                ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
1186                compLitExpr->set_result( nullptr );
1187                compLitExpr->set_initializer( nullptr );
1188                delete compLitExpr;
1189                declsToAddBefore.push_back( tempvar );                                  // add modified temporary to current block
1190                return new VariableExpr( tempvar );
1191        }
1192
1193        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
1194                PassVisitor<ReturnTypeFixer> fixer;
1195                acceptAll( translationUnit, fixer );
1196        }
1197
1198        void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
1199                FunctionType * ftype = functionDecl->get_functionType();
1200                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1201                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
1202                if ( retVals.size() == 1 ) {
1203                        // 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).
1204                        // ensure other return values have a name.
1205                        DeclarationWithType * ret = retVals.front();
1206                        if ( ret->get_name() == "" ) {
1207                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1208                        }
1209                        ret->get_attributes().push_back( new Attribute( "unused" ) );
1210                }
1211        }
1212
1213        void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
1214                // xxx - need to handle named return values - this information needs to be saved somehow
1215                // so that resolution has access to the names.
1216                // Note that this pass needs to happen early so that other passes which look for tuple types
1217                // find them in all of the right places, including function return types.
1218                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1219                if ( retVals.size() > 1 ) {
1220                        // generate a single return parameter which is the tuple of all of the return values
1221                        TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
1222                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
1223                        ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
1224                        deleteAll( retVals );
1225                        retVals.clear();
1226                        retVals.push_back( newRet );
1227                }
1228        }
1229
1230        void FixObjectType::fix( std::list< Declaration * > & translationUnit ) {
1231                PassVisitor<FixObjectType> fixer;
1232                acceptAll( translationUnit, fixer );
1233        }
1234
1235        void FixObjectType::previsit( ObjectDecl * objDecl ) {
1236                Type *new_type = ResolvExpr::resolveTypeof( objDecl->get_type(), indexer );
1237                new_type->get_qualifiers() -= Type::Lvalue; // even if typeof is lvalue, variable can never have lvalue-qualified type
1238                objDecl->set_type( new_type );
1239        }
1240
1241        void FixObjectType::previsit( FunctionDecl * funcDecl ) {
1242                Type *new_type = ResolvExpr::resolveTypeof( funcDecl->type, indexer );
1243                new_type->get_qualifiers() -= Type::Lvalue; // even if typeof is lvalue, variable can never have lvalue-qualified type
1244                funcDecl->set_type( new_type );
1245        }
1246
1247        void FixObjectType::previsit( TypeDecl *typeDecl ) {
1248                if ( typeDecl->get_base() ) {
1249                        Type *new_type = ResolvExpr::resolveTypeof( typeDecl->get_base(), indexer );
1250                        new_type->get_qualifiers() -= Type::Lvalue; // even if typeof is lvalue, variable can never have lvalue-qualified type
1251                        typeDecl->set_base( new_type );
1252                } // if
1253        }
1254
1255        void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
1256                PassVisitor<ArrayLength> len;
1257                acceptAll( translationUnit, len );
1258        }
1259
1260        void ArrayLength::previsit( ObjectDecl * objDecl ) {
1261                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) {
1262                        if ( at->dimension ) return;
1263                        if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) {
1264                                at->dimension = new ConstantExpr( Constant::from_ulong( init->initializers.size() ) );
1265                        }
1266                }
1267        }
1268
1269        void ArrayLength::previsit( ArrayType * type ) {
1270                if ( type->dimension ) {
1271                        // need to resolve array dimensions early so that constructor code can correctly determine
1272                        // if a type is a VLA (and hence whether its elements need to be constructed)
1273                        ResolvExpr::findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
1274
1275                        // must re-evaluate whether a type is a VLA, now that more information is available
1276                        // (e.g. the dimension may have been an enumerator, which was unknown prior to this step)
1277                        type->isVarLen = ! InitTweak::isConstExpr( type->dimension );
1278                }
1279        }
1280
1281        struct LabelFinder {
1282                std::set< Label > & labels;
1283                LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1284                void previsit( Statement * stmt ) {
1285                        for ( Label & l : stmt->labels ) {
1286                                labels.insert( l );
1287                        }
1288                }
1289        };
1290
1291        void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1292                GuardValue( labels );
1293                PassVisitor<LabelFinder> finder( labels );
1294                funcDecl->accept( finder );
1295        }
1296
1297        Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1298                // convert &&label into label address
1299                if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1300                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1301                                if ( labels.count( nameExpr->name ) ) {
1302                                        Label name = nameExpr->name;
1303                                        delete addrExpr;
1304                                        return new LabelAddressExpr( name );
1305                                }
1306                        }
1307                }
1308                return addrExpr;
1309        }
1310} // namespace SymTab
1311
1312// Local Variables: //
1313// tab-width: 4 //
1314// mode: c++ //
1315// compile-command: "make install" //
1316// End: //
Note: See TracBrowser for help on using the repository browser.