source: src/AST/SymbolTable.cpp@ f2ff0a6

ADT ast-experimental
Last change on this file since f2ff0a6 was 4b8b2a4, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Make unset locations earier to find with a search for 'CodeLocation()'.

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