source: src/ResolvExpr/Resolver.cc@ 09a1ae6

new-env with_gc
Last change on this file since 09a1ae6 was bd06384, checked in by Aaron Moss <a3moss@…>, 8 years ago

Add static roots to GC; fix some static GC_Objects

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