source: src/SymTab/Indexer.cc @ aa22c60

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since aa22c60 was 1cb7fab2, checked in by tdelisle <tdelisle@…>, 5 years ago

Added better support for enabling/disabling/compiling-out statistics

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