source: src/ResolvExpr/AlternativeFinder.cc@ b8524ca

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since b8524ca was 9d5089e, checked in by Aaron Moss <a3moss@…>, 6 years ago

Port CandidateFinder::makeFunctionCandidates() and deps

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