source: src/ResolvExpr/CandidateFinder.cpp@ 9d5089e

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 9d5089e was 9d5089e, checked in by Aaron Moss <a3moss@…>, 6 years ago

Port CandidateFinder::makeFunctionCandidates() and deps

  • Property mode set to 100644
File size: 46.6 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// CandidateFinder.cpp --
8//
9// Author : Aaron B. Moss
10// Created On : Wed Jun 5 14:30:00 2019
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Wed Jun 5 14:30:00 2019
13// Update Count : 1
14//
15
16#include "CandidateFinder.hpp"
17
18#include <deque>
19#include <iterator> // for back_inserter
20#include <sstream>
21#include <string>
22#include <unordered_map>
23#include <vector>
24
25#include "Candidate.hpp"
26#include "CompilationState.h"
27#include "Cost.h"
28#include "ExplodedArg.hpp"
29#include "Resolver.h"
30#include "SatisfyAssertions.hpp"
31#include "typeops.h" // for adjustExprType, conversionCost, polyCost, specCost
32#include "Unify.h"
33#include "AST/Expr.hpp"
34#include "AST/Node.hpp"
35#include "AST/Pass.hpp"
36#include "AST/Print.hpp"
37#include "AST/SymbolTable.hpp"
38#include "AST/Type.hpp"
39#include "SymTab/Mangler.h"
40#include "Tuples/Tuples.h" // for handleTupleAssignment
41
42#define PRINT( text ) if ( resolvep ) { text }
43
44namespace ResolvExpr {
45
46using std::move;
47
48/// partner to move that copies any copyable type
49template<typename T>
50T copy( const T & x ) { return x; }
51
52const ast::Expr * referenceToRvalueConversion( const ast::Expr * expr, Cost & cost ) {
53 if ( expr->result.as< ast::ReferenceType >() ) {
54 // cast away reference from expr
55 cost.incReference();
56 return new ast::CastExpr{ expr->location, expr, expr->result->stripReferences() };
57 }
58
59 return expr;
60}
61
62/// Unique identifier for matching expression resolutions to their requesting expression
63UniqueId globalResnSlot = 0;
64
65namespace {
66 /// First index is which argument, second is which alternative, third is which exploded element
67 using ExplodedArgs_new = std::deque< std::vector< ExplodedArg > >;
68
69 /// Returns a list of alternatives with the minimum cost in the given list
70 CandidateList findMinCost( const CandidateList & candidates ) {
71 CandidateList out;
72 Cost minCost = Cost::infinity;
73 for ( const CandidateRef & r : candidates ) {
74 if ( r->cost < minCost ) {
75 minCost = r->cost;
76 out.clear();
77 out.emplace_back( r );
78 } else if ( r->cost == minCost ) {
79 out.emplace_back( r );
80 }
81 }
82 return out;
83 }
84
85 /// Computes conversion cost between two types
86 Cost computeConversionCost(
87 const ast::Type * argType, const ast::Type * paramType, const ast::SymbolTable & symtab,
88 const ast::TypeEnvironment & env
89 ) {
90 PRINT(
91 std::cerr << std::endl << "converting ";
92 ast::print( std::cerr, argType, 2 );
93 std::cerr << std::endl << " to ";
94 ast::print( std::cerr, paramType, 2 );
95 std::cerr << std::endl << "environment is: ";
96 ast::print( std::cerr, env, 2 );
97 std::cerr << std::endl;
98 )
99 Cost convCost = conversionCost( argType, paramType, symtab, env );
100 PRINT(
101 std::cerr << std::endl << "cost is " << convCost << std::endl;
102 )
103 if ( convCost == Cost::infinity ) return convCost;
104 convCost.incPoly( polyCost( paramType, symtab, env ) + polyCost( argType, symtab, env ) );
105 PRINT(
106 std::cerr << "cost with polycost is " << convCost << std::endl;
107 )
108 return convCost;
109 }
110
111 /// Computes conversion cost for a given expression to a given type
112 const ast::Expr * computeExpressionConversionCost(
113 const ast::Expr * arg, const ast::Type * paramType, const ast::SymbolTable & symtab, const ast::TypeEnvironment & env, Cost & outCost
114 ) {
115 Cost convCost = computeConversionCost( arg->result, paramType, symtab, env );
116 outCost += convCost;
117
118 // If there is a non-zero conversion cost, ignoring poly cost, then the expression requires
119 // conversion. Ignore poly cost for now, since this requires resolution of the cast to
120 // infer parameters and this does not currently work for the reason stated below
121 Cost tmpCost = convCost;
122 tmpCost.incPoly( -tmpCost.get_polyCost() );
123 if ( tmpCost != Cost::zero ) {
124 ast::ptr< ast::Type > newType = paramType;
125 env.apply( newType );
126 return new ast::CastExpr{ arg->location, arg, newType };
127
128 // xxx - *should* be able to resolve this cast, but at the moment pointers are not
129 // castable to zero_t, but are implicitly convertible. This is clearly inconsistent,
130 // once this is fixed it should be possible to resolve the cast.
131 // xxx - this isn't working, it appears because type1 (parameter) is seen as widenable,
132 // but it shouldn't be because this makes the conversion from DT* to DT* since
133 // commontype(zero_t, DT*) is DT*, rather than nothing
134
135 // CandidateFinder finder{ symtab, env };
136 // finder.find( arg, ResolvMode::withAdjustment() );
137 // assertf( finder.candidates.size() > 0,
138 // "Somehow castable expression failed to find alternatives." );
139 // assertf( finder.candidates.size() == 1,
140 // "Somehow got multiple alternatives for known cast expression." );
141 // return finder.candidates.front()->expr;
142 }
143
144 return arg;
145 }
146
147 /// Computes conversion cost for a given candidate
148 Cost computeApplicationConversionCost(
149 CandidateRef cand, const ast::SymbolTable & symtab
150 ) {
151 auto appExpr = cand->expr.strict_as< ast::ApplicationExpr >();
152 auto pointer = appExpr->func->result.strict_as< ast::PointerType >();
153 auto function = pointer->base.strict_as< ast::FunctionType >();
154
155 Cost convCost = Cost::zero;
156 const auto & params = function->params;
157 auto param = params.begin();
158 auto & args = appExpr->args;
159
160 for ( unsigned i = 0; i < args.size(); ++i ) {
161 const ast::Type * argType = args[i]->result;
162 PRINT(
163 std::cerr << "arg expression:" << std::endl;
164 ast::print( std::cerr, args[i], 2 );
165 std::cerr << "--- results are" << std::endl;
166 ast::print( std::cerr, argType, 2 );
167 )
168
169 if ( param == params.end() ) {
170 if ( function->isVarArgs ) {
171 convCost.incUnsafe();
172 PRINT( std::cerr << "end of params with varargs function: inc unsafe: "
173 << convCost << std::endl; ; )
174 // convert reference-typed expressions into value-typed expressions
175 cand->expr = ast::mutate_field_index(
176 appExpr, &ast::ApplicationExpr::args, i,
177 referenceToRvalueConversion( args[i], convCost ) );
178 continue;
179 } else return Cost::infinity;
180 }
181
182 if ( auto def = args[i].as< ast::DefaultArgExpr >() ) {
183 // Default arguments should be free - don't include conversion cost.
184 // Unwrap them here because they are not relevant to the rest of the system
185 cand->expr = ast::mutate_field_index(
186 appExpr, &ast::ApplicationExpr::args, i, def->expr );
187 ++param;
188 continue;
189 }
190
191 // mark conversion cost and also specialization cost of param type
192 const ast::Type * paramType = (*param)->get_type();
193 cand->expr = ast::mutate_field_index(
194 appExpr, &ast::ApplicationExpr::args, i,
195 computeExpressionConversionCost(
196 args[i], paramType, symtab, cand->env, convCost ) );
197 convCost.decSpec( specCost( paramType ) );
198 ++param; // can't be in for-loop update because of the continue
199 }
200
201 if ( param != params.end() ) return Cost::infinity;
202
203 // specialization cost of return types can't be accounted for directly, it disables
204 // otherwise-identical calls, like this example based on auto-newline in the I/O lib:
205 //
206 // forall(otype OS) {
207 // void ?|?(OS&, int); // with newline
208 // OS& ?|?(OS&, int); // no newline, always chosen due to more specialization
209 // }
210
211 // mark type variable and specialization cost of forall clause
212 convCost.incVar( function->forall.size() );
213 for ( const ast::TypeDecl * td : function->forall ) {
214 convCost.decSpec( td->assertions.size() );
215 }
216
217 return convCost;
218 }
219
220 void makeUnifiableVars(
221 const ast::ParameterizedType * type, ast::OpenVarSet & unifiableVars,
222 ast::AssertionSet & need
223 ) {
224 for ( const ast::TypeDecl * tyvar : type->forall ) {
225 unifiableVars[ tyvar->name ] = ast::TypeDecl::Data{ tyvar };
226 for ( const ast::DeclWithType * assn : tyvar->assertions ) {
227 need[ assn ].isUsed = true;
228 }
229 }
230 }
231
232 /// Gets a default value from an initializer, nullptr if not present
233 const ast::ConstantExpr * getDefaultValue( const ast::Init * init ) {
234 if ( auto si = dynamic_cast< const ast::SingleInit * >( init ) ) {
235 if ( auto ce = si->value.as< ast::CastExpr >() ) {
236 return ce->arg.as< ast::ConstantExpr >();
237 } else {
238 return si->value.as< ast::ConstantExpr >();
239 }
240 }
241 return nullptr;
242 }
243
244 /// State to iteratively build a match of parameter expressions to arguments
245 struct ArgPack {
246 std::size_t parent; ///< Index of parent pack
247 ast::ptr< ast::Expr > expr; ///< The argument stored here
248 Cost cost; ///< The cost of this argument
249 ast::TypeEnvironment env; ///< Environment for this pack
250 ast::AssertionSet need; ///< Assertions outstanding for this pack
251 ast::AssertionSet have; ///< Assertions found for this pack
252 ast::OpenVarSet open; ///< Open variables for this pack
253 unsigned nextArg; ///< Index of next argument in arguments list
254 unsigned tupleStart; ///< Number of tuples that start at this index
255 unsigned nextExpl; ///< Index of next exploded element
256 unsigned explAlt; ///< Index of alternative for nextExpl > 0
257
258 ArgPack()
259 : parent( 0 ), expr(), cost( Cost::zero ), env(), need(), have(), open(), nextArg( 0 ),
260 tupleStart( 0 ), nextExpl( 0 ), explAlt( 0 ) {}
261
262 ArgPack(
263 const ast::TypeEnvironment & env, const ast::AssertionSet & need,
264 const ast::AssertionSet & have, const ast::OpenVarSet & open )
265 : parent( 0 ), expr(), cost( Cost::zero ), env( env ), need( need ), have( have ),
266 open( open ), nextArg( 0 ), tupleStart( 0 ), nextExpl( 0 ), explAlt( 0 ) {}
267
268 ArgPack(
269 std::size_t parent, const ast::Expr * expr, ast::TypeEnvironment && env,
270 ast::AssertionSet && need, ast::AssertionSet && have, ast::OpenVarSet && open,
271 unsigned nextArg, unsigned tupleStart = 0, Cost cost = Cost::zero,
272 unsigned nextExpl = 0, unsigned explAlt = 0 )
273 : parent(parent), expr( expr ), cost( cost ), env( move( env ) ), need( move( need ) ),
274 have( move( have ) ), open( move( open ) ), nextArg( nextArg ), tupleStart( tupleStart ),
275 nextExpl( nextExpl ), explAlt( explAlt ) {}
276
277 ArgPack(
278 const ArgPack & o, ast::TypeEnvironment && env, ast::AssertionSet && need,
279 ast::AssertionSet && have, ast::OpenVarSet && open, unsigned nextArg, Cost added )
280 : parent( o.parent ), expr( o.expr ), cost( o.cost + added ), env( move( env ) ),
281 need( move( need ) ), have( move( have ) ), open( move( open ) ), nextArg( nextArg ),
282 tupleStart( o.tupleStart ), nextExpl( 0 ), explAlt( 0 ) {}
283
284 /// true if this pack is in the middle of an exploded argument
285 bool hasExpl() const { return nextExpl > 0; }
286
287 /// Gets the list of exploded candidates for this pack
288 const ExplodedArg & getExpl( const ExplodedArgs_new & args ) const {
289 return args[ nextArg-1 ][ explAlt ];
290 }
291
292 /// Ends a tuple expression, consolidating the appropriate args
293 void endTuple( const std::vector< ArgPack > & packs ) {
294 // add all expressions in tuple to list, summing cost
295 std::deque< const ast::Expr * > exprs;
296 const ArgPack * pack = this;
297 if ( expr ) { exprs.emplace_front( expr ); }
298 while ( pack->tupleStart == 0 ) {
299 pack = &packs[pack->parent];
300 exprs.emplace_front( pack->expr );
301 cost += pack->cost;
302 }
303 // reset pack to appropriate tuple
304 std::vector< ast::ptr< ast::Expr > > exprv( exprs.begin(), exprs.end() );
305 expr = new ast::TupleExpr{ expr->location, move( exprv ) };
306 tupleStart = pack->tupleStart - 1;
307 parent = pack->parent;
308 }
309 };
310
311 /// Instantiates an argument to match a parameter, returns false if no matching results left
312 bool instantiateArgument(
313 const ast::Type * paramType, const ast::Init * init, const ExplodedArgs_new & args,
314 std::vector< ArgPack > & results, std::size_t & genStart, const ast::SymbolTable & symtab,
315 unsigned nTuples = 0
316 ) {
317 if ( auto tupleType = dynamic_cast< const ast::TupleType * >( paramType ) ) {
318 // paramType is a TupleType -- group args into a TupleExpr
319 ++nTuples;
320 for ( const ast::Type * type : *tupleType ) {
321 // xxx - dropping initializer changes behaviour from previous, but seems correct
322 // ^^^ need to handle the case where a tuple has a default argument
323 if ( ! instantiateArgument(
324 type, nullptr, args, results, genStart, symtab, nTuples ) ) return false;
325 nTuples = 0;
326 }
327 // re-constitute tuples for final generation
328 for ( auto i = genStart; i < results.size(); ++i ) {
329 results[i].endTuple( results );
330 }
331 return true;
332 } else if ( const ast::TypeInstType * ttype = Tuples::isTtype( paramType ) ) {
333 // paramType is a ttype, consumes all remaining arguments
334
335 // completed tuples; will be spliced to end of results to finish
336 std::vector< ArgPack > finalResults{};
337
338 // iterate until all results completed
339 std::size_t genEnd;
340 ++nTuples;
341 do {
342 genEnd = results.size();
343
344 // add another argument to results
345 for ( std::size_t i = genStart; i < genEnd; ++i ) {
346 unsigned nextArg = results[i].nextArg;
347
348 // use next element of exploded tuple if present
349 if ( results[i].hasExpl() ) {
350 const ExplodedArg & expl = results[i].getExpl( args );
351
352 unsigned nextExpl = results[i].nextExpl + 1;
353 if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
354
355 results.emplace_back(
356 i, expl.exprs[ results[i].nextExpl ], copy( results[i].env ),
357 copy( results[i].need ), copy( results[i].have ),
358 copy( results[i].open ), nextArg, nTuples, Cost::zero, nextExpl,
359 results[i].explAlt );
360
361 continue;
362 }
363
364 // finish result when out of arguments
365 if ( nextArg >= args.size() ) {
366 ArgPack newResult{
367 results[i].env, results[i].need, results[i].have, results[i].open };
368 newResult.nextArg = nextArg;
369 const ast::Type * argType = nullptr;
370
371 if ( nTuples > 0 || ! results[i].expr ) {
372 // first iteration or no expression to clone,
373 // push empty tuple expression
374 newResult.parent = i;
375 std::vector< ast::ptr< ast::Expr > > emptyList;
376 newResult.expr =
377 new ast::TupleExpr{ CodeLocation{}, move( emptyList ) };
378 argType = newResult.expr->result;
379 } else {
380 // clone result to collect tuple
381 newResult.parent = results[i].parent;
382 newResult.cost = results[i].cost;
383 newResult.tupleStart = results[i].tupleStart;
384 newResult.expr = results[i].expr;
385 argType = newResult.expr->result;
386
387 if ( results[i].tupleStart > 0 && Tuples::isTtype( argType ) ) {
388 // the case where a ttype value is passed directly is special,
389 // e.g. for argument forwarding purposes
390 // xxx - what if passing multiple arguments, last of which is
391 // ttype?
392 // xxx - what would happen if unify was changed so that unifying
393 // tuple
394 // types flattened both before unifying lists? then pass in
395 // TupleType (ttype) below.
396 --newResult.tupleStart;
397 } else {
398 // collapse leftover arguments into tuple
399 newResult.endTuple( results );
400 argType = newResult.expr->result;
401 }
402 }
403
404 // check unification for ttype before adding to final
405 if (
406 unify(
407 ttype, argType, newResult.env, newResult.need, newResult.have,
408 newResult.open, symtab )
409 ) {
410 finalResults.emplace_back( move( newResult ) );
411 }
412
413 continue;
414 }
415
416 // add each possible next argument
417 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
418 const ExplodedArg & expl = args[nextArg][j];
419
420 // fresh copies of parent parameters for this iteration
421 ast::TypeEnvironment env = results[i].env;
422 ast::OpenVarSet open = results[i].open;
423
424 env.addActual( expl.env, open );
425
426 // skip empty tuple arguments by (nearly) cloning parent into next gen
427 if ( expl.exprs.empty() ) {
428 results.emplace_back(
429 results[i], move( env ), copy( results[i].need ),
430 copy( results[i].have ), move( open ), nextArg + 1, expl.cost );
431
432 continue;
433 }
434
435 // add new result
436 results.emplace_back(
437 i, expl.exprs.front(), move( env ), copy( results[i].need ),
438 copy( results[i].have ), move( open ), nextArg + 1, nTuples,
439 expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
440 }
441 }
442
443 // reset for next round
444 genStart = genEnd;
445 nTuples = 0;
446 } while ( genEnd != results.size() );
447
448 // splice final results onto results
449 for ( std::size_t i = 0; i < finalResults.size(); ++i ) {
450 results.emplace_back( move( finalResults[i] ) );
451 }
452 return ! finalResults.empty();
453 }
454
455 // iterate each current subresult
456 std::size_t genEnd = results.size();
457 for ( std::size_t i = genStart; i < genEnd; ++i ) {
458 unsigned nextArg = results[i].nextArg;
459
460 // use remainder of exploded tuple if present
461 if ( results[i].hasExpl() ) {
462 const ExplodedArg & expl = results[i].getExpl( args );
463 const ast::Expr * expr = expl.exprs[ results[i].nextExpl ];
464
465 ast::TypeEnvironment env = results[i].env;
466 ast::AssertionSet need = results[i].need, have = results[i].have;
467 ast::OpenVarSet open = results[i].open;
468
469 const ast::Type * argType = expr->result;
470
471 PRINT(
472 std::cerr << "param type is ";
473 ast::print( std::cerr, paramType );
474 std::cerr << std::endl << "arg type is ";
475 ast::print( std::cerr, argType );
476 std::cerr << std::endl;
477 )
478
479 if ( unify( paramType, argType, env, need, have, open, symtab ) ) {
480 unsigned nextExpl = results[i].nextExpl + 1;
481 if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
482
483 results.emplace_back(
484 i, expr, move( env ), move( need ), move( have ), move( open ), nextArg,
485 nTuples, Cost::zero, nextExpl, results[i].explAlt );
486 }
487
488 continue;
489 }
490
491 // use default initializers if out of arguments
492 if ( nextArg >= args.size() ) {
493 if ( const ast::ConstantExpr * cnst = getDefaultValue( init ) ) {
494 ast::TypeEnvironment env = results[i].env;
495 ast::AssertionSet need = results[i].need, have = results[i].have;
496 ast::OpenVarSet open = results[i].open;
497
498 if ( unify( paramType, cnst->result, env, need, have, open, symtab ) ) {
499 results.emplace_back(
500 i, new ast::DefaultArgExpr{ cnst->location, cnst }, move( env ),
501 move( need ), move( have ), move( open ), nextArg, nTuples );
502 }
503 }
504
505 continue;
506 }
507
508 // Check each possible next argument
509 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
510 const ExplodedArg & expl = args[nextArg][j];
511
512 // fresh copies of parent parameters for this iteration
513 ast::TypeEnvironment env = results[i].env;
514 ast::AssertionSet need = results[i].need, have = results[i].have;
515 ast::OpenVarSet open = results[i].open;
516
517 env.addActual( expl.env, open );
518
519 // skip empty tuple arguments by (nearly) cloning parent into next gen
520 if ( expl.exprs.empty() ) {
521 results.emplace_back(
522 results[i], move( env ), move( need ), move( have ), move( open ),
523 nextArg + 1, expl.cost );
524
525 continue;
526 }
527
528 // consider only first exploded arg
529 const ast::Expr * expr = expl.exprs.front();
530 const ast::Type * argType = expr->result;
531
532 PRINT(
533 std::cerr << "param type is ";
534 ast::print( std::cerr, paramType );
535 std::cerr << std::endl << "arg type is ";
536 ast::print( std::cerr, argType );
537 std::cerr << std::endl;
538 )
539
540 // attempt to unify types
541 if ( unify( paramType, argType, env, need, have, open, symtab ) ) {
542 // add new result
543 results.emplace_back(
544 i, expr, move( env ), move( need ), move( have ), move( open ),
545 nextArg + 1, nTuples, expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
546 }
547 }
548 }
549
550 // reset for next parameter
551 genStart = genEnd;
552
553 return genEnd != results.size();
554 }
555
556 /// Actually visits expressions to find their candidate interpretations
557 struct Finder final : public ast::WithShortCircuiting {
558 CandidateFinder & selfFinder;
559 const ast::SymbolTable & symtab;
560 CandidateList & candidates;
561 const ast::TypeEnvironment & tenv;
562 ast::ptr< ast::Type > & targetType;
563
564 Finder( CandidateFinder & f )
565 : selfFinder( f ), symtab( f.symtab ), candidates( f.candidates ), tenv( f.env ),
566 targetType( f.targetType ) {}
567
568 void previsit( const ast::Node * ) { visit_children = false; }
569
570 /// Convenience to add candidate to list
571 template<typename... Args>
572 void addCandidate( Args &&... args ) {
573 candidates.emplace_back( new Candidate{ std::forward<Args>( args )... } );
574 }
575
576 void postvisit( const ast::ApplicationExpr * applicationExpr ) {
577 addCandidate( applicationExpr, tenv );
578 }
579
580 /// Set up candidate assertions for inference
581 void inferParameters( CandidateRef & newCand, CandidateList & out ) {
582 // Set need bindings for any unbound assertions
583 UniqueId crntResnSlot = 0; // matching ID for this expression's assertions
584 for ( auto & assn : newCand->need ) {
585 // skip already-matched assertions
586 if ( assn.second.resnSlot != 0 ) continue;
587 // assign slot for expression if needed
588 if ( crntResnSlot == 0 ) { crntResnSlot = ++globalResnSlot; }
589 // fix slot to assertion
590 assn.second.resnSlot = crntResnSlot;
591 }
592 // pair slot to expression
593 if ( crntResnSlot != 0 ) {
594 newCand->expr.get_and_mutate()->inferred.resnSlots().emplace_back( crntResnSlot );
595 }
596
597 // add to output list; assertion satisfaction will occur later
598 out.emplace_back( newCand );
599 }
600
601 /// Completes a function candidate with arguments located
602 void validateFunctionCandidate(
603 const CandidateRef & func, ArgPack & result, const std::vector< ArgPack > & results,
604 CandidateList & out
605 ) {
606 ast::ApplicationExpr * appExpr =
607 new ast::ApplicationExpr{ func->expr->location, func->expr };
608 // sum cost and accumulate arguments
609 std::deque< const ast::Expr * > args;
610 Cost cost = func->cost;
611 const ArgPack * pack = &result;
612 while ( pack->expr ) {
613 args.emplace_front( pack->expr );
614 cost += pack->cost;
615 pack = &results[pack->parent];
616 }
617 std::vector< ast::ptr< ast::Expr > > vargs( args.begin(), args.end() );
618 appExpr->args = move( vargs );
619 // build and validate new candidate
620 auto newCand =
621 std::make_shared<Candidate>( appExpr, result.env, result.open, result.need, cost );
622 PRINT(
623 std::cerr << "instantiate function success: " << appExpr << std::endl;
624 std::cerr << "need assertions:" << std::endl;
625 ast::print( std::cerr, result.need, 2 );
626 )
627 inferParameters( newCand, out );
628 }
629
630 /// Builds a list of candidates for a function, storing them in out
631 void makeFunctionCandidates(
632 const CandidateRef & func, const ast::FunctionType * funcType,
633 const ExplodedArgs_new & args, CandidateList & out
634 ) {
635 ast::OpenVarSet funcOpen;
636 ast::AssertionSet funcNeed, funcHave;
637 ast::TypeEnvironment funcEnv{ func->env };
638 makeUnifiableVars( funcType, funcOpen, funcNeed );
639 // add all type variables as open variables now so that those not used in the parameter
640 // list are still considered open
641 funcEnv.add( funcType->forall );
642
643 if ( targetType && ! targetType->isVoid() && ! funcType->returns.empty() ) {
644 // attempt to narrow based on expected target type
645 const ast::Type * returnType = funcType->returns.front()->get_type();
646 if ( ! unify(
647 returnType, targetType, funcEnv, funcNeed, funcHave, funcOpen, symtab )
648 ) {
649 // unification failed, do not pursue this candidate
650 return;
651 }
652 }
653
654 // iteratively build matches, one parameter at a time
655 std::vector< ArgPack > results;
656 results.emplace_back( funcEnv, funcNeed, funcHave, funcOpen );
657 std::size_t genStart = 0;
658
659 for ( const ast::DeclWithType * param : funcType->params ) {
660 auto obj = strict_dynamic_cast< const ast::ObjectDecl * >( param );
661 // Try adding the arguments corresponding to the current parameter to the existing
662 // matches
663 if ( ! instantiateArgument(
664 obj->type, obj->init, args, results, genStart, symtab ) ) return;
665 }
666
667 if ( funcType->isVarArgs ) {
668 // append any unused arguments to vararg pack
669 std::size_t genEnd;
670 do {
671 genEnd = results.size();
672
673 // iterate results
674 for ( std::size_t i = genStart; i < genEnd; ++i ) {
675 unsigned nextArg = results[i].nextArg;
676
677 // use remainder of exploded tuple if present
678 if ( results[i].hasExpl() ) {
679 const ExplodedArg & expl = results[i].getExpl( args );
680
681 unsigned nextExpl = results[i].nextExpl + 1;
682 if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
683
684 results.emplace_back(
685 i, expl.exprs[ results[i].nextExpl ], copy( results[i].env ),
686 copy( results[i].need ), copy( results[i].have ),
687 copy( results[i].open ), nextArg, 0, Cost::zero, nextExpl,
688 results[i].explAlt );
689
690 continue;
691 }
692
693 // finish result when out of arguments
694 if ( nextArg >= args.size() ) {
695 validateFunctionCandidate( func, results[i], results, out );
696
697 continue;
698 }
699
700 // add each possible next argument
701 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
702 const ExplodedArg & expl = args[nextArg][j];
703
704 // fresh copies of parent parameters for this iteration
705 ast::TypeEnvironment env = results[i].env;
706 ast::OpenVarSet open = results[i].open;
707
708 env.addActual( expl.env, open );
709
710 // skip empty tuple arguments by (nearly) cloning parent into next gen
711 if ( expl.exprs.empty() ) {
712 results.emplace_back(
713 results[i], move( env ), copy( results[i].need ),
714 copy( results[i].have ), move( open ), nextArg + 1,
715 expl.cost );
716
717 continue;
718 }
719
720 // add new result
721 results.emplace_back(
722 i, expl.exprs.front(), move( env ), copy( results[i].need ),
723 copy( results[i].have ), move( open ), nextArg + 1, 0, expl.cost,
724 expl.exprs.size() == 1 ? 0 : 1, j );
725 }
726 }
727
728 genStart = genEnd;
729 } while( genEnd != results.size() );
730 } else {
731 // filter out the results that don't use all the arguments
732 for ( std::size_t i = genStart; i < results.size(); ++i ) {
733 ArgPack & result = results[i];
734 if ( ! result.hasExpl() && result.nextArg >= args.size() ) {
735 validateFunctionCandidate( func, result, results, out );
736 }
737 }
738 }
739 }
740
741 /// Adds implicit struct-conversions to the alternative list
742 void addAnonConversions( const CandidateRef & cand ) {
743 #warning unimplemented
744 (void)cand;
745 assert(false);
746 }
747
748 void postvisit( const ast::UntypedExpr * untypedExpr ) {
749 CandidateFinder funcFinder{ symtab, tenv };
750 funcFinder.find( untypedExpr->func, ResolvMode::withAdjustment() );
751 // short-circuit if no candidates
752 if ( funcFinder.candidates.empty() ) return;
753
754 std::vector< CandidateFinder > argCandidates =
755 selfFinder.findSubExprs( untypedExpr->args );
756
757 // take care of possible tuple assignments
758 // if not tuple assignment, handled as normal function call
759 Tuples::handleTupleAssignment( selfFinder, untypedExpr, argCandidates );
760
761 // find function operators
762 ast::ptr< ast::Expr > opExpr = new ast::NameExpr{ untypedExpr->location, "?()" };
763 CandidateFinder opFinder{ symtab, tenv };
764 // okay if there aren't any function operations
765 opFinder.find( opExpr, ResolvMode::withoutFailFast() );
766 PRINT(
767 std::cerr << "known function ops:" << std::endl;
768 print( std::cerr, opFinder.candidates, 1 );
769 )
770
771 // pre-explode arguments
772 ExplodedArgs_new argExpansions;
773 for ( const CandidateFinder & args : argCandidates ) {
774 argExpansions.emplace_back();
775 auto & argE = argExpansions.back();
776 for ( const CandidateRef & arg : args ) { argE.emplace_back( *arg, symtab ); }
777 }
778
779 // Find function matches
780 CandidateList found;
781 SemanticErrorException errors;
782 for ( CandidateRef & func : funcFinder ) {
783 try {
784 PRINT(
785 std::cerr << "working on alternative:" << std::endl;
786 print( std::cerr, *func, 2 );
787 )
788
789 // check if the type is a pointer to function
790 const ast::Type * funcResult = func->expr->result->stripReferences();
791 if ( auto pointer = dynamic_cast< const ast::PointerType * >( funcResult ) ) {
792 if ( auto function = pointer->base.as< ast::FunctionType >() ) {
793 CandidateRef newFunc{ new Candidate{ *func } };
794 newFunc->expr =
795 referenceToRvalueConversion( newFunc->expr, newFunc->cost );
796 makeFunctionCandidates( newFunc, function, argExpansions, found );
797 }
798 } else if (
799 auto inst = dynamic_cast< const ast::TypeInstType * >( funcResult )
800 ) {
801 if ( const ast::EqvClass * clz = func->env.lookup( inst->name ) ) {
802 if ( auto function = clz->bound.as< ast::FunctionType >() ) {
803 CandidateRef newFunc{ new Candidate{ *func } };
804 newFunc->expr =
805 referenceToRvalueConversion( newFunc->expr, newFunc->cost );
806 makeFunctionCandidates( newFunc, function, argExpansions, found );
807 }
808 }
809 }
810 } catch ( SemanticErrorException & e ) { errors.append( e ); }
811 }
812
813 // Find matches on function operators `?()`
814 if ( ! opFinder.candidates.empty() ) {
815 // add exploded function alternatives to front of argument list
816 std::vector< ExplodedArg > funcE;
817 funcE.reserve( funcFinder.candidates.size() );
818 for ( const CandidateRef & func : funcFinder ) {
819 funcE.emplace_back( *func, symtab );
820 }
821 argExpansions.emplace_front( move( funcE ) );
822
823 for ( const CandidateRef & op : opFinder ) {
824 try {
825 // check if type is pointer-to-function
826 const ast::Type * opResult = op->expr->result->stripReferences();
827 if ( auto pointer = dynamic_cast< const ast::PointerType * >( opResult ) ) {
828 if ( auto function = pointer->base.as< ast::FunctionType >() ) {
829 CandidateRef newOp{ new Candidate{ *op} };
830 newOp->expr =
831 referenceToRvalueConversion( newOp->expr, newOp->cost );
832 makeFunctionCandidates( newOp, function, argExpansions, found );
833 }
834 }
835 } catch ( SemanticErrorException & e ) { errors.append( e ); }
836 }
837 }
838
839 // Implement SFINAE; resolution errors are only errors if there aren't any non-error
840 // candidates
841 if ( found.empty() && ! errors.isEmpty() ) { throw errors; }
842
843 // Compute conversion costs
844 for ( CandidateRef & withFunc : found ) {
845 Cost cvtCost = computeApplicationConversionCost( withFunc, symtab );
846
847 PRINT(
848 auto appExpr = withFunc->expr.strict_as< ast::ApplicationExpr >();
849 auto pointer = appExpr->func->result.strict_as< ast::PointerType >();
850 auto function = pointer->base.strict_as< ast::FunctionType >();
851
852 std::cerr << "Case +++++++++++++ " << appExpr->func << std::endl;
853 std::cerr << "parameters are:" << std::endl;
854 ast::printAll( std::cerr, function->params, 2 );
855 std::cerr << "arguments are:" << std::endl;
856 ast::printAll( std::cerr, appExpr->args, 2 );
857 std::cerr << "bindings are:" << std::endl;
858 ast::print( std::cerr, withFunc->env, 2 );
859 std::cerr << "cost is: " << withFunc->cost << std::endl;
860 std::cerr << "cost of conversion is:" << cvtCost << std::endl;
861 )
862
863 if ( cvtCost != Cost::infinity ) {
864 withFunc->cvtCost = cvtCost;
865 candidates.emplace_back( move( withFunc ) );
866 }
867 }
868 found = move( candidates );
869
870 // use a new list so that candidates are not examined by addAnonConversions twice
871 CandidateList winners = findMinCost( found );
872 promoteCvtCost( winners );
873
874 // function may return a struct/union value, in which case we need to add candidates
875 // for implicit conversions to each of the anonymous members, which must happen after
876 // `findMinCost`, since anon conversions are never the cheapest
877 for ( const CandidateRef & c : winners ) {
878 addAnonConversions( c );
879 }
880 spliceBegin( candidates, winners );
881
882 if ( candidates.empty() && targetType && ! targetType->isVoid() ) {
883 // If resolution is unsuccessful with a target type, try again without, since it
884 // will sometimes succeed when it wouldn't with a target type binding.
885 // For example:
886 // forall( otype T ) T & ?[]( T *, ptrdiff_t );
887 // const char * x = "hello world";
888 // unsigned char ch = x[0];
889 // Fails with simple return type binding (xxx -- check this!) as follows:
890 // * T is bound to unsigned char
891 // * (x: const char *) is unified with unsigned char *, which fails
892 // xxx -- fix this better
893 targetType = nullptr;
894 postvisit( untypedExpr );
895 }
896 }
897
898 /// true if expression is an lvalue
899 static bool isLvalue( const ast::Expr * x ) {
900 return x->result && ( x->result->is_lvalue() || x->result.as< ast::ReferenceType >() );
901 }
902
903 void postvisit( const ast::AddressExpr * addressExpr ) {
904 CandidateFinder finder{ symtab, tenv };
905 finder.find( addressExpr->arg );
906 for ( CandidateRef & r : finder.candidates ) {
907 if ( ! isLvalue( r->expr ) ) continue;
908 addCandidate( *r, new ast::AddressExpr{ addressExpr->location, r->expr } );
909 }
910 }
911
912 void postvisit( const ast::LabelAddressExpr * labelExpr ) {
913 addCandidate( labelExpr, tenv );
914 }
915
916 void postvisit( const ast::CastExpr * castExpr ) {
917 #warning unimplemented
918 (void)castExpr;
919 assert(false);
920 }
921
922 void postvisit( const ast::VirtualCastExpr * castExpr ) {
923 assertf( castExpr->result, "Implicit virtual cast targets not yet supported." );
924 CandidateFinder finder{ symtab, tenv };
925 // don't prune here, all alternatives guaranteed to have same type
926 finder.find( castExpr->arg, ResolvMode::withoutPrune() );
927 for ( CandidateRef & r : finder.candidates ) {
928 addCandidate(
929 *r, new ast::VirtualCastExpr{ castExpr->location, r->expr, castExpr->result } );
930 }
931 }
932
933 void postvisit( const ast::UntypedMemberExpr * memberExpr ) {
934 #warning unimplemented
935 (void)memberExpr;
936 assert(false);
937 }
938
939 void postvisit( const ast::MemberExpr * memberExpr ) {
940 addCandidate( memberExpr, tenv );
941 }
942
943 void postvisit( const ast::NameExpr * variableExpr ) {
944 #warning unimplemented
945 (void)variableExpr;
946 assert(false);
947 }
948
949 void postvisit( const ast::VariableExpr * variableExpr ) {
950 // not sufficient to just pass `variableExpr` here, type might have changed since
951 // creation
952 addCandidate(
953 new ast::VariableExpr{ variableExpr->location, variableExpr->var }, tenv );
954 }
955
956 void postvisit( const ast::ConstantExpr * constantExpr ) {
957 addCandidate( constantExpr, tenv );
958 }
959
960 void postvisit( const ast::SizeofExpr * sizeofExpr ) {
961 #warning unimplemented
962 (void)sizeofExpr;
963 assert(false);
964 }
965
966 void postvisit( const ast::AlignofExpr * alignofExpr ) {
967 #warning unimplemented
968 (void)alignofExpr;
969 assert(false);
970 }
971
972 void postvisit( const ast::UntypedOffsetofExpr * offsetofExpr ) {
973 #warning unimplemented
974 (void)offsetofExpr;
975 assert(false);
976 }
977
978 void postvisit( const ast::OffsetofExpr * offsetofExpr ) {
979 addCandidate( offsetofExpr, tenv );
980 }
981
982 void postvisit( const ast::OffsetPackExpr * offsetPackExpr ) {
983 addCandidate( offsetPackExpr, tenv );
984 }
985
986 void postvisit( const ast::LogicalExpr * logicalExpr ) {
987 CandidateFinder finder1{ symtab, tenv };
988 finder1.find( logicalExpr->arg1, ResolvMode::withAdjustment() );
989 if ( finder1.candidates.empty() ) return;
990
991 CandidateFinder finder2{ symtab, tenv };
992 finder2.find( logicalExpr->arg2, ResolvMode::withAdjustment() );
993 if ( finder2.candidates.empty() ) return;
994
995 for ( const CandidateRef & r1 : finder1.candidates ) {
996 for ( const CandidateRef & r2 : finder2.candidates ) {
997 ast::TypeEnvironment env{ r1->env };
998 env.simpleCombine( r2->env );
999 ast::OpenVarSet open{ r1->open };
1000 mergeOpenVars( open, r2->open );
1001 ast::AssertionSet need;
1002 mergeAssertionSet( need, r1->need );
1003 mergeAssertionSet( need, r2->need );
1004
1005 addCandidate(
1006 new ast::LogicalExpr{
1007 logicalExpr->location, r1->expr, r2->expr, logicalExpr->isAnd },
1008 move( env ), move( open ), move( need ), r1->cost + r2->cost );
1009 }
1010 }
1011 }
1012
1013 void postvisit( const ast::ConditionalExpr * conditionalExpr ) {
1014 // candidates for condition
1015 CandidateFinder finder1{ symtab, tenv };
1016 finder1.find( conditionalExpr->arg1, ResolvMode::withAdjustment() );
1017 if ( finder1.candidates.empty() ) return;
1018
1019 // candidates for true result
1020 CandidateFinder finder2{ symtab, tenv };
1021 finder2.find( conditionalExpr->arg2, ResolvMode::withAdjustment() );
1022 if ( finder2.candidates.empty() ) return;
1023
1024 // candidates for false result
1025 CandidateFinder finder3{ symtab, tenv };
1026 finder3.find( conditionalExpr->arg3, ResolvMode::withAdjustment() );
1027 if ( finder3.candidates.empty() ) return;
1028
1029 for ( const CandidateRef & r1 : finder1.candidates ) {
1030 for ( const CandidateRef & r2 : finder2.candidates ) {
1031 for ( const CandidateRef & r3 : finder3.candidates ) {
1032 ast::TypeEnvironment env{ r1->env };
1033 env.simpleCombine( r2->env );
1034 env.simpleCombine( r3->env );
1035 ast::OpenVarSet open{ r1->open };
1036 mergeOpenVars( open, r2->open );
1037 mergeOpenVars( open, r3->open );
1038 ast::AssertionSet need;
1039 mergeAssertionSet( need, r1->need );
1040 mergeAssertionSet( need, r2->need );
1041 mergeAssertionSet( need, r3->need );
1042 ast::AssertionSet have;
1043
1044 // unify true and false results, then infer parameters to produce new
1045 // candidates
1046 ast::ptr< ast::Type > common;
1047 if (
1048 unify(
1049 r2->expr->result, r3->expr->result, env, need, have, open, symtab,
1050 common )
1051 ) {
1052 #warning unimplemented
1053 assert(false);
1054 }
1055 }
1056 }
1057 }
1058 }
1059
1060 void postvisit( const ast::CommaExpr * commaExpr ) {
1061 ast::TypeEnvironment env{ tenv };
1062 ast::ptr< ast::Expr > arg1 = resolveInVoidContext( commaExpr->arg1, symtab, env );
1063
1064 CandidateFinder finder2{ symtab, env };
1065 finder2.find( commaExpr->arg2, ResolvMode::withAdjustment() );
1066
1067 for ( const CandidateRef & r2 : finder2.candidates ) {
1068 addCandidate( *r2, new ast::CommaExpr{ commaExpr->location, arg1, r2->expr } );
1069 }
1070 }
1071
1072 void postvisit( const ast::ImplicitCopyCtorExpr * ctorExpr ) {
1073 addCandidate( ctorExpr, tenv );
1074 }
1075
1076 void postvisit( const ast::ConstructorExpr * ctorExpr ) {
1077 CandidateFinder finder{ symtab, tenv };
1078 finder.find( ctorExpr->callExpr, ResolvMode::withoutPrune() );
1079 for ( CandidateRef & r : finder.candidates ) {
1080 addCandidate( *r, new ast::ConstructorExpr{ ctorExpr->location, r->expr } );
1081 }
1082 }
1083
1084 void postvisit( const ast::RangeExpr * rangeExpr ) {
1085 // resolve low and high, accept candidates where low and high types unify
1086 CandidateFinder finder1{ symtab, tenv };
1087 finder1.find( rangeExpr->low, ResolvMode::withAdjustment() );
1088 if ( finder1.candidates.empty() ) return;
1089
1090 CandidateFinder finder2{ symtab, tenv };
1091 finder2.find( rangeExpr->high, ResolvMode::withAdjustment() );
1092 if ( finder2.candidates.empty() ) return;
1093
1094 for ( const CandidateRef & r1 : finder1.candidates ) {
1095 for ( const CandidateRef & r2 : finder2.candidates ) {
1096 ast::TypeEnvironment env{ r1->env };
1097 env.simpleCombine( r2->env );
1098 ast::OpenVarSet open{ r1->open };
1099 mergeOpenVars( open, r2->open );
1100 ast::AssertionSet need;
1101 mergeAssertionSet( need, r1->need );
1102 mergeAssertionSet( need, r2->need );
1103 ast::AssertionSet have;
1104
1105 ast::ptr< ast::Type > common;
1106 if (
1107 unify(
1108 r1->expr->result, r2->expr->result, env, need, have, open, symtab,
1109 common )
1110 ) {
1111 ast::RangeExpr * newExpr =
1112 new ast::RangeExpr{ rangeExpr->location, r1->expr, r2->expr };
1113 newExpr->result = common ? common : r1->expr->result;
1114
1115 #warning unimplemented
1116 assert(false);
1117 }
1118 }
1119 }
1120 }
1121
1122 void postvisit( const ast::UntypedTupleExpr * tupleExpr ) {
1123 std::vector< CandidateFinder > subCandidates =
1124 selfFinder.findSubExprs( tupleExpr->exprs );
1125 std::vector< CandidateList > possibilities;
1126 combos( subCandidates.begin(), subCandidates.end(), back_inserter( possibilities ) );
1127
1128 for ( const CandidateList & subs : possibilities ) {
1129 std::vector< ast::ptr< ast::Expr > > exprs;
1130 exprs.reserve( subs.size() );
1131 for ( const CandidateRef & sub : subs ) { exprs.emplace_back( sub->expr ); }
1132
1133 ast::TypeEnvironment env;
1134 ast::OpenVarSet open;
1135 ast::AssertionSet need;
1136 for ( const CandidateRef & sub : subs ) {
1137 env.simpleCombine( sub->env );
1138 mergeOpenVars( open, sub->open );
1139 mergeAssertionSet( need, sub->need );
1140 }
1141
1142 addCandidate(
1143 new ast::TupleExpr{ tupleExpr->location, move( exprs ) },
1144 move( env ), move( open ), move( need ), sumCost( subs ) );
1145 }
1146 }
1147
1148 void postvisit( const ast::TupleExpr * tupleExpr ) {
1149 addCandidate( tupleExpr, tenv );
1150 }
1151
1152 void postvisit( const ast::TupleIndexExpr * tupleExpr ) {
1153 addCandidate( tupleExpr, tenv );
1154 }
1155
1156 void postvisit( const ast::TupleAssignExpr * tupleExpr ) {
1157 addCandidate( tupleExpr, tenv );
1158 }
1159
1160 void postvisit( const ast::UniqueExpr * unqExpr ) {
1161 CandidateFinder finder{ symtab, tenv };
1162 finder.find( unqExpr->expr, ResolvMode::withAdjustment() );
1163 for ( CandidateRef & r : finder.candidates ) {
1164 // ensure that the the id is passed on so that the expressions are "linked"
1165 addCandidate( *r, new ast::UniqueExpr{ unqExpr->location, r->expr, unqExpr->id } );
1166 }
1167 }
1168
1169 void postvisit( const ast::StmtExpr * stmtExpr ) {
1170 #warning unimplemented
1171 (void)stmtExpr;
1172 assert(false);
1173 }
1174
1175 void postvisit( const ast::UntypedInitExpr * initExpr ) {
1176 #warning unimplemented
1177 (void)initExpr;
1178 assert(false);
1179 }
1180
1181 void postvisit( const ast::InitExpr * ) {
1182 assertf( false, "CandidateFinder should never see a resolved InitExpr." );
1183 }
1184
1185 void postvisit( const ast::DeletedExpr * ) {
1186 assertf( false, "CandidateFinder should never see a DeletedExpr." );
1187 }
1188
1189 void postvisit( const ast::GenericExpr * ) {
1190 assertf( false, "_Generic is not yet supported." );
1191 }
1192 };
1193
1194 /// Prunes a list of candidates down to those that have the minimum conversion cost for a given
1195 /// return type. Skips ambiguous candidates.
1196 CandidateList pruneCandidates( CandidateList & candidates ) {
1197 struct PruneStruct {
1198 CandidateRef candidate;
1199 bool ambiguous;
1200
1201 PruneStruct() = default;
1202 PruneStruct( const CandidateRef & c ) : candidate( c ), ambiguous( false ) {}
1203 };
1204
1205 // find lowest-cost candidate for each type
1206 std::unordered_map< std::string, PruneStruct > selected;
1207 for ( CandidateRef & candidate : candidates ) {
1208 std::string mangleName;
1209 {
1210 ast::ptr< ast::Type > newType = candidate->expr->result;
1211 candidate->env.apply( newType );
1212 mangleName = Mangle::mangle( newType );
1213 }
1214
1215 auto found = selected.find( mangleName );
1216 if ( found != selected.end() ) {
1217 if ( candidate->cost < found->second.candidate->cost ) {
1218 PRINT(
1219 std::cerr << "cost " << candidate->cost << " beats "
1220 << found->second.candidate->cost << std::endl;
1221 )
1222
1223 found->second = PruneStruct{ candidate };
1224 } else if ( candidate->cost == found->second.candidate->cost ) {
1225 // if one of the candidates contains a deleted identifier, can pick the other,
1226 // since deleted expressions should not be ambiguous if there is another option
1227 // that is at least as good
1228 if ( findDeletedExpr( candidate->expr ) ) {
1229 // do nothing
1230 PRINT( std::cerr << "candidate is deleted" << std::endl; )
1231 } else if ( findDeletedExpr( found->second.candidate->expr ) ) {
1232 PRINT( std::cerr << "current is deleted" << std::endl; )
1233 found->second = PruneStruct{ candidate };
1234 } else {
1235 PRINT( std::cerr << "marking ambiguous" << std::endl; )
1236 found->second.ambiguous = true;
1237 }
1238 } else {
1239 PRINT(
1240 std::cerr << "cost " << candidate->cost << " loses to "
1241 << found->second.candidate->cost << std::endl;
1242 )
1243 }
1244 } else {
1245 selected.emplace_hint( found, mangleName, candidate );
1246 }
1247 }
1248
1249 // report unambiguous min-cost candidates
1250 CandidateList out;
1251 for ( auto & target : selected ) {
1252 if ( target.second.ambiguous ) continue;
1253
1254 CandidateRef cand = target.second.candidate;
1255
1256 ast::ptr< ast::Type > newResult = cand->expr->result;
1257 cand->env.applyFree( newResult );
1258 cand->expr = ast::mutate_field(
1259 cand->expr.get(), &ast::Expr::result, move( newResult ) );
1260
1261 out.emplace_back( cand );
1262 }
1263 return out;
1264 }
1265
1266} // anonymous namespace
1267
1268void CandidateFinder::find( const ast::Expr * expr, ResolvMode mode ) {
1269 // Find alternatives for expression
1270 ast::Pass<Finder> finder{ *this };
1271 expr->accept( finder );
1272
1273 if ( mode.failFast && candidates.empty() ) {
1274 SemanticError( expr, "No reasonable alternatives for expression " );
1275 }
1276
1277 if ( mode.satisfyAssns || mode.prune ) {
1278 // trim candidates to just those where the assertions are satisfiable
1279 // - necessary pre-requisite to pruning
1280 CandidateList satisfied;
1281 std::vector< std::string > errors;
1282 for ( auto & candidate : candidates ) {
1283 satisfyAssertions( *candidate, symtab, satisfied, errors );
1284 }
1285
1286 // fail early if none such
1287 if ( mode.failFast && satisfied.empty() ) {
1288 std::ostringstream stream;
1289 stream << "No alternatives with satisfiable assertions for " << expr << "\n";
1290 for ( const auto& err : errors ) {
1291 stream << err;
1292 }
1293 SemanticError( expr->location, stream.str() );
1294 }
1295
1296 // reset candidates
1297 candidates = move( satisfied );
1298 }
1299
1300 if ( mode.prune ) {
1301 // trim candidates to single best one
1302 PRINT(
1303 std::cerr << "alternatives before prune:" << std::endl;
1304 print( std::cerr, candidates );
1305 )
1306
1307 CandidateList pruned = pruneCandidates( candidates );
1308
1309 if ( mode.failFast && pruned.empty() ) {
1310 std::ostringstream stream;
1311 CandidateList winners = findMinCost( candidates );
1312 stream << "Cannot choose between " << winners.size() << " alternatives for "
1313 "expression\n";
1314 ast::print( stream, expr );
1315 stream << " Alternatives are:\n";
1316 print( stream, winners, 1 );
1317 SemanticError( expr->location, stream.str() );
1318 }
1319
1320 auto oldsize = candidates.size();
1321 candidates = move( pruned );
1322
1323 PRINT(
1324 std::cerr << "there are " << oldsize << " alternatives before elimination" << std::endl;
1325 )
1326 PRINT(
1327 std::cerr << "there are " << candidates.size() << " alternatives after elimination"
1328 << std::endl;
1329 )
1330 }
1331
1332 // adjust types after pruning so that types substituted by pruneAlternatives are correctly
1333 // adjusted
1334 if ( mode.adjust ) {
1335 for ( CandidateRef & r : candidates ) {
1336 r->expr = ast::mutate_field(
1337 r->expr.get(), &ast::Expr::result,
1338 adjustExprType( r->expr->result, r->env, symtab ) );
1339 }
1340 }
1341
1342 // Central location to handle gcc extension keyword, etc. for all expressions
1343 for ( CandidateRef & r : candidates ) {
1344 if ( r->expr->extension != expr->extension ) {
1345 r->expr.get_and_mutate()->extension = expr->extension;
1346 }
1347 }
1348}
1349
1350std::vector< CandidateFinder > CandidateFinder::findSubExprs(
1351 const std::vector< ast::ptr< ast::Expr > > & xs
1352) {
1353 std::vector< CandidateFinder > out;
1354
1355 for ( const auto & x : xs ) {
1356 out.emplace_back( symtab, env );
1357 out.back().find( x, ResolvMode::withAdjustment() );
1358
1359 PRINT(
1360 std::cerr << "findSubExprs" << std::endl;
1361 print( std::cerr, out.back().candidates );
1362 )
1363 }
1364
1365 return out;
1366}
1367
1368} // namespace ResolvExpr
1369
1370// Local Variables: //
1371// tab-width: 4 //
1372// mode: c++ //
1373// compile-command: "make install" //
1374// End: //
Note: See TracBrowser for help on using the repository browser.