source: src/ResolvExpr/CandidateFinder.cpp@ dd78dbc

Last change on this file since dd78dbc was d68a3f7, checked in by JiadaL <j82liang@…>, 14 months ago

Update makeEnumOffsetCast to not report error for cast to non-parent type (later be a losing candidate)

  • Property mode set to 100644
File size: 81.1 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
[5eb3f65]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Sat Jun 22 08:07:26 2024
13// Update Count : 4
[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 );
[85855b0]515
516 auto paramAsEnum = dynamic_cast<const ast::EnumInstType *>(paramType);
517 auto argAsEnum =dynamic_cast<const ast::EnumInstType *>(argType);
518 if (paramAsEnum && argAsEnum) {
519 if (paramAsEnum->base->name != argAsEnum->base->name) {
520 Cost c = castCost(argType, paramType, expr, context.symtab, env);
521 if (c < Cost::infinity) {
522 CandidateFinder subFinder( context, env );
523 expr = subFinder.makeEnumOffsetCast(argAsEnum, paramAsEnum, expr, c);
[d68a3f7]524 if ( expr )
525 results.emplace_back(
526 i, expr, std::move( env ), std::move( need ), std::move( have ), std::move( open ),
527 nextArg + 1, nTuples, expl.cost + c, expl.exprs.size() == 1 ? 0 : 1, j );
[85855b0]528 continue;
529 } else {
530 std::cerr << "Cannot instantiate " << paramAsEnum->base->name << " with " << argAsEnum->base->name << std::endl;
531 }
532 }
533 }
534 results.emplace_back(
535 i, expr, std::move( env ), std::move( need ), std::move( have ), std::move( open ),
536 nextArg + 1, nTuples, expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
[9d5089e]537 }
538 }
539 }
540
541 // reset for next parameter
542 genStart = genEnd;
543
[e0e9a0b]544 return genEnd != results.size(); // were any new results added?
[432ce7a]545 }
546
[c8e4d2f8]547 /// Generate a cast expression from `arg` to `toType`
[2890212]548 const ast::Expr * restructureCast(
[17a0ede2]549 ast::ptr< ast::Expr > & arg, const ast::Type * toType, ast::GeneratedFlag isGenerated = ast::GeneratedCast
[898ae07]550 ) {
[2890212]551 if (
552 arg->result->size() > 1
553 && ! toType->isVoid()
554 && ! dynamic_cast< const ast::ReferenceType * >( toType )
[898ae07]555 ) {
[2890212]556 // Argument is a tuple and the target type is neither void nor a reference. Cast each
557 // member of the tuple to its corresponding target type, producing the tuple of those
558 // cast expressions. If there are more components of the tuple than components in the
559 // target type, then excess components do not come out in the result expression (but
[898ae07]560 // UniqueExpr ensures that the side effects will still be produced)
561 if ( Tuples::maybeImpureIgnoreUnique( arg ) ) {
[2890212]562 // expressions which may contain side effects require a single unique instance of
[898ae07]563 // the expression
564 arg = new ast::UniqueExpr{ arg->location, arg };
565 }
566 std::vector< ast::ptr< ast::Expr > > components;
567 for ( unsigned i = 0; i < toType->size(); ++i ) {
568 // cast each component
569 ast::ptr< ast::Expr > idx = new ast::TupleIndexExpr{ arg->location, arg, i };
[2890212]570 components.emplace_back(
[898ae07]571 restructureCast( idx, toType->getComponent( i ), isGenerated ) );
572 }
[09f34a84]573 return new ast::TupleExpr{ arg->location, std::move( components ) };
[898ae07]574 } else {
575 // handle normally
576 return new ast::CastExpr{ arg->location, arg, toType, isGenerated };
577 }
578 }
579
580 /// Gets the name from an untyped member expression (must be NameExpr)
581 const std::string & getMemberName( const ast::UntypedMemberExpr * memberExpr ) {
582 if ( memberExpr->member.as< ast::ConstantExpr >() ) {
583 SemanticError( memberExpr, "Indexed access to struct fields unsupported: " );
584 }
585
586 return memberExpr->member.strict_as< ast::NameExpr >()->name;
[c8e4d2f8]587 }
588
[396037d]589 /// Actually visits expressions to find their candidate interpretations
[9ea38de]590 class Finder final : public ast::WithShortCircuiting {
[39d8950]591 const ResolveContext & context;
[396037d]592 const ast::SymbolTable & symtab;
[9ea38de]593 public:
[943bfad]594 // static size_t traceId;
[9ea38de]595 CandidateFinder & selfFinder;
[396037d]596 CandidateList & candidates;
597 const ast::TypeEnvironment & tenv;
598 ast::ptr< ast::Type > & targetType;
599
[71d6bd8]600 enum Errors {
601 NotFound,
602 NoMatch,
603 ArgsToFew,
604 ArgsToMany,
605 RetsToFew,
606 RetsToMany,
607 NoReason
608 };
609
610 struct {
611 Errors code = NotFound;
612 } reason;
613
[396037d]614 Finder( CandidateFinder & f )
[39d8950]615 : context( f.context ), symtab( context.symtab ), selfFinder( f ),
616 candidates( f.candidates ), tenv( f.env ), targetType( f.targetType ) {}
[2890212]617
[4b7cce6]618 void previsit( const ast::Node * ) { visit_children = false; }
619
620 /// Convenience to add candidate to list
621 template<typename... Args>
622 void addCandidate( Args &&... args ) {
623 candidates.emplace_back( new Candidate{ std::forward<Args>( args )... } );
[71d6bd8]624 reason.code = NoReason;
[4b7cce6]625 }
626
627 void postvisit( const ast::ApplicationExpr * applicationExpr ) {
628 addCandidate( applicationExpr, tenv );
629 }
630
[9d5089e]631 /// Set up candidate assertions for inference
[64727bd]632 void inferParameters( CandidateRef & newCand, CandidateList & out );
[9d5089e]633
634 /// Completes a function candidate with arguments located
[2890212]635 void validateFunctionCandidate(
636 const CandidateRef & func, ArgPack & result, const std::vector< ArgPack > & results,
[64727bd]637 CandidateList & out );
[9d5089e]638
[432ce7a]639 /// Builds a list of candidates for a function, storing them in out
640 void makeFunctionCandidates(
[b96b1c0]641 const CodeLocation & location,
[2890212]642 const CandidateRef & func, const ast::FunctionType * funcType,
[0bd3faf]643 const ExplodedArgs & args, CandidateList & out );
[9d5089e]644
[64727bd]645 /// Adds implicit struct-conversions to the alternative list
646 void addAnonConversions( const CandidateRef & cand );
647
648 /// Adds aggregate member interpretations
649 void addAggMembers(
650 const ast::BaseInstType * aggrInst, const ast::Expr * expr,
651 const Candidate & cand, const Cost & addedCost, const std::string & name
652 );
653
[85855b0]654 void addEnumValueAsCandidate(const ast::EnumInstType * instType, const ast::Expr * expr,
655 const Cost & addedCost
656 );
657
[64727bd]658 /// Adds tuple member interpretations
659 void addTupleMembers(
660 const ast::TupleType * tupleType, const ast::Expr * expr, const Candidate & cand,
661 const Cost & addedCost, const ast::Expr * member
662 );
663
664 /// true if expression is an lvalue
665 static bool isLvalue( const ast::Expr * x ) {
666 return x->result && ( x->get_lvalue() || x->result.as< ast::ReferenceType >() );
667 }
668
669 void postvisit( const ast::UntypedExpr * untypedExpr );
670 void postvisit( const ast::VariableExpr * variableExpr );
671 void postvisit( const ast::ConstantExpr * constantExpr );
672 void postvisit( const ast::SizeofExpr * sizeofExpr );
673 void postvisit( const ast::AlignofExpr * alignofExpr );
674 void postvisit( const ast::AddressExpr * addressExpr );
675 void postvisit( const ast::LabelAddressExpr * labelExpr );
676 void postvisit( const ast::CastExpr * castExpr );
677 void postvisit( const ast::VirtualCastExpr * castExpr );
678 void postvisit( const ast::KeywordCastExpr * castExpr );
679 void postvisit( const ast::UntypedMemberExpr * memberExpr );
680 void postvisit( const ast::MemberExpr * memberExpr );
681 void postvisit( const ast::NameExpr * nameExpr );
682 void postvisit( const ast::UntypedOffsetofExpr * offsetofExpr );
683 void postvisit( const ast::OffsetofExpr * offsetofExpr );
684 void postvisit( const ast::OffsetPackExpr * offsetPackExpr );
685 void postvisit( const ast::LogicalExpr * logicalExpr );
686 void postvisit( const ast::ConditionalExpr * conditionalExpr );
687 void postvisit( const ast::CommaExpr * commaExpr );
688 void postvisit( const ast::ImplicitCopyCtorExpr * ctorExpr );
689 void postvisit( const ast::ConstructorExpr * ctorExpr );
690 void postvisit( const ast::RangeExpr * rangeExpr );
691 void postvisit( const ast::UntypedTupleExpr * tupleExpr );
692 void postvisit( const ast::TupleExpr * tupleExpr );
693 void postvisit( const ast::TupleIndexExpr * tupleExpr );
694 void postvisit( const ast::TupleAssignExpr * tupleExpr );
695 void postvisit( const ast::UniqueExpr * unqExpr );
696 void postvisit( const ast::StmtExpr * stmtExpr );
697 void postvisit( const ast::UntypedInitExpr * initExpr );
[a55ebcc]698 void postvisit( const ast::QualifiedNameExpr * qualifiedExpr );
[525f7ad]699 void postvisit( const ast::CountExpr * countExpr );
[64727bd]700
701 void postvisit( const ast::InitExpr * ) {
702 assertf( false, "CandidateFinder should never see a resolved InitExpr." );
703 }
704
705 void postvisit( const ast::DeletedExpr * ) {
706 assertf( false, "CandidateFinder should never see a DeletedExpr." );
707 }
708
709 void postvisit( const ast::GenericExpr * ) {
710 assertf( false, "_Generic is not yet supported." );
711 }
712 };
713
714 /// Set up candidate assertions for inference
715 void Finder::inferParameters( CandidateRef & newCand, CandidateList & out ) {
716 // Set need bindings for any unbound assertions
[fa761c2]717 ast::UniqueId crntResnSlot = 0; // matching ID for this expression's assertions
[64727bd]718 for ( auto & assn : newCand->need ) {
719 // skip already-matched assertions
720 if ( assn.second.resnSlot != 0 ) continue;
721 // assign slot for expression if needed
722 if ( crntResnSlot == 0 ) { crntResnSlot = ++globalResnSlot; }
723 // fix slot to assertion
724 assn.second.resnSlot = crntResnSlot;
725 }
726 // pair slot to expression
727 if ( crntResnSlot != 0 ) {
728 newCand->expr.get_and_mutate()->inferred.resnSlots().emplace_back( crntResnSlot );
729 }
730
731 // add to output list; assertion satisfaction will occur later
732 out.emplace_back( newCand );
733 }
734
735 /// Completes a function candidate with arguments located
736 void Finder::validateFunctionCandidate(
737 const CandidateRef & func, ArgPack & result, const std::vector< ArgPack > & results,
738 CandidateList & out
739 ) {
740 ast::ApplicationExpr * appExpr =
741 new ast::ApplicationExpr{ func->expr->location, func->expr };
742 // sum cost and accumulate arguments
743 std::deque< const ast::Expr * > args;
744 Cost cost = func->cost;
745 const ArgPack * pack = &result;
746 while ( pack->expr ) {
747 args.emplace_front( pack->expr );
748 cost += pack->cost;
749 pack = &results[pack->parent];
750 }
751 std::vector< ast::ptr< ast::Expr > > vargs( args.begin(), args.end() );
752 appExpr->args = std::move( vargs );
753 // build and validate new candidate
754 auto newCand =
755 std::make_shared<Candidate>( appExpr, result.env, result.open, result.need, cost );
756 PRINT(
757 std::cerr << "instantiate function success: " << appExpr << std::endl;
758 std::cerr << "need assertions:" << std::endl;
759 ast::print( std::cerr, result.need, 2 );
760 )
761 inferParameters( newCand, out );
762 }
763
764 /// Builds a list of candidates for a function, storing them in out
765 void Finder::makeFunctionCandidates(
766 const CodeLocation & location,
767 const CandidateRef & func, const ast::FunctionType * funcType,
[0bd3faf]768 const ExplodedArgs & args, CandidateList & out
[64727bd]769 ) {
770 ast::OpenVarSet funcOpen;
771 ast::AssertionSet funcNeed, funcHave;
772 ast::TypeEnvironment funcEnv{ func->env };
773 makeUnifiableVars( funcType, funcOpen, funcNeed );
774 // add all type variables as open variables now so that those not used in the
775 // parameter list are still considered open
776 funcEnv.add( funcType->forall );
777
778 if ( targetType && ! targetType->isVoid() && ! funcType->returns.empty() ) {
779 // attempt to narrow based on expected target type
780 const ast::Type * returnType = funcType->returns.front();
781 if ( selfFinder.strictMode ) {
[2908f08]782 if ( !unifyExact(
[64727bd]783 returnType, targetType, funcEnv, funcNeed, funcHave, funcOpen, noWiden() ) // xxx - is no widening correct?
784 ) {
785 // unification failed, do not pursue this candidate
786 return;
[954c954]787 }
[2908f08]788 } else {
789 if ( !unify(
[64727bd]790 returnType, targetType, funcEnv, funcNeed, funcHave, funcOpen )
791 ) {
792 // unification failed, do not pursue this candidate
793 return;
794 }
[9d5089e]795 }
[64727bd]796 }
[9d5089e]797
[64727bd]798 // iteratively build matches, one parameter at a time
799 std::vector< ArgPack > results;
800 results.emplace_back( funcEnv, funcNeed, funcHave, funcOpen );
801 std::size_t genStart = 0;
[9d5089e]802
[64727bd]803 // xxx - how to handle default arg after change to ftype representation?
804 if (const ast::VariableExpr * varExpr = func->expr.as<ast::VariableExpr>()) {
805 if (const ast::FunctionDecl * funcDecl = varExpr->var.as<ast::FunctionDecl>()) {
806 // function may have default args only if directly calling by name
807 // must use types on candidate however, due to RenameVars substitution
808 auto nParams = funcType->params.size();
[9d5089e]809
[64727bd]810 for (size_t i=0; i<nParams; ++i) {
811 auto obj = funcDecl->params[i].strict_as<ast::ObjectDecl>();
812 if ( !instantiateArgument( location,
[af746cc]813 funcType->params[i], obj->init, args, results, genStart, context)) return;
[64727bd]814 }
815 goto endMatch;
816 }
817 }
818 for ( const auto & param : funcType->params ) {
819 // Try adding the arguments corresponding to the current parameter to the existing
820 // matches
821 // no default args for indirect calls
822 if ( !instantiateArgument( location,
[af746cc]823 param, nullptr, args, results, genStart, context ) ) return;
[64727bd]824 }
[9d5089e]825
[64727bd]826 endMatch:
827 if ( funcType->isVarArgs ) {
828 // append any unused arguments to vararg pack
829 std::size_t genEnd;
830 do {
831 genEnd = results.size();
[9d5089e]832
[64727bd]833 // iterate results
834 for ( std::size_t i = genStart; i < genEnd; ++i ) {
835 unsigned nextArg = results[i].nextArg;
[9d5089e]836
[64727bd]837 // use remainder of exploded tuple if present
838 if ( results[i].hasExpl() ) {
839 const ExplodedArg & expl = results[i].getExpl( args );
[9d5089e]840
[64727bd]841 unsigned nextExpl = results[i].nextExpl + 1;
842 if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
[9d5089e]843
[64727bd]844 results.emplace_back(
845 i, expl.exprs[ results[i].nextExpl ], copy( results[i].env ),
846 copy( results[i].need ), copy( results[i].have ),
847 copy( results[i].open ), nextArg, 0, Cost::zero, nextExpl,
848 results[i].explAlt );
849
850 continue;
851 }
[9d5089e]852
[64727bd]853 // finish result when out of arguments
854 if ( nextArg >= args.size() ) {
855 validateFunctionCandidate( func, results[i], results, out );
[9d5089e]856
[64727bd]857 continue;
858 }
[9d5089e]859
[64727bd]860 // add each possible next argument
861 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
862 const ExplodedArg & expl = args[nextArg][j];
[9d5089e]863
[64727bd]864 // fresh copies of parent parameters for this iteration
865 ast::TypeEnvironment env = results[i].env;
866 ast::OpenVarSet open = results[i].open;
[9d5089e]867
[64727bd]868 env.addActual( expl.env, open );
[9d5089e]869
[64727bd]870 // skip empty tuple arguments by (nearly) cloning parent into next gen
871 if ( expl.exprs.empty() ) {
[9d5089e]872 results.emplace_back(
[64727bd]873 results[i], std::move( env ), copy( results[i].need ),
874 copy( results[i].have ), std::move( open ), nextArg + 1,
875 expl.cost );
876
877 continue;
[9d5089e]878 }
879
[64727bd]880 // add new result
881 results.emplace_back(
882 i, expl.exprs.front(), std::move( env ), copy( results[i].need ),
883 copy( results[i].have ), std::move( open ), nextArg + 1, 0, expl.cost,
884 expl.exprs.size() == 1 ? 0 : 1, j );
[9d5089e]885 }
886 }
[64727bd]887
888 genStart = genEnd;
889 } while( genEnd != results.size() );
890 } else {
891 // filter out the results that don't use all the arguments
892 for ( std::size_t i = genStart; i < results.size(); ++i ) {
893 ArgPack & result = results[i];
894 if ( ! result.hasExpl() && result.nextArg >= args.size() ) {
895 validateFunctionCandidate( func, result, results, out );
896 }
[9d5089e]897 }
[4b7cce6]898 }
[64727bd]899 }
[4b7cce6]900
[85855b0]901 void Finder::addEnumValueAsCandidate( const ast::EnumInstType * enumInst, const ast::Expr * expr,
902 const Cost & addedCost
903 ) {
904 if ( enumInst->base->base ) {
905 CandidateFinder finder( context, tenv );
906 auto location = expr->location;
907 auto callExpr = new ast::UntypedExpr(
[5eb3f65]908 location, new ast::NameExpr( location, "value" ), {expr}
[85855b0]909 );
910 finder.find( callExpr );
911 CandidateList winners = findMinCost( finder.candidates );
912 if (winners.size() != 1) {
[5eb3f65]913 SemanticError( callExpr, "Ambiguous expression in value..." );
[85855b0]914 }
915 CandidateRef & choice = winners.front();
916 choice->cost += addedCost;
917 addAnonConversions(choice);
918 candidates.emplace_back( std::move(choice) );
919 }
920 }
921
[64727bd]922 /// Adds implicit struct-conversions to the alternative list
923 void Finder::addAnonConversions( const CandidateRef & cand ) {
924 // adds anonymous member interpretations whenever an aggregate value type is seen.
925 // it's okay for the aggregate expression to have reference type -- cast it to the
926 // base type to treat the aggregate as the referenced value
927 ast::ptr< ast::Expr > aggrExpr( cand->expr );
928 ast::ptr< ast::Type > & aggrType = aggrExpr.get_and_mutate()->result;
929 cand->env.apply( aggrType );
[2890212]930
[64727bd]931 if ( aggrType.as< ast::ReferenceType >() ) {
932 aggrExpr = new ast::CastExpr{ aggrExpr, aggrType->stripReferences() };
933 }
[c8e4d2f8]934
[64727bd]935 if ( auto structInst = aggrExpr->result.as< ast::StructInstType >() ) {
936 addAggMembers( structInst, aggrExpr, *cand, Cost::unsafe, "" );
937 } else if ( auto unionInst = aggrExpr->result.as< ast::UnionInstType >() ) {
938 addAggMembers( unionInst, aggrExpr, *cand, Cost::unsafe, "" );
[af746cc]939 } else if ( auto enumInst = aggrExpr->result.as< ast::EnumInstType >() ) {
[85855b0]940 addEnumValueAsCandidate(enumInst, aggrExpr, Cost::unsafe);
[c8e4d2f8]941 }
[64727bd]942 }
[85855b0]943
[c8e4d2f8]944
[64727bd]945 /// Adds aggregate member interpretations
946 void Finder::addAggMembers(
947 const ast::BaseInstType * aggrInst, const ast::Expr * expr,
948 const Candidate & cand, const Cost & addedCost, const std::string & name
949 ) {
950 for ( const ast::Decl * decl : aggrInst->lookup( name ) ) {
951 auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( decl );
952 CandidateRef newCand = std::make_shared<Candidate>(
953 cand, new ast::MemberExpr{ expr->location, dwt, expr }, addedCost );
954 // add anonymous member interpretations whenever an aggregate value type is seen
955 // as a member expression
956 addAnonConversions( newCand );
957 candidates.emplace_back( std::move( newCand ) );
[432ce7a]958 }
[64727bd]959 }
[432ce7a]960
[64727bd]961 /// Adds tuple member interpretations
962 void Finder::addTupleMembers(
963 const ast::TupleType * tupleType, const ast::Expr * expr, const Candidate & cand,
964 const Cost & addedCost, const ast::Expr * member
965 ) {
966 if ( auto constantExpr = dynamic_cast< const ast::ConstantExpr * >( member ) ) {
967 // get the value of the constant expression as an int, must be between 0 and the
968 // length of the tuple to have meaning
969 long long val = constantExpr->intValue();
970 if ( val >= 0 && (unsigned long long)val < tupleType->size() ) {
971 addCandidate(
972 cand, new ast::TupleIndexExpr{ expr->location, expr, (unsigned)val },
973 addedCost );
[898ae07]974 }
975 }
[64727bd]976 }
[898ae07]977
[64727bd]978 void Finder::postvisit( const ast::UntypedExpr * untypedExpr ) {
979 std::vector< CandidateFinder > argCandidates =
980 selfFinder.findSubExprs( untypedExpr->args );
981
982 // take care of possible tuple assignments
983 // if not tuple assignment, handled as normal function call
984 Tuples::handleTupleAssignment( selfFinder, untypedExpr, argCandidates );
985
986 CandidateFinder funcFinder( context, tenv );
[acb33f15]987 std::string funcName;
[64727bd]988 if (auto nameExpr = untypedExpr->func.as<ast::NameExpr>()) {
[acb33f15]989 funcName = nameExpr->name;
[64727bd]990 auto kind = ast::SymbolTable::getSpecialFunctionKind(nameExpr->name);
991 if (kind != ast::SymbolTable::SpecialFunctionKind::NUMBER_OF_KINDS) {
992 assertf(!argCandidates.empty(), "special function call without argument");
993 for (auto & firstArgCand: argCandidates[0]) {
994 ast::ptr<ast::Type> argType = firstArgCand->expr->result;
995 firstArgCand->env.apply(argType);
996 // strip references
997 // xxx - is this correct?
998 while (argType.as<ast::ReferenceType>()) argType = argType.as<ast::ReferenceType>()->base;
999
1000 // convert 1-tuple to plain type
1001 if (auto tuple = argType.as<ast::TupleType>()) {
1002 if (tuple->size() == 1) {
1003 argType = tuple->types[0];
[e5c3811]1004 }
[64727bd]1005 }
[e5c3811]1006
[64727bd]1007 // if argType is an unbound type parameter, all special functions need to be searched.
1008 if (isUnboundType(argType)) {
1009 funcFinder.otypeKeys.clear();
1010 break;
[e5c3811]1011 }
[64727bd]1012
[14755e5]1013 if (argType.as<ast::PointerType>()) funcFinder.otypeKeys.insert(Mangle::Encoding::pointer);
[64727bd]1014 else funcFinder.otypeKeys.insert(Mangle::mangle(argType, Mangle::NoGenericParams | Mangle::Type));
[e5c3811]1015 }
1016 }
[64727bd]1017 }
1018 // if candidates are already produced, do not fail
1019 // xxx - is it possible that handleTupleAssignment and main finder both produce candidates?
1020 // this means there exists ctor/assign functions with a tuple as first parameter.
[4a89b52]1021 ResolveMode mode = {
[64727bd]1022 true, // adjust
1023 !untypedExpr->func.as<ast::NameExpr>(), // prune if not calling by name
1024 selfFinder.candidates.empty() // failfast if other options are not found
1025 };
1026 funcFinder.find( untypedExpr->func, mode );
1027 // short-circuit if no candidates
1028 // if ( funcFinder.candidates.empty() ) return;
[432ce7a]1029
[64727bd]1030 reason.code = NoMatch;
[432ce7a]1031
[64727bd]1032 // find function operators
1033 ast::ptr< ast::Expr > opExpr = new ast::NameExpr{ untypedExpr->location, "?()" }; // ??? why not ?{}
1034 CandidateFinder opFinder( context, tenv );
1035 // okay if there aren't any function operations
[4a89b52]1036 opFinder.find( opExpr, ResolveMode::withoutFailFast() );
[64727bd]1037 PRINT(
1038 std::cerr << "known function ops:" << std::endl;
1039 print( std::cerr, opFinder.candidates, 1 );
1040 )
[432ce7a]1041
[64727bd]1042 // pre-explode arguments
[0bd3faf]1043 ExplodedArgs argExpansions;
[64727bd]1044 for ( const CandidateFinder & args : argCandidates ) {
1045 argExpansions.emplace_back();
1046 auto & argE = argExpansions.back();
1047 for ( const CandidateRef & arg : args ) { argE.emplace_back( *arg, symtab ); }
1048 }
1049
1050 // Find function matches
1051 CandidateList found;
1052 SemanticErrorException errors;
[acb33f15]1053
[64727bd]1054 for ( CandidateRef & func : funcFinder ) {
1055 try {
1056 PRINT(
1057 std::cerr << "working on alternative:" << std::endl;
1058 print( std::cerr, *func, 2 );
1059 )
1060
1061 // check if the type is a pointer to function
1062 const ast::Type * funcResult = func->expr->result->stripReferences();
1063 if ( auto pointer = dynamic_cast< const ast::PointerType * >( funcResult ) ) {
1064 if ( auto function = pointer->base.as< ast::FunctionType >() ) {
1065 // if (!selfFinder.allowVoid && function->returns.empty()) continue;
1066 CandidateRef newFunc{ new Candidate{ *func } };
1067 newFunc->expr =
1068 referenceToRvalueConversion( newFunc->expr, newFunc->cost );
1069 makeFunctionCandidates( untypedExpr->location,
1070 newFunc, function, argExpansions, found );
1071 }
1072 } else if (
1073 auto inst = dynamic_cast< const ast::TypeInstType * >( funcResult )
1074 ) {
1075 if ( const ast::EqvClass * clz = func->env.lookup( *inst ) ) {
1076 if ( auto function = clz->bound.as< ast::FunctionType >() ) {
1077 CandidateRef newFunc( new Candidate( *func ) );
[2890212]1078 newFunc->expr =
[432ce7a]1079 referenceToRvalueConversion( newFunc->expr, newFunc->cost );
[b96b1c0]1080 makeFunctionCandidates( untypedExpr->location,
1081 newFunc, function, argExpansions, found );
[432ce7a]1082 }
1083 }
[64727bd]1084 }
1085 } catch ( SemanticErrorException & e ) { errors.append( e ); }
1086 }
1087
1088 // Find matches on function operators `?()`
1089 if ( ! opFinder.candidates.empty() ) {
1090 // add exploded function alternatives to front of argument list
1091 std::vector< ExplodedArg > funcE;
1092 funcE.reserve( funcFinder.candidates.size() );
1093 for ( const CandidateRef & func : funcFinder ) {
1094 funcE.emplace_back( *func, symtab );
[432ce7a]1095 }
[64727bd]1096 argExpansions.emplace_front( std::move( funcE ) );
[432ce7a]1097
[64727bd]1098 for ( const CandidateRef & op : opFinder ) {
1099 try {
1100 // check if type is pointer-to-function
1101 const ast::Type * opResult = op->expr->result->stripReferences();
1102 if ( auto pointer = dynamic_cast< const ast::PointerType * >( opResult ) ) {
1103 if ( auto function = pointer->base.as< ast::FunctionType >() ) {
1104 CandidateRef newOp{ new Candidate{ *op} };
1105 newOp->expr =
1106 referenceToRvalueConversion( newOp->expr, newOp->cost );
1107 makeFunctionCandidates( untypedExpr->location,
1108 newOp, function, argExpansions, found );
[432ce7a]1109 }
[64727bd]1110 }
1111 } catch ( SemanticErrorException & e ) { errors.append( e ); }
[432ce7a]1112 }
[64727bd]1113 }
[432ce7a]1114
[64727bd]1115 // Implement SFINAE; resolution errors are only errors if there aren't any non-error
1116 // candidates
1117 if ( found.empty() && ! errors.isEmpty() ) { throw errors; }
[432ce7a]1118
[64727bd]1119 // only keep the best matching intrinsic result to match C semantics (no unexpected narrowing/widening)
1120 // TODO: keep one for each set of argument candidates?
1121 Cost intrinsicCost = Cost::infinity;
1122 CandidateList intrinsicResult;
[46da46b]1123
[64727bd]1124 // Compute conversion costs
1125 for ( CandidateRef & withFunc : found ) {
1126 Cost cvtCost = computeApplicationConversionCost( withFunc, symtab );
[432ce7a]1127
[acb33f15]1128 if (funcName == "?|?") {
[64727bd]1129 PRINT(
1130 auto appExpr = withFunc->expr.strict_as< ast::ApplicationExpr >();
1131 auto pointer = appExpr->func->result.strict_as< ast::PointerType >();
1132 auto function = pointer->base.strict_as< ast::FunctionType >();
1133
1134 std::cerr << "Case +++++++++++++ " << appExpr->func << std::endl;
1135 std::cerr << "parameters are:" << std::endl;
1136 ast::printAll( std::cerr, function->params, 2 );
1137 std::cerr << "arguments are:" << std::endl;
1138 ast::printAll( std::cerr, appExpr->args, 2 );
1139 std::cerr << "bindings are:" << std::endl;
1140 ast::print( std::cerr, withFunc->env, 2 );
1141 std::cerr << "cost is: " << withFunc->cost << std::endl;
1142 std::cerr << "cost of conversion is:" << cvtCost << std::endl;
1143 )
[acb33f15]1144 }
[64727bd]1145 if ( cvtCost != Cost::infinity ) {
1146 withFunc->cvtCost = cvtCost;
1147 withFunc->cost += cvtCost;
1148 auto func = withFunc->expr.strict_as<ast::ApplicationExpr>()->func.as<ast::VariableExpr>();
1149 if (func && func->var->linkage == ast::Linkage::Intrinsic) {
1150 if (withFunc->cost < intrinsicCost) {
1151 intrinsicResult.clear();
1152 intrinsicCost = withFunc->cost;
1153 }
1154 if (withFunc->cost == intrinsicCost) {
1155 intrinsicResult.emplace_back(std::move(withFunc));
[46da46b]1156 }
[2908f08]1157 } else {
[64727bd]1158 candidates.emplace_back( std::move( withFunc ) );
1159 }
[432ce7a]1160 }
1161 }
[64727bd]1162 spliceBegin( candidates, intrinsicResult );
1163 found = std::move( candidates );
1164
1165 // use a new list so that candidates are not examined by addAnonConversions twice
1166 // CandidateList winners = findMinCost( found );
1167 // promoteCvtCost( winners );
1168
1169 // function may return a struct/union value, in which case we need to add candidates
1170 // for implicit conversions to each of the anonymous members, which must happen after
1171 // `findMinCost`, since anon conversions are never the cheapest
1172 for ( const CandidateRef & c : found ) {
1173 addAnonConversions( c );
1174 }
1175 // would this be too slow when we don't check cost anymore?
1176 spliceBegin( candidates, found );
1177
1178 if ( candidates.empty() && targetType && ! targetType->isVoid() && !selfFinder.strictMode ) {
1179 // If resolution is unsuccessful with a target type, try again without, since it
1180 // will sometimes succeed when it wouldn't with a target type binding.
1181 // For example:
1182 // forall( otype T ) T & ?[]( T *, ptrdiff_t );
1183 // const char * x = "hello world";
1184 // unsigned char ch = x[0];
1185 // Fails with simple return type binding (xxx -- check this!) as follows:
1186 // * T is bound to unsigned char
1187 // * (x: const char *) is unified with unsigned char *, which fails
1188 // xxx -- fix this better
1189 targetType = nullptr;
1190 postvisit( untypedExpr );
[4b7cce6]1191 }
[64727bd]1192 }
[4b7cce6]1193
[64727bd]1194 void Finder::postvisit( const ast::AddressExpr * addressExpr ) {
1195 CandidateFinder finder( context, tenv );
1196 finder.find( addressExpr->arg );
[71d6bd8]1197
[64727bd]1198 if ( finder.candidates.empty() ) return;
[71d6bd8]1199
[64727bd]1200 reason.code = NoMatch;
[4b7cce6]1201
[64727bd]1202 for ( CandidateRef & r : finder.candidates ) {
[2908f08]1203 if ( !isLvalue( r->expr ) ) continue;
[64727bd]1204 addCandidate( *r, new ast::AddressExpr{ addressExpr->location, r->expr } );
[4b7cce6]1205 }
[64727bd]1206 }
[4b7cce6]1207
[64727bd]1208 void Finder::postvisit( const ast::LabelAddressExpr * labelExpr ) {
1209 addCandidate( labelExpr, tenv );
1210 }
[c8e4d2f8]1211
[64727bd]1212 void Finder::postvisit( const ast::CastExpr * castExpr ) {
1213 ast::ptr< ast::Type > toType = castExpr->result;
1214 assert( toType );
1215 toType = resolveTypeof( toType, context );
1216 toType = adjustExprType( toType, tenv, symtab );
[46da46b]1217
[64727bd]1218 CandidateFinder finder( context, tenv, toType );
1219 if (toType->isVoid()) {
1220 finder.allowVoid = true;
1221 }
1222 if ( castExpr->kind == ast::CastExpr::Return ) {
1223 finder.strictMode = true;
[4a89b52]1224 finder.find( castExpr->arg, ResolveMode::withAdjustment() );
[c8e4d2f8]1225
[64727bd]1226 // return casts are eliminated (merely selecting an overload, no actual operation)
1227 candidates = std::move(finder.candidates);
[0f5e8cd]1228 return;
1229 }
1230 else if (toType->isVoid()) {
1231 finder.find( castExpr->arg ); // no adjust
1232 }
1233 else {
1234 finder.find( castExpr->arg, ResolveMode::withAdjustment() );
[64727bd]1235 }
[71d6bd8]1236
[64727bd]1237 if ( !finder.candidates.empty() ) reason.code = NoMatch;
[c8e4d2f8]1238
[64727bd]1239 CandidateList matches;
1240 Cost minExprCost = Cost::infinity;
1241 Cost minCastCost = Cost::infinity;
1242 for ( CandidateRef & cand : finder.candidates ) {
1243 ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have;
1244 ast::OpenVarSet open( cand->open );
[c8e4d2f8]1245
[64727bd]1246 cand->env.extractOpenVars( open );
[c8e4d2f8]1247
[64727bd]1248 // It is possible that a cast can throw away some values in a multiply-valued
1249 // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of the
1250 // subexpression results that are cast directly. The candidate is invalid if it
1251 // has fewer results than there are types to cast to.
1252 int discardedValues = cand->expr->result->size() - toType->size();
1253 if ( discardedValues < 0 ) continue;
[bb87dd0]1254
[64727bd]1255 // unification run for side-effects
1256 unify( toType, cand->expr->result, cand->env, need, have, open );
1257 Cost thisCost =
1258 (castExpr->isGenerated == ast::GeneratedFlag::GeneratedCast)
1259 ? conversionCost( cand->expr->result, toType, cand->expr->get_lvalue(), symtab, cand->env )
1260 : castCost( cand->expr->result, toType, cand->expr->get_lvalue(), symtab, cand->env );
[85855b0]1261
1262 // Redefine enum cast
1263 auto argAsEnum = cand->expr->result.as<ast::EnumInstType>();
1264 auto toAsEnum = toType.as<ast::EnumInstType>();
[d3aa55e9]1265 if ( argAsEnum && toAsEnum && argAsEnum->name != toAsEnum->name ) {
1266 CandidateFinder subFinder(context, tenv);
1267 ast::ptr<ast::Expr> offsetExpr = subFinder.makeEnumOffsetCast(argAsEnum, toAsEnum, cand->expr, thisCost);
[d68a3f7]1268 if ( offsetExpr )
1269 cand->expr = offsetExpr;
[85855b0]1270 }
[64727bd]1271
1272 PRINT(
1273 std::cerr << "working on cast with result: " << toType << std::endl;
1274 std::cerr << "and expr type: " << cand->expr->result << std::endl;
1275 std::cerr << "env: " << cand->env << std::endl;
1276 )
1277 if ( thisCost != Cost::infinity ) {
[c8e4d2f8]1278 PRINT(
[64727bd]1279 std::cerr << "has finite cost." << std::endl;
[c8e4d2f8]1280 )
[64727bd]1281 // count one safe conversion for each value that is thrown away
1282 thisCost.incSafe( discardedValues );
1283 // select first on argument cost, then conversion cost
1284 if ( cand->cost < minExprCost || ( cand->cost == minExprCost && thisCost < minCastCost ) ) {
1285 minExprCost = cand->cost;
1286 minCastCost = thisCost;
1287 matches.clear();
[c8e4d2f8]1288 }
[85855b0]1289 // ambigious case, still output candidates to print in error message
[64727bd]1290 if ( cand->cost == minExprCost && thisCost == minCastCost ) {
1291 CandidateRef newCand = std::make_shared<Candidate>(
1292 restructureCast( cand->expr, toType, castExpr->isGenerated ),
1293 copy( cand->env ), std::move( open ), std::move( need ), cand->cost + thisCost);
[14755e5]1294 // currently assertions are always resolved immediately so this should have no effect.
[64727bd]1295 // if this somehow changes in the future (e.g. delayed by indeterminate return type)
1296 // we may need to revisit the logic.
1297 inferParameters( newCand, matches );
1298 }
1299 // else skip, better alternatives found
[4b7cce6]1300
1301 }
1302 }
[64727bd]1303 candidates = std::move(matches);
1304 //CandidateList minArgCost = findMinCost( matches );
1305 //promoteCvtCost( minArgCost );
1306 //candidates = findMinCost( minArgCost );
1307 }
[4ef08f7]1308
[64727bd]1309 void Finder::postvisit( const ast::VirtualCastExpr * castExpr ) {
1310 assertf( castExpr->result, "Implicit virtual cast targets not yet supported." );
1311 CandidateFinder finder( context, tenv );
1312 // don't prune here, all alternatives guaranteed to have same type
[4a89b52]1313 finder.find( castExpr->arg, ResolveMode::withoutPrune() );
[64727bd]1314 for ( CandidateRef & r : finder.candidates ) {
1315 addCandidate(
1316 *r,
1317 new ast::VirtualCastExpr{ castExpr->location, r->expr, castExpr->result } );
1318 }
1319 }
[4ef08f7]1320
[64727bd]1321 void Finder::postvisit( const ast::KeywordCastExpr * castExpr ) {
1322 const auto & loc = castExpr->location;
1323 assertf( castExpr->result, "Cast target should have been set in Validate." );
1324 auto ref = castExpr->result.strict_as<ast::ReferenceType>();
1325 auto inst = ref->base.strict_as<ast::StructInstType>();
1326 auto target = inst->base.get();
1327
1328 CandidateFinder finder( context, tenv );
1329
1330 auto pick_alternatives = [target, this](CandidateList & found, bool expect_ref) {
1331 for (auto & cand : found) {
1332 const ast::Type * expr = cand->expr->result.get();
1333 if (expect_ref) {
1334 auto res = dynamic_cast<const ast::ReferenceType*>(expr);
1335 if (!res) { continue; }
1336 expr = res->base.get();
1337 }
[4ef08f7]1338
[64727bd]1339 if (auto insttype = dynamic_cast<const ast::TypeInstType*>(expr)) {
1340 auto td = cand->env.lookup(*insttype);
1341 if (!td) { continue; }
1342 expr = td->bound.get();
1343 }
[4ef08f7]1344
[64727bd]1345 if (auto base = dynamic_cast<const ast::StructInstType*>(expr)) {
1346 if (base->base == target) {
1347 candidates.push_back( std::move(cand) );
1348 reason.code = NoReason;
[4ef08f7]1349 }
1350 }
[64727bd]1351 }
1352 };
[4ef08f7]1353
[64727bd]1354 try {
1355 // Attempt 1 : turn (thread&)X into (thread$&)X.__thrd
1356 // Clone is purely for memory management
1357 std::unique_ptr<const ast::Expr> tech1 { new ast::UntypedMemberExpr(loc, new ast::NameExpr(loc, castExpr->concrete_target.field), castExpr->arg) };
[4ef08f7]1358
[64727bd]1359 // don't prune here, since it's guaranteed all alternatives will have the same type
[4a89b52]1360 finder.find( tech1.get(), ResolveMode::withoutPrune() );
[64727bd]1361 pick_alternatives(finder.candidates, false);
[4ef08f7]1362
[64727bd]1363 return;
1364 } catch(SemanticErrorException & ) {}
[4ef08f7]1365
[64727bd]1366 // Fallback : turn (thread&)X into (thread$&)get_thread(X)
1367 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 })) };
1368 // don't prune here, since it's guaranteed all alternatives will have the same type
[4a89b52]1369 finder.find( fallback.get(), ResolveMode::withoutPrune() );
[64727bd]1370
1371 pick_alternatives(finder.candidates, true);
1372
1373 // Whatever happens here, we have no more fallbacks
1374 }
1375
1376 void Finder::postvisit( const ast::UntypedMemberExpr * memberExpr ) {
1377 CandidateFinder aggFinder( context, tenv );
[4a89b52]1378 aggFinder.find( memberExpr->aggregate, ResolveMode::withAdjustment() );
[64727bd]1379 for ( CandidateRef & agg : aggFinder.candidates ) {
1380 // it's okay for the aggregate expression to have reference type -- cast it to the
1381 // base type to treat the aggregate as the referenced value
1382 Cost addedCost = Cost::zero;
1383 agg->expr = referenceToRvalueConversion( agg->expr, addedCost );
1384
1385 // find member of the given type
1386 if ( auto structInst = agg->expr->result.as< ast::StructInstType >() ) {
1387 addAggMembers(
1388 structInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) );
1389 } else if ( auto unionInst = agg->expr->result.as< ast::UnionInstType >() ) {
1390 addAggMembers(
1391 unionInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) );
1392 } else if ( auto tupleType = agg->expr->result.as< ast::TupleType >() ) {
1393 addTupleMembers( tupleType, agg->expr, *agg, addedCost, memberExpr->member );
[898ae07]1394 }
[4b7cce6]1395 }
[64727bd]1396 }
[4b7cce6]1397
[64727bd]1398 void Finder::postvisit( const ast::MemberExpr * memberExpr ) {
1399 addCandidate( memberExpr, tenv );
1400 }
[4b7cce6]1401
[64727bd]1402 void Finder::postvisit( const ast::NameExpr * nameExpr ) {
1403 std::vector< ast::SymbolTable::IdData > declList;
1404 if (!selfFinder.otypeKeys.empty()) {
1405 auto kind = ast::SymbolTable::getSpecialFunctionKind(nameExpr->name);
1406 assertf(kind != ast::SymbolTable::SpecialFunctionKind::NUMBER_OF_KINDS, "special lookup with non-special target: %s", nameExpr->name.c_str());
[e5c3811]1407
[64727bd]1408 for (auto & otypeKey: selfFinder.otypeKeys) {
1409 auto result = symtab.specialLookupId(kind, otypeKey);
1410 declList.insert(declList.end(), std::make_move_iterator(result.begin()), std::make_move_iterator(result.end()));
[e5c3811]1411 }
[64727bd]1412 } else {
[85855b0]1413 declList = symtab.lookupIdIgnoreHidden( nameExpr->name );
[64727bd]1414 }
1415 PRINT( std::cerr << "nameExpr is " << nameExpr->name << std::endl; )
[71d6bd8]1416
[64727bd]1417 if ( declList.empty() ) return;
[71d6bd8]1418
[64727bd]1419 reason.code = NoMatch;
[898ae07]1420
[64727bd]1421 for ( auto & data : declList ) {
1422 Cost cost = Cost::zero;
1423 ast::Expr * newExpr = data.combine( nameExpr->location, cost );
[9e23b446]1424
[64727bd]1425 CandidateRef newCand = std::make_shared<Candidate>(
[eb7586e]1426 newExpr, copy( tenv ), ast::OpenVarSet{}, ast::AssertionSet{}, Cost::zero,
[64727bd]1427 cost );
1428 if (newCand->expr->env) {
1429 newCand->env.add(*newCand->expr->env);
1430 auto mutExpr = newCand->expr.get_and_mutate();
1431 mutExpr->env = nullptr;
1432 newCand->expr = mutExpr;
[898ae07]1433 }
[4b7cce6]1434
[64727bd]1435 PRINT(
1436 std::cerr << "decl is ";
1437 ast::print( std::cerr, data.id );
1438 std::cerr << std::endl;
1439 std::cerr << "newExpr is ";
1440 ast::print( std::cerr, newExpr );
1441 std::cerr << std::endl;
1442 )
1443 newCand->expr = ast::mutate_field(
1444 newCand->expr.get(), &ast::Expr::result,
1445 renameTyVars( newCand->expr->result ) );
1446 // add anonymous member interpretations whenever an aggregate value type is seen
1447 // as a name expression
1448 addAnonConversions( newCand );
1449 candidates.emplace_back( std::move( newCand ) );
[4b7cce6]1450 }
[64727bd]1451 }
[4b7cce6]1452
[fc1a3e2]1453 void Finder::postvisit(const ast::VariableExpr *variableExpr) {
1454 // not sufficient to just pass `variableExpr` here, type might have changed
[0522ebe]1455
[fc1a3e2]1456 auto cand = new Candidate(variableExpr, tenv);
1457 candidates.emplace_back(cand);
1458 }
[4b7cce6]1459
[64727bd]1460 void Finder::postvisit( const ast::ConstantExpr * constantExpr ) {
1461 addCandidate( constantExpr, tenv );
1462 }
[4b7cce6]1463
[64727bd]1464 void Finder::postvisit( const ast::SizeofExpr * sizeofExpr ) {
1465 if ( sizeofExpr->type ) {
1466 addCandidate(
1467 new ast::SizeofExpr{
1468 sizeofExpr->location, resolveTypeof( sizeofExpr->type, context ) },
1469 tenv );
1470 } else {
1471 // find all candidates for the argument to sizeof
1472 CandidateFinder finder( context, tenv );
1473 finder.find( sizeofExpr->expr );
1474 // find the lowest-cost candidate, otherwise ambiguous
1475 CandidateList winners = findMinCost( finder.candidates );
1476 if ( winners.size() != 1 ) {
1477 SemanticError(
1478 sizeofExpr->expr.get(), "Ambiguous expression in sizeof operand: " );
[898ae07]1479 }
[64727bd]1480 // return the lowest-cost candidate
1481 CandidateRef & choice = winners.front();
1482 choice->expr = referenceToRvalueConversion( choice->expr, choice->cost );
1483 choice->cost = Cost::zero;
1484 addCandidate( *choice, new ast::SizeofExpr{ sizeofExpr->location, choice->expr } );
[4b7cce6]1485 }
[64727bd]1486 }
[4b7cce6]1487
[525f7ad]1488 void Finder::postvisit( const ast::CountExpr * countExpr ) {
[bfa7bf0]1489 const ast::UntypedExpr * untyped = nullptr;
[0c327ce]1490 if ( countExpr->type ) {
1491 auto enumInst = countExpr->type.as<ast::EnumInstType>();
1492 if ( enumInst ) {
1493 addCandidate( ast::ConstantExpr::from_ulong(countExpr->location, enumInst->base->members.size()), tenv );
1494 return;
1495 }
1496 auto untypedFirst = ast::UntypedExpr::createCall( countExpr->location, "lowerBound", {} );
1497 auto castFirst = new ast::CastExpr( countExpr->location, untypedFirst , countExpr->type );
1498 untyped = ast::UntypedExpr::createCall(
1499 countExpr->location, "Countof", { castFirst }
1500 );
1501 }
1502 if (!untyped) untyped = ast::UntypedExpr::createCall(
1503 countExpr->location, "Countof", { countExpr->expr }
1504 );
1505 CandidateFinder finder( context, tenv );
1506 finder.find( untyped );
1507 CandidateList winners = findMinCost( finder.candidates );
1508 if ( winners.size() == 0 ) {
1509 SemanticError( countExpr->expr, "Countof is not implemented for operand: " );
1510 }
1511 if ( winners.size() != 1 ) {
1512 SemanticError( countExpr->expr, "Ambiguous expression in countof operand: " );
[525f7ad]1513 }
[0c327ce]1514 CandidateRef & choice = winners.front();
1515 choice->expr = referenceToRvalueConversion( choice->expr, choice->cost );
1516 addCandidate( *choice, choice->expr );
[525f7ad]1517 }
1518
[64727bd]1519 void Finder::postvisit( const ast::AlignofExpr * alignofExpr ) {
1520 if ( alignofExpr->type ) {
1521 addCandidate(
1522 new ast::AlignofExpr{
1523 alignofExpr->location, resolveTypeof( alignofExpr->type, context ) },
1524 tenv );
1525 } else {
1526 // find all candidates for the argument to alignof
1527 CandidateFinder finder( context, tenv );
1528 finder.find( alignofExpr->expr );
1529 // find the lowest-cost candidate, otherwise ambiguous
1530 CandidateList winners = findMinCost( finder.candidates );
1531 if ( winners.size() != 1 ) {
1532 SemanticError(
1533 alignofExpr->expr.get(), "Ambiguous expression in alignof operand: " );
[898ae07]1534 }
[64727bd]1535 // return the lowest-cost candidate
1536 CandidateRef & choice = winners.front();
1537 choice->expr = referenceToRvalueConversion( choice->expr, choice->cost );
1538 choice->cost = Cost::zero;
1539 addCandidate(
1540 *choice, new ast::AlignofExpr{ alignofExpr->location, choice->expr } );
[4b7cce6]1541 }
[64727bd]1542 }
[4b7cce6]1543
[64727bd]1544 void Finder::postvisit( const ast::UntypedOffsetofExpr * offsetofExpr ) {
1545 const ast::BaseInstType * aggInst;
1546 if (( aggInst = offsetofExpr->type.as< ast::StructInstType >() )) ;
1547 else if (( aggInst = offsetofExpr->type.as< ast::UnionInstType >() )) ;
1548 else return;
[4b7cce6]1549
[64727bd]1550 for ( const ast::Decl * member : aggInst->lookup( offsetofExpr->member ) ) {
1551 auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( member );
1552 addCandidate(
1553 new ast::OffsetofExpr{ offsetofExpr->location, aggInst, dwt }, tenv );
[4b7cce6]1554 }
[64727bd]1555 }
[4b7cce6]1556
[64727bd]1557 void Finder::postvisit( const ast::OffsetofExpr * offsetofExpr ) {
1558 addCandidate( offsetofExpr, tenv );
1559 }
[4b7cce6]1560
[64727bd]1561 void Finder::postvisit( const ast::OffsetPackExpr * offsetPackExpr ) {
1562 addCandidate( offsetPackExpr, tenv );
1563 }
[71d6bd8]1564
[64727bd]1565 void Finder::postvisit( const ast::LogicalExpr * logicalExpr ) {
1566 CandidateFinder finder1( context, tenv );
[ab780e6]1567 ast::ptr<ast::Expr> arg1 = createCondExpr( logicalExpr->arg1 );
[61e362f]1568 finder1.find( arg1, ResolveMode::withAdjustment() );
[64727bd]1569 if ( finder1.candidates.empty() ) return;
[4b7cce6]1570
[64727bd]1571 CandidateFinder finder2( context, tenv );
[ab780e6]1572 ast::ptr<ast::Expr> arg2 = createCondExpr( logicalExpr->arg2 );
[61e362f]1573 finder2.find( arg2, ResolveMode::withAdjustment() );
[64727bd]1574 if ( finder2.candidates.empty() ) return;
[4b7cce6]1575
[64727bd]1576 reason.code = NoMatch;
[4b7cce6]1577
[64727bd]1578 for ( const CandidateRef & r1 : finder1.candidates ) {
[4b7cce6]1579 for ( const CandidateRef & r2 : finder2.candidates ) {
[64727bd]1580 ast::TypeEnvironment env{ r1->env };
1581 env.simpleCombine( r2->env );
1582 ast::OpenVarSet open{ r1->open };
1583 mergeOpenVars( open, r2->open );
1584 ast::AssertionSet need;
1585 mergeAssertionSet( need, r1->need );
1586 mergeAssertionSet( need, r2->need );
[4b7cce6]1587
[64727bd]1588 addCandidate(
1589 new ast::LogicalExpr{
1590 logicalExpr->location, r1->expr, r2->expr, logicalExpr->isAnd },
1591 std::move( env ), std::move( open ), std::move( need ), r1->cost + r2->cost );
[4b7cce6]1592 }
1593 }
[64727bd]1594 }
1595
1596 void Finder::postvisit( const ast::ConditionalExpr * conditionalExpr ) {
1597 // candidates for condition
[ab780e6]1598 ast::ptr<ast::Expr> arg1 = createCondExpr( conditionalExpr->arg1 );
[2810700]1599 CandidateFinder finder1( context, tenv );
[61e362f]1600 finder1.find( arg1, ResolveMode::withAdjustment() );
[64727bd]1601 if ( finder1.candidates.empty() ) return;
[4b7cce6]1602
[64727bd]1603 // candidates for true result
[2beaf9b]1604 // FIX ME: resolves and runs arg1 twice when arg2 is missing.
[2810700]1605 ast::Expr const * arg2 = conditionalExpr->arg2;
1606 arg2 = arg2 ? arg2 : conditionalExpr->arg1.get();
[64727bd]1607 CandidateFinder finder2( context, tenv );
1608 finder2.allowVoid = true;
[2810700]1609 finder2.find( arg2, ResolveMode::withAdjustment() );
[64727bd]1610 if ( finder2.candidates.empty() ) return;
[4b7cce6]1611
[64727bd]1612 // candidates for false result
1613 CandidateFinder finder3( context, tenv );
1614 finder3.allowVoid = true;
[4a89b52]1615 finder3.find( conditionalExpr->arg3, ResolveMode::withAdjustment() );
[64727bd]1616 if ( finder3.candidates.empty() ) return;
[4b7cce6]1617
[64727bd]1618 reason.code = NoMatch;
[71d6bd8]1619
[64727bd]1620 for ( const CandidateRef & r1 : finder1.candidates ) {
1621 for ( const CandidateRef & r2 : finder2.candidates ) {
1622 for ( const CandidateRef & r3 : finder3.candidates ) {
[4b7cce6]1623 ast::TypeEnvironment env{ r1->env };
1624 env.simpleCombine( r2->env );
[64727bd]1625 env.simpleCombine( r3->env );
[4b7cce6]1626 ast::OpenVarSet open{ r1->open };
1627 mergeOpenVars( open, r2->open );
[64727bd]1628 mergeOpenVars( open, r3->open );
[4b7cce6]1629 ast::AssertionSet need;
1630 mergeAssertionSet( need, r1->need );
1631 mergeAssertionSet( need, r2->need );
[64727bd]1632 mergeAssertionSet( need, r3->need );
[4b7cce6]1633 ast::AssertionSet have;
1634
[64727bd]1635 // unify true and false results, then infer parameters to produce new
1636 // candidates
[4b7cce6]1637 ast::ptr< ast::Type > common;
[2890212]1638 if (
1639 unify(
[64727bd]1640 r2->expr->result, r3->expr->result, env, need, have, open,
[2890212]1641 common )
[4b7cce6]1642 ) {
[64727bd]1643 // generate typed expression
1644 ast::ConditionalExpr * newExpr = new ast::ConditionalExpr{
1645 conditionalExpr->location, r1->expr, r2->expr, r3->expr };
1646 newExpr->result = common ? common : r2->expr->result;
1647 // convert both options to result type
1648 Cost cost = r1->cost + r2->cost + r3->cost;
1649 newExpr->arg2 = computeExpressionConversionCost(
1650 newExpr->arg2, newExpr->result, symtab, env, cost );
1651 newExpr->arg3 = computeExpressionConversionCost(
1652 newExpr->arg3, newExpr->result, symtab, env, cost );
1653 // output candidate
[898ae07]1654 CandidateRef newCand = std::make_shared<Candidate>(
[64727bd]1655 newExpr, std::move( env ), std::move( open ), std::move( need ), cost );
[898ae07]1656 inferParameters( newCand, candidates );
[4b7cce6]1657 }
1658 }
1659 }
1660 }
[64727bd]1661 }
[4b7cce6]1662
[64727bd]1663 void Finder::postvisit( const ast::CommaExpr * commaExpr ) {
1664 ast::TypeEnvironment env{ tenv };
1665 ast::ptr< ast::Expr > arg1 = resolveInVoidContext( commaExpr->arg1, context, env );
[4b7cce6]1666
[64727bd]1667 CandidateFinder finder2( context, env );
[4a89b52]1668 finder2.find( commaExpr->arg2, ResolveMode::withAdjustment() );
[4b7cce6]1669
[64727bd]1670 for ( const CandidateRef & r2 : finder2.candidates ) {
1671 addCandidate( *r2, new ast::CommaExpr{ commaExpr->location, arg1, r2->expr } );
[4b7cce6]1672 }
[64727bd]1673 }
[4b7cce6]1674
[64727bd]1675 void Finder::postvisit( const ast::ImplicitCopyCtorExpr * ctorExpr ) {
1676 addCandidate( ctorExpr, tenv );
1677 }
[4b7cce6]1678
[64727bd]1679 void Finder::postvisit( const ast::ConstructorExpr * ctorExpr ) {
1680 CandidateFinder finder( context, tenv );
1681 finder.allowVoid = true;
[4a89b52]1682 finder.find( ctorExpr->callExpr, ResolveMode::withoutPrune() );
[64727bd]1683 for ( CandidateRef & r : finder.candidates ) {
1684 addCandidate( *r, new ast::ConstructorExpr{ ctorExpr->location, r->expr } );
[4b7cce6]1685 }
[64727bd]1686 }
1687
1688 void Finder::postvisit( const ast::RangeExpr * rangeExpr ) {
1689 // resolve low and high, accept candidates where low and high types unify
1690 CandidateFinder finder1( context, tenv );
[4a89b52]1691 finder1.find( rangeExpr->low, ResolveMode::withAdjustment() );
[64727bd]1692 if ( finder1.candidates.empty() ) return;
1693
1694 CandidateFinder finder2( context, tenv );
[4a89b52]1695 finder2.find( rangeExpr->high, ResolveMode::withAdjustment() );
[64727bd]1696 if ( finder2.candidates.empty() ) return;
1697
1698 reason.code = NoMatch;
[4b7cce6]1699
[64727bd]1700 for ( const CandidateRef & r1 : finder1.candidates ) {
1701 for ( const CandidateRef & r2 : finder2.candidates ) {
1702 ast::TypeEnvironment env{ r1->env };
1703 env.simpleCombine( r2->env );
1704 ast::OpenVarSet open{ r1->open };
1705 mergeOpenVars( open, r2->open );
1706 ast::AssertionSet need;
1707 mergeAssertionSet( need, r1->need );
1708 mergeAssertionSet( need, r2->need );
1709 ast::AssertionSet have;
1710
1711 ast::ptr< ast::Type > common;
1712 if (
1713 unify(
1714 r1->expr->result, r2->expr->result, env, need, have, open,
1715 common )
1716 ) {
1717 // generate new expression
1718 ast::RangeExpr * newExpr =
1719 new ast::RangeExpr{ rangeExpr->location, r1->expr, r2->expr };
1720 newExpr->result = common ? common : r1->expr->result;
1721 // add candidate
1722 CandidateRef newCand = std::make_shared<Candidate>(
1723 newExpr, std::move( env ), std::move( open ), std::move( need ),
1724 r1->cost + r2->cost );
1725 inferParameters( newCand, candidates );
1726 }
1727 }
[4b7cce6]1728 }
[64727bd]1729 }
[4b7cce6]1730
[64727bd]1731 void Finder::postvisit( const ast::UntypedTupleExpr * tupleExpr ) {
1732 std::vector< CandidateFinder > subCandidates =
1733 selfFinder.findSubExprs( tupleExpr->exprs );
1734 std::vector< CandidateList > possibilities;
1735 combos( subCandidates.begin(), subCandidates.end(), back_inserter( possibilities ) );
1736
1737 for ( const CandidateList & subs : possibilities ) {
1738 std::vector< ast::ptr< ast::Expr > > exprs;
1739 exprs.reserve( subs.size() );
1740 for ( const CandidateRef & sub : subs ) { exprs.emplace_back( sub->expr ); }
1741
1742 ast::TypeEnvironment env;
1743 ast::OpenVarSet open;
1744 ast::AssertionSet need;
1745 for ( const CandidateRef & sub : subs ) {
1746 env.simpleCombine( sub->env );
1747 mergeOpenVars( open, sub->open );
1748 mergeAssertionSet( need, sub->need );
[4b7cce6]1749 }
[64727bd]1750
1751 addCandidate(
1752 new ast::TupleExpr{ tupleExpr->location, std::move( exprs ) },
1753 std::move( env ), std::move( open ), std::move( need ), sumCost( subs ) );
[4b7cce6]1754 }
[64727bd]1755 }
1756
1757 void Finder::postvisit( const ast::TupleExpr * tupleExpr ) {
1758 addCandidate( tupleExpr, tenv );
1759 }
1760
1761 void Finder::postvisit( const ast::TupleIndexExpr * tupleExpr ) {
1762 addCandidate( tupleExpr, tenv );
1763 }
1764
1765 void Finder::postvisit( const ast::TupleAssignExpr * tupleExpr ) {
1766 addCandidate( tupleExpr, tenv );
1767 }
[4b7cce6]1768
[64727bd]1769 void Finder::postvisit( const ast::UniqueExpr * unqExpr ) {
1770 CandidateFinder finder( context, tenv );
[4a89b52]1771 finder.find( unqExpr->expr, ResolveMode::withAdjustment() );
[64727bd]1772 for ( CandidateRef & r : finder.candidates ) {
1773 // ensure that the the id is passed on so that the expressions are "linked"
1774 addCandidate( *r, new ast::UniqueExpr{ unqExpr->location, r->expr, unqExpr->id } );
[4b7cce6]1775 }
[64727bd]1776 }
[4b7cce6]1777
[64727bd]1778 void Finder::postvisit( const ast::StmtExpr * stmtExpr ) {
1779 addCandidate( resolveStmtExpr( stmtExpr, context ), tenv );
1780 }
[17a0ede2]1781
[64727bd]1782 void Finder::postvisit( const ast::UntypedInitExpr * initExpr ) {
1783 // handle each option like a cast
1784 CandidateList matches;
1785 PRINT(
1786 std::cerr << "untyped init expr: " << initExpr << std::endl;
1787 )
1788 // O(n^2) checks of d-types with e-types
1789 for ( const ast::InitAlternative & initAlt : initExpr->initAlts ) {
1790 // calculate target type
1791 const ast::Type * toType = resolveTypeof( initAlt.type, context );
1792 toType = adjustExprType( toType, tenv, symtab );
1793 // The call to find must occur inside this loop, otherwise polymorphic return
1794 // types are not bound to the initialization type, since return type variables are
1795 // only open for the duration of resolving the UntypedExpr.
1796 CandidateFinder finder( context, tenv, toType );
[4a89b52]1797 finder.find( initExpr->expr, ResolveMode::withAdjustment() );
[64727bd]1798
1799 Cost minExprCost = Cost::infinity;
1800 Cost minCastCost = Cost::infinity;
1801 for ( CandidateRef & cand : finder.candidates ) {
1802 if (reason.code == NotFound) reason.code = NoMatch;
1803
1804 ast::TypeEnvironment env{ cand->env };
1805 ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have;
1806 ast::OpenVarSet open{ cand->open };
1807
1808 PRINT(
1809 std::cerr << " @ " << toType << " " << initAlt.designation << std::endl;
1810 )
1811
1812 // It is possible that a cast can throw away some values in a multiply-valued
1813 // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of
1814 // the subexpression results that are cast directly. The candidate is invalid
1815 // if it has fewer results than there are types to cast to.
1816 int discardedValues = cand->expr->result->size() - toType->size();
1817 if ( discardedValues < 0 ) continue;
[17a0ede2]1818
[64727bd]1819 // unification run for side-effects
[af746cc]1820 ast::ptr<ast::Type> common;
1821 bool canUnify = unify( toType, cand->expr->result, env, need, have, open, common );
[64727bd]1822 (void) canUnify;
1823 Cost thisCost = computeConversionCost( cand->expr->result, toType, cand->expr->get_lvalue(),
1824 symtab, env );
1825 PRINT(
1826 Cost legacyCost = castCost( cand->expr->result, toType, cand->expr->get_lvalue(),
[bb87dd0]1827 symtab, env );
[64727bd]1828 std::cerr << "Considering initialization:";
1829 std::cerr << std::endl << " FROM: " << cand->expr->result << std::endl;
1830 std::cerr << std::endl << " TO: " << toType << std::endl;
1831 std::cerr << std::endl << " Unification " << (canUnify ? "succeeded" : "failed");
1832 std::cerr << std::endl << " Legacy cost " << legacyCost;
1833 std::cerr << std::endl << " New cost " << thisCost;
1834 std::cerr << std::endl;
1835 )
1836 if ( thisCost != Cost::infinity ) {
1837 // count one safe conversion for each value that is thrown away
1838 thisCost.incSafe( discardedValues );
1839 if ( cand->cost < minExprCost || ( cand->cost == minExprCost && thisCost < minCastCost ) ) {
1840 minExprCost = cand->cost;
1841 minCastCost = thisCost;
1842 matches.clear();
1843 }
[acb33f15]1844 CandidateRef newCand = std::make_shared<Candidate>(
1845 new ast::InitExpr{
1846 initExpr->location,
1847 restructureCast( cand->expr, toType ),
1848 initAlt.designation },
1849 std::move(env), std::move( open ), std::move( need ), cand->cost + thisCost );
1850 // currently assertions are always resolved immediately so this should have no effect.
1851 // if this somehow changes in the future (e.g. delayed by indeterminate return type)
1852 // we may need to revisit the logic.
1853 inferParameters( newCand, matches );
[7aa209e7]1854 }
[17a0ede2]1855 }
[4b7cce6]1856 }
1857
[64727bd]1858 // select first on argument cost, then conversion cost
1859 // CandidateList minArgCost = findMinCost( matches );
1860 // promoteCvtCost( minArgCost );
1861 // candidates = findMinCost( minArgCost );
1862 candidates = std::move(matches);
1863 }
[396037d]1864
[a55ebcc]1865 void Finder::postvisit( const ast::QualifiedNameExpr * expr ) {
1866 std::vector< ast::SymbolTable::IdData > declList = symtab.lookupId( expr->name );
1867 if ( declList.empty() ) return;
1868
1869 for ( ast::SymbolTable::IdData & data: declList ) {
1870 const ast::Type * t = data.id->get_type()->stripReferences();
1871 if ( const ast::EnumInstType * enumInstType =
1872 dynamic_cast<const ast::EnumInstType *>( t ) ) {
[85855b0]1873 if ( (enumInstType->base->name == expr->type_name)
1874 || (expr->type_decl && enumInstType->base->name == expr->type_decl->name) ) {
[a55ebcc]1875 Cost cost = Cost::zero;
1876 ast::Expr * newExpr = data.combine( expr->location, cost );
1877 CandidateRef newCand =
1878 std::make_shared<Candidate>(
[14755e5]1879 newExpr, copy( tenv ), ast::OpenVarSet{},
[eb7586e]1880 ast::AssertionSet{}, Cost::zero, cost
[a55ebcc]1881 );
1882 if (newCand->expr->env) {
1883 newCand->env.add(*newCand->expr->env);
1884 auto mutExpr = newCand->expr.get_and_mutate();
1885 mutExpr->env = nullptr;
1886 newCand->expr = mutExpr;
1887 }
1888
1889 newCand->expr = ast::mutate_field(
1890 newCand->expr.get(), &ast::Expr::result,
1891 renameTyVars( newCand->expr->result ) );
1892 addAnonConversions( newCand );
1893 candidates.emplace_back( std::move( newCand ) );
1894 }
1895 }
1896 }
1897 }
[0d070ca]1898 // size_t Finder::traceId = Stats::Heap::new_stacktrace_id("Finder");
[2890212]1899 /// Prunes a list of candidates down to those that have the minimum conversion cost for a given
[396037d]1900 /// return type. Skips ambiguous candidates.
[d57e349]1901
[1389810]1902} // anonymous namespace
[d57e349]1903
[1389810]1904bool CandidateFinder::pruneCandidates( CandidateList & candidates, CandidateList & out, std::vector<std::string> & errors ) {
1905 struct PruneStruct {
1906 CandidateRef candidate;
1907 bool ambiguous;
1908
1909 PruneStruct() = default;
1910 PruneStruct( const CandidateRef & c ) : candidate( c ), ambiguous( false ) {}
1911 };
1912
1913 // find lowest-cost candidate for each type
1914 std::unordered_map< std::string, PruneStruct > selected;
1915 // attempt to skip satisfyAssertions on more expensive alternatives if better options have been found
1916 std::sort(candidates.begin(), candidates.end(), [](const CandidateRef & x, const CandidateRef & y){return x->cost < y->cost;});
1917 for ( CandidateRef & candidate : candidates ) {
1918 std::string mangleName;
1919 {
1920 ast::ptr< ast::Type > newType = candidate->expr->result;
1921 assertf(candidate->expr->result, "Result of expression %p for candidate is null", candidate->expr.get());
1922 candidate->env.apply( newType );
1923 mangleName = Mangle::mangle( newType );
1924 }
1925
1926 auto found = selected.find( mangleName );
1927 if (found != selected.end() && found->second.candidate->cost < candidate->cost) {
1928 PRINT(
1929 std::cerr << "cost " << candidate->cost << " loses to "
1930 << found->second.candidate->cost << std::endl;
1931 )
1932 continue;
1933 }
1934
1935 // xxx - when do satisfyAssertions produce more than 1 result?
1936 // this should only happen when initial result type contains
1937 // unbound type parameters, then it should never be pruned by
1938 // the previous step, since renameTyVars guarantees the mangled name
1939 // is unique.
1940 CandidateList satisfied;
[e3282fe]1941 bool needRecomputeKey = false;
1942 if (candidate->need.empty()) {
1943 satisfied.emplace_back(candidate);
1944 }
1945 else {
[39d8950]1946 satisfyAssertions(candidate, context.symtab, satisfied, errors);
[e3282fe]1947 needRecomputeKey = true;
1948 }
[1389810]1949
1950 for (auto & newCand : satisfied) {
1951 // recomputes type key, if satisfyAssertions changed it
[e3282fe]1952 if (needRecomputeKey)
[d57e349]1953 {
[1389810]1954 ast::ptr< ast::Type > newType = newCand->expr->result;
1955 assertf(newCand->expr->result, "Result of expression %p for candidate is null", newCand->expr.get());
1956 newCand->env.apply( newType );
[d57e349]1957 mangleName = Mangle::mangle( newType );
1958 }
1959 auto found = selected.find( mangleName );
1960 if ( found != selected.end() ) {
[46da46b]1961 // tiebreaking by picking the lower cost on CURRENT expression
1962 // NOTE: this behavior is different from C semantics.
1963 // Specific remediations are performed for C operators at postvisit(UntypedExpr).
1964 // Further investigations may take place.
1965 if ( newCand->cost < found->second.candidate->cost
1966 || (newCand->cost == found->second.candidate->cost && newCand->cvtCost < found->second.candidate->cvtCost) ) {
[d57e349]1967 PRINT(
[1389810]1968 std::cerr << "cost " << newCand->cost << " beats "
[d57e349]1969 << found->second.candidate->cost << std::endl;
1970 )
1971
[1389810]1972 found->second = PruneStruct{ newCand };
[64727bd]1973 } else if ( newCand->cost == found->second.candidate->cost && newCand->cvtCost == found->second.candidate->cvtCost ) {
[2890212]1974 // if one of the candidates contains a deleted identifier, can pick the other,
1975 // since deleted expressions should not be ambiguous if there is another option
[d57e349]1976 // that is at least as good
[1389810]1977 if ( findDeletedExpr( newCand->expr ) ) {
[d57e349]1978 // do nothing
1979 PRINT( std::cerr << "candidate is deleted" << std::endl; )
1980 } else if ( findDeletedExpr( found->second.candidate->expr ) ) {
1981 PRINT( std::cerr << "current is deleted" << std::endl; )
[1389810]1982 found->second = PruneStruct{ newCand };
[d57e349]1983 } else {
1984 PRINT( std::cerr << "marking ambiguous" << std::endl; )
1985 found->second.ambiguous = true;
1986 }
[943bfad]1987 } else {
[1389810]1988 // xxx - can satisfyAssertions increase the cost?
[d57e349]1989 PRINT(
[1389810]1990 std::cerr << "cost " << newCand->cost << " loses to "
[d57e349]1991 << found->second.candidate->cost << std::endl;
[943bfad]1992 )
[d57e349]1993 }
1994 } else {
[1389810]1995 selected.emplace_hint( found, mangleName, newCand );
[d57e349]1996 }
1997 }
[1389810]1998 }
[d57e349]1999
[1389810]2000 // report unambiguous min-cost candidates
2001 // CandidateList out;
2002 for ( auto & target : selected ) {
2003 if ( target.second.ambiguous ) continue;
[d57e349]2004
[1389810]2005 CandidateRef cand = target.second.candidate;
[2890212]2006
[1389810]2007 ast::ptr< ast::Type > newResult = cand->expr->result;
2008 cand->env.applyFree( newResult );
2009 cand->expr = ast::mutate_field(
[09f34a84]2010 cand->expr.get(), &ast::Expr::result, std::move( newResult ) );
[2890212]2011
[1389810]2012 out.emplace_back( cand );
[d57e349]2013 }
[1389810]2014 // if everything is lost in satisfyAssertions, report the error
2015 return !selected.empty();
2016}
[396037d]2017
[4a89b52]2018void CandidateFinder::find( const ast::Expr * expr, ResolveMode mode ) {
[396037d]2019 // Find alternatives for expression
2020 ast::Pass<Finder> finder{ *this };
2021 expr->accept( finder );
2022
2023 if ( mode.failFast && candidates.empty() ) {
[7ff3e522]2024 switch(finder.core.reason.code) {
[71d6bd8]2025 case Finder::NotFound:
2026 { SemanticError( expr, "No alternatives for expression " ); break; }
2027 case Finder::NoMatch:
2028 { SemanticError( expr, "Invalid application of existing declaration(s) in expression " ); break; }
2029 case Finder::ArgsToFew:
2030 case Finder::ArgsToMany:
2031 case Finder::RetsToFew:
2032 case Finder::RetsToMany:
2033 case Finder::NoReason:
2034 default:
2035 { SemanticError( expr->location, "No reasonable alternatives for expression : reasons unkown" ); }
2036 }
[396037d]2037 }
2038
[1389810]2039 /*
[396037d]2040 if ( mode.satisfyAssns || mode.prune ) {
2041 // trim candidates to just those where the assertions are satisfiable
2042 // - necessary pre-requisite to pruning
2043 CandidateList satisfied;
2044 std::vector< std::string > errors;
[b69233ac]2045 for ( CandidateRef & candidate : candidates ) {
[9ea38de]2046 satisfyAssertions( candidate, localSyms, satisfied, errors );
[396037d]2047 }
2048
2049 // fail early if none such
2050 if ( mode.failFast && satisfied.empty() ) {
2051 std::ostringstream stream;
2052 stream << "No alternatives with satisfiable assertions for " << expr << "\n";
2053 for ( const auto& err : errors ) {
2054 stream << err;
2055 }
2056 SemanticError( expr->location, stream.str() );
2057 }
2058
2059 // reset candidates
[9d5089e]2060 candidates = move( satisfied );
[396037d]2061 }
[1389810]2062 */
[396037d]2063
[46da46b]2064 // optimization: don't prune for NameExpr since it never has cost
[64727bd]2065 if ( mode.prune && !dynamic_cast<const ast::NameExpr *>(expr) ) {
[396037d]2066 // trim candidates to single best one
2067 PRINT(
2068 std::cerr << "alternatives before prune:" << std::endl;
2069 print( std::cerr, candidates );
2070 )
2071
[1389810]2072 CandidateList pruned;
2073 std::vector<std::string> errors;
2074 bool found = pruneCandidates( candidates, pruned, errors );
[2890212]2075
[396037d]2076 if ( mode.failFast && pruned.empty() ) {
2077 std::ostringstream stream;
[943bfad]2078 if (found) {
[1389810]2079 CandidateList winners = findMinCost( candidates );
2080 stream << "Cannot choose between " << winners.size() << " alternatives for "
2081 "expression\n";
2082 ast::print( stream, expr );
2083 stream << " Alternatives are:\n";
2084 print( stream, winners, 1 );
2085 SemanticError( expr->location, stream.str() );
2086 }
2087 else {
2088 stream << "No alternatives with satisfiable assertions for " << expr << "\n";
2089 for ( const auto& err : errors ) {
2090 stream << err;
2091 }
2092 SemanticError( expr->location, stream.str() );
2093 }
[396037d]2094 }
[d57e349]2095
2096 auto oldsize = candidates.size();
[09f34a84]2097 candidates = std::move( pruned );
[d57e349]2098
2099 PRINT(
2100 std::cerr << "there are " << oldsize << " alternatives before elimination" << std::endl;
2101 )
2102 PRINT(
[2890212]2103 std::cerr << "there are " << candidates.size() << " alternatives after elimination"
[d57e349]2104 << std::endl;
2105 )
[396037d]2106 }
2107
[2890212]2108 // adjust types after pruning so that types substituted by pruneAlternatives are correctly
[d57e349]2109 // adjusted
2110 if ( mode.adjust ) {
2111 for ( CandidateRef & r : candidates ) {
[2890212]2112 r->expr = ast::mutate_field(
2113 r->expr.get(), &ast::Expr::result,
[39d8950]2114 adjustExprType( r->expr->result, r->env, context.symtab ) );
[d57e349]2115 }
2116 }
2117
2118 // Central location to handle gcc extension keyword, etc. for all expressions
2119 for ( CandidateRef & r : candidates ) {
2120 if ( r->expr->extension != expr->extension ) {
2121 r->expr.get_and_mutate()->extension = expr->extension;
2122 }
2123 }
[99d4584]2124}
2125
[2890212]2126std::vector< CandidateFinder > CandidateFinder::findSubExprs(
2127 const std::vector< ast::ptr< ast::Expr > > & xs
[2773ab8]2128) {
2129 std::vector< CandidateFinder > out;
2130
[396037d]2131 for ( const auto & x : xs ) {
[39d8950]2132 out.emplace_back( context, env );
[4a89b52]2133 out.back().find( x, ResolveMode::withAdjustment() );
[2890212]2134
[396037d]2135 PRINT(
2136 std::cerr << "findSubExprs" << std::endl;
2137 print( std::cerr, out.back().candidates );
2138 )
2139 }
[2773ab8]2140
2141 return out;
2142}
2143
[64727bd]2144const ast::Expr * referenceToRvalueConversion( const ast::Expr * expr, Cost & cost ) {
2145 if ( expr->result.as< ast::ReferenceType >() ) {
2146 // cast away reference from expr
2147 cost.incReference();
2148 return new ast::CastExpr{ expr, expr->result->stripReferences() };
2149 }
2150
2151 return expr;
2152}
2153
[85855b0]2154const ast::Expr * CandidateFinder::makeEnumOffsetCast( const ast::EnumInstType * src,
[d68a3f7]2155 const ast::EnumInstType * dst, const ast::Expr * expr, Cost minCost ) {
[85855b0]2156 auto srcDecl = src->base;
2157 auto dstDecl = dst->base;
2158
2159 if (srcDecl->name == dstDecl->name) return expr;
2160
2161 for (auto& dstChild: dstDecl->inlinedDecl) {
2162 Cost c = castCost(src, dstChild, false, context.symtab, env);
2163 ast::CastExpr * castToDst;
2164 if (c<minCost) {
2165 unsigned offset = dstDecl->calChildOffset(dstChild.get());
2166 if (offset > 0) {
2167 auto untyped = ast::UntypedExpr::createCall(
2168 expr->location,
2169 "?+?",
[d3aa55e9]2170 { new ast::CastExpr( expr->location,
2171 expr,
2172 new ast::BasicType(ast::BasicKind::SignedInt),
2173 ast::GeneratedFlag::ExplicitCast ),
2174 ast::ConstantExpr::from_int(expr->location, offset)} );
[85855b0]2175 CandidateFinder finder(context, env);
2176 finder.find( untyped );
2177 CandidateList winners = findMinCost( finder.candidates );
2178 CandidateRef & choice = winners.front();
2179 choice->expr = new ast::CastExpr(expr->location, choice->expr, dstChild, ast::GeneratedFlag::ExplicitCast);
[d68a3f7]2180 auto destExpr = makeEnumOffsetCast( src, dstChild, choice->expr, minCost );
2181 if ( !destExpr ) continue;
2182 castToDst = new ast::CastExpr( destExpr, dst );
[85855b0]2183 } else {
2184 castToDst = new ast::CastExpr( expr, dst );
2185 }
2186 return castToDst;
2187 }
2188 }
2189 return nullptr;
2190}
2191
[64727bd]2192Cost computeConversionCost(
2193 const ast::Type * argType, const ast::Type * paramType, bool argIsLvalue,
2194 const ast::SymbolTable & symtab, const ast::TypeEnvironment & env
2195) {
2196 PRINT(
2197 std::cerr << std::endl << "converting ";
2198 ast::print( std::cerr, argType, 2 );
2199 std::cerr << std::endl << " to ";
2200 ast::print( std::cerr, paramType, 2 );
2201 std::cerr << std::endl << "environment is: ";
2202 ast::print( std::cerr, env, 2 );
2203 std::cerr << std::endl;
2204 )
2205 Cost convCost = conversionCost( argType, paramType, argIsLvalue, symtab, env );
2206 PRINT(
2207 std::cerr << std::endl << "cost is " << convCost << std::endl;
2208 )
2209 if ( convCost == Cost::infinity ) return convCost;
2210 convCost.incPoly( polyCost( paramType, symtab, env ) + polyCost( argType, symtab, env ) );
2211 PRINT(
2212 std::cerr << "cost with polycost is " << convCost << std::endl;
2213 )
2214 return convCost;
2215}
2216
[ab780e6]2217const ast::Expr * createCondExpr( const ast::Expr * expr ) {
2218 assert( expr );
2219 return new ast::CastExpr( expr->location,
2220 ast::UntypedExpr::createCall( expr->location,
2221 "?!=?",
2222 {
2223 expr,
2224 new ast::ConstantExpr( expr->location,
2225 new ast::ZeroType(), "0", std::make_optional( 0ull )
2226 ),
2227 }
2228 ),
[7a780ad]2229 new ast::BasicType( ast::BasicKind::SignedInt )
[ab780e6]2230 );
[af746cc]2231}
2232
[99d4584]2233} // namespace ResolvExpr
2234
2235// Local Variables: //
2236// tab-width: 4 //
2237// mode: c++ //
2238// compile-command: "make install" //
2239// End: //
Note: See TracBrowser for help on using the repository browser.