source: src/SymTab/Indexer.cc @ ef5b828

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since ef5b828 was ef5b828, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Indexer now has const lookup by default

  • Property mode set to 100644
File size: 24.8 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 : Aaron B. Moss
12// Last Modified On : Fri Mar  8 13:55:00 2019
13// Update Count     : 21
14//
15
16#include "Indexer.h"
17
18#include <cassert>                 // for assert, strict_dynamic_cast
19#include <string>                  // for string, operator<<, operator!=
20#include <memory>                  // for shared_ptr, make_shared
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#include <vector>                  // for vector
25
26#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
27#include "Common/SemanticError.h"  // for SemanticError
28#include "Common/utility.h"        // for cloneAll
29#include "Common/Stats/Counter.h"  // for counters
30#include "GenPoly/GenPoly.h"       // for getFunctionType
31#include "InitTweak/InitTweak.h"   // for isConstructor, isCopyFunction, isC...
32#include "Mangler.h"               // for Mangler
33#include "Parser/LinkageSpec.h"    // for isMangled, isOverridable, Spec
34#include "ResolvExpr/typeops.h"    // for typesCompatible
35#include "SynTree/Constant.h"      // for Constant
36#include "SynTree/Declaration.h"   // for DeclarationWithType, FunctionDecl
37#include "SynTree/Expression.h"    // for Expression, ImplicitCopyCtorExpr
38#include "SynTree/Initializer.h"   // for Initializer
39#include "SynTree/Statement.h"     // for CompoundStmt, Statement, ForStmt (...
40#include "SynTree/Type.h"          // for Type, StructInstType, UnionInstType
41
42namespace SymTab {
43
44        // Statistics block
45        namespace {
46                static inline auto stats() {
47                        using namespace Stats::Counters;
48                        static auto group   = build<CounterGroup>("Indexers");
49                        static struct {
50                                SimpleCounter * count;
51                                AverageCounter<double> * size;
52                                SimpleCounter * new_scopes;
53                                SimpleCounter * lazy_scopes;
54                                AverageCounter<double> * avg_scope_depth;
55                                MaxCounter<size_t> * max_scope_depth;
56                                SimpleCounter * add_calls;
57                                SimpleCounter * lookup_calls;
58                                SimpleCounter * map_lookups;
59                                SimpleCounter * map_mutations;
60                        } ret = {
61                                .count   = build<SimpleCounter>("Count", group),
62                                .size    = build<AverageCounter<double>>("Average Size", group),
63                                .new_scopes = build<SimpleCounter>("Scopes", group),
64                                .lazy_scopes = build<SimpleCounter>("Lazy Scopes", group),
65                                .avg_scope_depth = build<AverageCounter<double>>("Average Scope", group),
66                                .max_scope_depth = build<MaxCounter<size_t>>("Max Scope", group),
67                                .add_calls = build<SimpleCounter>("Add Calls", group),
68                                .lookup_calls = build<SimpleCounter>("Lookup Calls", group),
69                                .map_lookups = build<SimpleCounter>("Map Lookups", group),
70                                .map_mutations = build<SimpleCounter>("Map Mutations", group)
71                        };
72                        return ret;
73                }
74        }
75
76        Indexer::Indexer()
77        : idTable(), typeTable(), structTable(), enumTable(), unionTable(), traitTable(),
78          prevScope(), scope( 0 ), repScope( 0 ) { ++* stats().count; }
79
80        Indexer::~Indexer() {
81                stats().size->push( idTable ? idTable->size() : 0 );
82        }
83
84        void Indexer::lazyInitScope() {
85                if ( repScope < scope ) {
86                        ++* stats().lazy_scopes;
87                        // create rollback
88                        prevScope = std::make_shared<Indexer>( * this );
89                        // update repScope
90                        repScope = scope;
91                }
92        }
93
94        void Indexer::enterScope() {
95                ++scope;
96
97                ++* stats().new_scopes;
98                stats().avg_scope_depth->push( scope );
99                stats().max_scope_depth->push( scope );
100        }
101
102        void Indexer::leaveScope() {
103                if ( repScope == scope ) {
104                        Ptr prev = prevScope;           // make sure prevScope stays live
105                        * this = std::move(* prevScope);  // replace with previous scope
106                }
107
108                --scope;
109        }
110
111        void Indexer::lookupId( const std::string & id, std::list< IdData > &out ) const {
112                ++* stats().lookup_calls;
113                if ( ! idTable ) return;
114
115                ++* stats().map_lookups;
116                auto decls = idTable->find( id );
117                if ( decls == idTable->end() ) return;
118
119                for ( auto decl : *(decls->second) ) {
120                        out.push_back( decl.second );
121                }
122        }
123
124        const NamedTypeDecl * Indexer::lookupType( const std::string & id ) const { return lookupMutableType(id); }
125        NamedTypeDecl * Indexer::lookupMutableType( const std::string & id ) const {
126                ++* stats().lookup_calls;
127                if ( ! typeTable ) return nullptr;
128                ++* stats().map_lookups;
129                auto it = typeTable->find( id );
130                return it == typeTable->end() ? nullptr : it->second.decl;
131        }
132
133        const StructDecl * Indexer::lookupStruct( const std::string & id ) const { return lookupMutableStruct(id); }
134        StructDecl * Indexer::lookupMutableStruct( const std::string & id ) const {
135                ++* stats().lookup_calls;
136                if ( ! structTable ) return nullptr;
137                ++* stats().map_lookups;
138                auto it = structTable->find( id );
139                return it == structTable->end() ? nullptr : it->second.decl;
140        }
141
142        const EnumDecl * Indexer::lookupEnum( const std::string & id ) const { return lookupMutableEnum(id); }
143        EnumDecl * Indexer::lookupMutableEnum( const std::string & id ) const {
144                ++* stats().lookup_calls;
145                if ( ! enumTable ) return nullptr;
146                ++* stats().map_lookups;
147                auto it = enumTable->find( id );
148                return it == enumTable->end() ? nullptr : it->second.decl;
149        }
150
151        const UnionDecl * Indexer::lookupUnion( const std::string & id ) const { return lookupMutableUnion(id); }
152        UnionDecl * Indexer::lookupMutableUnion( const std::string & id ) const {
153                ++* stats().lookup_calls;
154                if ( ! unionTable ) return nullptr;
155                ++* stats().map_lookups;
156                auto it = unionTable->find( id );
157                return it == unionTable->end() ? nullptr : it->second.decl;
158        }
159
160        const TraitDecl * Indexer::lookupTrait( const std::string & id ) const { return lookupMutableTrait(id); }
161        TraitDecl * Indexer::lookupMutableTrait( const std::string & id ) const {
162                ++* stats().lookup_calls;
163                if ( ! traitTable ) return nullptr;
164                ++* stats().map_lookups;
165                auto it = traitTable->find( id );
166                return it == traitTable->end() ? nullptr : it->second.decl;
167        }
168
169        const Indexer * Indexer::atScope( unsigned long target ) const {
170                // by lazy construction, final indexer in list has repScope 0, cannot be > target
171                // otherwise, will find first scope representing the target
172                const Indexer * indexer = this;
173                while ( indexer->repScope > target ) {
174                        indexer = indexer->prevScope.get();
175                }
176                return indexer;
177        }
178
179        const NamedTypeDecl * Indexer::globalLookupType( const std::string & id ) const {
180                return atScope( 0 )->lookupType( id );
181        }
182
183        const StructDecl * Indexer::globalLookupStruct( const std::string & id ) const {
184                return atScope( 0 )->lookupStruct( id );
185        }
186
187        const UnionDecl * Indexer::globalLookupUnion( const std::string & id ) const {
188                return atScope( 0 )->lookupUnion( id );
189        }
190
191        const EnumDecl * Indexer::globalLookupEnum( const std::string & id ) const {
192                return atScope( 0 )->lookupEnum( id );
193        }
194
195        bool isFunction( DeclarationWithType * decl ) {
196                return GenPoly::getFunctionType( decl->get_type() );
197        }
198
199        bool isObject( DeclarationWithType * decl ) {
200                return ! isFunction( decl );
201        }
202
203        bool isDefinition( DeclarationWithType * decl ) {
204                if ( FunctionDecl * func = dynamic_cast< FunctionDecl * >( decl ) ) {
205                        // a function is a definition if it has a body
206                        return func->statements;
207                } else {
208                        // an object is a definition if it is not marked extern.
209                        // both objects must be marked extern
210                        return ! decl->get_storageClasses().is_extern;
211                }
212        }
213
214
215        bool Indexer::addedIdConflicts(
216                        const Indexer::IdData & existing, DeclarationWithType * added,
217                        Indexer::OnConflict handleConflicts, BaseSyntaxNode * deleteStmt ) {
218                // if we're giving the same name mangling to things of different types then there is
219                // something wrong
220                assert( (isObject( added ) && isObject( existing.id ) )
221                        || ( isFunction( added ) && isFunction( existing.id ) ) );
222
223                if ( LinkageSpec::isOverridable( existing.id->linkage ) ) {
224                        // new definition shadows the autogenerated one, even at the same scope
225                        return false;
226                } else if ( LinkageSpec::isMangled( added->linkage )
227                                || ResolvExpr::typesCompatible(
228                                        added->get_type(), existing.id->get_type(), Indexer() ) ) {
229
230                        // it is a conflict if one declaration is deleted and the other is not
231                        if ( deleteStmt && ! existing.deleteStmt ) {
232                                if ( handleConflicts.mode == OnConflict::Error ) {
233                                        SemanticError( added, "deletion of defined identifier " );
234                                }
235                                return true;
236                        } else if ( ! deleteStmt && existing.deleteStmt ) {
237                                if ( handleConflicts.mode == OnConflict::Error ) {
238                                        SemanticError( added, "definition of deleted identifier " );
239                                }
240                                return true;
241                        }
242
243                        if ( isDefinition( added ) && isDefinition( existing.id ) ) {
244                                if ( handleConflicts.mode == OnConflict::Error ) {
245                                        SemanticError( added,
246                                                isFunction( added ) ?
247                                                        "duplicate function definition for " :
248                                                        "duplicate object definition for " );
249                                }
250                                return true;
251                        } // if
252                } else {
253                        if ( handleConflicts.mode == OnConflict::Error ) {
254                                SemanticError( added, "duplicate definition for " );
255                        }
256                        return true;
257                } // if
258
259                return true;
260        }
261
262        bool Indexer::hasCompatibleCDecl( const std::string & id, const std::string &mangleName ) const {
263                if ( ! idTable ) return false;
264
265                ++* stats().map_lookups;
266                auto decls = idTable->find( id );
267                if ( decls == idTable->end() ) return false;
268
269                for ( auto decl : *(decls->second) ) {
270                        // skip other scopes (hidden by this decl)
271                        if ( decl.second.scope != scope ) continue;
272                        // check for C decl with compatible type (by mangleName)
273                        if ( ! LinkageSpec::isMangled( decl.second.id->linkage ) && decl.first == mangleName ) {
274                                return true;
275                        }
276                }
277
278                return false;
279        }
280
281        bool Indexer::hasIncompatibleCDecl(
282                        const std::string & id, const std::string &mangleName ) const {
283                if ( ! idTable ) return false;
284
285                ++* stats().map_lookups;
286                auto decls = idTable->find( id );
287                if ( decls == idTable->end() ) return false;
288
289                for ( auto decl : *(decls->second) ) {
290                        // skip other scopes (hidden by this decl)
291                        if ( decl.second.scope != scope ) continue;
292                        // check for C decl with incompatible type (by manglename)
293                        if ( ! LinkageSpec::isMangled( decl.second.id->linkage ) && decl.first != mangleName ) {
294                                return true;
295                        }
296                }
297
298                return false;
299        }
300
301        /// gets the base type of the first parameter; decl must be a ctor/dtor/assignment function
302        std::string getOtypeKey( FunctionDecl * function ) {
303                auto& params = function->type->parameters;
304                assert( ! params.empty() );
305                // use base type of pointer, so that qualifiers on the pointer type aren't considered.
306                Type * base = InitTweak::getPointerBase( params.front()->get_type() );
307                assert( base );
308                return Mangler::mangle( base );
309        }
310
311        /// gets the declaration for the function acting on a type specified by otype key,
312        /// nullptr if none such
313        FunctionDecl * getFunctionForOtype( DeclarationWithType * decl, const std::string& otypeKey ) {
314                FunctionDecl * func = dynamic_cast< FunctionDecl * >( decl );
315                if ( ! func || otypeKey != getOtypeKey( func ) ) return nullptr;
316                return func;
317        }
318
319        bool Indexer::removeSpecialOverrides(
320                        Indexer::IdData& data, Indexer::MangleTable::Ptr& mangleTable ) {
321                // if a type contains user defined ctor/dtor/assign, then special rules trigger, which
322                // determinethe set of ctor/dtor/assign that can be used  by the requester. In particular,
323                // if the user defines a default ctor, then the generated default ctor is unavailable,
324                // likewise for copy ctor and dtor. If the user defines any ctor/dtor, then no generated
325                // field ctors are available. If the user defines any ctor then the generated default ctor
326                // is unavailable (intrinsic default ctor must be overridden exactly). If the user defines
327                // anything that looks like a copy constructor, then the generated copy constructor is
328                // unavailable, and likewise for the assignment operator.
329
330                // only relevant on function declarations
331                FunctionDecl * function = dynamic_cast< FunctionDecl * >( data.id );
332                if ( ! function ) return true;
333                // only need to perform this check for constructors, destructors, and assignment functions
334                if ( ! CodeGen::isCtorDtorAssign( data.id->name ) ) return true;
335
336                // set up information for this type
337                bool dataIsUserDefinedFunc = ! LinkageSpec::isOverridable( function->linkage );
338                bool dataIsCopyFunc = InitTweak::isCopyFunction( function, function->name );
339                std::string dataOtypeKey = getOtypeKey( function );
340
341                if ( dataIsUserDefinedFunc && dataIsCopyFunc ) {
342                        // this is a user-defined copy function
343                        // if this is the first such, delete/remove non-user-defined overloads as needed
344                        std::vector< std::string > removed;
345                        std::vector< MangleTable::value_type > deleted;
346                        bool alreadyUserDefinedFunc = false;
347
348                        for ( const auto& entry : * mangleTable ) {
349                                // skip decls that aren't functions or are for the wrong type
350                                FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
351                                if ( ! decl ) continue;
352
353                                bool isCopyFunc = InitTweak::isCopyFunction( decl, decl->name );
354                                if ( ! LinkageSpec::isOverridable( decl->linkage ) ) {
355                                        // matching user-defined function
356                                        if ( isCopyFunc ) {
357                                                // mutation already performed, return early
358                                                return true;
359                                        } else {
360                                                // note that non-copy deletions already performed
361                                                alreadyUserDefinedFunc = true;
362                                        }
363                                } else {
364                                        // non-user-defined function; mark for deletion/removal as appropriate
365                                        if ( isCopyFunc ) {
366                                                removed.push_back( entry.first );
367                                        } else if ( ! alreadyUserDefinedFunc ) {
368                                                deleted.push_back( entry );
369                                        }
370                                }
371                        }
372
373                        // perform removals from mangle table, and deletions if necessary
374                        for ( const auto& key : removed ) {
375                                ++* stats().map_mutations;
376                                mangleTable = mangleTable->erase( key );
377                        }
378                        if ( ! alreadyUserDefinedFunc ) for ( const auto& entry : deleted ) {
379                                ++* stats().map_mutations;
380                                mangleTable = mangleTable->set( entry.first, IdData{ entry.second, function } );
381                        }
382                } else if ( dataIsUserDefinedFunc ) {
383                        // this is a user-defined non-copy function
384                        // if this is the first user-defined function, delete non-user-defined overloads
385                        std::vector< MangleTable::value_type > deleted;
386
387                        for ( const auto& entry : * mangleTable ) {
388                                // skip decls that aren't functions or are for the wrong type
389                                FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
390                                if ( ! decl ) continue;
391
392                                // exit early if already a matching user-defined function;
393                                // earlier function will have mutated table
394                                if ( ! LinkageSpec::isOverridable( decl->linkage ) ) return true;
395
396                                // skip mutating intrinsic functions
397                                if ( decl->linkage == LinkageSpec::Intrinsic ) continue;
398
399                                // user-defined non-copy functions do not override copy functions
400                                if ( InitTweak::isCopyFunction( decl, decl->name ) ) continue;
401
402                                // this function to be deleted after mangleTable iteration is complete
403                                deleted.push_back( entry );
404                        }
405
406                        // mark deletions to update mangle table
407                        // this needs to be a separate loop because of iterator invalidation
408                        for ( const auto& entry : deleted ) {
409                                ++* stats().map_mutations;
410                                mangleTable = mangleTable->set( entry.first, IdData{ entry.second, function } );
411                        }
412                } else if ( function->linkage != LinkageSpec::Intrinsic ) {
413                        // this is an overridable generated function
414                        // if there already exists a matching user-defined function, delete this appropriately
415                        for ( const auto& entry : * mangleTable ) {
416                                // skip decls that aren't functions or are for the wrong type
417                                FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
418                                if ( ! decl ) continue;
419
420                                // skip non-user-defined functions
421                                if ( LinkageSpec::isOverridable( decl->linkage ) ) continue;
422
423                                if ( dataIsCopyFunc ) {
424                                        // remove current function if exists a user-defined copy function
425                                        // since the signatures for copy functions don't need to match exactly, using
426                                        // a delete statement is the wrong approach
427                                        if ( InitTweak::isCopyFunction( decl, decl->name ) ) return false;
428                                } else {
429                                        // mark current function deleted by first user-defined function found
430                                        data.deleteStmt = decl;
431                                        return true;
432                                }
433                        }
434                }
435
436                // nothing (more) to fix, return true
437                return true;
438        }
439
440        void Indexer::addId(
441                        DeclarationWithType * decl, OnConflict handleConflicts, Expression * baseExpr,
442                        BaseSyntaxNode * deleteStmt ) {
443                ++* stats().add_calls;
444                const std::string &name = decl->name;
445                if ( name == "" ) return;
446
447                std::string mangleName;
448                if ( LinkageSpec::isOverridable( decl->linkage ) ) {
449                        // mangle the name without including the appropriate suffix, so overridable routines
450                        // are placed into the same "bucket" as their user defined versions.
451                        mangleName = Mangler::mangle( decl, false );
452                } else {
453                        mangleName = Mangler::mangle( decl );
454                } // if
455
456                // this ensures that no two declarations with the same unmangled name at the same scope
457                // both have C linkage
458                if ( LinkageSpec::isMangled( decl->linkage ) ) {
459                        // Check that a Cforall declaration doesn't override any C declaration
460                        if ( hasCompatibleCDecl( name, mangleName ) ) {
461                                SemanticError( decl, "Cforall declaration hides C function " );
462                        }
463                } else {
464                        // NOTE: only correct if name mangling is completely isomorphic to C
465                        // type-compatibility, which it may not be.
466                        if ( hasIncompatibleCDecl( name, mangleName ) ) {
467                                SemanticError( decl, "conflicting overload of C function " );
468                        }
469                }
470
471                // ensure tables exist and add identifier
472                MangleTable::Ptr mangleTable;
473                if ( ! idTable ) {
474                        idTable = IdTable::new_ptr();
475                        mangleTable = MangleTable::new_ptr();
476                } else {
477                        ++* stats().map_lookups;
478                        auto decls = idTable->find( name );
479                        if ( decls == idTable->end() ) {
480                                mangleTable = MangleTable::new_ptr();
481                        } else {
482                                mangleTable = decls->second;
483                                // skip in-scope repeat declarations of same identifier
484                                ++* stats().map_lookups;
485                                auto existing = mangleTable->find( mangleName );
486                                if ( existing != mangleTable->end()
487                                                && existing->second.scope == scope
488                                                && existing->second.id ) {
489                                        if ( addedIdConflicts( existing->second, decl, handleConflicts, deleteStmt ) ) {
490                                                if ( handleConflicts.mode == OnConflict::Delete ) {
491                                                        // set delete expression for conflicting identifier
492                                                        lazyInitScope();
493                                                        * stats().map_mutations += 2;
494                                                        idTable = idTable->set(
495                                                                name,
496                                                                mangleTable->set(
497                                                                        mangleName,
498                                                                        IdData{ existing->second, handleConflicts.deleteStmt } ) );
499                                                }
500                                                return;
501                                        }
502                                }
503                        }
504                }
505
506                // add/overwrite with new identifier
507                lazyInitScope();
508                IdData data{ decl, baseExpr, deleteStmt, scope };
509                // Ensure that auto-generated ctor/dtor/assignment are deleted if necessary
510                if ( ! removeSpecialOverrides( data, mangleTable ) ) return;
511                * stats().map_mutations += 2;
512                idTable = idTable->set( name, mangleTable->set( mangleName, std::move(data) ) );
513        }
514
515        void Indexer::addId( DeclarationWithType * decl, Expression * baseExpr ) {
516                // default handling of conflicts is to raise an error
517                addId( decl, OnConflict::error(), baseExpr, decl->isDeleted ? decl : nullptr );
518        }
519
520        void Indexer::addDeletedId( DeclarationWithType * decl, BaseSyntaxNode * deleteStmt ) {
521                // default handling of conflicts is to raise an error
522                addId( decl, OnConflict::error(), nullptr, deleteStmt );
523        }
524
525        bool addedTypeConflicts( NamedTypeDecl * existing, NamedTypeDecl * added ) {
526                if ( existing->base == nullptr ) {
527                        return false;
528                } else if ( added->base == nullptr ) {
529                        return true;
530                } else {
531                        assert( existing->base && added->base );
532                        // typedef redeclarations are errors only if types are different
533                        if ( ! ResolvExpr::typesCompatible( existing->base, added->base, Indexer() ) ) {
534                                SemanticError( added->location, "redeclaration of " + added->name );
535                        }
536                }
537                // does not need to be added to the table if both existing and added have a base that are
538                // the same
539                return true;
540        }
541
542        void Indexer::addType( NamedTypeDecl * decl ) {
543                ++* stats().add_calls;
544                const std::string & id = decl->name;
545
546                if ( ! typeTable ) {
547                        typeTable = TypeTable::new_ptr();
548                } else {
549                        ++* stats().map_lookups;
550                        auto existing = typeTable->find( id );
551                        if ( existing != typeTable->end()
552                                && existing->second.scope == scope
553                                && addedTypeConflicts( existing->second.decl, decl ) ) return;
554                }
555
556                lazyInitScope();
557                ++* stats().map_mutations;
558                typeTable = typeTable->set( id, Scoped<NamedTypeDecl>{ decl, scope } );
559        }
560
561        bool addedDeclConflicts( AggregateDecl * existing, AggregateDecl * added ) {
562                if ( ! existing->body ) {
563                        return false;
564                } else if ( added->body ) {
565                        SemanticError( added, "redeclaration of " );
566                } // if
567                return true;
568        }
569
570        void Indexer::addStruct( const std::string & id ) {
571                addStruct( new StructDecl( id ) );
572        }
573
574        void Indexer::addStruct( StructDecl * decl ) {
575                ++* stats().add_calls;
576                const std::string & id = decl->name;
577
578                if ( ! structTable ) {
579                        structTable = StructTable::new_ptr();
580                } else {
581                        ++* stats().map_lookups;
582                        auto existing = structTable->find( id );
583                        if ( existing != structTable->end()
584                                && existing->second.scope == scope
585                                && addedDeclConflicts( existing->second.decl, decl ) ) return;
586                }
587
588                lazyInitScope();
589                ++* stats().map_mutations;
590                structTable = structTable->set( id, Scoped<StructDecl>{ decl, scope } );
591        }
592
593        void Indexer::addEnum( EnumDecl * decl ) {
594                ++* stats().add_calls;
595                const std::string & id = decl->name;
596
597                if ( ! enumTable ) {
598                        enumTable = EnumTable::new_ptr();
599                } else {
600                        ++* stats().map_lookups;
601                        auto existing = enumTable->find( id );
602                        if ( existing != enumTable->end()
603                                && existing->second.scope == scope
604                                && addedDeclConflicts( existing->second.decl, decl ) ) return;
605                }
606
607                lazyInitScope();
608                ++* stats().map_mutations;
609                enumTable = enumTable->set( id, Scoped<EnumDecl>{ decl, scope } );
610        }
611
612        void Indexer::addUnion( const std::string & id ) {
613                addUnion( new UnionDecl( id ) );
614        }
615
616        void Indexer::addUnion( UnionDecl * decl ) {
617                ++* stats().add_calls;
618                const std::string & id = decl->name;
619
620                if ( ! unionTable ) {
621                        unionTable = UnionTable::new_ptr();
622                } else {
623                        ++* stats().map_lookups;
624                        auto existing = unionTable->find( id );
625                        if ( existing != unionTable->end()
626                                && existing->second.scope == scope
627                                && addedDeclConflicts( existing->second.decl, decl ) ) return;
628                }
629
630                lazyInitScope();
631                ++* stats().map_mutations;
632                unionTable = unionTable->set( id, Scoped<UnionDecl>{ decl, scope } );
633        }
634
635        void Indexer::addTrait( TraitDecl * decl ) {
636                ++* stats().add_calls;
637                const std::string & id = decl->name;
638
639                if ( ! traitTable ) {
640                        traitTable = TraitTable::new_ptr();
641                } else {
642                        ++* stats().map_lookups;
643                        auto existing = traitTable->find( id );
644                        if ( existing != traitTable->end()
645                                && existing->second.scope == scope
646                                && addedDeclConflicts( existing->second.decl, decl ) ) return;
647                }
648
649                lazyInitScope();
650                ++* stats().map_mutations;
651                traitTable = traitTable->set( id, Scoped<TraitDecl>{ decl, scope } );
652        }
653
654        void Indexer::addMembers( AggregateDecl * aggr, Expression * expr,
655                        OnConflict handleConflicts ) {
656                for ( Declaration * decl : aggr->members ) {
657                        if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
658                                addId( dwt, handleConflicts, expr );
659                                if ( dwt->name == "" ) {
660                                        Type * t = dwt->get_type()->stripReferences();
661                                        if ( dynamic_cast<StructInstType *>( t ) || dynamic_cast<UnionInstType *>( t ) ) {
662                                                Expression * base = expr->clone();
663                                                ResolvExpr::Cost cost = ResolvExpr::Cost::zero; // xxx - carry this cost into the indexer as a base cost?
664                                                ResolvExpr::referenceToRvalueConversion( base, cost );
665                                                addMembers( t->getAggr(), new MemberExpr( dwt, base ), handleConflicts );
666                                        }
667                                }
668                        }
669                }
670        }
671
672        void Indexer::addWith( std::list< Expression * > & withExprs, BaseSyntaxNode * withStmt ) {
673                for ( Expression * expr : withExprs ) {
674                        if ( expr->result ) {
675                                AggregateDecl * aggr = expr->result->stripReferences()->getAggr();
676                                assertf( aggr, "WithStmt expr has non-aggregate type: %s", toString( expr->result ).c_str() );
677
678                                addMembers( aggr, expr, OnConflict::deleteWith( withStmt ) );
679                        }
680                }
681        }
682
683        void Indexer::addIds( const std::list< DeclarationWithType * > & decls ) {
684                for ( auto d : decls ) {
685                        addId( d );
686                }
687        }
688
689        void Indexer::addTypes( const std::list< TypeDecl * > & tds ) {
690                for ( auto td : tds ) {
691                        addType( td );
692                        addIds( td->assertions );
693                }
694        }
695
696        void Indexer::addFunctionType( FunctionType * ftype ) {
697                addTypes( ftype->forall );
698                addIds( ftype->returnVals );
699                addIds( ftype->parameters );
700        }
701
702        Expression * Indexer::IdData::combine( ResolvExpr::Cost & cost ) const {
703                Expression * ret = nullptr;
704                if ( baseExpr ) {
705                        Expression * base = baseExpr->clone();
706                        ResolvExpr::referenceToRvalueConversion( base, cost );
707                        ret = new MemberExpr( id, base );
708                        // xxx - this introduces hidden environments, for now remove them.
709                        // std::swap( base->env, ret->env );
710                        delete base->env;
711                        base->env = nullptr;
712                } else {
713                        ret = new VariableExpr( id );
714                }
715                if ( deleteStmt ) ret = new DeletedExpr( ret, deleteStmt );
716                return ret;
717        }
718} // namespace SymTab
719
720// Local Variables: //
721// tab-width: 4 //
722// mode: c++ //
723// compile-command: "make install" //
724// End: //
Note: See TracBrowser for help on using the repository browser.