source: src/SymTab/Indexer.cc @ dcd73d1

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

implement implicit ctor/dtor deletion, track managed types when inserting ConstructorInit? nodes, remove fallbackInit case, update tests

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