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 |
|
---|
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 "SymTab/Mangler.h"
|
---|
42 | #include "SymTab/Validate.h" // for validateType
|
---|
43 | #include "Tuples/Tuples.h" // for handleTupleAssignment
|
---|
44 |
|
---|
45 | #define PRINT( text ) if ( resolvep ) { text }
|
---|
46 |
|
---|
47 | namespace ResolvExpr {
|
---|
48 |
|
---|
49 | using std::move;
|
---|
50 |
|
---|
51 | /// partner to move that copies any copyable type
|
---|
52 | template<typename T>
|
---|
53 | T copy( const T & x ) { return x; }
|
---|
54 |
|
---|
55 | const 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, expr->result->stripReferences() };
|
---|
60 | }
|
---|
61 |
|
---|
62 | return expr;
|
---|
63 | }
|
---|
64 |
|
---|
65 | /// Unique identifier for matching expression resolutions to their requesting expression
|
---|
66 | UniqueId globalResnSlot = 0;
|
---|
67 |
|
---|
68 | Cost 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 |
|
---|
93 | namespace {
|
---|
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 |
|
---|
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, 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 |
|
---|
149 | /// Computes conversion cost for a given candidate
|
---|
150 | Cost computeApplicationConversionCost(
|
---|
151 | CandidateRef cand, const ast::SymbolTable & symtab
|
---|
152 | ) {
|
---|
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();
|
---|
556 | }
|
---|
557 |
|
---|
558 | /// Generate a cast expression from `arg` to `toType`
|
---|
559 | const ast::Expr * restructureCast(
|
---|
560 | ast::ptr< ast::Expr > & arg, const ast::Type * toType, ast::GeneratedFlag isGenerated = ast::GeneratedCast
|
---|
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;
|
---|
598 | }
|
---|
599 |
|
---|
600 | /// Actually visits expressions to find their candidate interpretations
|
---|
601 | struct Finder final : public ast::WithShortCircuiting {
|
---|
602 | CandidateFinder & selfFinder;
|
---|
603 | const ast::SymbolTable & symtab;
|
---|
604 | CandidateList & candidates;
|
---|
605 | const ast::TypeEnvironment & tenv;
|
---|
606 | ast::ptr< ast::Type > & targetType;
|
---|
607 |
|
---|
608 | Finder( CandidateFinder & f )
|
---|
609 | : selfFinder( f ), symtab( f.symtab ), candidates( f.candidates ), tenv( f.env ),
|
---|
610 | targetType( f.targetType ) {}
|
---|
611 |
|
---|
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 |
|
---|
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 |
|
---|
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 | ) {
|
---|
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 | }
|
---|
783 | }
|
---|
784 |
|
---|
785 | /// Adds implicit struct-conversions to the alternative list
|
---|
786 | void addAnonConversions( const CandidateRef & cand ) {
|
---|
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 = new ast::CastExpr{ aggrExpr, aggrType->stripReferences() };
|
---|
796 | }
|
---|
797 |
|
---|
798 | if ( auto structInst = aggrExpr->result.as< ast::StructInstType >() ) {
|
---|
799 | addAggMembers( structInst, aggrExpr, *cand, Cost::safe, "" );
|
---|
800 | } else if ( auto unionInst = aggrExpr->result.as< ast::UnionInstType >() ) {
|
---|
801 | addAggMembers( unionInst, aggrExpr, *cand, Cost::safe, "" );
|
---|
802 | }
|
---|
803 | }
|
---|
804 |
|
---|
805 | /// Adds aggregate member interpretations
|
---|
806 | void addAggMembers(
|
---|
807 | const ast::ReferenceToType * aggrInst, const ast::Expr * expr,
|
---|
808 | const Candidate & cand, const Cost & addedCost, const std::string & name
|
---|
809 | ) {
|
---|
810 | for ( const ast::Decl * decl : aggrInst->lookup( name ) ) {
|
---|
811 | auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( decl );
|
---|
812 | CandidateRef newCand = std::make_shared<Candidate>(
|
---|
813 | cand, new ast::MemberExpr{ expr->location, dwt, expr }, addedCost );
|
---|
814 | // add anonymous member interpretations whenever an aggregate value type is seen
|
---|
815 | // as a member expression
|
---|
816 | addAnonConversions( newCand );
|
---|
817 | candidates.emplace_back( move( newCand ) );
|
---|
818 | }
|
---|
819 | }
|
---|
820 |
|
---|
821 | /// Adds tuple member interpretations
|
---|
822 | void addTupleMembers(
|
---|
823 | const ast::TupleType * tupleType, const ast::Expr * expr, const Candidate & cand,
|
---|
824 | const Cost & addedCost, const ast::Expr * member
|
---|
825 | ) {
|
---|
826 | if ( auto constantExpr = dynamic_cast< const ast::ConstantExpr * >( member ) ) {
|
---|
827 | // get the value of the constant expression as an int, must be between 0 and the
|
---|
828 | // length of the tuple to have meaning
|
---|
829 | long long val = constantExpr->intValue();
|
---|
830 | if ( val >= 0 && (unsigned long long)val < tupleType->size() ) {
|
---|
831 | addCandidate(
|
---|
832 | cand, new ast::TupleIndexExpr{ expr->location, expr, (unsigned)val },
|
---|
833 | addedCost );
|
---|
834 | }
|
---|
835 | }
|
---|
836 | }
|
---|
837 |
|
---|
838 | void postvisit( const ast::UntypedExpr * untypedExpr ) {
|
---|
839 | CandidateFinder funcFinder{ symtab, tenv };
|
---|
840 | funcFinder.find( untypedExpr->func, ResolvMode::withAdjustment() );
|
---|
841 | // short-circuit if no candidates
|
---|
842 | if ( funcFinder.candidates.empty() ) return;
|
---|
843 |
|
---|
844 | std::vector< CandidateFinder > argCandidates =
|
---|
845 | selfFinder.findSubExprs( untypedExpr->args );
|
---|
846 |
|
---|
847 | // take care of possible tuple assignments
|
---|
848 | // if not tuple assignment, handled as normal function call
|
---|
849 | Tuples::handleTupleAssignment( selfFinder, untypedExpr, argCandidates );
|
---|
850 |
|
---|
851 | // find function operators
|
---|
852 | ast::ptr< ast::Expr > opExpr = new ast::NameExpr{ untypedExpr->location, "?()" };
|
---|
853 | CandidateFinder opFinder{ symtab, tenv };
|
---|
854 | // okay if there aren't any function operations
|
---|
855 | opFinder.find( opExpr, ResolvMode::withoutFailFast() );
|
---|
856 | PRINT(
|
---|
857 | std::cerr << "known function ops:" << std::endl;
|
---|
858 | print( std::cerr, opFinder.candidates, 1 );
|
---|
859 | )
|
---|
860 |
|
---|
861 | // pre-explode arguments
|
---|
862 | ExplodedArgs_new argExpansions;
|
---|
863 | for ( const CandidateFinder & args : argCandidates ) {
|
---|
864 | argExpansions.emplace_back();
|
---|
865 | auto & argE = argExpansions.back();
|
---|
866 | for ( const CandidateRef & arg : args ) { argE.emplace_back( *arg, symtab ); }
|
---|
867 | }
|
---|
868 |
|
---|
869 | // Find function matches
|
---|
870 | CandidateList found;
|
---|
871 | SemanticErrorException errors;
|
---|
872 | for ( CandidateRef & func : funcFinder ) {
|
---|
873 | try {
|
---|
874 | PRINT(
|
---|
875 | std::cerr << "working on alternative:" << std::endl;
|
---|
876 | print( std::cerr, *func, 2 );
|
---|
877 | )
|
---|
878 |
|
---|
879 | // check if the type is a pointer to function
|
---|
880 | const ast::Type * funcResult = func->expr->result->stripReferences();
|
---|
881 | if ( auto pointer = dynamic_cast< const ast::PointerType * >( funcResult ) ) {
|
---|
882 | if ( auto function = pointer->base.as< ast::FunctionType >() ) {
|
---|
883 | CandidateRef newFunc{ new Candidate{ *func } };
|
---|
884 | newFunc->expr =
|
---|
885 | referenceToRvalueConversion( newFunc->expr, newFunc->cost );
|
---|
886 | makeFunctionCandidates( newFunc, function, argExpansions, found );
|
---|
887 | }
|
---|
888 | } else if (
|
---|
889 | auto inst = dynamic_cast< const ast::TypeInstType * >( funcResult )
|
---|
890 | ) {
|
---|
891 | if ( const ast::EqvClass * clz = func->env.lookup( inst->name ) ) {
|
---|
892 | if ( auto function = clz->bound.as< ast::FunctionType >() ) {
|
---|
893 | CandidateRef newFunc{ new Candidate{ *func } };
|
---|
894 | newFunc->expr =
|
---|
895 | referenceToRvalueConversion( newFunc->expr, newFunc->cost );
|
---|
896 | makeFunctionCandidates( newFunc, function, argExpansions, found );
|
---|
897 | }
|
---|
898 | }
|
---|
899 | }
|
---|
900 | } catch ( SemanticErrorException & e ) { errors.append( e ); }
|
---|
901 | }
|
---|
902 |
|
---|
903 | // Find matches on function operators `?()`
|
---|
904 | if ( ! opFinder.candidates.empty() ) {
|
---|
905 | // add exploded function alternatives to front of argument list
|
---|
906 | std::vector< ExplodedArg > funcE;
|
---|
907 | funcE.reserve( funcFinder.candidates.size() );
|
---|
908 | for ( const CandidateRef & func : funcFinder ) {
|
---|
909 | funcE.emplace_back( *func, symtab );
|
---|
910 | }
|
---|
911 | argExpansions.emplace_front( move( funcE ) );
|
---|
912 |
|
---|
913 | for ( const CandidateRef & op : opFinder ) {
|
---|
914 | try {
|
---|
915 | // check if type is pointer-to-function
|
---|
916 | const ast::Type * opResult = op->expr->result->stripReferences();
|
---|
917 | if ( auto pointer = dynamic_cast< const ast::PointerType * >( opResult ) ) {
|
---|
918 | if ( auto function = pointer->base.as< ast::FunctionType >() ) {
|
---|
919 | CandidateRef newOp{ new Candidate{ *op} };
|
---|
920 | newOp->expr =
|
---|
921 | referenceToRvalueConversion( newOp->expr, newOp->cost );
|
---|
922 | makeFunctionCandidates( newOp, function, argExpansions, found );
|
---|
923 | }
|
---|
924 | }
|
---|
925 | } catch ( SemanticErrorException & e ) { errors.append( e ); }
|
---|
926 | }
|
---|
927 | }
|
---|
928 |
|
---|
929 | // Implement SFINAE; resolution errors are only errors if there aren't any non-error
|
---|
930 | // candidates
|
---|
931 | if ( found.empty() && ! errors.isEmpty() ) { throw errors; }
|
---|
932 |
|
---|
933 | // Compute conversion costs
|
---|
934 | for ( CandidateRef & withFunc : found ) {
|
---|
935 | Cost cvtCost = computeApplicationConversionCost( withFunc, symtab );
|
---|
936 |
|
---|
937 | PRINT(
|
---|
938 | auto appExpr = withFunc->expr.strict_as< ast::ApplicationExpr >();
|
---|
939 | auto pointer = appExpr->func->result.strict_as< ast::PointerType >();
|
---|
940 | auto function = pointer->base.strict_as< ast::FunctionType >();
|
---|
941 |
|
---|
942 | std::cerr << "Case +++++++++++++ " << appExpr->func << std::endl;
|
---|
943 | std::cerr << "parameters are:" << std::endl;
|
---|
944 | ast::printAll( std::cerr, function->params, 2 );
|
---|
945 | std::cerr << "arguments are:" << std::endl;
|
---|
946 | ast::printAll( std::cerr, appExpr->args, 2 );
|
---|
947 | std::cerr << "bindings are:" << std::endl;
|
---|
948 | ast::print( std::cerr, withFunc->env, 2 );
|
---|
949 | std::cerr << "cost is: " << withFunc->cost << std::endl;
|
---|
950 | std::cerr << "cost of conversion is:" << cvtCost << std::endl;
|
---|
951 | )
|
---|
952 |
|
---|
953 | if ( cvtCost != Cost::infinity ) {
|
---|
954 | withFunc->cvtCost = cvtCost;
|
---|
955 | candidates.emplace_back( move( withFunc ) );
|
---|
956 | }
|
---|
957 | }
|
---|
958 | found = move( candidates );
|
---|
959 |
|
---|
960 | // use a new list so that candidates are not examined by addAnonConversions twice
|
---|
961 | CandidateList winners = findMinCost( found );
|
---|
962 | promoteCvtCost( winners );
|
---|
963 |
|
---|
964 | // function may return a struct/union value, in which case we need to add candidates
|
---|
965 | // for implicit conversions to each of the anonymous members, which must happen after
|
---|
966 | // `findMinCost`, since anon conversions are never the cheapest
|
---|
967 | for ( const CandidateRef & c : winners ) {
|
---|
968 | addAnonConversions( c );
|
---|
969 | }
|
---|
970 | spliceBegin( candidates, winners );
|
---|
971 |
|
---|
972 | if ( candidates.empty() && targetType && ! targetType->isVoid() ) {
|
---|
973 | // If resolution is unsuccessful with a target type, try again without, since it
|
---|
974 | // will sometimes succeed when it wouldn't with a target type binding.
|
---|
975 | // For example:
|
---|
976 | // forall( otype T ) T & ?[]( T *, ptrdiff_t );
|
---|
977 | // const char * x = "hello world";
|
---|
978 | // unsigned char ch = x[0];
|
---|
979 | // Fails with simple return type binding (xxx -- check this!) as follows:
|
---|
980 | // * T is bound to unsigned char
|
---|
981 | // * (x: const char *) is unified with unsigned char *, which fails
|
---|
982 | // xxx -- fix this better
|
---|
983 | targetType = nullptr;
|
---|
984 | postvisit( untypedExpr );
|
---|
985 | }
|
---|
986 | }
|
---|
987 |
|
---|
988 | /// true if expression is an lvalue
|
---|
989 | static bool isLvalue( const ast::Expr * x ) {
|
---|
990 | return x->result && ( x->result->is_lvalue() || x->result.as< ast::ReferenceType >() );
|
---|
991 | }
|
---|
992 |
|
---|
993 | void postvisit( const ast::AddressExpr * addressExpr ) {
|
---|
994 | CandidateFinder finder{ symtab, tenv };
|
---|
995 | finder.find( addressExpr->arg );
|
---|
996 | for ( CandidateRef & r : finder.candidates ) {
|
---|
997 | if ( ! isLvalue( r->expr ) ) continue;
|
---|
998 | addCandidate( *r, new ast::AddressExpr{ addressExpr->location, r->expr } );
|
---|
999 | }
|
---|
1000 | }
|
---|
1001 |
|
---|
1002 | void postvisit( const ast::LabelAddressExpr * labelExpr ) {
|
---|
1003 | addCandidate( labelExpr, tenv );
|
---|
1004 | }
|
---|
1005 |
|
---|
1006 | void postvisit( const ast::CastExpr * castExpr ) {
|
---|
1007 | ast::ptr< ast::Type > toType = castExpr->result;
|
---|
1008 | assert( toType );
|
---|
1009 | toType = resolveTypeof( toType, symtab );
|
---|
1010 | toType = SymTab::validateType( toType, symtab );
|
---|
1011 | toType = adjustExprType( toType, tenv, symtab );
|
---|
1012 |
|
---|
1013 | CandidateFinder finder{ symtab, tenv, toType };
|
---|
1014 | finder.find( castExpr->arg, ResolvMode::withAdjustment() );
|
---|
1015 |
|
---|
1016 | CandidateList matches;
|
---|
1017 | for ( CandidateRef & cand : finder.candidates ) {
|
---|
1018 | ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have;
|
---|
1019 | ast::OpenVarSet open( cand->open );
|
---|
1020 |
|
---|
1021 | cand->env.extractOpenVars( open );
|
---|
1022 |
|
---|
1023 | // It is possible that a cast can throw away some values in a multiply-valued
|
---|
1024 | // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of the
|
---|
1025 | // subexpression results that are cast directly. The candidate is invalid if it
|
---|
1026 | // has fewer results than there are types to cast to.
|
---|
1027 | int discardedValues = cand->expr->result->size() - toType->size();
|
---|
1028 | if ( discardedValues < 0 ) continue;
|
---|
1029 |
|
---|
1030 | // unification run for side-effects
|
---|
1031 | unify( toType, cand->expr->result, cand->env, need, have, open, symtab );
|
---|
1032 | Cost thisCost = castCost( cand->expr->result, toType, symtab, cand->env );
|
---|
1033 | PRINT(
|
---|
1034 | std::cerr << "working on cast with result: " << toType << std::endl;
|
---|
1035 | std::cerr << "and expr type: " << cand->expr->result << std::endl;
|
---|
1036 | std::cerr << "env: " << cand->env << std::endl;
|
---|
1037 | )
|
---|
1038 | if ( thisCost != Cost::infinity ) {
|
---|
1039 | PRINT(
|
---|
1040 | std::cerr << "has finite cost." << std::endl;
|
---|
1041 | )
|
---|
1042 | // count one safe conversion for each value that is thrown away
|
---|
1043 | thisCost.incSafe( discardedValues );
|
---|
1044 | CandidateRef newCand = std::make_shared<Candidate>(
|
---|
1045 | restructureCast( cand->expr, toType, castExpr->isGenerated ),
|
---|
1046 | copy( cand->env ), move( open ), move( need ), cand->cost,
|
---|
1047 | cand->cost + thisCost );
|
---|
1048 | inferParameters( newCand, matches );
|
---|
1049 | }
|
---|
1050 | }
|
---|
1051 |
|
---|
1052 | // select first on argument cost, then conversion cost
|
---|
1053 | CandidateList minArgCost = findMinCost( matches );
|
---|
1054 | promoteCvtCost( minArgCost );
|
---|
1055 | candidates = findMinCost( minArgCost );
|
---|
1056 | }
|
---|
1057 |
|
---|
1058 | void postvisit( const ast::VirtualCastExpr * castExpr ) {
|
---|
1059 | assertf( castExpr->result, "Implicit virtual cast targets not yet supported." );
|
---|
1060 | CandidateFinder finder{ symtab, tenv };
|
---|
1061 | // don't prune here, all alternatives guaranteed to have same type
|
---|
1062 | finder.find( castExpr->arg, ResolvMode::withoutPrune() );
|
---|
1063 | for ( CandidateRef & r : finder.candidates ) {
|
---|
1064 | addCandidate(
|
---|
1065 | *r,
|
---|
1066 | new ast::VirtualCastExpr{ castExpr->location, r->expr, castExpr->result } );
|
---|
1067 | }
|
---|
1068 | }
|
---|
1069 |
|
---|
1070 | void postvisit( const ast::UntypedMemberExpr * memberExpr ) {
|
---|
1071 | CandidateFinder aggFinder{ symtab, tenv };
|
---|
1072 | aggFinder.find( memberExpr->aggregate, ResolvMode::withAdjustment() );
|
---|
1073 | for ( CandidateRef & agg : aggFinder.candidates ) {
|
---|
1074 | // it's okay for the aggregate expression to have reference type -- cast it to the
|
---|
1075 | // base type to treat the aggregate as the referenced value
|
---|
1076 | Cost addedCost = Cost::zero;
|
---|
1077 | agg->expr = referenceToRvalueConversion( agg->expr, addedCost );
|
---|
1078 |
|
---|
1079 | // find member of the given type
|
---|
1080 | if ( auto structInst = agg->expr->result.as< ast::StructInstType >() ) {
|
---|
1081 | addAggMembers(
|
---|
1082 | structInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) );
|
---|
1083 | } else if ( auto unionInst = agg->expr->result.as< ast::UnionInstType >() ) {
|
---|
1084 | addAggMembers(
|
---|
1085 | unionInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) );
|
---|
1086 | } else if ( auto tupleType = agg->expr->result.as< ast::TupleType >() ) {
|
---|
1087 | addTupleMembers( tupleType, agg->expr, *agg, addedCost, memberExpr->member );
|
---|
1088 | }
|
---|
1089 | }
|
---|
1090 | }
|
---|
1091 |
|
---|
1092 | void postvisit( const ast::MemberExpr * memberExpr ) {
|
---|
1093 | addCandidate( memberExpr, tenv );
|
---|
1094 | }
|
---|
1095 |
|
---|
1096 | void postvisit( const ast::NameExpr * nameExpr ) {
|
---|
1097 | std::vector< ast::SymbolTable::IdData > declList = symtab.lookupId( nameExpr->name );
|
---|
1098 | PRINT( std::cerr << "nameExpr is " << nameExpr->name << std::endl; )
|
---|
1099 | for ( auto & data : declList ) {
|
---|
1100 | Cost cost = Cost::zero;
|
---|
1101 | ast::Expr * newExpr = data.combine( nameExpr->location, cost );
|
---|
1102 |
|
---|
1103 | CandidateRef newCand = std::make_shared<Candidate>(
|
---|
1104 | newExpr, copy( tenv ), ast::OpenVarSet{}, ast::AssertionSet{}, Cost::zero,
|
---|
1105 | cost );
|
---|
1106 | PRINT(
|
---|
1107 | std::cerr << "decl is ";
|
---|
1108 | ast::print( std::cerr, data.id );
|
---|
1109 | std::cerr << std::endl;
|
---|
1110 | std::cerr << "newExpr is ";
|
---|
1111 | ast::print( std::cerr, newExpr );
|
---|
1112 | std::cerr << std::endl;
|
---|
1113 | )
|
---|
1114 | newCand->expr = ast::mutate_field(
|
---|
1115 | newCand->expr.get(), &ast::Expr::result,
|
---|
1116 | renameTyVars( newCand->expr->result ) );
|
---|
1117 | // add anonymous member interpretations whenever an aggregate value type is seen
|
---|
1118 | // as a name expression
|
---|
1119 | addAnonConversions( newCand );
|
---|
1120 | candidates.emplace_back( move( newCand ) );
|
---|
1121 | }
|
---|
1122 | }
|
---|
1123 |
|
---|
1124 | void postvisit( const ast::VariableExpr * variableExpr ) {
|
---|
1125 | // not sufficient to just pass `variableExpr` here, type might have changed since
|
---|
1126 | // creation
|
---|
1127 | addCandidate(
|
---|
1128 | new ast::VariableExpr{ variableExpr->location, variableExpr->var }, tenv );
|
---|
1129 | }
|
---|
1130 |
|
---|
1131 | void postvisit( const ast::ConstantExpr * constantExpr ) {
|
---|
1132 | addCandidate( constantExpr, tenv );
|
---|
1133 | }
|
---|
1134 |
|
---|
1135 | void postvisit( const ast::SizeofExpr * sizeofExpr ) {
|
---|
1136 | if ( sizeofExpr->type ) {
|
---|
1137 | addCandidate(
|
---|
1138 | new ast::SizeofExpr{
|
---|
1139 | sizeofExpr->location, resolveTypeof( sizeofExpr->type, symtab ) },
|
---|
1140 | tenv );
|
---|
1141 | } else {
|
---|
1142 | // find all candidates for the argument to sizeof
|
---|
1143 | CandidateFinder finder{ symtab, tenv };
|
---|
1144 | finder.find( sizeofExpr->expr );
|
---|
1145 | // find the lowest-cost candidate, otherwise ambiguous
|
---|
1146 | CandidateList winners = findMinCost( finder.candidates );
|
---|
1147 | if ( winners.size() != 1 ) {
|
---|
1148 | SemanticError(
|
---|
1149 | sizeofExpr->expr.get(), "Ambiguous expression in sizeof operand: " );
|
---|
1150 | }
|
---|
1151 | // return the lowest-cost candidate
|
---|
1152 | CandidateRef & choice = winners.front();
|
---|
1153 | choice->expr = referenceToRvalueConversion( choice->expr, choice->cost );
|
---|
1154 | choice->cost = Cost::zero;
|
---|
1155 | addCandidate( *choice, new ast::SizeofExpr{ sizeofExpr->location, choice->expr } );
|
---|
1156 | }
|
---|
1157 | }
|
---|
1158 |
|
---|
1159 | void postvisit( const ast::AlignofExpr * alignofExpr ) {
|
---|
1160 | if ( alignofExpr->type ) {
|
---|
1161 | addCandidate(
|
---|
1162 | new ast::AlignofExpr{
|
---|
1163 | alignofExpr->location, resolveTypeof( alignofExpr->type, symtab ) },
|
---|
1164 | tenv );
|
---|
1165 | } else {
|
---|
1166 | // find all candidates for the argument to alignof
|
---|
1167 | CandidateFinder finder{ symtab, tenv };
|
---|
1168 | finder.find( alignofExpr->expr );
|
---|
1169 | // find the lowest-cost candidate, otherwise ambiguous
|
---|
1170 | CandidateList winners = findMinCost( finder.candidates );
|
---|
1171 | if ( winners.size() != 1 ) {
|
---|
1172 | SemanticError(
|
---|
1173 | alignofExpr->expr.get(), "Ambiguous expression in alignof 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(
|
---|
1180 | *choice, new ast::AlignofExpr{ alignofExpr->location, choice->expr } );
|
---|
1181 | }
|
---|
1182 | }
|
---|
1183 |
|
---|
1184 | void postvisit( const ast::UntypedOffsetofExpr * offsetofExpr ) {
|
---|
1185 | const ast::ReferenceToType * aggInst;
|
---|
1186 | if (( aggInst = offsetofExpr->type.as< ast::StructInstType >() )) ;
|
---|
1187 | else if (( aggInst = offsetofExpr->type.as< ast::UnionInstType >() )) ;
|
---|
1188 | else return;
|
---|
1189 |
|
---|
1190 | for ( const ast::Decl * member : aggInst->lookup( offsetofExpr->member ) ) {
|
---|
1191 | auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( member );
|
---|
1192 | addCandidate(
|
---|
1193 | new ast::OffsetofExpr{ offsetofExpr->location, aggInst, dwt }, tenv );
|
---|
1194 | }
|
---|
1195 | }
|
---|
1196 |
|
---|
1197 | void postvisit( const ast::OffsetofExpr * offsetofExpr ) {
|
---|
1198 | addCandidate( offsetofExpr, tenv );
|
---|
1199 | }
|
---|
1200 |
|
---|
1201 | void postvisit( const ast::OffsetPackExpr * offsetPackExpr ) {
|
---|
1202 | addCandidate( offsetPackExpr, tenv );
|
---|
1203 | }
|
---|
1204 |
|
---|
1205 | void postvisit( const ast::LogicalExpr * logicalExpr ) {
|
---|
1206 | CandidateFinder finder1{ symtab, tenv };
|
---|
1207 | finder1.find( logicalExpr->arg1, ResolvMode::withAdjustment() );
|
---|
1208 | if ( finder1.candidates.empty() ) return;
|
---|
1209 |
|
---|
1210 | CandidateFinder finder2{ symtab, tenv };
|
---|
1211 | finder2.find( logicalExpr->arg2, ResolvMode::withAdjustment() );
|
---|
1212 | if ( finder2.candidates.empty() ) return;
|
---|
1213 |
|
---|
1214 | for ( const CandidateRef & r1 : finder1.candidates ) {
|
---|
1215 | for ( const CandidateRef & r2 : finder2.candidates ) {
|
---|
1216 | ast::TypeEnvironment env{ r1->env };
|
---|
1217 | env.simpleCombine( r2->env );
|
---|
1218 | ast::OpenVarSet open{ r1->open };
|
---|
1219 | mergeOpenVars( open, r2->open );
|
---|
1220 | ast::AssertionSet need;
|
---|
1221 | mergeAssertionSet( need, r1->need );
|
---|
1222 | mergeAssertionSet( need, r2->need );
|
---|
1223 |
|
---|
1224 | addCandidate(
|
---|
1225 | new ast::LogicalExpr{
|
---|
1226 | logicalExpr->location, r1->expr, r2->expr, logicalExpr->isAnd },
|
---|
1227 | move( env ), move( open ), move( need ), r1->cost + r2->cost );
|
---|
1228 | }
|
---|
1229 | }
|
---|
1230 | }
|
---|
1231 |
|
---|
1232 | void postvisit( const ast::ConditionalExpr * conditionalExpr ) {
|
---|
1233 | // candidates for condition
|
---|
1234 | CandidateFinder finder1{ symtab, tenv };
|
---|
1235 | finder1.find( conditionalExpr->arg1, ResolvMode::withAdjustment() );
|
---|
1236 | if ( finder1.candidates.empty() ) return;
|
---|
1237 |
|
---|
1238 | // candidates for true result
|
---|
1239 | CandidateFinder finder2{ symtab, tenv };
|
---|
1240 | finder2.find( conditionalExpr->arg2, ResolvMode::withAdjustment() );
|
---|
1241 | if ( finder2.candidates.empty() ) return;
|
---|
1242 |
|
---|
1243 | // candidates for false result
|
---|
1244 | CandidateFinder finder3{ symtab, tenv };
|
---|
1245 | finder3.find( conditionalExpr->arg3, ResolvMode::withAdjustment() );
|
---|
1246 | if ( finder3.candidates.empty() ) return;
|
---|
1247 |
|
---|
1248 | for ( const CandidateRef & r1 : finder1.candidates ) {
|
---|
1249 | for ( const CandidateRef & r2 : finder2.candidates ) {
|
---|
1250 | for ( const CandidateRef & r3 : finder3.candidates ) {
|
---|
1251 | ast::TypeEnvironment env{ r1->env };
|
---|
1252 | env.simpleCombine( r2->env );
|
---|
1253 | env.simpleCombine( r3->env );
|
---|
1254 | ast::OpenVarSet open{ r1->open };
|
---|
1255 | mergeOpenVars( open, r2->open );
|
---|
1256 | mergeOpenVars( open, r3->open );
|
---|
1257 | ast::AssertionSet need;
|
---|
1258 | mergeAssertionSet( need, r1->need );
|
---|
1259 | mergeAssertionSet( need, r2->need );
|
---|
1260 | mergeAssertionSet( need, r3->need );
|
---|
1261 | ast::AssertionSet have;
|
---|
1262 |
|
---|
1263 | // unify true and false results, then infer parameters to produce new
|
---|
1264 | // candidates
|
---|
1265 | ast::ptr< ast::Type > common;
|
---|
1266 | if (
|
---|
1267 | unify(
|
---|
1268 | r2->expr->result, r3->expr->result, env, need, have, open, symtab,
|
---|
1269 | common )
|
---|
1270 | ) {
|
---|
1271 | // generate typed expression
|
---|
1272 | ast::ConditionalExpr * newExpr = new ast::ConditionalExpr{
|
---|
1273 | conditionalExpr->location, r1->expr, r2->expr, r3->expr };
|
---|
1274 | newExpr->result = common ? common : r2->expr->result;
|
---|
1275 | // convert both options to result type
|
---|
1276 | Cost cost = r1->cost + r2->cost + r3->cost;
|
---|
1277 | newExpr->arg2 = computeExpressionConversionCost(
|
---|
1278 | newExpr->arg2, newExpr->result, symtab, env, cost );
|
---|
1279 | newExpr->arg3 = computeExpressionConversionCost(
|
---|
1280 | newExpr->arg3, newExpr->result, symtab, env, cost );
|
---|
1281 | // output candidate
|
---|
1282 | CandidateRef newCand = std::make_shared<Candidate>(
|
---|
1283 | newExpr, move( env ), move( open ), move( need ), cost );
|
---|
1284 | inferParameters( newCand, candidates );
|
---|
1285 | }
|
---|
1286 | }
|
---|
1287 | }
|
---|
1288 | }
|
---|
1289 | }
|
---|
1290 |
|
---|
1291 | void postvisit( const ast::CommaExpr * commaExpr ) {
|
---|
1292 | ast::TypeEnvironment env{ tenv };
|
---|
1293 | ast::ptr< ast::Expr > arg1 = resolveInVoidContext( commaExpr->arg1, symtab, env );
|
---|
1294 |
|
---|
1295 | CandidateFinder finder2{ symtab, env };
|
---|
1296 | finder2.find( commaExpr->arg2, ResolvMode::withAdjustment() );
|
---|
1297 |
|
---|
1298 | for ( const CandidateRef & r2 : finder2.candidates ) {
|
---|
1299 | addCandidate( *r2, new ast::CommaExpr{ commaExpr->location, arg1, r2->expr } );
|
---|
1300 | }
|
---|
1301 | }
|
---|
1302 |
|
---|
1303 | void postvisit( const ast::ImplicitCopyCtorExpr * ctorExpr ) {
|
---|
1304 | addCandidate( ctorExpr, tenv );
|
---|
1305 | }
|
---|
1306 |
|
---|
1307 | void postvisit( const ast::ConstructorExpr * ctorExpr ) {
|
---|
1308 | CandidateFinder finder{ symtab, tenv };
|
---|
1309 | finder.find( ctorExpr->callExpr, ResolvMode::withoutPrune() );
|
---|
1310 | for ( CandidateRef & r : finder.candidates ) {
|
---|
1311 | addCandidate( *r, new ast::ConstructorExpr{ ctorExpr->location, r->expr } );
|
---|
1312 | }
|
---|
1313 | }
|
---|
1314 |
|
---|
1315 | void postvisit( const ast::RangeExpr * rangeExpr ) {
|
---|
1316 | // resolve low and high, accept candidates where low and high types unify
|
---|
1317 | CandidateFinder finder1{ symtab, tenv };
|
---|
1318 | finder1.find( rangeExpr->low, ResolvMode::withAdjustment() );
|
---|
1319 | if ( finder1.candidates.empty() ) return;
|
---|
1320 |
|
---|
1321 | CandidateFinder finder2{ symtab, tenv };
|
---|
1322 | finder2.find( rangeExpr->high, ResolvMode::withAdjustment() );
|
---|
1323 | if ( finder2.candidates.empty() ) return;
|
---|
1324 |
|
---|
1325 | for ( const CandidateRef & r1 : finder1.candidates ) {
|
---|
1326 | for ( const CandidateRef & r2 : finder2.candidates ) {
|
---|
1327 | ast::TypeEnvironment env{ r1->env };
|
---|
1328 | env.simpleCombine( r2->env );
|
---|
1329 | ast::OpenVarSet open{ r1->open };
|
---|
1330 | mergeOpenVars( open, r2->open );
|
---|
1331 | ast::AssertionSet need;
|
---|
1332 | mergeAssertionSet( need, r1->need );
|
---|
1333 | mergeAssertionSet( need, r2->need );
|
---|
1334 | ast::AssertionSet have;
|
---|
1335 |
|
---|
1336 | ast::ptr< ast::Type > common;
|
---|
1337 | if (
|
---|
1338 | unify(
|
---|
1339 | r1->expr->result, r2->expr->result, env, need, have, open, symtab,
|
---|
1340 | common )
|
---|
1341 | ) {
|
---|
1342 | // generate new expression
|
---|
1343 | ast::RangeExpr * newExpr =
|
---|
1344 | new ast::RangeExpr{ rangeExpr->location, r1->expr, r2->expr };
|
---|
1345 | newExpr->result = common ? common : r1->expr->result;
|
---|
1346 | // add candidate
|
---|
1347 | CandidateRef newCand = std::make_shared<Candidate>(
|
---|
1348 | newExpr, move( env ), move( open ), move( need ),
|
---|
1349 | r1->cost + r2->cost );
|
---|
1350 | inferParameters( newCand, candidates );
|
---|
1351 | }
|
---|
1352 | }
|
---|
1353 | }
|
---|
1354 | }
|
---|
1355 |
|
---|
1356 | void postvisit( const ast::UntypedTupleExpr * tupleExpr ) {
|
---|
1357 | std::vector< CandidateFinder > subCandidates =
|
---|
1358 | selfFinder.findSubExprs( tupleExpr->exprs );
|
---|
1359 | std::vector< CandidateList > possibilities;
|
---|
1360 | combos( subCandidates.begin(), subCandidates.end(), back_inserter( possibilities ) );
|
---|
1361 |
|
---|
1362 | for ( const CandidateList & subs : possibilities ) {
|
---|
1363 | std::vector< ast::ptr< ast::Expr > > exprs;
|
---|
1364 | exprs.reserve( subs.size() );
|
---|
1365 | for ( const CandidateRef & sub : subs ) { exprs.emplace_back( sub->expr ); }
|
---|
1366 |
|
---|
1367 | ast::TypeEnvironment env;
|
---|
1368 | ast::OpenVarSet open;
|
---|
1369 | ast::AssertionSet need;
|
---|
1370 | for ( const CandidateRef & sub : subs ) {
|
---|
1371 | env.simpleCombine( sub->env );
|
---|
1372 | mergeOpenVars( open, sub->open );
|
---|
1373 | mergeAssertionSet( need, sub->need );
|
---|
1374 | }
|
---|
1375 |
|
---|
1376 | addCandidate(
|
---|
1377 | new ast::TupleExpr{ tupleExpr->location, move( exprs ) },
|
---|
1378 | move( env ), move( open ), move( need ), sumCost( subs ) );
|
---|
1379 | }
|
---|
1380 | }
|
---|
1381 |
|
---|
1382 | void postvisit( const ast::TupleExpr * tupleExpr ) {
|
---|
1383 | addCandidate( tupleExpr, tenv );
|
---|
1384 | }
|
---|
1385 |
|
---|
1386 | void postvisit( const ast::TupleIndexExpr * tupleExpr ) {
|
---|
1387 | addCandidate( tupleExpr, tenv );
|
---|
1388 | }
|
---|
1389 |
|
---|
1390 | void postvisit( const ast::TupleAssignExpr * tupleExpr ) {
|
---|
1391 | addCandidate( tupleExpr, tenv );
|
---|
1392 | }
|
---|
1393 |
|
---|
1394 | void postvisit( const ast::UniqueExpr * unqExpr ) {
|
---|
1395 | CandidateFinder finder{ symtab, tenv };
|
---|
1396 | finder.find( unqExpr->expr, ResolvMode::withAdjustment() );
|
---|
1397 | for ( CandidateRef & r : finder.candidates ) {
|
---|
1398 | // ensure that the the id is passed on so that the expressions are "linked"
|
---|
1399 | addCandidate( *r, new ast::UniqueExpr{ unqExpr->location, r->expr, unqExpr->id } );
|
---|
1400 | }
|
---|
1401 | }
|
---|
1402 |
|
---|
1403 | void postvisit( const ast::StmtExpr * stmtExpr ) {
|
---|
1404 | addCandidate( resolveStmtExpr( stmtExpr, symtab ), tenv );
|
---|
1405 | }
|
---|
1406 |
|
---|
1407 | void postvisit( const ast::UntypedInitExpr * initExpr ) {
|
---|
1408 | // handle each option like a cast
|
---|
1409 | CandidateList matches;
|
---|
1410 | PRINT(
|
---|
1411 | std::cerr << "untyped init expr: " << initExpr << std::endl;
|
---|
1412 | )
|
---|
1413 | // O(n^2) checks of d-types with e-types
|
---|
1414 | for ( const ast::InitAlternative & initAlt : initExpr->initAlts ) {
|
---|
1415 | // calculate target type
|
---|
1416 | const ast::Type * toType = resolveTypeof( initAlt.type, symtab );
|
---|
1417 | toType = SymTab::validateType( toType, symtab );
|
---|
1418 | toType = adjustExprType( toType, tenv, symtab );
|
---|
1419 | // The call to find must occur inside this loop, otherwise polymorphic return
|
---|
1420 | // types are not bound to the initialization type, since return type variables are
|
---|
1421 | // only open for the duration of resolving the UntypedExpr.
|
---|
1422 | CandidateFinder finder{ symtab, tenv, toType };
|
---|
1423 | finder.find( initExpr->expr, ResolvMode::withAdjustment() );
|
---|
1424 | for ( CandidateRef & cand : finder.candidates ) {
|
---|
1425 | ast::TypeEnvironment env{ cand->env };
|
---|
1426 | ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have;
|
---|
1427 | ast::OpenVarSet open{ cand->open };
|
---|
1428 |
|
---|
1429 | PRINT(
|
---|
1430 | std::cerr << " @ " << toType << " " << initAlt.designation << std::endl;
|
---|
1431 | )
|
---|
1432 |
|
---|
1433 | // It is possible that a cast can throw away some values in a multiply-valued
|
---|
1434 | // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of
|
---|
1435 | // the subexpression results that are cast directly. The candidate is invalid
|
---|
1436 | // if it has fewer results than there are types to cast to.
|
---|
1437 | int discardedValues = cand->expr->result->size() - toType->size();
|
---|
1438 | if ( discardedValues < 0 ) continue;
|
---|
1439 |
|
---|
1440 | // unification run for side-effects
|
---|
1441 | unify( toType, cand->expr->result, env, need, have, open, symtab );
|
---|
1442 | Cost thisCost = castCost( cand->expr->result, toType, symtab, env );
|
---|
1443 |
|
---|
1444 | if ( thisCost != Cost::infinity ) {
|
---|
1445 | // count one safe conversion for each value that is thrown away
|
---|
1446 | thisCost.incSafe( discardedValues );
|
---|
1447 | CandidateRef newCand = std::make_shared<Candidate>(
|
---|
1448 | new ast::InitExpr{
|
---|
1449 | initExpr->location, restructureCast( cand->expr, toType ),
|
---|
1450 | initAlt.designation },
|
---|
1451 | copy( cand->env ), move( open ), move( need ), cand->cost, thisCost );
|
---|
1452 | inferParameters( newCand, matches );
|
---|
1453 | }
|
---|
1454 | }
|
---|
1455 | }
|
---|
1456 |
|
---|
1457 | // select first on argument cost, then conversion cost
|
---|
1458 | CandidateList minArgCost = findMinCost( matches );
|
---|
1459 | promoteCvtCost( minArgCost );
|
---|
1460 | candidates = findMinCost( minArgCost );
|
---|
1461 | }
|
---|
1462 |
|
---|
1463 | void postvisit( const ast::InitExpr * ) {
|
---|
1464 | assertf( false, "CandidateFinder should never see a resolved InitExpr." );
|
---|
1465 | }
|
---|
1466 |
|
---|
1467 | void postvisit( const ast::DeletedExpr * ) {
|
---|
1468 | assertf( false, "CandidateFinder should never see a DeletedExpr." );
|
---|
1469 | }
|
---|
1470 |
|
---|
1471 | void postvisit( const ast::GenericExpr * ) {
|
---|
1472 | assertf( false, "_Generic is not yet supported." );
|
---|
1473 | }
|
---|
1474 | };
|
---|
1475 |
|
---|
1476 | /// Prunes a list of candidates down to those that have the minimum conversion cost for a given
|
---|
1477 | /// return type. Skips ambiguous candidates.
|
---|
1478 | CandidateList pruneCandidates( CandidateList & candidates ) {
|
---|
1479 | struct PruneStruct {
|
---|
1480 | CandidateRef candidate;
|
---|
1481 | bool ambiguous;
|
---|
1482 |
|
---|
1483 | PruneStruct() = default;
|
---|
1484 | PruneStruct( const CandidateRef & c ) : candidate( c ), ambiguous( false ) {}
|
---|
1485 | };
|
---|
1486 |
|
---|
1487 | // find lowest-cost candidate for each type
|
---|
1488 | std::unordered_map< std::string, PruneStruct > selected;
|
---|
1489 | for ( CandidateRef & candidate : candidates ) {
|
---|
1490 | std::string mangleName;
|
---|
1491 | {
|
---|
1492 | ast::ptr< ast::Type > newType = candidate->expr->result;
|
---|
1493 | candidate->env.apply( newType );
|
---|
1494 | mangleName = Mangle::mangle( newType );
|
---|
1495 | }
|
---|
1496 |
|
---|
1497 | auto found = selected.find( mangleName );
|
---|
1498 | if ( found != selected.end() ) {
|
---|
1499 | if ( candidate->cost < found->second.candidate->cost ) {
|
---|
1500 | PRINT(
|
---|
1501 | std::cerr << "cost " << candidate->cost << " beats "
|
---|
1502 | << found->second.candidate->cost << std::endl;
|
---|
1503 | )
|
---|
1504 |
|
---|
1505 | found->second = PruneStruct{ candidate };
|
---|
1506 | } else if ( candidate->cost == found->second.candidate->cost ) {
|
---|
1507 | // if one of the candidates contains a deleted identifier, can pick the other,
|
---|
1508 | // since deleted expressions should not be ambiguous if there is another option
|
---|
1509 | // that is at least as good
|
---|
1510 | if ( findDeletedExpr( candidate->expr ) ) {
|
---|
1511 | // do nothing
|
---|
1512 | PRINT( std::cerr << "candidate is deleted" << std::endl; )
|
---|
1513 | } else if ( findDeletedExpr( found->second.candidate->expr ) ) {
|
---|
1514 | PRINT( std::cerr << "current is deleted" << std::endl; )
|
---|
1515 | found->second = PruneStruct{ candidate };
|
---|
1516 | } else {
|
---|
1517 | PRINT( std::cerr << "marking ambiguous" << std::endl; )
|
---|
1518 | found->second.ambiguous = true;
|
---|
1519 | }
|
---|
1520 | } else {
|
---|
1521 | PRINT(
|
---|
1522 | std::cerr << "cost " << candidate->cost << " loses to "
|
---|
1523 | << found->second.candidate->cost << std::endl;
|
---|
1524 | )
|
---|
1525 | }
|
---|
1526 | } else {
|
---|
1527 | selected.emplace_hint( found, mangleName, candidate );
|
---|
1528 | }
|
---|
1529 | }
|
---|
1530 |
|
---|
1531 | // report unambiguous min-cost candidates
|
---|
1532 | CandidateList out;
|
---|
1533 | for ( auto & target : selected ) {
|
---|
1534 | if ( target.second.ambiguous ) continue;
|
---|
1535 |
|
---|
1536 | CandidateRef cand = target.second.candidate;
|
---|
1537 |
|
---|
1538 | ast::ptr< ast::Type > newResult = cand->expr->result;
|
---|
1539 | cand->env.applyFree( newResult );
|
---|
1540 | cand->expr = ast::mutate_field(
|
---|
1541 | cand->expr.get(), &ast::Expr::result, move( newResult ) );
|
---|
1542 |
|
---|
1543 | out.emplace_back( cand );
|
---|
1544 | }
|
---|
1545 | return out;
|
---|
1546 | }
|
---|
1547 |
|
---|
1548 | } // anonymous namespace
|
---|
1549 |
|
---|
1550 | void CandidateFinder::find( const ast::Expr * expr, ResolvMode mode ) {
|
---|
1551 | // Find alternatives for expression
|
---|
1552 | ast::Pass<Finder> finder{ *this };
|
---|
1553 | expr->accept( finder );
|
---|
1554 |
|
---|
1555 | if ( mode.failFast && candidates.empty() ) {
|
---|
1556 | SemanticError( expr, "No reasonable alternatives for expression " );
|
---|
1557 | }
|
---|
1558 |
|
---|
1559 | if ( mode.satisfyAssns || mode.prune ) {
|
---|
1560 | // trim candidates to just those where the assertions are satisfiable
|
---|
1561 | // - necessary pre-requisite to pruning
|
---|
1562 | CandidateList satisfied;
|
---|
1563 | std::vector< std::string > errors;
|
---|
1564 | for ( CandidateRef & candidate : candidates ) {
|
---|
1565 | satisfyAssertions( candidate, symtab, satisfied, errors );
|
---|
1566 | }
|
---|
1567 |
|
---|
1568 | // fail early if none such
|
---|
1569 | if ( mode.failFast && satisfied.empty() ) {
|
---|
1570 | std::ostringstream stream;
|
---|
1571 | stream << "No alternatives with satisfiable assertions for " << expr << "\n";
|
---|
1572 | for ( const auto& err : errors ) {
|
---|
1573 | stream << err;
|
---|
1574 | }
|
---|
1575 | SemanticError( expr->location, stream.str() );
|
---|
1576 | }
|
---|
1577 |
|
---|
1578 | // reset candidates
|
---|
1579 | candidates = move( satisfied );
|
---|
1580 | }
|
---|
1581 |
|
---|
1582 | if ( mode.prune ) {
|
---|
1583 | // trim candidates to single best one
|
---|
1584 | PRINT(
|
---|
1585 | std::cerr << "alternatives before prune:" << std::endl;
|
---|
1586 | print( std::cerr, candidates );
|
---|
1587 | )
|
---|
1588 |
|
---|
1589 | CandidateList pruned = pruneCandidates( candidates );
|
---|
1590 |
|
---|
1591 | if ( mode.failFast && pruned.empty() ) {
|
---|
1592 | std::ostringstream stream;
|
---|
1593 | CandidateList winners = findMinCost( candidates );
|
---|
1594 | stream << "Cannot choose between " << winners.size() << " alternatives for "
|
---|
1595 | "expression\n";
|
---|
1596 | ast::print( stream, expr );
|
---|
1597 | stream << " Alternatives are:\n";
|
---|
1598 | print( stream, winners, 1 );
|
---|
1599 | SemanticError( expr->location, stream.str() );
|
---|
1600 | }
|
---|
1601 |
|
---|
1602 | auto oldsize = candidates.size();
|
---|
1603 | candidates = move( pruned );
|
---|
1604 |
|
---|
1605 | PRINT(
|
---|
1606 | std::cerr << "there are " << oldsize << " alternatives before elimination" << std::endl;
|
---|
1607 | )
|
---|
1608 | PRINT(
|
---|
1609 | std::cerr << "there are " << candidates.size() << " alternatives after elimination"
|
---|
1610 | << std::endl;
|
---|
1611 | )
|
---|
1612 | }
|
---|
1613 |
|
---|
1614 | // adjust types after pruning so that types substituted by pruneAlternatives are correctly
|
---|
1615 | // adjusted
|
---|
1616 | if ( mode.adjust ) {
|
---|
1617 | for ( CandidateRef & r : candidates ) {
|
---|
1618 | r->expr = ast::mutate_field(
|
---|
1619 | r->expr.get(), &ast::Expr::result,
|
---|
1620 | adjustExprType( r->expr->result, r->env, symtab ) );
|
---|
1621 | }
|
---|
1622 | }
|
---|
1623 |
|
---|
1624 | // Central location to handle gcc extension keyword, etc. for all expressions
|
---|
1625 | for ( CandidateRef & r : candidates ) {
|
---|
1626 | if ( r->expr->extension != expr->extension ) {
|
---|
1627 | r->expr.get_and_mutate()->extension = expr->extension;
|
---|
1628 | }
|
---|
1629 | }
|
---|
1630 | }
|
---|
1631 |
|
---|
1632 | std::vector< CandidateFinder > CandidateFinder::findSubExprs(
|
---|
1633 | const std::vector< ast::ptr< ast::Expr > > & xs
|
---|
1634 | ) {
|
---|
1635 | std::vector< CandidateFinder > out;
|
---|
1636 |
|
---|
1637 | for ( const auto & x : xs ) {
|
---|
1638 | out.emplace_back( symtab, env );
|
---|
1639 | out.back().find( x, ResolvMode::withAdjustment() );
|
---|
1640 |
|
---|
1641 | PRINT(
|
---|
1642 | std::cerr << "findSubExprs" << std::endl;
|
---|
1643 | print( std::cerr, out.back().candidates );
|
---|
1644 | )
|
---|
1645 | }
|
---|
1646 |
|
---|
1647 | return out;
|
---|
1648 | }
|
---|
1649 |
|
---|
1650 | } // namespace ResolvExpr
|
---|
1651 |
|
---|
1652 | // Local Variables: //
|
---|
1653 | // tab-width: 4 //
|
---|
1654 | // mode: c++ //
|
---|
1655 | // compile-command: "make install" //
|
---|
1656 | // End: //
|
---|