source: src/ResolvExpr/CandidateFinder.cpp@ bcd74f3

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since bcd74f3 was 71d6bd8, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

First attempt at better errors on 'No reasonable alternatives' split not found and found but didn't match

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