source: src/ResolvExpr/AlternativeFinder.cc@ 33a7b6d

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 stuck-waitfor-destruct with_gc
Last change on this file since 33a7b6d was 33a7b6d, checked in by Rob Schluntz <rschlunt@…>, 10 years ago

changed use of formal types to actual types for boxing return parameters and passing type variables, fix bug where generic struct's members would change types when a member is accessed on a concrete instantiation

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