source: src/SymTab/Indexer.cc @ af84a35

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumwith_gc
Last change on this file since af84a35 was 0a75b77, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Simplify removeSpecialOverrides and modify it to delete functions rather than hide

  • Property mode set to 100644
File size: 27.1 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 && ! data.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                                // only implicitly delete non-user defined functions that are  not intrinsic, and are
169                                // not copy functions (assignment or copy constructor), unless a user-defined copy function exists.
170                                // deleteStmt will be non-null only if a user-defined function is found.
171                                if (isNotUserDefinedFunc && (! isCopyFunc || existsUserDefinedCopyFunc)) {
172                                        ball.decl.deleteStmt = val.deleteStmt;
173                                }
174                                out.push_back( ball.decl );
175                        }
176                }
177        }
178
179        void Indexer::makeWritable() {
180                if ( ! tables ) {
181                        // create indexer if not yet set
182                        tables = new Indexer::Impl( scope );
183                } else if ( tables->refCount > 1 || tables->scope != scope ) {
184                        // make this indexer the base of a fresh indexer at the current scope
185                        tables = new Indexer::Impl( scope, std::move( *this ) );
186                }
187        }
188
189        Indexer::Indexer() : tables( 0 ), scope( 0 ) {}
190
191        Indexer::Indexer( const Indexer &that ) : doDebug( that.doDebug ), tables( newRef( that.tables ) ), scope( that.scope ) {}
192
193        Indexer::Indexer( Indexer &&that ) : doDebug( that.doDebug ), tables( that.tables ), scope( that.scope ) {
194                that.tables = 0;
195        }
196
197        Indexer::~Indexer() {
198                deleteRef( tables );
199        }
200
201        Indexer& Indexer::operator= ( const Indexer &that ) {
202                deleteRef( tables );
203
204                tables = newRef( that.tables );
205                scope = that.scope;
206                doDebug = that.doDebug;
207
208                return *this;
209        }
210
211        Indexer& Indexer::operator= ( Indexer &&that ) {
212                deleteRef( tables );
213
214                tables = that.tables;
215                scope = that.scope;
216                doDebug = that.doDebug;
217
218                that.tables = 0;
219
220                return *this;
221        }
222
223        void Indexer::lookupId( const std::string &id, std::list< IdData > &out ) const {
224                std::unordered_set< std::string > foundMangleNames;
225
226                Indexer::Impl *searchTables = tables;
227                while ( searchTables ) {
228
229                        IdTable::const_iterator decls = searchTables->idTable.find( id );
230                        if ( decls != searchTables->idTable.end() ) {
231                                const MangleTable &mangleTable = decls->second;
232                                for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
233                                        // mark the mangled name as found, skipping this insertion if a declaration for that name has already been found
234                                        if ( foundMangleNames.insert( decl->first ).second == false ) continue;
235
236                                        out.push_back( decl->second );
237                                }
238                        }
239
240                        // get declarations from base indexers
241                        searchTables = searchTables->base.tables;
242                }
243
244                // some special functions, e.g. constructors and destructors
245                // remove autogenerated functions when they are defined so that
246                // they can never be matched
247                removeSpecialOverrides( id, out );
248        }
249
250        NamedTypeDecl *Indexer::lookupType( const std::string &id ) const {
251                if ( ! tables ) return 0;
252
253                TypeTable::const_iterator ret = tables->typeTable.find( id );
254                return ret != tables->typeTable.end() ? ret->second : tables->base.lookupType( id );
255        }
256
257        StructDecl *Indexer::lookupStruct( const std::string &id ) const {
258                if ( ! tables ) return 0;
259
260                StructTable::const_iterator ret = tables->structTable.find( id );
261                return ret != tables->structTable.end() ? ret->second : tables->base.lookupStruct( id );
262        }
263
264        EnumDecl *Indexer::lookupEnum( const std::string &id ) const {
265                if ( ! tables ) return 0;
266
267                EnumTable::const_iterator ret = tables->enumTable.find( id );
268                return ret != tables->enumTable.end() ? ret->second : tables->base.lookupEnum( id );
269        }
270
271        UnionDecl *Indexer::lookupUnion( const std::string &id ) const {
272                if ( ! tables ) return 0;
273
274                UnionTable::const_iterator ret = tables->unionTable.find( id );
275                return ret != tables->unionTable.end() ? ret->second : tables->base.lookupUnion( id );
276        }
277
278        TraitDecl *Indexer::lookupTrait( const std::string &id ) const {
279                if ( ! tables ) return 0;
280
281                TraitTable::const_iterator ret = tables->traitTable.find( id );
282                return ret != tables->traitTable.end() ? ret->second : tables->base.lookupTrait( id );
283        }
284
285        const Indexer::IdData * Indexer::lookupIdAtScope( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
286                if ( ! tables ) return nullptr;
287                if ( tables->scope < scope ) return nullptr;
288
289                IdTable::const_iterator decls = tables->idTable.find( id );
290                if ( decls != tables->idTable.end() ) {
291                        const MangleTable &mangleTable = decls->second;
292                        MangleTable::const_iterator decl = mangleTable.find( mangleName );
293                        if ( decl != mangleTable.end() ) return &decl->second;
294                }
295
296                return tables->base.lookupIdAtScope( id, mangleName, scope );
297        }
298
299        Indexer::IdData * Indexer::lookupIdAtScope( const std::string &id, const std::string &mangleName, unsigned long scope ) {
300                return const_cast<IdData *>(const_cast<const Indexer *>(this)->lookupIdAtScope( id, mangleName, scope ));
301        }
302
303        bool Indexer::hasIncompatibleCDecl( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
304                if ( ! tables ) return false;
305                if ( tables->scope < scope ) return false;
306
307                IdTable::const_iterator decls = tables->idTable.find( id );
308                if ( decls != tables->idTable.end() ) {
309                        const MangleTable &mangleTable = decls->second;
310                        for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
311                                // check for C decls with the same name, skipping those with a compatible type (by mangleName)
312                                if ( ! LinkageSpec::isMangled( decl->second.id->get_linkage() ) && decl->first != mangleName ) return true;
313                        }
314                }
315
316                return tables->base.hasIncompatibleCDecl( id, mangleName, scope );
317        }
318
319        bool Indexer::hasCompatibleCDecl( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
320                if ( ! tables ) return false;
321                if ( tables->scope < scope ) return false;
322
323                IdTable::const_iterator decls = tables->idTable.find( id );
324                if ( decls != tables->idTable.end() ) {
325                        const MangleTable &mangleTable = decls->second;
326                        for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
327                                // check for C decls with the same name, skipping
328                                // those with an incompatible type (by mangleName)
329                                if ( ! LinkageSpec::isMangled( decl->second.id->get_linkage() ) && decl->first == mangleName ) return true;
330                        }
331                }
332
333                return tables->base.hasCompatibleCDecl( id, mangleName, scope );
334        }
335
336        NamedTypeDecl *Indexer::lookupTypeAtScope( const std::string &id, unsigned long scope ) const {
337                if ( ! tables ) return 0;
338                if ( tables->scope < scope ) return 0;
339
340                TypeTable::const_iterator ret = tables->typeTable.find( id );
341                return ret != tables->typeTable.end() ? ret->second : tables->base.lookupTypeAtScope( id, scope );
342        }
343
344        StructDecl *Indexer::lookupStructAtScope( const std::string &id, unsigned long scope ) const {
345                if ( ! tables ) return 0;
346                if ( tables->scope < scope ) return 0;
347
348                StructTable::const_iterator ret = tables->structTable.find( id );
349                return ret != tables->structTable.end() ? ret->second : tables->base.lookupStructAtScope( id, scope );
350        }
351
352        EnumDecl *Indexer::lookupEnumAtScope( const std::string &id, unsigned long scope ) const {
353                if ( ! tables ) return 0;
354                if ( tables->scope < scope ) return 0;
355
356                EnumTable::const_iterator ret = tables->enumTable.find( id );
357                return ret != tables->enumTable.end() ? ret->second : tables->base.lookupEnumAtScope( id, scope );
358        }
359
360        UnionDecl *Indexer::lookupUnionAtScope( const std::string &id, unsigned long scope ) const {
361                if ( ! tables ) return 0;
362                if ( tables->scope < scope ) return 0;
363
364                UnionTable::const_iterator ret = tables->unionTable.find( id );
365                return ret != tables->unionTable.end() ? ret->second : tables->base.lookupUnionAtScope( id, scope );
366        }
367
368        TraitDecl *Indexer::lookupTraitAtScope( const std::string &id, unsigned long scope ) const {
369                if ( ! tables ) return 0;
370                if ( tables->scope < scope ) return 0;
371
372                TraitTable::const_iterator ret = tables->traitTable.find( id );
373                return ret != tables->traitTable.end() ? ret->second : tables->base.lookupTraitAtScope( id, scope );
374        }
375
376        bool isFunction( DeclarationWithType * decl ) {
377                return GenPoly::getFunctionType( decl->get_type() );
378        }
379
380        bool isObject( DeclarationWithType * decl ) {
381                return ! isFunction( decl );
382        }
383
384        bool isDefinition( DeclarationWithType * decl ) {
385                if ( FunctionDecl * func = dynamic_cast< FunctionDecl * >( decl ) ) {
386                        // a function is a definition if it has a body
387                        return func->statements;
388                } else {
389                        // an object is a definition if it is not marked extern.
390                        // both objects must be marked extern
391                        return ! decl->get_storageClasses().is_extern;
392                }
393        }
394
395        bool addedIdConflicts( Indexer::IdData & existing, DeclarationWithType *added, BaseSyntaxNode * deleteStmt, Indexer::ConflictFunction handleConflicts ) {
396                // if we're giving the same name mangling to things of different types then there is something wrong
397                assert( (isObject( added ) && isObject( existing.id ) )
398                        || ( isFunction( added ) && isFunction( existing.id ) ) );
399
400                if ( LinkageSpec::isOverridable( existing.id->get_linkage() ) ) {
401                        // new definition shadows the autogenerated one, even at the same scope
402                        return false;
403                } else if ( LinkageSpec::isMangled( added->get_linkage() ) || ResolvExpr::typesCompatible( added->get_type(), existing.id->get_type(), Indexer() ) ) {
404
405                        // it is a conflict if one declaration is deleted and the other is not
406                        if ( deleteStmt && ! existing.deleteStmt ) {
407                                return handleConflicts( existing, "deletion of defined identifier " );
408                        } else if ( ! deleteStmt && existing.deleteStmt ) {
409                                return handleConflicts( existing, "definition of deleted identifier " );
410                        }
411
412                        if ( isDefinition( added ) && isDefinition( existing.id ) ) {
413                                if ( isFunction( added ) ) {
414                                        return handleConflicts( existing, "duplicate function definition for " );
415                                } else {
416                                        return handleConflicts( existing, "duplicate object definition for " );
417                                } // if
418                        } // if
419                } else {
420                        return handleConflicts( existing, "duplicate definition for " );
421                } // if
422
423                return true;
424        }
425
426        void Indexer::addId( DeclarationWithType *decl, ConflictFunction handleConflicts, Expression * baseExpr, BaseSyntaxNode * deleteStmt ) {
427                if ( decl->name == "" ) return;
428                debugPrint( "Adding Id " << decl->name << std::endl );
429                makeWritable();
430
431                const std::string &name = decl->name;
432                std::string mangleName;
433                if ( LinkageSpec::isOverridable( decl->linkage ) ) {
434                        // mangle the name without including the appropriate suffix, so overridable routines are placed into the
435                        // same "bucket" as their user defined versions.
436                        mangleName = Mangler::mangle( decl, false );
437                } else {
438                        mangleName = Mangler::mangle( decl );
439                } // if
440
441                // this ensures that no two declarations with the same unmangled name at the same scope both have C linkage
442                if ( ! LinkageSpec::isMangled( decl->linkage ) ) {
443                        // NOTE this is broken in Richard's original code in such a way that it never triggers (it
444                        // doesn't check decls that have the same manglename, and all C-linkage decls are defined to
445                        // have their name as their manglename, hence the error can never trigger).
446                        // The code here is closer to correct, but name mangling would have to be completely
447                        // isomorphic to C type-compatibility, which it may not be.
448                        if ( hasIncompatibleCDecl( name, mangleName, scope ) ) {
449                                SemanticError( decl, "conflicting overload of C function " );
450                        }
451                } else {
452                        // Check that a Cforall declaration doesn't override any C declaration
453                        if ( hasCompatibleCDecl( name, mangleName, scope ) ) {
454                                SemanticError( decl, "Cforall declaration hides C function " );
455                        }
456                }
457
458                // Skip repeat declarations of the same identifier
459                IdData * existing = lookupIdAtScope( name, mangleName, scope );
460                if ( existing && existing->id && addedIdConflicts( *existing, decl, deleteStmt, handleConflicts ) ) return;
461
462                // add to indexer
463                tables->idTable[ name ][ mangleName ] = IdData{ decl, baseExpr, deleteStmt };
464                ++tables->size;
465        }
466
467        void Indexer::addId( DeclarationWithType * decl, Expression * baseExpr ) {
468                // default handling of conflicts is to raise an error
469                addId( decl, [decl](IdData &, const std::string & msg) { SemanticError( decl, msg ); return true; }, baseExpr, decl->isDeleted ? decl : nullptr );
470        }
471
472        void Indexer::addDeletedId( DeclarationWithType * decl, BaseSyntaxNode * deleteStmt ) {
473                // default handling of conflicts is to raise an error
474                addId( decl, [decl](IdData &, const std::string & msg) { SemanticError( decl, msg ); return true; }, nullptr, deleteStmt );
475        }
476
477        bool addedTypeConflicts( NamedTypeDecl *existing, NamedTypeDecl *added ) {
478                if ( existing->get_base() == 0 ) {
479                        return false;
480                } else if ( added->get_base() == 0 ) {
481                        return true;
482                } else {
483                        SemanticError( added, "redeclaration of " );
484                }
485        }
486
487        void Indexer::addType( NamedTypeDecl *decl ) {
488                debugPrint( "Adding type " << decl->name << std::endl );
489                makeWritable();
490
491                const std::string &id = decl->get_name();
492                TypeTable::iterator existing = tables->typeTable.find( id );
493                if ( existing == tables->typeTable.end() ) {
494                        NamedTypeDecl *parent = tables->base.lookupTypeAtScope( id, scope );
495                        if ( ! parent || ! addedTypeConflicts( parent, decl ) ) {
496                                tables->typeTable.insert( existing, std::make_pair( id, decl ) );
497                                ++tables->size;
498                        }
499                } else {
500                        if ( ! addedTypeConflicts( existing->second, decl ) ) {
501                                existing->second = decl;
502                        }
503                }
504        }
505
506        bool addedDeclConflicts( AggregateDecl *existing, AggregateDecl *added ) {
507                if ( ! existing->body ) {
508                        return false;
509                } else if ( added->body ) {
510                        SemanticError( added, "redeclaration of " );
511                } // if
512                return true;
513        }
514
515        void Indexer::addStruct( const std::string &id ) {
516                debugPrint( "Adding fwd decl for struct " << id << std::endl );
517                addStruct( new StructDecl( id ) );
518        }
519
520        void Indexer::addStruct( StructDecl *decl ) {
521                debugPrint( "Adding struct " << decl->name << std::endl );
522                makeWritable();
523
524                const std::string &id = decl->get_name();
525                StructTable::iterator existing = tables->structTable.find( id );
526                if ( existing == tables->structTable.end() ) {
527                        StructDecl *parent = tables->base.lookupStructAtScope( id, scope );
528                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
529                                tables->structTable.insert( existing, std::make_pair( id, decl ) );
530                                ++tables->size;
531                        }
532                } else {
533                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
534                                existing->second = decl;
535                        }
536                }
537        }
538
539        void Indexer::addEnum( EnumDecl *decl ) {
540                debugPrint( "Adding enum " << decl->name << std::endl );
541                makeWritable();
542
543                const std::string &id = decl->get_name();
544                EnumTable::iterator existing = tables->enumTable.find( id );
545                if ( existing == tables->enumTable.end() ) {
546                        EnumDecl *parent = tables->base.lookupEnumAtScope( id, scope );
547                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
548                                tables->enumTable.insert( existing, std::make_pair( id, decl ) );
549                                ++tables->size;
550                        }
551                } else {
552                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
553                                existing->second = decl;
554                        }
555                }
556        }
557
558        void Indexer::addUnion( const std::string &id ) {
559                debugPrint( "Adding fwd decl for union " << id << std::endl );
560                addUnion( new UnionDecl( id ) );
561        }
562
563        void Indexer::addUnion( UnionDecl *decl ) {
564                debugPrint( "Adding union " << decl->name << std::endl );
565                makeWritable();
566
567                const std::string &id = decl->get_name();
568                UnionTable::iterator existing = tables->unionTable.find( id );
569                if ( existing == tables->unionTable.end() ) {
570                        UnionDecl *parent = tables->base.lookupUnionAtScope( id, scope );
571                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
572                                tables->unionTable.insert( existing, std::make_pair( id, decl ) );
573                                ++tables->size;
574                        }
575                } else {
576                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
577                                existing->second = decl;
578                        }
579                }
580        }
581
582        void Indexer::addTrait( TraitDecl *decl ) {
583                debugPrint( "Adding trait " << decl->name << std::endl );
584                makeWritable();
585
586                const std::string &id = decl->get_name();
587                TraitTable::iterator existing = tables->traitTable.find( id );
588                if ( existing == tables->traitTable.end() ) {
589                        TraitDecl *parent = tables->base.lookupTraitAtScope( id, scope );
590                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
591                                tables->traitTable.insert( existing, std::make_pair( id, decl ) );
592                                ++tables->size;
593                        }
594                } else {
595                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
596                                existing->second = decl;
597                        }
598                }
599        }
600
601        void Indexer::addMembers( AggregateDecl * aggr, Expression * expr, ConflictFunction handleConflicts ) {
602                for ( Declaration * decl : aggr->members ) {
603                        if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
604                                addId( dwt, handleConflicts, expr );
605                                if ( dwt->name == "" ) {
606                                        Type * t = dwt->get_type()->stripReferences();
607                                        if ( dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t ) ) {
608                                                Expression * base = expr->clone();
609                                                ResolvExpr::Cost cost = ResolvExpr::Cost::zero; // xxx - carry this cost into the indexer as a base cost?
610                                                ResolvExpr::referenceToRvalueConversion( base, cost );
611                                                addMembers( t->getAggr(), new MemberExpr( dwt, base ), handleConflicts );
612                                        }
613                                }
614                        }
615                }
616        }
617
618        void Indexer::addWith( std::list< Expression * > & withExprs, BaseSyntaxNode * withStmt ) {
619                for ( Expression * expr : withExprs ) {
620                        if ( expr->result ) {
621                                AggregateDecl * aggr = expr->result->stripReferences()->getAggr();
622                                assertf( aggr, "WithStmt expr has non-aggregate type: %s", toString( expr->result ).c_str() );
623
624                                addMembers( aggr, expr, [withStmt](IdData & existing, const std::string &) {
625                                        // on conflict, delete the identifier
626                                        existing.deleteStmt = withStmt;
627                                        return true;
628                                });
629                        }
630                }
631        }
632
633        void Indexer::addIds( const std::list< DeclarationWithType * > & decls ) {
634                for ( auto d : decls ) {
635                        addId( d );
636                }
637        }
638
639        void Indexer::addTypes( const std::list< TypeDecl * > & tds ) {
640                for ( auto td : tds ) {
641                        addType( td );
642                        addIds( td->assertions );
643                }
644        }
645
646        void Indexer::addFunctionType( FunctionType * ftype ) {
647                addTypes( ftype->forall );
648                addIds( ftype->returnVals );
649                addIds( ftype->parameters );
650        }
651
652        void Indexer::enterScope() {
653                ++scope;
654
655                if ( doDebug ) {
656                        std::cerr << "--- Entering scope " << scope << std::endl;
657                }
658        }
659
660        void Indexer::leaveScope() {
661                using std::cerr;
662
663                assert( scope > 0 && "cannot leave initial scope" );
664                if ( doDebug ) {
665                        cerr << "--- Leaving scope " << scope << " containing" << std::endl;
666                }
667                --scope;
668
669                while ( tables && tables->scope > scope ) {
670                        if ( doDebug ) {
671                                dump( tables->idTable, cerr );
672                                dump( tables->typeTable, cerr );
673                                dump( tables->structTable, cerr );
674                                dump( tables->enumTable, cerr );
675                                dump( tables->unionTable, cerr );
676                                dump( tables->traitTable, cerr );
677                        }
678
679                        // swap tables for base table until we find one at an appropriate scope
680                        Indexer::Impl *base = newRef( tables->base.tables );
681                        deleteRef( tables );
682                        tables = base;
683                }
684        }
685
686        void Indexer::print( std::ostream &os, int indent ) const {
687                using std::cerr;
688
689                if ( tables ) {
690                        os << "--- scope " << tables->scope << " ---" << std::endl;
691
692                        os << "===idTable===" << std::endl;
693                        dump( tables->idTable, os );
694                        os << "===typeTable===" << std::endl;
695                        dump( tables->typeTable, os );
696                        os << "===structTable===" << std::endl;
697                        dump( tables->structTable, os );
698                        os << "===enumTable===" << std::endl;
699                        dump( tables->enumTable, os );
700                        os << "===unionTable===" << std::endl;
701                        dump( tables->unionTable, os );
702                        os << "===contextTable===" << std::endl;
703                        dump( tables->traitTable, os );
704
705                        tables->base.print( os, indent );
706                } else {
707                        os << "--- end ---" << std::endl;
708                }
709
710        }
711
712        Expression * Indexer::IdData::combine( ResolvExpr::Cost & cost ) const {
713                Expression * ret = nullptr;
714                if ( baseExpr ) {
715                        Expression * base = baseExpr->clone();
716                        ResolvExpr::referenceToRvalueConversion( base, cost );
717                        ret = new MemberExpr( id, base );
718                        // xxx - this introduces hidden environments, for now remove them.
719                        // std::swap( base->env, ret->env );
720                        delete base->env;
721                        base->env = nullptr;
722                } else {
723                        ret = new VariableExpr( id );
724                }
725                if ( deleteStmt ) ret = new DeletedExpr( ret, deleteStmt );
726                return ret;
727        }
728} // namespace SymTab
729
730// Local Variables: //
731// tab-width: 4 //
732// mode: c++ //
733// compile-command: "make install" //
734// End: //
Note: See TracBrowser for help on using the repository browser.