source: src/SymTab/Validate.cc @ 940bba3

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 940bba3 was e491159, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Moved ScopedMap? to Common folder

  • Property mode set to 100644
File size: 26.8 KB
RevLine 
[0dd3a2f]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//
[9cb8e88d]7// Validate.cc --
[0dd3a2f]8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:50:04 2015
[4e06c1e]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Tue Jul 12 17:49:21 2016
13// Update Count     : 298
[0dd3a2f]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; neither do tuple types.  A function
26//   taking no arguments has no argument types, and tuples are flattened.
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.
[51b7345]39
40#include <list>
41#include <iterator>
[e491159]42#include "Common/ScopedMap.h"
[630a82a]43#include "Common/utility.h"
44#include "Common/UniqueName.h"
[51b7345]45#include "Validate.h"
46#include "SynTree/Visitor.h"
47#include "SynTree/Mutator.h"
48#include "SynTree/Type.h"
[630a82a]49#include "SynTree/Expression.h"
[51b7345]50#include "SynTree/Statement.h"
51#include "SynTree/TypeSubstitution.h"
[68cd1ce]52#include "Indexer.h"
[51b7345]53#include "FixFunction.h"
[cc79d97]54// #include "ImplementationType.h"
[630a82a]55#include "GenPoly/DeclMutator.h"
[51b7345]56#include "AddVisit.h"
[f6d7e0f]57#include "MakeLibCfa.h"
[cc79d97]58#include "TypeEquality.h"
[620cb95]59#include "Autogen.h"
[1cbca6e]60#include "ResolvExpr/typeops.h"
[79970ed]61#include <algorithm>
[51b7345]62
[c8ffe20b]63#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
[51b7345]64
65namespace SymTab {
[a08ba92]66        class HoistStruct : public Visitor {
67          public:
[82dd287]68                /// Flattens nested struct types
[0dd3a2f]69                static void hoistStruct( std::list< Declaration * > &translationUnit );
[9cb8e88d]70
[0dd3a2f]71                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
[9cb8e88d]72
[0dd3a2f]73                virtual void visit( StructDecl *aggregateDecl );
74                virtual void visit( UnionDecl *aggregateDecl );
[c8ffe20b]75
[0dd3a2f]76                virtual void visit( CompoundStmt *compoundStmt );
77                virtual void visit( SwitchStmt *switchStmt );
[a08ba92]78          private:
[0dd3a2f]79                HoistStruct();
[c8ffe20b]80
[0dd3a2f]81                template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
[c8ffe20b]82
[0dd3a2f]83                std::list< Declaration * > declsToAdd;
84                bool inStruct;
[a08ba92]85        };
[c8ffe20b]86
[de91427b]87        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
[bda58ad]88        class EnumAndPointerDecayPass : public Visitor {
[0dd3a2f]89                typedef Visitor Parent;
90                virtual void visit( EnumDecl *aggregateDecl );
91                virtual void visit( FunctionType *func );
[a08ba92]92        };
[82dd287]93
94        /// Associates forward declarations of aggregates with their definitions
[a08ba92]95        class Pass2 : public Indexer {
[0dd3a2f]96                typedef Indexer Parent;
[a08ba92]97          public:
[0dd3a2f]98                Pass2( bool doDebug, const Indexer *indexer );
[a08ba92]99          private:
[0dd3a2f]100                virtual void visit( StructInstType *structInst );
101                virtual void visit( UnionInstType *unionInst );
[4040425]102                virtual void visit( TraitInstType *contextInst );
[0dd3a2f]103                virtual void visit( StructDecl *structDecl );
104                virtual void visit( UnionDecl *unionDecl );
105                virtual void visit( TypeInstType *typeInst );
106
107                const Indexer *indexer;
[9cb8e88d]108
[0dd3a2f]109                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
110                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
111                ForwardStructsType forwardStructs;
112                ForwardUnionsType forwardUnions;
[a08ba92]113        };
[c8ffe20b]114
[82dd287]115        /// Replaces array and function types in forall lists by appropriate pointer type
[a08ba92]116        class Pass3 : public Indexer {
[0dd3a2f]117                typedef Indexer Parent;
[a08ba92]118          public:
[0dd3a2f]119                Pass3( const Indexer *indexer );
[a08ba92]120          private:
[0dd3a2f]121                virtual void visit( ObjectDecl *object );
122                virtual void visit( FunctionDecl *func );
[c8ffe20b]123
[0dd3a2f]124                const Indexer *indexer;
[a08ba92]125        };
[c8ffe20b]126
[de91427b]127        class ReturnChecker : public Visitor {
128          public:
129                /// Checks that return statements return nothing if their return type is void
130                /// and return something if the return type is non-void.
131                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
132          private:
133                virtual void visit( FunctionDecl * functionDecl );
134
135                virtual void visit( ReturnStmt * returnStmt );
136
137                std::list< DeclarationWithType * > returnVals;
138        };
139
[a08ba92]140        class EliminateTypedef : public Mutator {
141          public:
[de91427b]142                EliminateTypedef() : scopeLevel( 0 ) {}
143                /// Replaces typedefs by forward declarations
[0dd3a2f]144                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
[a08ba92]145          private:
[0dd3a2f]146                virtual Declaration *mutate( TypedefDecl *typeDecl );
147                virtual TypeDecl *mutate( TypeDecl *typeDecl );
148                virtual DeclarationWithType *mutate( FunctionDecl *funcDecl );
[1db21619]149                virtual DeclarationWithType *mutate( ObjectDecl *objDecl );
[0dd3a2f]150                virtual CompoundStmt *mutate( CompoundStmt *compoundStmt );
151                virtual Type *mutate( TypeInstType *aggregateUseType );
152                virtual Expression *mutate( CastExpr *castExpr );
[cc79d97]153
[85c4ef0]154                virtual Declaration *mutate( StructDecl * structDecl );
155                virtual Declaration *mutate( UnionDecl * unionDecl );
156                virtual Declaration *mutate( EnumDecl * enumDecl );
[4040425]157                virtual Declaration *mutate( TraitDecl * contextDecl );
[85c4ef0]158
159                template<typename AggDecl>
160                AggDecl *handleAggregate( AggDecl * aggDecl );
161
[45161b4d]162                template<typename AggDecl>
163                void addImplicitTypedef( AggDecl * aggDecl );
[70a06f6]164
[46f6134]165                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
[e491159]166                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
[679864e1]167                typedef std::map< std::string, TypeDecl * > TypeDeclMap;
[cc79d97]168                TypedefMap typedefNames;
[679864e1]169                TypeDeclMap typedeclNames;
[cc79d97]170                int scopeLevel;
[a08ba92]171        };
[c8ffe20b]172
[9cb8e88d]173        class VerifyCtorDtor : public Visitor {
174        public:
175                /// ensure that constructors and destructors have at least one
176                /// parameter, the first of which must be a pointer, and no
177                /// return values.
178                static void verify( std::list< Declaration * > &translationUnit );
179
180                virtual void visit( FunctionDecl *funcDecl );
[5f98ce5]181        };
[70a06f6]182
[630a82a]183        class CompoundLiteral : public GenPoly::DeclMutator {
184                DeclarationNode::StorageClass storageclass = DeclarationNode::NoStorageClass;
185
186                virtual DeclarationWithType * mutate( ObjectDecl *objectDecl );
187                virtual Expression *mutate( CompoundLiteralExpr *compLitExpr );
[9cb8e88d]188        };
189
[a08ba92]190        void validate( std::list< Declaration * > &translationUnit, bool doDebug ) {
[bda58ad]191                EnumAndPointerDecayPass epc;
[0dd3a2f]192                Pass2 pass2( doDebug, 0 );
193                Pass3 pass3( 0 );
[630a82a]194                CompoundLiteral compoundliteral;
195
[0dd3a2f]196                EliminateTypedef::eliminateTypedef( translationUnit );
197                HoistStruct::hoistStruct( translationUnit );
[bda58ad]198                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecayPass
199                acceptAll( translationUnit, epc );
[0dd3a2f]200                acceptAll( translationUnit, pass2 );
[de91427b]201                ReturnChecker::checkFunctionReturns( translationUnit );
[40e636a]202                compoundliteral.mutateDeclarationList( translationUnit );
[0dd3a2f]203                acceptAll( translationUnit, pass3 );
[9cb8e88d]204                VerifyCtorDtor::verify( translationUnit );
[a08ba92]205        }
[9cb8e88d]206
[a08ba92]207        void validateType( Type *type, const Indexer *indexer ) {
[bda58ad]208                EnumAndPointerDecayPass epc;
[0dd3a2f]209                Pass2 pass2( false, indexer );
210                Pass3 pass3( indexer );
[bda58ad]211                type->accept( epc );
[0dd3a2f]212                type->accept( pass2 );
213                type->accept( pass3 );
[a08ba92]214        }
[c8ffe20b]215
[a08ba92]216        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
[0dd3a2f]217                HoistStruct hoister;
218                acceptAndAdd( translationUnit, hoister, true );
[a08ba92]219        }
[c8ffe20b]220
[a08ba92]221        HoistStruct::HoistStruct() : inStruct( false ) {
222        }
[c8ffe20b]223
[a08ba92]224        void filter( std::list< Declaration * > &declList, bool (*pred)( Declaration * ), bool doDelete ) {
[0dd3a2f]225                std::list< Declaration * >::iterator i = declList.begin();
226                while ( i != declList.end() ) {
227                        std::list< Declaration * >::iterator next = i;
228                        ++next;
229                        if ( pred( *i ) ) {
230                                if ( doDelete ) {
231                                        delete *i;
232                                } // if
233                                declList.erase( i );
234                        } // if
235                        i = next;
236                } // while
[a08ba92]237        }
[c8ffe20b]238
[a08ba92]239        bool isStructOrUnion( Declaration *decl ) {
[0dd3a2f]240                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
[a08ba92]241        }
[51b7345]242
[a08ba92]243        template< typename AggDecl >
244        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
[0dd3a2f]245                if ( inStruct ) {
246                        // Add elements in stack order corresponding to nesting structure.
247                        declsToAdd.push_front( aggregateDecl );
248                        Visitor::visit( aggregateDecl );
249                } else {
250                        inStruct = true;
251                        Visitor::visit( aggregateDecl );
252                        inStruct = false;
253                } // if
254                // Always remove the hoisted aggregate from the inner structure.
255                filter( aggregateDecl->get_members(), isStructOrUnion, false );
[a08ba92]256        }
[c8ffe20b]257
[a08ba92]258        void HoistStruct::visit( StructDecl *aggregateDecl ) {
[0dd3a2f]259                handleAggregate( aggregateDecl );
[a08ba92]260        }
[c8ffe20b]261
[a08ba92]262        void HoistStruct::visit( UnionDecl *aggregateDecl ) {
[0dd3a2f]263                handleAggregate( aggregateDecl );
[a08ba92]264        }
[c8ffe20b]265
[a08ba92]266        void HoistStruct::visit( CompoundStmt *compoundStmt ) {
[0dd3a2f]267                addVisit( compoundStmt, *this );
[a08ba92]268        }
[c8ffe20b]269
[a08ba92]270        void HoistStruct::visit( SwitchStmt *switchStmt ) {
[0dd3a2f]271                addVisit( switchStmt, *this );
[a08ba92]272        }
[c8ffe20b]273
[bda58ad]274        void EnumAndPointerDecayPass::visit( EnumDecl *enumDecl ) {
[0dd3a2f]275                // Set the type of each member of the enumeration to be EnumConstant
276                for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
[f6d7e0f]277                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
[0dd3a2f]278                        assert( obj );
[a436947]279                        obj->set_type( new EnumInstType( Type::Qualifiers( true, false, false, false, false, false ), enumDecl->get_name() ) );
[0dd3a2f]280                } // for
281                Parent::visit( enumDecl );
[a08ba92]282        }
[51b7345]283
[a08ba92]284        namespace {
[83de11e]285                template< typename DWTList >
286                void fixFunctionList( DWTList & dwts, FunctionType * func ) {
[0dd3a2f]287                        // the only case in which "void" is valid is where it is the only one in the list; then it should be removed
288                        // entirely other fix ups are handled by the FixFunction class
[83de11e]289                        typedef typename DWTList::iterator DWTIterator;
290                        DWTIterator begin( dwts.begin() ), end( dwts.end() );
[0dd3a2f]291                        if ( begin == end ) return;
292                        FixFunction fixer;
293                        DWTIterator i = begin;
[83de11e]294                        *i = (*i)->acceptMutator( fixer );
[0dd3a2f]295                        if ( fixer.get_isVoid() ) {
296                                DWTIterator j = i;
297                                ++i;
[bda58ad]298                                delete *j;
[83de11e]299                                dwts.erase( j );
[9cb8e88d]300                                if ( i != end ) {
[0dd3a2f]301                                        throw SemanticError( "invalid type void in function type ", func );
302                                } // if
303                        } else {
304                                ++i;
305                                for ( ; i != end; ++i ) {
306                                        FixFunction fixer;
307                                        *i = (*i )->acceptMutator( fixer );
308                                        if ( fixer.get_isVoid() ) {
309                                                throw SemanticError( "invalid type void in function type ", func );
310                                        } // if
311                                } // for
312                        } // if
313                }
[a08ba92]314        }
[c8ffe20b]315
[bda58ad]316        void EnumAndPointerDecayPass::visit( FunctionType *func ) {
[0dd3a2f]317                // Fix up parameters and return types
[83de11e]318                fixFunctionList( func->get_parameters(), func );
319                fixFunctionList( func->get_returnVals(), func );
[0dd3a2f]320                Visitor::visit( func );
[a08ba92]321        }
[c8ffe20b]322
[a08ba92]323        Pass2::Pass2( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) {
[0dd3a2f]324                if ( other_indexer ) {
325                        indexer = other_indexer;
326                } else {
327                        indexer = this;
328                } // if
[a08ba92]329        }
[c8ffe20b]330
[a08ba92]331        void Pass2::visit( StructInstType *structInst ) {
[0dd3a2f]332                Parent::visit( structInst );
333                StructDecl *st = indexer->lookupStruct( structInst->get_name() );
334                // it's not a semantic error if the struct is not found, just an implicit forward declaration
335                if ( st ) {
[98735ef]336                        //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
[0dd3a2f]337                        structInst->set_baseStruct( st );
338                } // if
339                if ( ! st || st->get_members().empty() ) {
340                        // use of forward declaration
341                        forwardStructs[ structInst->get_name() ].push_back( structInst );
342                } // if
[a08ba92]343        }
[c8ffe20b]344
[a08ba92]345        void Pass2::visit( UnionInstType *unionInst ) {
[0dd3a2f]346                Parent::visit( unionInst );
347                UnionDecl *un = indexer->lookupUnion( unionInst->get_name() );
348                // it's not a semantic error if the union is not found, just an implicit forward declaration
349                if ( un ) {
350                        unionInst->set_baseUnion( un );
351                } // if
352                if ( ! un || un->get_members().empty() ) {
353                        // use of forward declaration
354                        forwardUnions[ unionInst->get_name() ].push_back( unionInst );
355                } // if
[a08ba92]356        }
[c8ffe20b]357
[4040425]358        void Pass2::visit( TraitInstType *contextInst ) {
[0dd3a2f]359                Parent::visit( contextInst );
[4040425]360                TraitDecl *ctx = indexer->lookupTrait( contextInst->get_name() );
[0dd3a2f]361                if ( ! ctx ) {
362                        throw SemanticError( "use of undeclared context " + contextInst->get_name() );
[17cd4eb]363                } // if
[0dd3a2f]364                for ( std::list< TypeDecl * >::const_iterator i = ctx->get_parameters().begin(); i != ctx->get_parameters().end(); ++i ) {
365                        for ( std::list< DeclarationWithType * >::const_iterator assert = (*i )->get_assertions().begin(); assert != (*i )->get_assertions().end(); ++assert ) {
[4040425]366                                if ( TraitInstType *otherCtx = dynamic_cast< TraitInstType * >(*assert ) ) {
[0dd3a2f]367                                        cloneAll( otherCtx->get_members(), contextInst->get_members() );
368                                } else {
369                                        contextInst->get_members().push_back( (*assert )->clone() );
370                                } // if
371                        } // for
372                } // for
[51b986f]373
374                if ( ctx->get_parameters().size() != contextInst->get_parameters().size() ) {
375                        throw SemanticError( "incorrect number of context parameters: ", contextInst );
376                } // if
377
[79970ed]378                // need to clone members of the context for ownership purposes
379                std::list< Declaration * > members;
380                std::transform( ctx->get_members().begin(), ctx->get_members().end(), back_inserter( members ), [](Declaration * dwt) { return dwt->clone(); } );
381
382                applySubstitution( ctx->get_parameters().begin(), ctx->get_parameters().end(), contextInst->get_parameters().begin(), members.begin(), members.end(), back_inserter( contextInst->get_members() ) );
[a08ba92]383        }
[c8ffe20b]384
[a08ba92]385        void Pass2::visit( StructDecl *structDecl ) {
[677c1be]386                // visit struct members first so that the types of self-referencing members are updated properly
387                Parent::visit( structDecl );
[0dd3a2f]388                if ( ! structDecl->get_members().empty() ) {
389                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
390                        if ( fwds != forwardStructs.end() ) {
391                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
392                                        (*inst )->set_baseStruct( structDecl );
393                                } // for
394                                forwardStructs.erase( fwds );
395                        } // if
396                } // if
[a08ba92]397        }
[c8ffe20b]398
[a08ba92]399        void Pass2::visit( UnionDecl *unionDecl ) {
[677c1be]400                Parent::visit( unionDecl );
[0dd3a2f]401                if ( ! unionDecl->get_members().empty() ) {
402                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
403                        if ( fwds != forwardUnions.end() ) {
404                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
405                                        (*inst )->set_baseUnion( unionDecl );
406                                } // for
407                                forwardUnions.erase( fwds );
408                        } // if
409                } // if
[a08ba92]410        }
[c8ffe20b]411
[a08ba92]412        void Pass2::visit( TypeInstType *typeInst ) {
[0dd3a2f]413                if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) {
414                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
415                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
416                        } // if
417                } // if
[a08ba92]418        }
[c8ffe20b]419
[a08ba92]420        Pass3::Pass3( const Indexer *other_indexer ) :  Indexer( false ) {
[0dd3a2f]421                if ( other_indexer ) {
422                        indexer = other_indexer;
423                } else {
424                        indexer = this;
425                } // if
[a08ba92]426        }
[c8ffe20b]427
[82dd287]428        /// Fix up assertions
[a08ba92]429        void forallFixer( Type *func ) {
[0dd3a2f]430                for ( std::list< TypeDecl * >::iterator type = func->get_forall().begin(); type != func->get_forall().end(); ++type ) {
431                        std::list< DeclarationWithType * > toBeDone, nextRound;
432                        toBeDone.splice( toBeDone.end(), (*type )->get_assertions() );
433                        while ( ! toBeDone.empty() ) {
434                                for ( std::list< DeclarationWithType * >::iterator assertion = toBeDone.begin(); assertion != toBeDone.end(); ++assertion ) {
[4040425]435                                        if ( TraitInstType *ctx = dynamic_cast< TraitInstType * >( (*assertion )->get_type() ) ) {
[0dd3a2f]436                                                for ( std::list< Declaration * >::const_iterator i = ctx->get_members().begin(); i != ctx->get_members().end(); ++i ) {
437                                                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *i );
438                                                        assert( dwt );
439                                                        nextRound.push_back( dwt->clone() );
440                                                }
441                                                delete ctx;
442                                        } else {
443                                                FixFunction fixer;
444                                                *assertion = (*assertion )->acceptMutator( fixer );
445                                                if ( fixer.get_isVoid() ) {
446                                                        throw SemanticError( "invalid type void in assertion of function ", func );
447                                                }
448                                                (*type )->get_assertions().push_back( *assertion );
449                                        } // if
450                                } // for
451                                toBeDone.clear();
452                                toBeDone.splice( toBeDone.end(), nextRound );
453                        } // while
454                } // for
[a08ba92]455        }
[c8ffe20b]456
[a08ba92]457        void Pass3::visit( ObjectDecl *object ) {
[0dd3a2f]458                forallFixer( object->get_type() );
459                if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) {
460                        forallFixer( pointer->get_base() );
461                } // if
462                Parent::visit( object );
463                object->fixUniqueId();
[a08ba92]464        }
[c8ffe20b]465
[a08ba92]466        void Pass3::visit( FunctionDecl *func ) {
[0dd3a2f]467                forallFixer( func->get_type() );
468                Parent::visit( func );
469                func->fixUniqueId();
[a08ba92]470        }
[c8ffe20b]471
[de91427b]472        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
473                ReturnChecker checker;
474                acceptAll( translationUnit, checker );
475        }
476
477        void ReturnChecker::visit( FunctionDecl * functionDecl ) {
478                std::list< DeclarationWithType * > oldReturnVals = returnVals;
479                returnVals = functionDecl->get_functionType()->get_returnVals();
480                Visitor::visit( functionDecl );
481                returnVals = oldReturnVals;
482        }
483
484        void ReturnChecker::visit( ReturnStmt * returnStmt ) {
[74d1804]485                // Previously this also checked for the existence of an expr paired with no return values on
486                // the  function return type. This is incorrect, since you can have an expression attached to
487                // a return statement in a void-returning function in C. The expression is treated as if it
488                // were cast to void.
[de91427b]489                if ( returnStmt->get_expr() == NULL && returnVals.size() != 0 ) {
490                        throw SemanticError( "Non-void function returns no values: " , returnStmt );
491                }
492        }
493
494
[a08ba92]495        bool isTypedef( Declaration *decl ) {
[0dd3a2f]496                return dynamic_cast< TypedefDecl * >( decl );
[a08ba92]497        }
[c8ffe20b]498
[a08ba92]499        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
[0dd3a2f]500                EliminateTypedef eliminator;
501                mutateAll( translationUnit, eliminator );
[5f98ce5]502                if ( eliminator.typedefNames.count( "size_t" ) ) {
503                        // grab and remember declaration of size_t
504                        SizeType = eliminator.typedefNames["size_t"].first->get_base()->clone();
505                } else {
[40e636a]506                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
507                        // eventually should have a warning for this case.
508                        SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
[5f98ce5]509                }
[0dd3a2f]510                filter( translationUnit, isTypedef, true );
[5f98ce5]511
[a08ba92]512        }
[c8ffe20b]513
[85c4ef0]514        Type *EliminateTypedef::mutate( TypeInstType * typeInst ) {
[9cb8e88d]515                // instances of typedef types will come here. If it is an instance
[cc79d97]516                // of a typdef type, link the instance to its actual type.
517                TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
[0dd3a2f]518                if ( def != typedefNames.end() ) {
[cc79d97]519                        Type *ret = def->second.first->get_base()->clone();
[0dd3a2f]520                        ret->get_qualifiers() += typeInst->get_qualifiers();
[0215a76f]521                        // place instance parameters on the typedef'd type
522                        if ( ! typeInst->get_parameters().empty() ) {
523                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
524                                if ( ! rtt ) {
525                                        throw SemanticError("cannot apply type parameters to base type of " + typeInst->get_name());
526                                }
527                                rtt->get_parameters().clear();
[b644d6f]528                                cloneAll( typeInst->get_parameters(), rtt->get_parameters() );
529                                mutateAll( rtt->get_parameters(), *this );  // recursively fix typedefs on parameters
[1db21619]530                        } // if
[0dd3a2f]531                        delete typeInst;
532                        return ret;
[679864e1]533                } else {
534                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->get_name() );
535                        assert( base != typedeclNames.end() );
[1e8b02f5]536                        typeInst->set_baseType( base->second );
[0dd3a2f]537                } // if
538                return typeInst;
[a08ba92]539        }
[c8ffe20b]540
[85c4ef0]541        Declaration *EliminateTypedef::mutate( TypedefDecl * tyDecl ) {
[0dd3a2f]542                Declaration *ret = Mutator::mutate( tyDecl );
[5f98ce5]543
[cc79d97]544                if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
[9cb8e88d]545                        // typedef to the same name from the same scope
[cc79d97]546                        // must be from the same type
547
548                        Type * t1 = tyDecl->get_base();
549                        Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
[1cbca6e]550                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
[cc79d97]551                                throw SemanticError( "cannot redefine typedef: " + tyDecl->get_name() );
[85c4ef0]552                        }
[cc79d97]553                } else {
[46f6134]554                        typedefNames[ tyDecl->get_name() ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
[cc79d97]555                } // if
556
[0dd3a2f]557                // When a typedef is a forward declaration:
558                //    typedef struct screen SCREEN;
559                // the declaration portion must be retained:
560                //    struct screen;
561                // because the expansion of the typedef is:
562                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
563                // hence the type-name "screen" must be defined.
564                // Note, qualifiers on the typedef are superfluous for the forward declaration.
565                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( tyDecl->get_base() ) ) {
566                        return new StructDecl( aggDecl->get_name() );
567                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( tyDecl->get_base() ) ) {
568                        return new UnionDecl( aggDecl->get_name() );
[956a9c7]569                } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( tyDecl->get_base() ) ) {
570                        return new EnumDecl( enumDecl->get_name() );
[0dd3a2f]571                } else {
[46f6134]572                        return ret->clone();
[0dd3a2f]573                } // if
[a08ba92]574        }
[c8ffe20b]575
[85c4ef0]576        TypeDecl *EliminateTypedef::mutate( TypeDecl * typeDecl ) {
[cc79d97]577                TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
[0dd3a2f]578                if ( i != typedefNames.end() ) {
579                        typedefNames.erase( i ) ;
580                } // if
[679864e1]581
582                typedeclNames[ typeDecl->get_name() ] = typeDecl;
[0dd3a2f]583                return typeDecl;
[a08ba92]584        }
[c8ffe20b]585
[85c4ef0]586        DeclarationWithType *EliminateTypedef::mutate( FunctionDecl * funcDecl ) {
[46f6134]587                typedefNames.beginScope();
[0dd3a2f]588                DeclarationWithType *ret = Mutator::mutate( funcDecl );
[46f6134]589                typedefNames.endScope();
[0dd3a2f]590                return ret;
[a08ba92]591        }
[c8ffe20b]592
[1db21619]593        DeclarationWithType *EliminateTypedef::mutate( ObjectDecl * objDecl ) {
[46f6134]594                typedefNames.beginScope();
[1db21619]595                DeclarationWithType *ret = Mutator::mutate( objDecl );
[46f6134]596                typedefNames.endScope();
[02e5ab6]597                // is the type a function?
[1db21619]598                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( ret->get_type() ) ) {
[02e5ab6]599                        // replace the current object declaration with a function declaration
[1db21619]600                        return new FunctionDecl( ret->get_name(), ret->get_storageClass(), ret->get_linkage(), funtype, 0, ret->get_isInline(), ret->get_isNoreturn() );
601                } else if ( objDecl->get_isInline() || objDecl->get_isNoreturn() ) {
602                        throw SemanticError( "invalid inline or _Noreturn specification in declaration of ", objDecl );
603                } // if
[0dd3a2f]604                return ret;
[a08ba92]605        }
[c8ffe20b]606
[85c4ef0]607        Expression *EliminateTypedef::mutate( CastExpr * castExpr ) {
[46f6134]608                typedefNames.beginScope();
[0dd3a2f]609                Expression *ret = Mutator::mutate( castExpr );
[46f6134]610                typedefNames.endScope();
[0dd3a2f]611                return ret;
[a08ba92]612        }
[c8ffe20b]613
[85c4ef0]614        CompoundStmt *EliminateTypedef::mutate( CompoundStmt * compoundStmt ) {
[46f6134]615                typedefNames.beginScope();
[cc79d97]616                scopeLevel += 1;
[0dd3a2f]617                CompoundStmt *ret = Mutator::mutate( compoundStmt );
[cc79d97]618                scopeLevel -= 1;
[0dd3a2f]619                std::list< Statement * >::iterator i = compoundStmt->get_kids().begin();
620                while ( i != compoundStmt->get_kids().end() ) {
[85c4ef0]621                        std::list< Statement * >::iterator next = i+1;
[0dd3a2f]622                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( *i ) ) {
623                                if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
624                                        delete *i;
625                                        compoundStmt->get_kids().erase( i );
626                                } // if
627                        } // if
628                        i = next;
629                } // while
[46f6134]630                typedefNames.endScope();
[0dd3a2f]631                return ret;
[a08ba92]632        }
[85c4ef0]633
[45161b4d]634        // there may be typedefs nested within aggregates in order for everything to work properly, these should be removed
635        // as well
[85c4ef0]636        template<typename AggDecl>
637        AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
638                std::list<Declaration *>::iterator it = aggDecl->get_members().begin();
639                for ( ; it != aggDecl->get_members().end(); ) {
640                        std::list< Declaration * >::iterator next = it+1;
641                        if ( dynamic_cast< TypedefDecl * >( *it ) ) {
642                                delete *it;
643                                aggDecl->get_members().erase( it );
644                        } // if
645                        it = next;
646                }
647                return aggDecl;
648        }
649
[45161b4d]650        template<typename AggDecl>
651        void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
652                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
653                        Type *type;
654                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
655                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
656                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
657                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
658                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
659                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
660                        } // if
[46f6134]661                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), DeclarationNode::NoStorageClass, type ) );
662                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
[45161b4d]663                } // if
664        }
[4e06c1e]665
[85c4ef0]666        Declaration *EliminateTypedef::mutate( StructDecl * structDecl ) {
[45161b4d]667                addImplicitTypedef( structDecl );
[85c4ef0]668                Mutator::mutate( structDecl );
669                return handleAggregate( structDecl );
670        }
671
672        Declaration *EliminateTypedef::mutate( UnionDecl * unionDecl ) {
[45161b4d]673                addImplicitTypedef( unionDecl );
[85c4ef0]674                Mutator::mutate( unionDecl );
675                return handleAggregate( unionDecl );
676        }
677
678        Declaration *EliminateTypedef::mutate( EnumDecl * enumDecl ) {
[45161b4d]679                addImplicitTypedef( enumDecl );
[85c4ef0]680                Mutator::mutate( enumDecl );
681                return handleAggregate( enumDecl );
682        }
683
[45161b4d]684        Declaration *EliminateTypedef::mutate( TraitDecl * contextDecl ) {
[85c4ef0]685                Mutator::mutate( contextDecl );
686                return handleAggregate( contextDecl );
687        }
688
[9cb8e88d]689        void VerifyCtorDtor::verify( std::list< Declaration * > & translationUnit ) {
690                VerifyCtorDtor verifier;
691                acceptAll( translationUnit, verifier );
692        }
693
694        void VerifyCtorDtor::visit( FunctionDecl * funcDecl ) {
695                FunctionType * funcType = funcDecl->get_functionType();
696                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
697                std::list< DeclarationWithType * > &params = funcType->get_parameters();
698
699                if ( funcDecl->get_name() == "?{}" || funcDecl->get_name() == "^?{}" ) {
700                        if ( params.size() == 0 ) {
701                                throw SemanticError( "Constructors and destructors require at least one parameter ", funcDecl );
702                        }
703                        if ( ! dynamic_cast< PointerType * >( params.front()->get_type() ) ) {
704                                throw SemanticError( "First parameter of a constructor or destructor must be a pointer ", funcDecl );
705                        }
706                        if ( returnVals.size() != 0 ) {
707                                throw SemanticError( "Constructors and destructors cannot have explicit return values ", funcDecl );
708                        }
709                }
710
711                Visitor::visit( funcDecl );
712        }
[70a06f6]713
[630a82a]714        DeclarationWithType * CompoundLiteral::mutate( ObjectDecl *objectDecl ) {
715                storageclass = objectDecl->get_storageClass();
716                DeclarationWithType * temp = Mutator::mutate( objectDecl );
717                storageclass = DeclarationNode::NoStorageClass;
718                return temp;
719        }
720
721        Expression *CompoundLiteral::mutate( CompoundLiteralExpr *compLitExpr ) {
722                // transform [storage_class] ... (struct S){ 3, ... };
723                // into [storage_class] struct S temp =  { 3, ... };
724                static UniqueName indexName( "_compLit" );
725
726                ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageclass, LinkageSpec::C, 0, compLitExpr->get_type(), compLitExpr->get_initializer() );
727                compLitExpr->set_type( 0 );
728                compLitExpr->set_initializer( 0 );
729                delete compLitExpr;
730                DeclarationWithType * newtempvar = mutate( tempvar );
731                addDeclaration( newtempvar );                                   // add modified temporary to current block
732                return new VariableExpr( newtempvar );
733        }
[51b7345]734} // namespace SymTab
[0dd3a2f]735
736// Local Variables: //
737// tab-width: 4 //
738// mode: c++ //
739// compile-command: "make install" //
740// End: //
Note: See TracBrowser for help on using the repository browser.