source: src/SymTab/Indexer.cc @ 9a7a3b6

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since 9a7a3b6 was 9a7a3b6, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Fix lookup{SUE}AtScope? functions to look in only a specific scope and provide lookupAtGlobalScope functions

  • Property mode set to 100644
File size: 28.3 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Indexer.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:37:33 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Aug 17 16:08:40 2017
13// Update Count     : 20
14//
15
16#include "Indexer.h"
17
18#include <cassert>                 // for assert, strict_dynamic_cast
19#include <iostream>                // for operator<<, basic_ostream, ostream
20#include <string>                  // for string, operator<<, operator!=
21#include <unordered_map>           // for operator!=, unordered_map<>::const...
22#include <unordered_set>           // for unordered_set
23#include <utility>                 // for pair, make_pair, move
24
25#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
26#include "Common/SemanticError.h"  // for SemanticError
27#include "Common/utility.h"        // for cloneAll
28#include "GenPoly/GenPoly.h"
29#include "InitTweak/InitTweak.h"   // for isConstructor, isCopyFunction, isC...
30#include "Mangler.h"               // for Mangler
31#include "Parser/LinkageSpec.h"    // for isMangled, isOverridable, Spec
32#include "ResolvExpr/typeops.h"    // for typesCompatible
33#include "SynTree/Constant.h"      // for Constant
34#include "SynTree/Declaration.h"   // for DeclarationWithType, FunctionDecl
35#include "SynTree/Expression.h"    // for Expression, ImplicitCopyCtorExpr
36#include "SynTree/Initializer.h"   // for Initializer
37#include "SynTree/Statement.h"     // for CompoundStmt, Statement, ForStmt (...
38#include "SynTree/Type.h"          // for Type, StructInstType, UnionInstType
39
40#define debugPrint(x) if ( doDebug ) { std::cerr << x; }
41
42namespace SymTab {
43        std::ostream & operator<<( std::ostream & out, const Indexer::IdData & data ) {
44                return out << "(" << data.id << "," << data.baseExpr << ")";
45        }
46
47        typedef std::unordered_map< std::string, Indexer::IdData > MangleTable;
48        typedef std::unordered_map< std::string, MangleTable > IdTable;
49        typedef std::unordered_map< std::string, NamedTypeDecl* > TypeTable;
50        typedef std::unordered_map< std::string, StructDecl* > StructTable;
51        typedef std::unordered_map< std::string, EnumDecl* > EnumTable;
52        typedef std::unordered_map< std::string, UnionDecl* > UnionTable;
53        typedef std::unordered_map< std::string, TraitDecl* > TraitTable;
54
55        void dump( const IdTable &table, std::ostream &os ) {
56                for ( IdTable::const_iterator id = table.begin(); id != table.end(); ++id ) {
57                        for ( MangleTable::const_iterator mangle = id->second.begin(); mangle != id->second.end(); ++mangle ) {
58                                os << mangle->second << std::endl;
59                        }
60                }
61        }
62
63        template< typename Decl >
64        void dump( const std::unordered_map< std::string, Decl* > &table, std::ostream &os ) {
65                for ( typename std::unordered_map< std::string, Decl* >::const_iterator it = table.begin(); it != table.end(); ++it ) {
66                        os << it->second << std::endl;
67                } // for
68        }
69
70        struct Indexer::Impl {
71                Impl( unsigned long _scope ) : refCount(1), scope( _scope ), size( 0 ), base(),
72                                idTable(), typeTable(), structTable(), enumTable(), unionTable(), traitTable() {}
73                Impl( unsigned long _scope, Indexer &&_base ) : refCount(1), scope( _scope ), size( 0 ), base( _base ),
74                                idTable(), typeTable(), structTable(), enumTable(), unionTable(), traitTable() {}
75                unsigned long refCount;   ///< Number of references to these tables
76                unsigned long scope;      ///< Scope these tables are associated with
77                unsigned long size;       ///< Number of elements stored in this table
78                const Indexer base;       ///< Base indexer this extends
79
80                IdTable idTable;          ///< Identifier namespace
81                TypeTable typeTable;      ///< Type namespace
82                StructTable structTable;  ///< Struct namespace
83                EnumTable enumTable;      ///< Enum namespace
84                UnionTable unionTable;    ///< Union namespace
85                TraitTable traitTable;    ///< Trait namespace
86        };
87
88        Indexer::Impl *Indexer::newRef( Indexer::Impl *toClone ) {
89                if ( ! toClone ) return 0;
90
91                // shorten the search chain by skipping empty links
92                Indexer::Impl *ret = toClone->size == 0 ? toClone->base.tables : toClone;
93                if ( ret ) { ++ret->refCount; }
94
95                return ret;
96        }
97
98        void Indexer::deleteRef( Indexer::Impl *toFree ) {
99                if ( ! toFree ) return;
100
101                if ( --toFree->refCount == 0 ) delete toFree;
102        }
103
104        void Indexer::removeSpecialOverrides( const std::string &id, std::list< IdData > & out ) const {
105                // only need to perform this step for constructors, destructors, and assignment functions
106                if ( ! CodeGen::isCtorDtorAssign( id ) ) return;
107
108                // helpful data structure to organize properties for a type
109                struct ValueType {
110                        struct DeclBall { // properties for this particular decl
111                                IdData decl;
112                                bool isUserDefinedFunc;
113                                bool isCopyFunc;
114                        };
115                        // properties for this type
116                        bool existsUserDefinedCopyFunc = false;    // user-defined copy ctor found
117                        BaseSyntaxNode * deleteStmt = nullptr;     // non-null if a user-defined function is found
118                        std::list< DeclBall > decls;
119
120                        // another FunctionDecl for the current type was found - determine
121                        // if it has special properties and update data structure accordingly
122                        ValueType & operator+=( IdData data ) {
123                                DeclarationWithType * function = data.id;
124                                bool isUserDefinedFunc = ! LinkageSpec::isOverridable( function->linkage );
125                                bool isCopyFunc = InitTweak::isCopyFunction( function, function->name );
126                                decls.push_back( DeclBall{ data, isUserDefinedFunc, isCopyFunc } );
127                                existsUserDefinedCopyFunc = existsUserDefinedCopyFunc || (isUserDefinedFunc && isCopyFunc);
128                                if ( isUserDefinedFunc && ! deleteStmt ) {
129                                        // any user-defined function can act as an implicit delete statement for generated constructors.
130                                        // a delete stmt should not act as an implicit delete statement.
131                                        deleteStmt = data.id;
132                                }
133                                return *this;
134                        }
135                }; // ValueType
136
137                std::list< IdData > copy;
138                copy.splice( copy.end(), out );
139
140                // organize discovered declarations by type
141                std::unordered_map< std::string, ValueType > funcMap;
142                for ( auto decl : copy ) {
143                        if ( FunctionDecl * function = dynamic_cast< FunctionDecl * >( decl.id ) ) {
144                                std::list< DeclarationWithType * > & params = function->type->parameters;
145                                assert( ! params.empty() );
146                                // use base type of pointer, so that qualifiers on the pointer type aren't considered.
147                                Type * base = InitTweak::getPointerBase( params.front()->get_type() );
148                                assert( base );
149                                funcMap[ Mangler::mangle( base ) ] += decl;
150                        } else {
151                                out.push_back( decl );
152                        }
153                }
154
155                // if a type contains user defined ctor/dtor/assign, then special rules trigger, which determine
156                // the set of ctor/dtor/assign that can be used  by the requester. In particular, if the user defines
157                // a default ctor, then the generated default ctor is unavailable, likewise for copy ctor
158                // and dtor. If the user defines any ctor/dtor, then no generated field ctors are available.
159                // If the user defines any ctor then the generated default ctor is unavailable (intrinsic default
160                // ctor must be overridden exactly). If the user defines anything that looks like a copy constructor,
161                // then the generated copy constructor is unavailable, and likewise for the assignment operator.
162                for ( std::pair< const std::string, ValueType > & pair : funcMap ) {
163                        ValueType & val = pair.second;
164                        for ( ValueType::DeclBall ball : val.decls ) {
165                                bool isNotUserDefinedFunc = ! ball.isUserDefinedFunc && ball.decl.id->linkage != LinkageSpec::Intrinsic;
166                                bool isCopyFunc = ball.isCopyFunc;
167                                bool existsUserDefinedCopyFunc = val.existsUserDefinedCopyFunc;
168
169                                // only implicitly delete non-user defined functions that are not intrinsic, and are
170                                // not copy functions (assignment or copy constructor). If a  user-defined copy function exists,
171                                // do not pass along the non-user-defined copy functions since signatures do not have to match,
172                                // and the generated functions will often be cheaper.
173                                if ( isNotUserDefinedFunc ) {
174                                        if ( isCopyFunc ) {
175                                                // Skip over non-user-defined copy functions when there is a user-defined copy function.
176                                                // Since their signatures do not have to be exact, deleting them is the wrong choice.
177                                                if ( existsUserDefinedCopyFunc ) continue;
178                                        } else {
179                                                // delete non-user-defined non-copy functions if applicable.
180                                                // deleteStmt will be non-null only if a user-defined function is found.
181                                                ball.decl.deleteStmt = val.deleteStmt;
182                                        }
183                                }
184                                out.push_back( ball.decl );
185                        }
186                }
187        }
188
189        void Indexer::makeWritable() {
190                if ( ! tables ) {
191                        // create indexer if not yet set
192                        tables = new Indexer::Impl( scope );
193                } else if ( tables->refCount > 1 || tables->scope != scope ) {
194                        // make this indexer the base of a fresh indexer at the current scope
195                        tables = new Indexer::Impl( scope, std::move( *this ) );
196                }
197        }
198
199        Indexer::Indexer() : tables( 0 ), scope( 0 ) {}
200
201        Indexer::Indexer( const Indexer &that ) : doDebug( that.doDebug ), tables( newRef( that.tables ) ), scope( that.scope ) {}
202
203        Indexer::Indexer( Indexer &&that ) : doDebug( that.doDebug ), tables( that.tables ), scope( that.scope ) {
204                that.tables = 0;
205        }
206
207        Indexer::~Indexer() {
208                deleteRef( tables );
209        }
210
211        Indexer& Indexer::operator= ( const Indexer &that ) {
212                deleteRef( tables );
213
214                tables = newRef( that.tables );
215                scope = that.scope;
216                doDebug = that.doDebug;
217
218                return *this;
219        }
220
221        Indexer& Indexer::operator= ( Indexer &&that ) {
222                deleteRef( tables );
223
224                tables = that.tables;
225                scope = that.scope;
226                doDebug = that.doDebug;
227
228                that.tables = 0;
229
230                return *this;
231        }
232
233        void Indexer::lookupId( const std::string &id, std::list< IdData > &out ) const {
234                std::unordered_set< std::string > foundMangleNames;
235
236                Indexer::Impl *searchTables = tables;
237                while ( searchTables ) {
238
239                        IdTable::const_iterator decls = searchTables->idTable.find( id );
240                        if ( decls != searchTables->idTable.end() ) {
241                                const MangleTable &mangleTable = decls->second;
242                                for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
243                                        // mark the mangled name as found, skipping this insertion if a declaration for that name has already been found
244                                        if ( foundMangleNames.insert( decl->first ).second == false ) continue;
245
246                                        out.push_back( decl->second );
247                                }
248                        }
249
250                        // get declarations from base indexers
251                        searchTables = searchTables->base.tables;
252                }
253
254                // some special functions, e.g. constructors and destructors
255                // remove autogenerated functions when they are defined so that
256                // they can never be matched
257                removeSpecialOverrides( id, out );
258        }
259
260        NamedTypeDecl *Indexer::lookupType( const std::string &id ) const {
261                if ( ! tables ) return 0;
262
263                TypeTable::const_iterator ret = tables->typeTable.find( id );
264                return ret != tables->typeTable.end() ? ret->second : tables->base.lookupType( id );
265        }
266
267        StructDecl *Indexer::lookupStruct( const std::string &id ) const {
268                if ( ! tables ) return 0;
269
270                StructTable::const_iterator ret = tables->structTable.find( id );
271                return ret != tables->structTable.end() ? ret->second : tables->base.lookupStruct( id );
272        }
273
274        StructDecl *Indexer::globalLookupStruct( const std::string &id ) const {
275                return lookupStructAtScope( id, 0 );
276        }
277
278        UnionDecl *Indexer::globalLookupUnion( const std::string &id ) const {
279                return lookupUnionAtScope( id, 0 );
280        }
281
282        EnumDecl *Indexer::globalLookupEnum( const std::string &id ) const {
283                return lookupEnumAtScope( id, 0 );
284        }
285
286        EnumDecl *Indexer::lookupEnum( const std::string &id ) const {
287                if ( ! tables ) return 0;
288
289                EnumTable::const_iterator ret = tables->enumTable.find( id );
290                return ret != tables->enumTable.end() ? ret->second : tables->base.lookupEnum( id );
291        }
292
293        UnionDecl *Indexer::lookupUnion( const std::string &id ) const {
294                if ( ! tables ) return 0;
295
296                UnionTable::const_iterator ret = tables->unionTable.find( id );
297                return ret != tables->unionTable.end() ? ret->second : tables->base.lookupUnion( id );
298        }
299
300        TraitDecl *Indexer::lookupTrait( const std::string &id ) const {
301                if ( ! tables ) return 0;
302
303                TraitTable::const_iterator ret = tables->traitTable.find( id );
304                return ret != tables->traitTable.end() ? ret->second : tables->base.lookupTrait( id );
305        }
306
307        const Indexer::IdData * Indexer::lookupIdAtScope( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
308                if ( ! tables ) return nullptr;
309                if ( tables->scope < scope ) return nullptr;
310
311                IdTable::const_iterator decls = tables->idTable.find( id );
312                if ( decls != tables->idTable.end() ) {
313                        const MangleTable &mangleTable = decls->second;
314                        MangleTable::const_iterator decl = mangleTable.find( mangleName );
315                        if ( decl != mangleTable.end() ) return &decl->second;
316                }
317
318                return tables->base.lookupIdAtScope( id, mangleName, scope );
319        }
320
321        Indexer::IdData * Indexer::lookupIdAtScope( const std::string &id, const std::string &mangleName, unsigned long scope ) {
322                return const_cast<IdData *>(const_cast<const Indexer *>(this)->lookupIdAtScope( id, mangleName, scope ));
323        }
324
325        bool Indexer::hasIncompatibleCDecl( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
326                if ( ! tables ) return false;
327                if ( tables->scope < scope ) return false;
328
329                IdTable::const_iterator decls = tables->idTable.find( id );
330                if ( decls != tables->idTable.end() ) {
331                        const MangleTable &mangleTable = decls->second;
332                        for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
333                                // check for C decls with the same name, skipping those with a compatible type (by mangleName)
334                                if ( ! LinkageSpec::isMangled( decl->second.id->get_linkage() ) && decl->first != mangleName ) return true;
335                        }
336                }
337
338                return tables->base.hasIncompatibleCDecl( id, mangleName, scope );
339        }
340
341        bool Indexer::hasCompatibleCDecl( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
342                if ( ! tables ) return false;
343                if ( tables->scope < scope ) return false;
344
345                IdTable::const_iterator decls = tables->idTable.find( id );
346                if ( decls != tables->idTable.end() ) {
347                        const MangleTable &mangleTable = decls->second;
348                        for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
349                                // check for C decls with the same name, skipping
350                                // those with an incompatible type (by mangleName)
351                                if ( ! LinkageSpec::isMangled( decl->second.id->get_linkage() ) && decl->first == mangleName ) return true;
352                        }
353                }
354
355                return tables->base.hasCompatibleCDecl( id, mangleName, scope );
356        }
357
358        NamedTypeDecl *Indexer::lookupTypeAtScope( const std::string &id, unsigned long scope ) const {
359                if ( ! tables ) return 0;
360                if ( tables->scope < scope ) return 0;
361                if ( tables->scope > scope ) return tables->base.lookupTypeAtScope( id, scope );
362
363                TypeTable::const_iterator ret = tables->typeTable.find( id );
364                return ret != tables->typeTable.end() ? ret->second : tables->base.lookupTypeAtScope( id, scope );
365        }
366
367        StructDecl *Indexer::lookupStructAtScope( const std::string &id, unsigned long scope ) const {
368                if ( ! tables ) return 0;
369                if ( tables->scope < scope ) return 0;
370                if ( tables->scope > scope ) return tables->base.lookupStructAtScope( id, scope );
371
372                StructTable::const_iterator ret = tables->structTable.find( id );
373                return ret != tables->structTable.end() ? ret->second : tables->base.lookupStructAtScope( id, scope );
374        }
375
376        EnumDecl *Indexer::lookupEnumAtScope( const std::string &id, unsigned long scope ) const {
377                if ( ! tables ) return 0;
378                if ( tables->scope < scope ) return 0;
379                if ( tables->scope > scope ) return tables->base.lookupEnumAtScope( id, scope );
380
381                EnumTable::const_iterator ret = tables->enumTable.find( id );
382                return ret != tables->enumTable.end() ? ret->second : tables->base.lookupEnumAtScope( id, scope );
383        }
384
385        UnionDecl *Indexer::lookupUnionAtScope( const std::string &id, unsigned long scope ) const {
386                if ( ! tables ) return 0;
387                if ( tables->scope < scope ) return 0;
388                if ( tables->scope > scope ) return tables->base.lookupUnionAtScope( id, scope );
389
390                UnionTable::const_iterator ret = tables->unionTable.find( id );
391                return ret != tables->unionTable.end() ? ret->second : tables->base.lookupUnionAtScope( id, scope );
392        }
393
394        TraitDecl *Indexer::lookupTraitAtScope( const std::string &id, unsigned long scope ) const {
395                if ( ! tables ) return 0;
396                if ( tables->scope < scope ) return 0;
397                if ( tables->scope > scope ) return tables->base.lookupTraitAtScope( id, scope );
398
399                TraitTable::const_iterator ret = tables->traitTable.find( id );
400                return ret != tables->traitTable.end() ? ret->second : tables->base.lookupTraitAtScope( id, scope );
401        }
402
403        bool isFunction( DeclarationWithType * decl ) {
404                return GenPoly::getFunctionType( decl->get_type() );
405        }
406
407        bool isObject( DeclarationWithType * decl ) {
408                return ! isFunction( decl );
409        }
410
411        bool isDefinition( DeclarationWithType * decl ) {
412                if ( FunctionDecl * func = dynamic_cast< FunctionDecl * >( decl ) ) {
413                        // a function is a definition if it has a body
414                        return func->statements;
415                } else {
416                        // an object is a definition if it is not marked extern.
417                        // both objects must be marked extern
418                        return ! decl->get_storageClasses().is_extern;
419                }
420        }
421
422        bool addedIdConflicts( Indexer::IdData & existing, DeclarationWithType *added, BaseSyntaxNode * deleteStmt, Indexer::ConflictFunction handleConflicts ) {
423                // if we're giving the same name mangling to things of different types then there is something wrong
424                assert( (isObject( added ) && isObject( existing.id ) )
425                        || ( isFunction( added ) && isFunction( existing.id ) ) );
426
427                if ( LinkageSpec::isOverridable( existing.id->get_linkage() ) ) {
428                        // new definition shadows the autogenerated one, even at the same scope
429                        return false;
430                } else if ( LinkageSpec::isMangled( added->get_linkage() ) || ResolvExpr::typesCompatible( added->get_type(), existing.id->get_type(), Indexer() ) ) {
431
432                        // it is a conflict if one declaration is deleted and the other is not
433                        if ( deleteStmt && ! existing.deleteStmt ) {
434                                return handleConflicts( existing, "deletion of defined identifier " );
435                        } else if ( ! deleteStmt && existing.deleteStmt ) {
436                                return handleConflicts( existing, "definition of deleted identifier " );
437                        }
438
439                        if ( isDefinition( added ) && isDefinition( existing.id ) ) {
440                                if ( isFunction( added ) ) {
441                                        return handleConflicts( existing, "duplicate function definition for " );
442                                } else {
443                                        return handleConflicts( existing, "duplicate object definition for " );
444                                } // if
445                        } // if
446                } else {
447                        return handleConflicts( existing, "duplicate definition for " );
448                } // if
449
450                return true;
451        }
452
453        void Indexer::addId( DeclarationWithType *decl, ConflictFunction handleConflicts, Expression * baseExpr, BaseSyntaxNode * deleteStmt ) {
454                if ( decl->name == "" ) return;
455                debugPrint( "Adding Id " << decl->name << std::endl );
456                makeWritable();
457
458                const std::string &name = decl->name;
459                std::string mangleName;
460                if ( LinkageSpec::isOverridable( decl->linkage ) ) {
461                        // mangle the name without including the appropriate suffix, so overridable routines are placed into the
462                        // same "bucket" as their user defined versions.
463                        mangleName = Mangler::mangle( decl, false );
464                } else {
465                        mangleName = Mangler::mangle( decl );
466                } // if
467
468                // this ensures that no two declarations with the same unmangled name at the same scope both have C linkage
469                if ( ! LinkageSpec::isMangled( decl->linkage ) ) {
470                        // NOTE this is broken in Richard's original code in such a way that it never triggers (it
471                        // doesn't check decls that have the same manglename, and all C-linkage decls are defined to
472                        // have their name as their manglename, hence the error can never trigger).
473                        // The code here is closer to correct, but name mangling would have to be completely
474                        // isomorphic to C type-compatibility, which it may not be.
475                        if ( hasIncompatibleCDecl( name, mangleName, scope ) ) {
476                                SemanticError( decl, "conflicting overload of C function " );
477                        }
478                } else {
479                        // Check that a Cforall declaration doesn't override any C declaration
480                        if ( hasCompatibleCDecl( name, mangleName, scope ) ) {
481                                SemanticError( decl, "Cforall declaration hides C function " );
482                        }
483                }
484
485                // Skip repeat declarations of the same identifier
486                IdData * existing = lookupIdAtScope( name, mangleName, scope );
487                if ( existing && existing->id && addedIdConflicts( *existing, decl, deleteStmt, handleConflicts ) ) return;
488
489                // add to indexer
490                tables->idTable[ name ][ mangleName ] = IdData{ decl, baseExpr, deleteStmt };
491                ++tables->size;
492        }
493
494        void Indexer::addId( DeclarationWithType * decl, Expression * baseExpr ) {
495                // default handling of conflicts is to raise an error
496                addId( decl, [decl](IdData &, const std::string & msg) { SemanticError( decl, msg ); return true; }, baseExpr, decl->isDeleted ? decl : nullptr );
497        }
498
499        void Indexer::addDeletedId( DeclarationWithType * decl, BaseSyntaxNode * deleteStmt ) {
500                // default handling of conflicts is to raise an error
501                addId( decl, [decl](IdData &, const std::string & msg) { SemanticError( decl, msg ); return true; }, nullptr, deleteStmt );
502        }
503
504        bool addedTypeConflicts( NamedTypeDecl *existing, NamedTypeDecl *added ) {
505                if ( existing->get_base() == 0 ) {
506                        return false;
507                } else if ( added->get_base() == 0 ) {
508                        return true;
509                } else {
510                        SemanticError( added, "redeclaration of " );
511                }
512        }
513
514        void Indexer::addType( NamedTypeDecl *decl ) {
515                debugPrint( "Adding type " << decl->name << std::endl );
516                makeWritable();
517
518                const std::string &id = decl->name;
519                TypeTable::iterator existing = tables->typeTable.find( id );
520                if ( existing == tables->typeTable.end() ) {
521                        NamedTypeDecl *parent = tables->base.lookupTypeAtScope( id, scope );
522                        if ( ! parent || ! addedTypeConflicts( parent, decl ) ) {
523                                tables->typeTable.insert( existing, std::make_pair( id, decl ) );
524                                ++tables->size;
525                        }
526                } else {
527                        if ( ! addedTypeConflicts( existing->second, decl ) ) {
528                                existing->second = decl;
529                        }
530                }
531        }
532
533        bool addedDeclConflicts( AggregateDecl *existing, AggregateDecl *added ) {
534                if ( ! existing->body ) {
535                        return false;
536                } else if ( added->body ) {
537                        SemanticError( added, "redeclaration of " );
538                } // if
539                return true;
540        }
541
542        void Indexer::addStruct( const std::string &id ) {
543                debugPrint( "Adding fwd decl for struct " << id << std::endl );
544                addStruct( new StructDecl( id ) );
545        }
546
547        void Indexer::addStruct( StructDecl *decl ) {
548                debugPrint( "Adding struct " << decl->name << std::endl );
549                makeWritable();
550
551                const std::string &id = decl->name;
552                StructTable::iterator existing = tables->structTable.find( id );
553                if ( existing == tables->structTable.end() ) {
554                        StructDecl *parent = tables->base.lookupStructAtScope( id, scope );
555                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
556                                tables->structTable.insert( existing, std::make_pair( id, decl ) );
557                                ++tables->size;
558                        }
559                } else {
560                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
561                                existing->second = decl;
562                        }
563                }
564        }
565
566        void Indexer::addEnum( EnumDecl *decl ) {
567                debugPrint( "Adding enum " << decl->name << std::endl );
568                makeWritable();
569
570                const std::string &id = decl->name;
571                EnumTable::iterator existing = tables->enumTable.find( id );
572                if ( existing == tables->enumTable.end() ) {
573                        EnumDecl *parent = tables->base.lookupEnumAtScope( id, scope );
574                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
575                                tables->enumTable.insert( existing, std::make_pair( id, decl ) );
576                                ++tables->size;
577                        }
578                } else {
579                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
580                                existing->second = decl;
581                        }
582                }
583        }
584
585        void Indexer::addUnion( const std::string &id ) {
586                debugPrint( "Adding fwd decl for union " << id << std::endl );
587                addUnion( new UnionDecl( id ) );
588        }
589
590        void Indexer::addUnion( UnionDecl *decl ) {
591                debugPrint( "Adding union " << decl->name << std::endl );
592                makeWritable();
593
594                const std::string &id = decl->name;
595                UnionTable::iterator existing = tables->unionTable.find( id );
596                if ( existing == tables->unionTable.end() ) {
597                        UnionDecl *parent = tables->base.lookupUnionAtScope( id, scope );
598                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
599                                tables->unionTable.insert( existing, std::make_pair( id, decl ) );
600                                ++tables->size;
601                        }
602                } else {
603                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
604                                existing->second = decl;
605                        }
606                }
607        }
608
609        void Indexer::addTrait( TraitDecl *decl ) {
610                debugPrint( "Adding trait " << decl->name << std::endl );
611                makeWritable();
612
613                const std::string &id = decl->name;
614                TraitTable::iterator existing = tables->traitTable.find( id );
615                if ( existing == tables->traitTable.end() ) {
616                        TraitDecl *parent = tables->base.lookupTraitAtScope( id, scope );
617                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
618                                tables->traitTable.insert( existing, std::make_pair( id, decl ) );
619                                ++tables->size;
620                        }
621                } else {
622                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
623                                existing->second = decl;
624                        }
625                }
626        }
627
628        void Indexer::addMembers( AggregateDecl * aggr, Expression * expr, ConflictFunction handleConflicts ) {
629                for ( Declaration * decl : aggr->members ) {
630                        if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
631                                addId( dwt, handleConflicts, expr );
632                                if ( dwt->name == "" ) {
633                                        Type * t = dwt->get_type()->stripReferences();
634                                        if ( dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t ) ) {
635                                                Expression * base = expr->clone();
636                                                ResolvExpr::Cost cost = ResolvExpr::Cost::zero; // xxx - carry this cost into the indexer as a base cost?
637                                                ResolvExpr::referenceToRvalueConversion( base, cost );
638                                                addMembers( t->getAggr(), new MemberExpr( dwt, base ), handleConflicts );
639                                        }
640                                }
641                        }
642                }
643        }
644
645        void Indexer::addWith( std::list< Expression * > & withExprs, BaseSyntaxNode * withStmt ) {
646                for ( Expression * expr : withExprs ) {
647                        if ( expr->result ) {
648                                AggregateDecl * aggr = expr->result->stripReferences()->getAggr();
649                                assertf( aggr, "WithStmt expr has non-aggregate type: %s", toString( expr->result ).c_str() );
650
651                                addMembers( aggr, expr, [withStmt](IdData & existing, const std::string &) {
652                                        // on conflict, delete the identifier
653                                        existing.deleteStmt = withStmt;
654                                        return true;
655                                });
656                        }
657                }
658        }
659
660        void Indexer::addIds( const std::list< DeclarationWithType * > & decls ) {
661                for ( auto d : decls ) {
662                        addId( d );
663                }
664        }
665
666        void Indexer::addTypes( const std::list< TypeDecl * > & tds ) {
667                for ( auto td : tds ) {
668                        addType( td );
669                        addIds( td->assertions );
670                }
671        }
672
673        void Indexer::addFunctionType( FunctionType * ftype ) {
674                addTypes( ftype->forall );
675                addIds( ftype->returnVals );
676                addIds( ftype->parameters );
677        }
678
679        void Indexer::enterScope() {
680                ++scope;
681
682                if ( doDebug ) {
683                        std::cerr << "--- Entering scope " << scope << std::endl;
684                }
685        }
686
687        void Indexer::leaveScope() {
688                using std::cerr;
689
690                assert( scope > 0 && "cannot leave initial scope" );
691                if ( doDebug ) {
692                        cerr << "--- Leaving scope " << scope << " containing" << std::endl;
693                }
694                --scope;
695
696                while ( tables && tables->scope > scope ) {
697                        if ( doDebug ) {
698                                dump( tables->idTable, cerr );
699                                dump( tables->typeTable, cerr );
700                                dump( tables->structTable, cerr );
701                                dump( tables->enumTable, cerr );
702                                dump( tables->unionTable, cerr );
703                                dump( tables->traitTable, cerr );
704                        }
705
706                        // swap tables for base table until we find one at an appropriate scope
707                        Indexer::Impl *base = newRef( tables->base.tables );
708                        deleteRef( tables );
709                        tables = base;
710                }
711        }
712
713        void Indexer::print( std::ostream &os, int indent ) const {
714                using std::cerr;
715
716                if ( tables ) {
717                        os << "--- scope " << tables->scope << " ---" << std::endl;
718
719                        os << "===idTable===" << std::endl;
720                        dump( tables->idTable, os );
721                        os << "===typeTable===" << std::endl;
722                        dump( tables->typeTable, os );
723                        os << "===structTable===" << std::endl;
724                        dump( tables->structTable, os );
725                        os << "===enumTable===" << std::endl;
726                        dump( tables->enumTable, os );
727                        os << "===unionTable===" << std::endl;
728                        dump( tables->unionTable, os );
729                        os << "===contextTable===" << std::endl;
730                        dump( tables->traitTable, os );
731
732                        tables->base.print( os, indent );
733                } else {
734                        os << "--- end ---" << std::endl;
735                }
736
737        }
738
739        Expression * Indexer::IdData::combine( ResolvExpr::Cost & cost ) const {
740                Expression * ret = nullptr;
741                if ( baseExpr ) {
742                        Expression * base = baseExpr->clone();
743                        ResolvExpr::referenceToRvalueConversion( base, cost );
744                        ret = new MemberExpr( id, base );
745                        // xxx - this introduces hidden environments, for now remove them.
746                        // std::swap( base->env, ret->env );
747                        delete base->env;
748                        base->env = nullptr;
749                } else {
750                        ret = new VariableExpr( id );
751                }
752                if ( deleteStmt ) ret = new DeletedExpr( ret, deleteStmt );
753                return ret;
754        }
755} // namespace SymTab
756
757// Local Variables: //
758// tab-width: 4 //
759// mode: c++ //
760// compile-command: "make install" //
761// End: //
Note: See TracBrowser for help on using the repository browser.