source: src/ResolvExpr/CandidateFinder.cpp@ e5c3811

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since e5c3811 was e5c3811, checked in by Fangren Yu <f37yu@…>, 5 years ago

create dedicated symbol tables for big 3 operators
note: arbitrary this param type is not supported; it is currently allowed although never used

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