source: src/ResolvExpr/AlternativeFinder.cc@ 1132b62

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

major change to instantiateFunction to match arguments against the formal parameter's structure rather than the reverse

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