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