source: src/ResolvExpr/Resolver.cpp@ 1b56a7f

Last change on this file since 1b56a7f was 2ae845e9, checked in by Andrew Beach <ajbeach@…>, 11 months ago

Removed debug output from resolver. Also made the early decision happen a bit earlier since it is a rare case.

  • Property mode set to 100644
File size: 44.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// Resolver.cpp --
8//
9// Author : Aaron B. Moss
10// Created On : Sun May 17 12:17:01 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Dec 14 18:44:43 2023
13// Update Count : 251
14//
15
16#include <cassert> // for strict_dynamic_cast, assert
17#include <memory> // for allocator, allocator_traits<...
18#include <tuple> // for get
19#include <vector> // for vector
20
21#include "Candidate.hpp"
22#include "CandidateFinder.hpp"
23#include "CurrentObject.hpp" // for CurrentObject
24#include "RenameVars.hpp" // for RenameVars, global_renamer
25#include "Resolver.hpp"
26#include "ResolveTypeof.hpp"
27#include "ResolveMode.hpp" // for ResolveMode
28#include "Typeops.hpp" // for extractResultType
29#include "Unify.hpp" // for unify
30#include "CompilationState.hpp"
31#include "AST/Decl.hpp"
32#include "AST/Init.hpp"
33#include "AST/Pass.hpp"
34#include "AST/Print.hpp"
35#include "AST/SymbolTable.hpp"
36#include "AST/Type.hpp"
37#include "Common/Eval.hpp" // for eval
38#include "Common/Iterate.hpp" // for group_iterate
39#include "Common/SemanticError.hpp" // for SemanticError
40#include "Common/Stats/ResolveTime.hpp" // for ResolveTime::start(), ResolveTime::stop()
41#include "Common/ToString.hpp" // for toCString
42#include "Common/UniqueName.hpp" // for UniqueName
43#include "InitTweak/GenInit.hpp"
44#include "InitTweak/InitTweak.hpp" // for isIntrinsicSingleArgCallStmt
45#include "SymTab/Mangler.hpp" // for Mangler
46#include "Tuples/Tuples.hpp"
47#include "Validate/FindSpecialDecls.hpp" // for SizeType
48
49using namespace std;
50
51namespace ResolvExpr {
52
53namespace {
54 /// Finds deleted expressions in an expression tree
55 struct DeleteFinder final : public ast::WithShortCircuiting, public ast::WithVisitorRef<DeleteFinder> {
56 const ast::DeletedExpr * result = nullptr;
57
58 void previsit( const ast::DeletedExpr * expr ) {
59 if ( result ) { visit_children = false; }
60 else { result = expr; }
61 }
62
63 void previsit( const ast::Expr * expr ) {
64 if ( result ) { visit_children = false; }
65 if (expr->inferred.hasParams()) {
66 for (auto & imp : expr->inferred.inferParams() ) {
67 imp.second.expr->accept(*visitor);
68 }
69 }
70 }
71 };
72
73 struct ResolveDesignators final : public ast::WithShortCircuiting {
74 ResolveContext& context;
75 bool result = false;
76
77 ResolveDesignators( ResolveContext& _context ): context(_context) {};
78
79 void previsit( const ast::Node * ) {
80 // short circuit if we already know there are designations
81 if ( result ) visit_children = false;
82 }
83
84 void previsit( const ast::Designation * des ) {
85 if ( result ) visit_children = false;
86 else if ( ! des->designators.empty() ) {
87 if ( (des->designators.size() == 1) ) {
88 const ast::Expr * designator = des->designators.at(0);
89 if ( const ast::NameExpr * designatorName = dynamic_cast<const ast::NameExpr *>(designator) ) {
90 auto candidates = context.symtab.lookupId(designatorName->name);
91 for ( auto candidate : candidates ) {
92 if ( dynamic_cast<const ast::EnumInstType *>(candidate.id->get_type()) ) {
93 result = true;
94 break;
95 }
96 }
97 }
98 }
99 visit_children = false;
100 }
101 }
102 };
103} // anonymous namespace
104
105/// Check if this expression is or includes a deleted expression
106const ast::DeletedExpr * findDeletedExpr( const ast::Expr * expr ) {
107 return ast::Pass<DeleteFinder>::read( expr );
108}
109
110namespace {
111 /// always-accept candidate filter
112 bool anyCandidate( const Candidate & ) { return true; }
113
114 /// Calls the CandidateFinder and finds the single best candidate
115 CandidateRef findUnfinishedKindExpression(
116 const ast::Expr * untyped, const ResolveContext & context, const std::string & kind,
117 std::function<bool(const Candidate &)> pred = anyCandidate, ResolveMode mode = {}
118 ) {
119 if ( ! untyped ) return nullptr;
120
121 // xxx - this isn't thread-safe, but should work until we parallelize the resolver
122 static unsigned recursion_level = 0;
123
124 ++recursion_level;
125 ast::TypeEnvironment env;
126 CandidateFinder finder( context, env );
127 finder.allowVoid = true;
128 finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode );
129 --recursion_level;
130
131 // produce a filtered list of candidates
132 CandidateList candidates;
133 for ( auto & cand : finder.candidates ) {
134 if ( pred( *cand ) ) { candidates.emplace_back( cand ); }
135 }
136
137 // produce invalid error if no candidates
138 if ( candidates.empty() ) {
139 SemanticError( untyped,
140 toString( "No reasonable alternatives for ", kind, (kind != "" ? " " : ""),
141 "expression: ") );
142 }
143
144 // search for cheapest candidate
145 CandidateList winners;
146 bool seen_undeleted = false;
147 for ( CandidateRef & cand : candidates ) {
148 int c = winners.empty() ? -1 : cand->cost.compare( winners.front()->cost );
149
150 if ( c > 0 ) continue; // skip more expensive than winner
151
152 if ( c < 0 ) {
153 // reset on new cheapest
154 seen_undeleted = ! findDeletedExpr( cand->expr );
155 winners.clear();
156 } else /* if ( c == 0 ) */ {
157 if ( findDeletedExpr( cand->expr ) ) {
158 // skip deleted expression if already seen one equivalent-cost not
159 if ( seen_undeleted ) continue;
160 } else if ( ! seen_undeleted ) {
161 // replace list of equivalent-cost deleted expressions with one non-deleted
162 winners.clear();
163 seen_undeleted = true;
164 }
165 }
166
167 winners.emplace_back( std::move( cand ) );
168 }
169
170 // promote candidate.cvtCost to .cost
171 // promoteCvtCost( winners );
172
173 // produce ambiguous errors, if applicable
174 if ( winners.size() != 1 ) {
175 std::ostringstream stream;
176 stream << "Cannot choose between " << winners.size() << " alternatives for "
177 << kind << (kind != "" ? " " : "") << "expression\n";
178 ast::print( stream, untyped );
179 stream << " Alternatives are:\n";
180 print( stream, winners, 1 );
181 SemanticError( untyped->location, stream.str() );
182 }
183
184 // single selected choice
185 CandidateRef & choice = winners.front();
186
187 // fail on only expression deleted
188 if ( ! seen_undeleted ) {
189 SemanticError( untyped->location, choice->expr.get(), "Unique best alternative "
190 "includes deleted identifier in " );
191 }
192
193 return std::move( choice );
194 }
195
196 /// Strips extraneous casts out of an expression
197 struct StripCasts final {
198 const ast::Expr * postvisit( const ast::CastExpr * castExpr ) {
199 if (
200 castExpr->isGenerated == ast::GeneratedCast
201 && typesCompatible( castExpr->arg->result, castExpr->result )
202 ) {
203 ast::EnumInstType const * arg, * result;
204 if ( ( result = castExpr->result.as<ast::EnumInstType>() ) &&
205 ( arg = castExpr->arg.as<ast::EnumInstType>() ) &&
206 arg->base->name != result->base->name) {
207 return castExpr;
208 }
209 // generated cast is the same type as its argument, remove it after keeping env
210 return ast::mutate_field(
211 castExpr->arg.get(), &ast::Expr::env, castExpr->env );
212 }
213 return castExpr;
214 }
215
216 static void strip( ast::ptr< ast::Expr > & expr ) {
217 ast::Pass< StripCasts > stripper;
218 expr = expr->accept( stripper );
219 }
220 };
221
222 /// Swaps argument into expression pointer, saving original environment
223 void swap_and_save_env( ast::ptr< ast::Expr > & expr, const ast::Expr * newExpr ) {
224 ast::ptr< ast::TypeSubstitution > env = expr->env;
225 expr.set_and_mutate( newExpr )->env = env;
226 }
227
228 /// Removes cast to type of argument (unlike StripCasts, also handles non-generated casts)
229 void removeExtraneousCast( ast::ptr<ast::Expr> & expr ) {
230 if ( const ast::CastExpr * castExpr = expr.as< ast::CastExpr >() ) {
231 if ( typesCompatible( castExpr->arg->result, castExpr->result ) ) {
232 // cast is to the same type as its argument, remove it
233 swap_and_save_env( expr, castExpr->arg );
234 }
235 }
236 }
237
238} // anonymous namespace
239
240/// Establish post-resolver invariants for expressions
241void finishExpr(
242 ast::ptr< ast::Expr > & expr, const ast::TypeEnvironment & env,
243 const ast::TypeSubstitution * oldenv = nullptr
244) {
245 // set up new type substitution for expression
246 ast::ptr< ast::TypeSubstitution > newenv =
247 oldenv ? oldenv : new ast::TypeSubstitution{};
248 env.writeToSubstitution( *newenv.get_and_mutate() );
249 expr.get_and_mutate()->env = std::move( newenv );
250 // remove unncecessary casts
251 StripCasts::strip( expr );
252}
253
254ast::ptr< ast::Expr > resolveInVoidContext(
255 const ast::Expr * expr, const ResolveContext & context,
256 ast::TypeEnvironment & env
257) {
258 assertf( expr, "expected a non-null expression" );
259
260 // set up and resolve expression cast to void
261 ast::ptr< ast::CastExpr > untyped = new ast::CastExpr{ expr };
262 CandidateRef choice = findUnfinishedKindExpression(
263 untyped, context, "", anyCandidate );
264
265 // a cast expression has either 0 or 1 interpretations (by language rules);
266 // if 0, an exception has already been thrown, and this code will not run
267 const ast::CastExpr * castExpr = choice->expr.strict_as< ast::CastExpr >();
268 env = std::move( choice->env );
269
270 return castExpr->arg;
271}
272
273/// Resolve `untyped` to the expression whose candidate is the best match for a `void`
274/// context.
275ast::ptr< ast::Expr > findVoidExpression(
276 const ast::Expr * untyped, const ResolveContext & context
277) {
278 ast::TypeEnvironment env;
279 ast::ptr< ast::Expr > newExpr = resolveInVoidContext( untyped, context, env );
280 finishExpr( newExpr, env, untyped->env );
281 return newExpr;
282}
283
284namespace {
285 /// resolve `untyped` to the expression whose candidate satisfies `pred` with the
286 /// lowest cost, returning the resolved version
287 ast::ptr< ast::Expr > findKindExpression(
288 const ast::Expr * untyped, const ResolveContext & context,
289 std::function<bool(const Candidate &)> pred = anyCandidate,
290 const std::string & kind = "", ResolveMode mode = {}
291 ) {
292 if ( ! untyped ) return {};
293 CandidateRef choice =
294 findUnfinishedKindExpression( untyped, context, kind, pred, mode );
295 ResolvExpr::finishExpr( choice->expr, choice->env, untyped->env );
296 return std::move( choice->expr );
297 }
298
299 /// Resolve `untyped` to the single expression whose candidate is the best match
300 ast::ptr< ast::Expr > findSingleExpression(
301 const ast::Expr * untyped, const ResolveContext & context
302 ) {
303 Stats::ResolveTime::start( untyped );
304 auto res = findKindExpression( untyped, context );
305 Stats::ResolveTime::stop();
306 return res;
307 }
308} // anonymous namespace
309
310ast::ptr< ast::Expr > findSingleExpression(
311 const ast::Expr * untyped, const ast::Type * type,
312 const ResolveContext & context
313) {
314 assert( untyped && type );
315 ast::ptr< ast::Expr > castExpr = new ast::CastExpr{ untyped, type };
316 ast::ptr< ast::Expr > newExpr = findSingleExpression( castExpr, context );
317 removeExtraneousCast( newExpr );
318 return newExpr;
319}
320
321namespace {
322 bool structOrUnionOrEnum( const Candidate & i ) {
323 const ast::Type * t = i.expr->result->stripReferences();
324 return dynamic_cast< const ast::StructInstType * >( t ) || dynamic_cast< const ast::UnionInstType * >( t ) || dynamic_cast< const ast::EnumInstType * >( t );
325 }
326 /// Predicate for "Candidate has integral type"
327 bool hasIntegralType( const Candidate & i ) {
328 const ast::Type * type = i.expr->result;
329
330 if ( auto bt = dynamic_cast< const ast::BasicType * >( type ) ) {
331 return bt->isInteger();
332 } else if (
333 dynamic_cast< const ast::EnumInstType * >( type )
334 || dynamic_cast< const ast::ZeroType * >( type )
335 || dynamic_cast< const ast::OneType * >( type )
336 ) {
337 return true;
338 } else return false;
339 }
340
341 /// Resolve `untyped` as an integral expression, returning the resolved version
342 ast::ptr< ast::Expr > findIntegralExpression(
343 const ast::Expr * untyped, const ResolveContext & context
344 ) {
345 return findKindExpression( untyped, context, hasIntegralType, "condition" );
346 }
347
348 ast::ptr< ast::Expr > findCondExpression(
349 const ast::Expr * untyped, const ResolveContext & context
350 ) {
351 if ( nullptr == untyped ) return untyped;
352 ast::ptr<ast::Expr> condExpr = createCondExpr( untyped );
353 return findIntegralExpression( condExpr, context );
354 }
355
356 /// check if a type is a character type
357 bool isCharType( const ast::Type * t ) {
358 if ( auto bt = dynamic_cast< const ast::BasicType * >( t ) ) {
359 return bt->kind == ast::BasicKind::Char
360 || bt->kind == ast::BasicKind::SignedChar
361 || bt->kind == ast::BasicKind::UnsignedChar;
362 }
363 return false;
364 }
365
366 /// Advance a type itertor to the next mutex parameter
367 template<typename Iter>
368 inline bool nextMutex( Iter & it, const Iter & end ) {
369 while ( it != end && ! (*it)->is_mutex() ) { ++it; }
370 return it != end;
371 }
372} // anonymous namespace
373
374class Resolver final
375: public ast::WithSymbolTable, public ast::WithGuards,
376 public ast::WithVisitorRef<Resolver>, public ast::WithShortCircuiting,
377 public ast::WithStmtsToAdd<> {
378
379 ast::ptr< ast::Type > functionReturn = nullptr;
380 ast::CurrentObject currentObject;
381 // for work previously in GenInit
382 static InitTweak::ManagedTypes managedTypes;
383 ResolveContext context;
384
385 bool inEnumDecl = false;
386
387public:
388 static size_t traceId;
389 Resolver( const ast::TranslationGlobal & global ) :
390 ast::WithSymbolTable(ast::SymbolTable::ErrorDetection::ValidateOnAdd),
391 context{ symtab, global } {}
392 Resolver( const ResolveContext & context ) :
393 ast::WithSymbolTable{ context.symtab },
394 context{ symtab, context.global } {}
395
396 const ast::FunctionDecl * previsit( const ast::FunctionDecl * );
397 const ast::FunctionDecl * postvisit( const ast::FunctionDecl * );
398 const ast::ObjectDecl * previsit( const ast::ObjectDecl * );
399 void previsit( const ast::AggregateDecl * );
400 void previsit( const ast::StructDecl * );
401 void previsit( const ast::EnumDecl * );
402 const ast::StaticAssertDecl * previsit( const ast::StaticAssertDecl * );
403
404 const ast::ArrayType * previsit( const ast::ArrayType * );
405 const ast::PointerType * previsit( const ast::PointerType * );
406
407 const ast::ExprStmt * previsit( const ast::ExprStmt * );
408 const ast::AsmExpr * previsit( const ast::AsmExpr * );
409 const ast::AsmStmt * previsit( const ast::AsmStmt * );
410 const ast::IfStmt * previsit( const ast::IfStmt * );
411 const ast::WhileDoStmt * previsit( const ast::WhileDoStmt * );
412 const ast::ForStmt * previsit( const ast::ForStmt * );
413 const ast::SwitchStmt * previsit( const ast::SwitchStmt * );
414 const ast::CaseClause * previsit( const ast::CaseClause * );
415 const ast::BranchStmt * previsit( const ast::BranchStmt * );
416 const ast::ReturnStmt * previsit( const ast::ReturnStmt * );
417 const ast::ThrowStmt * previsit( const ast::ThrowStmt * );
418 const ast::CatchClause * previsit( const ast::CatchClause * );
419 const ast::CatchClause * postvisit( const ast::CatchClause * );
420 const ast::WaitForStmt * previsit( const ast::WaitForStmt * );
421 const ast::WithStmt * previsit( const ast::WithStmt * );
422
423 const ast::SingleInit * previsit( const ast::SingleInit * );
424 const ast::ListInit * previsit( const ast::ListInit * );
425 const ast::ConstructorInit * previsit( const ast::ConstructorInit * );
426
427 void resolveWithExprs(std::vector<ast::ptr<ast::Expr>> & exprs, std::list<ast::ptr<ast::Stmt>> & stmtsToAdd);
428 bool shouldGenCtorInit( const ast::ObjectDecl * ) const;
429
430 void beginScope() { managedTypes.beginScope(); }
431 void endScope() { managedTypes.endScope(); }
432 bool on_error(ast::ptr<ast::Decl> & decl);
433};
434// size_t Resolver::traceId = Stats::Heap::new_stacktrace_id("Resolver");
435
436InitTweak::ManagedTypes Resolver::managedTypes;
437
438void resolve( ast::TranslationUnit& translationUnit ) {
439 ast::Pass< Resolver >::run( translationUnit, translationUnit.global );
440}
441
442ast::ptr< ast::Init > resolveCtorInit(
443 const ast::ConstructorInit * ctorInit, const ResolveContext & context
444) {
445 assert( ctorInit );
446 ast::Pass< Resolver > resolver( context );
447 return ctorInit->accept( resolver );
448}
449
450const ast::Expr * resolveStmtExpr(
451 const ast::StmtExpr * stmtExpr, const ResolveContext & context
452) {
453 assert( stmtExpr );
454 ast::Pass< Resolver > resolver( context );
455 auto ret = mutate(stmtExpr->accept(resolver));
456 strict_dynamic_cast< ast::StmtExpr * >( ret )->computeResult();
457 return ret;
458}
459
460namespace {
461 const ast::Attribute * handleAttribute(const CodeLocation & loc, const ast::Attribute * attr, const ResolveContext & context) {
462 std::string name = attr->normalizedName();
463 if (name == "constructor" || name == "destructor") {
464 if (attr->params.size() == 1) {
465 auto arg = attr->params.front();
466 auto resolved = ResolvExpr::findSingleExpression( arg, new ast::BasicType( ast::BasicKind::LongLongSignedInt ), context );
467 auto result = eval(arg);
468
469 auto mutAttr = mutate(attr);
470 mutAttr->params.front() = resolved;
471 if (! result.hasKnownValue) {
472 SemanticWarning(loc, Warning::GccAttributes,
473 toCString( name, " priorities must be integers from 0 to 65535 inclusive: ", arg ) );
474 }
475 else {
476 auto priority = result.knownValue;
477 if (priority < 101) {
478 SemanticWarning(loc, Warning::GccAttributes,
479 toCString( name, " priorities from 0 to 100 are reserved for the implementation" ) );
480 } else if (priority < 201 && ! buildingLibrary()) {
481 SemanticWarning(loc, Warning::GccAttributes,
482 toCString( name, " priorities from 101 to 200 are reserved for the implementation" ) );
483 }
484 }
485 return mutAttr;
486 } else if (attr->params.size() > 1) {
487 SemanticWarning(loc, Warning::GccAttributes, toCString( "too many arguments to ", name, " attribute" ) );
488 } else {
489 SemanticWarning(loc, Warning::GccAttributes, toCString( "too few arguments to ", name, " attribute" ) );
490 }
491 }
492 return attr;
493 }
494}
495
496const ast::FunctionDecl * Resolver::previsit( const ast::FunctionDecl * functionDecl ) {
497 GuardValue( functionReturn );
498
499 assert (functionDecl->unique());
500 if (!functionDecl->has_body() && !functionDecl->withExprs.empty()) {
501 SemanticError(functionDecl->location, functionDecl, "Function without body has with declarations");
502 }
503
504 if (!functionDecl->isTypeFixed) {
505 auto mutDecl = mutate(functionDecl);
506 auto mutType = mutDecl->type.get_and_mutate();
507
508 for (auto & attr: mutDecl->attributes) {
509 attr = handleAttribute(mutDecl->location, attr, context );
510 }
511
512 // handle assertions
513
514 symtab.enterScope();
515 mutType->forall.clear();
516 mutType->assertions.clear();
517 for (auto & typeParam : mutDecl->type_params) {
518 symtab.addType(typeParam);
519 mutType->forall.emplace_back(new ast::TypeInstType(typeParam));
520 }
521 for (auto & asst : mutDecl->assertions) {
522 asst = fixObjectType(asst.strict_as<ast::ObjectDecl>(), context);
523 symtab.addId(asst);
524 mutType->assertions.emplace_back(new ast::VariableExpr(functionDecl->location, asst));
525 }
526
527 // temporarily adds params to symbol table.
528 // actual scoping rules for params and withexprs differ - see Pass::visit(FunctionDecl)
529
530 std::vector<ast::ptr<ast::Type>> paramTypes;
531 std::vector<ast::ptr<ast::Type>> returnTypes;
532
533 for (auto & param : mutDecl->params) {
534 param = fixObjectType(param.strict_as<ast::ObjectDecl>(), context);
535 symtab.addId(param);
536 paramTypes.emplace_back(param->get_type());
537 }
538 for (auto & ret : mutDecl->returns) {
539 ret = fixObjectType(ret.strict_as<ast::ObjectDecl>(), context);
540 returnTypes.emplace_back(ret->get_type());
541 }
542 // since function type in decl is just a view of param types, need to update that as well
543 mutType->params = std::move(paramTypes);
544 mutType->returns = std::move(returnTypes);
545
546 auto renamedType = strict_dynamic_cast<const ast::FunctionType *>(renameTyVars(mutType, RenameMode::GEN_EXPR_ID));
547
548 std::list<ast::ptr<ast::Stmt>> newStmts;
549 resolveWithExprs (mutDecl->withExprs, newStmts);
550
551 if (mutDecl->stmts) {
552 auto mutStmt = mutDecl->stmts.get_and_mutate();
553 mutStmt->kids.splice(mutStmt->kids.begin(), std::move(newStmts));
554 mutDecl->stmts = mutStmt;
555 }
556
557 symtab.leaveScope();
558
559 mutDecl->type = renamedType;
560 mutDecl->mangleName = Mangle::mangle(mutDecl);
561 mutDecl->isTypeFixed = true;
562 functionDecl = mutDecl;
563 }
564 managedTypes.handleDWT(functionDecl);
565
566 functionReturn = extractResultType( functionDecl->type );
567 return functionDecl;
568}
569
570const ast::FunctionDecl * Resolver::postvisit( const ast::FunctionDecl * functionDecl ) {
571 // default value expressions have an environment which shouldn't be there and trips up
572 // later passes.
573 assert( functionDecl->unique() );
574 ast::FunctionType * mutType = mutate( functionDecl->type.get() );
575
576 for ( unsigned i = 0 ; i < mutType->params.size() ; ++i ) {
577 if ( const ast::ObjectDecl * obj = mutType->params[i].as< ast::ObjectDecl >() ) {
578 if ( const ast::SingleInit * init = obj->init.as< ast::SingleInit >() ) {
579 if ( init->value->env == nullptr ) continue;
580 // clone initializer minus the initializer environment
581 auto mutParam = mutate( mutType->params[i].strict_as< ast::ObjectDecl >() );
582 auto mutInit = mutate( mutParam->init.strict_as< ast::SingleInit >() );
583 auto mutValue = mutate( mutInit->value.get() );
584
585 mutValue->env = nullptr;
586 mutInit->value = mutValue;
587 mutParam->init = mutInit;
588 mutType->params[i] = mutParam;
589
590 assert( ! mutType->params[i].strict_as< ast::ObjectDecl >()->init.strict_as< ast::SingleInit >()->value->env);
591 }
592 }
593 }
594 mutate_field(functionDecl, &ast::FunctionDecl::type, mutType);
595 return functionDecl;
596}
597
598bool Resolver::shouldGenCtorInit( ast::ObjectDecl const * decl ) const {
599 // If we shouldn't try to construct it, then don't.
600 if ( !InitTweak::tryConstruct( decl ) ) return false;
601 // Otherwise, if it is a managed type, we may construct it.
602 if ( managedTypes.isManaged( decl ) ) return true;
603 // Skip construction if it is trivial at compile-time.
604 if ( InitTweak::isConstExpr( decl->init ) ) return false;
605 // Skip construction for local declarations.
606 return ( !isInFunction() || decl->storage.is_static );
607}
608
609const ast::ObjectDecl * Resolver::previsit( const ast::ObjectDecl * objectDecl ) {
610 // To handle initialization of routine pointers [e.g. int (*fp)(int) = foo()],
611 // class-variable `initContext` is changed multiple times because the LHS is analyzed
612 // twice. The second analysis changes `initContext` because a function type can contain
613 // object declarations in the return and parameter types. Therefore each value of
614 // `initContext` is retained so the type on the first analysis is preserved and used for
615 // selecting the RHS.
616 GuardValue( currentObject );
617
618 if ( inEnumDecl && dynamic_cast< const ast::EnumInstType * >( objectDecl->get_type() ) ) {
619 // enumerator initializers should not use the enum type to initialize, since the
620 // enum type is still incomplete at this point. Use `int` instead.
621
622 if ( auto enumBase = dynamic_cast< const ast::EnumInstType * >
623 ( objectDecl->get_type() )->base->base ) {
624 objectDecl = fixObjectType( objectDecl, context );
625 currentObject = ast::CurrentObject{
626 objectDecl->location,
627 enumBase
628 };
629 } else {
630 objectDecl = fixObjectType( objectDecl, context );
631 currentObject = ast::CurrentObject{
632 objectDecl->location, new ast::BasicType{ ast::BasicKind::SignedInt } };
633 }
634 } else {
635 if ( !objectDecl->isTypeFixed ) {
636 auto newDecl = fixObjectType(objectDecl, context);
637 auto mutDecl = mutate(newDecl);
638
639 // generate CtorInit wrapper when necessary.
640 // in certain cases, fixObjectType is called before reaching
641 // this object in visitor pass, thus disabling CtorInit codegen.
642 // this happens on aggregate members and function parameters.
643 if ( shouldGenCtorInit( mutDecl ) ) {
644 // constructed objects cannot be designated
645 if ( InitTweak::isDesignated( mutDecl->init ) ) {
646 ast::Pass<ResolveDesignators> res( context );
647 maybe_accept( mutDecl->init.get(), res );
648 if ( !res.core.result ) {
649 SemanticError( mutDecl, "Cannot include designations in the initializer for a managed Object.\n"
650 "If this is really what you want, initialize with @=." );
651 }
652 }
653 // constructed objects should not have initializers nested too deeply
654 if ( ! InitTweak::checkInitDepth( mutDecl ) ) SemanticError( mutDecl, "Managed object's initializer is too deep " );
655
656 mutDecl->init = InitTweak::genCtorInit( mutDecl->location, mutDecl );
657 }
658
659 objectDecl = mutDecl;
660 }
661 currentObject = ast::CurrentObject{ objectDecl->location, objectDecl->get_type() };
662 }
663
664 return objectDecl;
665}
666
667void Resolver::previsit( const ast::AggregateDecl * _aggDecl ) {
668 auto aggDecl = mutate(_aggDecl);
669 assertf(aggDecl == _aggDecl, "type declarations must be unique");
670
671 for (auto & member: aggDecl->members) {
672 // nested type decls are hoisted already. no need to do anything
673 if (auto obj = member.as<ast::ObjectDecl>()) {
674 member = fixObjectType(obj, context);
675 }
676 }
677}
678
679void Resolver::previsit( const ast::StructDecl * structDecl ) {
680 previsit(static_cast<const ast::AggregateDecl *>(structDecl));
681 managedTypes.handleStruct(structDecl);
682}
683
684void Resolver::previsit( const ast::EnumDecl * ) {
685 // in case we decide to allow nested enums
686 GuardValue( inEnumDecl );
687 inEnumDecl = true;
688 // don't need to fix types for enum fields
689}
690
691const ast::StaticAssertDecl * Resolver::previsit(
692 const ast::StaticAssertDecl * assertDecl
693) {
694 return ast::mutate_field(
695 assertDecl, &ast::StaticAssertDecl::cond,
696 findIntegralExpression( assertDecl->cond, context ) );
697}
698
699template< typename PtrType >
700const PtrType * handlePtrType( const PtrType * type, const ResolveContext & context ) {
701 if ( type->dimension ) {
702 const ast::Type * sizeType = context.global.sizeType.get();
703 ast::ptr< ast::Expr > dimension = findSingleExpression( type->dimension, sizeType, context );
704 assertf(dimension->env->empty(), "array dimension expr has nonempty env");
705 dimension.get_and_mutate()->env = nullptr;
706 ast::mutate_field( type, &PtrType::dimension, dimension );
707 }
708 return type;
709}
710
711const ast::ArrayType * Resolver::previsit( const ast::ArrayType * at ) {
712 return handlePtrType( at, context );
713}
714
715const ast::PointerType * Resolver::previsit( const ast::PointerType * pt ) {
716 return handlePtrType( pt, context );
717}
718
719const ast::ExprStmt * Resolver::previsit( const ast::ExprStmt * exprStmt ) {
720 visit_children = false;
721 assertf( exprStmt->expr, "ExprStmt has null expression in resolver" );
722
723 return ast::mutate_field(
724 exprStmt, &ast::ExprStmt::expr, findVoidExpression( exprStmt->expr, context ) );
725}
726
727const ast::AsmExpr * Resolver::previsit( const ast::AsmExpr * asmExpr ) {
728 visit_children = false;
729
730 asmExpr = ast::mutate_field(
731 asmExpr, &ast::AsmExpr::operand, findVoidExpression( asmExpr->operand, context ) );
732
733 return asmExpr;
734}
735
736const ast::AsmStmt * Resolver::previsit( const ast::AsmStmt * asmStmt ) {
737 visitor->maybe_accept( asmStmt, &ast::AsmStmt::input );
738 visitor->maybe_accept( asmStmt, &ast::AsmStmt::output );
739 visit_children = false;
740 return asmStmt;
741}
742
743const ast::IfStmt * Resolver::previsit( const ast::IfStmt * ifStmt ) {
744 return ast::mutate_field(
745 ifStmt, &ast::IfStmt::cond, findCondExpression( ifStmt->cond, context ) );
746}
747
748const ast::WhileDoStmt * Resolver::previsit( const ast::WhileDoStmt * whileDoStmt ) {
749 return ast::mutate_field(
750 whileDoStmt, &ast::WhileDoStmt::cond, findCondExpression( whileDoStmt->cond, context ) );
751}
752
753const ast::ForStmt * Resolver::previsit( const ast::ForStmt * forStmt ) {
754 if ( forStmt->cond ) {
755 forStmt = ast::mutate_field(
756 forStmt, &ast::ForStmt::cond, findCondExpression( forStmt->cond, context ) );
757 }
758
759 if ( forStmt->inc ) {
760 forStmt = ast::mutate_field(
761 forStmt, &ast::ForStmt::inc, findVoidExpression( forStmt->inc, context ) );
762 }
763
764 return forStmt;
765}
766
767const ast::SwitchStmt * Resolver::previsit( const ast::SwitchStmt * switchStmt ) {
768 GuardValue( currentObject );
769 switchStmt = ast::mutate_field(
770 switchStmt, &ast::SwitchStmt::cond,
771 findIntegralExpression( switchStmt->cond, context ) );
772 currentObject = ast::CurrentObject{ switchStmt->location, switchStmt->cond->result };
773 return switchStmt;
774}
775
776const ast::CaseClause * Resolver::previsit( const ast::CaseClause * caseStmt ) {
777 if ( caseStmt->cond ) {
778 std::deque< ast::InitAlternative > initAlts = currentObject.getOptions();
779 assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral "
780 "expression." );
781
782 ast::ptr< ast::Expr > untyped =
783 new ast::CastExpr{ caseStmt->location, caseStmt->cond, initAlts.front().type };
784 ast::ptr< ast::Expr > newExpr = findSingleExpression( untyped, context );
785
786 // case condition cannot have a cast in C, so it must be removed here, regardless of
787 // whether it would perform a conversion.
788 if ( const ast::CastExpr * castExpr = newExpr.as< ast::CastExpr >() ) {
789 swap_and_save_env( newExpr, castExpr->arg );
790 }
791
792 caseStmt = ast::mutate_field( caseStmt, &ast::CaseClause::cond, newExpr );
793 }
794 return caseStmt;
795}
796
797const ast::BranchStmt * Resolver::previsit( const ast::BranchStmt * branchStmt ) {
798 visit_children = false;
799 // must resolve the argument of a computed goto
800 if ( branchStmt->kind == ast::BranchStmt::Goto && branchStmt->computedTarget ) {
801 // computed goto argument is void*
802 ast::ptr< ast::Type > target = new ast::PointerType{ new ast::VoidType{} };
803 branchStmt = ast::mutate_field(
804 branchStmt, &ast::BranchStmt::computedTarget,
805 findSingleExpression( branchStmt->computedTarget, target, context ) );
806 }
807 return branchStmt;
808}
809
810const ast::ReturnStmt * Resolver::previsit( const ast::ReturnStmt * returnStmt ) {
811 visit_children = false;
812 if ( returnStmt->expr ) {
813 returnStmt = ast::mutate_field(
814 returnStmt, &ast::ReturnStmt::expr,
815 findSingleExpression( returnStmt->expr, functionReturn, context ) );
816 }
817 return returnStmt;
818}
819
820const ast::ThrowStmt * Resolver::previsit( const ast::ThrowStmt * throwStmt ) {
821 visit_children = false;
822 if ( throwStmt->expr ) {
823 const ast::StructDecl * exceptionDecl =
824 symtab.lookupStruct( "__cfaehm_base_exception_t" );
825 assert( exceptionDecl );
826 ast::ptr< ast::Type > exceptType =
827 new ast::PointerType{ new ast::StructInstType{ exceptionDecl } };
828 throwStmt = ast::mutate_field(
829 throwStmt, &ast::ThrowStmt::expr,
830 findSingleExpression( throwStmt->expr, exceptType, context ) );
831 }
832 return throwStmt;
833}
834
835const ast::CatchClause * Resolver::previsit( const ast::CatchClause * catchClause ) {
836 // Until we are very sure this invarent (ifs that move between passes have then)
837 // holds, check it. This allows a check for when to decode the mangling.
838 if ( auto ifStmt = catchClause->body.as<ast::IfStmt>() ) {
839 assert( ifStmt->then );
840 }
841 // Encode the catchStmt so the condition can see the declaration.
842 if ( catchClause->cond ) {
843 ast::CatchClause * clause = mutate( catchClause );
844 clause->body = new ast::IfStmt( clause->location, clause->cond, nullptr, clause->body );
845 clause->cond = nullptr;
846 return clause;
847 }
848 return catchClause;
849}
850
851const ast::CatchClause * Resolver::postvisit( const ast::CatchClause * catchClause ) {
852 // Decode the catchStmt so everything is stored properly.
853 const ast::IfStmt * ifStmt = catchClause->body.as<ast::IfStmt>();
854 if ( nullptr != ifStmt && nullptr == ifStmt->then ) {
855 assert( ifStmt->cond );
856 assert( ifStmt->else_ );
857 ast::CatchClause * clause = ast::mutate( catchClause );
858 clause->cond = ifStmt->cond;
859 clause->body = ifStmt->else_;
860 // ifStmt should be implicately deleted here.
861 return clause;
862 }
863 return catchClause;
864}
865
866const ast::WaitForStmt * Resolver::previsit( const ast::WaitForStmt * stmt ) {
867 visit_children = false;
868
869 // Resolve all clauses first
870 for ( unsigned i = 0; i < stmt->clauses.size(); ++i ) {
871 const ast::WaitForClause & clause = *stmt->clauses[i];
872
873 ast::TypeEnvironment env;
874 CandidateFinder funcFinder( context, env );
875
876 // Find all candidates for a function in canonical form
877 funcFinder.find( clause.target, ResolveMode::withAdjustment() );
878
879 if ( funcFinder.candidates.empty() ) {
880 stringstream ss;
881 ss << "Use of undeclared indentifier '";
882 ss << clause.target.strict_as< ast::NameExpr >()->name;
883 ss << "' in call to waitfor";
884 SemanticError( stmt->location, ss.str() );
885 }
886
887 if ( clause.target_args.empty() ) {
888 SemanticError( stmt->location,
889 "Waitfor clause must have at least one mutex parameter");
890 }
891
892 // Find all alternatives for all arguments in canonical form
893 std::vector< CandidateFinder > argFinders =
894 funcFinder.findSubExprs( clause.target_args );
895
896 // List all combinations of arguments
897 std::vector< CandidateList > possibilities;
898 combos( argFinders.begin(), argFinders.end(), back_inserter( possibilities ) );
899
900 // For every possible function:
901 // * try matching the arguments to the parameters, not the other way around because
902 // more arguments than parameters
903 CandidateList funcCandidates;
904 std::vector< CandidateList > argsCandidates;
905 SemanticErrorException errors;
906 for ( CandidateRef & func : funcFinder.candidates ) {
907 try {
908 auto pointerType = dynamic_cast< const ast::PointerType * >(
909 func->expr->result->stripReferences() );
910 if ( ! pointerType ) {
911 SemanticError( stmt->location, func->expr->result.get(),
912 "candidate not viable: not a pointer type\n" );
913 }
914
915 auto funcType = pointerType->base.as< ast::FunctionType >();
916 if ( ! funcType ) {
917 SemanticError( stmt->location, func->expr->result.get(),
918 "candidate not viable: not a function type\n" );
919 }
920
921 {
922 auto param = funcType->params.begin();
923 auto paramEnd = funcType->params.end();
924
925 if( ! nextMutex( param, paramEnd ) ) {
926 SemanticError( stmt->location, funcType,
927 "candidate function not viable: no mutex parameters\n");
928 }
929 }
930
931 CandidateRef func2{ new Candidate{ *func } };
932 // strip reference from function
933 func2->expr = referenceToRvalueConversion( func->expr, func2->cost );
934
935 // Each argument must be matched with a parameter of the current candidate
936 for ( auto & argsList : possibilities ) {
937 try {
938 // Declare data structures needed for resolution
939 ast::OpenVarSet open;
940 ast::AssertionSet need, have;
941 ast::TypeEnvironment resultEnv{ func->env };
942 // Add all type variables as open so that those not used in the
943 // parameter list are still considered open
944 resultEnv.add( funcType->forall );
945
946 // load type variables from arguments into one shared space
947 for ( auto & arg : argsList ) {
948 resultEnv.simpleCombine( arg->env );
949 }
950
951 // Make sure we don't widen any existing bindings
952 resultEnv.forbidWidening();
953
954 // Find any unbound type variables
955 resultEnv.extractOpenVars( open );
956
957 auto param = funcType->params.begin();
958 auto paramEnd = funcType->params.end();
959
960 unsigned n_mutex_param = 0;
961
962 // For every argument of its set, check if it matches one of the
963 // parameters. The order is important
964 for ( auto & arg : argsList ) {
965 // Ignore non-mutex arguments
966 if ( ! nextMutex( param, paramEnd ) ) {
967 // We ran out of parameters but still have arguments.
968 // This function doesn't match
969 SemanticError( stmt->location, funcType,
970 toString("candidate function not viable: too many mutex "
971 "arguments, expected ", n_mutex_param, "\n" ) );
972 }
973
974 ++n_mutex_param;
975
976 // Check if the argument matches the parameter type in the current scope.
977 // ast::ptr< ast::Type > paramType = (*param)->get_type();
978
979 if (
980 ! unify(
981 arg->expr->result, *param, resultEnv, need, have, open )
982 ) {
983 // Type doesn't match
984 stringstream ss;
985 ss << "candidate function not viable: no known conversion "
986 "from '";
987 ast::print( ss, *param );
988 ss << "' to '";
989 ast::print( ss, arg->expr->result );
990 ss << "' with env '";
991 ast::print( ss, resultEnv );
992 ss << "'\n";
993 SemanticError( stmt->location, funcType, ss.str() );
994 }
995
996 ++param;
997 }
998
999 // All arguments match!
1000
1001 // Check if parameters are missing
1002 if ( nextMutex( param, paramEnd ) ) {
1003 do {
1004 ++n_mutex_param;
1005 ++param;
1006 } while ( nextMutex( param, paramEnd ) );
1007
1008 // We ran out of arguments but still have parameters left; this
1009 // function doesn't match
1010 SemanticError( stmt->location, funcType,
1011 toString( "candidate function not viable: too few mutex "
1012 "arguments, expected ", n_mutex_param, "\n" ) );
1013 }
1014
1015 // All parameters match!
1016
1017 // Finish the expressions to tie in proper environments
1018 finishExpr( func2->expr, resultEnv );
1019 for ( CandidateRef & arg : argsList ) {
1020 finishExpr( arg->expr, resultEnv );
1021 }
1022
1023 // This is a match, store it and save it for later
1024 funcCandidates.emplace_back( std::move( func2 ) );
1025 argsCandidates.emplace_back( std::move( argsList ) );
1026
1027 } catch ( SemanticErrorException & e ) {
1028 errors.append( e );
1029 }
1030 }
1031 } catch ( SemanticErrorException & e ) {
1032 errors.append( e );
1033 }
1034 }
1035
1036 // Make sure correct number of arguments
1037 if( funcCandidates.empty() ) {
1038 SemanticErrorException top( stmt->location,
1039 "No alternatives for function in call to waitfor" );
1040 top.append( errors );
1041 throw top;
1042 }
1043
1044 if( argsCandidates.empty() ) {
1045 SemanticErrorException top( stmt->location,
1046 "No alternatives for arguments in call to waitfor" );
1047 top.append( errors );
1048 throw top;
1049 }
1050
1051 if( funcCandidates.size() > 1 ) {
1052 SemanticErrorException top( stmt->location,
1053 "Ambiguous function in call to waitfor" );
1054 top.append( errors );
1055 throw top;
1056 }
1057 if( argsCandidates.size() > 1 ) {
1058 SemanticErrorException top( stmt->location,
1059 "Ambiguous arguments in call to waitfor" );
1060 top.append( errors );
1061 throw top;
1062 }
1063 // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
1064
1065 // build new clause
1066 auto clause2 = new ast::WaitForClause( clause.location );
1067
1068 clause2->target = funcCandidates.front()->expr;
1069
1070 clause2->target_args.reserve( clause.target_args.size() );
1071 const ast::StructDecl * decl_monitor = symtab.lookupStruct( "monitor$" );
1072 for ( auto arg : argsCandidates.front() ) {
1073 const auto & loc = stmt->location;
1074
1075 ast::Expr * init = new ast::CastExpr( loc,
1076 new ast::UntypedExpr( loc,
1077 new ast::NameExpr( loc, "get_monitor" ),
1078 { arg->expr }
1079 ),
1080 new ast::PointerType(
1081 new ast::StructInstType(
1082 decl_monitor
1083 )
1084 )
1085 );
1086
1087 clause2->target_args.emplace_back( findSingleExpression( init, context ) );
1088 }
1089
1090 // Resolve the conditions as if it were an IfStmt, statements normally
1091 clause2->when_cond = findCondExpression( clause.when_cond, context );
1092 clause2->stmt = clause.stmt->accept( *visitor );
1093
1094 // set results into stmt
1095 auto n = mutate( stmt );
1096 n->clauses[i] = clause2;
1097 stmt = n;
1098 }
1099
1100 if ( stmt->timeout_stmt ) {
1101 // resolve the timeout as a size_t, the conditions like IfStmt, and stmts normally
1102 ast::ptr< ast::Type > target =
1103 new ast::BasicType{ ast::BasicKind::LongLongUnsignedInt };
1104 auto timeout_time = findSingleExpression( stmt->timeout_time, target, context );
1105 auto timeout_cond = findCondExpression( stmt->timeout_cond, context );
1106 auto timeout_stmt = stmt->timeout_stmt->accept( *visitor );
1107
1108 // set results into stmt
1109 auto n = mutate( stmt );
1110 n->timeout_time = std::move( timeout_time );
1111 n->timeout_cond = std::move( timeout_cond );
1112 n->timeout_stmt = std::move( timeout_stmt );
1113 stmt = n;
1114 }
1115
1116 if ( stmt->else_stmt ) {
1117 // resolve the condition like IfStmt, stmts normally
1118 auto else_cond = findCondExpression( stmt->else_cond, context );
1119 auto else_stmt = stmt->else_stmt->accept( *visitor );
1120
1121 // set results into stmt
1122 auto n = mutate( stmt );
1123 n->else_cond = std::move( else_cond );
1124 n->else_stmt = std::move( else_stmt );
1125 stmt = n;
1126 }
1127
1128 return stmt;
1129}
1130
1131const ast::WithStmt * Resolver::previsit( const ast::WithStmt * withStmt ) {
1132 auto mutStmt = mutate(withStmt);
1133 resolveWithExprs(mutStmt->exprs, stmtsToAddBefore);
1134 return mutStmt;
1135}
1136
1137void Resolver::resolveWithExprs(std::vector<ast::ptr<ast::Expr>> & exprs, std::list<ast::ptr<ast::Stmt>> & stmtsToAdd) {
1138 for (auto & expr : exprs) {
1139 // only struct- and union-typed expressions are viable candidates
1140 expr = findKindExpression( expr, context, structOrUnionOrEnum, "with expression" );
1141
1142 // if with expression might be impure, create a temporary so that it is evaluated once
1143 if ( Tuples::maybeImpure( expr ) ) {
1144 static UniqueName tmpNamer( "_with_tmp_" );
1145 const CodeLocation loc = expr->location;
1146 auto tmp = new ast::ObjectDecl(loc, tmpNamer.newName(), expr->result, new ast::SingleInit(loc, expr ) );
1147 expr = new ast::VariableExpr( loc, tmp );
1148 stmtsToAdd.push_back( new ast::DeclStmt(loc, tmp ) );
1149 if ( InitTweak::isConstructable( tmp->type ) ) {
1150 // generate ctor/dtor and resolve them
1151 tmp->init = InitTweak::genCtorInit( loc, tmp );
1152 }
1153 // since tmp is freshly created, this should modify tmp in-place
1154 tmp->accept( *visitor );
1155 } else if (expr->env && expr->env->empty()) {
1156 expr = ast::mutate_field(expr.get(), &ast::Expr::env, nullptr);
1157 }
1158 }
1159}
1160
1161const ast::SingleInit * Resolver::previsit( const ast::SingleInit * singleInit ) {
1162 visit_children = false;
1163 // resolve initialization using the possibilities as determined by the `currentObject`
1164 // cursor.
1165 ast::ptr< ast::Expr > untyped = new ast::UntypedInitExpr{
1166 singleInit->location, singleInit->value, currentObject.getOptions() };
1167 ast::ptr<ast::Expr> newExpr = findSingleExpression( untyped, context );
1168 const ast::InitExpr * initExpr = newExpr.strict_as< ast::InitExpr >();
1169
1170 // move cursor to the object that is actually initialized
1171 currentObject.setNext( initExpr->designation );
1172
1173 // discard InitExpr wrapper and retain relevant pieces.
1174 // `initExpr` may have inferred params in the case where the expression specialized a
1175 // function pointer, and newExpr may already have inferParams of its own, so a simple
1176 // swap is not sufficient
1177 ast::Expr::InferUnion inferred = initExpr->inferred;
1178 swap_and_save_env( newExpr, initExpr->expr );
1179 newExpr.get_and_mutate()->inferred.splice( std::move(inferred) );
1180
1181 // get the actual object's type (may not exactly match what comes back from the resolver
1182 // due to conversions)
1183 const ast::Type * initContext = currentObject.getCurrentType();
1184
1185 removeExtraneousCast( newExpr );
1186
1187 // check if actual object's type is char[]
1188 if ( auto at = dynamic_cast< const ast::ArrayType * >( initContext ) ) {
1189 if ( isCharType( at->base ) ) {
1190 // check if the resolved type is char*
1191 if ( auto pt = newExpr->result.as< ast::PointerType >() ) {
1192 if ( isCharType( pt->base ) ) {
1193 // strip cast if we're initializing a char[] with a char*
1194 // e.g. char x[] = "hello"
1195 if ( auto ce = newExpr.as< ast::CastExpr >() ) {
1196 swap_and_save_env( newExpr, ce->arg );
1197 }
1198 }
1199 }
1200 }
1201 }
1202
1203 // move cursor to next object in preparation for next initializer
1204 currentObject.increment();
1205
1206 // set initializer expression to resolved expression
1207 return ast::mutate_field( singleInit, &ast::SingleInit::value, std::move(newExpr) );
1208}
1209
1210const ast::ListInit * Resolver::previsit( const ast::ListInit * listInit ) {
1211 // move cursor into brace-enclosed initializer-list
1212 currentObject.enterListInit( listInit->location );
1213
1214 assert( listInit->designations.size() == listInit->initializers.size() );
1215 for ( unsigned i = 0; i < listInit->designations.size(); ++i ) {
1216 // iterate designations and initializers in pairs, moving the cursor to the current
1217 // designated object and resolving the initializer against that object
1218 listInit = ast::mutate_field_index(
1219 listInit, &ast::ListInit::designations, i,
1220 currentObject.findNext( listInit->designations[i] ) );
1221 listInit = ast::mutate_field_index(
1222 listInit, &ast::ListInit::initializers, i,
1223 listInit->initializers[i]->accept( *visitor ) );
1224 }
1225
1226 // move cursor out of brace-enclosed initializer-list
1227 currentObject.exitListInit();
1228
1229 visit_children = false;
1230 return listInit;
1231}
1232
1233const ast::ConstructorInit * Resolver::previsit( const ast::ConstructorInit * ctorInit ) {
1234 visitor->maybe_accept( ctorInit, &ast::ConstructorInit::ctor );
1235 visitor->maybe_accept( ctorInit, &ast::ConstructorInit::dtor );
1236
1237 // found a constructor - can get rid of C-style initializer
1238 // xxx - Rob suggests this field is dead code
1239 ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::init, nullptr );
1240
1241 // intrinsic single-parameter constructors and destructors do nothing. Since this was
1242 // implicitly generated, there's no way for it to have side effects, so get rid of it to
1243 // clean up generated code
1244 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
1245 ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::ctor, nullptr );
1246 }
1247 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
1248 ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::dtor, nullptr );
1249 }
1250
1251 return ctorInit;
1252}
1253
1254// suppress error on autogen functions and mark invalid autogen as deleted.
1255bool Resolver::on_error(ast::ptr<ast::Decl> & decl) {
1256 if (auto functionDecl = decl.as<ast::FunctionDecl>()) {
1257 // xxx - can intrinsic gen ever fail?
1258 if (functionDecl->linkage == ast::Linkage::AutoGen) {
1259 auto mutDecl = mutate(functionDecl);
1260 mutDecl->isDeleted = true;
1261 mutDecl->stmts = nullptr;
1262 decl = mutDecl;
1263 return false;
1264 }
1265 }
1266 return true;
1267}
1268
1269} // namespace ResolvExpr
1270
1271// Local Variables: //
1272// tab-width: 4 //
1273// mode: c++ //
1274// compile-command: "make install" //
1275// End: //
Note: See TracBrowser for help on using the repository browser.