source: src/SymTab/Validate.cc @ f1b1e4c

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since f1b1e4c was f1b1e4c, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

can construct global const objects, except with intrinsic constructors

  • Property mode set to 100644
File size: 26.2 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 : Rob Schluntz
12// Last Modified On : Wed May 11 13:17:52 2016
13// Update Count     : 297
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 "Indexer.h"
52#include "FixFunction.h"
53// #include "ImplementationType.h"
54#include "GenPoly/DeclMutator.h"
55#include "AddVisit.h"
56#include "MakeLibCfa.h"
57#include "TypeEquality.h"
58#include "Autogen.h"
59#include "ResolvExpr/typeops.h"
60
61#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
62
63namespace SymTab {
64        class HoistStruct : public Visitor {
65          public:
66                /// Flattens nested struct types
67                static void hoistStruct( std::list< Declaration * > &translationUnit );
68
69                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
70
71                virtual void visit( StructDecl *aggregateDecl );
72                virtual void visit( UnionDecl *aggregateDecl );
73
74                virtual void visit( CompoundStmt *compoundStmt );
75                virtual void visit( SwitchStmt *switchStmt );
76                virtual void visit( ChooseStmt *chooseStmt );
77                // virtual void visit( CaseStmt *caseStmt );
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::map< std::string, std::pair< TypedefDecl *, int > > TypedefMap;
166                TypedefMap typedefNames;
167                int scopeLevel;
168        };
169
170        class VerifyCtorDtor : public Visitor {
171        public:
172                /// ensure that constructors and destructors have at least one
173                /// parameter, the first of which must be a pointer, and no
174                /// return values.
175                static void verify( std::list< Declaration * > &translationUnit );
176
177                virtual void visit( FunctionDecl *funcDecl );
178};
179
180        class CompoundLiteral : public GenPoly::DeclMutator {
181                DeclarationNode::StorageClass storageclass = DeclarationNode::NoStorageClass;
182
183                virtual DeclarationWithType * mutate( ObjectDecl *objectDecl );
184                virtual Expression *mutate( CompoundLiteralExpr *compLitExpr );
185        };
186
187        void validate( std::list< Declaration * > &translationUnit, bool doDebug ) {
188                Pass1 pass1;
189                Pass2 pass2( doDebug, 0 );
190                Pass3 pass3( 0 );
191                CompoundLiteral compoundliteral;
192
193                EliminateTypedef::eliminateTypedef( translationUnit );
194                HoistStruct::hoistStruct( translationUnit );
195                acceptAll( translationUnit, pass1 );
196                acceptAll( translationUnit, pass2 );
197                ReturnChecker::checkFunctionReturns( translationUnit );
198                mutateAll( translationUnit, compoundliteral );
199                autogenerateRoutines( translationUnit );
200                acceptAll( translationUnit, pass3 );
201                VerifyCtorDtor::verify( translationUnit );
202        }
203
204        void validateType( Type *type, const Indexer *indexer ) {
205                Pass1 pass1;
206                Pass2 pass2( false, indexer );
207                Pass3 pass3( indexer );
208                type->accept( pass1 );
209                type->accept( pass2 );
210                type->accept( pass3 );
211        }
212
213        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
214                HoistStruct hoister;
215                acceptAndAdd( translationUnit, hoister, true );
216        }
217
218        HoistStruct::HoistStruct() : inStruct( false ) {
219        }
220
221        void filter( std::list< Declaration * > &declList, bool (*pred)( Declaration * ), bool doDelete ) {
222                std::list< Declaration * >::iterator i = declList.begin();
223                while ( i != declList.end() ) {
224                        std::list< Declaration * >::iterator next = i;
225                        ++next;
226                        if ( pred( *i ) ) {
227                                if ( doDelete ) {
228                                        delete *i;
229                                } // if
230                                declList.erase( i );
231                        } // if
232                        i = next;
233                } // while
234        }
235
236        bool isStructOrUnion( Declaration *decl ) {
237                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
238        }
239
240        template< typename AggDecl >
241        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
242                if ( inStruct ) {
243                        // Add elements in stack order corresponding to nesting structure.
244                        declsToAdd.push_front( aggregateDecl );
245                        Visitor::visit( aggregateDecl );
246                } else {
247                        inStruct = true;
248                        Visitor::visit( aggregateDecl );
249                        inStruct = false;
250                } // if
251                // Always remove the hoisted aggregate from the inner structure.
252                filter( aggregateDecl->get_members(), isStructOrUnion, false );
253        }
254
255        void HoistStruct::visit( StructDecl *aggregateDecl ) {
256                handleAggregate( aggregateDecl );
257        }
258
259        void HoistStruct::visit( UnionDecl *aggregateDecl ) {
260                handleAggregate( aggregateDecl );
261        }
262
263        void HoistStruct::visit( CompoundStmt *compoundStmt ) {
264                addVisit( compoundStmt, *this );
265        }
266
267        void HoistStruct::visit( SwitchStmt *switchStmt ) {
268                addVisit( switchStmt, *this );
269        }
270
271        void HoistStruct::visit( ChooseStmt *switchStmt ) {
272                addVisit( switchStmt, *this );
273        }
274
275        // void HoistStruct::visit( CaseStmt *caseStmt ) {
276        //      addVisit( caseStmt, *this );
277        // }
278
279        void Pass1::visit( EnumDecl *enumDecl ) {
280                // Set the type of each member of the enumeration to be EnumConstant
281
282                for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
283                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
284                        assert( obj );
285                        // obj->set_type( new EnumInstType( Type::Qualifiers( true, false, false, false, false, false ), enumDecl->get_name() ) );
286                        BasicType * enumType = new BasicType( Type::Qualifiers(), BasicType::SignedInt );
287                        obj->set_type( enumType ) ;
288                } // for
289                Parent::visit( enumDecl );
290        }
291
292        namespace {
293                template< typename DWTIterator, typename DWTList >
294                void fixFunctionList( DWTIterator begin, DWTIterator end, FunctionType *func, DWTList & dwts ) {
295                        // the only case in which "void" is valid is where it is the only one in the list; then it should be removed
296                        // entirely other fix ups are handled by the FixFunction class
297                        if ( begin == end ) return;
298                        FixFunction fixer;
299                        DWTIterator i = begin;
300                        *i = (*i)->acceptMutator( fixer );
301                        if ( fixer.get_isVoid() ) {
302                                DWTIterator j = i;
303                                ++i;
304                                dwts.erase( j );
305                                if ( i != end ) {
306                                        throw SemanticError( "invalid type void in function type ", func );
307                                } // if
308                        } else {
309                                ++i;
310                                for ( ; i != end; ++i ) {
311                                        FixFunction fixer;
312                                        *i = (*i )->acceptMutator( fixer );
313                                        if ( fixer.get_isVoid() ) {
314                                                throw SemanticError( "invalid type void in function type ", func );
315                                        } // if
316                                } // for
317                        } // if
318                }
319        }
320
321        void Pass1::visit( FunctionType *func ) {
322                // Fix up parameters and return types
323                fixFunctionList( func->get_parameters().begin(), func->get_parameters().end(), func, func->get_parameters() );
324                fixFunctionList( func->get_returnVals().begin(), func->get_returnVals().end(), func, func->get_returnVals() );
325                Visitor::visit( func );
326        }
327
328        Pass2::Pass2( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) {
329                if ( other_indexer ) {
330                        indexer = other_indexer;
331                } else {
332                        indexer = this;
333                } // if
334        }
335
336        void Pass2::visit( StructInstType *structInst ) {
337                Parent::visit( structInst );
338                StructDecl *st = indexer->lookupStruct( structInst->get_name() );
339                // it's not a semantic error if the struct is not found, just an implicit forward declaration
340                if ( st ) {
341                        //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
342                        structInst->set_baseStruct( st );
343                } // if
344                if ( ! st || st->get_members().empty() ) {
345                        // use of forward declaration
346                        forwardStructs[ structInst->get_name() ].push_back( structInst );
347                } // if
348        }
349
350        void Pass2::visit( UnionInstType *unionInst ) {
351                Parent::visit( unionInst );
352                UnionDecl *un = indexer->lookupUnion( unionInst->get_name() );
353                // it's not a semantic error if the union is not found, just an implicit forward declaration
354                if ( un ) {
355                        unionInst->set_baseUnion( un );
356                } // if
357                if ( ! un || un->get_members().empty() ) {
358                        // use of forward declaration
359                        forwardUnions[ unionInst->get_name() ].push_back( unionInst );
360                } // if
361        }
362
363        void Pass2::visit( TraitInstType *contextInst ) {
364                Parent::visit( contextInst );
365                TraitDecl *ctx = indexer->lookupTrait( contextInst->get_name() );
366                if ( ! ctx ) {
367                        throw SemanticError( "use of undeclared context " + contextInst->get_name() );
368                } // if
369                for ( std::list< TypeDecl * >::const_iterator i = ctx->get_parameters().begin(); i != ctx->get_parameters().end(); ++i ) {
370                        for ( std::list< DeclarationWithType * >::const_iterator assert = (*i )->get_assertions().begin(); assert != (*i )->get_assertions().end(); ++assert ) {
371                                if ( TraitInstType *otherCtx = dynamic_cast< TraitInstType * >(*assert ) ) {
372                                        cloneAll( otherCtx->get_members(), contextInst->get_members() );
373                                } else {
374                                        contextInst->get_members().push_back( (*assert )->clone() );
375                                } // if
376                        } // for
377                } // for
378
379                if ( ctx->get_parameters().size() != contextInst->get_parameters().size() ) {
380                        throw SemanticError( "incorrect number of context parameters: ", contextInst );
381                } // if
382
383                applySubstitution( ctx->get_parameters().begin(), ctx->get_parameters().end(), contextInst->get_parameters().begin(), ctx->get_members().begin(), ctx->get_members().end(), back_inserter( contextInst->get_members() ) );
384        }
385
386        void Pass2::visit( StructDecl *structDecl ) {
387                // visit struct members first so that the types of self-referencing members are updated properly
388                Parent::visit( structDecl );
389                if ( ! structDecl->get_members().empty() ) {
390                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
391                        if ( fwds != forwardStructs.end() ) {
392                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
393                                        (*inst )->set_baseStruct( structDecl );
394                                } // for
395                                forwardStructs.erase( fwds );
396                        } // if
397                } // if
398        }
399
400        void Pass2::visit( UnionDecl *unionDecl ) {
401                Parent::visit( unionDecl );
402                if ( ! unionDecl->get_members().empty() ) {
403                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
404                        if ( fwds != forwardUnions.end() ) {
405                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
406                                        (*inst )->set_baseUnion( unionDecl );
407                                } // for
408                                forwardUnions.erase( fwds );
409                        } // if
410                } // if
411        }
412
413        void Pass2::visit( TypeInstType *typeInst ) {
414                if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) {
415                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
416                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
417                        } // if
418                } // if
419        }
420
421        Pass3::Pass3( const Indexer *other_indexer ) :  Indexer( false ) {
422                if ( other_indexer ) {
423                        indexer = other_indexer;
424                } else {
425                        indexer = this;
426                } // if
427        }
428
429        /// Fix up assertions
430        void forallFixer( Type *func ) {
431                for ( std::list< TypeDecl * >::iterator type = func->get_forall().begin(); type != func->get_forall().end(); ++type ) {
432                        std::list< DeclarationWithType * > toBeDone, nextRound;
433                        toBeDone.splice( toBeDone.end(), (*type )->get_assertions() );
434                        while ( ! toBeDone.empty() ) {
435                                for ( std::list< DeclarationWithType * >::iterator assertion = toBeDone.begin(); assertion != toBeDone.end(); ++assertion ) {
436                                        if ( TraitInstType *ctx = dynamic_cast< TraitInstType * >( (*assertion )->get_type() ) ) {
437                                                for ( std::list< Declaration * >::const_iterator i = ctx->get_members().begin(); i != ctx->get_members().end(); ++i ) {
438                                                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *i );
439                                                        assert( dwt );
440                                                        nextRound.push_back( dwt->clone() );
441                                                }
442                                                delete ctx;
443                                        } else {
444                                                FixFunction fixer;
445                                                *assertion = (*assertion )->acceptMutator( fixer );
446                                                if ( fixer.get_isVoid() ) {
447                                                        throw SemanticError( "invalid type void in assertion of function ", func );
448                                                }
449                                                (*type )->get_assertions().push_back( *assertion );
450                                        } // if
451                                } // for
452                                toBeDone.clear();
453                                toBeDone.splice( toBeDone.end(), nextRound );
454                        } // while
455                } // for
456        }
457
458        void Pass3::visit( ObjectDecl *object ) {
459                forallFixer( object->get_type() );
460                if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) {
461                        forallFixer( pointer->get_base() );
462                } // if
463                Parent::visit( object );
464                object->fixUniqueId();
465        }
466
467        void Pass3::visit( FunctionDecl *func ) {
468                forallFixer( func->get_type() );
469                Parent::visit( func );
470                func->fixUniqueId();
471        }
472
473        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
474                ReturnChecker checker;
475                acceptAll( translationUnit, checker );
476        }
477
478        void ReturnChecker::visit( FunctionDecl * functionDecl ) {
479                std::list< DeclarationWithType * > oldReturnVals = returnVals;
480                returnVals = functionDecl->get_functionType()->get_returnVals();
481                Visitor::visit( functionDecl );
482                returnVals = oldReturnVals;
483        }
484
485        void ReturnChecker::visit( ReturnStmt * returnStmt ) {
486                if ( returnStmt->get_expr() == NULL && returnVals.size() != 0 ) {
487                        throw SemanticError( "Non-void function returns no values: " , returnStmt );
488                } else if ( returnStmt->get_expr() != NULL && returnVals.size() == 0 ) {
489                        throw SemanticError( "void function returns 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                filter( translationUnit, isTypedef, true );
502        }
503
504        Type *EliminateTypedef::mutate( TypeInstType * typeInst ) {
505                // instances of typedef types will come here. If it is an instance
506                // of a typdef type, link the instance to its actual type.
507                TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
508                if ( def != typedefNames.end() ) {
509                        Type *ret = def->second.first->get_base()->clone();
510                        ret->get_qualifiers() += typeInst->get_qualifiers();
511                        // place instance parameters on the typedef'd type
512                        if ( ! typeInst->get_parameters().empty() ) {
513                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
514                                if ( ! rtt ) {
515                                        throw SemanticError("cannot apply type parameters to base type of " + typeInst->get_name());
516                                }
517                                rtt->get_parameters().clear();
518                                cloneAll( typeInst->get_parameters(), rtt->get_parameters() );
519                                mutateAll( rtt->get_parameters(), *this );  // recursively fix typedefs on parameters
520                        } // if
521                        delete typeInst;
522                        return ret;
523                } // if
524                return typeInst;
525        }
526
527        Declaration *EliminateTypedef::mutate( TypedefDecl * tyDecl ) {
528                Declaration *ret = Mutator::mutate( tyDecl );
529                if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
530                        // typedef to the same name from the same scope
531                        // must be from the same type
532
533                        Type * t1 = tyDecl->get_base();
534                        Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
535                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
536                                throw SemanticError( "cannot redefine typedef: " + tyDecl->get_name() );
537                        }
538                } else {
539                        typedefNames[ tyDecl->get_name() ] = std::make_pair( tyDecl, scopeLevel );
540                } // if
541
542                // When a typedef is a forward declaration:
543                //    typedef struct screen SCREEN;
544                // the declaration portion must be retained:
545                //    struct screen;
546                // because the expansion of the typedef is:
547                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
548                // hence the type-name "screen" must be defined.
549                // Note, qualifiers on the typedef are superfluous for the forward declaration.
550                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( tyDecl->get_base() ) ) {
551                        return new StructDecl( aggDecl->get_name() );
552                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( tyDecl->get_base() ) ) {
553                        return new UnionDecl( aggDecl->get_name() );
554                } else {
555                        return ret;
556                } // if
557        }
558
559        TypeDecl *EliminateTypedef::mutate( TypeDecl * typeDecl ) {
560                TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
561                if ( i != typedefNames.end() ) {
562                        typedefNames.erase( i ) ;
563                } // if
564                return typeDecl;
565        }
566
567        DeclarationWithType *EliminateTypedef::mutate( FunctionDecl * funcDecl ) {
568                TypedefMap oldNames = typedefNames;
569                DeclarationWithType *ret = Mutator::mutate( funcDecl );
570                typedefNames = oldNames;
571                return ret;
572        }
573
574        DeclarationWithType *EliminateTypedef::mutate( ObjectDecl * objDecl ) {
575                TypedefMap oldNames = typedefNames;
576                DeclarationWithType *ret = Mutator::mutate( objDecl );
577                typedefNames = oldNames;
578                // is the type a function?
579                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( ret->get_type() ) ) {
580                        // replace the current object declaration with a function declaration
581                        return new FunctionDecl( ret->get_name(), ret->get_storageClass(), ret->get_linkage(), funtype, 0, ret->get_isInline(), ret->get_isNoreturn() );
582                } else if ( objDecl->get_isInline() || objDecl->get_isNoreturn() ) {
583                        throw SemanticError( "invalid inline or _Noreturn specification in declaration of ", objDecl );
584                } // if
585                return ret;
586        }
587
588        Expression *EliminateTypedef::mutate( CastExpr * castExpr ) {
589                TypedefMap oldNames = typedefNames;
590                Expression *ret = Mutator::mutate( castExpr );
591                typedefNames = oldNames;
592                return ret;
593        }
594
595        CompoundStmt *EliminateTypedef::mutate( CompoundStmt * compoundStmt ) {
596                TypedefMap oldNames = typedefNames;
597                scopeLevel += 1;
598                CompoundStmt *ret = Mutator::mutate( compoundStmt );
599                scopeLevel -= 1;
600                std::list< Statement * >::iterator i = compoundStmt->get_kids().begin();
601                while ( i != compoundStmt->get_kids().end() ) {
602                        std::list< Statement * >::iterator next = i+1;
603                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( *i ) ) {
604                                if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
605                                        delete *i;
606                                        compoundStmt->get_kids().erase( i );
607                                } // if
608                        } // if
609                        i = next;
610                } // while
611                typedefNames = oldNames;
612                return ret;
613        }
614
615        // there may be typedefs nested within aggregates in order for everything to work properly, these should be removed
616        // as well
617        template<typename AggDecl>
618        AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
619                std::list<Declaration *>::iterator it = aggDecl->get_members().begin();
620                for ( ; it != aggDecl->get_members().end(); ) {
621                        std::list< Declaration * >::iterator next = it+1;
622                        if ( dynamic_cast< TypedefDecl * >( *it ) ) {
623                                delete *it;
624                                aggDecl->get_members().erase( it );
625                        } // if
626                        it = next;
627                }
628                return aggDecl;
629        }
630
631        template<typename AggDecl>
632        void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
633                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
634                        Type *type;
635                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
636                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
637                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
638                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
639                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
640                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
641                        } // if
642                        TypedefDecl * tyDecl = new TypedefDecl( aggDecl->get_name(), DeclarationNode::NoStorageClass, type );
643                        typedefNames[ aggDecl->get_name() ] = std::make_pair( tyDecl, scopeLevel );
644                } // if
645        }
646        Declaration *EliminateTypedef::mutate( StructDecl * structDecl ) {
647                addImplicitTypedef( structDecl );
648                Mutator::mutate( structDecl );
649                return handleAggregate( structDecl );
650        }
651
652        Declaration *EliminateTypedef::mutate( UnionDecl * unionDecl ) {
653                addImplicitTypedef( unionDecl );
654                Mutator::mutate( unionDecl );
655                return handleAggregate( unionDecl );
656        }
657
658        Declaration *EliminateTypedef::mutate( EnumDecl * enumDecl ) {
659                addImplicitTypedef( enumDecl );
660                Mutator::mutate( enumDecl );
661                return handleAggregate( enumDecl );
662        }
663
664        Declaration *EliminateTypedef::mutate( TraitDecl * contextDecl ) {
665                Mutator::mutate( contextDecl );
666                return handleAggregate( contextDecl );
667        }
668
669        void VerifyCtorDtor::verify( std::list< Declaration * > & translationUnit ) {
670                VerifyCtorDtor verifier;
671                acceptAll( translationUnit, verifier );
672        }
673
674        void VerifyCtorDtor::visit( FunctionDecl * funcDecl ) {
675                FunctionType * funcType = funcDecl->get_functionType();
676                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
677                std::list< DeclarationWithType * > &params = funcType->get_parameters();
678
679                if ( funcDecl->get_name() == "?{}" || funcDecl->get_name() == "^?{}" ) {
680                        if ( params.size() == 0 ) {
681                                throw SemanticError( "Constructors and destructors require at least one parameter ", funcDecl );
682                        }
683                        if ( ! dynamic_cast< PointerType * >( params.front()->get_type() ) ) {
684                                throw SemanticError( "First parameter of a constructor or destructor must be a pointer ", funcDecl );
685                        }
686                        if ( returnVals.size() != 0 ) {
687                                throw SemanticError( "Constructors and destructors cannot have explicit return values ", funcDecl );
688                        }
689                }
690
691                Visitor::visit( funcDecl );
692                // original idea: modify signature of ctor/dtors and insert appropriate return statements
693                // to cause desired behaviour
694                // new idea: add comma exprs to every ctor call to produce first parameter.
695                // this requires some memoization of the first parameter, because it can be a
696                // complicated expression with side effects (see: malloc). idea: add temporary variable
697                // that is assigned address of constructed object in ctor argument position and
698                // return the temporary. It should also be done after all implicit ctors are
699                // added, so not in this pass!
700        }
701
702        DeclarationWithType * CompoundLiteral::mutate( ObjectDecl *objectDecl ) {
703                storageclass = objectDecl->get_storageClass();
704                DeclarationWithType * temp = Mutator::mutate( objectDecl );
705                storageclass = DeclarationNode::NoStorageClass;
706                return temp;
707        }
708
709        Expression *CompoundLiteral::mutate( CompoundLiteralExpr *compLitExpr ) {
710                // transform [storage_class] ... (struct S){ 3, ... };
711                // into [storage_class] struct S temp =  { 3, ... };
712                static UniqueName indexName( "_compLit" );
713
714                ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageclass, LinkageSpec::C, 0, compLitExpr->get_type(), compLitExpr->get_initializer() );
715                compLitExpr->set_type( 0 );
716                compLitExpr->set_initializer( 0 );
717                delete compLitExpr;
718                DeclarationWithType * newtempvar = mutate( tempvar );
719                addDeclaration( newtempvar );                                   // add modified temporary to current block
720                return new VariableExpr( newtempvar );
721        }
722} // namespace SymTab
723
724// Local Variables: //
725// tab-width: 4 //
726// mode: c++ //
727// compile-command: "make install" //
728// End: //
Note: See TracBrowser for help on using the repository browser.