source: src/SymTab/Indexer.cc @ 3c13c03

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

Merge branch 'replace-results-list' into tuples

Conflicts:

src/ResolvExpr/AlternativeFinder.cc
src/SymTab/Indexer.cc
src/SynTree/Mutator.cc
src/SynTree/Visitor.cc
src/Tuples/TupleAssignment.cc
src/Tuples/TupleAssignment.h

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