source: src/SymTab/Indexer.cc @ 34737de

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since 34737de was 79de2210, checked in by tdelisle <tdelisle@…>, 5 years ago

Instrumented Indexer at little

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