source: src/ResolvExpr/AlternativeFinder.cc@ 848ce71

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

resolve untyped member exprs for tuples

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