source: src/ResolvExpr/AlternativeFinder.cc@ dc86541

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 dc86541 was 77971f6, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

resolve ctor/dtors for UniqueExprs

  • Property mode set to 100644
File size: 45.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// AlternativeFinder.cc --
8//
9// Author : Richard C. Bilson
10// Created On : Sat May 16 23:52:08 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Mon Jul 4 17:02:51 2016
13// Update Count : 29
14//
15
16#include <list>
17#include <iterator>
18#include <algorithm>
19#include <functional>
20#include <cassert>
21#include <unordered_map>
22#include <utility>
23#include <vector>
24
25#include "AlternativeFinder.h"
26#include "Alternative.h"
27#include "Cost.h"
28#include "typeops.h"
29#include "Unify.h"
30#include "RenameVars.h"
31#include "SynTree/Type.h"
32#include "SynTree/Declaration.h"
33#include "SynTree/Expression.h"
34#include "SynTree/Initializer.h"
35#include "SynTree/Visitor.h"
36#include "SymTab/Indexer.h"
37#include "SymTab/Mangler.h"
38#include "SynTree/TypeSubstitution.h"
39#include "SymTab/Validate.h"
40#include "Tuples/Tuples.h"
41#include "Common/utility.h"
42#include "InitTweak/InitTweak.h"
43#include "InitTweak/GenInit.h"
44#include "ResolveTypeof.h"
45
46extern bool resolvep;
47#define PRINT( text ) if ( resolvep ) { text }
48//#define DEBUG_COST
49
50namespace ResolvExpr {
51 Expression *resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer, TypeEnvironment &env ) {
52 CastExpr *castToVoid = new CastExpr( expr );
53
54 AlternativeFinder finder( indexer, env );
55 finder.findWithAdjustment( castToVoid );
56
57 // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
58 // interpretations, an exception has already been thrown.
59 assert( finder.get_alternatives().size() == 1 );
60 CastExpr *newExpr = dynamic_cast< CastExpr* >( finder.get_alternatives().front().expr );
61 assert( newExpr );
62 env = finder.get_alternatives().front().env;
63 return newExpr->get_arg()->clone();
64 }
65
66 Cost sumCost( const AltList &in ) {
67 Cost total;
68 for ( AltList::const_iterator i = in.begin(); i != in.end(); ++i ) {
69 total += i->cost;
70 }
71 return total;
72 }
73
74 namespace {
75 void printAlts( const AltList &list, std::ostream &os, int indent = 0 ) {
76 for ( AltList::const_iterator i = list.begin(); i != list.end(); ++i ) {
77 i->print( os, indent );
78 os << std::endl;
79 }
80 }
81
82 void makeExprList( const AltList &in, std::list< Expression* > &out ) {
83 for ( AltList::const_iterator i = in.begin(); i != in.end(); ++i ) {
84 out.push_back( i->expr->clone() );
85 }
86 }
87
88 struct PruneStruct {
89 bool isAmbiguous;
90 AltList::iterator candidate;
91 PruneStruct() {}
92 PruneStruct( AltList::iterator candidate ): isAmbiguous( false ), candidate( candidate ) {}
93 };
94
95 /// Prunes a list of alternatives down to those that have the minimum conversion cost for a given return type; skips ambiguous interpretations
96 template< typename InputIterator, typename OutputIterator >
97 void pruneAlternatives( InputIterator begin, InputIterator end, OutputIterator out, const SymTab::Indexer &indexer ) {
98 // select the alternatives that have the minimum conversion cost for a particular set of result types
99 std::map< std::string, PruneStruct > selected;
100 for ( AltList::iterator candidate = begin; candidate != end; ++candidate ) {
101 PruneStruct current( candidate );
102 std::string mangleName;
103 {
104 Type * newType = candidate->expr->get_result()->clone();
105 candidate->env.apply( newType );
106 mangleName = SymTab::Mangler::mangle( newType );
107 delete newType;
108 }
109 std::map< std::string, PruneStruct >::iterator mapPlace = selected.find( mangleName );
110 if ( mapPlace != selected.end() ) {
111 if ( candidate->cost < mapPlace->second.candidate->cost ) {
112 PRINT(
113 std::cerr << "cost " << candidate->cost << " beats " << mapPlace->second.candidate->cost << std::endl;
114 )
115 selected[ mangleName ] = current;
116 } else if ( candidate->cost == mapPlace->second.candidate->cost ) {
117 PRINT(
118 std::cerr << "marking ambiguous" << std::endl;
119 )
120 mapPlace->second.isAmbiguous = true;
121 }
122 } else {
123 selected[ mangleName ] = current;
124 }
125 }
126
127 PRINT(
128 std::cerr << "there are " << selected.size() << " alternatives before elimination" << std::endl;
129 )
130
131 // accept the alternatives that were unambiguous
132 for ( std::map< std::string, PruneStruct >::iterator target = selected.begin(); target != selected.end(); ++target ) {
133 if ( ! target->second.isAmbiguous ) {
134 Alternative &alt = *target->second.candidate;
135 alt.env.applyFree( alt.expr->get_result() );
136 *out++ = alt;
137 }
138 }
139 }
140
141 void renameTypes( Expression *expr ) {
142 expr->get_result()->accept( global_renamer );
143 }
144 }
145
146 template< typename InputIterator, typename OutputIterator >
147 void AlternativeFinder::findSubExprs( InputIterator begin, InputIterator end, OutputIterator out ) {
148 while ( begin != end ) {
149 AlternativeFinder finder( indexer, env );
150 finder.findWithAdjustment( *begin );
151 // XXX either this
152 //Designators::fixDesignations( finder, (*begin++)->get_argName() );
153 // or XXX this
154 begin++;
155 PRINT(
156 std::cerr << "findSubExprs" << std::endl;
157 printAlts( finder.alternatives, std::cerr );
158 )
159 *out++ = finder;
160 }
161 }
162
163 AlternativeFinder::AlternativeFinder( const SymTab::Indexer &indexer, const TypeEnvironment &env )
164 : indexer( indexer ), env( env ) {
165 }
166
167 void AlternativeFinder::find( Expression *expr, bool adjust, bool prune ) {
168 expr->accept( *this );
169 if ( alternatives.empty() ) {
170 throw SemanticError( "No reasonable alternatives for expression ", expr );
171 }
172 for ( AltList::iterator i = alternatives.begin(); i != alternatives.end(); ++i ) {
173 if ( adjust ) {
174 adjustExprType( i->expr->get_result(), i->env, indexer );
175 }
176 }
177 if ( prune ) {
178 PRINT(
179 std::cerr << "alternatives before prune:" << std::endl;
180 printAlts( alternatives, std::cerr );
181 )
182 AltList::iterator oldBegin = alternatives.begin();
183 pruneAlternatives( alternatives.begin(), alternatives.end(), front_inserter( alternatives ), indexer );
184 if ( alternatives.begin() == oldBegin ) {
185 std::ostringstream stream;
186 stream << "Can't choose between alternatives for expression ";
187 expr->print( stream );
188 stream << "Alternatives are:";
189 AltList winners;
190 findMinCost( alternatives.begin(), alternatives.end(), back_inserter( winners ) );
191 printAlts( winners, stream, 8 );
192 throw SemanticError( stream.str() );
193 }
194 alternatives.erase( oldBegin, alternatives.end() );
195 PRINT(
196 std::cerr << "there are " << alternatives.size() << " alternatives after elimination" << std::endl;
197 )
198 }
199
200 // Central location to handle gcc extension keyword for all expression types.
201 for ( Alternative &iter: alternatives ) {
202 iter.expr->set_extension( expr->get_extension() );
203 } // for
204 }
205
206 void AlternativeFinder::findWithAdjustment( Expression *expr, bool prune ) {
207 find( expr, true, prune );
208 }
209
210 // std::unordered_map< Expression *, UniqueExpr * > ;
211
212 template< typename StructOrUnionType >
213 void AlternativeFinder::addAggMembers( StructOrUnionType *aggInst, Expression *expr, const Cost &newCost, const TypeEnvironment & env, Expression * member ) {
214 // by this point, member must be a name expr
215 NameExpr * nameExpr = safe_dynamic_cast< NameExpr * >( member );
216 const std::string & name = nameExpr->get_name();
217 std::list< Declaration* > members;
218 aggInst->lookup( name, members );
219 for ( std::list< Declaration* >::const_iterator i = members.begin(); i != members.end(); ++i ) {
220 if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType* >( *i ) ) {
221 alternatives.push_back( Alternative( new MemberExpr( dwt, expr->clone() ), env, newCost ) );
222 renameTypes( alternatives.back().expr );
223 } else {
224 assert( false );
225 }
226 }
227 }
228
229 void AlternativeFinder::addTupleMembers( TupleType * tupleType, Expression *expr, const Cost &newCost, const TypeEnvironment & env, Expression * member ) {
230 if ( ConstantExpr * constantExpr = dynamic_cast< ConstantExpr * >( member ) ) {
231 // get the value of the constant expression as an int, must be between 0 and the length of the tuple type to have meaning
232 // xxx - this should be improved by memoizing the value of constant exprs
233 // during parsing and reusing that information here.
234 std::stringstream ss( constantExpr->get_constant()->get_value() );
235 int val;
236 std::string tmp;
237 if ( ss >> val && ! (ss >> tmp) ) {
238 if ( val >= 0 && (unsigned int)val < tupleType->size() ) {
239 alternatives.push_back( Alternative( new TupleIndexExpr( expr->clone(), val ), env, newCost ) );
240 } // if
241 } // if
242 } // if
243 }
244
245 void AlternativeFinder::visit( ApplicationExpr *applicationExpr ) {
246 alternatives.push_back( Alternative( applicationExpr->clone(), env, Cost::zero ) );
247 }
248
249 Cost computeConversionCost( Alternative &alt, const SymTab::Indexer &indexer ) {
250 ApplicationExpr *appExpr = safe_dynamic_cast< ApplicationExpr* >( alt.expr );
251 PointerType *pointer = safe_dynamic_cast< PointerType* >( appExpr->get_function()->get_result() );
252 FunctionType *function = safe_dynamic_cast< FunctionType* >( pointer->get_base() );
253
254 Cost convCost( 0, 0, 0 );
255 std::list< DeclarationWithType* >& formals = function->get_parameters();
256 std::list< DeclarationWithType* >::iterator formal = formals.begin();
257 std::list< Expression* >& actuals = appExpr->get_args();
258
259 std::list< Type * > formalTypes;
260 std::list< Type * >::iterator formalType = formalTypes.end();
261
262 for ( std::list< Expression* >::iterator actualExpr = actuals.begin(); actualExpr != actuals.end(); ++actualExpr ) {
263
264 PRINT(
265 std::cerr << "actual expression:" << std::endl;
266 (*actualExpr)->print( std::cerr, 8 );
267 std::cerr << "--- results are" << std::endl;
268 (*actualExpr)->get_result()->print( std::cerr, 8 );
269 )
270 std::list< DeclarationWithType* >::iterator startFormal = formal;
271 Cost actualCost;
272 std::list< Type * > flatActualTypes;
273 flatten( (*actualExpr)->get_result(), back_inserter( flatActualTypes ) );
274 for ( std::list< Type* >::iterator actualType = flatActualTypes.begin(); actualType != flatActualTypes.end(); ++actualType ) {
275
276
277 // tuple handling code
278 if ( formalType == formalTypes.end() ) {
279 // the type of the formal parameter may be a tuple type. To make this easier to work with,
280 // flatten the tuple type and traverse the resulting list of types, incrementing the formal
281 // iterator once its types have been extracted. Once a particular formal parameter's type has
282 // been exhausted load the next formal parameter's type.
283 if ( formal == formals.end() ) {
284 if ( function->get_isVarArgs() ) {
285 convCost += Cost( 1, 0, 0 );
286 break;
287 } else {
288 return Cost::infinity;
289 }
290 }
291 formalTypes.clear();
292 flatten( (*formal)->get_type(), back_inserter( formalTypes ) );
293 formalType = formalTypes.begin();
294 ++formal;
295 }
296
297 PRINT(
298 std::cerr << std::endl << "converting ";
299 (*actualType)->print( std::cerr, 8 );
300 std::cerr << std::endl << " to ";
301 (*formal)->get_type()->print( std::cerr, 8 );
302 )
303 Cost newCost = conversionCost( *actualType, *formalType, indexer, alt.env );
304 PRINT(
305 std::cerr << std::endl << "cost is" << newCost << std::endl;
306 )
307
308 if ( newCost == Cost::infinity ) {
309 return newCost;
310 }
311 convCost += newCost;
312 actualCost += newCost;
313
314 convCost += Cost( 0, polyCost( *formalType, alt.env, indexer ) + polyCost( *actualType, alt.env, indexer ), 0 );
315
316 formalType++;
317 }
318 if ( actualCost != Cost( 0, 0, 0 ) ) {
319 std::list< DeclarationWithType* >::iterator startFormalPlusOne = startFormal;
320 startFormalPlusOne++;
321 if ( formal == startFormalPlusOne ) {
322 // not a tuple type
323 Type *newType = (*startFormal)->get_type()->clone();
324 alt.env.apply( newType );
325 *actualExpr = new CastExpr( *actualExpr, newType );
326 } else {
327 TupleType *newType = new TupleType( Type::Qualifiers() );
328 for ( std::list< DeclarationWithType* >::iterator i = startFormal; i != formal; ++i ) {
329 newType->get_types().push_back( (*i)->get_type()->clone() );
330 }
331 alt.env.apply( newType );
332 *actualExpr = new CastExpr( *actualExpr, newType );
333 }
334 }
335
336 }
337 if ( formal != formals.end() ) {
338 return Cost::infinity;
339 }
340
341 for ( InferredParams::const_iterator assert = appExpr->get_inferParams().begin(); assert != appExpr->get_inferParams().end(); ++assert ) {
342 PRINT(
343 std::cerr << std::endl << "converting ";
344 assert->second.actualType->print( std::cerr, 8 );
345 std::cerr << std::endl << " to ";
346 assert->second.formalType->print( std::cerr, 8 );
347 )
348 Cost newCost = conversionCost( assert->second.actualType, assert->second.formalType, indexer, alt.env );
349 PRINT(
350 std::cerr << std::endl << "cost of conversion is " << newCost << std::endl;
351 )
352 if ( newCost == Cost::infinity ) {
353 return newCost;
354 }
355 convCost += newCost;
356
357 convCost += Cost( 0, polyCost( assert->second.formalType, alt.env, indexer ) + polyCost( assert->second.actualType, alt.env, indexer ), 0 );
358 }
359
360 return convCost;
361 }
362
363 /// Adds type variables to the open variable set and marks their assertions
364 void makeUnifiableVars( Type *type, OpenVarSet &unifiableVars, AssertionSet &needAssertions ) {
365 for ( Type::ForallList::const_iterator tyvar = type->get_forall().begin(); tyvar != type->get_forall().end(); ++tyvar ) {
366 unifiableVars[ (*tyvar)->get_name() ] = (*tyvar)->get_kind();
367 for ( std::list< DeclarationWithType* >::iterator assert = (*tyvar)->get_assertions().begin(); assert != (*tyvar)->get_assertions().end(); ++assert ) {
368 needAssertions[ *assert ] = true;
369 }
370/// needAssertions.insert( needAssertions.end(), (*tyvar)->get_assertions().begin(), (*tyvar)->get_assertions().end() );
371 }
372 }
373
374 /// instantiate a single argument by matching actuals from [actualIt, actualEnd) against formalType,
375 /// producing expression(s) in out and their total cost in cost.
376 template< typename AltIterator, typename OutputIterator >
377 bool instantiateArgument( Type * formalType, Initializer * defaultValue, AltIterator & actualIt, AltIterator actualEnd, OpenVarSet & openVars, TypeEnvironment & resultEnv, AssertionSet & resultNeed, AssertionSet & resultHave, const SymTab::Indexer & indexer, Cost & cost, OutputIterator out ) {
378 if ( TupleType * tupleType = dynamic_cast< TupleType * >( formalType ) ) {
379 // formalType is a TupleType - group actuals into a TupleExpr whose type unifies with the TupleType
380 TupleExpr * tupleExpr = new TupleExpr();
381 for ( Type * type : *tupleType ) {
382 if ( ! instantiateArgument( type, defaultValue, actualIt, actualEnd, openVars, resultEnv, resultNeed, resultHave, indexer, cost, back_inserter( tupleExpr->get_exprs() ) ) ) {
383 delete tupleExpr;
384 return false;
385 }
386 }
387 tupleExpr->set_result( Tuples::makeTupleType( tupleExpr->get_exprs() ) );
388 *out++ = tupleExpr;
389 } else if ( actualIt != actualEnd ) {
390 // both actualType and formalType are atomic (non-tuple) types - if they unify
391 // then accept actual as an argument, otherwise return false (fail to instantiate argument)
392 Expression * actual = actualIt->expr;
393 Type * actualType = actual->get_result();
394 PRINT(
395 std::cerr << "formal type is ";
396 formalType->print( std::cerr );
397 std::cerr << std::endl << "actual type is ";
398 actualType->print( std::cerr );
399 std::cerr << std::endl;
400 )
401 if ( ! unify( formalType, actualType, resultEnv, resultNeed, resultHave, openVars, indexer ) ) {
402 return false;
403 }
404 // move the expression from the alternative to the output iterator
405 *out++ = actual;
406 actualIt->expr = nullptr;
407 cost += actualIt->cost;
408 ++actualIt;
409 } else {
410 // End of actuals - Handle default values
411 if ( SingleInit *si = dynamic_cast<SingleInit *>( defaultValue )) {
412 // so far, only constant expressions are accepted as default values
413 if ( ConstantExpr *cnstexpr = dynamic_cast<ConstantExpr *>( si->get_value()) ) {
414 if ( Constant *cnst = dynamic_cast<Constant *>( cnstexpr->get_constant() ) ) {
415 if ( unify( formalType, cnst->get_type(), resultEnv, resultNeed, resultHave, openVars, indexer ) ) {
416 // xxx - Don't know if this is right
417 *out++ = cnstexpr->clone();
418 return true;
419 } // if
420 } // if
421 } // if
422 } // if
423 return false;
424 } // if
425 return true;
426 }
427
428 bool AlternativeFinder::instantiateFunction( std::list< DeclarationWithType* >& formals, const AltList &actuals, bool isVarArgs, OpenVarSet& openVars, TypeEnvironment &resultEnv, AssertionSet &resultNeed, AssertionSet &resultHave, AltList & out ) {
429 simpleCombineEnvironments( actuals.begin(), actuals.end(), resultEnv );
430 // make sure we don't widen any existing bindings
431 for ( TypeEnvironment::iterator i = resultEnv.begin(); i != resultEnv.end(); ++i ) {
432 i->allowWidening = false;
433 }
434 resultEnv.extractOpenVars( openVars );
435
436 // flatten actuals so that each actual has an atomic (non-tuple) type
437 AltList exploded;
438 Tuples::explode( actuals, indexer, back_inserter( exploded ) );
439
440 AltList::iterator actualExpr = exploded.begin();
441 AltList::iterator actualEnd = exploded.end();
442 for ( DeclarationWithType * formal : formals ) {
443 // match flattened actuals with formal parameters - actuals will be grouped to match
444 // with formals as appropriate
445 Cost cost;
446 std::list< Expression * > newExprs;
447 ObjectDecl * obj = safe_dynamic_cast< ObjectDecl * >( formal );
448 if ( ! instantiateArgument( obj->get_type(), obj->get_init(), actualExpr, actualEnd, openVars, resultEnv, resultNeed, resultHave, indexer, cost, back_inserter( newExprs ) ) ) {
449 deleteAll( newExprs );
450 return false;
451 }
452 // success - produce argument as a new alternative
453 assert( newExprs.size() == 1 );
454 out.push_back( Alternative( newExprs.front(), resultEnv, cost ) );
455 }
456 if ( actualExpr != actualEnd ) {
457 // there are still actuals remaining, but we've run out of formal parameters to match against
458 // this is okay only if the function is variadic
459 if ( ! isVarArgs ) {
460 return false;
461 }
462 out.splice( out.end(), exploded, actualExpr, actualEnd );
463 }
464 return true;
465 }
466
467 // /// Map of declaration uniqueIds (intended to be the assertions in an AssertionSet) to their parents and the number of times they've been included
468 //typedef std::unordered_map< UniqueId, std::unordered_map< UniqueId, unsigned > > AssertionParentSet;
469
470 static const int recursionLimit = /*10*/ 4; ///< Limit to depth of recursion satisfaction
471 //static const unsigned recursionParentLimit = 1; ///< Limit to the number of times an assertion can recursively use itself
472
473 void addToIndexer( AssertionSet &assertSet, SymTab::Indexer &indexer ) {
474 for ( AssertionSet::iterator i = assertSet.begin(); i != assertSet.end(); ++i ) {
475 if ( i->second == true ) {
476 i->first->accept( indexer );
477 }
478 }
479 }
480
481 template< typename ForwardIterator, typename OutputIterator >
482 void inferRecursive( ForwardIterator begin, ForwardIterator end, const Alternative &newAlt, OpenVarSet &openVars, const SymTab::Indexer &decls, const AssertionSet &newNeed, /*const AssertionParentSet &needParents,*/
483 int level, const SymTab::Indexer &indexer, OutputIterator out ) {
484 if ( begin == end ) {
485 if ( newNeed.empty() ) {
486 *out++ = newAlt;
487 return;
488 } else if ( level >= recursionLimit ) {
489 throw SemanticError( "Too many recursive assertions" );
490 } else {
491 AssertionSet newerNeed;
492 PRINT(
493 std::cerr << "recursing with new set:" << std::endl;
494 printAssertionSet( newNeed, std::cerr, 8 );
495 )
496 inferRecursive( newNeed.begin(), newNeed.end(), newAlt, openVars, decls, newerNeed, /*needParents,*/ level+1, indexer, out );
497 return;
498 }
499 }
500
501 ForwardIterator cur = begin++;
502 if ( ! cur->second ) {
503 inferRecursive( begin, end, newAlt, openVars, decls, newNeed, /*needParents,*/ level, indexer, out );
504 }
505 DeclarationWithType *curDecl = cur->first;
506 PRINT(
507 std::cerr << "inferRecursive: assertion is ";
508 curDecl->print( std::cerr );
509 std::cerr << std::endl;
510 )
511 std::list< DeclarationWithType* > candidates;
512 decls.lookupId( curDecl->get_name(), candidates );
513/// if ( candidates.empty() ) { std::cerr << "no candidates!" << std::endl; }
514 for ( std::list< DeclarationWithType* >::const_iterator candidate = candidates.begin(); candidate != candidates.end(); ++candidate ) {
515 PRINT(
516 std::cerr << "inferRecursive: candidate is ";
517 (*candidate)->print( std::cerr );
518 std::cerr << std::endl;
519 )
520
521 AssertionSet newHave, newerNeed( newNeed );
522 TypeEnvironment newEnv( newAlt.env );
523 OpenVarSet newOpenVars( openVars );
524 Type *adjType = (*candidate)->get_type()->clone();
525 adjustExprType( adjType, newEnv, indexer );
526 adjType->accept( global_renamer );
527 PRINT(
528 std::cerr << "unifying ";
529 curDecl->get_type()->print( std::cerr );
530 std::cerr << " with ";
531 adjType->print( std::cerr );
532 std::cerr << std::endl;
533 )
534 if ( unify( curDecl->get_type(), adjType, newEnv, newerNeed, newHave, newOpenVars, indexer ) ) {
535 PRINT(
536 std::cerr << "success!" << std::endl;
537 )
538 SymTab::Indexer newDecls( decls );
539 addToIndexer( newHave, newDecls );
540 Alternative newerAlt( newAlt );
541 newerAlt.env = newEnv;
542 assert( (*candidate)->get_uniqueId() );
543 DeclarationWithType *candDecl = static_cast< DeclarationWithType* >( Declaration::declFromId( (*candidate)->get_uniqueId() ) );
544 //AssertionParentSet newNeedParents( needParents );
545 // skip repeatingly-self-recursive assertion satisfaction
546 // DOESN'T WORK: grandchild nodes conflict with their cousins
547 //if ( newNeedParents[ curDecl->get_uniqueId() ][ candDecl->get_uniqueId() ]++ > recursionParentLimit ) continue;
548 Expression *varExpr = new VariableExpr( candDecl );
549 delete varExpr->get_result();
550 varExpr->set_result( adjType->clone() );
551 PRINT(
552 std::cerr << "satisfying assertion " << curDecl->get_uniqueId() << " ";
553 curDecl->print( std::cerr );
554 std::cerr << " with declaration " << (*candidate)->get_uniqueId() << " ";
555 (*candidate)->print( std::cerr );
556 std::cerr << std::endl;
557 )
558 ApplicationExpr *appExpr = static_cast< ApplicationExpr* >( newerAlt.expr );
559 // XXX: this is a memory leak, but adjType can't be deleted because it might contain assertions
560 appExpr->get_inferParams()[ curDecl->get_uniqueId() ] = ParamEntry( (*candidate)->get_uniqueId(), adjType->clone(), curDecl->get_type()->clone(), varExpr );
561 inferRecursive( begin, end, newerAlt, newOpenVars, newDecls, newerNeed, /*newNeedParents,*/ level, indexer, out );
562 } else {
563 delete adjType;
564 }
565 }
566 }
567
568 template< typename OutputIterator >
569 void AlternativeFinder::inferParameters( const AssertionSet &need, AssertionSet &have, const Alternative &newAlt, OpenVarSet &openVars, OutputIterator out ) {
570// PRINT(
571// std::cerr << "inferParameters: assertions needed are" << std::endl;
572// printAll( need, std::cerr, 8 );
573// )
574 SymTab::Indexer decls( indexer );
575 PRINT(
576 std::cerr << "============= original indexer" << std::endl;
577 indexer.print( std::cerr );
578 std::cerr << "============= new indexer" << std::endl;
579 decls.print( std::cerr );
580 )
581 addToIndexer( have, decls );
582 AssertionSet newNeed;
583 //AssertionParentSet needParents;
584 inferRecursive( need.begin(), need.end(), newAlt, openVars, decls, newNeed, /*needParents,*/ 0, indexer, out );
585// PRINT(
586// std::cerr << "declaration 14 is ";
587// Declaration::declFromId
588// *out++ = newAlt;
589// )
590 }
591
592 template< typename OutputIterator >
593 void AlternativeFinder::makeFunctionAlternatives( const Alternative &func, FunctionType *funcType, const AltList &actualAlt, OutputIterator out ) {
594 OpenVarSet openVars;
595 AssertionSet resultNeed, resultHave;
596 TypeEnvironment resultEnv;
597 makeUnifiableVars( funcType, openVars, resultNeed );
598 AltList instantiatedActuals; // filled by instantiate function
599 if ( instantiateFunction( funcType->get_parameters(), actualAlt, funcType->get_isVarArgs(), openVars, resultEnv, resultNeed, resultHave, instantiatedActuals ) ) {
600 ApplicationExpr *appExpr = new ApplicationExpr( func.expr->clone() );
601 Alternative newAlt( appExpr, resultEnv, sumCost( instantiatedActuals ) );
602 makeExprList( instantiatedActuals, appExpr->get_args() );
603 PRINT(
604 std::cerr << "need assertions:" << std::endl;
605 printAssertionSet( resultNeed, std::cerr, 8 );
606 )
607 inferParameters( resultNeed, resultHave, newAlt, openVars, out );
608 }
609 }
610
611 void AlternativeFinder::visit( UntypedExpr *untypedExpr ) {
612 bool doneInit = false;
613 AlternativeFinder funcOpFinder( indexer, env );
614
615 AlternativeFinder funcFinder( indexer, env );
616
617 {
618 std::string fname = InitTweak::getFunctionName( untypedExpr );
619 if ( fname == "&&" ) {
620 VoidType v = Type::Qualifiers(); // resolve to type void *
621 PointerType pt( Type::Qualifiers(), v.clone() );
622 UntypedExpr *vexpr = untypedExpr->clone();
623 vexpr->set_result( pt.clone() );
624 alternatives.push_back( Alternative( vexpr, env, Cost()) );
625 return;
626 }
627 }
628
629 funcFinder.findWithAdjustment( untypedExpr->get_function() );
630 std::list< AlternativeFinder > argAlternatives;
631 findSubExprs( untypedExpr->begin_args(), untypedExpr->end_args(), back_inserter( argAlternatives ) );
632
633 std::list< AltList > possibilities;
634 combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
635
636 // take care of possible tuple assignments
637 // if not tuple assignment, assignment is taken care of as a normal function call
638 Tuples::handleTupleAssignment( *this, untypedExpr, possibilities );
639
640 AltList candidates;
641 SemanticError errors;
642
643 for ( AltList::const_iterator func = funcFinder.alternatives.begin(); func != funcFinder.alternatives.end(); ++func ) {
644 try {
645 PRINT(
646 std::cerr << "working on alternative: " << std::endl;
647 func->print( std::cerr, 8 );
648 )
649 // check if the type is pointer to function
650 PointerType *pointer;
651 if ( ( pointer = dynamic_cast< PointerType* >( func->expr->get_result() ) ) ) {
652 if ( FunctionType *function = dynamic_cast< FunctionType* >( pointer->get_base() ) ) {
653 for ( std::list< AltList >::iterator actualAlt = possibilities.begin(); actualAlt != possibilities.end(); ++actualAlt ) {
654 // XXX
655 //Designators::check_alternative( function, *actualAlt );
656 makeFunctionAlternatives( *func, function, *actualAlt, std::back_inserter( candidates ) );
657 }
658 } else if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( pointer->get_base() ) ) {
659 EqvClass eqvClass;
660 if ( func->env.lookup( typeInst->get_name(), eqvClass ) && eqvClass.type ) {
661 if ( FunctionType *function = dynamic_cast< FunctionType* >( eqvClass.type ) ) {
662 for ( std::list< AltList >::iterator actualAlt = possibilities.begin(); actualAlt != possibilities.end(); ++actualAlt ) {
663 makeFunctionAlternatives( *func, function, *actualAlt, std::back_inserter( candidates ) );
664 } // for
665 } // if
666 } // if
667 } // if
668 } else {
669 // seek a function operator that's compatible
670 if ( ! doneInit ) {
671 doneInit = true;
672 NameExpr *opExpr = new NameExpr( "?()" );
673 try {
674 funcOpFinder.findWithAdjustment( opExpr );
675 } catch( SemanticError &e ) {
676 // it's ok if there aren't any defined function ops
677 }
678 PRINT(
679 std::cerr << "known function ops:" << std::endl;
680 printAlts( funcOpFinder.alternatives, std::cerr, 8 );
681 )
682 }
683
684 for ( AltList::const_iterator funcOp = funcOpFinder.alternatives.begin(); funcOp != funcOpFinder.alternatives.end(); ++funcOp ) {
685 // check if the type is pointer to function
686 PointerType *pointer;
687 if ( ( pointer = dynamic_cast< PointerType* >( funcOp->expr->get_result() ) ) ) {
688 if ( FunctionType *function = dynamic_cast< FunctionType* >( pointer->get_base() ) ) {
689 for ( std::list< AltList >::iterator actualAlt = possibilities.begin(); actualAlt != possibilities.end(); ++actualAlt ) {
690 AltList currentAlt;
691 currentAlt.push_back( *func );
692 currentAlt.insert( currentAlt.end(), actualAlt->begin(), actualAlt->end() );
693 makeFunctionAlternatives( *funcOp, function, currentAlt, std::back_inserter( candidates ) );
694 } // for
695 } // if
696 } // if
697 } // for
698 } // if
699 } catch ( SemanticError &e ) {
700 errors.append( e );
701 }
702 } // for
703
704 // Implement SFINAE; resolution errors are only errors if there aren't any non-erroneous resolutions
705 if ( candidates.empty() && ! errors.isEmpty() ) { throw errors; }
706
707 for ( AltList::iterator withFunc = candidates.begin(); withFunc != candidates.end(); ++withFunc ) {
708 Cost cvtCost = computeConversionCost( *withFunc, indexer );
709
710 PRINT(
711 ApplicationExpr *appExpr = safe_dynamic_cast< ApplicationExpr* >( withFunc->expr );
712 PointerType *pointer = safe_dynamic_cast< PointerType* >( appExpr->get_function()->get_result() );
713 FunctionType *function = safe_dynamic_cast< FunctionType* >( pointer->get_base() );
714 std::cerr << "Case +++++++++++++" << std::endl;
715 std::cerr << "formals are:" << std::endl;
716 printAll( function->get_parameters(), std::cerr, 8 );
717 std::cerr << "actuals are:" << std::endl;
718 printAll( appExpr->get_args(), std::cerr, 8 );
719 std::cerr << "bindings are:" << std::endl;
720 withFunc->env.print( std::cerr, 8 );
721 std::cerr << "cost of conversion is:" << cvtCost << std::endl;
722 )
723 if ( cvtCost != Cost::infinity ) {
724 withFunc->cvtCost = cvtCost;
725 alternatives.push_back( *withFunc );
726 } // if
727 } // for
728 candidates.clear();
729 candidates.splice( candidates.end(), alternatives );
730
731 findMinCost( candidates.begin(), candidates.end(), std::back_inserter( alternatives ) );
732 }
733
734 bool isLvalue( Expression *expr ) {
735 // xxx - recurse into tuples?
736 return expr->has_result() && expr->get_result()->get_isLvalue();
737 }
738
739 void AlternativeFinder::visit( AddressExpr *addressExpr ) {
740 AlternativeFinder finder( indexer, env );
741 finder.find( addressExpr->get_arg() );
742 for ( std::list< Alternative >::iterator i = finder.alternatives.begin(); i != finder.alternatives.end(); ++i ) {
743 if ( isLvalue( i->expr ) ) {
744 alternatives.push_back( Alternative( new AddressExpr( i->expr->clone() ), i->env, i->cost ) );
745 } // if
746 } // for
747 }
748
749 void AlternativeFinder::visit( CastExpr *castExpr ) {
750 Type *& toType = castExpr->get_result();
751 toType = resolveTypeof( toType, indexer );
752 SymTab::validateType( toType, &indexer );
753 adjustExprType( toType, env, indexer );
754
755 AlternativeFinder finder( indexer, env );
756 finder.findWithAdjustment( castExpr->get_arg() );
757
758 AltList candidates;
759 for ( std::list< Alternative >::iterator i = finder.alternatives.begin(); i != finder.alternatives.end(); ++i ) {
760 AssertionSet needAssertions, haveAssertions;
761 OpenVarSet openVars;
762
763 // It's possible that a cast can throw away some values in a multiply-valued expression. (An example is a
764 // cast-to-void, which casts from one value to zero.) Figure out the prefix of the subexpression results
765 // that are cast directly. The candidate is invalid if it has fewer results than there are types to cast
766 // to.
767 int discardedValues = (*i).expr->get_result()->size() - castExpr->get_result()->size();
768 if ( discardedValues < 0 ) continue;
769 // xxx - may need to go into tuple types and extract relavent types and use unifyList
770 // unification run for side-effects
771 unify( castExpr->get_result(), (*i).expr->get_result(), i->env, needAssertions, haveAssertions, openVars, indexer );
772 Cost thisCost = castCost( (*i).expr->get_result(), castExpr->get_result(), indexer, i->env );
773 if ( thisCost != Cost::infinity ) {
774 // count one safe conversion for each value that is thrown away
775 thisCost += Cost( 0, 0, discardedValues );
776 CastExpr *newExpr = castExpr->clone();
777 newExpr->set_arg( i->expr->clone() );
778 candidates.push_back( Alternative( newExpr, i->env, i->cost, thisCost ) );
779 } // if
780 } // for
781
782 // findMinCost selects the alternatives with the lowest "cost" members, but has the side effect of copying the
783 // cvtCost member to the cost member (since the old cost is now irrelevant). Thus, calling findMinCost twice
784 // selects first based on argument cost, then on conversion cost.
785 AltList minArgCost;
786 findMinCost( candidates.begin(), candidates.end(), std::back_inserter( minArgCost ) );
787 findMinCost( minArgCost.begin(), minArgCost.end(), std::back_inserter( alternatives ) );
788 }
789
790 void AlternativeFinder::visit( UntypedMemberExpr *memberExpr ) {
791 AlternativeFinder funcFinder( indexer, env );
792 funcFinder.findWithAdjustment( memberExpr->get_aggregate() );
793
794 for ( AltList::const_iterator agg = funcFinder.alternatives.begin(); agg != funcFinder.alternatives.end(); ++agg ) {
795 if ( StructInstType *structInst = dynamic_cast< StructInstType* >( agg->expr->get_result() ) ) {
796 addAggMembers( structInst, agg->expr, agg->cost, agg->env, memberExpr->get_member() );
797 } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( agg->expr->get_result() ) ) {
798 addAggMembers( unionInst, agg->expr, agg->cost, agg->env, memberExpr->get_member() );
799 } else if ( TupleType * tupleType = dynamic_cast< TupleType * >( agg->expr->get_result() ) ) {
800 addTupleMembers( tupleType, agg->expr, agg->cost, agg->env, memberExpr->get_member() );
801 } // if
802 } // for
803 }
804
805 void AlternativeFinder::visit( MemberExpr *memberExpr ) {
806 alternatives.push_back( Alternative( memberExpr->clone(), env, Cost::zero ) );
807 }
808
809 void AlternativeFinder::visit( NameExpr *nameExpr ) {
810 std::list< DeclarationWithType* > declList;
811 indexer.lookupId( nameExpr->get_name(), declList );
812 PRINT( std::cerr << "nameExpr is " << nameExpr->get_name() << std::endl; )
813 for ( std::list< DeclarationWithType* >::iterator i = declList.begin(); i != declList.end(); ++i ) {
814 VariableExpr newExpr( *i, nameExpr->get_argName() );
815 alternatives.push_back( Alternative( newExpr.clone(), env, Cost() ) );
816 PRINT(
817 std::cerr << "decl is ";
818 (*i)->print( std::cerr );
819 std::cerr << std::endl;
820 std::cerr << "newExpr is ";
821 newExpr.print( std::cerr );
822 std::cerr << std::endl;
823 )
824 renameTypes( alternatives.back().expr );
825 if ( StructInstType *structInst = dynamic_cast< StructInstType* >( (*i)->get_type() ) ) {
826 NameExpr nameExpr( "" );
827 addAggMembers( structInst, &newExpr, Cost( 0, 0, 1 ), env, &nameExpr );
828 } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( (*i)->get_type() ) ) {
829 NameExpr nameExpr( "" );
830 addAggMembers( unionInst, &newExpr, Cost( 0, 0, 1 ), env, &nameExpr );
831 } // if
832 } // for
833 }
834
835 void AlternativeFinder::visit( VariableExpr *variableExpr ) {
836 // not sufficient to clone here, because variable's type may have changed
837 // since the VariableExpr was originally created.
838 alternatives.push_back( Alternative( new VariableExpr( variableExpr->get_var() ), env, Cost::zero ) );
839 }
840
841 void AlternativeFinder::visit( ConstantExpr *constantExpr ) {
842 alternatives.push_back( Alternative( constantExpr->clone(), env, Cost::zero ) );
843 }
844
845 void AlternativeFinder::visit( SizeofExpr *sizeofExpr ) {
846 if ( sizeofExpr->get_isType() ) {
847 // xxx - resolveTypeof?
848 alternatives.push_back( Alternative( sizeofExpr->clone(), env, Cost::zero ) );
849 } else {
850 // find all alternatives for the argument to sizeof
851 AlternativeFinder finder( indexer, env );
852 finder.find( sizeofExpr->get_expr() );
853 // find the lowest cost alternative among the alternatives, otherwise ambiguous
854 AltList winners;
855 findMinCost( finder.alternatives.begin(), finder.alternatives.end(), back_inserter( winners ) );
856 if ( winners.size() != 1 ) {
857 throw SemanticError( "Ambiguous expression in sizeof operand: ", sizeofExpr->get_expr() );
858 } // if
859 // return the lowest cost alternative for the argument
860 Alternative &choice = winners.front();
861 alternatives.push_back( Alternative( new SizeofExpr( choice.expr->clone() ), choice.env, Cost::zero ) );
862 } // if
863 }
864
865 void AlternativeFinder::visit( AlignofExpr *alignofExpr ) {
866 if ( alignofExpr->get_isType() ) {
867 // xxx - resolveTypeof?
868 alternatives.push_back( Alternative( alignofExpr->clone(), env, Cost::zero ) );
869 } else {
870 // find all alternatives for the argument to sizeof
871 AlternativeFinder finder( indexer, env );
872 finder.find( alignofExpr->get_expr() );
873 // find the lowest cost alternative among the alternatives, otherwise ambiguous
874 AltList winners;
875 findMinCost( finder.alternatives.begin(), finder.alternatives.end(), back_inserter( winners ) );
876 if ( winners.size() != 1 ) {
877 throw SemanticError( "Ambiguous expression in alignof operand: ", alignofExpr->get_expr() );
878 } // if
879 // return the lowest cost alternative for the argument
880 Alternative &choice = winners.front();
881 alternatives.push_back( Alternative( new AlignofExpr( choice.expr->clone() ), choice.env, Cost::zero ) );
882 } // if
883 }
884
885 template< typename StructOrUnionType >
886 void AlternativeFinder::addOffsetof( StructOrUnionType *aggInst, const std::string &name ) {
887 std::list< Declaration* > members;
888 aggInst->lookup( name, members );
889 for ( std::list< Declaration* >::const_iterator i = members.begin(); i != members.end(); ++i ) {
890 if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType* >( *i ) ) {
891 alternatives.push_back( Alternative( new OffsetofExpr( aggInst->clone(), dwt ), env, Cost::zero ) );
892 renameTypes( alternatives.back().expr );
893 } else {
894 assert( false );
895 }
896 }
897 }
898
899 void AlternativeFinder::visit( UntypedOffsetofExpr *offsetofExpr ) {
900 AlternativeFinder funcFinder( indexer, env );
901 // xxx - resolveTypeof?
902 if ( StructInstType *structInst = dynamic_cast< StructInstType* >( offsetofExpr->get_type() ) ) {
903 addOffsetof( structInst, offsetofExpr->get_member() );
904 } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( offsetofExpr->get_type() ) ) {
905 addOffsetof( unionInst, offsetofExpr->get_member() );
906 }
907 }
908
909 void AlternativeFinder::visit( OffsetofExpr *offsetofExpr ) {
910 alternatives.push_back( Alternative( offsetofExpr->clone(), env, Cost::zero ) );
911 }
912
913 void AlternativeFinder::visit( OffsetPackExpr *offsetPackExpr ) {
914 alternatives.push_back( Alternative( offsetPackExpr->clone(), env, Cost::zero ) );
915 }
916
917 void AlternativeFinder::resolveAttr( DeclarationWithType *funcDecl, FunctionType *function, Type *argType, const TypeEnvironment &env ) {
918 // assume no polymorphism
919 // assume no implicit conversions
920 assert( function->get_parameters().size() == 1 );
921 PRINT(
922 std::cerr << "resolvAttr: funcDecl is ";
923 funcDecl->print( std::cerr );
924 std::cerr << " argType is ";
925 argType->print( std::cerr );
926 std::cerr << std::endl;
927 )
928 if ( typesCompatibleIgnoreQualifiers( argType, function->get_parameters().front()->get_type(), indexer, env ) ) {
929 alternatives.push_back( Alternative( new AttrExpr( new VariableExpr( funcDecl ), argType->clone() ), env, Cost::zero ) );
930 for ( std::list< DeclarationWithType* >::iterator i = function->get_returnVals().begin(); i != function->get_returnVals().end(); ++i ) {
931 alternatives.back().expr->set_result( (*i)->get_type()->clone() );
932 } // for
933 } // if
934 }
935
936 void AlternativeFinder::visit( AttrExpr *attrExpr ) {
937 // assume no 'pointer-to-attribute'
938 NameExpr *nameExpr = dynamic_cast< NameExpr* >( attrExpr->get_attr() );
939 assert( nameExpr );
940 std::list< DeclarationWithType* > attrList;
941 indexer.lookupId( nameExpr->get_name(), attrList );
942 if ( attrExpr->get_isType() || attrExpr->get_expr() ) {
943 for ( std::list< DeclarationWithType* >::iterator i = attrList.begin(); i != attrList.end(); ++i ) {
944 // check if the type is function
945 if ( FunctionType *function = dynamic_cast< FunctionType* >( (*i)->get_type() ) ) {
946 // assume exactly one parameter
947 if ( function->get_parameters().size() == 1 ) {
948 if ( attrExpr->get_isType() ) {
949 resolveAttr( *i, function, attrExpr->get_type(), env );
950 } else {
951 AlternativeFinder finder( indexer, env );
952 finder.find( attrExpr->get_expr() );
953 for ( AltList::iterator choice = finder.alternatives.begin(); choice != finder.alternatives.end(); ++choice ) {
954 if ( choice->expr->get_result()->size() == 1 ) {
955 resolveAttr(*i, function, choice->expr->get_result(), choice->env );
956 } // fi
957 } // for
958 } // if
959 } // if
960 } // if
961 } // for
962 } else {
963 for ( std::list< DeclarationWithType* >::iterator i = attrList.begin(); i != attrList.end(); ++i ) {
964 VariableExpr newExpr( *i );
965 alternatives.push_back( Alternative( newExpr.clone(), env, Cost() ) );
966 renameTypes( alternatives.back().expr );
967 } // for
968 } // if
969 }
970
971 void AlternativeFinder::visit( LogicalExpr *logicalExpr ) {
972 AlternativeFinder firstFinder( indexer, env );
973 firstFinder.findWithAdjustment( logicalExpr->get_arg1() );
974 for ( AltList::const_iterator first = firstFinder.alternatives.begin(); first != firstFinder.alternatives.end(); ++first ) {
975 AlternativeFinder secondFinder( indexer, first->env );
976 secondFinder.findWithAdjustment( logicalExpr->get_arg2() );
977 for ( AltList::const_iterator second = secondFinder.alternatives.begin(); second != secondFinder.alternatives.end(); ++second ) {
978 LogicalExpr *newExpr = new LogicalExpr( first->expr->clone(), second->expr->clone(), logicalExpr->get_isAnd() );
979 alternatives.push_back( Alternative( newExpr, second->env, first->cost + second->cost ) );
980 }
981 }
982 }
983
984 void AlternativeFinder::visit( ConditionalExpr *conditionalExpr ) {
985 AlternativeFinder firstFinder( indexer, env );
986 firstFinder.findWithAdjustment( conditionalExpr->get_arg1() );
987 for ( AltList::const_iterator first = firstFinder.alternatives.begin(); first != firstFinder.alternatives.end(); ++first ) {
988 AlternativeFinder secondFinder( indexer, first->env );
989 secondFinder.findWithAdjustment( conditionalExpr->get_arg2() );
990 for ( AltList::const_iterator second = secondFinder.alternatives.begin(); second != secondFinder.alternatives.end(); ++second ) {
991 AlternativeFinder thirdFinder( indexer, second->env );
992 thirdFinder.findWithAdjustment( conditionalExpr->get_arg3() );
993 for ( AltList::const_iterator third = thirdFinder.alternatives.begin(); third != thirdFinder.alternatives.end(); ++third ) {
994 OpenVarSet openVars;
995 AssertionSet needAssertions, haveAssertions;
996 Alternative newAlt( 0, third->env, first->cost + second->cost + third->cost );
997 Type* commonType;
998 if ( unify( second->expr->get_result(), third->expr->get_result(), newAlt.env, needAssertions, haveAssertions, openVars, indexer, commonType ) ) {
999 ConditionalExpr *newExpr = new ConditionalExpr( first->expr->clone(), second->expr->clone(), third->expr->clone() );
1000 newExpr->set_result( commonType ? commonType : second->expr->get_result()->clone() );
1001 newAlt.expr = newExpr;
1002 inferParameters( needAssertions, haveAssertions, newAlt, openVars, back_inserter( alternatives ) );
1003 } // if
1004 } // for
1005 } // for
1006 } // for
1007 }
1008
1009 void AlternativeFinder::visit( CommaExpr *commaExpr ) {
1010 TypeEnvironment newEnv( env );
1011 Expression *newFirstArg = resolveInVoidContext( commaExpr->get_arg1(), indexer, newEnv );
1012 AlternativeFinder secondFinder( indexer, newEnv );
1013 secondFinder.findWithAdjustment( commaExpr->get_arg2() );
1014 for ( AltList::const_iterator alt = secondFinder.alternatives.begin(); alt != secondFinder.alternatives.end(); ++alt ) {
1015 alternatives.push_back( Alternative( new CommaExpr( newFirstArg->clone(), alt->expr->clone() ), alt->env, alt->cost ) );
1016 } // for
1017 delete newFirstArg;
1018 }
1019
1020 void AlternativeFinder::visit( TupleExpr *tupleExpr ) {
1021 std::list< AlternativeFinder > subExprAlternatives;
1022 findSubExprs( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end(), back_inserter( subExprAlternatives ) );
1023 std::list< AltList > possibilities;
1024 combos( subExprAlternatives.begin(), subExprAlternatives.end(), back_inserter( possibilities ) );
1025 for ( std::list< AltList >::const_iterator i = possibilities.begin(); i != possibilities.end(); ++i ) {
1026 TupleExpr *newExpr = new TupleExpr;
1027 makeExprList( *i, newExpr->get_exprs() );
1028 newExpr->set_result( Tuples::makeTupleType( newExpr->get_exprs() ) );
1029
1030 TypeEnvironment compositeEnv;
1031 simpleCombineEnvironments( i->begin(), i->end(), compositeEnv );
1032 alternatives.push_back( Alternative( newExpr, compositeEnv, sumCost( *i ) ) );
1033 } // for
1034 }
1035
1036 void AlternativeFinder::visit( ImplicitCopyCtorExpr * impCpCtorExpr ) {
1037 alternatives.push_back( Alternative( impCpCtorExpr->clone(), env, Cost::zero ) );
1038 }
1039
1040 void AlternativeFinder::visit( ConstructorExpr * ctorExpr ) {
1041 AlternativeFinder finder( indexer, env );
1042 // don't prune here, since it's guaranteed all alternatives will have the same type
1043 // (giving the alternatives different types is half of the point of ConstructorExpr nodes)
1044 finder.findWithAdjustment( ctorExpr->get_callExpr(), false );
1045 for ( Alternative & alt : finder.alternatives ) {
1046 alternatives.push_back( Alternative( new ConstructorExpr( alt.expr->clone() ), alt.env, alt.cost ) );
1047 }
1048 }
1049
1050 void AlternativeFinder::visit( TupleIndexExpr *tupleExpr ) {
1051 alternatives.push_back( Alternative( tupleExpr->clone(), env, Cost::zero ) );
1052 }
1053
1054 void AlternativeFinder::visit( TupleAssignExpr *tupleAssignExpr ) {
1055 alternatives.push_back( Alternative( tupleAssignExpr->clone(), env, Cost::zero ) );
1056 }
1057
1058 void AlternativeFinder::visit( UniqueExpr *unqExpr ) {
1059 // this won't work because the unqExprs wont share an expression anymore...
1060 AlternativeFinder finder( indexer, env );
1061 finder.findWithAdjustment( unqExpr->get_expr() );
1062 for ( Alternative & alt : finder.alternatives ) {
1063 // xxx - attach a resolved ConstructorInit node?
1064 // xxx - is it possible to make the objDecl's type const?
1065 static UniqueName tempNamer( "_unq_expr_" );
1066 ObjectDecl * objDecl = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, nullptr, alt.expr->get_result()->clone(), nullptr );
1067 // must be done on two lines because genCtorInit accesses objDecl's fields
1068 objDecl->set_init( InitTweak::genCtorInit( objDecl ) );
1069
1070 UniqueExpr * newUnqExpr = new UniqueExpr( alt.expr->clone(), unqExpr->get_id() );
1071 newUnqExpr->set_object( objDecl );
1072
1073 resolveObject( indexer, objDecl );
1074
1075 alternatives.push_back( Alternative( newUnqExpr, env, Cost::zero ) );
1076 }
1077 }
1078
1079} // namespace ResolvExpr
1080
1081// Local Variables: //
1082// tab-width: 4 //
1083// mode: c++ //
1084// compile-command: "make install" //
1085// End: //
Note: See TracBrowser for help on using the repository browser.