source: src/ResolvExpr/CandidateFinder.cpp@ 32490deb

Last change on this file since 32490deb was c75b30a, checked in by JiadaL <j82liang@…>, 22 months ago

Introduce posE, valueE, labelE pseudo language to the language. Rework the internal representation of enumeration.

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