source: src/AST/SymbolTable.cpp @ 72abc90a

Last change on this file since 72abc90a was 85855b0, checked in by JiadaL <j82liang@…>, 6 weeks ago
  1. Implement enum cast; 2. Change valueE so that opague enum returns quasi_void; 3. change enum hiding interpretation and pass visiting scheme
  • Property mode set to 100644
File size: 28.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// SymbolTable.cpp --
8//
9// Author           : Aaron B. Moss
10// Created On       : Wed May 29 11:00:00 2019
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Wed May 29 11:00:00 2019
13// Update Count     : 1
14//
15
16#include "SymbolTable.hpp"
17
18#include <cassert>
19
20#include "Copy.hpp"
21#include "Decl.hpp"
22#include "Expr.hpp"
23#include "Inspect.hpp"
24#include "Type.hpp"
25#include "CodeGen/OperatorTable.hpp"       // for isCtorDtorAssign
26#include "Common/SemanticError.hpp"
27#include "Common/Stats/Counter.hpp"
28#include "GenPoly/GenPoly.hpp"
29#include "InitTweak/InitTweak.hpp"
30#include "ResolvExpr/Cost.hpp"
31#include "ResolvExpr/CandidateFinder.hpp"  // for referenceToRvalueConversion
32#include "ResolvExpr/Unify.hpp"
33#include "SymTab/Mangler.hpp"
34
35namespace ast {
36
37// Statistics block
38namespace {
39        static inline auto stats() {
40                using namespace Stats::Counters;
41                static auto group   = build<CounterGroup>("Symbol Tables");
42                static struct {
43                        SimpleCounter * count;
44                        AverageCounter<double> * size;
45                        SimpleCounter * new_scopes;
46                        SimpleCounter * lazy_scopes;
47                        AverageCounter<double> * avg_scope_depth;
48                        MaxCounter<size_t> * max_scope_depth;
49                        SimpleCounter * add_calls;
50                        SimpleCounter * lookup_calls;
51                        SimpleCounter * map_lookups;
52                        SimpleCounter * map_mutations;
53                } ret = {
54                        .count   = build<SimpleCounter>("Count", group),
55                        .size    = build<AverageCounter<double>>("Average Size", group),
56                        .new_scopes = build<SimpleCounter>("Scopes", group),
57                        .lazy_scopes = build<SimpleCounter>("Lazy Scopes", group),
58                        .avg_scope_depth = build<AverageCounter<double>>("Average Scope", group),
59                        .max_scope_depth = build<MaxCounter<size_t>>("Max Scope", group),
60                        .add_calls = build<SimpleCounter>("Add Calls", group),
61                        .lookup_calls = build<SimpleCounter>("Lookup Calls", group),
62                        .map_lookups = build<SimpleCounter>("Map Lookups", group),
63                        .map_mutations = build<SimpleCounter>("Map Mutations", group)
64                };
65                return ret;
66        }
67}
68
69Expr * SymbolTable::IdData::combine( const CodeLocation & loc, ResolvExpr::Cost & cost ) const {
70        Expr * ret;
71        if ( baseExpr ) {
72                if (baseExpr->env) {
73                        Expr * base = deepCopy(baseExpr);
74                        const TypeSubstitution * subs = baseExpr->env;
75                        base->env = nullptr;
76                        ret = new MemberExpr{loc, id, referenceToRvalueConversion( base, cost )};
77                        ret->env = subs;
78                } else {
79                        ret = new MemberExpr{ loc, id, referenceToRvalueConversion( baseExpr, cost ) };
80                }
81        } else {
82                ret = new VariableExpr{ loc, id };
83        }
84        if ( deleter ) { ret = new DeletedExpr{ loc, ret, deleter }; }
85        return ret;
86}
87
88SymbolTable::SymbolTable( ErrorDetection errorMode )
89: idTable(), typeTable(), structTable(), enumTable(), unionTable(), traitTable(),
90  prevScope(), scope( 0 ), repScope( 0 ), errorMode(errorMode) { ++*stats().count; }
91
92SymbolTable::~SymbolTable() { stats().size->push( idTable ? idTable->size() : 0 ); }
93
94void SymbolTable::OnFindError( CodeLocation location, std::string error ) const {
95        assertf( errorMode != AssertClean, "Name collision/redefinition, found during a compilation phase where none should be possible.  Detail: %s", error.c_str() );
96        if (errorMode == ValidateOnAdd) {
97                SemanticError(location, error);
98        }
99        assertf( errorMode == IgnoreErrors, "Unrecognized symbol-table error mode %d", errorMode );
100}
101
102void SymbolTable::enterScope() {
103        ++scope;
104
105        ++*stats().new_scopes;
106        stats().avg_scope_depth->push( scope );
107        stats().max_scope_depth->push( scope );
108}
109
110void SymbolTable::leaveScope() {
111        if ( repScope == scope ) {
112                Ptr prev = prevScope;           // make sure prevScope stays live
113                *this = std::move(*prevScope);  // replace with previous scope
114        }
115
116        --scope;
117}
118
119SymbolTable::SpecialFunctionKind SymbolTable::getSpecialFunctionKind(const std::string & name) {
120        if (name == "?{}") return CTOR;
121        if (name == "^?{}") return DTOR;
122        if (name == "?=?") return ASSIGN;
123        return NUMBER_OF_KINDS;
124}
125
126std::vector<SymbolTable::IdData> SymbolTable::lookupId( const std::string &id ) const {
127        static Stats::Counters::CounterGroup * name_lookup_stats = Stats::Counters::build<Stats::Counters::CounterGroup>("Name Lookup Stats");
128        static std::map<std::string, Stats::Counters::SimpleCounter *> lookups_by_name;
129        static std::map<std::string, Stats::Counters::SimpleCounter *> candidates_by_name;
130
131        SpecialFunctionKind kind = getSpecialFunctionKind(id);
132        if (kind != NUMBER_OF_KINDS) return specialLookupId(kind);
133
134        ++*stats().lookup_calls;
135        if ( ! idTable ) return {};
136
137        ++*stats().map_lookups;
138        auto decls = idTable->find( id );
139        if ( decls == idTable->end() ) return {};
140
141        std::vector<IdData> out;
142        for ( auto decl : *(decls->second) ) {
143                out.push_back( decl.second );
144        }
145
146        if (Stats::Counters::enabled) {
147                if (! lookups_by_name.count(id)) {
148                        // leaks some strings, but it is because Counters do not hold them
149                        auto lookupCounterName = new std::string(id + "%count");
150                        auto candidatesCounterName = new std::string(id + "%candidate");
151                        lookups_by_name.emplace(id, new Stats::Counters::SimpleCounter(lookupCounterName->c_str(), name_lookup_stats));
152                        candidates_by_name.emplace(id, new Stats::Counters::SimpleCounter(candidatesCounterName->c_str(), name_lookup_stats));
153                }
154                (*lookups_by_name[id]) ++;
155                *candidates_by_name[id] += out.size();
156        }
157
158        return out;
159}
160
161std::vector<SymbolTable::IdData> SymbolTable::lookupIdIgnoreHidden( const std::string &id ) const {
162        std::vector<IdData> out;
163        std::vector<IdData> lookupResult = lookupId(id);
164        for ( auto candidate: lookupResult) {
165                if ( candidate.id ) {
166                        if (candidate.id->isHidden) continue;
167                }
168                out.push_back(candidate);
169        }
170        return out;
171}
172
173std::vector<SymbolTable::IdData> SymbolTable::specialLookupId( SymbolTable::SpecialFunctionKind kind, const std::string & otypeKey ) const {
174        static Stats::Counters::CounterGroup * special_stats = Stats::Counters::build<Stats::Counters::CounterGroup>("Special Lookups");
175        static Stats::Counters::SimpleCounter * stat_counts[3] = {
176                Stats::Counters::build<Stats::Counters::SimpleCounter>("constructor - count", special_stats),
177                Stats::Counters::build<Stats::Counters::SimpleCounter>("destructor - count", special_stats),
178                Stats::Counters::build<Stats::Counters::SimpleCounter>("assignment - count", special_stats)
179        };
180
181        static Stats::Counters::SimpleCounter * stat_candidates[3] = {
182                Stats::Counters::build<Stats::Counters::SimpleCounter>("constructor - candidates", special_stats),
183                Stats::Counters::build<Stats::Counters::SimpleCounter>("destructor - candidates", special_stats),
184                Stats::Counters::build<Stats::Counters::SimpleCounter>("assignment - candidates", special_stats)
185        };
186
187        static Stats::Counters::SimpleCounter * num_lookup_with_key
188                = Stats::Counters::build<Stats::Counters::SimpleCounter>("keyed lookups", special_stats);
189        static Stats::Counters::SimpleCounter * num_lookup_without_key
190                = Stats::Counters::build<Stats::Counters::SimpleCounter>("unkeyed lookups", special_stats);
191
192        assert (kind != NUMBER_OF_KINDS);
193        ++*stats().lookup_calls;
194        if ( ! specialFunctionTable[kind] ) return {};
195
196        std::vector<IdData> out;
197
198        if (otypeKey.empty()) { // returns everything
199                ++*num_lookup_without_key;
200                for (auto & table : *specialFunctionTable[kind]) {
201                        for (auto & decl : *table.second) {
202                                out.push_back(decl.second);
203                        }
204                }
205        } else {
206                ++*num_lookup_with_key;
207                ++*stats().map_lookups;
208                auto decls = specialFunctionTable[kind]->find(otypeKey);
209                if (decls == specialFunctionTable[kind]->end()) return {};
210
211                for (auto decl : *(decls->second)) {
212                        out.push_back(decl.second);
213                }
214        }
215
216        ++*stat_counts[kind];
217        *stat_candidates[kind] += out.size();
218
219        return out;
220}
221
222const NamedTypeDecl * SymbolTable::lookupType( const std::string &id ) const {
223        ++*stats().lookup_calls;
224        if ( ! typeTable ) return nullptr;
225        ++*stats().map_lookups;
226        auto it = typeTable->find( id );
227        return it == typeTable->end() ? nullptr : it->second.decl;
228}
229
230const StructDecl * SymbolTable::lookupStruct( const std::string &id ) const {
231        ++*stats().lookup_calls;
232        if ( ! structTable ) return nullptr;
233        ++*stats().map_lookups;
234        auto it = structTable->find( id );
235        return it == structTable->end() ? nullptr : it->second.decl;
236}
237
238const EnumDecl * SymbolTable::lookupEnum( const std::string &id ) const {
239        ++*stats().lookup_calls;
240        if ( ! enumTable ) return nullptr;
241        ++*stats().map_lookups;
242        auto it = enumTable->find( id );
243        return it == enumTable->end() ? nullptr : it->second.decl;
244}
245
246const UnionDecl * SymbolTable::lookupUnion( const std::string &id ) const {
247        ++*stats().lookup_calls;
248        if ( ! unionTable ) return nullptr;
249        ++*stats().map_lookups;
250        auto it = unionTable->find( id );
251        return it == unionTable->end() ? nullptr : it->second.decl;
252}
253
254const TraitDecl * SymbolTable::lookupTrait( const std::string &id ) const {
255        ++*stats().lookup_calls;
256        if ( ! traitTable ) return nullptr;
257        ++*stats().map_lookups;
258        auto it = traitTable->find( id );
259        return it == traitTable->end() ? nullptr : it->second.decl;
260}
261
262const NamedTypeDecl * SymbolTable::globalLookupType( const std::string &id ) const {
263        return atScope( 0 )->lookupType( id );
264}
265
266const StructDecl * SymbolTable::globalLookupStruct( const std::string &id ) const {
267        return atScope( 0 )->lookupStruct( id );
268}
269
270const UnionDecl * SymbolTable::globalLookupUnion( const std::string &id ) const {
271        return atScope( 0 )->lookupUnion( id );
272}
273
274const EnumDecl * SymbolTable::globalLookupEnum( const std::string &id ) const {
275        return atScope( 0 )->lookupEnum( id );
276}
277
278void SymbolTable::addId( const DeclWithType * decl, const Expr * baseExpr ) {
279        // default handling of conflicts is to raise an error
280        addIdCommon( decl, OnConflict::error(), baseExpr, decl->isDeleted ? decl : nullptr );
281}
282
283void SymbolTable::addDeletedId( const DeclWithType * decl, const Decl * deleter ) {
284        // default handling of conflicts is to raise an error
285        addIdCommon( decl, OnConflict::error(), nullptr, deleter );
286}
287
288bool SymbolTable::addedTypeConflicts(
289                const NamedTypeDecl * existing, const NamedTypeDecl * added ) const {
290        if ( existing->base == nullptr ) {
291                return false;
292        } else if ( added->base == nullptr ) {
293                return true;
294        } else {
295                // typedef redeclarations are errors only if types are different
296                if ( ! ResolvExpr::typesCompatible( existing->base, added->base ) ) {
297                        OnFindError( added->location, "redeclaration of " + added->name );
298                }
299        }
300        // does not need to be added to the table if both existing and added have a base that are
301        // the same
302        return true;
303}
304
305bool SymbolTable::addedDeclConflicts(
306                const AggregateDecl * existing, const AggregateDecl * added ) const {
307        if ( ! existing->body ) {
308                return false;
309        } else if ( added->body ) {
310                OnFindError( added, "redeclaration of " );
311        }
312        return true;
313}
314
315void SymbolTable::addType( const NamedTypeDecl * decl ) {
316        ++*stats().add_calls;
317        const std::string &id = decl->name;
318
319        if ( ! typeTable ) {
320                typeTable = TypeTable::new_ptr();
321        } else {
322                ++*stats().map_lookups;
323                auto existing = typeTable->find( id );
324                if ( existing != typeTable->end()
325                        && existing->second.scope == scope
326                        && addedTypeConflicts( existing->second.decl, decl ) ) return;
327        }
328
329        lazyInitScope();
330        ++*stats().map_mutations;
331        typeTable = typeTable->set( id, scoped<NamedTypeDecl>{ decl, scope } );
332}
333
334void SymbolTable::addStructId( const std::string &id ) {
335        addStruct( new StructDecl( CodeLocation(), id ) );
336}
337
338void SymbolTable::addStruct( const StructDecl * decl ) {
339        ++*stats().add_calls;
340        const std::string &id = decl->name;
341
342        if ( ! structTable ) {
343                structTable = StructTable::new_ptr();
344        } else {
345                ++*stats().map_lookups;
346                auto existing = structTable->find( id );
347                if ( existing != structTable->end()
348                        && existing->second.scope == scope
349                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
350        }
351
352        lazyInitScope();
353        ++*stats().map_mutations;
354        structTable = structTable->set( id, scoped<StructDecl>{ decl, scope } );
355}
356
357void SymbolTable::addEnum( const EnumDecl *decl ) {
358        ++*stats().add_calls;
359        const std::string &id = decl->name;
360
361        if ( ! enumTable ) {
362                enumTable = EnumTable::new_ptr();
363        } else {
364                ++*stats().map_lookups;
365                auto existing = enumTable->find( id );
366                if ( existing != enumTable->end()
367                        && existing->second.scope == scope
368                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
369        }
370
371        lazyInitScope();
372        ++*stats().map_mutations;
373        enumTable = enumTable->set( id, scoped<EnumDecl>{ decl, scope } );
374}
375
376void SymbolTable::addUnionId( const std::string &id ) {
377        addUnion( new UnionDecl( CodeLocation(), id ) );
378}
379
380void SymbolTable::addUnion( const UnionDecl * decl ) {
381        ++*stats().add_calls;
382        const std::string &id = decl->name;
383
384        if ( ! unionTable ) {
385                unionTable = UnionTable::new_ptr();
386        } else {
387                ++*stats().map_lookups;
388                auto existing = unionTable->find( id );
389                if ( existing != unionTable->end()
390                        && existing->second.scope == scope
391                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
392        }
393
394        lazyInitScope();
395        ++*stats().map_mutations;
396        unionTable = unionTable->set( id, scoped<UnionDecl>{ decl, scope } );
397}
398
399void SymbolTable::addTrait( const TraitDecl * decl ) {
400        ++*stats().add_calls;
401        const std::string &id = decl->name;
402
403        if ( ! traitTable ) {
404                traitTable = TraitTable::new_ptr();
405        } else {
406                ++*stats().map_lookups;
407                auto existing = traitTable->find( id );
408                if ( existing != traitTable->end()
409                        && existing->second.scope == scope
410                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
411        }
412
413        lazyInitScope();
414        ++*stats().map_mutations;
415        traitTable = traitTable->set( id, scoped<TraitDecl>{ decl, scope } );
416}
417
418
419void SymbolTable::addWith( const std::vector< ptr<Expr> > & withExprs, const Decl * withStmt ) {
420        for ( const Expr * expr : withExprs ) {
421                if ( ! expr->result ) continue;
422                const Type * resTy = expr->result->stripReferences();
423                auto aggrType = dynamic_cast< const BaseInstType * >( resTy );
424                assertf( aggrType, "WithStmt expr has non-aggregate type: %s",
425                        toString( expr->result ).c_str() );
426                const AggregateDecl * aggr = aggrType->aggr();
427                assertf( aggr, "WithStmt has null aggregate from type: %s",
428                        toString( expr->result ).c_str() );
429
430                addMembers( aggr, expr, OnConflict::deleteWith( withStmt ) );
431        }
432}
433
434void SymbolTable::addIds( const std::vector< ptr<DeclWithType> > & decls ) {
435        for ( const DeclWithType * decl : decls ) { addId( decl ); }
436}
437
438void SymbolTable::addTypes( const std::vector< ptr<TypeDecl> > & tds ) {
439        for ( const TypeDecl * td : tds ) {
440                addType( td );
441                addIds( td->assertions );
442        }
443}
444
445
446void SymbolTable::addFunction( const FunctionDecl * func ) {
447        for (auto & td : func->type_params) {
448                addType(td);
449        }
450        for (auto & asst : func->assertions) {
451                addId(asst);
452        }
453        // addTypes( func->type->forall );
454        addIds( func->returns );
455        addIds( func->params );
456}
457
458
459void SymbolTable::lazyInitScope() {
460        // do nothing if already in represented scope
461        if ( repScope == scope ) return;
462
463        ++*stats().lazy_scopes;
464        // create rollback
465        prevScope = std::make_shared<SymbolTable>( *this );
466        // update repScope
467        repScope = scope;
468}
469
470const ast::SymbolTable * SymbolTable::atScope( unsigned long target ) const {
471        // by lazy construction, final symtab in list has repScope 0, cannot be > target
472        // otherwise, will find first scope representing the target
473        const SymbolTable * symtab = this;
474        while ( symtab->repScope > target ) {
475                symtab = symtab->prevScope.get();
476        }
477        return symtab;
478}
479
480namespace {
481        /// gets the base type of the first parameter; decl must be a ctor/dtor/assignment function
482        std::string getOtypeKey( const FunctionType * ftype, bool stripParams = true ) {
483                const auto & params = ftype->params;
484                assert( ! params.empty() );
485                // use base type of pointer, so that qualifiers on the pointer type aren't considered.
486                const Type * base = ast::getPointerBase( params.front() );
487                assert( base );
488                if (stripParams) {
489                        if (dynamic_cast<const PointerType *>(base)) return Mangle::Encoding::pointer;
490                        return Mangle::mangle( base, Mangle::Type | Mangle::NoGenericParams );
491                } else {
492                        return Mangle::mangle( base );
493                }
494        }
495
496        /// gets the declaration for the function acting on a type specified by otype key,
497        /// nullptr if none such
498        const FunctionDecl * getFunctionForOtype(
499                        const DeclWithType * decl, const std::string & otypeKey ) {
500                auto func = dynamic_cast< const FunctionDecl * >( decl );
501                if ( ! func || otypeKey != getOtypeKey( func->type, false ) ) return nullptr;
502                return func;
503        }
504}
505
506bool SymbolTable::removeSpecialOverrides(
507                SymbolTable::IdData & data, SymbolTable::MangleTable::Ptr & mangleTable ) {
508        // if a type contains user defined ctor/dtor/assign, then special rules trigger, which
509        // determine the set of ctor/dtor/assign that can be used  by the requester. In particular,
510        // if the user defines a default ctor, then the generated default ctor is unavailable,
511        // likewise for copy ctor and dtor. If the user defines any ctor/dtor, then no generated
512        // field ctors are available. If the user defines any ctor then the generated default ctor
513        // is unavailable (intrinsic default ctor must be overridden exactly). If the user defines
514        // anything that looks like a copy constructor, then the generated copy constructor is
515        // unavailable, and likewise for the assignment operator.
516
517        // only relevant on function declarations
518        const FunctionDecl * function = data.id.as< FunctionDecl >();
519        if ( ! function ) return true;
520        // only need to perform this check for constructors, destructors, and assignment functions
521        if ( ! CodeGen::isCtorDtorAssign( data.id->name ) ) return true;
522
523        // set up information for this type
524        bool dataIsUserDefinedFunc = ! function->linkage.is_overrideable;
525        bool dataIsCopyFunc = InitTweak::isCopyFunction( function );
526        std::string dataOtypeKey = getOtypeKey( function->type, false ); // requires exact match to override autogen
527
528        if ( dataIsUserDefinedFunc && dataIsCopyFunc ) {
529                // this is a user-defined copy function
530                // if this is the first such, delete/remove non-user-defined overloads as needed
531                std::vector< std::string > removed;
532                std::vector< MangleTable::value_type > deleted;
533                bool alreadyUserDefinedFunc = false;
534
535                for ( const auto& entry : *mangleTable ) {
536                        // skip decls that aren't functions or are for the wrong type
537                        const FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
538                        if ( ! decl ) continue;
539
540                        bool isCopyFunc = InitTweak::isCopyFunction( decl );
541                        if ( ! decl->linkage.is_overrideable ) {
542                                // matching user-defined function
543                                if ( isCopyFunc ) {
544                                        // mutation already performed, return early
545                                        return true;
546                                } else {
547                                        // note that non-copy deletions already performed
548                                        alreadyUserDefinedFunc = true;
549                                }
550                        } else {
551                                // non-user-defined function; mark for deletion/removal as appropriate
552                                if ( isCopyFunc ) {
553                                        removed.push_back( entry.first );
554                                } else if ( ! alreadyUserDefinedFunc ) {
555                                        deleted.push_back( entry );
556                                }
557                        }
558                }
559
560                // perform removals from mangle table, and deletions if necessary
561                for ( const auto& key : removed ) {
562                        ++*stats().map_mutations;
563                        mangleTable = mangleTable->erase( key );
564                }
565                if ( ! alreadyUserDefinedFunc ) for ( const auto& entry : deleted ) {
566                        ++*stats().map_mutations;
567                        mangleTable = mangleTable->set( entry.first, entry.second.withDeleter( function ) );
568                }
569        } else if ( dataIsUserDefinedFunc ) {
570                // this is a user-defined non-copy function
571                // if this is the first user-defined function, delete non-user-defined overloads
572                std::vector< MangleTable::value_type > deleted;
573
574                for ( const auto& entry : *mangleTable ) {
575                        // skip decls that aren't functions or are for the wrong type
576                        const FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
577                        if ( ! decl ) continue;
578
579                        // exit early if already a matching user-defined function;
580                        // earlier function will have mutated table
581                        if ( ! decl->linkage.is_overrideable ) return true;
582
583                        // skip mutating intrinsic functions
584                        if ( decl->linkage == Linkage::Intrinsic ) continue;
585
586                        // user-defined non-copy functions do not override copy functions
587                        if ( InitTweak::isCopyFunction( decl ) ) continue;
588
589                        // this function to be deleted after mangleTable iteration is complete
590                        deleted.push_back( entry );
591                }
592
593                // mark deletions to update mangle table
594                // this needs to be a separate loop because of iterator invalidation
595                for ( const auto& entry : deleted ) {
596                        ++*stats().map_mutations;
597                        mangleTable = mangleTable->set( entry.first, entry.second.withDeleter( function ) );
598                }
599        } else if ( function->linkage != Linkage::Intrinsic ) {
600                // this is an overridable generated function
601                // if there already exists a matching user-defined function, delete this appropriately
602                for ( const auto& entry : *mangleTable ) {
603                        // skip decls that aren't functions or are for the wrong type
604                        const FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
605                        if ( ! decl ) continue;
606
607                        // skip non-user-defined functions
608                        if ( decl->linkage.is_overrideable ) continue;
609
610                        if ( dataIsCopyFunc ) {
611                                // remove current function if exists a user-defined copy function
612                                // since the signatures for copy functions don't need to match exactly, using
613                                // a delete statement is the wrong approach
614                                if ( InitTweak::isCopyFunction( decl ) ) return false;
615                        } else {
616                                // mark current function deleted by first user-defined function found
617                                data.deleter = decl;
618                                return true;
619                        }
620                }
621        }
622
623        // nothing (more) to fix, return true
624        return true;
625}
626
627namespace {
628        /// true iff the declaration represents a function
629        bool isFunction( const DeclWithType * decl ) {
630                return GenPoly::getFunctionType( decl->get_type() );
631        }
632
633        bool isObject( const DeclWithType * decl ) { return ! isFunction( decl ); }
634
635        /// true if the declaration represents a definition instead of a forward decl
636        bool isDefinition( const DeclWithType * decl ) {
637                if ( auto func = dynamic_cast< const FunctionDecl * >( decl ) ) {
638                        // a function is a definition if it has a body
639                        return func->stmts;
640                } else {
641                        // an object is a definition if it is not marked extern
642                        return ! decl->storage.is_extern;
643                }
644        }
645}
646
647bool SymbolTable::addedIdConflicts(
648                const SymbolTable::IdData & existing, const DeclWithType * added,
649                SymbolTable::OnConflict handleConflicts, const Decl * deleter ) {
650        // if we're giving the same name mangling to things of different types then there is something
651        // wrong
652        assert( (isObject( added ) && isObject( existing.id ) )
653                || ( isFunction( added ) && isFunction( existing.id ) ) );
654
655        if ( existing.id->linkage.is_overrideable ) {
656                // new definition shadows the autogenerated one, even at the same scope
657                return false;
658        } else if ( existing.id->linkage.is_overloadable
659                        || ResolvExpr::typesCompatible(
660                                added->get_type(), existing.id->get_type() ) ) {
661
662                // it is a conflict if one declaration is deleted and the other is not
663                if ( deleter && ! existing.deleter ) {
664                        if ( handleConflicts.mode == OnConflict::Error ) {
665                                OnFindError( added, "deletion of defined identifier " );
666                        }
667                        return true;
668                } else if ( ! deleter && existing.deleter ) {
669                        if ( handleConflicts.mode == OnConflict::Error ) {
670                                OnFindError( added, "definition of deleted identifier " );
671                        }
672                        return true;
673                }
674
675                // it is a conflict if both declarations are definitions
676                if ( isDefinition( added ) && isDefinition( existing.id ) ) {
677                        if ( handleConflicts.mode == OnConflict::Error ) {
678                                OnFindError( added,
679                                        isFunction( added ) ?
680                                                "duplicate function definition for " :
681                                                "duplicate object definition for " );
682                        }
683                        return true;
684                }
685        } else {
686                if ( handleConflicts.mode == OnConflict::Error ) {
687                        OnFindError( added, "duplicate definition for " );
688                }
689                return true;
690        }
691
692        return true;
693}
694
695void SymbolTable::addIdCommon(
696                const DeclWithType * decl, SymbolTable::OnConflict handleConflicts,
697                const Expr * baseExpr, const Decl * deleter ) {
698        SpecialFunctionKind kind = getSpecialFunctionKind(decl->name);
699        if (kind == NUMBER_OF_KINDS) { // not a special decl
700                addIdToTable(decl, decl->name, idTable, handleConflicts, baseExpr, deleter);
701        } else {
702                std::string key;
703                if (auto func = dynamic_cast<const FunctionDecl *>(decl)) {
704                        key = getOtypeKey(func->type);
705                } else if (auto obj = dynamic_cast<const ObjectDecl *>(decl)) {
706                        key = getOtypeKey(obj->type.strict_as<PointerType>()->base.strict_as<FunctionType>());
707                } else {
708                        assertf(false, "special decl with non-function type");
709                }
710                addIdToTable(decl, key, specialFunctionTable[kind], handleConflicts, baseExpr, deleter);
711        }
712}
713
714void SymbolTable::addIdToTable(
715                const DeclWithType * decl, const std::string & lookupKey,
716                IdTable::Ptr & table, SymbolTable::OnConflict handleConflicts,
717                const Expr * baseExpr, const Decl * deleter ) {
718        ++*stats().add_calls;
719        const std::string &name = decl->name;
720        if ( name == "" ) return;
721
722        std::string mangleName;
723        if ( decl->linkage.is_overrideable ) {
724                // mangle the name without including the appropriate suffix, so overridable routines
725                // are placed into the same "bucket" as their user defined versions.
726                mangleName = Mangle::mangle( decl, Mangle::Mode{ Mangle::NoOverrideable } );
727        } else {
728                mangleName = Mangle::mangle( decl );
729        }
730
731        // this ensures that no two declarations with the same unmangled name at the same scope
732        // both have C linkage
733        if ( decl->linkage.is_overloadable ) {
734                // Check that a Cforall declaration doesn't override any C declaration
735                if ( hasCompatibleCDecl( name, mangleName ) ) {
736                        OnFindError( decl, "Cforall declaration hides C function " );
737                }
738        } else {
739                // NOTE: only correct if name mangling is completely isomorphic to C
740                // type-compatibility, which it may not be.
741                if ( hasIncompatibleCDecl( name, mangleName ) ) {
742                        OnFindError( decl, "conflicting overload of C function " );
743                }
744        }
745
746        // ensure tables exist and add identifier
747        MangleTable::Ptr mangleTable;
748        if ( ! table ) {
749                table = IdTable::new_ptr();
750                mangleTable = MangleTable::new_ptr();
751        } else {
752                ++*stats().map_lookups;
753                auto decls = table->find( lookupKey );
754                if ( decls == table->end() ) {
755                        mangleTable = MangleTable::new_ptr();
756                } else {
757                        mangleTable = decls->second;
758                        // skip in-scope repeat declarations of same identifier
759                        ++*stats().map_lookups;
760                        auto existing = mangleTable->find( mangleName );
761                        if ( existing != mangleTable->end()
762                                        && existing->second.scope == scope
763                                        && existing->second.id
764                                        && addedIdConflicts( existing->second, decl, handleConflicts, deleter ) ) {
765                                if ( handleConflicts.mode == OnConflict::Delete ) {
766                                        // set delete expression for conflicting identifier
767                                        lazyInitScope();
768                                        *stats().map_mutations += 2;
769                                        table = table->set(
770                                                lookupKey,
771                                                mangleTable->set(
772                                                        mangleName,
773                                                        existing->second.withDeleter( handleConflicts.deleter ) ) );
774                                }
775                                return;
776                        }
777                }
778        }
779
780        // add/overwrite with new identifier
781        lazyInitScope();
782        IdData data{ decl, baseExpr, deleter, scope };
783        // Ensure that auto-generated ctor/dtor/assignment are deleted if necessary
784        if (table != idTable) { // adding to special table
785                if ( ! removeSpecialOverrides( data, mangleTable ) ) return;
786        }
787        *stats().map_mutations += 2;
788        table = table->set( lookupKey, mangleTable->set( mangleName, std::move(data) ) );
789}
790
791void SymbolTable::addMembers(
792                const AggregateDecl * aggr, const Expr * expr, SymbolTable::OnConflict handleConflicts ) {
793        for ( const ptr<Decl> & decl : aggr->members ) {
794                auto dwt = decl.as<DeclWithType>();
795                if ( nullptr == dwt ) continue;
796                addIdCommon( dwt, handleConflicts, expr );
797                // Inline through unnamed struct/union members.
798                if ( "" != dwt->name ) continue;
799                const Type * t = dwt->get_type()->stripReferences();
800                if ( auto rty = dynamic_cast<const BaseInstType *>( t ) ) {
801                        if ( ! dynamic_cast<const StructInstType *>(rty)
802                                && ! dynamic_cast<const UnionInstType *>(rty) ) continue;
803                        ResolvExpr::Cost cost = ResolvExpr::Cost::zero;
804                        ast::ptr<ast::TypeSubstitution> tmp = expr->env;
805                        expr = mutate_field(expr, &Expr::env, nullptr);
806                        const Expr * base = ResolvExpr::referenceToRvalueConversion( expr, cost );
807                        base = mutate_field(base, &Expr::env, tmp);
808
809                        addMembers(
810                                rty->aggr(), new MemberExpr{ base->location, dwt, base }, handleConflicts );
811                }
812        }
813}
814
815bool SymbolTable::hasCompatibleCDecl( const std::string &id, const std::string &mangleName ) const {
816        if ( ! idTable ) return false;
817
818        ++*stats().map_lookups;
819        auto decls = idTable->find( id );
820        if ( decls == idTable->end() ) return false;
821
822        for ( auto decl : *(decls->second) ) {
823                // skip other scopes (hidden by this decl)
824                if ( decl.second.scope != scope ) continue;
825                // check for C decl with compatible type (by mangleName)
826                if ( !decl.second.id->linkage.is_overloadable && decl.first == mangleName ) return true;
827        }
828
829        return false;
830}
831
832bool SymbolTable::hasIncompatibleCDecl( const std::string &id, const std::string &mangleName ) const {
833        if ( ! idTable ) return false;
834
835        ++*stats().map_lookups;
836        auto decls = idTable->find( id );
837        if ( decls == idTable->end() ) return false;
838
839        for ( auto decl : *(decls->second) ) {
840                // skip other scopes (hidden by this decl)
841                if ( decl.second.scope != scope ) continue;
842                // check for C decl with incompatible type (by manglename)
843                if ( !decl.second.id->linkage.is_overloadable && decl.first != mangleName ) return true;
844        }
845
846        return false;
847}
848
849}
850
851// Local Variables: //
852// tab-width: 4 //
853// mode: c++ //
854// compile-command: "make install" //
855// End: //
Note: See TracBrowser for help on using the repository browser.