source: src/ResolvExpr/Resolver.cc@ 2b79a70

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr no_list persistent-indexer pthread-emulation qualifiedEnum
Last change on this file since 2b79a70 was 2b79a70, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Resolve typeof earlier so that constructors are chosen appropriately [fixes #102]

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