source: src/ResolvExpr/Resolver.cc@ 152c2b2

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 152c2b2 was 665f432, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Fixed trac #149 where operand names in asm statements where incorrectly resolved (i.e., should not have been resolved)

  • Property mode set to 100644
File size: 66.0 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.cc --
8//
9// Author : Aaron B. Moss
10// Created On : Sun May 17 12:17:01 2015
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Wed May 29 11:00:00 2019
13// Update Count : 241
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 "Alternative.h" // for Alternative, AltList
22#include "AlternativeFinder.h" // for AlternativeFinder, resolveIn...
23#include "Candidate.hpp"
24#include "CandidateFinder.hpp"
25#include "CurrentObject.h" // for CurrentObject
26#include "RenameVars.h" // for RenameVars, global_renamer
27#include "Resolver.h"
28#include "ResolvMode.h" // for ResolvMode
29#include "typeops.h" // for extractResultType
30#include "Unify.h" // for unify
31#include "AST/Chain.hpp"
32#include "AST/Decl.hpp"
33#include "AST/Init.hpp"
34#include "AST/Pass.hpp"
35#include "AST/Print.hpp"
36#include "AST/SymbolTable.hpp"
37#include "AST/Type.hpp"
38#include "Common/PassVisitor.h" // for PassVisitor
39#include "Common/SemanticError.h" // for SemanticError
40#include "Common/utility.h" // for ValueGuard, group_iterate
41#include "InitTweak/GenInit.h"
42#include "InitTweak/InitTweak.h" // for isIntrinsicSingleArgCallStmt
43#include "ResolvExpr/TypeEnvironment.h" // for TypeEnvironment
44#include "SymTab/Autogen.h" // for SizeType
45#include "SymTab/Indexer.h" // for Indexer
46#include "SynTree/Declaration.h" // for ObjectDecl, TypeDecl, Declar...
47#include "SynTree/Expression.h" // for Expression, CastExpr, InitExpr
48#include "SynTree/Initializer.h" // for ConstructorInit, SingleInit
49#include "SynTree/Statement.h" // for ForStmt, Statement, BranchStmt
50#include "SynTree/Type.h" // for Type, BasicType, PointerType
51#include "SynTree/TypeSubstitution.h" // for TypeSubstitution
52#include "SynTree/Visitor.h" // for acceptAll, maybeAccept
53#include "Tuples/Tuples.h"
54#include "Validate/FindSpecialDecls.h" // for SizeType
55
56using namespace std;
57
58namespace ResolvExpr {
59 struct Resolver_old final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver_old>, public WithShortCircuiting, public WithStmtsToAdd {
60 Resolver_old() {}
61 Resolver_old( const SymTab::Indexer & other ) {
62 indexer = other;
63 }
64
65 void previsit( FunctionDecl * functionDecl );
66 void postvisit( FunctionDecl * functionDecl );
67 void previsit( ObjectDecl * objectDecll );
68 void previsit( EnumDecl * enumDecl );
69 void previsit( StaticAssertDecl * assertDecl );
70
71 void previsit( ArrayType * at );
72 void previsit( PointerType * at );
73
74 void previsit( ExprStmt * exprStmt );
75 void previsit( AsmExpr * asmExpr );
76 void previsit( AsmStmt * asmStmt );
77 void previsit( IfStmt * ifStmt );
78 void previsit( WhileStmt * whileStmt );
79 void previsit( ForStmt * forStmt );
80 void previsit( SwitchStmt * switchStmt );
81 void previsit( CaseStmt * caseStmt );
82 void previsit( BranchStmt * branchStmt );
83 void previsit( ReturnStmt * returnStmt );
84 void previsit( ThrowStmt * throwStmt );
85 void previsit( CatchStmt * catchStmt );
86 void previsit( WaitForStmt * stmt );
87
88 void previsit( SingleInit * singleInit );
89 void previsit( ListInit * listInit );
90 void previsit( ConstructorInit * ctorInit );
91 private:
92 typedef std::list< Initializer * >::iterator InitIterator;
93
94 template< typename PtrType >
95 void handlePtrType( PtrType * type );
96
97 void fallbackInit( ConstructorInit * ctorInit );
98
99 Type * functionReturn = nullptr;
100 CurrentObject currentObject = nullptr;
101 bool inEnumDecl = false;
102 };
103
104 struct ResolveWithExprs : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveWithExprs>, public WithShortCircuiting, public WithStmtsToAdd {
105 void previsit( FunctionDecl * );
106 void previsit( WithStmt * );
107
108 void resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts );
109 };
110
111 void resolve( std::list< Declaration * > translationUnit ) {
112 PassVisitor<Resolver_old> resolver;
113 acceptAll( translationUnit, resolver );
114 }
115
116 void resolveDecl( Declaration * decl, const SymTab::Indexer & indexer ) {
117 PassVisitor<Resolver_old> resolver( indexer );
118 maybeAccept( decl, resolver );
119 }
120
121 namespace {
122 struct DeleteFinder_old : public WithShortCircuiting {
123 DeletedExpr * delExpr = nullptr;
124 void previsit( DeletedExpr * expr ) {
125 if ( delExpr ) visit_children = false;
126 else delExpr = expr;
127 }
128
129 void previsit( Expression * ) {
130 if ( delExpr ) visit_children = false;
131 }
132 };
133 }
134
135 DeletedExpr * findDeletedExpr( Expression * expr ) {
136 PassVisitor<DeleteFinder_old> finder;
137 expr->accept( finder );
138 return finder.pass.delExpr;
139 }
140
141 namespace {
142 struct StripCasts_old {
143 Expression * postmutate( CastExpr * castExpr ) {
144 if ( castExpr->isGenerated && ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, SymTab::Indexer() ) ) {
145 // generated cast is to the same type as its argument, so it's unnecessary -- remove it
146 Expression * expr = castExpr->arg;
147 castExpr->arg = nullptr;
148 std::swap( expr->env, castExpr->env );
149 return expr;
150 }
151 return castExpr;
152 }
153
154 static void strip( Expression *& expr ) {
155 PassVisitor<StripCasts_old> stripper;
156 expr = expr->acceptMutator( stripper );
157 }
158 };
159
160 void finishExpr( Expression *& expr, const TypeEnvironment & env, TypeSubstitution * oldenv = nullptr ) {
161 expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
162 env.makeSubstitution( *expr->env );
163 StripCasts_old::strip( expr ); // remove unnecessary casts that may be buried in an expression
164 }
165
166 void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) {
167 if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
168 if ( typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) {
169 // cast is to the same type as its argument, so it's unnecessary -- remove it
170 expr = castExpr->arg;
171 castExpr->arg = nullptr;
172 std::swap( expr->env, castExpr->env );
173 delete castExpr;
174 }
175 }
176 }
177 } // namespace
178
179 namespace {
180 void findUnfinishedKindExpression(Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{} ) {
181 assertf( untyped, "expected a non-null expression." );
182
183 // xxx - this isn't thread-safe, but should work until we parallelize the resolver
184 static unsigned recursion_level = 0;
185
186 ++recursion_level;
187 TypeEnvironment env;
188 AlternativeFinder finder( indexer, env );
189 finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode );
190 --recursion_level;
191
192 #if 0
193 if ( finder.get_alternatives().size() != 1 ) {
194 std::cerr << "untyped expr is ";
195 untyped->print( std::cerr );
196 std::cerr << std::endl << "alternatives are:";
197 for ( const Alternative & alt : finder.get_alternatives() ) {
198 alt.print( std::cerr );
199 } // for
200 } // if
201 #endif
202
203 // produce filtered list of alternatives
204 AltList candidates;
205 for ( Alternative & alt : finder.get_alternatives() ) {
206 if ( pred( alt ) ) {
207 candidates.push_back( std::move( alt ) );
208 }
209 }
210
211 // produce invalid error if no candidates
212 if ( candidates.empty() ) {
213 SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") );
214 }
215
216 // search for cheapest candidate
217 AltList winners;
218 bool seen_undeleted = false;
219 for ( unsigned i = 0; i < candidates.size(); ++i ) {
220 int c = winners.empty() ? -1 : candidates[i].cost.compare( winners.front().cost );
221
222 if ( c > 0 ) continue; // skip more expensive than winner
223
224 if ( c < 0 ) {
225 // reset on new cheapest
226 seen_undeleted = ! findDeletedExpr( candidates[i].expr );
227 winners.clear();
228 } else /* if ( c == 0 ) */ {
229 if ( findDeletedExpr( candidates[i].expr ) ) {
230 // skip deleted expression if already seen one equivalent-cost not
231 if ( seen_undeleted ) continue;
232 } else if ( ! seen_undeleted ) {
233 // replace list of equivalent-cost deleted expressions with one non-deleted
234 winners.clear();
235 seen_undeleted = true;
236 }
237 }
238
239 winners.emplace_back( std::move( candidates[i] ) );
240 }
241
242 // promote alternative.cvtCost to .cost
243 // xxx - I don't know why this is done, but I'm keeping the behaviour from findMinCost
244 for ( Alternative& winner : winners ) {
245 winner.cost = winner.cvtCost;
246 }
247
248 // produce ambiguous errors, if applicable
249 if ( winners.size() != 1 ) {
250 std::ostringstream stream;
251 stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n";
252 untyped->print( stream );
253 stream << " Alternatives are:\n";
254 printAlts( winners, stream, 1 );
255 SemanticError( untyped->location, stream.str() );
256 }
257
258 // single selected choice
259 Alternative& choice = winners.front();
260
261 // fail on only expression deleted
262 if ( ! seen_undeleted ) {
263 SemanticError( untyped->location, choice.expr, "Unique best alternative includes deleted identifier in " );
264 }
265
266 // xxx - check for ambiguous expressions
267
268 // output selected choice
269 alt = std::move( choice );
270 }
271
272 /// resolve `untyped` to the expression whose alternative satisfies `pred` with the lowest cost; kindStr is used for providing better error messages
273 void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{}) {
274 if ( ! untyped ) return;
275 Alternative choice;
276 findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, mode );
277 finishExpr( choice.expr, choice.env, untyped->env );
278 delete untyped;
279 untyped = choice.expr;
280 choice.expr = nullptr;
281 }
282
283 bool standardAlternativeFilter( const Alternative & ) {
284 // currently don't need to filter, under normal circumstances.
285 // in the future, this may be useful for removing deleted expressions
286 return true;
287 }
288 } // namespace
289
290 // used in resolveTypeof
291 Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer ) {
292 TypeEnvironment env;
293 return resolveInVoidContext( expr, indexer, env );
294 }
295
296 Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer, TypeEnvironment & env ) {
297 // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
298 // interpretations, an exception has already been thrown.
299 assertf( expr, "expected a non-null expression." );
300
301 CastExpr * untyped = new CastExpr( expr ); // cast to void
302 untyped->location = expr->location;
303
304 // set up and resolve expression cast to void
305 Alternative choice;
306 findUnfinishedKindExpression( untyped, choice, indexer, "", standardAlternativeFilter, ResolvMode::withAdjustment() );
307 CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr );
308 assert( castExpr );
309 env = std::move( choice.env );
310
311 // clean up resolved expression
312 Expression * ret = castExpr->arg;
313 castExpr->arg = nullptr;
314
315 // unlink the arg so that it isn't deleted twice at the end of the program
316 untyped->arg = nullptr;
317 return ret;
318 }
319
320 void findVoidExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
321 resetTyVarRenaming();
322 TypeEnvironment env;
323 Expression * newExpr = resolveInVoidContext( untyped, indexer, env );
324 finishExpr( newExpr, env, untyped->env );
325 delete untyped;
326 untyped = newExpr;
327 }
328
329 void findSingleExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
330 findKindExpression( untyped, indexer, "", standardAlternativeFilter );
331 }
332
333 void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) {
334 assert( untyped && type );
335 // transfer location to generated cast for error purposes
336 CodeLocation location = untyped->location;
337 untyped = new CastExpr( untyped, type );
338 untyped->location = location;
339 findSingleExpression( untyped, indexer );
340 removeExtraneousCast( untyped, indexer );
341 }
342
343 namespace {
344 bool isIntegralType( const Alternative & alt ) {
345 Type * type = alt.expr->result;
346 if ( dynamic_cast< EnumInstType * >( type ) ) {
347 return true;
348 } else if ( BasicType * bt = dynamic_cast< BasicType * >( type ) ) {
349 return bt->isInteger();
350 } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
351 return true;
352 } else {
353 return false;
354 } // if
355 }
356
357 void findIntegralExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
358 findKindExpression( untyped, indexer, "condition", isIntegralType );
359 }
360 }
361
362
363 bool isStructOrUnion( const Alternative & alt ) {
364 Type * t = alt.expr->result->stripReferences();
365 return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t );
366 }
367
368 void resolveWithExprs( std::list< Declaration * > & translationUnit ) {
369 PassVisitor<ResolveWithExprs> resolver;
370 acceptAll( translationUnit, resolver );
371 }
372
373 void ResolveWithExprs::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) {
374 for ( Expression *& expr : withExprs ) {
375 // only struct- and union-typed expressions are viable candidates
376 findKindExpression( expr, indexer, "with statement", isStructOrUnion );
377
378 // if with expression might be impure, create a temporary so that it is evaluated once
379 if ( Tuples::maybeImpure( expr ) ) {
380 static UniqueName tmpNamer( "_with_tmp_" );
381 ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) );
382 expr = new VariableExpr( tmp );
383 newStmts.push_back( new DeclStmt( tmp ) );
384 if ( InitTweak::isConstructable( tmp->type ) ) {
385 // generate ctor/dtor and resolve them
386 tmp->init = InitTweak::genCtorInit( tmp );
387 tmp->accept( *visitor );
388 }
389 }
390 }
391 }
392
393 void ResolveWithExprs::previsit( WithStmt * withStmt ) {
394 resolveWithExprs( withStmt->exprs, stmtsToAddBefore );
395 }
396
397 void ResolveWithExprs::previsit( FunctionDecl * functionDecl ) {
398 {
399 // resolve with-exprs with parameters in scope and add any newly generated declarations to the
400 // front of the function body.
401 auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } );
402 indexer.addFunctionType( functionDecl->type );
403 std::list< Statement * > newStmts;
404 resolveWithExprs( functionDecl->withExprs, newStmts );
405 if ( functionDecl->statements ) {
406 functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts );
407 } else {
408 assertf( functionDecl->withExprs.empty() && newStmts.empty(), "Function %s without a body has with-clause and/or generated with declarations.", functionDecl->name.c_str() );
409 }
410 }
411 }
412
413 void Resolver_old::previsit( ObjectDecl * objectDecl ) {
414 // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that
415 // class-variable initContext is changed multiple time because the LHS is analysed twice.
416 // The second analysis changes initContext because of a function type can contain object
417 // declarations in the return and parameter types. So each value of initContext is
418 // retained, so the type on the first analysis is preserved and used for selecting the RHS.
419 GuardValue( currentObject );
420 currentObject = CurrentObject( objectDecl->get_type() );
421 if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
422 // enumerator initializers should not use the enum type to initialize, since
423 // the enum type is still incomplete at this point. Use signed int instead.
424 currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
425 }
426 }
427
428 template< typename PtrType >
429 void Resolver_old::handlePtrType( PtrType * type ) {
430 if ( type->get_dimension() ) {
431 findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
432 }
433 }
434
435 void Resolver_old::previsit( ArrayType * at ) {
436 handlePtrType( at );
437 }
438
439 void Resolver_old::previsit( PointerType * pt ) {
440 handlePtrType( pt );
441 }
442
443 void Resolver_old::previsit( FunctionDecl * functionDecl ) {
444#if 0
445 std::cerr << "resolver visiting functiondecl ";
446 functionDecl->print( std::cerr );
447 std::cerr << std::endl;
448#endif
449 GuardValue( functionReturn );
450 functionReturn = ResolvExpr::extractResultType( functionDecl->type );
451 }
452
453 void Resolver_old::postvisit( FunctionDecl * functionDecl ) {
454 // default value expressions have an environment which shouldn't be there and trips up
455 // later passes.
456 // xxx - it might be necessary to somehow keep the information from this environment, but I
457 // can't currently see how it's useful.
458 for ( Declaration * d : functionDecl->type->parameters ) {
459 if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
460 if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
461 delete init->value->env;
462 init->value->env = nullptr;
463 }
464 }
465 }
466 }
467
468 void Resolver_old::previsit( EnumDecl * ) {
469 // in case we decide to allow nested enums
470 GuardValue( inEnumDecl );
471 inEnumDecl = true;
472 }
473
474 void Resolver_old::previsit( StaticAssertDecl * assertDecl ) {
475 findIntegralExpression( assertDecl->condition, indexer );
476 }
477
478 void Resolver_old::previsit( ExprStmt * exprStmt ) {
479 visit_children = false;
480 assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
481 findVoidExpression( exprStmt->expr, indexer );
482 }
483
484 void Resolver_old::previsit( AsmExpr * asmExpr ) {
485 visit_children = false;
486 findVoidExpression( asmExpr->operand, indexer );
487 }
488
489 void Resolver_old::previsit( AsmStmt * asmStmt ) {
490 visit_children = false;
491 acceptAll( asmStmt->get_input(), *visitor );
492 acceptAll( asmStmt->get_output(), *visitor );
493 }
494
495 void Resolver_old::previsit( IfStmt * ifStmt ) {
496 findIntegralExpression( ifStmt->condition, indexer );
497 }
498
499 void Resolver_old::previsit( WhileStmt * whileStmt ) {
500 findIntegralExpression( whileStmt->condition, indexer );
501 }
502
503 void Resolver_old::previsit( ForStmt * forStmt ) {
504 if ( forStmt->condition ) {
505 findIntegralExpression( forStmt->condition, indexer );
506 } // if
507
508 if ( forStmt->increment ) {
509 findVoidExpression( forStmt->increment, indexer );
510 } // if
511 }
512
513 void Resolver_old::previsit( SwitchStmt * switchStmt ) {
514 GuardValue( currentObject );
515 findIntegralExpression( switchStmt->condition, indexer );
516
517 currentObject = CurrentObject( switchStmt->condition->result );
518 }
519
520 void Resolver_old::previsit( CaseStmt * caseStmt ) {
521 if ( caseStmt->condition ) {
522 std::list< InitAlternative > initAlts = currentObject.getOptions();
523 assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
524 // must remove cast from case statement because RangeExpr cannot be cast.
525 Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() );
526 findSingleExpression( newExpr, indexer );
527 // case condition cannot have a cast in C, so it must be removed, regardless of whether it performs a conversion.
528 // Ideally we would perform the conversion internally here.
529 if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( newExpr ) ) {
530 newExpr = castExpr->arg;
531 castExpr->arg = nullptr;
532 std::swap( newExpr->env, castExpr->env );
533 delete castExpr;
534 }
535 caseStmt->condition = newExpr;
536 }
537 }
538
539 void Resolver_old::previsit( BranchStmt * branchStmt ) {
540 visit_children = false;
541 // must resolve the argument for a computed goto
542 if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
543 if ( branchStmt->computedTarget ) {
544 // computed goto argument is void *
545 findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
546 } // if
547 } // if
548 }
549
550 void Resolver_old::previsit( ReturnStmt * returnStmt ) {
551 visit_children = false;
552 if ( returnStmt->expr ) {
553 findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
554 } // if
555 }
556
557 void Resolver_old::previsit( ThrowStmt * throwStmt ) {
558 visit_children = false;
559 // TODO: Replace *exception type with &exception type.
560 if ( throwStmt->get_expr() ) {
561 const StructDecl * exception_decl = indexer.lookupStruct( "__cfaabi_ehm__base_exception_t" );
562 assert( exception_decl );
563 Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, const_cast<StructDecl *>(exception_decl) ) );
564 findSingleExpression( throwStmt->expr, exceptType, indexer );
565 }
566 }
567
568 void Resolver_old::previsit( CatchStmt * catchStmt ) {
569 if ( catchStmt->cond ) {
570 findSingleExpression( catchStmt->cond, new BasicType( noQualifiers, BasicType::Bool ), indexer );
571 }
572 }
573
574 template< typename iterator_t >
575 inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
576 while( it != end && !(*it)->get_type()->get_mutex() ) {
577 it++;
578 }
579
580 return it != end;
581 }
582
583 void Resolver_old::previsit( WaitForStmt * stmt ) {
584 visit_children = false;
585
586 // Resolve all clauses first
587 for( auto& clause : stmt->clauses ) {
588
589 TypeEnvironment env;
590 AlternativeFinder funcFinder( indexer, env );
591
592 // Find all alternatives for a function in canonical form
593 funcFinder.findWithAdjustment( clause.target.function );
594
595 if ( funcFinder.get_alternatives().empty() ) {
596 stringstream ss;
597 ss << "Use of undeclared indentifier '";
598 ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
599 ss << "' in call to waitfor";
600 SemanticError( stmt->location, ss.str() );
601 }
602
603 if(clause.target.arguments.empty()) {
604 SemanticError( stmt->location, "Waitfor clause must have at least one mutex parameter");
605 }
606
607 // Find all alternatives for all arguments in canonical form
608 std::vector< AlternativeFinder > argAlternatives;
609 funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
610
611 // List all combinations of arguments
612 std::vector< AltList > possibilities;
613 combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
614
615 AltList func_candidates;
616 std::vector< AltList > args_candidates;
617
618 // For every possible function :
619 // try matching the arguments to the parameters
620 // not the other way around because we have more arguments than parameters
621 SemanticErrorException errors;
622 for ( Alternative & func : funcFinder.get_alternatives() ) {
623 try {
624 PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
625 if( !pointer ) {
626 SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" );
627 }
628
629 FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
630 if( !function ) {
631 SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" );
632 }
633
634
635 {
636 auto param = function->parameters.begin();
637 auto param_end = function->parameters.end();
638
639 if( !advance_to_mutex( param, param_end ) ) {
640 SemanticError(function, "candidate function not viable: no mutex parameters\n");
641 }
642 }
643
644 Alternative newFunc( func );
645 // Strip reference from function
646 referenceToRvalueConversion( newFunc.expr, newFunc.cost );
647
648 // For all the set of arguments we have try to match it with the parameter of the current function alternative
649 for ( auto & argsList : possibilities ) {
650
651 try {
652 // Declare data structures need for resolution
653 OpenVarSet openVars;
654 AssertionSet resultNeed, resultHave;
655 TypeEnvironment resultEnv( func.env );
656 makeUnifiableVars( function, openVars, resultNeed );
657 // add all type variables as open variables now so that those not used in the parameter
658 // list are still considered open.
659 resultEnv.add( function->forall );
660
661 // Load type variables from arguemnts into one shared space
662 simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );
663
664 // Make sure we don't widen any existing bindings
665 resultEnv.forbidWidening();
666
667 // Find any unbound type variables
668 resultEnv.extractOpenVars( openVars );
669
670 auto param = function->parameters.begin();
671 auto param_end = function->parameters.end();
672
673 int n_mutex_param = 0;
674
675 // For every arguments of its set, check if it matches one of the parameter
676 // The order is important
677 for( auto & arg : argsList ) {
678
679 // Ignore non-mutex arguments
680 if( !advance_to_mutex( param, param_end ) ) {
681 // We ran out of parameters but still have arguments
682 // this function doesn't match
683 SemanticError( function, toString("candidate function not viable: too many mutex arguments, expected ", n_mutex_param, "\n" ));
684 }
685
686 n_mutex_param++;
687
688 // Check if the argument matches the parameter type in the current scope
689 if( ! unify( arg.expr->get_result(), (*param)->get_type(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
690 // Type doesn't match
691 stringstream ss;
692 ss << "candidate function not viable: no known convertion from '";
693 (*param)->get_type()->print( ss );
694 ss << "' to '";
695 arg.expr->get_result()->print( ss );
696 ss << "' with env '";
697 resultEnv.print(ss);
698 ss << "'\n";
699 SemanticError( function, ss.str() );
700 }
701
702 param++;
703 }
704
705 // All arguments match !
706
707 // Check if parameters are missing
708 if( advance_to_mutex( param, param_end ) ) {
709 do {
710 n_mutex_param++;
711 param++;
712 } while( advance_to_mutex( param, param_end ) );
713
714 // We ran out of arguments but still have parameters left
715 // this function doesn't match
716 SemanticError( function, toString("candidate function not viable: too few mutex arguments, expected ", n_mutex_param, "\n" ));
717 }
718
719 // All parameters match !
720
721 // Finish the expressions to tie in the proper environments
722 finishExpr( newFunc.expr, resultEnv );
723 for( Alternative & alt : argsList ) {
724 finishExpr( alt.expr, resultEnv );
725 }
726
727 // This is a match store it and save it for later
728 func_candidates.push_back( newFunc );
729 args_candidates.push_back( argsList );
730
731 }
732 catch( SemanticErrorException & e ) {
733 errors.append( e );
734 }
735 }
736 }
737 catch( SemanticErrorException & e ) {
738 errors.append( e );
739 }
740 }
741
742 // Make sure we got the right number of arguments
743 if( func_candidates.empty() ) { SemanticErrorException top( stmt->location, "No alternatives for function in call to waitfor" ); top.append( errors ); throw top; }
744 if( args_candidates.empty() ) { SemanticErrorException top( stmt->location, "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
745 if( func_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous function in call to waitfor" ); top.append( errors ); throw top; }
746 if( args_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous arguments in call to waitfor" ); top.append( errors ); throw top; }
747 // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
748
749 // Swap the results from the alternative with the unresolved values.
750 // Alternatives will handle deletion on destruction
751 std::swap( clause.target.function, func_candidates.front().expr );
752 for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
753 std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
754 }
755
756 // Resolve the conditions as if it were an IfStmt
757 // Resolve the statments normally
758 findSingleExpression( clause.condition, this->indexer );
759 clause.statement->accept( *visitor );
760 }
761
762
763 if( stmt->timeout.statement ) {
764 // Resolve the timeout as an size_t for now
765 // Resolve the conditions as if it were an IfStmt
766 // Resolve the statments normally
767 findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
768 findSingleExpression( stmt->timeout.condition, this->indexer );
769 stmt->timeout.statement->accept( *visitor );
770 }
771
772 if( stmt->orelse.statement ) {
773 // Resolve the conditions as if it were an IfStmt
774 // Resolve the statments normally
775 findSingleExpression( stmt->orelse.condition, this->indexer );
776 stmt->orelse.statement->accept( *visitor );
777 }
778 }
779
780 bool isCharType( Type * t ) {
781 if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
782 return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
783 bt->get_kind() == BasicType::UnsignedChar;
784 }
785 return false;
786 }
787
788 void Resolver_old::previsit( SingleInit * singleInit ) {
789 visit_children = false;
790 // resolve initialization using the possibilities as determined by the currentObject cursor
791 Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
792 findSingleExpression( newExpr, indexer );
793 InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
794
795 // move cursor to the object that is actually initialized
796 currentObject.setNext( initExpr->get_designation() );
797
798 // discard InitExpr wrapper and retain relevant pieces
799 newExpr = initExpr->expr;
800 initExpr->expr = nullptr;
801 std::swap( initExpr->env, newExpr->env );
802 // InitExpr may have inferParams in the case where the expression specializes a function
803 // pointer, and newExpr may already have inferParams of its own, so a simple swap is not
804 // sufficient.
805 newExpr->spliceInferParams( initExpr );
806 delete initExpr;
807
808 // get the actual object's type (may not exactly match what comes back from the resolver
809 // due to conversions)
810 Type * initContext = currentObject.getCurrentType();
811
812 removeExtraneousCast( newExpr, indexer );
813
814 // check if actual object's type is char[]
815 if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
816 if ( isCharType( at->get_base() ) ) {
817 // check if the resolved type is char *
818 if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
819 if ( isCharType( pt->get_base() ) ) {
820 if ( CastExpr * ce = dynamic_cast< CastExpr * >( newExpr ) ) {
821 // strip cast if we're initializing a char[] with a char *,
822 // e.g. char x[] = "hello";
823 newExpr = ce->get_arg();
824 ce->set_arg( nullptr );
825 std::swap( ce->env, newExpr->env );
826 delete ce;
827 }
828 }
829 }
830 }
831 }
832
833 // set initializer expr to resolved express
834 singleInit->value = newExpr;
835
836 // move cursor to next object in preparation for next initializer
837 currentObject.increment();
838 }
839
840 void Resolver_old::previsit( ListInit * listInit ) {
841 visit_children = false;
842 // move cursor into brace-enclosed initializer-list
843 currentObject.enterListInit();
844 // xxx - fix this so that the list isn't copied, iterator should be used to change current
845 // element
846 std::list<Designation *> newDesignations;
847 for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
848 // iterate designations and initializers in pairs, moving the cursor to the current
849 // designated object and resolving the initializer against that object.
850 Designation * des = std::get<0>(p);
851 Initializer * init = std::get<1>(p);
852 newDesignations.push_back( currentObject.findNext( des ) );
853 init->accept( *visitor );
854 }
855 // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
856 listInit->get_designations() = newDesignations; // xxx - memory management
857 currentObject.exitListInit();
858
859 // xxx - this part has not be folded into CurrentObject yet
860 // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
861 // Type * base = tt->get_baseType()->get_base();
862 // if ( base ) {
863 // // know the implementation type, so try using that as the initContext
864 // ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
865 // currentObject = &tmpObj;
866 // visit( listInit );
867 // } else {
868 // // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
869 // Parent::visit( listInit );
870 // }
871 // } else {
872 }
873
874 // ConstructorInit - fall back on C-style initializer
875 void Resolver_old::fallbackInit( ConstructorInit * ctorInit ) {
876 // could not find valid constructor, or found an intrinsic constructor
877 // fall back on C-style initializer
878 delete ctorInit->get_ctor();
879 ctorInit->set_ctor( nullptr );
880 delete ctorInit->get_dtor();
881 ctorInit->set_dtor( nullptr );
882 maybeAccept( ctorInit->get_init(), *visitor );
883 }
884
885 // needs to be callable from outside the resolver, so this is a standalone function
886 void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
887 assert( ctorInit );
888 PassVisitor<Resolver_old> resolver( indexer );
889 ctorInit->accept( resolver );
890 }
891
892 void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
893 assert( stmtExpr );
894 PassVisitor<Resolver_old> resolver( indexer );
895 stmtExpr->accept( resolver );
896 stmtExpr->computeResult();
897 // xxx - aggregate the environments from all statements? Possibly in AlternativeFinder instead?
898 }
899
900 void Resolver_old::previsit( ConstructorInit * ctorInit ) {
901 visit_children = false;
902 // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
903 maybeAccept( ctorInit->ctor, *visitor );
904 maybeAccept( ctorInit->dtor, *visitor );
905
906 // found a constructor - can get rid of C-style initializer
907 delete ctorInit->init;
908 ctorInit->init = nullptr;
909
910 // intrinsic single parameter constructors and destructors do nothing. Since this was
911 // implicitly generated, there's no way for it to have side effects, so get rid of it
912 // to clean up generated code.
913 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
914 delete ctorInit->ctor;
915 ctorInit->ctor = nullptr;
916 }
917
918 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
919 delete ctorInit->dtor;
920 ctorInit->dtor = nullptr;
921 }
922
923 // xxx - todo -- what about arrays?
924 // if ( dtor == nullptr && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
925 // // can reduce the constructor down to a SingleInit using the
926 // // second argument from the ctor call, since
927 // delete ctorInit->get_ctor();
928 // ctorInit->set_ctor( nullptr );
929
930 // Expression * arg =
931 // ctorInit->set_init( new SingleInit( arg ) );
932 // }
933 }
934
935 ///////////////////////////////////////////////////////////////////////////
936 //
937 // *** NEW RESOLVER ***
938 //
939 ///////////////////////////////////////////////////////////////////////////
940
941 namespace {
942 /// Finds deleted expressions in an expression tree
943 struct DeleteFinder_new final : public ast::WithShortCircuiting {
944 const ast::DeletedExpr * delExpr = nullptr;
945
946 void previsit( const ast::DeletedExpr * expr ) {
947 if ( delExpr ) { visit_children = false; }
948 else { delExpr = expr; }
949 }
950
951 void previsit( const ast::Expr * ) {
952 if ( delExpr ) { visit_children = false; }
953 }
954 };
955 } // anonymous namespace
956
957 /// Check if this expression is or includes a deleted expression
958 const ast::DeletedExpr * findDeletedExpr( const ast::Expr * expr ) {
959 ast::Pass<DeleteFinder_new> finder;
960 expr->accept( finder );
961 return finder.pass.delExpr;
962 }
963
964 namespace {
965 /// always-accept candidate filter
966 bool anyCandidate( const Candidate & ) { return true; }
967
968 /// Calls the CandidateFinder and finds the single best candidate
969 CandidateRef findUnfinishedKindExpression(
970 const ast::Expr * untyped, const ast::SymbolTable & symtab, const std::string & kind,
971 std::function<bool(const Candidate &)> pred = anyCandidate, ResolvMode mode = {}
972 ) {
973 if ( ! untyped ) return nullptr;
974
975 // xxx - this isn't thread-safe, but should work until we parallelize the resolver
976 static unsigned recursion_level = 0;
977
978 ++recursion_level;
979 ast::TypeEnvironment env;
980 CandidateFinder finder{ symtab, env };
981 finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode );
982 --recursion_level;
983
984 // produce a filtered list of candidates
985 CandidateList candidates;
986 for ( auto & cand : finder.candidates ) {
987 if ( pred( *cand ) ) { candidates.emplace_back( cand ); }
988 }
989
990 // produce invalid error if no candidates
991 if ( candidates.empty() ) {
992 SemanticError( untyped,
993 toString( "No reasonable alternatives for ", kind, (kind != "" ? " " : ""),
994 "expression: ") );
995 }
996
997 // search for cheapest candidate
998 CandidateList winners;
999 bool seen_undeleted = false;
1000 for ( CandidateRef & cand : candidates ) {
1001 int c = winners.empty() ? -1 : cand->cost.compare( winners.front()->cost );
1002
1003 if ( c > 0 ) continue; // skip more expensive than winner
1004
1005 if ( c < 0 ) {
1006 // reset on new cheapest
1007 seen_undeleted = ! findDeletedExpr( cand->expr );
1008 winners.clear();
1009 } else /* if ( c == 0 ) */ {
1010 if ( findDeletedExpr( cand->expr ) ) {
1011 // skip deleted expression if already seen one equivalent-cost not
1012 if ( seen_undeleted ) continue;
1013 } else if ( ! seen_undeleted ) {
1014 // replace list of equivalent-cost deleted expressions with one non-deleted
1015 winners.clear();
1016 seen_undeleted = true;
1017 }
1018 }
1019
1020 winners.emplace_back( std::move( cand ) );
1021 }
1022
1023 // promote candidate.cvtCost to .cost
1024 promoteCvtCost( winners );
1025
1026 // produce ambiguous errors, if applicable
1027 if ( winners.size() != 1 ) {
1028 std::ostringstream stream;
1029 stream << "Cannot choose between " << winners.size() << " alternatives for "
1030 << kind << (kind != "" ? " " : "") << "expression\n";
1031 ast::print( stream, untyped );
1032 stream << " Alternatives are:\n";
1033 print( stream, winners, 1 );
1034 SemanticError( untyped->location, stream.str() );
1035 }
1036
1037 // single selected choice
1038 CandidateRef & choice = winners.front();
1039
1040 // fail on only expression deleted
1041 if ( ! seen_undeleted ) {
1042 SemanticError( untyped->location, choice->expr.get(), "Unique best alternative "
1043 "includes deleted identifier in " );
1044 }
1045
1046 return std::move( choice );
1047 }
1048
1049 /// Strips extraneous casts out of an expression
1050 struct StripCasts_new final {
1051 const ast::Expr * postmutate( const ast::CastExpr * castExpr ) {
1052 if (
1053 castExpr->isGenerated
1054 && typesCompatible( castExpr->arg->result, castExpr->result )
1055 ) {
1056 // generated cast is the same type as its argument, remove it after keeping env
1057 return ast::mutate_field(
1058 castExpr->arg.get(), &ast::Expr::env, castExpr->env );
1059 }
1060 return castExpr;
1061 }
1062
1063 static void strip( ast::ptr< ast::Expr > & expr ) {
1064 ast::Pass< StripCasts_new > stripper;
1065 expr = expr->accept( stripper );
1066 }
1067 };
1068
1069 /// Swaps argument into expression pointer, saving original environment
1070 void swap_and_save_env( ast::ptr< ast::Expr > & expr, const ast::Expr * newExpr ) {
1071 ast::ptr< ast::TypeSubstitution > env = expr->env;
1072 expr.set_and_mutate( newExpr )->env = env;
1073 }
1074
1075 /// Removes cast to type of argument (unlike StripCasts, also handles non-generated casts)
1076 void removeExtraneousCast( ast::ptr<ast::Expr> & expr, const ast::SymbolTable & symtab ) {
1077 if ( const ast::CastExpr * castExpr = expr.as< ast::CastExpr >() ) {
1078 if ( typesCompatible( castExpr->arg->result, castExpr->result, symtab ) ) {
1079 // cast is to the same type as its argument, remove it
1080 swap_and_save_env( expr, castExpr->arg );
1081 }
1082 }
1083 }
1084
1085 /// Establish post-resolver invariants for expressions
1086 void finishExpr(
1087 ast::ptr< ast::Expr > & expr, const ast::TypeEnvironment & env,
1088 const ast::TypeSubstitution * oldenv = nullptr
1089 ) {
1090 // set up new type substitution for expression
1091 ast::ptr< ast::TypeSubstitution > newenv =
1092 oldenv ? oldenv : new ast::TypeSubstitution{};
1093 env.writeToSubstitution( *newenv.get_and_mutate() );
1094 expr.get_and_mutate()->env = std::move( newenv );
1095 // remove unncecessary casts
1096 StripCasts_new::strip( expr );
1097 }
1098 } // anonymous namespace
1099
1100
1101 ast::ptr< ast::Expr > resolveInVoidContext(
1102 const ast::Expr * expr, const ast::SymbolTable & symtab, ast::TypeEnvironment & env
1103 ) {
1104 assertf( expr, "expected a non-null expression" );
1105
1106 // set up and resolve expression cast to void
1107 ast::CastExpr * untyped = new ast::CastExpr{ expr };
1108 CandidateRef choice = findUnfinishedKindExpression(
1109 untyped, symtab, "", anyCandidate, ResolvMode::withAdjustment() );
1110
1111 // a cast expression has either 0 or 1 interpretations (by language rules);
1112 // if 0, an exception has already been thrown, and this code will not run
1113 const ast::CastExpr * castExpr = choice->expr.strict_as< ast::CastExpr >();
1114 env = std::move( choice->env );
1115
1116 return castExpr->arg;
1117 }
1118
1119 namespace {
1120 /// Resolve `untyped` to the expression whose candidate is the best match for a `void`
1121 /// context.
1122 ast::ptr< ast::Expr > findVoidExpression(
1123 const ast::Expr * untyped, const ast::SymbolTable & symtab
1124 ) {
1125 resetTyVarRenaming();
1126 ast::TypeEnvironment env;
1127 ast::ptr< ast::Expr > newExpr = resolveInVoidContext( untyped, symtab, env );
1128 finishExpr( newExpr, env, untyped->env );
1129 return newExpr;
1130 }
1131
1132 /// resolve `untyped` to the expression whose candidate satisfies `pred` with the
1133 /// lowest cost, returning the resolved version
1134 ast::ptr< ast::Expr > findKindExpression(
1135 const ast::Expr * untyped, const ast::SymbolTable & symtab,
1136 std::function<bool(const Candidate &)> pred = anyCandidate,
1137 const std::string & kind = "", ResolvMode mode = {}
1138 ) {
1139 if ( ! untyped ) return {};
1140 CandidateRef choice =
1141 findUnfinishedKindExpression( untyped, symtab, kind, pred, mode );
1142 finishExpr( choice->expr, choice->env, untyped->env );
1143 return std::move( choice->expr );
1144 }
1145
1146 /// Resolve `untyped` to the single expression whose candidate is the best match
1147 ast::ptr< ast::Expr > findSingleExpression(
1148 const ast::Expr * untyped, const ast::SymbolTable & symtab
1149 ) {
1150 return findKindExpression( untyped, symtab );
1151 }
1152 } // anonymous namespace
1153
1154 ast::ptr< ast::Expr > findSingleExpression(
1155 const ast::Expr * untyped, const ast::Type * type, const ast::SymbolTable & symtab
1156 ) {
1157 assert( untyped && type );
1158 ast::ptr< ast::Expr > castExpr = new ast::CastExpr{ untyped, type };
1159 ast::ptr< ast::Expr > newExpr = findSingleExpression( castExpr, symtab );
1160 removeExtraneousCast( newExpr, symtab );
1161 return newExpr;
1162 }
1163
1164 namespace {
1165 /// Predicate for "Candidate has integral type"
1166 bool hasIntegralType( const Candidate & i ) {
1167 const ast::Type * type = i.expr->result;
1168
1169 if ( auto bt = dynamic_cast< const ast::BasicType * >( type ) ) {
1170 return bt->isInteger();
1171 } else if (
1172 dynamic_cast< const ast::EnumInstType * >( type )
1173 || dynamic_cast< const ast::ZeroType * >( type )
1174 || dynamic_cast< const ast::OneType * >( type )
1175 ) {
1176 return true;
1177 } else return false;
1178 }
1179
1180 /// Resolve `untyped` as an integral expression, returning the resolved version
1181 ast::ptr< ast::Expr > findIntegralExpression(
1182 const ast::Expr * untyped, const ast::SymbolTable & symtab
1183 ) {
1184 return findKindExpression( untyped, symtab, hasIntegralType, "condition" );
1185 }
1186
1187 /// check if a type is a character type
1188 bool isCharType( const ast::Type * t ) {
1189 if ( auto bt = dynamic_cast< const ast::BasicType * >( t ) ) {
1190 return bt->kind == ast::BasicType::Char
1191 || bt->kind == ast::BasicType::SignedChar
1192 || bt->kind == ast::BasicType::UnsignedChar;
1193 }
1194 return false;
1195 }
1196
1197 /// Advance a type itertor to the next mutex parameter
1198 template<typename Iter>
1199 inline bool nextMutex( Iter & it, const Iter & end ) {
1200 while ( it != end && ! (*it)->get_type()->is_mutex() ) { ++it; }
1201 return it != end;
1202 }
1203 }
1204
1205 class Resolver_new final
1206 : public ast::WithSymbolTable, public ast::WithGuards,
1207 public ast::WithVisitorRef<Resolver_new>, public ast::WithShortCircuiting,
1208 public ast::WithStmtsToAdd<> {
1209
1210 ast::ptr< ast::Type > functionReturn = nullptr;
1211 ast::CurrentObject currentObject;
1212 bool inEnumDecl = false;
1213
1214 public:
1215 Resolver_new() = default;
1216 Resolver_new( const ast::SymbolTable & syms ) { symtab = syms; }
1217
1218 void previsit( const ast::FunctionDecl * );
1219 const ast::FunctionDecl * postvisit( const ast::FunctionDecl * );
1220 void previsit( const ast::ObjectDecl * );
1221 void previsit( const ast::EnumDecl * );
1222 const ast::StaticAssertDecl * previsit( const ast::StaticAssertDecl * );
1223
1224 const ast::ArrayType * previsit( const ast::ArrayType * );
1225 const ast::PointerType * previsit( const ast::PointerType * );
1226
1227 const ast::ExprStmt * previsit( const ast::ExprStmt * );
1228 const ast::AsmExpr * previsit( const ast::AsmExpr * );
1229 const ast::AsmStmt * previsit( const ast::AsmStmt * );
1230 const ast::IfStmt * previsit( const ast::IfStmt * );
1231 const ast::WhileStmt * previsit( const ast::WhileStmt * );
1232 const ast::ForStmt * previsit( const ast::ForStmt * );
1233 const ast::SwitchStmt * previsit( const ast::SwitchStmt * );
1234 const ast::CaseStmt * previsit( const ast::CaseStmt * );
1235 const ast::BranchStmt * previsit( const ast::BranchStmt * );
1236 const ast::ReturnStmt * previsit( const ast::ReturnStmt * );
1237 const ast::ThrowStmt * previsit( const ast::ThrowStmt * );
1238 const ast::CatchStmt * previsit( const ast::CatchStmt * );
1239 const ast::WaitForStmt * previsit( const ast::WaitForStmt * );
1240
1241 const ast::SingleInit * previsit( const ast::SingleInit * );
1242 const ast::ListInit * previsit( const ast::ListInit * );
1243 const ast::ConstructorInit * previsit( const ast::ConstructorInit * );
1244 };
1245
1246 void resolve( std::list< ast::ptr<ast::Decl> >& translationUnit ) {
1247 ast::Pass< Resolver_new > resolver;
1248 accept_all( translationUnit, resolver );
1249 }
1250
1251 ast::ptr< ast::Init > resolveCtorInit(
1252 const ast::ConstructorInit * ctorInit, const ast::SymbolTable & symtab
1253 ) {
1254 assert( ctorInit );
1255 ast::Pass< Resolver_new > resolver{ symtab };
1256 return ctorInit->accept( resolver );
1257 }
1258
1259 ast::ptr< ast::Expr > resolveStmtExpr(
1260 const ast::StmtExpr * stmtExpr, const ast::SymbolTable & symtab
1261 ) {
1262 assert( stmtExpr );
1263 ast::Pass< Resolver_new > resolver{ symtab };
1264 ast::ptr< ast::Expr > ret = stmtExpr;
1265 ret = ret->accept( resolver );
1266 strict_dynamic_cast< ast::StmtExpr * >( ret.get_and_mutate() )->computeResult();
1267 return ret;
1268 }
1269
1270 void Resolver_new::previsit( const ast::FunctionDecl * functionDecl ) {
1271 GuardValue( functionReturn );
1272 functionReturn = extractResultType( functionDecl->type );
1273 }
1274
1275 const ast::FunctionDecl * Resolver_new::postvisit( const ast::FunctionDecl * functionDecl ) {
1276 // default value expressions have an environment which shouldn't be there and trips up
1277 // later passes.
1278 ast::ptr< ast::FunctionDecl > ret = functionDecl;
1279 for ( unsigned i = 0; i < functionDecl->type->params.size(); ++i ) {
1280 const ast::ptr<ast::DeclWithType> & d = functionDecl->type->params[i];
1281
1282 if ( const ast::ObjectDecl * obj = d.as< ast::ObjectDecl >() ) {
1283 if ( const ast::SingleInit * init = obj->init.as< ast::SingleInit >() ) {
1284 if ( init->value->env == nullptr ) continue;
1285 // clone initializer minus the initializer environment
1286 ast::chain_mutate( ret )
1287 ( &ast::FunctionDecl::type )
1288 ( &ast::FunctionType::params )[i]
1289 ( &ast::ObjectDecl::init )
1290 ( &ast::SingleInit::value )->env = nullptr;
1291
1292 assert( functionDecl != ret.get() || functionDecl->unique() );
1293 assert( ! ret->type->params[i].strict_as< ast::ObjectDecl >()->init.strict_as< ast::SingleInit >()->value->env );
1294 }
1295 }
1296 }
1297 return ret.get();
1298 }
1299
1300 void Resolver_new::previsit( const ast::ObjectDecl * objectDecl ) {
1301 // To handle initialization of routine pointers [e.g. int (*fp)(int) = foo()],
1302 // class-variable `initContext` is changed multiple times because the LHS is analyzed
1303 // twice. The second analysis changes `initContext` because a function type can contain
1304 // object declarations in the return and parameter types. Therefore each value of
1305 // `initContext` is retained so the type on the first analysis is preserved and used for
1306 // selecting the RHS.
1307 GuardValue( currentObject );
1308 currentObject = ast::CurrentObject{ objectDecl->location, objectDecl->get_type() };
1309 if ( inEnumDecl && dynamic_cast< const ast::EnumInstType * >( objectDecl->get_type() ) ) {
1310 // enumerator initializers should not use the enum type to initialize, since the
1311 // enum type is still incomplete at this point. Use `int` instead.
1312 currentObject = ast::CurrentObject{
1313 objectDecl->location, new ast::BasicType{ ast::BasicType::SignedInt } };
1314 }
1315 }
1316
1317 void Resolver_new::previsit( const ast::EnumDecl * ) {
1318 // in case we decide to allow nested enums
1319 GuardValue( inEnumDecl );
1320 inEnumDecl = false;
1321 }
1322
1323 const ast::StaticAssertDecl * Resolver_new::previsit(
1324 const ast::StaticAssertDecl * assertDecl
1325 ) {
1326 return ast::mutate_field(
1327 assertDecl, &ast::StaticAssertDecl::cond,
1328 findIntegralExpression( assertDecl->cond, symtab ) );
1329 }
1330
1331 template< typename PtrType >
1332 const PtrType * handlePtrType( const PtrType * type, const ast::SymbolTable & symtab ) {
1333 if ( type->dimension ) {
1334 #warning should use new equivalent to Validate::SizeType rather than sizeType here
1335 ast::ptr< ast::Type > sizeType = new ast::BasicType{ ast::BasicType::LongUnsignedInt };
1336 ast::mutate_field(
1337 type, &PtrType::dimension,
1338 findSingleExpression( type->dimension, sizeType, symtab ) );
1339 }
1340 return type;
1341 }
1342
1343 const ast::ArrayType * Resolver_new::previsit( const ast::ArrayType * at ) {
1344 return handlePtrType( at, symtab );
1345 }
1346
1347 const ast::PointerType * Resolver_new::previsit( const ast::PointerType * pt ) {
1348 return handlePtrType( pt, symtab );
1349 }
1350
1351 const ast::ExprStmt * Resolver_new::previsit( const ast::ExprStmt * exprStmt ) {
1352 visit_children = false;
1353 assertf( exprStmt->expr, "ExprStmt has null expression in resolver" );
1354
1355 return ast::mutate_field(
1356 exprStmt, &ast::ExprStmt::expr, findVoidExpression( exprStmt->expr, symtab ) );
1357 }
1358
1359 const ast::AsmExpr * Resolver_new::previsit( const ast::AsmExpr * asmExpr ) {
1360 visit_children = false;
1361
1362 asmExpr = ast::mutate_field(
1363 asmExpr, &ast::AsmExpr::operand, findVoidExpression( asmExpr->operand, symtab ) );
1364
1365 return asmExpr;
1366 }
1367
1368 const ast::AsmStmt * Resolver_new::previsit( const ast::AsmStmt * asmStmt ) {
1369 visitor->maybe_accept( asmStmt, &ast::AsmStmt::input );
1370 visitor->maybe_accept( asmStmt, &ast::AsmStmt::output );
1371 visit_children = false;
1372 return asmStmt;
1373 }
1374
1375 const ast::IfStmt * Resolver_new::previsit( const ast::IfStmt * ifStmt ) {
1376 return ast::mutate_field(
1377 ifStmt, &ast::IfStmt::cond, findIntegralExpression( ifStmt->cond, symtab ) );
1378 }
1379
1380 const ast::WhileStmt * Resolver_new::previsit( const ast::WhileStmt * whileStmt ) {
1381 return ast::mutate_field(
1382 whileStmt, &ast::WhileStmt::cond, findIntegralExpression( whileStmt->cond, symtab ) );
1383 }
1384
1385 const ast::ForStmt * Resolver_new::previsit( const ast::ForStmt * forStmt ) {
1386 if ( forStmt->cond ) {
1387 forStmt = ast::mutate_field(
1388 forStmt, &ast::ForStmt::cond, findIntegralExpression( forStmt->cond, symtab ) );
1389 }
1390
1391 if ( forStmt->inc ) {
1392 forStmt = ast::mutate_field(
1393 forStmt, &ast::ForStmt::inc, findVoidExpression( forStmt->inc, symtab ) );
1394 }
1395
1396 return forStmt;
1397 }
1398
1399 const ast::SwitchStmt * Resolver_new::previsit( const ast::SwitchStmt * switchStmt ) {
1400 GuardValue( currentObject );
1401 switchStmt = ast::mutate_field(
1402 switchStmt, &ast::SwitchStmt::cond,
1403 findIntegralExpression( switchStmt->cond, symtab ) );
1404 currentObject = ast::CurrentObject{ switchStmt->location, switchStmt->cond->result };
1405 return switchStmt;
1406 }
1407
1408 const ast::CaseStmt * Resolver_new::previsit( const ast::CaseStmt * caseStmt ) {
1409 if ( caseStmt->cond ) {
1410 std::deque< ast::InitAlternative > initAlts = currentObject.getOptions();
1411 assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral "
1412 "expression." );
1413
1414 ast::ptr< ast::Expr > untyped =
1415 new ast::CastExpr{ caseStmt->location, caseStmt->cond, initAlts.front().type };
1416 ast::ptr< ast::Expr > newExpr = findSingleExpression( untyped, symtab );
1417
1418 // case condition cannot have a cast in C, so it must be removed here, regardless of
1419 // whether it would perform a conversion.
1420 if ( const ast::CastExpr * castExpr = newExpr.as< ast::CastExpr >() ) {
1421 swap_and_save_env( newExpr, castExpr->arg );
1422 }
1423
1424 caseStmt = ast::mutate_field( caseStmt, &ast::CaseStmt::cond, newExpr );
1425 }
1426 return caseStmt;
1427 }
1428
1429 const ast::BranchStmt * Resolver_new::previsit( const ast::BranchStmt * branchStmt ) {
1430 visit_children = false;
1431 // must resolve the argument of a computed goto
1432 if ( branchStmt->kind == ast::BranchStmt::Goto && branchStmt->computedTarget ) {
1433 // computed goto argument is void*
1434 ast::ptr< ast::Type > target = new ast::PointerType{ new ast::VoidType{} };
1435 branchStmt = ast::mutate_field(
1436 branchStmt, &ast::BranchStmt::computedTarget,
1437 findSingleExpression( branchStmt->computedTarget, target, symtab ) );
1438 }
1439 return branchStmt;
1440 }
1441
1442 const ast::ReturnStmt * Resolver_new::previsit( const ast::ReturnStmt * returnStmt ) {
1443 visit_children = false;
1444 if ( returnStmt->expr ) {
1445 returnStmt = ast::mutate_field(
1446 returnStmt, &ast::ReturnStmt::expr,
1447 findSingleExpression( returnStmt->expr, functionReturn, symtab ) );
1448 }
1449 return returnStmt;
1450 }
1451
1452 const ast::ThrowStmt * Resolver_new::previsit( const ast::ThrowStmt * throwStmt ) {
1453 visit_children = false;
1454 if ( throwStmt->expr ) {
1455 const ast::StructDecl * exceptionDecl =
1456 symtab.lookupStruct( "__cfaabi_ehm__base_exception_t" );
1457 assert( exceptionDecl );
1458 ast::ptr< ast::Type > exceptType =
1459 new ast::PointerType{ new ast::StructInstType{ exceptionDecl } };
1460 throwStmt = ast::mutate_field(
1461 throwStmt, &ast::ThrowStmt::expr,
1462 findSingleExpression( throwStmt->expr, exceptType, symtab ) );
1463 }
1464 return throwStmt;
1465 }
1466
1467 const ast::CatchStmt * Resolver_new::previsit( const ast::CatchStmt * catchStmt ) {
1468 if ( catchStmt->cond ) {
1469 ast::ptr< ast::Type > boolType = new ast::BasicType{ ast::BasicType::Bool };
1470 catchStmt = ast::mutate_field(
1471 catchStmt, &ast::CatchStmt::cond,
1472 findSingleExpression( catchStmt->cond, boolType, symtab ) );
1473 }
1474 return catchStmt;
1475 }
1476
1477 const ast::WaitForStmt * Resolver_new::previsit( const ast::WaitForStmt * stmt ) {
1478 visit_children = false;
1479
1480 // Resolve all clauses first
1481 for ( unsigned i = 0; i < stmt->clauses.size(); ++i ) {
1482 const ast::WaitForStmt::Clause & clause = stmt->clauses[i];
1483
1484 ast::TypeEnvironment env;
1485 CandidateFinder funcFinder{ symtab, env };
1486
1487 // Find all candidates for a function in canonical form
1488 funcFinder.find( clause.target.func, ResolvMode::withAdjustment() );
1489
1490 if ( funcFinder.candidates.empty() ) {
1491 stringstream ss;
1492 ss << "Use of undeclared indentifier '";
1493 ss << clause.target.func.strict_as< ast::NameExpr >()->name;
1494 ss << "' in call to waitfor";
1495 SemanticError( stmt->location, ss.str() );
1496 }
1497
1498 if ( clause.target.args.empty() ) {
1499 SemanticError( stmt->location,
1500 "Waitfor clause must have at least one mutex parameter");
1501 }
1502
1503 // Find all alternatives for all arguments in canonical form
1504 std::vector< CandidateFinder > argFinders =
1505 funcFinder.findSubExprs( clause.target.args );
1506
1507 // List all combinations of arguments
1508 std::vector< CandidateList > possibilities;
1509 combos( argFinders.begin(), argFinders.end(), back_inserter( possibilities ) );
1510
1511 // For every possible function:
1512 // * try matching the arguments to the parameters, not the other way around because
1513 // more arguments than parameters
1514 CandidateList funcCandidates;
1515 std::vector< CandidateList > argsCandidates;
1516 SemanticErrorException errors;
1517 for ( CandidateRef & func : funcFinder.candidates ) {
1518 try {
1519 auto pointerType = dynamic_cast< const ast::PointerType * >(
1520 func->expr->result->stripReferences() );
1521 if ( ! pointerType ) {
1522 SemanticError( stmt->location, func->expr->result.get(),
1523 "candidate not viable: not a pointer type\n" );
1524 }
1525
1526 auto funcType = pointerType->base.as< ast::FunctionType >();
1527 if ( ! funcType ) {
1528 SemanticError( stmt->location, func->expr->result.get(),
1529 "candidate not viable: not a function type\n" );
1530 }
1531
1532 {
1533 auto param = funcType->params.begin();
1534 auto paramEnd = funcType->params.end();
1535
1536 if( ! nextMutex( param, paramEnd ) ) {
1537 SemanticError( stmt->location, funcType,
1538 "candidate function not viable: no mutex parameters\n");
1539 }
1540 }
1541
1542 CandidateRef func2{ new Candidate{ *func } };
1543 // strip reference from function
1544 func2->expr = referenceToRvalueConversion( func->expr, func2->cost );
1545
1546 // Each argument must be matched with a parameter of the current candidate
1547 for ( auto & argsList : possibilities ) {
1548 try {
1549 // Declare data structures needed for resolution
1550 ast::OpenVarSet open;
1551 ast::AssertionSet need, have;
1552 ast::TypeEnvironment resultEnv{ func->env };
1553 // Add all type variables as open so that those not used in the
1554 // parameter list are still considered open
1555 resultEnv.add( funcType->forall );
1556
1557 // load type variables from arguments into one shared space
1558 for ( auto & arg : argsList ) {
1559 resultEnv.simpleCombine( arg->env );
1560 }
1561
1562 // Make sure we don't widen any existing bindings
1563 resultEnv.forbidWidening();
1564
1565 // Find any unbound type variables
1566 resultEnv.extractOpenVars( open );
1567
1568 auto param = funcType->params.begin();
1569 auto paramEnd = funcType->params.end();
1570
1571 unsigned n_mutex_param = 0;
1572
1573 // For every argument of its set, check if it matches one of the
1574 // parameters. The order is important
1575 for ( auto & arg : argsList ) {
1576 // Ignore non-mutex arguments
1577 if ( ! nextMutex( param, paramEnd ) ) {
1578 // We ran out of parameters but still have arguments.
1579 // This function doesn't match
1580 SemanticError( stmt->location, funcType,
1581 toString("candidate function not viable: too many mutex "
1582 "arguments, expected ", n_mutex_param, "\n" ) );
1583 }
1584
1585 ++n_mutex_param;
1586
1587 // Check if the argument matches the parameter type in the current
1588 // scope
1589 ast::ptr< ast::Type > paramType = (*param)->get_type();
1590 if (
1591 ! unify(
1592 arg->expr->result, paramType, resultEnv, need, have, open,
1593 symtab )
1594 ) {
1595 // Type doesn't match
1596 stringstream ss;
1597 ss << "candidate function not viable: no known conversion "
1598 "from '";
1599 ast::print( ss, (*param)->get_type() );
1600 ss << "' to '";
1601 ast::print( ss, arg->expr->result );
1602 ss << "' with env '";
1603 ast::print( ss, resultEnv );
1604 ss << "'\n";
1605 SemanticError( stmt->location, funcType, ss.str() );
1606 }
1607
1608 ++param;
1609 }
1610
1611 // All arguments match!
1612
1613 // Check if parameters are missing
1614 if ( nextMutex( param, paramEnd ) ) {
1615 do {
1616 ++n_mutex_param;
1617 ++param;
1618 } while ( nextMutex( param, paramEnd ) );
1619
1620 // We ran out of arguments but still have parameters left; this
1621 // function doesn't match
1622 SemanticError( stmt->location, funcType,
1623 toString( "candidate function not viable: too few mutex "
1624 "arguments, expected ", n_mutex_param, "\n" ) );
1625 }
1626
1627 // All parameters match!
1628
1629 // Finish the expressions to tie in proper environments
1630 finishExpr( func2->expr, resultEnv );
1631 for ( CandidateRef & arg : argsList ) {
1632 finishExpr( arg->expr, resultEnv );
1633 }
1634
1635 // This is a match, store it and save it for later
1636 funcCandidates.emplace_back( std::move( func2 ) );
1637 argsCandidates.emplace_back( std::move( argsList ) );
1638
1639 } catch ( SemanticErrorException & e ) {
1640 errors.append( e );
1641 }
1642 }
1643 } catch ( SemanticErrorException & e ) {
1644 errors.append( e );
1645 }
1646 }
1647
1648 // Make sure correct number of arguments
1649 if( funcCandidates.empty() ) {
1650 SemanticErrorException top( stmt->location,
1651 "No alternatives for function in call to waitfor" );
1652 top.append( errors );
1653 throw top;
1654 }
1655
1656 if( argsCandidates.empty() ) {
1657 SemanticErrorException top( stmt->location,
1658 "No alternatives for arguments in call to waitfor" );
1659 top.append( errors );
1660 throw top;
1661 }
1662
1663 if( funcCandidates.size() > 1 ) {
1664 SemanticErrorException top( stmt->location,
1665 "Ambiguous function in call to waitfor" );
1666 top.append( errors );
1667 throw top;
1668 }
1669 if( argsCandidates.size() > 1 ) {
1670 SemanticErrorException top( stmt->location,
1671 "Ambiguous arguments in call to waitfor" );
1672 top.append( errors );
1673 throw top;
1674 }
1675 // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
1676
1677 // build new clause
1678 ast::WaitForStmt::Clause clause2;
1679
1680 clause2.target.func = funcCandidates.front()->expr;
1681
1682 clause2.target.args.reserve( clause.target.args.size() );
1683 for ( auto arg : argsCandidates.front() ) {
1684 clause2.target.args.emplace_back( std::move( arg->expr ) );
1685 }
1686
1687 // Resolve the conditions as if it were an IfStmt, statements normally
1688 clause2.cond = findSingleExpression( clause.cond, symtab );
1689 clause2.stmt = clause.stmt->accept( *visitor );
1690
1691 // set results into stmt
1692 auto n = mutate( stmt );
1693 n->clauses[i] = std::move( clause2 );
1694 stmt = n;
1695 }
1696
1697 if ( stmt->timeout.stmt ) {
1698 // resolve the timeout as a size_t, the conditions like IfStmt, and stmts normally
1699 ast::WaitForStmt::Timeout timeout2;
1700
1701 ast::ptr< ast::Type > target =
1702 new ast::BasicType{ ast::BasicType::LongLongUnsignedInt };
1703 timeout2.time = findSingleExpression( stmt->timeout.time, target, symtab );
1704 timeout2.cond = findSingleExpression( stmt->timeout.cond, symtab );
1705 timeout2.stmt = stmt->timeout.stmt->accept( *visitor );
1706
1707 // set results into stmt
1708 auto n = mutate( stmt );
1709 n->timeout = std::move( timeout2 );
1710 stmt = n;
1711 }
1712
1713 if ( stmt->orElse.stmt ) {
1714 // resolve the condition like IfStmt, stmts normally
1715 ast::WaitForStmt::OrElse orElse2;
1716
1717 orElse2.cond = findSingleExpression( stmt->orElse.cond, symtab );
1718 orElse2.stmt = stmt->orElse.stmt->accept( *visitor );
1719
1720 // set results into stmt
1721 auto n = mutate( stmt );
1722 n->orElse = std::move( orElse2 );
1723 stmt = n;
1724 }
1725
1726 return stmt;
1727 }
1728
1729
1730
1731 const ast::SingleInit * Resolver_new::previsit( const ast::SingleInit * singleInit ) {
1732 visit_children = false;
1733 // resolve initialization using the possibilities as determined by the `currentObject`
1734 // cursor.
1735 ast::ptr< ast::Expr > untyped = new ast::UntypedInitExpr{
1736 singleInit->location, singleInit->value, currentObject.getOptions() };
1737 ast::ptr<ast::Expr> newExpr = findSingleExpression( untyped, symtab );
1738 const ast::InitExpr * initExpr = newExpr.strict_as< ast::InitExpr >();
1739
1740 // move cursor to the object that is actually initialized
1741 currentObject.setNext( initExpr->designation );
1742
1743 // discard InitExpr wrapper and retain relevant pieces.
1744 // `initExpr` may have inferred params in the case where the expression specialized a
1745 // function pointer, and newExpr may already have inferParams of its own, so a simple
1746 // swap is not sufficient
1747 ast::Expr::InferUnion inferred = initExpr->inferred;
1748 swap_and_save_env( newExpr, initExpr->expr );
1749 newExpr.get_and_mutate()->inferred.splice( std::move(inferred) );
1750
1751 // get the actual object's type (may not exactly match what comes back from the resolver
1752 // due to conversions)
1753 const ast::Type * initContext = currentObject.getCurrentType();
1754
1755 removeExtraneousCast( newExpr, symtab );
1756
1757 // check if actual object's type is char[]
1758 if ( auto at = dynamic_cast< const ast::ArrayType * >( initContext ) ) {
1759 if ( isCharType( at->base ) ) {
1760 // check if the resolved type is char*
1761 if ( auto pt = newExpr->result.as< ast::PointerType >() ) {
1762 if ( isCharType( pt->base ) ) {
1763 // strip cast if we're initializing a char[] with a char*
1764 // e.g. char x[] = "hello"
1765 if ( auto ce = newExpr.as< ast::CastExpr >() ) {
1766 swap_and_save_env( newExpr, ce->arg );
1767 }
1768 }
1769 }
1770 }
1771 }
1772
1773 // move cursor to next object in preparation for next initializer
1774 currentObject.increment();
1775
1776 // set initializer expression to resolved expression
1777 return ast::mutate_field( singleInit, &ast::SingleInit::value, std::move(newExpr) );
1778 }
1779
1780 const ast::ListInit * Resolver_new::previsit( const ast::ListInit * listInit ) {
1781 // move cursor into brace-enclosed initializer-list
1782 currentObject.enterListInit( listInit->location );
1783
1784 assert( listInit->designations.size() == listInit->initializers.size() );
1785 for ( unsigned i = 0; i < listInit->designations.size(); ++i ) {
1786 // iterate designations and initializers in pairs, moving the cursor to the current
1787 // designated object and resolving the initializer against that object
1788 listInit = ast::mutate_field_index(
1789 listInit, &ast::ListInit::designations, i,
1790 currentObject.findNext( listInit->designations[i] ) );
1791 listInit = ast::mutate_field_index(
1792 listInit, &ast::ListInit::initializers, i,
1793 listInit->initializers[i]->accept( *visitor ) );
1794 }
1795
1796 // move cursor out of brace-enclosed initializer-list
1797 currentObject.exitListInit();
1798
1799 visit_children = false;
1800 return listInit;
1801 }
1802
1803 const ast::ConstructorInit * Resolver_new::previsit( const ast::ConstructorInit * ctorInit ) {
1804 visitor->maybe_accept( ctorInit, &ast::ConstructorInit::ctor );
1805 visitor->maybe_accept( ctorInit, &ast::ConstructorInit::dtor );
1806
1807 // found a constructor - can get rid of C-style initializer
1808 // xxx - Rob suggests this field is dead code
1809 ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::init, nullptr );
1810
1811 // intrinsic single-parameter constructors and destructors do nothing. Since this was
1812 // implicitly generated, there's no way for it to have side effects, so get rid of it to
1813 // clean up generated code
1814 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
1815 ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::ctor, nullptr );
1816 }
1817 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
1818 ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::dtor, nullptr );
1819 }
1820
1821 return ctorInit;
1822 }
1823
1824} // namespace ResolvExpr
1825
1826// Local Variables: //
1827// tab-width: 4 //
1828// mode: c++ //
1829// compile-command: "make install" //
1830// End: //
Note: See TracBrowser for help on using the repository browser.