source: src/ResolvExpr/Resolver.cc@ c960331

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since c960331 was 490fb92e, checked in by Fangren Yu <f37yu@…>, 5 years ago

move FixInit to new ast

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