source: src/ResolvExpr/AlternativeFinder.cc@ 3f0c6a5

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

resolve ctor/dtors for UniqueExprs

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