source: src/ResolvExpr/CandidateFinder.cpp@ 5dbb9f3

Last change on this file since 5dbb9f3 was 24d6572, checked in by Fangren Yu <f37yu@…>, 2 years ago

Merge branch 'master' into ast-experimental

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