source: src/SymTab/Indexer.cc @ ee1635c8

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

automatically hide generated assignment functions following the same rules as ctor/dtors

  • 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 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, 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                acceptAllNewScope( applicationExpr->get_results(), *this );
340                maybeAccept( applicationExpr->get_function(), *this );
341                acceptAll( applicationExpr->get_args(), *this );
342        }
343
344        void Indexer::visit( UntypedExpr *untypedExpr ) {
345                acceptAllNewScope( untypedExpr->get_results(), *this );
346                acceptAll( untypedExpr->get_args(), *this );
347        }
348
349        void Indexer::visit( NameExpr *nameExpr ) {
350                acceptAllNewScope( nameExpr->get_results(), *this );
351        }
352
353        void Indexer::visit( AddressExpr *addressExpr ) {
354                acceptAllNewScope( addressExpr->get_results(), *this );
355                maybeAccept( addressExpr->get_arg(), *this );
356        }
357
358        void Indexer::visit( LabelAddressExpr *labAddressExpr ) {
359                acceptAllNewScope( labAddressExpr->get_results(), *this );
360                maybeAccept( labAddressExpr->get_arg(), *this );
361        }
362
363        void Indexer::visit( CastExpr *castExpr ) {
364                acceptAllNewScope( castExpr->get_results(), *this );
365                maybeAccept( castExpr->get_arg(), *this );
366        }
367
368        void Indexer::visit( UntypedMemberExpr *memberExpr ) {
369                acceptAllNewScope( memberExpr->get_results(), *this );
370                maybeAccept( memberExpr->get_aggregate(), *this );
371        }
372
373        void Indexer::visit( MemberExpr *memberExpr ) {
374                acceptAllNewScope( memberExpr->get_results(), *this );
375                maybeAccept( memberExpr->get_aggregate(), *this );
376        }
377
378        void Indexer::visit( VariableExpr *variableExpr ) {
379                acceptAllNewScope( variableExpr->get_results(), *this );
380        }
381
382        void Indexer::visit( ConstantExpr *constantExpr ) {
383                acceptAllNewScope( constantExpr->get_results(), *this );
384                maybeAccept( constantExpr->get_constant(), *this );
385        }
386
387        void Indexer::visit( SizeofExpr *sizeofExpr ) {
388                acceptAllNewScope( sizeofExpr->get_results(), *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                acceptAllNewScope( alignofExpr->get_results(), *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                acceptAllNewScope( offsetofExpr->get_results(), *this );
407                maybeAccept( offsetofExpr->get_type(), *this );
408        }
409
410        void Indexer::visit( OffsetofExpr *offsetofExpr ) {
411                acceptAllNewScope( offsetofExpr->get_results(), *this );
412                maybeAccept( offsetofExpr->get_type(), *this );
413                maybeAccept( offsetofExpr->get_member(), *this );
414        }
415
416        void Indexer::visit( OffsetPackExpr *offsetPackExpr ) {
417                acceptAllNewScope( offsetPackExpr->get_results(), *this );
418                maybeAccept( offsetPackExpr->get_type(), *this );
419        }
420
421        void Indexer::visit( AttrExpr *attrExpr ) {
422                acceptAllNewScope( attrExpr->get_results(), *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                acceptAllNewScope( logicalExpr->get_results(), *this );
432                maybeAccept( logicalExpr->get_arg1(), *this );
433                maybeAccept( logicalExpr->get_arg2(), *this );
434        }
435
436        void Indexer::visit( ConditionalExpr *conditionalExpr ) {
437                acceptAllNewScope( conditionalExpr->get_results(), *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                acceptAllNewScope( commaExpr->get_results(), *this );
445                maybeAccept( commaExpr->get_arg1(), *this );
446                maybeAccept( commaExpr->get_arg2(), *this );
447        }
448
449        void Indexer::visit( TupleExpr *tupleExpr ) {
450                acceptAllNewScope( tupleExpr->get_results(), *this );
451                acceptAll( tupleExpr->get_exprs(), *this );
452        }
453
454        void Indexer::visit( SolvedTupleExpr *tupleExpr ) {
455                acceptAllNewScope( tupleExpr->get_results(), *this );
456                acceptAll( tupleExpr->get_exprs(), *this );
457        }
458
459        void Indexer::visit( TypeExpr *typeExpr ) {
460                acceptAllNewScope( typeExpr->get_results(), *this );
461                maybeAccept( typeExpr->get_type(), *this );
462        }
463
464        void Indexer::visit( AsmExpr *asmExpr ) {
465                maybeAccept( asmExpr->get_inout(), *this );
466                maybeAccept( asmExpr->get_constraint(), *this );
467                maybeAccept( asmExpr->get_operand(), *this );
468        }
469
470        void Indexer::visit( UntypedValofExpr *valofExpr ) {
471                acceptAllNewScope( valofExpr->get_results(), *this );
472                maybeAccept( valofExpr->get_body(), *this );
473        }
474
475
476        void Indexer::visit( TraitInstType *contextInst ) {
477                acceptAll( contextInst->get_parameters(), *this );
478                acceptAll( contextInst->get_members(), *this );
479        }
480
481        void Indexer::visit( StructInstType *structInst ) {
482                if ( ! lookupStruct( structInst->get_name() ) ) {
483                        debugPrint( "Adding struct " << structInst->get_name() << " from implicit forward declaration" << std::endl );
484                        addStruct( structInst->get_name() );
485                }
486                enterScope();
487                acceptAll( structInst->get_parameters(), *this );
488                leaveScope();
489        }
490
491        void Indexer::visit( UnionInstType *unionInst ) {
492                if ( ! lookupUnion( unionInst->get_name() ) ) {
493                        debugPrint( "Adding union " << unionInst->get_name() << " from implicit forward declaration" << std::endl );
494                        addUnion( unionInst->get_name() );
495                }
496                enterScope();
497                acceptAll( unionInst->get_parameters(), *this );
498                leaveScope();
499        }
500
501        void Indexer::visit( ForStmt *forStmt ) {
502            // for statements introduce a level of scope
503            enterScope();
504            Visitor::visit( forStmt );
505            leaveScope();
506        }
507
508
509
510        void Indexer::lookupId( const std::string &id, std::list< DeclarationWithType* > &out ) const {
511                std::unordered_set< std::string > foundMangleNames;
512
513                Indexer::Impl *searchTables = tables;
514                while ( searchTables ) {
515
516                        IdTable::const_iterator decls = searchTables->idTable.find( id );
517                        if ( decls != searchTables->idTable.end() ) {
518                                const MangleTable &mangleTable = decls->second;
519                                for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
520                                        // mark the mangled name as found, skipping this insertion if a declaration for that name has already been found
521                                        if ( foundMangleNames.insert( decl->first ).second == false ) continue;
522
523                                        out.push_back( decl->second );
524                                }
525                        }
526
527                        // get declarations from base indexers
528                        searchTables = searchTables->base.tables;
529                }
530
531                // some special functions, e.g. constructors and destructors
532                // remove autogenerated functions when they are defined so that
533                // they can never be matched
534                removeSpecialOverrides( id, out );
535        }
536
537        NamedTypeDecl *Indexer::lookupType( const std::string &id ) const {
538                if ( ! tables ) return 0;
539
540                TypeTable::const_iterator ret = tables->typeTable.find( id );
541                return ret != tables->typeTable.end() ? ret->second : tables->base.lookupType( id );
542        }
543
544        StructDecl *Indexer::lookupStruct( const std::string &id ) const {
545                if ( ! tables ) return 0;
546
547                StructTable::const_iterator ret = tables->structTable.find( id );
548                return ret != tables->structTable.end() ? ret->second : tables->base.lookupStruct( id );
549        }
550
551        EnumDecl *Indexer::lookupEnum( const std::string &id ) const {
552                if ( ! tables ) return 0;
553
554                EnumTable::const_iterator ret = tables->enumTable.find( id );
555                return ret != tables->enumTable.end() ? ret->second : tables->base.lookupEnum( id );
556        }
557
558        UnionDecl *Indexer::lookupUnion( const std::string &id ) const {
559                if ( ! tables ) return 0;
560
561                UnionTable::const_iterator ret = tables->unionTable.find( id );
562                return ret != tables->unionTable.end() ? ret->second : tables->base.lookupUnion( id );
563        }
564
565        TraitDecl *Indexer::lookupTrait( const std::string &id ) const {
566                if ( ! tables ) return 0;
567
568                TraitTable::const_iterator ret = tables->traitTable.find( id );
569                return ret != tables->traitTable.end() ? ret->second : tables->base.lookupTrait( id );
570        }
571
572        DeclarationWithType *Indexer::lookupIdAtScope( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
573                if ( ! tables ) return 0;
574                if ( tables->scope < scope ) return 0;
575
576                IdTable::const_iterator decls = tables->idTable.find( id );
577                if ( decls != tables->idTable.end() ) {
578                        const MangleTable &mangleTable = decls->second;
579                        MangleTable::const_iterator decl = mangleTable.find( mangleName );
580                        if ( decl != mangleTable.end() ) return decl->second;
581                }
582
583                return tables->base.lookupIdAtScope( id, mangleName, scope );
584        }
585
586        bool Indexer::hasIncompatibleCDecl( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
587                if ( ! tables ) return false;
588                if ( tables->scope < scope ) return false;
589
590                IdTable::const_iterator decls = tables->idTable.find( id );
591                if ( decls != tables->idTable.end() ) {
592                        const MangleTable &mangleTable = decls->second;
593                        for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
594                                // check for C decls with the same name, skipping those with a compatible type (by mangleName)
595                                if ( decl->second->get_linkage() == LinkageSpec::C && decl->first != mangleName ) return true;
596                        }
597                }
598
599                return tables->base.hasIncompatibleCDecl( id, mangleName, scope );
600        }
601
602        bool Indexer::hasCompatibleCDecl( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
603                if ( ! tables ) return false;
604                if ( tables->scope < scope ) return false;
605
606                IdTable::const_iterator decls = tables->idTable.find( id );
607                if ( decls != tables->idTable.end() ) {
608                        const MangleTable &mangleTable = decls->second;
609                        for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
610                                // check for C decls with the same name, skipping
611                                // those with an incompatible type (by mangleName)
612                                if ( decl->second->get_linkage() == LinkageSpec::C && decl->first == mangleName ) return true;
613                        }
614                }
615
616                return tables->base.hasCompatibleCDecl( id, mangleName, scope );
617        }
618
619        NamedTypeDecl *Indexer::lookupTypeAtScope( const std::string &id, unsigned long scope ) const {
620                if ( ! tables ) return 0;
621                if ( tables->scope < scope ) return 0;
622
623                TypeTable::const_iterator ret = tables->typeTable.find( id );
624                return ret != tables->typeTable.end() ? ret->second : tables->base.lookupTypeAtScope( id, scope );
625        }
626
627        StructDecl *Indexer::lookupStructAtScope( const std::string &id, unsigned long scope ) const {
628                if ( ! tables ) return 0;
629                if ( tables->scope < scope ) return 0;
630
631                StructTable::const_iterator ret = tables->structTable.find( id );
632                return ret != tables->structTable.end() ? ret->second : tables->base.lookupStructAtScope( id, scope );
633        }
634
635        EnumDecl *Indexer::lookupEnumAtScope( const std::string &id, unsigned long scope ) const {
636                if ( ! tables ) return 0;
637                if ( tables->scope < scope ) return 0;
638
639                EnumTable::const_iterator ret = tables->enumTable.find( id );
640                return ret != tables->enumTable.end() ? ret->second : tables->base.lookupEnumAtScope( id, scope );
641        }
642
643        UnionDecl *Indexer::lookupUnionAtScope( const std::string &id, unsigned long scope ) const {
644                if ( ! tables ) return 0;
645                if ( tables->scope < scope ) return 0;
646
647                UnionTable::const_iterator ret = tables->unionTable.find( id );
648                return ret != tables->unionTable.end() ? ret->second : tables->base.lookupUnionAtScope( id, scope );
649        }
650
651        TraitDecl *Indexer::lookupTraitAtScope( const std::string &id, unsigned long scope ) const {
652                if ( ! tables ) return 0;
653                if ( tables->scope < scope ) return 0;
654
655                TraitTable::const_iterator ret = tables->traitTable.find( id );
656                return ret != tables->traitTable.end() ? ret->second : tables->base.lookupTraitAtScope( id, scope );
657        }
658
659        bool addedIdConflicts( DeclarationWithType *existing, DeclarationWithType *added ) {
660                // if we're giving the same name mangling to things of different types then there is something wrong
661                assert( (dynamic_cast<ObjectDecl*>( added ) && dynamic_cast<ObjectDecl*>( existing ) )
662                        || (dynamic_cast<FunctionDecl*>( added ) && dynamic_cast<FunctionDecl*>( existing ) ) );
663
664                if ( LinkageSpec::isOverridable( existing->get_linkage() ) ) {
665                        // new definition shadows the autogenerated one, even at the same scope
666                        return false;
667                } else if ( added->get_linkage() != LinkageSpec::C || ResolvExpr::typesCompatible( added->get_type(), existing->get_type(), Indexer() ) ) {
668                        // typesCompatible doesn't really do the right thing here. When checking compatibility of function types,
669                        // we should ignore outermost pointer qualifiers, except _Atomic?
670                        FunctionDecl *newentry = dynamic_cast< FunctionDecl* >( added );
671                        FunctionDecl *oldentry = dynamic_cast< FunctionDecl* >( existing );
672                        if ( newentry && oldentry ) {
673                                if ( newentry->get_statements() && oldentry->get_statements() ) {
674                                        throw SemanticError( "duplicate function definition for ", added );
675                                } // if
676                        } else {
677                                // two objects with the same mangled name defined in the same scope.
678                                // both objects must be marked extern or both must be intrinsic for this to be okay
679                                // xxx - perhaps it's actually if either is intrinsic then this is okay?
680                                //       might also need to be same storage class?
681                                ObjectDecl *newobj = dynamic_cast< ObjectDecl* >( added );
682                                ObjectDecl *oldobj = dynamic_cast< ObjectDecl* >( existing );
683                                if ( newobj->get_storageClass() != DeclarationNode::Extern && oldobj->get_storageClass() != DeclarationNode::Extern ) {
684                                        throw SemanticError( "duplicate object definition for ", added );
685                                } // if
686                        } // if
687                } else {
688                        throw SemanticError( "duplicate definition for ", added );
689                } // if
690
691                return true;
692        }
693
694        void Indexer::addId( DeclarationWithType *decl ) {
695                makeWritable();
696
697                const std::string &name = decl->get_name();
698                std::string mangleName;
699                if ( LinkageSpec::isOverridable( decl->get_linkage() ) ) {
700                        // mangle the name without including the appropriate suffix, so overridable routines are placed into the
701                        // same "bucket" as their user defined versions.
702                        mangleName = Mangler::mangle( decl, false );
703                } else {
704                        mangleName = Mangler::mangle( decl );
705                } // if
706
707                // this ensures that no two declarations with the same unmangled name at the same scope both have C linkage
708                if ( decl->get_linkage() == LinkageSpec::C ) {
709                        // NOTE this is broken in Richard's original code in such a way that it never triggers (it
710                        // doesn't check decls that have the same manglename, and all C-linkage decls are defined to
711                        // have their name as their manglename, hence the error can never trigger).
712                        // The code here is closer to correct, but name mangling would have to be completely
713                        // isomorphic to C type-compatibility, which it may not be.
714                        if ( hasIncompatibleCDecl( name, mangleName, scope ) ) {
715                                throw SemanticError( "conflicting overload of C function ", decl );
716                        }
717                } else {
718                        // Check that a Cforall declaration doesn't overload any C declaration
719                        if ( hasCompatibleCDecl( name, mangleName, scope ) ) {
720                                throw SemanticError( "Cforall declaration hides C function ", decl );
721                        }
722                }
723
724                // Skip repeat declarations of the same identifier
725                DeclarationWithType *existing = lookupIdAtScope( name, mangleName, scope );
726                if ( existing && addedIdConflicts( existing, decl ) ) return;
727
728                // add to indexer
729                tables->idTable[ name ][ mangleName ] = decl;
730                ++tables->size;
731        }
732
733        bool addedTypeConflicts( NamedTypeDecl *existing, NamedTypeDecl *added ) {
734                if ( existing->get_base() == 0 ) {
735                        return false;
736                } else if ( added->get_base() == 0 ) {
737                        return true;
738                } else {
739                        throw SemanticError( "redeclaration of ", added );
740                }
741        }
742
743        void Indexer::addType( NamedTypeDecl *decl ) {
744                makeWritable();
745
746                const std::string &id = decl->get_name();
747                TypeTable::iterator existing = tables->typeTable.find( id );
748                if ( existing == tables->typeTable.end() ) {
749                        NamedTypeDecl *parent = tables->base.lookupTypeAtScope( id, scope );
750                        if ( ! parent || ! addedTypeConflicts( parent, decl ) ) {
751                                tables->typeTable.insert( existing, std::make_pair( id, decl ) );
752                                ++tables->size;
753                        }
754                } else {
755                        if ( ! addedTypeConflicts( existing->second, decl ) ) {
756                                existing->second = decl;
757                        }
758                }
759        }
760
761        bool addedDeclConflicts( AggregateDecl *existing, AggregateDecl *added ) {
762                if ( existing->get_members().empty() ) {
763                        return false;
764                } else if ( ! added->get_members().empty() ) {
765                        throw SemanticError( "redeclaration of ", added );
766                } // if
767                return true;
768        }
769
770        void Indexer::addStruct( const std::string &id ) {
771                addStruct( new StructDecl( id ) );
772        }
773
774        void Indexer::addStruct( StructDecl *decl ) {
775                makeWritable();
776
777                const std::string &id = decl->get_name();
778                StructTable::iterator existing = tables->structTable.find( id );
779                if ( existing == tables->structTable.end() ) {
780                        StructDecl *parent = tables->base.lookupStructAtScope( id, scope );
781                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
782                                tables->structTable.insert( existing, std::make_pair( id, decl ) );
783                                ++tables->size;
784                        }
785                } else {
786                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
787                                existing->second = decl;
788                        }
789                }
790        }
791
792        void Indexer::addEnum( EnumDecl *decl ) {
793                makeWritable();
794
795                const std::string &id = decl->get_name();
796                EnumTable::iterator existing = tables->enumTable.find( id );
797                if ( existing == tables->enumTable.end() ) {
798                        EnumDecl *parent = tables->base.lookupEnumAtScope( id, scope );
799                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
800                                tables->enumTable.insert( existing, std::make_pair( id, decl ) );
801                                ++tables->size;
802                        }
803                } else {
804                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
805                                existing->second = decl;
806                        }
807                }
808        }
809
810        void Indexer::addUnion( const std::string &id ) {
811                addUnion( new UnionDecl( id ) );
812        }
813
814        void Indexer::addUnion( UnionDecl *decl ) {
815                makeWritable();
816
817                const std::string &id = decl->get_name();
818                UnionTable::iterator existing = tables->unionTable.find( id );
819                if ( existing == tables->unionTable.end() ) {
820                        UnionDecl *parent = tables->base.lookupUnionAtScope( id, scope );
821                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
822                                tables->unionTable.insert( existing, std::make_pair( id, decl ) );
823                                ++tables->size;
824                        }
825                } else {
826                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
827                                existing->second = decl;
828                        }
829                }
830        }
831
832        void Indexer::addTrait( TraitDecl *decl ) {
833                makeWritable();
834
835                const std::string &id = decl->get_name();
836                TraitTable::iterator existing = tables->traitTable.find( id );
837                if ( existing == tables->traitTable.end() ) {
838                        TraitDecl *parent = tables->base.lookupTraitAtScope( id, scope );
839                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
840                                tables->traitTable.insert( existing, std::make_pair( id, decl ) );
841                                ++tables->size;
842                        }
843                } else {
844                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
845                                existing->second = decl;
846                        }
847                }
848        }
849
850        void Indexer::enterScope() {
851                ++scope;
852
853                if ( doDebug ) {
854                        std::cout << "--- Entering scope " << scope << std::endl;
855                }
856        }
857
858        void Indexer::leaveScope() {
859                using std::cout;
860
861                assert( scope > 0 && "cannot leave initial scope" );
862                --scope;
863
864                while ( tables && tables->scope > scope ) {
865                        if ( doDebug ) {
866                                cout << "--- Leaving scope " << tables->scope << " containing" << std::endl;
867                                dump( tables->idTable, cout );
868                                dump( tables->typeTable, cout );
869                                dump( tables->structTable, cout );
870                                dump( tables->enumTable, cout );
871                                dump( tables->unionTable, cout );
872                                dump( tables->traitTable, cout );
873                        }
874
875                        // swap tables for base table until we find one at an appropriate scope
876                        Indexer::Impl *base = newRef( tables->base.tables );
877                        deleteRef( tables );
878                        tables = base;
879                }
880        }
881
882        void Indexer::print( std::ostream &os, int indent ) const {
883            using std::cerr;
884
885                if ( tables ) {
886                        os << "--- scope " << tables->scope << " ---" << std::endl;
887
888                        os << "===idTable===" << std::endl;
889                        dump( tables->idTable, os );
890                        os << "===typeTable===" << std::endl;
891                        dump( tables->typeTable, os );
892                        os << "===structTable===" << std::endl;
893                        dump( tables->structTable, os );
894                        os << "===enumTable===" << std::endl;
895                        dump( tables->enumTable, os );
896                        os << "===unionTable===" << std::endl;
897                        dump( tables->unionTable, os );
898                        os << "===contextTable===" << std::endl;
899                        dump( tables->traitTable, os );
900
901                        tables->base.print( os, indent );
902                } else {
903                        os << "--- end ---" << std::endl;
904                }
905
906        }
907} // namespace SymTab
908
909// Local Variables: //
910// tab-width: 4 //
911// mode: c++ //
912// compile-command: "make install" //
913// End: //
Note: See TracBrowser for help on using the repository browser.