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

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

Assorted GC bugfixes

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