source: src/AST/SymbolTable.cpp @ 60c3d87e

Last change on this file since 60c3d87e was 62d62db, checked in by caparsons <caparson@…>, 16 months ago

Merge branch 'master' into ast-experimental

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