source: src/ResolvExpr/Resolver.cc@ b60f9d9

new-env
Last change on this file since b60f9d9 was b60f9d9, checked in by Aaron Moss <a3moss@…>, 7 years ago

Start on breadth-first assertion resolution

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