source: src/AST/SymbolTable.cpp @ 24d6572

ast-experimental
Last change on this file since 24d6572 was 24d6572, checked in by Fangren Yu <f37yu@…>, 13 months ago

Merge branch 'master' into ast-experimental

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