source: src/SymTab/Validate.cc @ c0b23644

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since c0b23644 was 5c4d27f, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Add error check for unimplemented expression parameters for trait types [fixes #60]

  • Property mode set to 100644
File size: 41.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 "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
51#include "Common/ScopedMap.h"          // for ScopedMap
52#include "Common/SemanticError.h"      // for SemanticError
53#include "Common/UniqueName.h"         // for UniqueName
54#include "Common/utility.h"            // for operator+, cloneAll, deleteAll
55#include "Concurrency/Keywords.h"      // for applyKeywords
56#include "FixFunction.h"               // for FixFunction
57#include "Indexer.h"                   // for Indexer
58#include "InitTweak/GenInit.h"         // for fixReturnStatements
59#include "InitTweak/InitTweak.h"       // for isCtorDtorAssign
60#include "Parser/LinkageSpec.h"        // for C
61#include "ResolvExpr/typeops.h"        // for typesCompatible
62#include "SymTab/AddVisit.h"           // for addVisit
63#include "SymTab/Autogen.h"            // for SizeType
64#include "SynTree/Attribute.h"         // for noAttributes, Attribute
65#include "SynTree/Constant.h"          // for Constant
66#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
67#include "SynTree/Expression.h"        // for CompoundLiteralExpr, Expressio...
68#include "SynTree/Initializer.h"       // for ListInit, Initializer
69#include "SynTree/Label.h"             // for operator==, Label
70#include "SynTree/Mutator.h"           // for Mutator
71#include "SynTree/Type.h"              // for Type, TypeInstType, EnumInstType
72#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
73#include "SynTree/Visitor.h"           // for Visitor
74
75class CompoundStmt;
76class ReturnStmt;
77class SwitchStmt;
78
79
80#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
81
82namespace SymTab {
83        class HoistStruct final : public Visitor {
84                template< typename Visitor >
85                friend void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor );
86            template< typename Visitor >
87            friend void addVisitStatementList( std::list< Statement* > &stmts, Visitor &visitor );
88          public:
89                /// Flattens nested struct types
90                static void hoistStruct( std::list< Declaration * > &translationUnit );
91
92                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
93
94                virtual void visit( EnumInstType *enumInstType );
95                virtual void visit( StructInstType *structInstType );
96                virtual void visit( UnionInstType *unionInstType );
97                virtual void visit( StructDecl *aggregateDecl );
98                virtual void visit( UnionDecl *aggregateDecl );
99
100                virtual void visit( CompoundStmt *compoundStmt );
101                virtual void visit( SwitchStmt *switchStmt );
102          private:
103                HoistStruct();
104
105                template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
106
107                std::list< Declaration * > declsToAdd, declsToAddAfter;
108                bool inStruct;
109        };
110
111        /// Fix return types so that every function returns exactly one value
112        struct ReturnTypeFixer {
113                static void fix( std::list< Declaration * > &translationUnit );
114
115                void postvisit( FunctionDecl * functionDecl );
116                void postvisit( FunctionType * ftype );
117        };
118
119        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
120        struct EnumAndPointerDecay {
121                void previsit( EnumDecl *aggregateDecl );
122                void previsit( FunctionType *func );
123        };
124
125        /// Associates forward declarations of aggregates with their definitions
126        struct LinkReferenceToTypes final : public WithIndexer {
127                LinkReferenceToTypes( const Indexer *indexer );
128                void postvisit( TypeInstType *typeInst );
129
130                void postvisit( EnumInstType *enumInst );
131                void postvisit( StructInstType *structInst );
132                void postvisit( UnionInstType *unionInst );
133                void postvisit( TraitInstType *traitInst );
134
135                void postvisit( EnumDecl *enumDecl );
136                void postvisit( StructDecl *structDecl );
137                void postvisit( UnionDecl *unionDecl );
138                void postvisit( TraitDecl * traitDecl );
139
140          private:
141                const Indexer *local_indexer;
142
143                typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
144                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
145                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
146                ForwardEnumsType forwardEnums;
147                ForwardStructsType forwardStructs;
148                ForwardUnionsType forwardUnions;
149        };
150
151        /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
152        struct ForallPointerDecay final {
153                void previsit( ObjectDecl * object );
154                void previsit( FunctionDecl * func );
155                void previsit( StructDecl * aggrDecl );
156                void previsit( UnionDecl * aggrDecl );
157        };
158
159        struct ReturnChecker : public WithGuards {
160                /// Checks that return statements return nothing if their return type is void
161                /// and return something if the return type is non-void.
162                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
163
164                void previsit( FunctionDecl * functionDecl );
165                void previsit( ReturnStmt * returnStmt );
166
167                typedef std::list< DeclarationWithType * > ReturnVals;
168                ReturnVals returnVals;
169        };
170
171        struct EliminateTypedef final : public WithVisitorRef<EliminateTypedef>, public WithGuards {
172                EliminateTypedef() : scopeLevel( 0 ) {}
173                /// Replaces typedefs by forward declarations
174                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
175
176                Type * postmutate( TypeInstType * aggregateUseType );
177                Declaration * postmutate( TypedefDecl * typeDecl );
178                void premutate( TypeDecl * typeDecl );
179                void premutate( FunctionDecl * funcDecl );
180                void premutate( ObjectDecl * objDecl );
181                DeclarationWithType * postmutate( ObjectDecl * objDecl );
182
183                void premutate( CastExpr * castExpr );
184
185                void premutate( CompoundStmt * compoundStmt );
186                CompoundStmt * postmutate( CompoundStmt * compoundStmt );
187
188                void premutate( StructDecl * structDecl );
189                Declaration * postmutate( StructDecl * structDecl );
190                void premutate( UnionDecl * unionDecl );
191                Declaration * postmutate( UnionDecl * unionDecl );
192                void premutate( EnumDecl * enumDecl );
193                Declaration * postmutate( EnumDecl * enumDecl );
194                Declaration * postmutate( TraitDecl * contextDecl );
195
196          private:
197                template<typename AggDecl>
198                AggDecl *handleAggregate( AggDecl * aggDecl );
199
200                template<typename AggDecl>
201                void addImplicitTypedef( AggDecl * aggDecl );
202
203                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
204                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
205                typedef std::map< std::string, TypeDecl * > TypeDeclMap;
206                TypedefMap typedefNames;
207                TypeDeclMap typedeclNames;
208                int scopeLevel;
209        };
210
211        struct VerifyCtorDtorAssign {
212                /// ensure that constructors, destructors, and assignment have at least one
213                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
214                /// return values.
215                static void verify( std::list< Declaration * > &translationUnit );
216
217                void previsit( FunctionDecl *funcDecl );
218        };
219
220        /// ensure that generic types have the correct number of type arguments
221        struct ValidateGenericParameters {
222                void previsit( StructInstType * inst );
223                void previsit( UnionInstType * inst );
224        };
225
226        struct ArrayLength {
227                /// for array types without an explicit length, compute the length and store it so that it
228                /// is known to the rest of the phases. For example,
229                ///   int x[] = { 1, 2, 3 };
230                ///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
231                /// here x and y are known at compile-time to have length 3, so change this into
232                ///   int x[3] = { 1, 2, 3 };
233                ///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
234                static void computeLength( std::list< Declaration * > & translationUnit );
235
236                void previsit( ObjectDecl * objDecl );
237        };
238
239        struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
240                Type::StorageClasses storageClasses;
241
242                void premutate( ObjectDecl *objectDecl );
243                Expression * postmutate( CompoundLiteralExpr *compLitExpr );
244        };
245
246        struct LabelAddressFixer final : public WithGuards {
247                std::set< Label > labels;
248
249                void premutate( FunctionDecl * funcDecl );
250                Expression * postmutate( AddressExpr * addrExpr );
251        };
252
253        FunctionDecl * dereferenceOperator = nullptr;
254        struct FindSpecialDeclarations final {
255                void previsit( FunctionDecl * funcDecl );
256        };
257
258        void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
259                PassVisitor<EnumAndPointerDecay> epc;
260                PassVisitor<LinkReferenceToTypes> lrt( nullptr );
261                PassVisitor<ForallPointerDecay> fpd;
262                PassVisitor<CompoundLiteral> compoundliteral;
263                PassVisitor<ValidateGenericParameters> genericParams;
264                PassVisitor<FindSpecialDeclarations> finder;
265                PassVisitor<LabelAddressFixer> labelAddrFixer;
266
267                EliminateTypedef::eliminateTypedef( translationUnit );
268                HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order
269                ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
270                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
271                acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
272                acceptAll( translationUnit, genericParams );  // check as early as possible - can't happen before LinkReferenceToTypes
273                VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
274                ReturnChecker::checkFunctionReturns( translationUnit );
275                InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
276                Concurrency::applyKeywords( translationUnit );
277                acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
278                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay
279                Concurrency::implementMutexFuncs( translationUnit );
280                Concurrency::implementThreadStarter( translationUnit );
281                mutateAll( translationUnit, compoundliteral );
282                ArrayLength::computeLength( translationUnit );
283                acceptAll( translationUnit, finder ); // xxx - remove this pass soon
284                mutateAll( translationUnit, labelAddrFixer );
285        }
286
287        void validateType( Type *type, const Indexer *indexer ) {
288                PassVisitor<EnumAndPointerDecay> epc;
289                PassVisitor<LinkReferenceToTypes> lrt( indexer );
290                PassVisitor<ForallPointerDecay> fpd;
291                type->accept( epc );
292                type->accept( lrt );
293                type->accept( fpd );
294        }
295
296        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
297                HoistStruct hoister;
298                acceptAndAdd( translationUnit, hoister );
299        }
300
301        HoistStruct::HoistStruct() : inStruct( false ) {
302        }
303
304        bool isStructOrUnion( Declaration *decl ) {
305                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
306        }
307
308        template< typename AggDecl >
309        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
310                if ( inStruct ) {
311                        // Add elements in stack order corresponding to nesting structure.
312                        declsToAdd.push_front( aggregateDecl );
313                        Visitor::visit( aggregateDecl );
314                } else {
315                        inStruct = true;
316                        Visitor::visit( aggregateDecl );
317                        inStruct = false;
318                } // if
319                // Always remove the hoisted aggregate from the inner structure.
320                filter( aggregateDecl->get_members(), isStructOrUnion, false );
321        }
322
323        void HoistStruct::visit( EnumInstType *structInstType ) {
324                if ( structInstType->get_baseEnum() ) {
325                        declsToAdd.push_front( structInstType->get_baseEnum() );
326                }
327        }
328
329        void HoistStruct::visit( StructInstType *structInstType ) {
330                if ( structInstType->get_baseStruct() ) {
331                        declsToAdd.push_front( structInstType->get_baseStruct() );
332                }
333        }
334
335        void HoistStruct::visit( UnionInstType *structInstType ) {
336                if ( structInstType->get_baseUnion() ) {
337                        declsToAdd.push_front( structInstType->get_baseUnion() );
338                }
339        }
340
341        void HoistStruct::visit( StructDecl *aggregateDecl ) {
342                handleAggregate( aggregateDecl );
343        }
344
345        void HoistStruct::visit( UnionDecl *aggregateDecl ) {
346                handleAggregate( aggregateDecl );
347        }
348
349        void HoistStruct::visit( CompoundStmt *compoundStmt ) {
350                addVisit( compoundStmt, *this );
351        }
352
353        void HoistStruct::visit( SwitchStmt *switchStmt ) {
354                addVisit( switchStmt, *this );
355        }
356
357        void EnumAndPointerDecay::previsit( EnumDecl *enumDecl ) {
358                // Set the type of each member of the enumeration to be EnumConstant
359                for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
360                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
361                        assert( obj );
362                        obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->get_name() ) );
363                } // for
364        }
365
366        namespace {
367                template< typename DWTList >
368                void fixFunctionList( DWTList & dwts, FunctionType * func ) {
369                        // the only case in which "void" is valid is where it is the only one in the list; then it should be removed
370                        // entirely. other fix ups are handled by the FixFunction class
371                        typedef typename DWTList::iterator DWTIterator;
372                        DWTIterator begin( dwts.begin() ), end( dwts.end() );
373                        if ( begin == end ) return;
374                        PassVisitor<FixFunction> fixer;
375                        DWTIterator i = begin;
376                        *i = (*i)->acceptMutator( fixer );
377                        if ( fixer.pass.isVoid ) {
378                                DWTIterator j = i;
379                                ++i;
380                                delete *j;
381                                dwts.erase( j );
382                                if ( i != end ) {
383                                        throw SemanticError( "invalid type void in function type ", func );
384                                } // if
385                        } else {
386                                ++i;
387                                for ( ; i != end; ++i ) {
388                                        PassVisitor<FixFunction> fixer;
389                                        *i = (*i)->acceptMutator( fixer );
390                                        if ( fixer.pass.isVoid ) {
391                                                throw SemanticError( "invalid type void in function type ", func );
392                                        } // if
393                                } // for
394                        } // if
395                }
396        }
397
398        void EnumAndPointerDecay::previsit( FunctionType *func ) {
399                // Fix up parameters and return types
400                fixFunctionList( func->get_parameters(), func );
401                fixFunctionList( func->get_returnVals(), func );
402        }
403
404        LinkReferenceToTypes::LinkReferenceToTypes( const Indexer *other_indexer ) {
405                if ( other_indexer ) {
406                        local_indexer = other_indexer;
407                } else {
408                        local_indexer = &indexer;
409                } // if
410        }
411
412        void LinkReferenceToTypes::postvisit( EnumInstType *enumInst ) {
413                EnumDecl *st = local_indexer->lookupEnum( enumInst->get_name() );
414                // it's not a semantic error if the enum is not found, just an implicit forward declaration
415                if ( st ) {
416                        //assert( ! enumInst->get_baseEnum() || enumInst->get_baseEnum()->get_members().empty() || ! st->get_members().empty() );
417                        enumInst->set_baseEnum( st );
418                } // if
419                if ( ! st || st->get_members().empty() ) {
420                        // use of forward declaration
421                        forwardEnums[ enumInst->get_name() ].push_back( enumInst );
422                } // if
423        }
424
425        void checkGenericParameters( ReferenceToType * inst ) {
426                for ( Expression * param : inst->parameters ) {
427                        if ( ! dynamic_cast< TypeExpr * >( param ) ) {
428                                throw SemanticError( "Expression parameters for generic types are currently unsupported: ", inst );
429                        }
430                }
431        }
432
433        void LinkReferenceToTypes::postvisit( StructInstType *structInst ) {
434                StructDecl *st = local_indexer->lookupStruct( structInst->get_name() );
435                // it's not a semantic error if the struct is not found, just an implicit forward declaration
436                if ( st ) {
437                        //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
438                        structInst->set_baseStruct( st );
439                } // if
440                if ( ! st || st->get_members().empty() ) {
441                        // use of forward declaration
442                        forwardStructs[ structInst->get_name() ].push_back( structInst );
443                } // if
444                checkGenericParameters( structInst );
445        }
446
447        void LinkReferenceToTypes::postvisit( UnionInstType *unionInst ) {
448                UnionDecl *un = local_indexer->lookupUnion( unionInst->get_name() );
449                // it's not a semantic error if the union is not found, just an implicit forward declaration
450                if ( un ) {
451                        unionInst->set_baseUnion( un );
452                } // if
453                if ( ! un || un->get_members().empty() ) {
454                        // use of forward declaration
455                        forwardUnions[ unionInst->get_name() ].push_back( unionInst );
456                } // if
457                checkGenericParameters( unionInst );
458        }
459
460        template< typename Decl >
461        void normalizeAssertions( std::list< Decl * > & assertions ) {
462                // ensure no duplicate trait members after the clone
463                auto pred = [](Decl * d1, Decl * d2) {
464                        // only care if they're equal
465                        DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
466                        DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
467                        if ( dwt1 && dwt2 ) {
468                                if ( dwt1->get_name() == dwt2->get_name() && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
469                                        // std::cerr << "=========== equal:" << std::endl;
470                                        // std::cerr << "d1: " << d1 << std::endl;
471                                        // std::cerr << "d2: " << d2 << std::endl;
472                                        return false;
473                                }
474                        }
475                        return d1 < d2;
476                };
477                std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
478                // if ( unique_members.size() != assertions.size() ) {
479                //      std::cerr << "============different" << std::endl;
480                //      std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
481                // }
482
483                std::list< Decl * > order;
484                order.splice( order.end(), assertions );
485                std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
486                        return unique_members.count( decl );
487                });
488        }
489
490        // expand assertions from trait instance, performing the appropriate type variable substitutions
491        template< typename Iterator >
492        void expandAssertions( TraitInstType * inst, Iterator out ) {
493                assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toString( inst ).c_str() );
494                std::list< DeclarationWithType * > asserts;
495                for ( Declaration * decl : inst->baseTrait->members ) {
496                        asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
497                }
498                // substitute trait decl parameters for instance parameters
499                applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
500        }
501
502        void LinkReferenceToTypes::postvisit( TraitDecl * traitDecl ) {
503                if ( traitDecl->name == "sized" ) {
504                        // "sized" is a special trait - flick the sized status on for the type variable
505                        assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
506                        TypeDecl * td = traitDecl->parameters.front();
507                        td->set_sized( true );
508                }
509
510                // move assertions from type parameters into the body of the trait
511                for ( TypeDecl * td : traitDecl->parameters ) {
512                        for ( DeclarationWithType * assert : td->assertions ) {
513                                if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
514                                        expandAssertions( inst, back_inserter( traitDecl->members ) );
515                                } else {
516                                        traitDecl->members.push_back( assert->clone() );
517                                }
518                        }
519                        deleteAll( td->assertions );
520                        td->assertions.clear();
521                } // for
522        }
523
524        void LinkReferenceToTypes::postvisit( TraitInstType * traitInst ) {
525                // handle other traits
526                TraitDecl *traitDecl = local_indexer->lookupTrait( traitInst->name );
527                if ( ! traitDecl ) {
528                        throw SemanticError( "use of undeclared trait " + traitInst->name );
529                } // if
530                if ( traitDecl->get_parameters().size() != traitInst->get_parameters().size() ) {
531                        throw SemanticError( "incorrect number of trait parameters: ", traitInst );
532                } // if
533                traitInst->baseTrait = traitDecl;
534
535                // need to carry over the 'sized' status of each decl in the instance
536                for ( auto p : group_iterate( traitDecl->get_parameters(), traitInst->get_parameters() ) ) {
537                        TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
538                        if ( ! expr ) {
539                                throw SemanticError( "Expression parameters for trait instances are currently unsupported: ", std::get<1>(p) );
540                        }
541                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
542                                TypeDecl * formalDecl = std::get<0>(p);
543                                TypeDecl * instDecl = inst->get_baseType();
544                                if ( formalDecl->get_sized() ) instDecl->set_sized( true );
545                        }
546                }
547                // normalizeAssertions( traitInst->members );
548        }
549
550        void LinkReferenceToTypes::postvisit( EnumDecl *enumDecl ) {
551                // visit enum members first so that the types of self-referencing members are updated properly
552                if ( ! enumDecl->get_members().empty() ) {
553                        ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->get_name() );
554                        if ( fwds != forwardEnums.end() ) {
555                                for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
556                                        (*inst )->set_baseEnum( enumDecl );
557                                } // for
558                                forwardEnums.erase( fwds );
559                        } // if
560                } // if
561        }
562
563        void LinkReferenceToTypes::postvisit( StructDecl *structDecl ) {
564                // visit struct members first so that the types of self-referencing members are updated properly
565                // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
566                if ( ! structDecl->get_members().empty() ) {
567                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
568                        if ( fwds != forwardStructs.end() ) {
569                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
570                                        (*inst )->set_baseStruct( structDecl );
571                                } // for
572                                forwardStructs.erase( fwds );
573                        } // if
574                } // if
575        }
576
577        void LinkReferenceToTypes::postvisit( UnionDecl *unionDecl ) {
578                if ( ! unionDecl->get_members().empty() ) {
579                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
580                        if ( fwds != forwardUnions.end() ) {
581                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
582                                        (*inst )->set_baseUnion( unionDecl );
583                                } // for
584                                forwardUnions.erase( fwds );
585                        } // if
586                } // if
587        }
588
589        void LinkReferenceToTypes::postvisit( TypeInstType *typeInst ) {
590                if ( NamedTypeDecl *namedTypeDecl = local_indexer->lookupType( typeInst->get_name() ) ) {
591                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
592                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
593                        } // if
594                } // if
595        }
596
597        /// Fix up assertions - flattens assertion lists, removing all trait instances
598        void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
599                for ( TypeDecl * type : forall ) {
600                        std::list< DeclarationWithType * > asserts;
601                        asserts.splice( asserts.end(), type->assertions );
602                        // expand trait instances into their members
603                        for ( DeclarationWithType * assertion : asserts ) {
604                                if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
605                                        // expand trait instance into all of its members
606                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
607                                        delete traitInst;
608                                } else {
609                                        // pass other assertions through
610                                        type->assertions.push_back( assertion );
611                                } // if
612                        } // for
613                        // apply FixFunction to every assertion to check for invalid void type
614                        for ( DeclarationWithType *& assertion : type->assertions ) {
615                                PassVisitor<FixFunction> fixer;
616                                assertion = assertion->acceptMutator( fixer );
617                                if ( fixer.pass.isVoid ) {
618                                        throw SemanticError( "invalid type void in assertion of function ", node );
619                                } // if
620                        } // for
621                        // normalizeAssertions( type->assertions );
622                } // for
623        }
624
625        void ForallPointerDecay::previsit( ObjectDecl *object ) {
626                forallFixer( object->type->forall, object );
627                if ( PointerType *pointer = dynamic_cast< PointerType * >( object->type ) ) {
628                        forallFixer( pointer->base->forall, object );
629                } // if
630                object->fixUniqueId();
631        }
632
633        void ForallPointerDecay::previsit( FunctionDecl *func ) {
634                forallFixer( func->type->forall, func );
635                func->fixUniqueId();
636        }
637
638        void ForallPointerDecay::previsit( StructDecl * aggrDecl ) {
639                forallFixer( aggrDecl->parameters, aggrDecl );
640        }
641
642        void ForallPointerDecay::previsit( UnionDecl * aggrDecl ) {
643                forallFixer( aggrDecl->parameters, aggrDecl );
644        }
645
646        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
647                PassVisitor<ReturnChecker> checker;
648                acceptAll( translationUnit, checker );
649        }
650
651        void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
652                GuardValue( returnVals );
653                returnVals = functionDecl->get_functionType()->get_returnVals();
654        }
655
656        void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
657                // Previously this also checked for the existence of an expr paired with no return values on
658                // the  function return type. This is incorrect, since you can have an expression attached to
659                // a return statement in a void-returning function in C. The expression is treated as if it
660                // were cast to void.
661                if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
662                        throw SemanticError( "Non-void function returns no values: " , returnStmt );
663                }
664        }
665
666
667        bool isTypedef( Declaration *decl ) {
668                return dynamic_cast< TypedefDecl * >( decl );
669        }
670
671        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
672                PassVisitor<EliminateTypedef> eliminator;
673                mutateAll( translationUnit, eliminator );
674                if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
675                        // grab and remember declaration of size_t
676                        SizeType = eliminator.pass.typedefNames["size_t"].first->get_base()->clone();
677                } else {
678                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
679                        // eventually should have a warning for this case.
680                        SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
681                }
682                filter( translationUnit, isTypedef, true );
683        }
684
685        Type * EliminateTypedef::postmutate( TypeInstType * typeInst ) {
686                // instances of typedef types will come here. If it is an instance
687                // of a typdef type, link the instance to its actual type.
688                TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
689                if ( def != typedefNames.end() ) {
690                        Type *ret = def->second.first->base->clone();
691                        ret->get_qualifiers() |= typeInst->get_qualifiers();
692                        // place instance parameters on the typedef'd type
693                        if ( ! typeInst->parameters.empty() ) {
694                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
695                                if ( ! rtt ) {
696                                        throw SemanticError("Cannot apply type parameters to base type of " + typeInst->name);
697                                }
698                                rtt->get_parameters().clear();
699                                cloneAll( typeInst->parameters, rtt->parameters );
700                                mutateAll( rtt->parameters, *visitor );  // recursively fix typedefs on parameters
701                        } // if
702                        delete typeInst;
703                        return ret;
704                } else {
705                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->get_name() );
706                        assertf( base != typedeclNames.end(), "Cannot find typedecl name %s", typeInst->name.c_str() );
707                        typeInst->set_baseType( base->second );
708                } // if
709                return typeInst;
710        }
711
712        struct VarLenChecker : WithShortCircuiting {
713                void previsit( FunctionType * ) { visit_children = false; }
714                void previsit( ArrayType * at ) {
715                        isVarLen |= at->isVarLen;
716                }
717                bool isVarLen = false;
718        };
719
720        bool isVariableLength( Type * t ) {
721                PassVisitor<VarLenChecker> varLenChecker;
722                maybeAccept( t, varLenChecker );
723                return varLenChecker.pass.isVarLen;
724        }
725
726        Declaration *EliminateTypedef::postmutate( TypedefDecl * tyDecl ) {
727                if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
728                        // typedef to the same name from the same scope
729                        // must be from the same type
730
731                        Type * t1 = tyDecl->get_base();
732                        Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
733                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
734                                throw SemanticError( "Cannot redefine typedef: " + tyDecl->name );
735                        }
736                        // cannot redefine VLA typedefs
737                        if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
738                                throw SemanticError( "Cannot redefine typedef: " + tyDecl->name );
739                        }
740                } else {
741                        typedefNames[ tyDecl->get_name() ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
742                } // if
743
744                // When a typedef is a forward declaration:
745                //    typedef struct screen SCREEN;
746                // the declaration portion must be retained:
747                //    struct screen;
748                // because the expansion of the typedef is:
749                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
750                // hence the type-name "screen" must be defined.
751                // Note, qualifiers on the typedef are superfluous for the forward declaration.
752
753                Type *designatorType = tyDecl->get_base()->stripDeclarator();
754                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
755                        return new StructDecl( aggDecl->get_name(), DeclarationNode::Struct, noAttributes, tyDecl->get_linkage() );
756                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
757                        return new UnionDecl( aggDecl->get_name(), noAttributes, tyDecl->get_linkage() );
758                } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
759                        return new EnumDecl( enumDecl->get_name(), noAttributes, tyDecl->get_linkage() );
760                } else {
761                        return tyDecl->clone();
762                } // if
763        }
764
765        void EliminateTypedef::premutate( TypeDecl * typeDecl ) {
766                TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
767                if ( i != typedefNames.end() ) {
768                        typedefNames.erase( i ) ;
769                } // if
770
771                typedeclNames[ typeDecl->get_name() ] = typeDecl;
772        }
773
774        void EliminateTypedef::premutate( FunctionDecl * ) {
775                GuardScope( typedefNames );
776        }
777
778        void EliminateTypedef::premutate( ObjectDecl * ) {
779                GuardScope( typedefNames );
780        }
781
782        DeclarationWithType *EliminateTypedef::postmutate( ObjectDecl * objDecl ) {
783                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( objDecl->get_type() ) ) { // function type?
784                        // replace the current object declaration with a function declaration
785                        FunctionDecl * newDecl = new FunctionDecl( objDecl->get_name(), objDecl->get_storageClasses(), objDecl->get_linkage(), funtype, 0, objDecl->get_attributes(), objDecl->get_funcSpec() );
786                        objDecl->get_attributes().clear();
787                        objDecl->set_type( nullptr );
788                        delete objDecl;
789                        return newDecl;
790                } // if
791                return objDecl;
792        }
793
794        void EliminateTypedef::premutate( CastExpr * ) {
795                GuardScope( typedefNames );
796        }
797
798        void EliminateTypedef::premutate( CompoundStmt * ) {
799                GuardScope( typedefNames );
800                scopeLevel += 1;
801                GuardAction( [this](){ scopeLevel -= 1; } );
802        }
803
804        CompoundStmt *EliminateTypedef::postmutate( CompoundStmt * compoundStmt ) {
805                // remove and delete decl stmts
806                filter( compoundStmt->kids, [](Statement * stmt) {
807                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
808                                if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
809                                        return true;
810                                } // if
811                        } // if
812                        return false;
813                }, true);
814                return compoundStmt;
815        }
816
817        // there may be typedefs nested within aggregates. in order for everything to work properly, these should be removed
818        // as well
819        template<typename AggDecl>
820        AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
821                filter( aggDecl->members, isTypedef, true );
822                return aggDecl;
823        }
824
825        template<typename AggDecl>
826        void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
827                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
828                        Type *type = nullptr;
829                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
830                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
831                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
832                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
833                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
834                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
835                        } // if
836                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), Type::StorageClasses(), type, aggDecl->get_linkage() ) );
837                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
838                } // if
839        }
840
841        void EliminateTypedef::premutate( StructDecl * structDecl ) {
842                addImplicitTypedef( structDecl );
843        }
844
845
846        Declaration *EliminateTypedef::postmutate( StructDecl * structDecl ) {
847                return handleAggregate( structDecl );
848        }
849
850        void EliminateTypedef::premutate( UnionDecl * unionDecl ) {
851                addImplicitTypedef( unionDecl );
852        }
853
854        Declaration *EliminateTypedef::postmutate( UnionDecl * unionDecl ) {
855                return handleAggregate( unionDecl );
856        }
857
858        void EliminateTypedef::premutate( EnumDecl * enumDecl ) {
859                addImplicitTypedef( enumDecl );
860        }
861
862        Declaration *EliminateTypedef::postmutate( EnumDecl * enumDecl ) {
863                return handleAggregate( enumDecl );
864        }
865
866        Declaration *EliminateTypedef::postmutate( TraitDecl * traitDecl ) {
867                return handleAggregate( traitDecl );
868        }
869
870        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
871                PassVisitor<VerifyCtorDtorAssign> verifier;
872                acceptAll( translationUnit, verifier );
873        }
874
875        void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
876                FunctionType * funcType = funcDecl->get_functionType();
877                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
878                std::list< DeclarationWithType * > &params = funcType->get_parameters();
879
880                if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
881                        if ( params.size() == 0 ) {
882                                throw SemanticError( "Constructors, destructors, and assignment functions require at least one parameter ", funcDecl );
883                        }
884                        ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
885                        if ( ! refType ) {
886                                throw SemanticError( "First parameter of a constructor, destructor, or assignment function must be a reference ", funcDecl );
887                        }
888                        if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
889                                throw SemanticError( "Constructors and destructors cannot have explicit return values ", funcDecl );
890                        }
891                }
892        }
893
894        template< typename Aggr >
895        void validateGeneric( Aggr * inst ) {
896                std::list< TypeDecl * > * params = inst->get_baseParameters();
897                if ( params ) {
898                        std::list< Expression * > & args = inst->get_parameters();
899
900                        // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
901                        // A substitution is used to ensure that defaults are replaced correctly, e.g.,
902                        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
903                        //   vector(int) v;
904                        // after insertion of default values becomes
905                        //   vector(int, heap_allocator(T))
906                        // and the substitution is built with T=int so that after substitution, the result is
907                        //   vector(int, heap_allocator(int))
908                        TypeSubstitution sub;
909                        auto paramIter = params->begin();
910                        for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) {
911                                if ( i < args.size() ) {
912                                        TypeExpr * expr = strict_dynamic_cast< TypeExpr * >( *std::next( args.begin(), i ) );
913                                        sub.add( (*paramIter)->get_name(), expr->get_type()->clone() );
914                                } else if ( i == args.size() ) {
915                                        Type * defaultType = (*paramIter)->get_init();
916                                        if ( defaultType ) {
917                                                args.push_back( new TypeExpr( defaultType->clone() ) );
918                                                sub.add( (*paramIter)->get_name(), defaultType->clone() );
919                                        }
920                                }
921                        }
922
923                        sub.apply( inst );
924                        if ( args.size() < params->size() ) throw SemanticError( "Too few type arguments in generic type ", inst );
925                        if ( args.size() > params->size() ) throw SemanticError( "Too many type arguments in generic type ", inst );
926                }
927        }
928
929        void ValidateGenericParameters::previsit( StructInstType * inst ) {
930                validateGeneric( inst );
931        }
932
933        void ValidateGenericParameters::previsit( UnionInstType * inst ) {
934                validateGeneric( inst );
935        }
936
937        void CompoundLiteral::premutate( ObjectDecl *objectDecl ) {
938                storageClasses = objectDecl->get_storageClasses();
939        }
940
941        Expression *CompoundLiteral::postmutate( CompoundLiteralExpr *compLitExpr ) {
942                // transform [storage_class] ... (struct S){ 3, ... };
943                // into [storage_class] struct S temp =  { 3, ... };
944                static UniqueName indexName( "_compLit" );
945
946                ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
947                compLitExpr->set_result( nullptr );
948                compLitExpr->set_initializer( nullptr );
949                delete compLitExpr;
950                declsToAddBefore.push_back( tempvar );                                  // add modified temporary to current block
951                return new VariableExpr( tempvar );
952        }
953
954        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
955                PassVisitor<ReturnTypeFixer> fixer;
956                acceptAll( translationUnit, fixer );
957        }
958
959        void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
960                FunctionType * ftype = functionDecl->get_functionType();
961                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
962                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
963                if ( retVals.size() == 1 ) {
964                        // 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).
965                        // ensure other return values have a name.
966                        DeclarationWithType * ret = retVals.front();
967                        if ( ret->get_name() == "" ) {
968                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
969                        }
970                        ret->get_attributes().push_back( new Attribute( "unused" ) );
971                }
972        }
973
974        void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
975                // xxx - need to handle named return values - this information needs to be saved somehow
976                // so that resolution has access to the names.
977                // Note that this pass needs to happen early so that other passes which look for tuple types
978                // find them in all of the right places, including function return types.
979                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
980                if ( retVals.size() > 1 ) {
981                        // generate a single return parameter which is the tuple of all of the return values
982                        TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
983                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
984                        ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
985                        deleteAll( retVals );
986                        retVals.clear();
987                        retVals.push_back( newRet );
988                }
989        }
990
991        void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
992                PassVisitor<ArrayLength> len;
993                acceptAll( translationUnit, len );
994        }
995
996        void ArrayLength::previsit( ObjectDecl * objDecl ) {
997                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->get_type() ) ) {
998                        if ( at->get_dimension() ) return;
999                        if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->get_init() ) ) {
1000                                at->set_dimension( new ConstantExpr( Constant::from_ulong( init->get_initializers().size() ) ) );
1001                        }
1002                }
1003        }
1004
1005        struct LabelFinder {
1006                std::set< Label > & labels;
1007                LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1008                void previsit( Statement * stmt ) {
1009                        for ( Label & l : stmt->labels ) {
1010                                labels.insert( l );
1011                        }
1012                }
1013        };
1014
1015        void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1016                GuardValue( labels );
1017                PassVisitor<LabelFinder> finder( labels );
1018                funcDecl->accept( finder );
1019        }
1020
1021        Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1022                // convert &&label into label address
1023                if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1024                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1025                                if ( labels.count( nameExpr->name ) ) {
1026                                        Label name = nameExpr->name;
1027                                        delete addrExpr;
1028                                        return new LabelAddressExpr( name );
1029                                }
1030                        }
1031                }
1032                return addrExpr;
1033        }
1034
1035        void FindSpecialDeclarations::previsit( FunctionDecl * funcDecl ) {
1036                if ( ! dereferenceOperator ) {
1037                        if ( funcDecl->get_name() == "*?" && funcDecl->get_linkage() == LinkageSpec::Intrinsic ) {
1038                                FunctionType * ftype = funcDecl->get_functionType();
1039                                if ( ftype->get_parameters().size() == 1 && ftype->get_parameters().front()->get_type()->get_qualifiers() == Type::Qualifiers() ) {
1040                                        dereferenceOperator = funcDecl;
1041                                }
1042                        }
1043                }
1044        }
1045} // namespace SymTab
1046
1047// Local Variables: //
1048// tab-width: 4 //
1049// mode: c++ //
1050// compile-command: "make install" //
1051// End: //
Note: See TracBrowser for help on using the repository browser.