source: src/SymTab/Validate.cc @ e15ba975

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resnenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since e15ba975 was 7e08acf, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Apply generic substitution to qualified typedefs

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