source: src/ResolvExpr/Resolver.cc@ bcef6c8

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since bcef6c8 was 93401f8, checked in by Peter A. Buhr <pabuhr@…>, 8 years ago

add space in error message

  • Property mode set to 100644
File size: 31.0 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//
9// Author : Richard C. Bilson
10// Created On : Sun May 17 12:17:01 2015
[93401f8]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Sat Feb 17 11:19:40 2018
13// Update Count : 213
[a32b204]14//
15
[ea6332d]16#include <stddef.h> // for NULL
[e3e16bc]17#include <cassert> // for strict_dynamic_cast, assert
[ea6332d]18#include <memory> // for allocator, allocator_traits<...
19#include <tuple> // for get
[bd4f2e9]20#include <vector>
[ea6332d]21
22#include "Alternative.h" // for Alternative, AltList
23#include "AlternativeFinder.h" // for AlternativeFinder, resolveIn...
[a4ca48c]24#include "Common/PassVisitor.h" // for PassVisitor
[ea6332d]25#include "Common/SemanticError.h" // for SemanticError
26#include "Common/utility.h" // for ValueGuard, group_iterate
27#include "CurrentObject.h" // for CurrentObject
[0a60c04]28#include "InitTweak/GenInit.h"
[ea6332d]29#include "InitTweak/InitTweak.h" // for isIntrinsicSingleArgCallStmt
30#include "RenameVars.h" // for RenameVars, global_renamer
31#include "ResolvExpr/TypeEnvironment.h" // for TypeEnvironment
32#include "ResolveTypeof.h" // for resolveTypeof
[e4d829b]33#include "Resolver.h"
[ea6332d]34#include "SymTab/Autogen.h" // for SizeType
35#include "SymTab/Indexer.h" // for Indexer
36#include "SynTree/Declaration.h" // for ObjectDecl, TypeDecl, Declar...
37#include "SynTree/Expression.h" // for Expression, CastExpr, InitExpr
38#include "SynTree/Initializer.h" // for ConstructorInit, SingleInit
39#include "SynTree/Statement.h" // for ForStmt, Statement, BranchStmt
40#include "SynTree/Type.h" // for Type, BasicType, PointerType
41#include "SynTree/TypeSubstitution.h" // for TypeSubstitution
42#include "SynTree/Visitor.h" // for acceptAll, maybeAccept
[0a60c04]43#include "Tuples/Tuples.h"
[ea6332d]44#include "typeops.h" // for extractResultType
[1dcd9554]45#include "Unify.h" // for unify
[51b73452]46
[d9a0e76]47using namespace std;
[51b73452]48
[d9a0e76]49namespace ResolvExpr {
[0a60c04]50 struct Resolver final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver>, public WithShortCircuiting, public WithStmtsToAdd {
[a4ca48c]51 Resolver() {}
52 Resolver( const SymTab::Indexer & other ) {
53 indexer = other;
[1d2b64f]54 }
[71f4e4f]55
[a4ca48c]56 void previsit( FunctionDecl *functionDecl );
57 void postvisit( FunctionDecl *functionDecl );
[3c398b6]58 void previsit( ObjectDecl *objectDecll );
[a4ca48c]59 void previsit( TypeDecl *typeDecl );
60 void previsit( EnumDecl * enumDecl );
61
62 void previsit( ArrayType * at );
63 void previsit( PointerType * at );
64
65 void previsit( ExprStmt *exprStmt );
66 void previsit( AsmExpr *asmExpr );
67 void previsit( AsmStmt *asmStmt );
68 void previsit( IfStmt *ifStmt );
69 void previsit( WhileStmt *whileStmt );
70 void previsit( ForStmt *forStmt );
71 void previsit( SwitchStmt *switchStmt );
72 void previsit( CaseStmt *caseStmt );
73 void previsit( BranchStmt *branchStmt );
74 void previsit( ReturnStmt *returnStmt );
75 void previsit( ThrowStmt *throwStmt );
76 void previsit( CatchStmt *catchStmt );
[695e00d]77 void previsit( WaitForStmt * stmt );
[882ad37]78 void previsit( WithStmt * withStmt );
[a4ca48c]79
80 void previsit( SingleInit *singleInit );
81 void previsit( ListInit *listInit );
82 void previsit( ConstructorInit *ctorInit );
[a32b204]83 private:
[c28a038d]84 typedef std::list< Initializer * >::iterator InitIterator;
[94b4364]85
[40e636a]86 template< typename PtrType >
87 void handlePtrType( PtrType * type );
88
[c28a038d]89 void resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts );
90 void fallbackInit( ConstructorInit * ctorInit );
[b726084]91
[77971f6]92 Type * functionReturn = nullptr;
[e4d829b]93 CurrentObject currentObject = nullptr;
[a436947]94 bool inEnumDecl = false;
[a32b204]95 };
[d9a0e76]96
[a32b204]97 void resolve( std::list< Declaration * > translationUnit ) {
[a4ca48c]98 PassVisitor<Resolver> resolver;
[a32b204]99 acceptAll( translationUnit, resolver );
[d9a0e76]100 }
101
[8b11840]102 void resolveDecl( Declaration * decl, const SymTab::Indexer &indexer ) {
103 PassVisitor<Resolver> resolver( indexer );
104 maybeAccept( decl, resolver );
105 }
106
[c71b256]107 namespace {
108 struct DeleteFinder : public WithShortCircuiting {
109 DeletedExpr * delExpr = nullptr;
110 void previsit( DeletedExpr * expr ) {
111 if ( delExpr ) visit_children = false;
112 else delExpr = expr;
113 }
114
115 void previsit( Expression * ) {
116 if ( delExpr ) visit_children = false;
117 }
118 };
119 }
120
121 DeletedExpr * findDeletedExpr( Expression * expr ) {
122 PassVisitor<DeleteFinder> finder;
123 expr->accept( finder );
124 return finder.pass.delExpr;
[d9a0e76]125 }
[a32b204]126
127 namespace {
[7664fad]128 void finishExpr( Expression *expr, const TypeEnvironment &env, TypeSubstitution * oldenv = nullptr ) {
129 expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
[a32b204]130 env.makeSubstitution( *expr->get_env() );
131 }
[0a22cda]132
133 void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) {
134 if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
135 if ( ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) {
136 // cast is to the same type as its argument, so it's unnecessary -- remove it
137 expr = castExpr->arg;
138 castExpr->arg = nullptr;
139 std::swap( expr->env, castExpr->env );
140 delete castExpr;
141 }
142 }
143 }
[db4ecc5]144 } // namespace
[a32b204]145
[8f98b78]146 namespace {
[c71b256]147 void findUnfinishedKindExpression(Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, bool adjust = false, bool prune = true, bool failFast = true) {
148 assertf( untyped, "expected a non-null expression." );
[8587878e]149 TypeEnvironment env;
150 AlternativeFinder finder( indexer, env );
[c71b256]151 finder.find( untyped, adjust, prune, failFast );
152
153 #if 0
154 if ( finder.get_alternatives().size() != 1 ) {
155 std::cerr << "untyped expr is ";
156 untyped->print( std::cerr );
157 std::cerr << std::endl << "alternatives are:";
158 for ( const Alternative & alt : finder.get_alternatives() ) {
159 alt.print( std::cerr );
160 } // for
161 } // if
162 #endif
[8587878e]163
164 AltList candidates;
165 for ( Alternative & alt : finder.get_alternatives() ) {
[c71b256]166 if ( pred( alt ) ) {
[8587878e]167 candidates.push_back( std::move( alt ) );
168 }
169 }
170
[c71b256]171 // xxx - if > 1 alternative with same cost, ignore deleted and pick from remaining
[8587878e]172 // choose the lowest cost expression among the candidates
173 AltList winners;
174 findMinCost( candidates.begin(), candidates.end(), back_inserter( winners ) );
175 if ( winners.size() == 0 ) {
[7c782af]176 throw SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") );
[8587878e]177 } else if ( winners.size() != 1 ) {
178 std::ostringstream stream;
[c71b256]179 stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n";
[8587878e]180 untyped->print( stream );
[93401f8]181 stream << " Alternatives are:\n";
[8587878e]182 printAlts( winners, stream, 1 );
[d55d7a6]183 throw SemanticError( untyped->location, stream.str() );
[8587878e]184 }
185
186 // there is one unambiguous interpretation - move the expression into the with statement
[c71b256]187 Alternative & choice = winners.front();
188 if ( findDeletedExpr( choice.expr ) ) {
[7c782af]189 throw SemanticError( choice.expr, "Unique best alternative includes deleted identifier in " );
[c71b256]190 }
191 alt = std::move( choice );
192 }
193
194 /// resolve `untyped` to the expression whose alternative satisfies `pred` with the lowest cost; kindStr is used for providing better error messages
195 void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, bool adjust = false, bool prune = true, bool failFast = true) {
196 if ( ! untyped ) return;
197 Alternative choice;
198 findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, adjust, prune, failFast );
199 finishExpr( choice.expr, choice.env, untyped->env );
[8587878e]200 delete untyped;
[c71b256]201 untyped = choice.expr;
202 choice.expr = nullptr;
[8587878e]203 }
204
[c71b256]205 bool standardAlternativeFilter( const Alternative & ) {
206 // currently don't need to filter, under normal circumstances.
207 // in the future, this may be useful for removing deleted expressions
208 return true;
209 }
210 } // namespace
211
212 // used in resolveTypeof
213 Expression * resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer ) {
214 TypeEnvironment env;
215 return resolveInVoidContext( expr, indexer, env );
216 }
217
218 Expression * resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer, TypeEnvironment &env ) {
219 // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
220 // interpretations, an exception has already been thrown.
221 assertf( expr, "expected a non-null expression." );
222
223 static CastExpr untyped( nullptr ); // cast to void
224
225 // set up and resolve expression cast to void
226 untyped.arg = expr;
227 Alternative choice;
228 findUnfinishedKindExpression( &untyped, choice, indexer, "", standardAlternativeFilter, true );
229 CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr );
230 env = std::move( choice.env );
231
232 // clean up resolved expression
233 Expression * ret = castExpr->arg;
234 castExpr->arg = nullptr;
235
236 // unlink the arg so that it isn't deleted twice at the end of the program
237 untyped.arg = nullptr;
238 return ret;
239 }
240
241 void findVoidExpression( Expression *& untyped, const SymTab::Indexer &indexer ) {
242 resetTyVarRenaming();
243 TypeEnvironment env;
244 Expression * newExpr = resolveInVoidContext( untyped, indexer, env );
245 finishExpr( newExpr, env, untyped->env );
246 delete untyped;
247 untyped = newExpr;
248 }
249
250 void findSingleExpression( Expression *&untyped, const SymTab::Indexer &indexer ) {
251 findKindExpression( untyped, indexer, "", standardAlternativeFilter );
252 }
253
254 void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) {
255 assert( untyped && type );
256 untyped = new CastExpr( untyped, type );
257 findSingleExpression( untyped, indexer );
258 removeExtraneousCast( untyped, indexer );
259 }
260
261 namespace {
262 bool isIntegralType( const Alternative & alt ) {
263 Type * type = alt.expr->result;
[a32b204]264 if ( dynamic_cast< EnumInstType * >( type ) ) {
265 return true;
266 } else if ( BasicType *bt = dynamic_cast< BasicType * >( type ) ) {
267 return bt->isInteger();
[89e6ffc]268 } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
269 return true;
[a32b204]270 } else {
271 return false;
272 } // if
273 }
[71f4e4f]274
[08da53d]275 void findIntegralExpression( Expression *& untyped, const SymTab::Indexer &indexer ) {
[8587878e]276 findKindExpression( untyped, indexer, "condition", isIntegralType );
[a32b204]277 }
278 }
[71f4e4f]279
[a4ca48c]280 void Resolver::previsit( ObjectDecl *objectDecl ) {
281 Type *new_type = resolveTypeof( objectDecl->get_type(), indexer );
[a32b204]282 objectDecl->set_type( new_type );
[3cfe27f]283 // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that class-variable
284 // initContext is changed multiple time because the LHS is analysed twice. The second analysis changes
285 // initContext because of a function type can contain object declarations in the return and parameter types. So
286 // each value of initContext is retained, so the type on the first analysis is preserved and used for selecting
287 // the RHS.
[a4ca48c]288 GuardValue( currentObject );
[e4d829b]289 currentObject = CurrentObject( objectDecl->get_type() );
290 if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
[a436947]291 // enumerator initializers should not use the enum type to initialize, since
292 // the enum type is still incomplete at this point. Use signed int instead.
[e4d829b]293 currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
[a436947]294 }
[bfbf97f]295 }
296
[40e636a]297 template< typename PtrType >
298 void Resolver::handlePtrType( PtrType * type ) {
299 if ( type->get_dimension() ) {
[08da53d]300 findSingleExpression( type->dimension, SymTab::SizeType->clone(), indexer );
[d1d17f5]301 }
[40e636a]302 }
303
[a4ca48c]304 void Resolver::previsit( ArrayType * at ) {
[40e636a]305 handlePtrType( at );
[a32b204]306 }
[94b4364]307
[a4ca48c]308 void Resolver::previsit( PointerType * pt ) {
[40e636a]309 handlePtrType( pt );
310 }
311
[a4ca48c]312 void Resolver::previsit( TypeDecl *typeDecl ) {
[a32b204]313 if ( typeDecl->get_base() ) {
[a4ca48c]314 Type *new_type = resolveTypeof( typeDecl->get_base(), indexer );
[a32b204]315 typeDecl->set_base( new_type );
316 } // if
317 }
[94b4364]318
[a4ca48c]319 void Resolver::previsit( FunctionDecl *functionDecl ) {
[d9a0e76]320#if 0
[a4ca48c]321 std::cerr << "resolver visiting functiondecl ";
322 functionDecl->print( std::cerr );
323 std::cerr << std::endl;
[d9a0e76]324#endif
[c28a038d]325 Type *new_type = resolveTypeof( functionDecl->type, indexer );
[a32b204]326 functionDecl->set_type( new_type );
[a4ca48c]327 GuardValue( functionReturn );
[60914351]328 functionReturn = ResolvExpr::extractResultType( functionDecl->type );
329
330 {
331 // resolve with-exprs with parameters in scope and add any newly generated declarations to the
332 // front of the function body.
333 auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } );
334 indexer.addFunctionType( functionDecl->type );
335 std::list< Statement * > newStmts;
336 resolveWithExprs( functionDecl->withExprs, newStmts );
[a33fdbe]337 if ( functionDecl->statements ) {
338 functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts );
339 } else {
340 assertf( functionDecl->withExprs.empty() && newStmts.empty(), "Function %s without a body has with-clause and/or generated with declarations.", functionDecl->name.c_str() );
341 }
[60914351]342 }
[a4ca48c]343 }
[88d1066]344
[a4ca48c]345 void Resolver::postvisit( FunctionDecl *functionDecl ) {
[88d1066]346 // default value expressions have an environment which shouldn't be there and trips up later passes.
347 // xxx - it might be necessary to somehow keep the information from this environment, but I can't currently
348 // see how it's useful.
[c28a038d]349 for ( Declaration * d : functionDecl->type->parameters ) {
[88d1066]350 if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
[c28a038d]351 if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
352 delete init->value->env;
353 init->value->env = nullptr;
[88d1066]354 }
355 }
356 }
[a32b204]357 }
[51b73452]358
[a4ca48c]359 void Resolver::previsit( EnumDecl * ) {
[a436947]360 // in case we decide to allow nested enums
[a4ca48c]361 GuardValue( inEnumDecl );
[a436947]362 inEnumDecl = true;
363 }
364
[a4ca48c]365 void Resolver::previsit( ExprStmt *exprStmt ) {
366 visit_children = false;
[08da53d]367 assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
368 findVoidExpression( exprStmt->expr, indexer );
[a32b204]369 }
[51b73452]370
[a4ca48c]371 void Resolver::previsit( AsmExpr *asmExpr ) {
372 visit_children = false;
[08da53d]373 findVoidExpression( asmExpr->operand, indexer );
[7f5566b]374 if ( asmExpr->get_inout() ) {
[08da53d]375 findVoidExpression( asmExpr->inout, indexer );
[7f5566b]376 } // if
377 }
378
[a4ca48c]379 void Resolver::previsit( AsmStmt *asmStmt ) {
380 visit_children = false;
381 acceptAll( asmStmt->get_input(), *visitor );
382 acceptAll( asmStmt->get_output(), *visitor );
[7f5566b]383 }
384
[a4ca48c]385 void Resolver::previsit( IfStmt *ifStmt ) {
[8587878e]386 findIntegralExpression( ifStmt->condition, indexer );
[a32b204]387 }
[51b73452]388
[a4ca48c]389 void Resolver::previsit( WhileStmt *whileStmt ) {
[8587878e]390 findIntegralExpression( whileStmt->condition, indexer );
[a32b204]391 }
[51b73452]392
[a4ca48c]393 void Resolver::previsit( ForStmt *forStmt ) {
[08da53d]394 if ( forStmt->condition ) {
[8587878e]395 findIntegralExpression( forStmt->condition, indexer );
[a32b204]396 } // if
[71f4e4f]397
[08da53d]398 if ( forStmt->increment ) {
399 findVoidExpression( forStmt->increment, indexer );
[a32b204]400 } // if
401 }
[51b73452]402
[a4ca48c]403 void Resolver::previsit( SwitchStmt *switchStmt ) {
404 GuardValue( currentObject );
[08da53d]405 findIntegralExpression( switchStmt->condition, indexer );
[71f4e4f]406
[08da53d]407 currentObject = CurrentObject( switchStmt->condition->result );
[a32b204]408 }
[51b73452]409
[a4ca48c]410 void Resolver::previsit( CaseStmt *caseStmt ) {
[32b8144]411 if ( caseStmt->get_condition() ) {
[e4d829b]412 std::list< InitAlternative > initAlts = currentObject.getOptions();
413 assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
[08da53d]414 // must remove cast from case statement because RangeExpr cannot be cast.
415 Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() );
416 findSingleExpression( newExpr, indexer );
417 CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( newExpr );
418 caseStmt->condition = castExpr->arg;
419 castExpr->arg = nullptr;
[32b8144]420 delete castExpr;
421 }
[a32b204]422 }
[51b73452]423
[a4ca48c]424 void Resolver::previsit( BranchStmt *branchStmt ) {
425 visit_children = false;
[de62360d]426 // must resolve the argument for a computed goto
427 if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
[08da53d]428 if ( branchStmt->computedTarget ) {
429 // computed goto argument is void *
430 findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
[de62360d]431 } // if
432 } // if
433 }
434
[a4ca48c]435 void Resolver::previsit( ReturnStmt *returnStmt ) {
436 visit_children = false;
[08da53d]437 if ( returnStmt->expr ) {
438 findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
[a32b204]439 } // if
440 }
[51b73452]441
[a4ca48c]442 void Resolver::previsit( ThrowStmt *throwStmt ) {
443 visit_children = false;
[cbce272]444 // TODO: Replace *exception type with &exception type.
[307a732]445 if ( throwStmt->get_expr() ) {
[cbce272]446 StructDecl * exception_decl =
[36982fc]447 indexer.lookupStruct( "__cfaabi_ehm__base_exception_t" );
[cbce272]448 assert( exception_decl );
[08da53d]449 Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, exception_decl ) );
450 findSingleExpression( throwStmt->expr, exceptType, indexer );
[307a732]451 }
452 }
453
[a4ca48c]454 void Resolver::previsit( CatchStmt *catchStmt ) {
[08da53d]455 if ( catchStmt->cond ) {
456 findSingleExpression( catchStmt->cond, new BasicType( noQualifiers, BasicType::Bool ), indexer );
[cbce272]457 }
458 }
459
[1dcd9554]460 template< typename iterator_t >
461 inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
462 while( it != end && !(*it)->get_type()->get_mutex() ) {
463 it++;
464 }
465
466 return it != end;
467 }
468
[695e00d]469 void Resolver::previsit( WaitForStmt * stmt ) {
[8f98b78]470 visit_children = false;
[1dcd9554]471
472 // Resolve all clauses first
473 for( auto& clause : stmt->clauses ) {
474
475 TypeEnvironment env;
[8f98b78]476 AlternativeFinder funcFinder( indexer, env );
[1dcd9554]477
478 // Find all alternatives for a function in canonical form
479 funcFinder.findWithAdjustment( clause.target.function );
480
481 if ( funcFinder.get_alternatives().empty() ) {
482 stringstream ss;
483 ss << "Use of undeclared indentifier '";
484 ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
485 ss << "' in call to waitfor";
[d55d7a6]486 throw SemanticError( stmt->location, ss.str() );
[1dcd9554]487 }
488
489 // Find all alternatives for all arguments in canonical form
[bd4f2e9]490 std::vector< AlternativeFinder > argAlternatives;
[1dcd9554]491 funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
492
493 // List all combinations of arguments
[bd4f2e9]494 std::vector< AltList > possibilities;
[1dcd9554]495 combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
496
497 AltList func_candidates;
498 std::vector< AltList > args_candidates;
499
500 // For every possible function :
501 // try matching the arguments to the parameters
502 // not the other way around because we have more arguments than parameters
503 SemanticError errors;
504 for ( Alternative & func : funcFinder.get_alternatives() ) {
505 try {
506 PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
507 if( !pointer ) {
[d55d7a6]508 throw SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" );
[1dcd9554]509 }
510
511 FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
512 if( !function ) {
[d55d7a6]513 throw SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" );
[1dcd9554]514 }
515
516
517 {
518 auto param = function->parameters.begin();
519 auto param_end = function->parameters.end();
520
521 if( !advance_to_mutex( param, param_end ) ) {
[d55d7a6]522 throw SemanticError(function, "candidate function not viable: no mutex parameters\n");
[1dcd9554]523 }
524 }
525
526 Alternative newFunc( func );
527 // Strip reference from function
528 referenceToRvalueConversion( newFunc.expr );
529
530 // For all the set of arguments we have try to match it with the parameter of the current function alternative
531 for ( auto & argsList : possibilities ) {
532
533 try {
534 // Declare data structures need for resolution
535 OpenVarSet openVars;
536 AssertionSet resultNeed, resultHave;
537 TypeEnvironment resultEnv;
538
539 // Load type variables from arguemnts into one shared space
540 simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );
541
542 // Make sure we don't widen any existing bindings
543 for ( auto & i : resultEnv ) {
544 i.allowWidening = false;
545 }
546
547 // Find any unbound type variables
548 resultEnv.extractOpenVars( openVars );
549
550 auto param = function->parameters.begin();
551 auto param_end = function->parameters.end();
552
553 // For every arguments of its set, check if it matches one of the parameter
554 // The order is important
555 for( auto & arg : argsList ) {
556
557 // Ignore non-mutex arguments
558 if( !advance_to_mutex( param, param_end ) ) {
559 // We ran out of parameters but still have arguments
560 // this function doesn't match
[d55d7a6]561 throw SemanticError( function, "candidate function not viable: too many mutex arguments\n" );
[1dcd9554]562 }
563
564 // Check if the argument matches the parameter type in the current scope
[8f98b78]565 if( ! unify( (*param)->get_type(), arg.expr->get_result(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
[1dcd9554]566 // Type doesn't match
567 stringstream ss;
568 ss << "candidate function not viable: no known convertion from '";
569 arg.expr->get_result()->print( ss );
570 ss << "' to '";
571 (*param)->get_type()->print( ss );
572 ss << "'\n";
[d55d7a6]573 throw SemanticError( function, ss.str() );
[1dcd9554]574 }
575
576 param++;
577 }
578
579 // All arguments match !
580
581 // Check if parameters are missing
582 if( advance_to_mutex( param, param_end ) ) {
583 // We ran out of arguments but still have parameters left
584 // this function doesn't match
[d55d7a6]585 throw SemanticError( function, "candidate function not viable: too few mutex arguments\n" );
[1dcd9554]586 }
587
588 // All parameters match !
589
590 // Finish the expressions to tie in the proper environments
591 finishExpr( newFunc.expr, resultEnv );
592 for( Alternative & alt : argsList ) {
593 finishExpr( alt.expr, resultEnv );
594 }
595
596 // This is a match store it and save it for later
597 func_candidates.push_back( newFunc );
598 args_candidates.push_back( argsList );
599
600 }
601 catch( SemanticError &e ) {
602 errors.append( e );
603 }
604 }
605 }
606 catch( SemanticError &e ) {
607 errors.append( e );
608 }
609 }
610
611 // Make sure we got the right number of arguments
[d55d7a6]612 if( func_candidates.empty() ) { SemanticError top( stmt->location, "No alternatives for function in call to waitfor" ); top.append( errors ); throw top; }
613 if( args_candidates.empty() ) { SemanticError top( stmt->location, "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
614 if( func_candidates.size() > 1 ) { SemanticError top( stmt->location, "Ambiguous function in call to waitfor" ); top.append( errors ); throw top; }
615 if( args_candidates.size() > 1 ) { SemanticError top( stmt->location, "Ambiguous arguments in call to waitfor" ); top.append( errors ); throw top; }
[c71b256]616 // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
[1dcd9554]617
618 // Swap the results from the alternative with the unresolved values.
619 // Alternatives will handle deletion on destruction
620 std::swap( clause.target.function, func_candidates.front().expr );
621 for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
622 std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
623 }
624
625 // Resolve the conditions as if it were an IfStmt
626 // Resolve the statments normally
[08da53d]627 findSingleExpression( clause.condition, this->indexer );
[8f98b78]628 clause.statement->accept( *visitor );
[1dcd9554]629 }
630
631
632 if( stmt->timeout.statement ) {
633 // Resolve the timeout as an size_t for now
634 // Resolve the conditions as if it were an IfStmt
635 // Resolve the statments normally
[08da53d]636 findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
637 findSingleExpression( stmt->timeout.condition, this->indexer );
[8f98b78]638 stmt->timeout.statement->accept( *visitor );
[1dcd9554]639 }
640
641 if( stmt->orelse.statement ) {
642 // Resolve the conditions as if it were an IfStmt
643 // Resolve the statments normally
[08da53d]644 findSingleExpression( stmt->orelse.condition, this->indexer );
[8f98b78]645 stmt->orelse.statement->accept( *visitor );
[1dcd9554]646 }
647 }
648
[c71b256]649 bool isStructOrUnion( const Alternative & alt ) {
650 Type * t = alt.expr->result->stripReferences();
[882ad37]651 return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t );
652 }
653
[c28a038d]654 void Resolver::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) {
655 for ( Expression *& expr : withExprs ) {
[882ad37]656 // only struct- and union-typed expressions are viable candidates
[8587878e]657 findKindExpression( expr, indexer, "with statement", isStructOrUnion );
[0a60c04]658
659 // if with expression might be impure, create a temporary so that it is evaluated once
660 if ( Tuples::maybeImpure( expr ) ) {
661 static UniqueName tmpNamer( "_with_tmp_" );
662 ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) );
663 expr = new VariableExpr( tmp );
[c28a038d]664 newStmts.push_back( new DeclStmt( tmp ) );
[0a60c04]665 if ( InitTweak::isConstructable( tmp->type ) ) {
666 // generate ctor/dtor and resolve them
667 tmp->init = InitTweak::genCtorInit( tmp );
668 tmp->accept( *visitor );
669 }
670 }
[882ad37]671 }
672 }
673
[c28a038d]674 void Resolver::previsit( WithStmt * withStmt ) {
675 resolveWithExprs( withStmt->exprs, stmtsToAddBefore );
676 }
677
[b5c5684]678 template< typename T >
679 bool isCharType( T t ) {
680 if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
[71f4e4f]681 return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
[b5c5684]682 bt->get_kind() == BasicType::UnsignedChar;
683 }
684 return false;
685 }
686
[a4ca48c]687 void Resolver::previsit( SingleInit *singleInit ) {
688 visit_children = false;
[62423350]689 // resolve initialization using the possibilities as determined by the currentObject cursor
[0a22cda]690 Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
[08da53d]691 findSingleExpression( newExpr, indexer );
[e3e16bc]692 InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
[62423350]693
694 // move cursor to the object that is actually initialized
[e4d829b]695 currentObject.setNext( initExpr->get_designation() );
[62423350]696
697 // discard InitExpr wrapper and retain relevant pieces
[08da53d]698 newExpr = initExpr->expr;
699 initExpr->expr = nullptr;
700 std::swap( initExpr->env, newExpr->env );
[bb666f64]701 std::swap( initExpr->inferParams, newExpr->inferParams ) ;
[e4d829b]702 delete initExpr;
703
[62423350]704 // get the actual object's type (may not exactly match what comes back from the resolver due to conversions)
705 Type * initContext = currentObject.getCurrentType();
706
[0a22cda]707 removeExtraneousCast( newExpr, indexer );
708
[62423350]709 // check if actual object's type is char[]
710 if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
711 if ( isCharType( at->get_base() ) ) {
712 // check if the resolved type is char *
713 if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
714 if ( isCharType( pt->get_base() ) ) {
[0a22cda]715 if ( CastExpr *ce = dynamic_cast< CastExpr * >( newExpr ) ) {
716 // strip cast if we're initializing a char[] with a char *, e.g. char x[] = "hello";
717 newExpr = ce->get_arg();
718 ce->set_arg( nullptr );
719 std::swap( ce->env, newExpr->env );
720 delete ce;
721 }
[62423350]722 }
723 }
724 }
725 }
[94b4364]726
[62423350]727 // set initializer expr to resolved express
[0a22cda]728 singleInit->value = newExpr;
[62423350]729
730 // move cursor to next object in preparation for next initializer
731 currentObject.increment();
732 }
[94b4364]733
[a4ca48c]734 void Resolver::previsit( ListInit * listInit ) {
735 visit_children = false;
[62423350]736 // move cursor into brace-enclosed initializer-list
[e4d829b]737 currentObject.enterListInit();
738 // xxx - fix this so that the list isn't copied, iterator should be used to change current element
739 std::list<Designation *> newDesignations;
740 for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
[62423350]741 // iterate designations and initializers in pairs, moving the cursor to the current designated object and resolving
742 // the initializer against that object.
[e4d829b]743 Designation * des = std::get<0>(p);
744 Initializer * init = std::get<1>(p);
745 newDesignations.push_back( currentObject.findNext( des ) );
[a4ca48c]746 init->accept( *visitor );
[b5c5684]747 }
[62423350]748 // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
[e4d829b]749 listInit->get_designations() = newDesignations; // xxx - memory management
750 currentObject.exitListInit();
751
[62423350]752 // xxx - this part has not be folded into CurrentObject yet
[e4d829b]753 // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
754 // Type * base = tt->get_baseType()->get_base();
755 // if ( base ) {
756 // // know the implementation type, so try using that as the initContext
757 // ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
758 // currentObject = &tmpObj;
759 // visit( listInit );
760 // } else {
761 // // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
762 // Parent::visit( listInit );
763 // }
764 // } else {
[a32b204]765 }
[71f4e4f]766
[f1e012b]767 // ConstructorInit - fall back on C-style initializer
768 void Resolver::fallbackInit( ConstructorInit * ctorInit ) {
769 // could not find valid constructor, or found an intrinsic constructor
770 // fall back on C-style initializer
771 delete ctorInit->get_ctor();
772 ctorInit->set_ctor( NULL );
[71a145de]773 delete ctorInit->get_dtor();
774 ctorInit->set_dtor( NULL );
[a4ca48c]775 maybeAccept( ctorInit->get_init(), *visitor );
[f1e012b]776 }
777
[1d2b64f]778 // needs to be callable from outside the resolver, so this is a standalone function
779 void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
780 assert( ctorInit );
[a4ca48c]781 PassVisitor<Resolver> resolver( indexer );
[1d2b64f]782 ctorInit->accept( resolver );
783 }
784
785 void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
786 assert( stmtExpr );
[a4ca48c]787 PassVisitor<Resolver> resolver( indexer );
[1d2b64f]788 stmtExpr->accept( resolver );
[5e2c348]789 stmtExpr->computeResult();
[1d2b64f]790 }
791
[a4ca48c]792 void Resolver::previsit( ConstructorInit *ctorInit ) {
793 visit_children = false;
[1ba88a0]794 // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
[a4ca48c]795 maybeAccept( ctorInit->get_ctor(), *visitor );
796 maybeAccept( ctorInit->get_dtor(), *visitor );
[071a31a]797
[5b2f5bb]798 // found a constructor - can get rid of C-style initializer
799 delete ctorInit->get_init();
800 ctorInit->set_init( NULL );
[ec79847]801
802 // intrinsic single parameter constructors and destructors do nothing. Since this was
803 // implicitly generated, there's no way for it to have side effects, so get rid of it
804 // to clean up generated code.
[f9cebb5]805 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_ctor() ) ) {
[ec79847]806 delete ctorInit->get_ctor();
807 ctorInit->set_ctor( NULL );
808 }
[f9cebb5]809
810 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_dtor() ) ) {
[ec79847]811 delete ctorInit->get_dtor();
812 ctorInit->set_dtor( NULL );
813 }
[a465caff]814
815 // xxx - todo -- what about arrays?
816 // if ( dtor == NULL && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
817 // // can reduce the constructor down to a SingleInit using the
818 // // second argument from the ctor call, since
819 // delete ctorInit->get_ctor();
820 // ctorInit->set_ctor( NULL );
821
822 // Expression * arg =
823 // ctorInit->set_init( new SingleInit( arg ) );
824 // }
[71f4e4f]825 }
[51b73452]826} // namespace ResolvExpr
[a32b204]827
828// Local Variables: //
829// tab-width: 4 //
830// mode: c++ //
831// compile-command: "make install" //
832// End: //
Note: See TracBrowser for help on using the repository browser.