source: src/ResolvExpr/Resolver.cc@ ce7ed2c

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

Introduce a temporary for with expressions that may contain side-effects and evaluate the expression once

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