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

Last change on this file since 8d26b7a was 0f5e8cd, checked in by Fangren Yu <f37yu@…>, 16 months ago

attempt to fix #286

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