source: src/ResolvExpr/CandidateFinder.cpp@ a1a1f37d

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