source: src/SymTab/Validate.cc @ 8b6b552

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 8b6b552 was 46f6134, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Implemented owning scoped map for typedef elimination phase

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