source: src/ResolvExpr/AlternativeFinder.cc@ fed6a0f

ADT ast-experimental
Last change on this file since fed6a0f was fed6a0f, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Header Clean-up: Moving more declarations to the header of the implementation file.

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