source: src/ResolvExpr/Resolver.cc@ 8d7bef2

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

First pass at delete removal

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