source: src/ResolvExpr/CandidateFinder.cpp@ b96b1c0

stuck-waitfor-destruct
Last change on this file since b96b1c0 was b96b1c0, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Reproduing changes from commit eb8d791. This fixes most of the errors from resolver update.

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