source: src/ResolvExpr/CandidateFinder.cpp@ 234b1cb

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 234b1cb was b69233ac, checked in by Aaron Moss <a3moss@…>, 6 years ago

Port assertion satisfaction to new AST

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