source: src/ResolvExpr/Resolver.cc@ eff03a94

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

Merge remote-tracking branch 'origin/with_gc' into new-env

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