source: src/SymTab/Indexer.cc @ 2ae171d8

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

Minor clean up

  • Property mode set to 100644
File size: 35.8 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// Indexer.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:37:33 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Aug 17 16:08:40 2017
13// Update Count     : 20
14//
15
16#include "Indexer.h"
17
18#include <cassert>                 // for assert, safe_dynamic_cast
19#include <iostream>                // for operator<<, basic_ostream, ostream
20#include <string>                  // for string, operator<<, operator!=
21#include <unordered_map>           // for operator!=, unordered_map<>::const...
22#include <unordered_set>           // for unordered_set
23#include <utility>                 // for pair, make_pair, move
24
25#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
26#include "Common/SemanticError.h"  // for SemanticError
27#include "Common/utility.h"        // for cloneAll
28#include "InitTweak/InitTweak.h"   // for isConstructor, isCopyFunction, isC...
29#include "Mangler.h"               // for Mangler
30#include "Parser/LinkageSpec.h"    // for isMangled, isOverridable, Spec
31#include "ResolvExpr/typeops.h"    // for typesCompatible
32#include "SynTree/Constant.h"      // for Constant
33#include "SynTree/Declaration.h"   // for DeclarationWithType, FunctionDecl
34#include "SynTree/Expression.h"    // for Expression, ImplicitCopyCtorExpr
35#include "SynTree/Initializer.h"   // for Initializer
36#include "SynTree/Statement.h"     // for CompoundStmt, Statement, ForStmt (...
37#include "SynTree/Type.h"          // for Type, StructInstType, UnionInstType
38
39#define debugPrint(x) if ( doDebug ) { std::cout << x; }
40
41namespace SymTab {
42        struct NewScope {
43                NewScope( SymTab::Indexer & indexer ) : indexer( indexer ) { indexer.enterScope(); }
44                ~NewScope() { indexer.leaveScope(); }
45                SymTab::Indexer & indexer;
46        };
47
48        template< typename TreeType, typename VisitorType >
49        inline void acceptNewScope( TreeType *tree, VisitorType &visitor ) {
50                visitor.enterScope();
51                maybeAccept( tree, visitor );
52                visitor.leaveScope();
53        }
54
55        typedef std::unordered_map< std::string, DeclarationWithType* > MangleTable;
56        typedef std::unordered_map< std::string, MangleTable > IdTable;
57        typedef std::unordered_map< std::string, NamedTypeDecl* > TypeTable;
58        typedef std::unordered_map< std::string, StructDecl* > StructTable;
59        typedef std::unordered_map< std::string, EnumDecl* > EnumTable;
60        typedef std::unordered_map< std::string, UnionDecl* > UnionTable;
61        typedef std::unordered_map< std::string, TraitDecl* > TraitTable;
62
63        void dump( const IdTable &table, std::ostream &os ) {
64                for ( IdTable::const_iterator id = table.begin(); id != table.end(); ++id ) {
65                        for ( MangleTable::const_iterator mangle = id->second.begin(); mangle != id->second.end(); ++mangle ) {
66                                os << mangle->second << std::endl;
67                        }
68                }
69        }
70
71        template< typename Decl >
72        void dump( const std::unordered_map< std::string, Decl* > &table, std::ostream &os ) {
73                for ( typename std::unordered_map< std::string, Decl* >::const_iterator it = table.begin(); it != table.end(); ++it ) {
74                        os << it->second << std::endl;
75                } // for
76        }
77
78        struct Indexer::Impl {
79                Impl( unsigned long _scope ) : refCount(1), scope( _scope ), size( 0 ), base(),
80                                idTable(), typeTable(), structTable(), enumTable(), unionTable(), traitTable() {}
81                Impl( unsigned long _scope, Indexer &&_base ) : refCount(1), scope( _scope ), size( 0 ), base( _base ),
82                                idTable(), typeTable(), structTable(), enumTable(), unionTable(), traitTable() {}
83                unsigned long refCount;   ///< Number of references to these tables
84                unsigned long scope;      ///< Scope these tables are associated with
85                unsigned long size;       ///< Number of elements stored in this table
86                const Indexer base;       ///< Base indexer this extends
87
88                IdTable idTable;          ///< Identifier namespace
89                TypeTable typeTable;      ///< Type namespace
90                StructTable structTable;  ///< Struct namespace
91                EnumTable enumTable;      ///< Enum namespace
92                UnionTable unionTable;    ///< Union namespace
93                TraitTable traitTable;    ///< Trait namespace
94        };
95
96        Indexer::Impl *Indexer::newRef( Indexer::Impl *toClone ) {
97                if ( ! toClone ) return 0;
98
99                // shorten the search chain by skipping empty links
100                Indexer::Impl *ret = toClone->size == 0 ? toClone->base.tables : toClone;
101                if ( ret ) { ++ret->refCount; }
102
103                return ret;
104        }
105
106        void Indexer::deleteRef( Indexer::Impl *toFree ) {
107                if ( ! toFree ) return;
108
109                if ( --toFree->refCount == 0 ) delete toFree;
110        }
111
112        void Indexer::removeSpecialOverrides( const std::string &id, std::list< DeclarationWithType * > & out ) const {
113                // only need to perform this step for constructors, destructors, and assignment functions
114                if ( ! CodeGen::isCtorDtorAssign( id ) ) return;
115
116                // helpful data structure
117                struct ValueType {
118                        struct DeclBall {
119                                FunctionDecl * decl;
120                                bool isUserDefinedFunc; // properties for this particular decl
121                                bool isDefaultCtor;
122                                bool isDtor;
123                                bool isCopyFunc;
124                        };
125                        // properties for this type
126                        bool existsUserDefinedFunc = false;    // any user-defined function found
127                        bool existsUserDefinedCtor = false;    // any user-defined constructor found
128                        bool existsUserDefinedDtor = false;    // any user-defined destructor found
129                        bool existsUserDefinedCopyFunc = false;    // user-defined copy ctor found
130                        bool existsUserDefinedDefaultCtor = false; // user-defined default ctor found
131                        std::list< DeclBall > decls;
132
133                        // another FunctionDecl for the current type was found - determine
134                        // if it has special properties and update data structure accordingly
135                        ValueType & operator+=( FunctionDecl * function ) {
136                                bool isUserDefinedFunc = ! LinkageSpec::isOverridable( function->get_linkage() );
137                                bool isDefaultCtor = InitTweak::isDefaultConstructor( function );
138                                bool isDtor = InitTweak::isDestructor( function );
139                                bool isCopyFunc = InitTweak::isCopyFunction( function, function->get_name() );
140                                decls.push_back( DeclBall{ function, isUserDefinedFunc, isDefaultCtor, isDtor, isCopyFunc } );
141                                existsUserDefinedFunc = existsUserDefinedFunc || isUserDefinedFunc;
142                                existsUserDefinedCtor = existsUserDefinedCtor || (isUserDefinedFunc && CodeGen::isConstructor( function->get_name() ) );
143                                existsUserDefinedDtor = existsUserDefinedDtor || (isUserDefinedFunc && isDtor);
144                                existsUserDefinedCopyFunc = existsUserDefinedCopyFunc || (isUserDefinedFunc && isCopyFunc);
145                                existsUserDefinedDefaultCtor = existsUserDefinedDefaultCtor || (isUserDefinedFunc && isDefaultCtor);
146                                return *this;
147                        }
148                }; // ValueType
149
150                std::list< DeclarationWithType * > copy;
151                copy.splice( copy.end(), out );
152
153                // organize discovered declarations by type
154                std::unordered_map< std::string, ValueType > funcMap;
155                for ( DeclarationWithType * decl : copy ) {
156                        if ( FunctionDecl * function = dynamic_cast< FunctionDecl * >( decl ) ) {
157                                std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
158                                assert( ! params.empty() );
159                                // use base type of pointer, so that qualifiers on the pointer type aren't considered.
160                                Type * base = InitTweak::getPointerBase( params.front()->get_type() );
161                                assert( base );
162                                funcMap[ Mangler::mangle( base ) ] += function;
163                        } else {
164                                out.push_back( decl );
165                        }
166                }
167
168                // if a type contains user defined ctor/dtor/assign, then special rules trigger, which determine
169                // the set of ctor/dtor/assign that are seen by the requester. In particular, if the user defines
170                // a default ctor, then the generated default ctor should never be seen, likewise for copy ctor
171                // and dtor. If the user defines any ctor/dtor, then no generated field ctors should be seen.
172                // If the user defines any ctor then the generated default ctor should not be seen (intrinsic default
173                // ctor must be overridden exactly).
174                for ( std::pair< const std::string, ValueType > & pair : funcMap ) {
175                        ValueType & val = pair.second;
176                        for ( ValueType::DeclBall ball : val.decls ) {
177                                bool noUserDefinedFunc = ! val.existsUserDefinedFunc;
178                                bool isUserDefinedFunc = ball.isUserDefinedFunc;
179                                bool isAcceptableDefaultCtor = (! val.existsUserDefinedCtor || (! val.existsUserDefinedDefaultCtor && ball.decl->get_linkage() == LinkageSpec::Intrinsic)) && ball.isDefaultCtor; // allow default constructors only when no user-defined constructors exist, except in the case of intrinsics, which require exact overrides
180                                bool isAcceptableCopyFunc = ! val.existsUserDefinedCopyFunc && ball.isCopyFunc; // handles copy ctor and assignment operator
181                                bool isAcceptableDtor = ! val.existsUserDefinedDtor && ball.isDtor;
182                                if ( noUserDefinedFunc || isUserDefinedFunc || isAcceptableDefaultCtor || isAcceptableCopyFunc || isAcceptableDtor ) {
183                                        // decl conforms to the rules described above, so it should be seen by the requester
184                                        out.push_back( ball.decl );
185                                }
186                        }
187                }
188        }
189
190        void Indexer::makeWritable() {
191                if ( ! tables ) {
192                        // create indexer if not yet set
193                        tables = new Indexer::Impl( scope );
194                } else if ( tables->refCount > 1 || tables->scope != scope ) {
195                        // make this indexer the base of a fresh indexer at the current scope
196                        tables = new Indexer::Impl( scope, std::move( *this ) );
197                }
198        }
199
200        Indexer::Indexer( bool _doDebug ) : tables( 0 ), scope( 0 ), doDebug( _doDebug ) {}
201
202        Indexer::Indexer( const Indexer &that ) : tables( newRef( that.tables ) ), scope( that.scope ), doDebug( that.doDebug ) {}
203
204        Indexer::Indexer( Indexer &&that ) : tables( that.tables ), scope( that.scope ), doDebug( that.doDebug ) {
205                that.tables = 0;
206        }
207
208        Indexer::~Indexer() {
209                deleteRef( tables );
210        }
211
212        Indexer& Indexer::operator= ( const Indexer &that ) {
213                deleteRef( tables );
214
215                tables = newRef( that.tables );
216                scope = that.scope;
217                doDebug = that.doDebug;
218
219                return *this;
220        }
221
222        Indexer& Indexer::operator= ( Indexer &&that ) {
223                deleteRef( tables );
224
225                tables = that.tables;
226                scope = that.scope;
227                doDebug = that.doDebug;
228
229                that.tables = 0;
230
231                return *this;
232        }
233
234        void Indexer::visit( ObjectDecl *objectDecl ) {
235                enterScope();
236                maybeAccept( objectDecl->get_type(), *this );
237                leaveScope();
238                maybeAccept( objectDecl->get_init(), *this );
239                maybeAccept( objectDecl->get_bitfieldWidth(), *this );
240                if ( objectDecl->get_name() != "" ) {
241                        debugPrint( "Adding object " << objectDecl->get_name() << std::endl );
242                        addId( objectDecl );
243                } // if
244        }
245
246        void Indexer::visit( FunctionDecl *functionDecl ) {
247                if ( functionDecl->get_name() == "" ) return;
248                debugPrint( "Adding function " << functionDecl->get_name() << std::endl );
249                addId( functionDecl );
250                enterScope();
251                maybeAccept( functionDecl->get_functionType(), *this );
252                maybeAccept( functionDecl->get_statements(), *this );
253                leaveScope();
254        }
255
256
257// A NOTE ON THE ORDER OF TRAVERSAL
258//
259// Types and typedefs have their base types visited before they are added to the type table.  This is ok, since there is
260// no such thing as a recursive type or typedef.
261//
262//             typedef struct { T *x; } T; // never allowed
263//
264// for structs/unions, it is possible to have recursion, so the decl should be added as if it's incomplete to begin, the
265// members are traversed, and then the complete type should be added (assuming the type is completed by this particular
266// declaration).
267//
268//             struct T { struct T *x; }; // allowed
269//
270// It is important to add the complete type to the symbol table *after* the members/base has been traversed, since that
271// traversal may modify the definition of the type and these modifications should be visible when the symbol table is
272// queried later in this pass.
273//
274// TODO: figure out whether recursive contexts are sensible/possible/reasonable.
275
276
277        void Indexer::visit( TypeDecl *typeDecl ) {
278                // see A NOTE ON THE ORDER OF TRAVERSAL, above
279                // note that assertions come after the type is added to the symtab, since they are not part of the type proper
280                // and may depend on the type itself
281                enterScope();
282                acceptAll( typeDecl->get_parameters(), *this );
283                maybeAccept( typeDecl->get_base(), *this );
284                leaveScope();
285                debugPrint( "Adding type " << typeDecl->get_name() << std::endl );
286                addType( typeDecl );
287                acceptAll( typeDecl->get_assertions(), *this );
288                acceptNewScope( typeDecl->get_init(), *this );
289        }
290
291        void Indexer::visit( TypedefDecl *typeDecl ) {
292                enterScope();
293                acceptAll( typeDecl->get_parameters(), *this );
294                maybeAccept( typeDecl->get_base(), *this );
295                leaveScope();
296                debugPrint( "Adding typedef " << typeDecl->get_name() << std::endl );
297                addType( typeDecl );
298        }
299
300        void Indexer::visit( StructDecl *aggregateDecl ) {
301                // make up a forward declaration and add it before processing the members
302                // needs to be on the heap because addStruct saves the pointer
303                StructDecl &fwdDecl = *new StructDecl( aggregateDecl->get_name() );
304                cloneAll( aggregateDecl->get_parameters(), fwdDecl.get_parameters() );
305                debugPrint( "Adding fwd decl for struct " << fwdDecl.get_name() << std::endl );
306                addStruct( &fwdDecl );
307
308                enterScope();
309                acceptAll( aggregateDecl->get_parameters(), *this );
310                acceptAll( aggregateDecl->get_members(), *this );
311                leaveScope();
312
313                debugPrint( "Adding struct " << aggregateDecl->get_name() << std::endl );
314                // this addition replaces the forward declaration
315                addStruct( aggregateDecl );
316        }
317
318        void Indexer::visit( UnionDecl *aggregateDecl ) {
319                // make up a forward declaration and add it before processing the members
320                UnionDecl fwdDecl( aggregateDecl->get_name() );
321                cloneAll( aggregateDecl->get_parameters(), fwdDecl.get_parameters() );
322                debugPrint( "Adding fwd decl for union " << fwdDecl.get_name() << std::endl );
323                addUnion( &fwdDecl );
324
325                enterScope();
326                acceptAll( aggregateDecl->get_parameters(), *this );
327                acceptAll( aggregateDecl->get_members(), *this );
328                leaveScope();
329
330                debugPrint( "Adding union " << aggregateDecl->get_name() << std::endl );
331                addUnion( aggregateDecl );
332        }
333
334        void Indexer::visit( EnumDecl *aggregateDecl ) {
335                debugPrint( "Adding enum " << aggregateDecl->get_name() << std::endl );
336                addEnum( aggregateDecl );
337                // unlike structs, contexts, and unions, enums inject their members into the global scope
338                acceptAll( aggregateDecl->get_members(), *this );
339        }
340
341        void Indexer::visit( TraitDecl *aggregateDecl ) {
342                enterScope();
343                acceptAll( aggregateDecl->get_parameters(), *this );
344                acceptAll( aggregateDecl->get_members(), *this );
345                leaveScope();
346
347                debugPrint( "Adding trait " << aggregateDecl->get_name() << std::endl );
348                addTrait( aggregateDecl );
349        }
350
351        void Indexer::visit( CompoundStmt *compoundStmt ) {
352                enterScope();
353                acceptAll( compoundStmt->get_kids(), *this );
354                leaveScope();
355        }
356
357        void Indexer::visit( IfStmt *ifStmt ) {
358            // for statements introduce a level of scope
359            enterScope();
360            Visitor::visit( ifStmt );
361            leaveScope();
362        }
363
364        void Indexer::visit( ForStmt *forStmt ) {
365            // for statements introduce a level of scope
366            enterScope();
367            Visitor::visit( forStmt );
368            leaveScope();
369        }
370
371        void Indexer::visit( CatchStmt *catchStmt ) {
372                // catch statements introduce a level of scope (for the caught exception)
373                enterScope();
374                Visitor::visit( catchStmt );
375                leaveScope();
376        }
377
378        void Indexer::visit( ApplicationExpr *applicationExpr ) {
379                acceptNewScope( applicationExpr->get_result(), *this );
380                maybeAccept( applicationExpr->get_function(), *this );
381                acceptAll( applicationExpr->get_args(), *this );
382        }
383
384        void Indexer::visit( UntypedExpr *untypedExpr ) {
385                acceptNewScope( untypedExpr->get_result(), *this );
386                acceptAll( untypedExpr->get_args(), *this );
387        }
388
389        void Indexer::visit( NameExpr *nameExpr ) {
390                acceptNewScope( nameExpr->get_result(), *this );
391        }
392
393        void Indexer::visit( AddressExpr *addressExpr ) {
394                acceptNewScope( addressExpr->get_result(), *this );
395                maybeAccept( addressExpr->get_arg(), *this );
396        }
397
398        void Indexer::visit( LabelAddressExpr *labAddressExpr ) {
399                acceptNewScope( labAddressExpr->get_result(), *this );
400                maybeAccept( labAddressExpr->get_arg(), *this );
401        }
402
403        void Indexer::visit( CastExpr *castExpr ) {
404                acceptNewScope( castExpr->get_result(), *this );
405                maybeAccept( castExpr->get_arg(), *this );
406        }
407
408        void Indexer::visit( UntypedMemberExpr *memberExpr ) {
409                acceptNewScope( memberExpr->get_result(), *this );
410                maybeAccept( memberExpr->get_aggregate(), *this );
411        }
412
413        void Indexer::visit( MemberExpr *memberExpr ) {
414                acceptNewScope( memberExpr->get_result(), *this );
415                maybeAccept( memberExpr->get_aggregate(), *this );
416        }
417
418        void Indexer::visit( VariableExpr *variableExpr ) {
419                acceptNewScope( variableExpr->get_result(), *this );
420        }
421
422        void Indexer::visit( ConstantExpr *constantExpr ) {
423                acceptNewScope( constantExpr->get_result(), *this );
424                maybeAccept( constantExpr->get_constant(), *this );
425        }
426
427        void Indexer::visit( SizeofExpr *sizeofExpr ) {
428                acceptNewScope( sizeofExpr->get_result(), *this );
429                if ( sizeofExpr->get_isType() ) {
430                        maybeAccept( sizeofExpr->get_type(), *this );
431                } else {
432                        maybeAccept( sizeofExpr->get_expr(), *this );
433                }
434        }
435
436        void Indexer::visit( AlignofExpr *alignofExpr ) {
437                acceptNewScope( alignofExpr->get_result(), *this );
438                if ( alignofExpr->get_isType() ) {
439                        maybeAccept( alignofExpr->get_type(), *this );
440                } else {
441                        maybeAccept( alignofExpr->get_expr(), *this );
442                }
443        }
444
445        void Indexer::visit( UntypedOffsetofExpr *offsetofExpr ) {
446                acceptNewScope( offsetofExpr->get_result(), *this );
447                maybeAccept( offsetofExpr->get_type(), *this );
448        }
449
450        void Indexer::visit( OffsetofExpr *offsetofExpr ) {
451                acceptNewScope( offsetofExpr->get_result(), *this );
452                maybeAccept( offsetofExpr->get_type(), *this );
453                maybeAccept( offsetofExpr->get_member(), *this );
454        }
455
456        void Indexer::visit( OffsetPackExpr *offsetPackExpr ) {
457                acceptNewScope( offsetPackExpr->get_result(), *this );
458                maybeAccept( offsetPackExpr->get_type(), *this );
459        }
460
461        void Indexer::visit( AttrExpr *attrExpr ) {
462                acceptNewScope( attrExpr->get_result(), *this );
463                if ( attrExpr->get_isType() ) {
464                        maybeAccept( attrExpr->get_type(), *this );
465                } else {
466                        maybeAccept( attrExpr->get_expr(), *this );
467                }
468        }
469
470        void Indexer::visit( LogicalExpr *logicalExpr ) {
471                acceptNewScope( logicalExpr->get_result(), *this );
472                maybeAccept( logicalExpr->get_arg1(), *this );
473                maybeAccept( logicalExpr->get_arg2(), *this );
474        }
475
476        void Indexer::visit( ConditionalExpr *conditionalExpr ) {
477                acceptNewScope( conditionalExpr->get_result(), *this );
478                maybeAccept( conditionalExpr->get_arg1(), *this );
479                maybeAccept( conditionalExpr->get_arg2(), *this );
480                maybeAccept( conditionalExpr->get_arg3(), *this );
481        }
482
483        void Indexer::visit( CommaExpr *commaExpr ) {
484                acceptNewScope( commaExpr->get_result(), *this );
485                maybeAccept( commaExpr->get_arg1(), *this );
486                maybeAccept( commaExpr->get_arg2(), *this );
487        }
488
489        void Indexer::visit( TypeExpr *typeExpr ) {
490                acceptNewScope( typeExpr->get_result(), *this );
491                maybeAccept( typeExpr->get_type(), *this );
492        }
493
494        void Indexer::visit( AsmExpr *asmExpr ) {
495                maybeAccept( asmExpr->get_inout(), *this );
496                maybeAccept( asmExpr->get_constraint(), *this );
497                maybeAccept( asmExpr->get_operand(), *this );
498        }
499
500        void Indexer::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
501                acceptNewScope( impCpCtorExpr->get_result(), *this );
502                maybeAccept( impCpCtorExpr->get_callExpr(), *this );
503                acceptAll( impCpCtorExpr->get_tempDecls(), *this );
504                acceptAll( impCpCtorExpr->get_returnDecls(), *this );
505                acceptAll( impCpCtorExpr->get_dtors(), *this );
506        }
507
508        void Indexer::visit( ConstructorExpr * ctorExpr ) {
509                acceptNewScope( ctorExpr->get_result(), *this );
510                maybeAccept( ctorExpr->get_callExpr(), *this );
511        }
512
513        void Indexer::visit( CompoundLiteralExpr *compLitExpr ) {
514                acceptNewScope( compLitExpr->get_result(), *this );
515                maybeAccept( compLitExpr->get_initializer(), *this );
516        }
517
518        void Indexer::visit( RangeExpr *rangeExpr ) {
519                maybeAccept( rangeExpr->get_low(), *this );
520                maybeAccept( rangeExpr->get_high(), *this );
521        }
522
523        void Indexer::visit( UntypedTupleExpr *tupleExpr ) {
524                acceptNewScope( tupleExpr->get_result(), *this );
525                acceptAll( tupleExpr->get_exprs(), *this );
526        }
527
528        void Indexer::visit( TupleExpr *tupleExpr ) {
529                acceptNewScope( tupleExpr->get_result(), *this );
530                acceptAll( tupleExpr->get_exprs(), *this );
531        }
532
533        void Indexer::visit( TupleIndexExpr *tupleExpr ) {
534                acceptNewScope( tupleExpr->get_result(), *this );
535                maybeAccept( tupleExpr->get_tuple(), *this );
536        }
537
538        void Indexer::visit( TupleAssignExpr *tupleExpr ) {
539                acceptNewScope( tupleExpr->get_result(), *this );
540                maybeAccept( tupleExpr->get_stmtExpr(), *this );
541        }
542
543        void Indexer::visit( StmtExpr *stmtExpr ) {
544                acceptNewScope( stmtExpr->get_result(), *this );
545                maybeAccept( stmtExpr->get_statements(), *this );
546                acceptAll( stmtExpr->get_returnDecls(), *this );
547                acceptAll( stmtExpr->get_dtors(), *this );
548        }
549
550        void Indexer::visit( UniqueExpr *uniqueExpr ) {
551                acceptNewScope( uniqueExpr->get_result(), *this );
552                maybeAccept( uniqueExpr->get_expr(), *this );
553        }
554
555
556        void Indexer::visit( TraitInstType *contextInst ) {
557                acceptAll( contextInst->get_parameters(), *this );
558                acceptAll( contextInst->get_members(), *this );
559        }
560
561        void Indexer::visit( StructInstType *structInst ) {
562                if ( ! lookupStruct( structInst->get_name() ) ) {
563                        debugPrint( "Adding struct " << structInst->get_name() << " from implicit forward declaration" << std::endl );
564                        addStruct( structInst->get_name() );
565                }
566                enterScope();
567                acceptAll( structInst->get_parameters(), *this );
568                leaveScope();
569        }
570
571        void Indexer::visit( UnionInstType *unionInst ) {
572                if ( ! lookupUnion( unionInst->get_name() ) ) {
573                        debugPrint( "Adding union " << unionInst->get_name() << " from implicit forward declaration" << std::endl );
574                        addUnion( unionInst->get_name() );
575                }
576                enterScope();
577                acceptAll( unionInst->get_parameters(), *this );
578                leaveScope();
579        }
580
581        void Indexer::lookupId( const std::string &id, std::list< DeclarationWithType* > &out ) const {
582                std::unordered_set< std::string > foundMangleNames;
583
584                Indexer::Impl *searchTables = tables;
585                while ( searchTables ) {
586
587                        IdTable::const_iterator decls = searchTables->idTable.find( id );
588                        if ( decls != searchTables->idTable.end() ) {
589                                const MangleTable &mangleTable = decls->second;
590                                for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
591                                        // mark the mangled name as found, skipping this insertion if a declaration for that name has already been found
592                                        if ( foundMangleNames.insert( decl->first ).second == false ) continue;
593
594                                        out.push_back( decl->second );
595                                }
596                        }
597
598                        // get declarations from base indexers
599                        searchTables = searchTables->base.tables;
600                }
601
602                // some special functions, e.g. constructors and destructors
603                // remove autogenerated functions when they are defined so that
604                // they can never be matched
605                removeSpecialOverrides( id, out );
606        }
607
608        NamedTypeDecl *Indexer::lookupType( const std::string &id ) const {
609                if ( ! tables ) return 0;
610
611                TypeTable::const_iterator ret = tables->typeTable.find( id );
612                return ret != tables->typeTable.end() ? ret->second : tables->base.lookupType( id );
613        }
614
615        StructDecl *Indexer::lookupStruct( const std::string &id ) const {
616                if ( ! tables ) return 0;
617
618                StructTable::const_iterator ret = tables->structTable.find( id );
619                return ret != tables->structTable.end() ? ret->second : tables->base.lookupStruct( id );
620        }
621
622        EnumDecl *Indexer::lookupEnum( const std::string &id ) const {
623                if ( ! tables ) return 0;
624
625                EnumTable::const_iterator ret = tables->enumTable.find( id );
626                return ret != tables->enumTable.end() ? ret->second : tables->base.lookupEnum( id );
627        }
628
629        UnionDecl *Indexer::lookupUnion( const std::string &id ) const {
630                if ( ! tables ) return 0;
631
632                UnionTable::const_iterator ret = tables->unionTable.find( id );
633                return ret != tables->unionTable.end() ? ret->second : tables->base.lookupUnion( id );
634        }
635
636        TraitDecl *Indexer::lookupTrait( const std::string &id ) const {
637                if ( ! tables ) return 0;
638
639                TraitTable::const_iterator ret = tables->traitTable.find( id );
640                return ret != tables->traitTable.end() ? ret->second : tables->base.lookupTrait( id );
641        }
642
643        DeclarationWithType *Indexer::lookupIdAtScope( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
644                if ( ! tables ) return 0;
645                if ( tables->scope < scope ) return 0;
646
647                IdTable::const_iterator decls = tables->idTable.find( id );
648                if ( decls != tables->idTable.end() ) {
649                        const MangleTable &mangleTable = decls->second;
650                        MangleTable::const_iterator decl = mangleTable.find( mangleName );
651                        if ( decl != mangleTable.end() ) return decl->second;
652                }
653
654                return tables->base.lookupIdAtScope( id, mangleName, scope );
655        }
656
657        bool Indexer::hasIncompatibleCDecl( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
658                if ( ! tables ) return false;
659                if ( tables->scope < scope ) return false;
660
661                IdTable::const_iterator decls = tables->idTable.find( id );
662                if ( decls != tables->idTable.end() ) {
663                        const MangleTable &mangleTable = decls->second;
664                        for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
665                                // check for C decls with the same name, skipping those with a compatible type (by mangleName)
666                                if ( ! LinkageSpec::isMangled( decl->second->get_linkage() ) && decl->first != mangleName ) return true;
667                        }
668                }
669
670                return tables->base.hasIncompatibleCDecl( id, mangleName, scope );
671        }
672
673        bool Indexer::hasCompatibleCDecl( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
674                if ( ! tables ) return false;
675                if ( tables->scope < scope ) return false;
676
677                IdTable::const_iterator decls = tables->idTable.find( id );
678                if ( decls != tables->idTable.end() ) {
679                        const MangleTable &mangleTable = decls->second;
680                        for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
681                                // check for C decls with the same name, skipping
682                                // those with an incompatible type (by mangleName)
683                                if ( ! LinkageSpec::isMangled( decl->second->get_linkage() ) && decl->first == mangleName ) return true;
684                        }
685                }
686
687                return tables->base.hasCompatibleCDecl( id, mangleName, scope );
688        }
689
690        NamedTypeDecl *Indexer::lookupTypeAtScope( const std::string &id, unsigned long scope ) const {
691                if ( ! tables ) return 0;
692                if ( tables->scope < scope ) return 0;
693
694                TypeTable::const_iterator ret = tables->typeTable.find( id );
695                return ret != tables->typeTable.end() ? ret->second : tables->base.lookupTypeAtScope( id, scope );
696        }
697
698        StructDecl *Indexer::lookupStructAtScope( const std::string &id, unsigned long scope ) const {
699                if ( ! tables ) return 0;
700                if ( tables->scope < scope ) return 0;
701
702                StructTable::const_iterator ret = tables->structTable.find( id );
703                return ret != tables->structTable.end() ? ret->second : tables->base.lookupStructAtScope( id, scope );
704        }
705
706        EnumDecl *Indexer::lookupEnumAtScope( const std::string &id, unsigned long scope ) const {
707                if ( ! tables ) return 0;
708                if ( tables->scope < scope ) return 0;
709
710                EnumTable::const_iterator ret = tables->enumTable.find( id );
711                return ret != tables->enumTable.end() ? ret->second : tables->base.lookupEnumAtScope( id, scope );
712        }
713
714        UnionDecl *Indexer::lookupUnionAtScope( const std::string &id, unsigned long scope ) const {
715                if ( ! tables ) return 0;
716                if ( tables->scope < scope ) return 0;
717
718                UnionTable::const_iterator ret = tables->unionTable.find( id );
719                return ret != tables->unionTable.end() ? ret->second : tables->base.lookupUnionAtScope( id, scope );
720        }
721
722        TraitDecl *Indexer::lookupTraitAtScope( const std::string &id, unsigned long scope ) const {
723                if ( ! tables ) return 0;
724                if ( tables->scope < scope ) return 0;
725
726                TraitTable::const_iterator ret = tables->traitTable.find( id );
727                return ret != tables->traitTable.end() ? ret->second : tables->base.lookupTraitAtScope( id, scope );
728        }
729
730        bool addedIdConflicts( DeclarationWithType *existing, DeclarationWithType *added ) {
731                // if we're giving the same name mangling to things of different types then there is something wrong
732                assert( (dynamic_cast<ObjectDecl*>( added ) && dynamic_cast<ObjectDecl*>( existing ) )
733                        || (dynamic_cast<FunctionDecl*>( added ) && dynamic_cast<FunctionDecl*>( existing ) ) );
734
735                if ( LinkageSpec::isOverridable( existing->get_linkage() ) ) {
736                        // new definition shadows the autogenerated one, even at the same scope
737                        return false;
738                } else if ( LinkageSpec::isMangled( added->get_linkage() ) || ResolvExpr::typesCompatible( added->get_type(), existing->get_type(), Indexer() ) ) {
739                        // typesCompatible doesn't really do the right thing here. When checking compatibility of function types,
740                        // we should ignore outermost pointer qualifiers, except _Atomic?
741                        FunctionDecl *newentry = dynamic_cast< FunctionDecl* >( added );
742                        FunctionDecl *oldentry = dynamic_cast< FunctionDecl* >( existing );
743                        if ( newentry && oldentry ) {
744                                if ( newentry->get_statements() && oldentry->get_statements() ) {
745                                        throw SemanticError( "duplicate function definition for ", added );
746                                } // if
747                        } else {
748                                // two objects with the same mangled name defined in the same scope.
749                                // both objects must be marked extern or both must be intrinsic for this to be okay
750                                // xxx - perhaps it's actually if either is intrinsic then this is okay?
751                                //       might also need to be same storage class?
752                                ObjectDecl *newobj = dynamic_cast< ObjectDecl* >( added );
753                                ObjectDecl *oldobj = dynamic_cast< ObjectDecl* >( existing );
754                                if ( ! newobj->get_storageClasses().is_extern && ! oldobj->get_storageClasses().is_extern ) {
755                                        throw SemanticError( "duplicate object definition for ", added );
756                                } // if
757                        } // if
758                } else {
759                        throw SemanticError( "duplicate definition for ", added );
760                } // if
761
762                return true;
763        }
764
765        void Indexer::addId( DeclarationWithType *decl ) {
766                makeWritable();
767
768                const std::string &name = decl->get_name();
769                std::string mangleName;
770                if ( LinkageSpec::isOverridable( decl->get_linkage() ) ) {
771                        // mangle the name without including the appropriate suffix, so overridable routines are placed into the
772                        // same "bucket" as their user defined versions.
773                        mangleName = Mangler::mangle( decl, false );
774                } else {
775                        mangleName = Mangler::mangle( decl );
776                } // if
777
778                // this ensures that no two declarations with the same unmangled name at the same scope both have C linkage
779                if ( ! LinkageSpec::isMangled( decl->get_linkage() ) ) {
780                        // NOTE this is broken in Richard's original code in such a way that it never triggers (it
781                        // doesn't check decls that have the same manglename, and all C-linkage decls are defined to
782                        // have their name as their manglename, hence the error can never trigger).
783                        // The code here is closer to correct, but name mangling would have to be completely
784                        // isomorphic to C type-compatibility, which it may not be.
785                        if ( hasIncompatibleCDecl( name, mangleName, scope ) ) {
786                                throw SemanticError( "conflicting overload of C function ", decl );
787                        }
788                } else {
789                        // Check that a Cforall declaration doesn't overload any C declaration
790                        if ( hasCompatibleCDecl( name, mangleName, scope ) ) {
791                                throw SemanticError( "Cforall declaration hides C function ", decl );
792                        }
793                }
794
795                // Skip repeat declarations of the same identifier
796                DeclarationWithType *existing = lookupIdAtScope( name, mangleName, scope );
797                if ( existing && addedIdConflicts( existing, decl ) ) return;
798
799                // add to indexer
800                tables->idTable[ name ][ mangleName ] = decl;
801                ++tables->size;
802        }
803
804        bool addedTypeConflicts( NamedTypeDecl *existing, NamedTypeDecl *added ) {
805                if ( existing->get_base() == 0 ) {
806                        return false;
807                } else if ( added->get_base() == 0 ) {
808                        return true;
809                } else {
810                        throw SemanticError( "redeclaration of ", added );
811                }
812        }
813
814        void Indexer::addType( NamedTypeDecl *decl ) {
815                makeWritable();
816
817                const std::string &id = decl->get_name();
818                TypeTable::iterator existing = tables->typeTable.find( id );
819                if ( existing == tables->typeTable.end() ) {
820                        NamedTypeDecl *parent = tables->base.lookupTypeAtScope( id, scope );
821                        if ( ! parent || ! addedTypeConflicts( parent, decl ) ) {
822                                tables->typeTable.insert( existing, std::make_pair( id, decl ) );
823                                ++tables->size;
824                        }
825                } else {
826                        if ( ! addedTypeConflicts( existing->second, decl ) ) {
827                                existing->second = decl;
828                        }
829                }
830        }
831
832        bool addedDeclConflicts( AggregateDecl *existing, AggregateDecl *added ) {
833                if ( existing->get_members().empty() ) {
834                        return false;
835                } else if ( ! added->get_members().empty() ) {
836                        throw SemanticError( "redeclaration of ", added );
837                } // if
838                return true;
839        }
840
841        void Indexer::addStruct( const std::string &id ) {
842                addStruct( new StructDecl( id ) );
843        }
844
845        void Indexer::addStruct( StructDecl *decl ) {
846                makeWritable();
847
848                const std::string &id = decl->get_name();
849                StructTable::iterator existing = tables->structTable.find( id );
850                if ( existing == tables->structTable.end() ) {
851                        StructDecl *parent = tables->base.lookupStructAtScope( id, scope );
852                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
853                                tables->structTable.insert( existing, std::make_pair( id, decl ) );
854                                ++tables->size;
855                        }
856                } else {
857                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
858                                existing->second = decl;
859                        }
860                }
861        }
862
863        void Indexer::addEnum( EnumDecl *decl ) {
864                makeWritable();
865
866                const std::string &id = decl->get_name();
867                EnumTable::iterator existing = tables->enumTable.find( id );
868                if ( existing == tables->enumTable.end() ) {
869                        EnumDecl *parent = tables->base.lookupEnumAtScope( id, scope );
870                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
871                                tables->enumTable.insert( existing, std::make_pair( id, decl ) );
872                                ++tables->size;
873                        }
874                } else {
875                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
876                                existing->second = decl;
877                        }
878                }
879        }
880
881        void Indexer::addUnion( const std::string &id ) {
882                addUnion( new UnionDecl( id ) );
883        }
884
885        void Indexer::addUnion( UnionDecl *decl ) {
886                makeWritable();
887
888                const std::string &id = decl->get_name();
889                UnionTable::iterator existing = tables->unionTable.find( id );
890                if ( existing == tables->unionTable.end() ) {
891                        UnionDecl *parent = tables->base.lookupUnionAtScope( id, scope );
892                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
893                                tables->unionTable.insert( existing, std::make_pair( id, decl ) );
894                                ++tables->size;
895                        }
896                } else {
897                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
898                                existing->second = decl;
899                        }
900                }
901        }
902
903        void Indexer::addTrait( TraitDecl *decl ) {
904                makeWritable();
905
906                const std::string &id = decl->get_name();
907                TraitTable::iterator existing = tables->traitTable.find( id );
908                if ( existing == tables->traitTable.end() ) {
909                        TraitDecl *parent = tables->base.lookupTraitAtScope( id, scope );
910                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
911                                tables->traitTable.insert( existing, std::make_pair( id, decl ) );
912                                ++tables->size;
913                        }
914                } else {
915                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
916                                existing->second = decl;
917                        }
918                }
919        }
920
921        void Indexer::enterScope() {
922                ++scope;
923
924                if ( doDebug ) {
925                        std::cout << "--- Entering scope " << scope << std::endl;
926                }
927        }
928
929        void Indexer::leaveScope() {
930                using std::cout;
931
932                assert( scope > 0 && "cannot leave initial scope" );
933                --scope;
934
935                while ( tables && tables->scope > scope ) {
936                        if ( doDebug ) {
937                                cout << "--- Leaving scope " << tables->scope << " containing" << std::endl;
938                                dump( tables->idTable, cout );
939                                dump( tables->typeTable, cout );
940                                dump( tables->structTable, cout );
941                                dump( tables->enumTable, cout );
942                                dump( tables->unionTable, cout );
943                                dump( tables->traitTable, cout );
944                        }
945
946                        // swap tables for base table until we find one at an appropriate scope
947                        Indexer::Impl *base = newRef( tables->base.tables );
948                        deleteRef( tables );
949                        tables = base;
950                }
951        }
952
953        void Indexer::print( std::ostream &os, int indent ) const {
954            using std::cerr;
955
956                if ( tables ) {
957                        os << "--- scope " << tables->scope << " ---" << std::endl;
958
959                        os << "===idTable===" << std::endl;
960                        dump( tables->idTable, os );
961                        os << "===typeTable===" << std::endl;
962                        dump( tables->typeTable, os );
963                        os << "===structTable===" << std::endl;
964                        dump( tables->structTable, os );
965                        os << "===enumTable===" << std::endl;
966                        dump( tables->enumTable, os );
967                        os << "===unionTable===" << std::endl;
968                        dump( tables->unionTable, os );
969                        os << "===contextTable===" << std::endl;
970                        dump( tables->traitTable, os );
971
972                        tables->base.print( os, indent );
973                } else {
974                        os << "--- end ---" << std::endl;
975                }
976
977        }
978} // namespace SymTab
979
980// Local Variables: //
981// tab-width: 4 //
982// mode: c++ //
983// compile-command: "make install" //
984// End: //
Note: See TracBrowser for help on using the repository browser.