source: src/ResolvExpr/CandidateFinder.cpp@ f2898df

Last change on this file since f2898df was 59c8dff, checked in by JiadaL <j82liang@…>, 20 months ago

Draft Implementation for enum position pesudo function (posE). EnumPosExpr is mostly irrelevant for now. It is used in development/code probing and will be removed later

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