source: src/ResolvExpr/CandidateFinder.cpp@ 8f7109c

Last change on this file since 8f7109c was 31f4837, checked in by JiadaL <j82liang@…>, 17 months ago

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

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