source: src/SymTab/Validate.cc @ 1486116

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 1486116 was cce9429, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

fix function return type in Validate and add single return decl, construct the return decl, fix polymorphic functions to use the return decl

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