source: src/SymTab/Validate.cc @ daf9671

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 daf9671 was 11ab8ea8, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

add checks for generic type parameter length

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