source: src/ResolvExpr/AlternativeFinder.cc@ ec7f50a

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr no_list persistent-indexer pthread-emulation qualifiedEnum
Last change on this file since ec7f50a was bd78797, checked in by Aaron Moss <a3moss@…>, 7 years ago

closes #118

  • Property mode set to 100644
File size: 71.5 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// AlternativeFinder.cc --
8//
9// Author : Richard C. Bilson
10// Created On : Sat May 16 23:52:08 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Nov 1 21:00:56 2018
13// Update Count : 35
14//
15
16#include <algorithm> // for copy
17#include <cassert> // for strict_dynamic_cast, assert, assertf
18#include <cstddef> // for size_t
19#include <iostream> // for operator<<, cerr, ostream, endl
20#include <iterator> // for back_insert_iterator, back_inserter
21#include <list> // for _List_iterator, list, _List_const_...
22#include <map> // for _Rb_tree_iterator, map, _Rb_tree_c...
23#include <memory> // for allocator_traits<>::value_type, unique_ptr
24#include <utility> // for pair
25#include <vector> // for vector
26
27#include "CompilationState.h" // for resolvep
28#include "Alternative.h" // for AltList, Alternative
29#include "AlternativeFinder.h"
30#include "Common/SemanticError.h" // for SemanticError
31#include "Common/utility.h" // for deleteAll, printAll, CodeLocation
32#include "Cost.h" // for Cost, Cost::zero, operator<<, Cost...
33#include "ExplodedActual.h" // for ExplodedActual
34#include "InitTweak/InitTweak.h" // for getFunctionName
35#include "RenameVars.h" // for RenameVars, global_renamer
36#include "ResolveAssertions.h" // for resolveAssertions
37#include "ResolveTypeof.h" // for resolveTypeof
38#include "Resolver.h" // for resolveStmtExpr
39#include "SymTab/Indexer.h" // for Indexer
40#include "SymTab/Mangler.h" // for Mangler
41#include "SymTab/Validate.h" // for validateType
42#include "SynTree/Constant.h" // for Constant
43#include "SynTree/Declaration.h" // for DeclarationWithType, TypeDecl, Dec...
44#include "SynTree/Expression.h" // for Expression, CastExpr, NameExpr
45#include "SynTree/Initializer.h" // for SingleInit, operator<<, Designation
46#include "SynTree/SynTree.h" // for UniqueId
47#include "SynTree/Type.h" // for Type, FunctionType, PointerType
48#include "Tuples/Explode.h" // for explode
49#include "Tuples/Tuples.h" // for isTtype, handleTupleAssignment
50#include "Unify.h" // for unify
51#include "typeops.h" // for adjustExprType, polyCost, castCost
52
53#define PRINT( text ) if ( resolvep ) { text }
54//#define DEBUG_COST
55
56using std::move;
57
58/// copies any copyable type
59template<typename T>
60T copy(const T& x) { return x; }
61
62namespace ResolvExpr {
63 struct AlternativeFinder::Finder : public WithShortCircuiting {
64 Finder( AlternativeFinder & altFinder ) : altFinder( altFinder ), indexer( altFinder.indexer ), alternatives( altFinder.alternatives ), env( altFinder.env ), targetType( altFinder.targetType ) {}
65
66 void previsit( BaseSyntaxNode * ) { visit_children = false; }
67
68 void postvisit( ApplicationExpr * applicationExpr );
69 void postvisit( UntypedExpr * untypedExpr );
70 void postvisit( AddressExpr * addressExpr );
71 void postvisit( LabelAddressExpr * labelExpr );
72 void postvisit( CastExpr * castExpr );
73 void postvisit( VirtualCastExpr * castExpr );
74 void postvisit( UntypedMemberExpr * memberExpr );
75 void postvisit( MemberExpr * memberExpr );
76 void postvisit( NameExpr * variableExpr );
77 void postvisit( VariableExpr * variableExpr );
78 void postvisit( ConstantExpr * constantExpr );
79 void postvisit( SizeofExpr * sizeofExpr );
80 void postvisit( AlignofExpr * alignofExpr );
81 void postvisit( UntypedOffsetofExpr * offsetofExpr );
82 void postvisit( OffsetofExpr * offsetofExpr );
83 void postvisit( OffsetPackExpr * offsetPackExpr );
84 void postvisit( AttrExpr * attrExpr );
85 void postvisit( LogicalExpr * logicalExpr );
86 void postvisit( ConditionalExpr * conditionalExpr );
87 void postvisit( CommaExpr * commaExpr );
88 void postvisit( ImplicitCopyCtorExpr * impCpCtorExpr );
89 void postvisit( ConstructorExpr * ctorExpr );
90 void postvisit( RangeExpr * rangeExpr );
91 void postvisit( UntypedTupleExpr * tupleExpr );
92 void postvisit( TupleExpr * tupleExpr );
93 void postvisit( TupleIndexExpr * tupleExpr );
94 void postvisit( TupleAssignExpr * tupleExpr );
95 void postvisit( UniqueExpr * unqExpr );
96 void postvisit( StmtExpr * stmtExpr );
97 void postvisit( UntypedInitExpr * initExpr );
98 void postvisit( InitExpr * initExpr );
99 void postvisit( DeletedExpr * delExpr );
100 void postvisit( GenericExpr * genExpr );
101
102 /// Adds alternatives for anonymous members
103 void addAnonConversions( const Alternative & alt );
104 /// Adds alternatives for member expressions, given the aggregate, conversion cost for that aggregate, and name of the member
105 template< typename StructOrUnionType > void addAggMembers( StructOrUnionType *aggInst, Expression *expr, const Alternative &alt, const Cost &newCost, const std::string & name );
106 /// Adds alternatives for member expressions where the left side has tuple type
107 void addTupleMembers( TupleType *tupleType, Expression *expr, const Alternative &alt, const Cost &newCost, Expression *member );
108 /// Adds alternatives for offsetof expressions, given the base type and name of the member
109 template< typename StructOrUnionType > void addOffsetof( StructOrUnionType *aggInst, const std::string &name );
110 /// Takes a final result and checks if its assertions can be satisfied
111 template<typename OutputIterator>
112 void validateFunctionAlternative( const Alternative &func, ArgPack& result, const std::vector<ArgPack>& results, OutputIterator out );
113 /// Finds matching alternatives for a function, given a set of arguments
114 template<typename OutputIterator>
115 void makeFunctionAlternatives( const Alternative &func, FunctionType *funcType, const ExplodedArgs& args, OutputIterator out );
116 /// Sets up parameter inference for an output alternative
117 template< typename OutputIterator >
118 void inferParameters( Alternative &newAlt, OutputIterator out );
119 private:
120 AlternativeFinder & altFinder;
121 const SymTab::Indexer &indexer;
122 AltList & alternatives;
123 const TypeEnvironment &env;
124 Type *& targetType;
125 };
126
127 Cost sumCost( const AltList &in ) {
128 Cost total = Cost::zero;
129 for ( AltList::const_iterator i = in.begin(); i != in.end(); ++i ) {
130 total += i->cost;
131 }
132 return total;
133 }
134
135 void printAlts( const AltList &list, std::ostream &os, unsigned int indentAmt ) {
136 Indenter indent = { Indenter::tabsize, indentAmt };
137 for ( AltList::const_iterator i = list.begin(); i != list.end(); ++i ) {
138 i->print( os, indent );
139 os << std::endl;
140 }
141 }
142
143 namespace {
144 void makeExprList( const AltList &in, std::list< Expression* > &out ) {
145 for ( AltList::const_iterator i = in.begin(); i != in.end(); ++i ) {
146 out.push_back( i->expr->clone() );
147 }
148 }
149
150 struct PruneStruct {
151 bool isAmbiguous;
152 AltList::iterator candidate;
153 PruneStruct() {}
154 PruneStruct( AltList::iterator candidate ): isAmbiguous( false ), candidate( candidate ) {}
155 };
156
157 /// Prunes a list of alternatives down to those that have the minimum conversion cost for a given return type; skips ambiguous interpretations
158 template< typename InputIterator, typename OutputIterator >
159 void pruneAlternatives( InputIterator begin, InputIterator end, OutputIterator out ) {
160 // select the alternatives that have the minimum conversion cost for a particular set of result types
161 std::map< std::string, PruneStruct > selected;
162 for ( AltList::iterator candidate = begin; candidate != end; ++candidate ) {
163 PruneStruct current( candidate );
164 std::string mangleName;
165 {
166 Type * newType = candidate->expr->get_result()->clone();
167 candidate->env.apply( newType );
168 mangleName = SymTab::Mangler::mangle( newType );
169 delete newType;
170 }
171 std::map< std::string, PruneStruct >::iterator mapPlace = selected.find( mangleName );
172 if ( mapPlace != selected.end() ) {
173 if ( candidate->cost < mapPlace->second.candidate->cost ) {
174 PRINT(
175 std::cerr << "cost " << candidate->cost << " beats " << mapPlace->second.candidate->cost << std::endl;
176 )
177 selected[ mangleName ] = current;
178 } else if ( candidate->cost == mapPlace->second.candidate->cost ) {
179 // if one of the candidates contains a deleted identifier, can pick the other, since
180 // deleted expressions should not be ambiguous if there is another option that is at least as good
181 if ( findDeletedExpr( candidate->expr ) ) {
182 // do nothing
183 PRINT( std::cerr << "candidate is deleted" << std::endl; )
184 } else if ( findDeletedExpr( mapPlace->second.candidate->expr ) ) {
185 PRINT( std::cerr << "current is deleted" << std::endl; )
186 selected[ mangleName ] = current;
187 } else {
188 PRINT(
189 std::cerr << "marking ambiguous" << std::endl;
190 )
191 mapPlace->second.isAmbiguous = true;
192 }
193 } else {
194 PRINT(
195 std::cerr << "cost " << candidate->cost << " loses to " << mapPlace->second.candidate->cost << std::endl;
196 )
197 }
198 } else {
199 selected[ mangleName ] = current;
200 }
201 }
202
203 // accept the alternatives that were unambiguous
204 for ( std::map< std::string, PruneStruct >::iterator target = selected.begin(); target != selected.end(); ++target ) {
205 if ( ! target->second.isAmbiguous ) {
206 Alternative &alt = *target->second.candidate;
207 alt.env.applyFree( alt.expr->get_result() );
208 *out++ = alt;
209 }
210 }
211 }
212
213 void renameTypes( Expression *expr ) {
214 renameTyVars( expr->result );
215 }
216 } // namespace
217
218 void referenceToRvalueConversion( Expression *& expr, Cost & cost ) {
219 if ( dynamic_cast< ReferenceType * >( expr->get_result() ) ) {
220 // cast away reference from expr
221 expr = new CastExpr( expr, expr->get_result()->stripReferences()->clone() );
222 cost.incReference();
223 }
224 }
225
226 template< typename InputIterator, typename OutputIterator >
227 void AlternativeFinder::findSubExprs( InputIterator begin, InputIterator end, OutputIterator out ) {
228 while ( begin != end ) {
229 AlternativeFinder finder( indexer, env );
230 finder.findWithAdjustment( *begin );
231 // XXX either this
232 //Designators::fixDesignations( finder, (*begin++)->get_argName() );
233 // or XXX this
234 begin++;
235 PRINT(
236 std::cerr << "findSubExprs" << std::endl;
237 printAlts( finder.alternatives, std::cerr );
238 )
239 *out++ = finder;
240 }
241 }
242
243 AlternativeFinder::AlternativeFinder( const SymTab::Indexer &indexer, const TypeEnvironment &env )
244 : indexer( indexer ), env( env ) {
245 }
246
247 void AlternativeFinder::find( Expression *expr, ResolvMode mode ) {
248 PassVisitor<Finder> finder( *this );
249 expr->accept( finder );
250 if ( mode.failFast && alternatives.empty() ) {
251 PRINT(
252 std::cerr << "No reasonable alternatives for expression " << expr << std::endl;
253 )
254 SemanticError( expr, "No reasonable alternatives for expression " );
255 }
256 if ( mode.resolveAssns || mode.prune ) {
257 // trim candidates just to those where the assertions resolve
258 // - necessary pre-requisite to pruning
259 AltList candidates;
260 for ( unsigned i = 0; i < alternatives.size(); ++i ) {
261 resolveAssertions( alternatives[i], indexer, candidates );
262 }
263 // fail early if none such
264 if ( mode.failFast && candidates.empty() ) {
265 std::ostringstream stream;
266 stream << "No resolvable alternatives for expression " << expr << "\n"
267 << "Alternatives with failing assertions are:\n";
268 printAlts( alternatives, stream, 1 );
269 SemanticError( expr->location, stream.str() );
270 }
271 // reset alternatives
272 alternatives = std::move( candidates );
273 }
274 if ( mode.prune ) {
275 auto oldsize = alternatives.size();
276 PRINT(
277 std::cerr << "alternatives before prune:" << std::endl;
278 printAlts( alternatives, std::cerr );
279 )
280 AltList pruned;
281 pruneAlternatives( alternatives.begin(), alternatives.end(), back_inserter( pruned ) );
282 if ( mode.failFast && pruned.empty() ) {
283 std::ostringstream stream;
284 AltList winners;
285 findMinCost( alternatives.begin(), alternatives.end(), back_inserter( winners ) );
286 stream << "Cannot choose between " << winners.size() << " alternatives for expression\n";
287 expr->print( stream );
288 stream << " Alternatives are:\n";
289 printAlts( winners, stream, 1 );
290 SemanticError( expr->location, stream.str() );
291 }
292 alternatives = move(pruned);
293 PRINT(
294 std::cerr << "there are " << oldsize << " alternatives before elimination" << std::endl;
295 )
296 PRINT(
297 std::cerr << "there are " << alternatives.size() << " alternatives after elimination" << std::endl;
298 )
299 }
300 // adjust types after pruning so that types substituted by pruneAlternatives are correctly adjusted
301 if ( mode.adjust ) {
302 for ( Alternative& i : alternatives ) {
303 adjustExprType( i.expr->get_result(), i.env, indexer );
304 }
305 }
306
307 // Central location to handle gcc extension keyword, etc. for all expression types.
308 for ( Alternative &iter: alternatives ) {
309 iter.expr->set_extension( expr->get_extension() );
310 iter.expr->location = expr->location;
311 } // for
312 }
313
314 void AlternativeFinder::findWithAdjustment( Expression *expr ) {
315 find( expr, ResolvMode::withAdjustment() );
316 }
317
318 void AlternativeFinder::findWithoutPrune( Expression * expr ) {
319 find( expr, ResolvMode::withoutPrune() );
320 }
321
322 void AlternativeFinder::maybeFind( Expression * expr ) {
323 find( expr, ResolvMode::withoutFailFast() );
324 }
325
326 void AlternativeFinder::Finder::addAnonConversions( const Alternative & alt ) {
327 // adds anonymous member interpretations whenever an aggregate value type is seen.
328 // it's okay for the aggregate expression to have reference type -- cast it to the base type to treat the aggregate as the referenced value
329 std::unique_ptr<Expression> aggrExpr( alt.expr->clone() );
330 alt.env.apply( aggrExpr->result );
331 Type * aggrType = aggrExpr->result;
332 if ( dynamic_cast< ReferenceType * >( aggrType ) ) {
333 aggrType = aggrType->stripReferences();
334 aggrExpr.reset( new CastExpr( aggrExpr.release(), aggrType->clone() ) );
335 }
336
337 if ( StructInstType *structInst = dynamic_cast< StructInstType* >( aggrExpr->result ) ) {
338 addAggMembers( structInst, aggrExpr.get(), alt, alt.cost+Cost::safe, "" );
339 } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( aggrExpr->result ) ) {
340 addAggMembers( unionInst, aggrExpr.get(), alt, alt.cost+Cost::safe, "" );
341 } // if
342 }
343
344 template< typename StructOrUnionType >
345 void AlternativeFinder::Finder::addAggMembers( StructOrUnionType *aggInst, Expression *expr, const Alternative& alt, const Cost &newCost, const std::string & name ) {
346 std::list< Declaration* > members;
347 aggInst->lookup( name, members );
348
349 for ( Declaration * decl : members ) {
350 if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType* >( decl ) ) {
351 // addAnonAlternatives uses vector::push_back, which invalidates references to existing elements, so
352 // can't construct in place and use vector::back
353 Alternative newAlt{ alt, new MemberExpr{ dwt, expr->clone() }, newCost };
354 renameTypes( newAlt.expr );
355 addAnonConversions( newAlt ); // add anonymous member interpretations whenever an aggregate value type is seen as a member expression.
356 alternatives.push_back( std::move(newAlt) );
357 } else {
358 assert( false );
359 }
360 }
361 }
362
363 void AlternativeFinder::Finder::addTupleMembers( TupleType *tupleType, Expression *expr, const Alternative &alt, const Cost &newCost, Expression *member ) {
364 if ( ConstantExpr * constantExpr = dynamic_cast< ConstantExpr * >( member ) ) {
365 // get the value of the constant expression as an int, must be between 0 and the length of the tuple type to have meaning
366 auto val = constantExpr->intValue();
367 std::string tmp;
368 if ( val >= 0 && (unsigned long long)val < tupleType->size() ) {
369 alternatives.push_back( Alternative{
370 alt, new TupleIndexExpr( expr->clone(), val ), newCost } );
371 } // if
372 } // if
373 }
374
375 void AlternativeFinder::Finder::postvisit( ApplicationExpr *applicationExpr ) {
376 alternatives.push_back( Alternative{ applicationExpr->clone(), env } );
377 }
378
379 Cost computeConversionCost( Type * actualType, Type * formalType, const SymTab::Indexer &indexer, const TypeEnvironment & env ) {
380 PRINT(
381 std::cerr << std::endl << "converting ";
382 actualType->print( std::cerr, 8 );
383 std::cerr << std::endl << " to ";
384 formalType->print( std::cerr, 8 );
385 std::cerr << std::endl << "environment is: ";
386 env.print( std::cerr, 8 );
387 std::cerr << std::endl;
388 )
389 Cost convCost = conversionCost( actualType, formalType, indexer, env );
390 PRINT(
391 std::cerr << std::endl << "cost is " << convCost << std::endl;
392 )
393 if ( convCost == Cost::infinity ) {
394 return convCost;
395 }
396 convCost.incPoly( polyCost( formalType, env, indexer ) + polyCost( actualType, env, indexer ) );
397 PRINT(
398 std::cerr << "cost with polycost is " << convCost << std::endl;
399 )
400 return convCost;
401 }
402
403 Cost computeExpressionConversionCost( Expression *& actualExpr, Type * formalType, const SymTab::Indexer &indexer, const TypeEnvironment & env ) {
404 Cost convCost = computeConversionCost( actualExpr->result, formalType, indexer, env );
405
406 // if there is a non-zero conversion cost, ignoring poly cost, then the expression requires conversion.
407 // ignore poly cost for now, since this requires resolution of the cast to infer parameters and this
408 // does not currently work for the reason stated below.
409 Cost tmpCost = convCost;
410 tmpCost.incPoly( -tmpCost.get_polyCost() );
411 if ( tmpCost != Cost::zero ) {
412 Type *newType = formalType->clone();
413 env.apply( newType );
414 actualExpr = new CastExpr( actualExpr, newType );
415 // xxx - SHOULD be able to resolve this cast, but at the moment pointers are not castable to zero_t, but are implicitly convertible. This is clearly
416 // inconsistent, once this is fixed it should be possible to resolve the cast.
417 // xxx - this isn't working, it appears because type1 (the formal type) is seen as widenable, but it shouldn't be, because this makes the conversion from DT* to DT* since commontype(zero_t, DT*) is DT*, rather than just nothing.
418
419 // AlternativeFinder finder( indexer, env );
420 // finder.findWithAdjustment( actualExpr );
421 // assertf( finder.get_alternatives().size() > 0, "Somehow castable expression failed to find alternatives." );
422 // assertf( finder.get_alternatives().size() == 1, "Somehow got multiple alternatives for known cast expression." );
423 // Alternative & alt = finder.get_alternatives().front();
424 // delete actualExpr;
425 // actualExpr = alt.expr->clone();
426 }
427 return convCost;
428 }
429
430 Cost computeApplicationConversionCost( Alternative &alt, const SymTab::Indexer &indexer ) {
431 ApplicationExpr *appExpr = strict_dynamic_cast< ApplicationExpr* >( alt.expr );
432 PointerType *pointer = strict_dynamic_cast< PointerType* >( appExpr->function->result );
433 FunctionType *function = strict_dynamic_cast< FunctionType* >( pointer->base );
434
435 Cost convCost = Cost::zero;
436 std::list< DeclarationWithType* >& formals = function->parameters;
437 std::list< DeclarationWithType* >::iterator formal = formals.begin();
438 std::list< Expression* >& actuals = appExpr->args;
439
440 for ( Expression*& actualExpr : actuals ) {
441 Type * actualType = actualExpr->result;
442 PRINT(
443 std::cerr << "actual expression:" << std::endl;
444 actualExpr->print( std::cerr, 8 );
445 std::cerr << "--- results are" << std::endl;
446 actualType->print( std::cerr, 8 );
447 )
448 if ( formal == formals.end() ) {
449 if ( function->isVarArgs ) {
450 convCost.incUnsafe();
451 PRINT( std::cerr << "end of formals with varargs function: inc unsafe: " << convCost << std::endl; ; )
452 // convert reference-typed expressions to value-typed expressions
453 referenceToRvalueConversion( actualExpr, convCost );
454 continue;
455 } else {
456 return Cost::infinity;
457 }
458 }
459 if ( DefaultArgExpr * def = dynamic_cast< DefaultArgExpr * >( actualExpr ) ) {
460 // default arguments should be free - don't include conversion cost.
461 // Unwrap them here because they are not relevant to the rest of the system.
462 actualExpr = def->expr;
463 ++formal;
464 continue;
465 }
466 // mark conversion cost to formal and also specialization cost of formal type
467 Type * formalType = (*formal)->get_type();
468 convCost += computeExpressionConversionCost( actualExpr, formalType, indexer, alt.env );
469 convCost.decSpec( specCost( formalType ) );
470 ++formal; // can't be in for-loop update because of the continue
471 }
472 if ( formal != formals.end() ) {
473 return Cost::infinity;
474 }
475
476 // specialization cost of return types can't be accounted for directly, it disables
477 // otherwise-identical calls, like this example based on auto-newline in the I/O lib:
478 //
479 // forall(otype OS) {
480 // void ?|?(OS&, int); // with newline
481 // OS& ?|?(OS&, int); // no newline, always chosen due to more specialization
482 // }
483
484 // mark type variable and specialization cost of forall clause
485 convCost.incVar( function->forall.size() );
486 for ( TypeDecl* td : function->forall ) {
487 convCost.decSpec( td->assertions.size() );
488 }
489
490 // xxx -- replace with new costs in resolver
491 for ( InferredParams::const_iterator assert = appExpr->inferParams.begin(); assert != appExpr->inferParams.end(); ++assert ) {
492 convCost += computeConversionCost( assert->second.actualType, assert->second.formalType, indexer, alt.env );
493 }
494
495 return convCost;
496 }
497
498 /// Adds type variables to the open variable set and marks their assertions
499 void makeUnifiableVars( Type *type, OpenVarSet &unifiableVars, AssertionSet &needAssertions ) {
500 for ( Type::ForallList::const_iterator tyvar = type->forall.begin(); tyvar != type->forall.end(); ++tyvar ) {
501 unifiableVars[ (*tyvar)->get_name() ] = TypeDecl::Data{ *tyvar };
502 for ( std::list< DeclarationWithType* >::iterator assert = (*tyvar)->assertions.begin(); assert != (*tyvar)->assertions.end(); ++assert ) {
503 needAssertions[ *assert ].isUsed = true;
504 }
505 }
506 }
507
508 /// Unique identifier for matching expression resolutions to their requesting expression
509 UniqueId globalResnSlot = 0;
510
511 template< typename OutputIterator >
512 void AlternativeFinder::Finder::inferParameters( Alternative &newAlt, OutputIterator out ) {
513 // Set need bindings for any unbound assertions
514 UniqueId crntResnSlot = 0; // matching ID for this expression's assertions
515 for ( auto& assn : newAlt.need ) {
516 // skip already-matched assertions
517 if ( assn.info.resnSlot != 0 ) continue;
518 // assign slot for expression if needed
519 if ( crntResnSlot == 0 ) { crntResnSlot = ++globalResnSlot; }
520 // fix slot to assertion
521 assn.info.resnSlot = crntResnSlot;
522 }
523 // pair slot to expression
524 if ( crntResnSlot != 0 ) { newAlt.expr->resnSlots.push_back( crntResnSlot ); }
525
526 // add to output list, assertion resolution is deferred
527 *out++ = newAlt;
528 }
529
530 /// Gets a default value from an initializer, nullptr if not present
531 ConstantExpr* getDefaultValue( Initializer* init ) {
532 if ( SingleInit* si = dynamic_cast<SingleInit*>( init ) ) {
533 if ( CastExpr* ce = dynamic_cast<CastExpr*>( si->value ) ) {
534 return dynamic_cast<ConstantExpr*>( ce->arg );
535 } else {
536 return dynamic_cast<ConstantExpr*>( si->value );
537 }
538 }
539 return nullptr;
540 }
541
542 /// State to iteratively build a match of parameter expressions to arguments
543 struct ArgPack {
544 std::size_t parent; ///< Index of parent pack
545 std::unique_ptr<Expression> expr; ///< The argument stored here
546 Cost cost; ///< The cost of this argument
547 TypeEnvironment env; ///< Environment for this pack
548 AssertionSet need; ///< Assertions outstanding for this pack
549 AssertionSet have; ///< Assertions found for this pack
550 OpenVarSet openVars; ///< Open variables for this pack
551 unsigned nextArg; ///< Index of next argument in arguments list
552 unsigned tupleStart; ///< Number of tuples that start at this index
553 unsigned nextExpl; ///< Index of next exploded element
554 unsigned explAlt; ///< Index of alternative for nextExpl > 0
555
556 ArgPack()
557 : parent(0), expr(), cost(Cost::zero), env(), need(), have(), openVars(), nextArg(0),
558 tupleStart(0), nextExpl(0), explAlt(0) {}
559
560 ArgPack(const TypeEnvironment& env, const AssertionSet& need, const AssertionSet& have,
561 const OpenVarSet& openVars)
562 : parent(0), expr(), cost(Cost::zero), env(env), need(need), have(have),
563 openVars(openVars), nextArg(0), tupleStart(0), nextExpl(0), explAlt(0) {}
564
565 ArgPack(std::size_t parent, Expression* expr, TypeEnvironment&& env, AssertionSet&& need,
566 AssertionSet&& have, OpenVarSet&& openVars, unsigned nextArg,
567 unsigned tupleStart = 0, Cost cost = Cost::zero, unsigned nextExpl = 0,
568 unsigned explAlt = 0 )
569 : parent(parent), expr(expr->clone()), cost(cost), env(move(env)), need(move(need)),
570 have(move(have)), openVars(move(openVars)), nextArg(nextArg), tupleStart(tupleStart),
571 nextExpl(nextExpl), explAlt(explAlt) {}
572
573 ArgPack(const ArgPack& o, TypeEnvironment&& env, AssertionSet&& need, AssertionSet&& have,
574 OpenVarSet&& openVars, unsigned nextArg, Cost added )
575 : parent(o.parent), expr(o.expr ? o.expr->clone() : nullptr), cost(o.cost + added),
576 env(move(env)), need(move(need)), have(move(have)), openVars(move(openVars)),
577 nextArg(nextArg), tupleStart(o.tupleStart), nextExpl(0), explAlt(0) {}
578
579 /// true iff this pack is in the middle of an exploded argument
580 bool hasExpl() const { return nextExpl > 0; }
581
582 /// Gets the list of exploded alternatives for this pack
583 const ExplodedActual& getExpl( const ExplodedArgs& args ) const {
584 return args[nextArg-1][explAlt];
585 }
586
587 /// Ends a tuple expression, consolidating the appropriate actuals
588 void endTuple( const std::vector<ArgPack>& packs ) {
589 // add all expressions in tuple to list, summing cost
590 std::list<Expression*> exprs;
591 const ArgPack* pack = this;
592 if ( expr ) { exprs.push_front( expr.release() ); }
593 while ( pack->tupleStart == 0 ) {
594 pack = &packs[pack->parent];
595 exprs.push_front( pack->expr->clone() );
596 cost += pack->cost;
597 }
598 // reset pack to appropriate tuple
599 expr.reset( new TupleExpr( exprs ) );
600 tupleStart = pack->tupleStart - 1;
601 parent = pack->parent;
602 }
603 };
604
605 /// Instantiates an argument to match a formal, returns false if no results left
606 bool instantiateArgument( Type* formalType, Initializer* initializer,
607 const ExplodedArgs& args, std::vector<ArgPack>& results, std::size_t& genStart,
608 const SymTab::Indexer& indexer, unsigned nTuples = 0 ) {
609 if ( TupleType * tupleType = dynamic_cast<TupleType*>( formalType ) ) {
610 // formalType is a TupleType - group actuals into a TupleExpr
611 ++nTuples;
612 for ( Type* type : *tupleType ) {
613 // xxx - dropping initializer changes behaviour from previous, but seems correct
614 // ^^^ need to handle the case where a tuple has a default argument
615 if ( ! instantiateArgument(
616 type, nullptr, args, results, genStart, indexer, nTuples ) )
617 return false;
618 nTuples = 0;
619 }
620 // re-consititute tuples for final generation
621 for ( auto i = genStart; i < results.size(); ++i ) {
622 results[i].endTuple( results );
623 }
624 return true;
625 } else if ( TypeInstType * ttype = Tuples::isTtype( formalType ) ) {
626 // formalType is a ttype, consumes all remaining arguments
627 // xxx - mixing default arguments with variadic??
628
629 // completed tuples; will be spliced to end of results to finish
630 std::vector<ArgPack> finalResults{};
631
632 // iterate until all results completed
633 std::size_t genEnd;
634 ++nTuples;
635 do {
636 genEnd = results.size();
637
638 // add another argument to results
639 for ( std::size_t i = genStart; i < genEnd; ++i ) {
640 auto nextArg = results[i].nextArg;
641
642 // use next element of exploded tuple if present
643 if ( results[i].hasExpl() ) {
644 const ExplodedActual& expl = results[i].getExpl( args );
645
646 unsigned nextExpl = results[i].nextExpl + 1;
647 if ( nextExpl == expl.exprs.size() ) {
648 nextExpl = 0;
649 }
650
651 results.emplace_back(
652 i, expl.exprs[results[i].nextExpl].get(), copy(results[i].env),
653 copy(results[i].need), copy(results[i].have),
654 copy(results[i].openVars), nextArg, nTuples, Cost::zero, nextExpl,
655 results[i].explAlt );
656
657 continue;
658 }
659
660 // finish result when out of arguments
661 if ( nextArg >= args.size() ) {
662 ArgPack newResult{
663 results[i].env, results[i].need, results[i].have,
664 results[i].openVars };
665 newResult.nextArg = nextArg;
666 Type* argType;
667
668 if ( nTuples > 0 || ! results[i].expr ) {
669 // first iteration or no expression to clone,
670 // push empty tuple expression
671 newResult.parent = i;
672 std::list<Expression*> emptyList;
673 newResult.expr.reset( new TupleExpr( emptyList ) );
674 argType = newResult.expr->get_result();
675 } else {
676 // clone result to collect tuple
677 newResult.parent = results[i].parent;
678 newResult.cost = results[i].cost;
679 newResult.tupleStart = results[i].tupleStart;
680 newResult.expr.reset( results[i].expr->clone() );
681 argType = newResult.expr->get_result();
682
683 if ( results[i].tupleStart > 0 && Tuples::isTtype( argType ) ) {
684 // the case where a ttype value is passed directly is special,
685 // e.g. for argument forwarding purposes
686 // xxx - what if passing multiple arguments, last of which is
687 // ttype?
688 // xxx - what would happen if unify was changed so that unifying
689 // tuple
690 // types flattened both before unifying lists? then pass in
691 // TupleType (ttype) below.
692 --newResult.tupleStart;
693 } else {
694 // collapse leftover arguments into tuple
695 newResult.endTuple( results );
696 argType = newResult.expr->get_result();
697 }
698 }
699
700 // check unification for ttype before adding to final
701 if ( unify( ttype, argType, newResult.env, newResult.need, newResult.have,
702 newResult.openVars, indexer ) ) {
703 finalResults.push_back( move(newResult) );
704 }
705
706 continue;
707 }
708
709 // add each possible next argument
710 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
711 const ExplodedActual& expl = args[nextArg][j];
712
713 // fresh copies of parent parameters for this iteration
714 TypeEnvironment env = results[i].env;
715 OpenVarSet openVars = results[i].openVars;
716
717 env.addActual( expl.env, openVars );
718
719 // skip empty tuple arguments by (near-)cloning parent into next gen
720 if ( expl.exprs.empty() ) {
721 results.emplace_back(
722 results[i], move(env), copy(results[i].need),
723 copy(results[i].have), move(openVars), nextArg + 1, expl.cost );
724
725 continue;
726 }
727
728 // add new result
729 results.emplace_back(
730 i, expl.exprs.front().get(), move(env), copy(results[i].need),
731 copy(results[i].have), move(openVars), nextArg + 1,
732 nTuples, expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
733 }
734 }
735
736 // reset for next round
737 genStart = genEnd;
738 nTuples = 0;
739 } while ( genEnd != results.size() );
740
741 // splice final results onto results
742 for ( std::size_t i = 0; i < finalResults.size(); ++i ) {
743 results.push_back( move(finalResults[i]) );
744 }
745 return ! finalResults.empty();
746 }
747
748 // iterate each current subresult
749 std::size_t genEnd = results.size();
750 for ( std::size_t i = genStart; i < genEnd; ++i ) {
751 auto nextArg = results[i].nextArg;
752
753 // use remainder of exploded tuple if present
754 if ( results[i].hasExpl() ) {
755 const ExplodedActual& expl = results[i].getExpl( args );
756 Expression* expr = expl.exprs[results[i].nextExpl].get();
757
758 TypeEnvironment env = results[i].env;
759 AssertionSet need = results[i].need, have = results[i].have;
760 OpenVarSet openVars = results[i].openVars;
761
762 Type* actualType = expr->get_result();
763
764 PRINT(
765 std::cerr << "formal type is ";
766 formalType->print( std::cerr );
767 std::cerr << std::endl << "actual type is ";
768 actualType->print( std::cerr );
769 std::cerr << std::endl;
770 )
771
772 if ( unify( formalType, actualType, env, need, have, openVars, indexer ) ) {
773 unsigned nextExpl = results[i].nextExpl + 1;
774 if ( nextExpl == expl.exprs.size() ) {
775 nextExpl = 0;
776 }
777
778 results.emplace_back(
779 i, expr, move(env), move(need), move(have), move(openVars), nextArg,
780 nTuples, Cost::zero, nextExpl, results[i].explAlt );
781 }
782
783 continue;
784 }
785
786 // use default initializers if out of arguments
787 if ( nextArg >= args.size() ) {
788 if ( ConstantExpr* cnstExpr = getDefaultValue( initializer ) ) {
789 if ( Constant* cnst = dynamic_cast<Constant*>( cnstExpr->get_constant() ) ) {
790 TypeEnvironment env = results[i].env;
791 AssertionSet need = results[i].need, have = results[i].have;
792 OpenVarSet openVars = results[i].openVars;
793
794 if ( unify( formalType, cnst->get_type(), env, need, have, openVars,
795 indexer ) ) {
796 results.emplace_back(
797 i, new DefaultArgExpr( cnstExpr ), move(env), move(need), move(have),
798 move(openVars), nextArg, nTuples );
799 }
800 }
801 }
802
803 continue;
804 }
805
806 // Check each possible next argument
807 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
808 const ExplodedActual& expl = args[nextArg][j];
809
810 // fresh copies of parent parameters for this iteration
811 TypeEnvironment env = results[i].env;
812 AssertionSet need = results[i].need, have = results[i].have;
813 OpenVarSet openVars = results[i].openVars;
814
815 env.addActual( expl.env, openVars );
816
817 // skip empty tuple arguments by (near-)cloning parent into next gen
818 if ( expl.exprs.empty() ) {
819 results.emplace_back(
820 results[i], move(env), move(need), move(have), move(openVars),
821 nextArg + 1, expl.cost );
822
823 continue;
824 }
825
826 // consider only first exploded actual
827 Expression* expr = expl.exprs.front().get();
828 Type* actualType = expr->result->clone();
829
830 PRINT(
831 std::cerr << "formal type is ";
832 formalType->print( std::cerr );
833 std::cerr << std::endl << "actual type is ";
834 actualType->print( std::cerr );
835 std::cerr << std::endl;
836 )
837
838 // attempt to unify types
839 if ( unify( formalType, actualType, env, need, have, openVars, indexer ) ) {
840 // add new result
841 results.emplace_back(
842 i, expr, move(env), move(need), move(have), move(openVars), nextArg + 1,
843 nTuples, expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
844 }
845 }
846 }
847
848 // reset for next parameter
849 genStart = genEnd;
850
851 return genEnd != results.size();
852 }
853
854 template<typename OutputIterator>
855 void AlternativeFinder::Finder::validateFunctionAlternative( const Alternative &func, ArgPack& result,
856 const std::vector<ArgPack>& results, OutputIterator out ) {
857 ApplicationExpr *appExpr = new ApplicationExpr( func.expr->clone() );
858 // sum cost and accumulate actuals
859 std::list<Expression*>& args = appExpr->args;
860 Cost cost = func.cost;
861 const ArgPack* pack = &result;
862 while ( pack->expr ) {
863 args.push_front( pack->expr->clone() );
864 cost += pack->cost;
865 pack = &results[pack->parent];
866 }
867 // build and validate new alternative
868 Alternative newAlt{ appExpr, result.env, result.openVars, result.need, cost };
869 PRINT(
870 std::cerr << "instantiate function success: " << appExpr << std::endl;
871 std::cerr << "need assertions:" << std::endl;
872 printAssertionSet( result.need, std::cerr, 8 );
873 )
874 inferParameters( newAlt, out );
875 }
876
877 template<typename OutputIterator>
878 void AlternativeFinder::Finder::makeFunctionAlternatives( const Alternative &func,
879 FunctionType *funcType, const ExplodedArgs &args, OutputIterator out ) {
880 OpenVarSet funcOpenVars;
881 AssertionSet funcNeed, funcHave;
882 TypeEnvironment funcEnv( func.env );
883 makeUnifiableVars( funcType, funcOpenVars, funcNeed );
884 // add all type variables as open variables now so that those not used in the parameter
885 // list are still considered open.
886 funcEnv.add( funcType->forall );
887
888 if ( targetType && ! targetType->isVoid() && ! funcType->returnVals.empty() ) {
889 // attempt to narrow based on expected target type
890 Type * returnType = funcType->returnVals.front()->get_type();
891 if ( ! unify( returnType, targetType, funcEnv, funcNeed, funcHave, funcOpenVars,
892 indexer ) ) {
893 // unification failed, don't pursue this function alternative
894 return;
895 }
896 }
897
898 // iteratively build matches, one parameter at a time
899 std::vector<ArgPack> results;
900 results.push_back( ArgPack{ funcEnv, funcNeed, funcHave, funcOpenVars } );
901 std::size_t genStart = 0;
902
903 for ( DeclarationWithType* formal : funcType->parameters ) {
904 ObjectDecl* obj = strict_dynamic_cast< ObjectDecl* >( formal );
905 if ( ! instantiateArgument(
906 obj->type, obj->init, args, results, genStart, indexer ) )
907 return;
908 }
909
910 if ( funcType->get_isVarArgs() ) {
911 // append any unused arguments to vararg pack
912 std::size_t genEnd;
913 do {
914 genEnd = results.size();
915
916 // iterate results
917 for ( std::size_t i = genStart; i < genEnd; ++i ) {
918 auto nextArg = results[i].nextArg;
919
920 // use remainder of exploded tuple if present
921 if ( results[i].hasExpl() ) {
922 const ExplodedActual& expl = results[i].getExpl( args );
923
924 unsigned nextExpl = results[i].nextExpl + 1;
925 if ( nextExpl == expl.exprs.size() ) {
926 nextExpl = 0;
927 }
928
929 results.emplace_back(
930 i, expl.exprs[results[i].nextExpl].get(), copy(results[i].env),
931 copy(results[i].need), copy(results[i].have),
932 copy(results[i].openVars), nextArg, 0, Cost::zero, nextExpl,
933 results[i].explAlt );
934
935 continue;
936 }
937
938 // finish result when out of arguments
939 if ( nextArg >= args.size() ) {
940 validateFunctionAlternative( func, results[i], results, out );
941
942 continue;
943 }
944
945 // add each possible next argument
946 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
947 const ExplodedActual& expl = args[nextArg][j];
948
949 // fresh copies of parent parameters for this iteration
950 TypeEnvironment env = results[i].env;
951 OpenVarSet openVars = results[i].openVars;
952
953 env.addActual( expl.env, openVars );
954
955 // skip empty tuple arguments by (near-)cloning parent into next gen
956 if ( expl.exprs.empty() ) {
957 results.emplace_back(
958 results[i], move(env), copy(results[i].need),
959 copy(results[i].have), move(openVars), nextArg + 1, expl.cost );
960
961 continue;
962 }
963
964 // add new result
965 results.emplace_back(
966 i, expl.exprs.front().get(), move(env), copy(results[i].need),
967 copy(results[i].have), move(openVars), nextArg + 1, 0,
968 expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
969 }
970 }
971
972 genStart = genEnd;
973 } while ( genEnd != results.size() );
974 } else {
975 // filter out results that don't use all the arguments
976 for ( std::size_t i = genStart; i < results.size(); ++i ) {
977 ArgPack& result = results[i];
978 if ( ! result.hasExpl() && result.nextArg >= args.size() ) {
979 validateFunctionAlternative( func, result, results, out );
980 }
981 }
982 }
983 }
984
985 void AlternativeFinder::Finder::postvisit( UntypedExpr *untypedExpr ) {
986 AlternativeFinder funcFinder( indexer, env );
987 funcFinder.findWithAdjustment( untypedExpr->function );
988 // if there are no function alternatives, then proceeding is a waste of time.
989 // xxx - findWithAdjustment throws, so this check and others like it shouldn't be necessary.
990 if ( funcFinder.alternatives.empty() ) return;
991
992 std::vector< AlternativeFinder > argAlternatives;
993 altFinder.findSubExprs( untypedExpr->begin_args(), untypedExpr->end_args(),
994 back_inserter( argAlternatives ) );
995
996 // take care of possible tuple assignments
997 // if not tuple assignment, assignment is taken care of as a normal function call
998 Tuples::handleTupleAssignment( altFinder, untypedExpr, argAlternatives );
999
1000 // find function operators
1001 static NameExpr *opExpr = new NameExpr( "?()" );
1002 AlternativeFinder funcOpFinder( indexer, env );
1003 // it's ok if there aren't any defined function ops
1004 funcOpFinder.maybeFind( opExpr );
1005 PRINT(
1006 std::cerr << "known function ops:" << std::endl;
1007 printAlts( funcOpFinder.alternatives, std::cerr, 1 );
1008 )
1009
1010 // pre-explode arguments
1011 ExplodedArgs argExpansions;
1012 argExpansions.reserve( argAlternatives.size() );
1013
1014 for ( const AlternativeFinder& arg : argAlternatives ) {
1015 argExpansions.emplace_back();
1016 auto& argE = argExpansions.back();
1017 // argE.reserve( arg.alternatives.size() );
1018
1019 for ( const Alternative& actual : arg ) {
1020 argE.emplace_back( actual, indexer );
1021 }
1022 }
1023
1024 AltList candidates;
1025 SemanticErrorException errors;
1026 for ( AltList::iterator func = funcFinder.alternatives.begin(); func != funcFinder.alternatives.end(); ++func ) {
1027 try {
1028 PRINT(
1029 std::cerr << "working on alternative: " << std::endl;
1030 func->print( std::cerr, 8 );
1031 )
1032 // check if the type is pointer to function
1033 if ( PointerType *pointer = dynamic_cast< PointerType* >( func->expr->result->stripReferences() ) ) {
1034 if ( FunctionType *function = dynamic_cast< FunctionType* >( pointer->base ) ) {
1035 Alternative newFunc( *func );
1036 referenceToRvalueConversion( newFunc.expr, newFunc.cost );
1037 makeFunctionAlternatives( newFunc, function, argExpansions,
1038 std::back_inserter( candidates ) );
1039 }
1040 } else if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( func->expr->result->stripReferences() ) ) { // handle ftype (e.g. *? on function pointer)
1041 if ( const EqvClass *eqvClass = func->env.lookup( typeInst->name ) ) {
1042 if ( FunctionType *function = dynamic_cast< FunctionType* >( eqvClass->type ) ) {
1043 Alternative newFunc( *func );
1044 referenceToRvalueConversion( newFunc.expr, newFunc.cost );
1045 makeFunctionAlternatives( newFunc, function, argExpansions,
1046 std::back_inserter( candidates ) );
1047 } // if
1048 } // if
1049 }
1050 } catch ( SemanticErrorException &e ) {
1051 errors.append( e );
1052 }
1053 } // for
1054
1055 // try each function operator ?() with each function alternative
1056 if ( ! funcOpFinder.alternatives.empty() ) {
1057 // add exploded function alternatives to front of argument list
1058 std::vector<ExplodedActual> funcE;
1059 funcE.reserve( funcFinder.alternatives.size() );
1060 for ( const Alternative& actual : funcFinder ) {
1061 funcE.emplace_back( actual, indexer );
1062 }
1063 argExpansions.insert( argExpansions.begin(), move(funcE) );
1064
1065 for ( AltList::iterator funcOp = funcOpFinder.alternatives.begin();
1066 funcOp != funcOpFinder.alternatives.end(); ++funcOp ) {
1067 try {
1068 // check if type is a pointer to function
1069 if ( PointerType* pointer = dynamic_cast<PointerType*>(
1070 funcOp->expr->result->stripReferences() ) ) {
1071 if ( FunctionType* function =
1072 dynamic_cast<FunctionType*>( pointer->base ) ) {
1073 Alternative newFunc( *funcOp );
1074 referenceToRvalueConversion( newFunc.expr, newFunc.cost );
1075 makeFunctionAlternatives( newFunc, function, argExpansions,
1076 std::back_inserter( candidates ) );
1077 }
1078 }
1079 } catch ( SemanticErrorException &e ) {
1080 errors.append( e );
1081 }
1082 }
1083 }
1084
1085 // Implement SFINAE; resolution errors are only errors if there aren't any non-erroneous resolutions
1086 if ( candidates.empty() && ! errors.isEmpty() ) { throw errors; }
1087
1088 // compute conversionsion costs
1089 for ( Alternative& withFunc : candidates ) {
1090 Cost cvtCost = computeApplicationConversionCost( withFunc, indexer );
1091
1092 PRINT(
1093 ApplicationExpr *appExpr = strict_dynamic_cast< ApplicationExpr* >( withFunc.expr );
1094 PointerType *pointer = strict_dynamic_cast< PointerType* >( appExpr->function->result );
1095 FunctionType *function = strict_dynamic_cast< FunctionType* >( pointer->base );
1096 std::cerr << "Case +++++++++++++ " << appExpr->function << std::endl;
1097 std::cerr << "formals are:" << std::endl;
1098 printAll( function->parameters, std::cerr, 8 );
1099 std::cerr << "actuals are:" << std::endl;
1100 printAll( appExpr->args, std::cerr, 8 );
1101 std::cerr << "bindings are:" << std::endl;
1102 withFunc.env.print( std::cerr, 8 );
1103 std::cerr << "cost is: " << withFunc.cost << std::endl;
1104 std::cerr << "cost of conversion is:" << cvtCost << std::endl;
1105 )
1106 if ( cvtCost != Cost::infinity ) {
1107 withFunc.cvtCost = cvtCost;
1108 alternatives.push_back( withFunc );
1109 } // if
1110 } // for
1111
1112 candidates = move(alternatives);
1113
1114 // use a new list so that alternatives are not examined by addAnonConversions twice.
1115 AltList winners;
1116 findMinCost( candidates.begin(), candidates.end(), std::back_inserter( winners ) );
1117
1118 // function may return struct or union value, in which case we need to add alternatives
1119 // for implicit conversions to each of the anonymous members, must happen after findMinCost
1120 // since anon conversions are never the cheapest expression
1121 for ( const Alternative & alt : winners ) {
1122 addAnonConversions( alt );
1123 }
1124 spliceBegin( alternatives, winners );
1125
1126 if ( alternatives.empty() && targetType && ! targetType->isVoid() ) {
1127 // xxx - this is a temporary hack. If resolution is unsuccessful with a target type, try again without a
1128 // target type, since it will sometimes succeed when it wouldn't easily with target type binding. For example,
1129 // forall( otype T ) lvalue T ?[?]( T *, ptrdiff_t );
1130 // const char * x = "hello world";
1131 // unsigned char ch = x[0];
1132 // Fails with simple return type binding. First, T is bound to unsigned char, then (x: const char *) is unified
1133 // with unsigned char *, which fails because pointer base types must be unified exactly. The new resolver should
1134 // fix this issue in a more robust way.
1135 targetType = nullptr;
1136 postvisit( untypedExpr );
1137 }
1138 }
1139
1140 bool isLvalue( Expression *expr ) {
1141 // xxx - recurse into tuples?
1142 return expr->result && ( expr->result->get_lvalue() || dynamic_cast< ReferenceType * >( expr->result ) );
1143 }
1144
1145 void AlternativeFinder::Finder::postvisit( AddressExpr *addressExpr ) {
1146 AlternativeFinder finder( indexer, env );
1147 finder.find( addressExpr->get_arg() );
1148 for ( Alternative& alt : finder.alternatives ) {
1149 if ( isLvalue( alt.expr ) ) {
1150 alternatives.push_back(
1151 Alternative{ alt, new AddressExpr( alt.expr->clone() ), alt.cost } );
1152 } // if
1153 } // for
1154 }
1155
1156 void AlternativeFinder::Finder::postvisit( LabelAddressExpr * expr ) {
1157 alternatives.push_back( Alternative{ expr->clone(), env } );
1158 }
1159
1160 Expression * restructureCast( Expression * argExpr, Type * toType, bool isGenerated ) {
1161 if ( argExpr->get_result()->size() > 1 && ! toType->isVoid() && ! dynamic_cast<ReferenceType *>( toType ) ) {
1162 // Argument expression is a tuple and the target type is not void and not a reference type.
1163 // Cast each member of the tuple to its corresponding target type, producing the tuple of those
1164 // cast expressions. If there are more components of the tuple than components in the target type,
1165 // then excess components do not come out in the result expression (but UniqueExprs ensure that
1166 // side effects will still be done).
1167 if ( Tuples::maybeImpureIgnoreUnique( argExpr ) ) {
1168 // expressions which may contain side effects require a single unique instance of the expression.
1169 argExpr = new UniqueExpr( argExpr );
1170 }
1171 std::list< Expression * > componentExprs;
1172 for ( unsigned int i = 0; i < toType->size(); i++ ) {
1173 // cast each component
1174 TupleIndexExpr * idx = new TupleIndexExpr( argExpr->clone(), i );
1175 componentExprs.push_back( restructureCast( idx, toType->getComponent( i ), isGenerated ) );
1176 }
1177 delete argExpr;
1178 assert( componentExprs.size() > 0 );
1179 // produce the tuple of casts
1180 return new TupleExpr( componentExprs );
1181 } else {
1182 // handle normally
1183 CastExpr * ret = new CastExpr( argExpr, toType->clone() );
1184 ret->isGenerated = isGenerated;
1185 return ret;
1186 }
1187 }
1188
1189 void AlternativeFinder::Finder::postvisit( CastExpr *castExpr ) {
1190 Type *& toType = castExpr->get_result();
1191 assert( toType );
1192 toType = resolveTypeof( toType, indexer );
1193 SymTab::validateType( toType, &indexer );
1194 adjustExprType( toType, env, indexer );
1195
1196 AlternativeFinder finder( indexer, env );
1197 finder.targetType = toType;
1198 finder.findWithAdjustment( castExpr->arg );
1199
1200 AltList candidates;
1201 for ( Alternative & alt : finder.alternatives ) {
1202 AssertionSet needAssertions( alt.need.begin(), alt.need.end() );
1203 AssertionSet haveAssertions;
1204 OpenVarSet openVars{ alt.openVars };
1205
1206 alt.env.extractOpenVars( openVars );
1207
1208 // It's possible that a cast can throw away some values in a multiply-valued expression. (An example is a
1209 // cast-to-void, which casts from one value to zero.) Figure out the prefix of the subexpression results
1210 // that are cast directly. The candidate is invalid if it has fewer results than there are types to cast
1211 // to.
1212 int discardedValues = alt.expr->result->size() - castExpr->result->size();
1213 if ( discardedValues < 0 ) continue;
1214 // xxx - may need to go into tuple types and extract relevant types and use unifyList. Note that currently, this does not
1215 // allow casting a tuple to an atomic type (e.g. (int)([1, 2, 3]))
1216 // unification run for side-effects
1217 unify( castExpr->result, alt.expr->result, alt.env, needAssertions,
1218 haveAssertions, openVars, indexer );
1219 Cost thisCost = castCost( alt.expr->result, castExpr->result, indexer,
1220 alt.env );
1221 PRINT(
1222 std::cerr << "working on cast with result: " << castExpr->result << std::endl;
1223 std::cerr << "and expr type: " << alt.expr->result << std::endl;
1224 std::cerr << "env: " << alt.env << std::endl;
1225 )
1226 if ( thisCost != Cost::infinity ) {
1227 PRINT(
1228 std::cerr << "has finite cost." << std::endl;
1229 )
1230 // count one safe conversion for each value that is thrown away
1231 thisCost.incSafe( discardedValues );
1232 Alternative newAlt{
1233 restructureCast( alt.expr->clone(), toType, castExpr->isGenerated ),
1234 alt.env, openVars, needAssertions, alt.cost, alt.cost + thisCost };
1235 inferParameters( newAlt, back_inserter( candidates ) );
1236 } // if
1237 } // for
1238
1239 // findMinCost selects the alternatives with the lowest "cost" members, but has the side effect of copying the
1240 // cvtCost member to the cost member (since the old cost is now irrelevant). Thus, calling findMinCost twice
1241 // selects first based on argument cost, then on conversion cost.
1242 AltList minArgCost;
1243 findMinCost( candidates.begin(), candidates.end(), std::back_inserter( minArgCost ) );
1244 findMinCost( minArgCost.begin(), minArgCost.end(), std::back_inserter( alternatives ) );
1245 }
1246
1247 void AlternativeFinder::Finder::postvisit( VirtualCastExpr * castExpr ) {
1248 assertf( castExpr->get_result(), "Implicit virtual cast targets not yet supported." );
1249 AlternativeFinder finder( indexer, env );
1250 // don't prune here, since it's guaranteed all alternatives will have the same type
1251 finder.findWithoutPrune( castExpr->get_arg() );
1252 for ( Alternative & alt : finder.alternatives ) {
1253 alternatives.push_back( Alternative{
1254 alt, new VirtualCastExpr{ alt.expr->clone(), castExpr->get_result()->clone() },
1255 alt.cost } );
1256 }
1257 }
1258
1259 namespace {
1260 /// Gets name from untyped member expression (member must be NameExpr)
1261 const std::string& get_member_name( UntypedMemberExpr *memberExpr ) {
1262 if ( dynamic_cast< ConstantExpr * >( memberExpr->get_member() ) ) {
1263 SemanticError( memberExpr, "Indexed access to struct fields unsupported: " );
1264 } // if
1265 NameExpr * nameExpr = dynamic_cast< NameExpr * >( memberExpr->get_member() );
1266 assert( nameExpr );
1267 return nameExpr->get_name();
1268 }
1269 }
1270
1271 void AlternativeFinder::Finder::postvisit( UntypedMemberExpr *memberExpr ) {
1272 AlternativeFinder funcFinder( indexer, env );
1273 funcFinder.findWithAdjustment( memberExpr->get_aggregate() );
1274 for ( AltList::const_iterator agg = funcFinder.alternatives.begin(); agg != funcFinder.alternatives.end(); ++agg ) {
1275 // it's okay for the aggregate expression to have reference type -- cast it to the base type to treat the aggregate as the referenced value
1276 Cost cost = agg->cost;
1277 Expression * aggrExpr = agg->expr->clone();
1278 referenceToRvalueConversion( aggrExpr, cost );
1279 std::unique_ptr<Expression> guard( aggrExpr );
1280
1281 // find member of the given type
1282 if ( StructInstType *structInst = dynamic_cast< StructInstType* >( aggrExpr->get_result() ) ) {
1283 addAggMembers( structInst, aggrExpr, *agg, cost, get_member_name(memberExpr) );
1284 } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( aggrExpr->get_result() ) ) {
1285 addAggMembers( unionInst, aggrExpr, *agg, cost, get_member_name(memberExpr) );
1286 } else if ( TupleType * tupleType = dynamic_cast< TupleType * >( aggrExpr->get_result() ) ) {
1287 addTupleMembers( tupleType, aggrExpr, *agg, cost, memberExpr->get_member() );
1288 } // if
1289 } // for
1290 }
1291
1292 void AlternativeFinder::Finder::postvisit( MemberExpr *memberExpr ) {
1293 alternatives.push_back( Alternative{ memberExpr->clone(), env } );
1294 }
1295
1296 void AlternativeFinder::Finder::postvisit( NameExpr *nameExpr ) {
1297 std::list< SymTab::Indexer::IdData > declList;
1298 indexer.lookupId( nameExpr->name, declList );
1299 PRINT( std::cerr << "nameExpr is " << nameExpr->name << std::endl; )
1300 for ( auto & data : declList ) {
1301 Cost cost = Cost::zero;
1302 Expression * newExpr = data.combine( cost );
1303
1304 // addAnonAlternatives uses vector::push_back, which invalidates references to existing elements, so
1305 // can't construct in place and use vector::back
1306 Alternative newAlt{ newExpr, env, OpenVarSet{}, AssertionList{}, Cost::zero, cost };
1307 PRINT(
1308 std::cerr << "decl is ";
1309 data.id->print( std::cerr );
1310 std::cerr << std::endl;
1311 std::cerr << "newExpr is ";
1312 newExpr->print( std::cerr );
1313 std::cerr << std::endl;
1314 )
1315 renameTypes( newAlt.expr );
1316 addAnonConversions( newAlt ); // add anonymous member interpretations whenever an aggregate value type is seen as a name expression.
1317 alternatives.push_back( std::move(newAlt) );
1318 } // for
1319 }
1320
1321 void AlternativeFinder::Finder::postvisit( VariableExpr *variableExpr ) {
1322 // not sufficient to clone here, because variable's type may have changed
1323 // since the VariableExpr was originally created.
1324 alternatives.push_back( Alternative{ new VariableExpr{ variableExpr->var }, env } );
1325 }
1326
1327 void AlternativeFinder::Finder::postvisit( ConstantExpr *constantExpr ) {
1328 alternatives.push_back( Alternative{ constantExpr->clone(), env } );
1329 }
1330
1331 void AlternativeFinder::Finder::postvisit( SizeofExpr *sizeofExpr ) {
1332 if ( sizeofExpr->get_isType() ) {
1333 Type * newType = sizeofExpr->get_type()->clone();
1334 alternatives.push_back( Alternative{
1335 new SizeofExpr{ resolveTypeof( newType, indexer ) }, env } );
1336 } else {
1337 // find all alternatives for the argument to sizeof
1338 AlternativeFinder finder( indexer, env );
1339 finder.find( sizeofExpr->get_expr() );
1340 // find the lowest cost alternative among the alternatives, otherwise ambiguous
1341 AltList winners;
1342 findMinCost( finder.alternatives.begin(), finder.alternatives.end(), back_inserter( winners ) );
1343 if ( winners.size() != 1 ) {
1344 SemanticError( sizeofExpr->get_expr(), "Ambiguous expression in sizeof operand: " );
1345 } // if
1346 // return the lowest cost alternative for the argument
1347 Alternative &choice = winners.front();
1348 referenceToRvalueConversion( choice.expr, choice.cost );
1349 alternatives.push_back( Alternative{
1350 choice, new SizeofExpr( choice.expr->clone() ), Cost::zero } );
1351 } // if
1352 }
1353
1354 void AlternativeFinder::Finder::postvisit( AlignofExpr *alignofExpr ) {
1355 if ( alignofExpr->get_isType() ) {
1356 Type * newType = alignofExpr->get_type()->clone();
1357 alternatives.push_back( Alternative{
1358 new AlignofExpr{ resolveTypeof( newType, indexer ) }, env } );
1359 } else {
1360 // find all alternatives for the argument to sizeof
1361 AlternativeFinder finder( indexer, env );
1362 finder.find( alignofExpr->get_expr() );
1363 // find the lowest cost alternative among the alternatives, otherwise ambiguous
1364 AltList winners;
1365 findMinCost( finder.alternatives.begin(), finder.alternatives.end(), back_inserter( winners ) );
1366 if ( winners.size() != 1 ) {
1367 SemanticError( alignofExpr->get_expr(), "Ambiguous expression in alignof operand: " );
1368 } // if
1369 // return the lowest cost alternative for the argument
1370 Alternative &choice = winners.front();
1371 referenceToRvalueConversion( choice.expr, choice.cost );
1372 alternatives.push_back( Alternative{
1373 choice, new AlignofExpr{ choice.expr->clone() }, Cost::zero } );
1374 } // if
1375 }
1376
1377 template< typename StructOrUnionType >
1378 void AlternativeFinder::Finder::addOffsetof( StructOrUnionType *aggInst, const std::string &name ) {
1379 std::list< Declaration* > members;
1380 aggInst->lookup( name, members );
1381 for ( std::list< Declaration* >::const_iterator i = members.begin(); i != members.end(); ++i ) {
1382 if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType* >( *i ) ) {
1383 alternatives.push_back( Alternative{
1384 new OffsetofExpr{ aggInst->clone(), dwt }, env } );
1385 renameTypes( alternatives.back().expr );
1386 } else {
1387 assert( false );
1388 }
1389 }
1390 }
1391
1392 void AlternativeFinder::Finder::postvisit( UntypedOffsetofExpr *offsetofExpr ) {
1393 AlternativeFinder funcFinder( indexer, env );
1394 // xxx - resolveTypeof?
1395 if ( StructInstType *structInst = dynamic_cast< StructInstType* >( offsetofExpr->get_type() ) ) {
1396 addOffsetof( structInst, offsetofExpr->member );
1397 } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( offsetofExpr->get_type() ) ) {
1398 addOffsetof( unionInst, offsetofExpr->member );
1399 }
1400 }
1401
1402 void AlternativeFinder::Finder::postvisit( OffsetofExpr *offsetofExpr ) {
1403 alternatives.push_back( Alternative{ offsetofExpr->clone(), env } );
1404 }
1405
1406 void AlternativeFinder::Finder::postvisit( OffsetPackExpr *offsetPackExpr ) {
1407 alternatives.push_back( Alternative{ offsetPackExpr->clone(), env } );
1408 }
1409
1410 namespace {
1411 void resolveAttr( SymTab::Indexer::IdData data, FunctionType *function, Type *argType, const TypeEnvironment &env, AlternativeFinder & finder ) {
1412 // assume no polymorphism
1413 // assume no implicit conversions
1414 assert( function->get_parameters().size() == 1 );
1415 PRINT(
1416 std::cerr << "resolvAttr: funcDecl is ";
1417 data.id->print( std::cerr );
1418 std::cerr << " argType is ";
1419 argType->print( std::cerr );
1420 std::cerr << std::endl;
1421 )
1422 const SymTab::Indexer & indexer = finder.get_indexer();
1423 AltList & alternatives = finder.get_alternatives();
1424 if ( typesCompatibleIgnoreQualifiers( argType, function->get_parameters().front()->get_type(), indexer, env ) ) {
1425 Cost cost = Cost::zero;
1426 Expression * newExpr = data.combine( cost );
1427 alternatives.push_back( Alternative{
1428 new AttrExpr{ newExpr, argType->clone() }, env, OpenVarSet{},
1429 AssertionList{}, Cost::zero, cost } );
1430 for ( DeclarationWithType * retVal : function->returnVals ) {
1431 alternatives.back().expr->result = retVal->get_type()->clone();
1432 } // for
1433 } // if
1434 }
1435 }
1436
1437 void AlternativeFinder::Finder::postvisit( AttrExpr *attrExpr ) {
1438 // assume no 'pointer-to-attribute'
1439 NameExpr *nameExpr = dynamic_cast< NameExpr* >( attrExpr->get_attr() );
1440 assert( nameExpr );
1441 std::list< SymTab::Indexer::IdData > attrList;
1442 indexer.lookupId( nameExpr->get_name(), attrList );
1443 if ( attrExpr->get_isType() || attrExpr->get_expr() ) {
1444 for ( auto & data : attrList ) {
1445 DeclarationWithType * id = data.id;
1446 // check if the type is function
1447 if ( FunctionType *function = dynamic_cast< FunctionType* >( id->get_type() ) ) {
1448 // assume exactly one parameter
1449 if ( function->get_parameters().size() == 1 ) {
1450 if ( attrExpr->get_isType() ) {
1451 resolveAttr( data, function, attrExpr->get_type(), env, altFinder);
1452 } else {
1453 AlternativeFinder finder( indexer, env );
1454 finder.find( attrExpr->get_expr() );
1455 for ( AltList::iterator choice = finder.alternatives.begin(); choice != finder.alternatives.end(); ++choice ) {
1456 if ( choice->expr->get_result()->size() == 1 ) {
1457 resolveAttr(data, function, choice->expr->get_result(), choice->env, altFinder );
1458 } // fi
1459 } // for
1460 } // if
1461 } // if
1462 } // if
1463 } // for
1464 } else {
1465 for ( auto & data : attrList ) {
1466 Cost cost = Cost::zero;
1467 Expression * newExpr = data.combine( cost );
1468 alternatives.push_back( Alternative{
1469 newExpr, env, OpenVarSet{}, AssertionList{}, Cost::zero, cost } );
1470 renameTypes( alternatives.back().expr );
1471 } // for
1472 } // if
1473 }
1474
1475 void AlternativeFinder::Finder::postvisit( LogicalExpr *logicalExpr ) {
1476 AlternativeFinder firstFinder( indexer, env );
1477 firstFinder.findWithAdjustment( logicalExpr->get_arg1() );
1478 if ( firstFinder.alternatives.empty() ) return;
1479 AlternativeFinder secondFinder( indexer, env );
1480 secondFinder.findWithAdjustment( logicalExpr->get_arg2() );
1481 if ( secondFinder.alternatives.empty() ) return;
1482 for ( const Alternative & first : firstFinder.alternatives ) {
1483 for ( const Alternative & second : secondFinder.alternatives ) {
1484 TypeEnvironment compositeEnv{ first.env };
1485 compositeEnv.simpleCombine( second.env );
1486 OpenVarSet openVars{ first.openVars };
1487 mergeOpenVars( openVars, second.openVars );
1488 AssertionSet need;
1489 cloneAll( first.need, need );
1490 cloneAll( second.need, need );
1491
1492 LogicalExpr *newExpr = new LogicalExpr{
1493 first.expr->clone(), second.expr->clone(), logicalExpr->get_isAnd() };
1494 alternatives.push_back( Alternative{
1495 newExpr, std::move(compositeEnv), std::move(openVars),
1496 AssertionList( need.begin(), need.end() ), first.cost + second.cost } );
1497 }
1498 }
1499 }
1500
1501 void AlternativeFinder::Finder::postvisit( ConditionalExpr *conditionalExpr ) {
1502 // find alternatives for condition
1503 AlternativeFinder firstFinder( indexer, env );
1504 firstFinder.findWithAdjustment( conditionalExpr->arg1 );
1505 if ( firstFinder.alternatives.empty() ) return;
1506 // find alternatives for true expression
1507 AlternativeFinder secondFinder( indexer, env );
1508 secondFinder.findWithAdjustment( conditionalExpr->arg2 );
1509 if ( secondFinder.alternatives.empty() ) return;
1510 // find alterantives for false expression
1511 AlternativeFinder thirdFinder( indexer, env );
1512 thirdFinder.findWithAdjustment( conditionalExpr->arg3 );
1513 if ( thirdFinder.alternatives.empty() ) return;
1514 for ( const Alternative & first : firstFinder.alternatives ) {
1515 for ( const Alternative & second : secondFinder.alternatives ) {
1516 for ( const Alternative & third : thirdFinder.alternatives ) {
1517 TypeEnvironment compositeEnv{ first.env };
1518 compositeEnv.simpleCombine( second.env );
1519 compositeEnv.simpleCombine( third.env );
1520 OpenVarSet openVars{ first.openVars };
1521 mergeOpenVars( openVars, second.openVars );
1522 mergeOpenVars( openVars, third.openVars );
1523 AssertionSet need;
1524 cloneAll( first.need, need );
1525 cloneAll( second.need, need );
1526 cloneAll( third.need, need );
1527 AssertionSet have;
1528
1529 // unify true and false types, then infer parameters to produce new alternatives
1530 Type* commonType = nullptr;
1531 if ( unify( second.expr->result, third.expr->result, compositeEnv,
1532 need, have, openVars, indexer, commonType ) ) {
1533 ConditionalExpr *newExpr = new ConditionalExpr{
1534 first.expr->clone(), second.expr->clone(), third.expr->clone() };
1535 newExpr->result = commonType ? commonType : second.expr->result->clone();
1536 // convert both options to the conditional result type
1537 Cost cost = first.cost + second.cost + third.cost;
1538 cost += computeExpressionConversionCost(
1539 newExpr->arg2, newExpr->result, indexer, compositeEnv );
1540 cost += computeExpressionConversionCost(
1541 newExpr->arg3, newExpr->result, indexer, compositeEnv );
1542 // output alternative
1543 Alternative newAlt{
1544 newExpr, std::move(compositeEnv), std::move(openVars),
1545 AssertionList( need.begin(), need.end() ), cost };
1546 inferParameters( newAlt, back_inserter( alternatives ) );
1547 } // if
1548 } // for
1549 } // for
1550 } // for
1551 }
1552
1553 void AlternativeFinder::Finder::postvisit( CommaExpr *commaExpr ) {
1554 TypeEnvironment newEnv( env );
1555 Expression *newFirstArg = resolveInVoidContext( commaExpr->get_arg1(), indexer, newEnv );
1556 AlternativeFinder secondFinder( indexer, newEnv );
1557 secondFinder.findWithAdjustment( commaExpr->get_arg2() );
1558 for ( const Alternative & alt : secondFinder.alternatives ) {
1559 alternatives.push_back( Alternative{
1560 alt, new CommaExpr{ newFirstArg->clone(), alt.expr->clone() }, alt.cost } );
1561 } // for
1562 delete newFirstArg;
1563 }
1564
1565 void AlternativeFinder::Finder::postvisit( RangeExpr * rangeExpr ) {
1566 // resolve low and high, accept alternatives whose low and high types unify
1567 AlternativeFinder firstFinder( indexer, env );
1568 firstFinder.findWithAdjustment( rangeExpr->low );
1569 if ( firstFinder.alternatives.empty() ) return;
1570 AlternativeFinder secondFinder( indexer, env );
1571 secondFinder.findWithAdjustment( rangeExpr->high );
1572 if ( secondFinder.alternatives.empty() ) return;
1573 for ( const Alternative & first : firstFinder.alternatives ) {
1574 for ( const Alternative & second : secondFinder.alternatives ) {
1575 TypeEnvironment compositeEnv{ first.env };
1576 compositeEnv.simpleCombine( second.env );
1577 OpenVarSet openVars{ first.openVars };
1578 mergeOpenVars( openVars, second.openVars );
1579 AssertionSet need;
1580 cloneAll( first.need, need );
1581 cloneAll( second.need, need );
1582 AssertionSet have;
1583
1584 Type* commonType = nullptr;
1585 if ( unify( first.expr->result, second.expr->result, compositeEnv, need, have,
1586 openVars, indexer, commonType ) ) {
1587 RangeExpr * newExpr =
1588 new RangeExpr{ first.expr->clone(), second.expr->clone() };
1589 newExpr->result = commonType ? commonType : first.expr->result->clone();
1590 Alternative newAlt{
1591 newExpr, std::move(compositeEnv), std::move(openVars),
1592 AssertionList( need.begin(), need.end() ), first.cost + second.cost };
1593 inferParameters( newAlt, back_inserter( alternatives ) );
1594 } // if
1595 } // for
1596 } // for
1597 }
1598
1599 void AlternativeFinder::Finder::postvisit( UntypedTupleExpr *tupleExpr ) {
1600 std::vector< AlternativeFinder > subExprAlternatives;
1601 altFinder.findSubExprs( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end(),
1602 back_inserter( subExprAlternatives ) );
1603 std::vector< AltList > possibilities;
1604 combos( subExprAlternatives.begin(), subExprAlternatives.end(),
1605 back_inserter( possibilities ) );
1606 for ( const AltList& alts : possibilities ) {
1607 std::list< Expression * > exprs;
1608 makeExprList( alts, exprs );
1609
1610 TypeEnvironment compositeEnv;
1611 OpenVarSet openVars;
1612 AssertionSet need;
1613 for ( const Alternative& alt : alts ) {
1614 compositeEnv.simpleCombine( alt.env );
1615 mergeOpenVars( openVars, alt.openVars );
1616 cloneAll( alt.need, need );
1617 }
1618
1619 alternatives.push_back( Alternative{
1620 new TupleExpr{ exprs }, std::move(compositeEnv), std::move(openVars),
1621 AssertionList( need.begin(), need.end() ), sumCost( alts ) } );
1622 } // for
1623 }
1624
1625 void AlternativeFinder::Finder::postvisit( TupleExpr *tupleExpr ) {
1626 alternatives.push_back( Alternative{ tupleExpr->clone(), env } );
1627 }
1628
1629 void AlternativeFinder::Finder::postvisit( ImplicitCopyCtorExpr * impCpCtorExpr ) {
1630 alternatives.push_back( Alternative{ impCpCtorExpr->clone(), env } );
1631 }
1632
1633 void AlternativeFinder::Finder::postvisit( ConstructorExpr * ctorExpr ) {
1634 AlternativeFinder finder( indexer, env );
1635 // don't prune here, since it's guaranteed all alternatives will have the same type
1636 // (giving the alternatives different types is half of the point of ConstructorExpr nodes)
1637 finder.findWithoutPrune( ctorExpr->get_callExpr() );
1638 for ( Alternative & alt : finder.alternatives ) {
1639 alternatives.push_back( Alternative{
1640 alt, new ConstructorExpr( alt.expr->clone() ), alt.cost } );
1641 }
1642 }
1643
1644 void AlternativeFinder::Finder::postvisit( TupleIndexExpr *tupleExpr ) {
1645 alternatives.push_back( Alternative{ tupleExpr->clone(), env } );
1646 }
1647
1648 void AlternativeFinder::Finder::postvisit( TupleAssignExpr *tupleAssignExpr ) {
1649 alternatives.push_back( Alternative{ tupleAssignExpr->clone(), env } );
1650 }
1651
1652 void AlternativeFinder::Finder::postvisit( UniqueExpr *unqExpr ) {
1653 AlternativeFinder finder( indexer, env );
1654 finder.findWithAdjustment( unqExpr->get_expr() );
1655 for ( Alternative & alt : finder.alternatives ) {
1656 // ensure that the id is passed on to the UniqueExpr alternative so that the expressions are "linked"
1657 UniqueExpr * newUnqExpr = new UniqueExpr( alt.expr->clone(), unqExpr->get_id() );
1658 alternatives.push_back( Alternative{ alt, newUnqExpr, alt.cost } );
1659 }
1660 }
1661
1662 void AlternativeFinder::Finder::postvisit( StmtExpr *stmtExpr ) {
1663 StmtExpr * newStmtExpr = stmtExpr->clone();
1664 ResolvExpr::resolveStmtExpr( newStmtExpr, indexer );
1665 // xxx - this env is almost certainly wrong, and needs to somehow contain the combined environments from all of the statements in the stmtExpr...
1666 alternatives.push_back( Alternative{ newStmtExpr, env } );
1667 }
1668
1669 void AlternativeFinder::Finder::postvisit( UntypedInitExpr *initExpr ) {
1670 // handle each option like a cast
1671 AltList candidates;
1672 PRINT(
1673 std::cerr << "untyped init expr: " << initExpr << std::endl;
1674 )
1675 // O(N^2) checks of d-types with e-types
1676 for ( InitAlternative & initAlt : initExpr->get_initAlts() ) {
1677 Type * toType = resolveTypeof( initAlt.type->clone(), indexer );
1678 SymTab::validateType( toType, &indexer );
1679 adjustExprType( toType, env, indexer );
1680 // Ideally the call to findWithAdjustment could be moved out of the loop, but unfortunately it currently has to occur inside or else
1681 // polymorphic return types are not properly bound to the initialization type, since return type variables are only open for the duration of resolving
1682 // the UntypedExpr. This is only actually an issue in initialization contexts that allow more than one possible initialization type, but it is still suboptimal.
1683 AlternativeFinder finder( indexer, env );
1684 finder.targetType = toType;
1685 finder.findWithAdjustment( initExpr->expr );
1686 for ( Alternative & alt : finder.get_alternatives() ) {
1687 TypeEnvironment newEnv( alt.env );
1688 AssertionSet need;
1689 cloneAll( alt.need, need );
1690 AssertionSet have;
1691 OpenVarSet openVars( alt.openVars );
1692 // xxx - find things in env that don't have a "representative type" and claim
1693 // those are open vars?
1694 PRINT(
1695 std::cerr << " @ " << toType << " " << initAlt.designation << std::endl;
1696 )
1697 // It's possible that a cast can throw away some values in a multiply-valued
1698 // expression. (An example is a cast-to-void, which casts from one value to
1699 // zero.) Figure out the prefix of the subexpression results that are cast
1700 // directly. The candidate is invalid if it has fewer results than there are
1701 // types to cast to.
1702 int discardedValues = alt.expr->result->size() - toType->size();
1703 if ( discardedValues < 0 ) continue;
1704 // xxx - may need to go into tuple types and extract relevant types and use
1705 // unifyList. Note that currently, this does not allow casting a tuple to an
1706 // atomic type (e.g. (int)([1, 2, 3]))
1707
1708 // unification run for side-effects
1709 unify( toType, alt.expr->result, newEnv, need, have, openVars, indexer );
1710 // xxx - do some inspecting on this line... why isn't result bound to initAlt.type?
1711
1712 Cost thisCost = castCost( alt.expr->result, toType, indexer, newEnv );
1713 if ( thisCost != Cost::infinity ) {
1714 // count one safe conversion for each value that is thrown away
1715 thisCost.incSafe( discardedValues );
1716 Alternative newAlt{
1717 new InitExpr{
1718 restructureCast( alt.expr->clone(), toType, true ), initAlt.designation->clone() },
1719 std::move(newEnv), std::move(openVars),
1720 AssertionList( need.begin(), need.end() ), alt.cost, thisCost };
1721 inferParameters( newAlt, back_inserter( candidates ) );
1722 }
1723 }
1724 }
1725
1726 // findMinCost selects the alternatives with the lowest "cost" members, but has the side effect of copying the
1727 // cvtCost member to the cost member (since the old cost is now irrelevant). Thus, calling findMinCost twice
1728 // selects first based on argument cost, then on conversion cost.
1729 AltList minArgCost;
1730 findMinCost( candidates.begin(), candidates.end(), std::back_inserter( minArgCost ) );
1731 findMinCost( minArgCost.begin(), minArgCost.end(), std::back_inserter( alternatives ) );
1732 }
1733
1734 void AlternativeFinder::Finder::postvisit( InitExpr * ) {
1735 assertf( false, "AlternativeFinder should never see a resolved InitExpr." );
1736 }
1737
1738 void AlternativeFinder::Finder::postvisit( DeletedExpr * ) {
1739 assertf( false, "AlternativeFinder should never see a DeletedExpr." );
1740 }
1741
1742 void AlternativeFinder::Finder::postvisit( GenericExpr * ) {
1743 assertf( false, "_Generic is not yet supported." );
1744 }
1745} // namespace ResolvExpr
1746
1747// Local Variables: //
1748// tab-width: 4 //
1749// mode: c++ //
1750// compile-command: "make install" //
1751// End: //
Note: See TracBrowser for help on using the repository browser.