source: src/AST/SymbolTable.cpp@ efe89894

ast-experimental
Last change on this file since efe89894 was bccd70a, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Removed internal code from TypeSubstitution header. It caused a chain of include problems, which have been corrected.

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