source: src/ResolvExpr/CandidateFinder.cpp@ 5936244

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 5936244 was e3282fe, checked in by Fangren Yu <f37yu@…>, 5 years ago

optimize out some mangle calls

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