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 | void postvisit( const ast::InitExpr * ) { |
---|
701 | assertf( false, "CandidateFinder should never see a resolved InitExpr." ); |
---|
702 | } |
---|
703 | |
---|
704 | void postvisit( const ast::DeletedExpr * ) { |
---|
705 | assertf( false, "CandidateFinder should never see a DeletedExpr." ); |
---|
706 | } |
---|
707 | |
---|
708 | void postvisit( const ast::GenericExpr * ) { |
---|
709 | assertf( false, "_Generic is not yet supported." ); |
---|
710 | } |
---|
711 | }; |
---|
712 | |
---|
713 | /// Set up candidate assertions for inference |
---|
714 | void Finder::inferParameters( CandidateRef & newCand, CandidateList & out ) { |
---|
715 | // Set need bindings for any unbound assertions |
---|
716 | ast::UniqueId crntResnSlot = 0; // matching ID for this expression's assertions |
---|
717 | for ( auto & assn : newCand->need ) { |
---|
718 | // skip already-matched assertions |
---|
719 | if ( assn.second.resnSlot != 0 ) continue; |
---|
720 | // assign slot for expression if needed |
---|
721 | if ( crntResnSlot == 0 ) { crntResnSlot = ++globalResnSlot; } |
---|
722 | // fix slot to assertion |
---|
723 | assn.second.resnSlot = crntResnSlot; |
---|
724 | } |
---|
725 | // pair slot to expression |
---|
726 | if ( crntResnSlot != 0 ) { |
---|
727 | newCand->expr.get_and_mutate()->inferred.resnSlots().emplace_back( crntResnSlot ); |
---|
728 | } |
---|
729 | |
---|
730 | // add to output list; assertion satisfaction will occur later |
---|
731 | out.emplace_back( newCand ); |
---|
732 | } |
---|
733 | |
---|
734 | /// Completes a function candidate with arguments located |
---|
735 | void Finder::validateFunctionCandidate( |
---|
736 | const CandidateRef & func, ArgPack & result, const std::vector< ArgPack > & results, |
---|
737 | CandidateList & out |
---|
738 | ) { |
---|
739 | ast::ApplicationExpr * appExpr = |
---|
740 | new ast::ApplicationExpr{ func->expr->location, func->expr }; |
---|
741 | // sum cost and accumulate arguments |
---|
742 | std::deque< const ast::Expr * > args; |
---|
743 | Cost cost = func->cost; |
---|
744 | const ArgPack * pack = &result; |
---|
745 | while ( pack->expr ) { |
---|
746 | args.emplace_front( pack->expr ); |
---|
747 | cost += pack->cost; |
---|
748 | pack = &results[pack->parent]; |
---|
749 | } |
---|
750 | std::vector< ast::ptr< ast::Expr > > vargs( args.begin(), args.end() ); |
---|
751 | appExpr->args = std::move( vargs ); |
---|
752 | // build and validate new candidate |
---|
753 | auto newCand = |
---|
754 | std::make_shared<Candidate>( appExpr, result.env, result.open, result.need, cost ); |
---|
755 | PRINT( |
---|
756 | std::cerr << "instantiate function success: " << appExpr << std::endl; |
---|
757 | std::cerr << "need assertions:" << std::endl; |
---|
758 | ast::print( std::cerr, result.need, 2 ); |
---|
759 | ) |
---|
760 | inferParameters( newCand, out ); |
---|
761 | } |
---|
762 | |
---|
763 | /// Builds a list of candidates for a function, storing them in out |
---|
764 | void Finder::makeFunctionCandidates( |
---|
765 | const CodeLocation & location, |
---|
766 | const CandidateRef & func, const ast::FunctionType * funcType, |
---|
767 | const ExplodedArgs & args, CandidateList & out |
---|
768 | ) { |
---|
769 | ast::OpenVarSet funcOpen; |
---|
770 | ast::AssertionSet funcNeed, funcHave; |
---|
771 | ast::TypeEnvironment funcEnv{ func->env }; |
---|
772 | makeUnifiableVars( funcType, funcOpen, funcNeed ); |
---|
773 | // add all type variables as open variables now so that those not used in the |
---|
774 | // parameter list are still considered open |
---|
775 | funcEnv.add( funcType->forall ); |
---|
776 | |
---|
777 | if ( targetType && ! targetType->isVoid() && ! funcType->returns.empty() ) { |
---|
778 | // attempt to narrow based on expected target type |
---|
779 | const ast::Type * returnType = funcType->returns.front(); |
---|
780 | if ( selfFinder.strictMode ) { |
---|
781 | if ( !unifyExact( |
---|
782 | returnType, targetType, funcEnv, funcNeed, funcHave, funcOpen, noWiden() ) // xxx - is no widening correct? |
---|
783 | ) { |
---|
784 | // unification failed, do not pursue this candidate |
---|
785 | return; |
---|
786 | } |
---|
787 | } else { |
---|
788 | if ( !unify( |
---|
789 | returnType, targetType, funcEnv, funcNeed, funcHave, funcOpen ) |
---|
790 | ) { |
---|
791 | // unification failed, do not pursue this candidate |
---|
792 | return; |
---|
793 | } |
---|
794 | } |
---|
795 | } |
---|
796 | |
---|
797 | // iteratively build matches, one parameter at a time |
---|
798 | std::vector< ArgPack > results; |
---|
799 | results.emplace_back( funcEnv, funcNeed, funcHave, funcOpen ); |
---|
800 | std::size_t genStart = 0; |
---|
801 | |
---|
802 | // xxx - how to handle default arg after change to ftype representation? |
---|
803 | if (const ast::VariableExpr * varExpr = func->expr.as<ast::VariableExpr>()) { |
---|
804 | if (const ast::FunctionDecl * funcDecl = varExpr->var.as<ast::FunctionDecl>()) { |
---|
805 | // function may have default args only if directly calling by name |
---|
806 | // must use types on candidate however, due to RenameVars substitution |
---|
807 | auto nParams = funcType->params.size(); |
---|
808 | |
---|
809 | for (size_t i=0; i<nParams; ++i) { |
---|
810 | auto obj = funcDecl->params[i].strict_as<ast::ObjectDecl>(); |
---|
811 | if ( !instantiateArgument( location, |
---|
812 | funcType->params[i], obj->init, args, results, genStart, context)) return; |
---|
813 | } |
---|
814 | goto endMatch; |
---|
815 | } |
---|
816 | } |
---|
817 | for ( const auto & param : funcType->params ) { |
---|
818 | // Try adding the arguments corresponding to the current parameter to the existing |
---|
819 | // matches |
---|
820 | // no default args for indirect calls |
---|
821 | if ( !instantiateArgument( location, |
---|
822 | param, nullptr, args, results, genStart, context ) ) return; |
---|
823 | } |
---|
824 | |
---|
825 | endMatch: |
---|
826 | if ( funcType->isVarArgs ) { |
---|
827 | // append any unused arguments to vararg pack |
---|
828 | std::size_t genEnd; |
---|
829 | do { |
---|
830 | genEnd = results.size(); |
---|
831 | |
---|
832 | // iterate results |
---|
833 | for ( std::size_t i = genStart; i < genEnd; ++i ) { |
---|
834 | unsigned nextArg = results[i].nextArg; |
---|
835 | |
---|
836 | // use remainder of exploded tuple if present |
---|
837 | if ( results[i].hasExpl() ) { |
---|
838 | const ExplodedArg & expl = results[i].getExpl( args ); |
---|
839 | |
---|
840 | unsigned nextExpl = results[i].nextExpl + 1; |
---|
841 | if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; } |
---|
842 | |
---|
843 | results.emplace_back( |
---|
844 | i, expl.exprs[ results[i].nextExpl ], copy( results[i].env ), |
---|
845 | copy( results[i].need ), copy( results[i].have ), |
---|
846 | copy( results[i].open ), nextArg, 0, Cost::zero, nextExpl, |
---|
847 | results[i].explAlt ); |
---|
848 | |
---|
849 | continue; |
---|
850 | } |
---|
851 | |
---|
852 | // finish result when out of arguments |
---|
853 | if ( nextArg >= args.size() ) { |
---|
854 | validateFunctionCandidate( func, results[i], results, out ); |
---|
855 | |
---|
856 | continue; |
---|
857 | } |
---|
858 | |
---|
859 | // add each possible next argument |
---|
860 | for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) { |
---|
861 | const ExplodedArg & expl = args[nextArg][j]; |
---|
862 | |
---|
863 | // fresh copies of parent parameters for this iteration |
---|
864 | ast::TypeEnvironment env = results[i].env; |
---|
865 | ast::OpenVarSet open = results[i].open; |
---|
866 | |
---|
867 | env.addActual( expl.env, open ); |
---|
868 | |
---|
869 | // skip empty tuple arguments by (nearly) cloning parent into next gen |
---|
870 | if ( expl.exprs.empty() ) { |
---|
871 | results.emplace_back( |
---|
872 | results[i], std::move( env ), copy( results[i].need ), |
---|
873 | copy( results[i].have ), std::move( open ), nextArg + 1, |
---|
874 | expl.cost ); |
---|
875 | |
---|
876 | continue; |
---|
877 | } |
---|
878 | |
---|
879 | // add new result |
---|
880 | results.emplace_back( |
---|
881 | i, expl.exprs.front(), std::move( env ), copy( results[i].need ), |
---|
882 | copy( results[i].have ), std::move( open ), nextArg + 1, 0, expl.cost, |
---|
883 | expl.exprs.size() == 1 ? 0 : 1, j ); |
---|
884 | } |
---|
885 | } |
---|
886 | |
---|
887 | genStart = genEnd; |
---|
888 | } while( genEnd != results.size() ); |
---|
889 | } else { |
---|
890 | // filter out the results that don't use all the arguments |
---|
891 | for ( std::size_t i = genStart; i < results.size(); ++i ) { |
---|
892 | ArgPack & result = results[i]; |
---|
893 | if ( ! result.hasExpl() && result.nextArg >= args.size() ) { |
---|
894 | validateFunctionCandidate( func, result, results, out ); |
---|
895 | } |
---|
896 | } |
---|
897 | } |
---|
898 | } |
---|
899 | |
---|
900 | void Finder::addEnumValueAsCandidate( const ast::EnumInstType * enumInst, const ast::Expr * expr, |
---|
901 | const Cost & addedCost |
---|
902 | ) { |
---|
903 | if ( enumInst->base->base ) { |
---|
904 | CandidateFinder finder( context, tenv ); |
---|
905 | auto location = expr->location; |
---|
906 | auto callExpr = new ast::UntypedExpr( |
---|
907 | location, new ast::NameExpr( location, "value" ), {expr} |
---|
908 | ); |
---|
909 | finder.find( callExpr ); |
---|
910 | CandidateList winners = findMinCost( finder.candidates ); |
---|
911 | if (winners.size() != 1) { |
---|
912 | SemanticError( callExpr, "Ambiguous expression in value..." ); |
---|
913 | } |
---|
914 | CandidateRef & choice = winners.front(); |
---|
915 | choice->cost += addedCost; |
---|
916 | addAnonConversions(choice); |
---|
917 | candidates.emplace_back( std::move(choice) ); |
---|
918 | } |
---|
919 | } |
---|
920 | |
---|
921 | /// Adds implicit struct-conversions to the alternative list |
---|
922 | void Finder::addAnonConversions( const CandidateRef & cand ) { |
---|
923 | // adds anonymous member interpretations whenever an aggregate value type is seen. |
---|
924 | // it's okay for the aggregate expression to have reference type -- cast it to the |
---|
925 | // base type to treat the aggregate as the referenced value |
---|
926 | ast::ptr< ast::Expr > aggrExpr( cand->expr ); |
---|
927 | ast::ptr< ast::Type > & aggrType = aggrExpr.get_and_mutate()->result; |
---|
928 | cand->env.apply( aggrType ); |
---|
929 | |
---|
930 | if ( aggrType.as< ast::ReferenceType >() ) { |
---|
931 | aggrExpr = new ast::CastExpr{ aggrExpr, aggrType->stripReferences() }; |
---|
932 | } |
---|
933 | |
---|
934 | if ( auto structInst = aggrExpr->result.as< ast::StructInstType >() ) { |
---|
935 | addAggMembers( structInst, aggrExpr, *cand, Cost::unsafe, "" ); |
---|
936 | } else if ( auto unionInst = aggrExpr->result.as< ast::UnionInstType >() ) { |
---|
937 | addAggMembers( unionInst, aggrExpr, *cand, Cost::unsafe, "" ); |
---|
938 | } else if ( auto enumInst = aggrExpr->result.as< ast::EnumInstType >() ) { |
---|
939 | addEnumValueAsCandidate(enumInst, aggrExpr, Cost::unsafe); |
---|
940 | } |
---|
941 | } |
---|
942 | |
---|
943 | |
---|
944 | /// Adds aggregate member interpretations |
---|
945 | void Finder::addAggMembers( |
---|
946 | const ast::BaseInstType * aggrInst, const ast::Expr * expr, |
---|
947 | const Candidate & cand, const Cost & addedCost, const std::string & name |
---|
948 | ) { |
---|
949 | for ( const ast::Decl * decl : aggrInst->lookup( name ) ) { |
---|
950 | auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( decl ); |
---|
951 | CandidateRef newCand = std::make_shared<Candidate>( |
---|
952 | cand, new ast::MemberExpr{ expr->location, dwt, expr }, addedCost ); |
---|
953 | // add anonymous member interpretations whenever an aggregate value type is seen |
---|
954 | // as a member expression |
---|
955 | addAnonConversions( newCand ); |
---|
956 | candidates.emplace_back( std::move( newCand ) ); |
---|
957 | } |
---|
958 | } |
---|
959 | |
---|
960 | /// Adds tuple member interpretations |
---|
961 | void Finder::addTupleMembers( |
---|
962 | const ast::TupleType * tupleType, const ast::Expr * expr, const Candidate & cand, |
---|
963 | const Cost & addedCost, const ast::Expr * member |
---|
964 | ) { |
---|
965 | if ( auto constantExpr = dynamic_cast< const ast::ConstantExpr * >( member ) ) { |
---|
966 | // get the value of the constant expression as an int, must be between 0 and the |
---|
967 | // length of the tuple to have meaning |
---|
968 | long long val = constantExpr->intValue(); |
---|
969 | if ( val >= 0 && (unsigned long long)val < tupleType->size() ) { |
---|
970 | addCandidate( |
---|
971 | cand, new ast::TupleIndexExpr{ expr->location, expr, (unsigned)val }, |
---|
972 | addedCost ); |
---|
973 | } |
---|
974 | } |
---|
975 | } |
---|
976 | |
---|
977 | void Finder::postvisit( const ast::UntypedExpr * untypedExpr ) { |
---|
978 | std::vector< CandidateFinder > argCandidates = |
---|
979 | selfFinder.findSubExprs( untypedExpr->args ); |
---|
980 | |
---|
981 | // take care of possible tuple assignments |
---|
982 | // if not tuple assignment, handled as normal function call |
---|
983 | Tuples::handleTupleAssignment( selfFinder, untypedExpr, argCandidates ); |
---|
984 | |
---|
985 | CandidateFinder funcFinder( context, tenv ); |
---|
986 | std::string funcName; |
---|
987 | if (auto nameExpr = untypedExpr->func.as<ast::NameExpr>()) { |
---|
988 | funcName = nameExpr->name; |
---|
989 | auto kind = ast::SymbolTable::getSpecialFunctionKind(nameExpr->name); |
---|
990 | if (kind != ast::SymbolTable::SpecialFunctionKind::NUMBER_OF_KINDS) { |
---|
991 | assertf(!argCandidates.empty(), "special function call without argument"); |
---|
992 | for (auto & firstArgCand: argCandidates[0]) { |
---|
993 | ast::ptr<ast::Type> argType = firstArgCand->expr->result; |
---|
994 | firstArgCand->env.apply(argType); |
---|
995 | // strip references |
---|
996 | // xxx - is this correct? |
---|
997 | while (argType.as<ast::ReferenceType>()) argType = argType.as<ast::ReferenceType>()->base; |
---|
998 | |
---|
999 | // convert 1-tuple to plain type |
---|
1000 | if (auto tuple = argType.as<ast::TupleType>()) { |
---|
1001 | if (tuple->size() == 1) { |
---|
1002 | argType = tuple->types[0]; |
---|
1003 | } |
---|
1004 | } |
---|
1005 | |
---|
1006 | // if argType is an unbound type parameter, all special functions need to be searched. |
---|
1007 | if (isUnboundType(argType)) { |
---|
1008 | funcFinder.otypeKeys.clear(); |
---|
1009 | break; |
---|
1010 | } |
---|
1011 | |
---|
1012 | if (argType.as<ast::PointerType>()) funcFinder.otypeKeys.insert(Mangle::Encoding::pointer); |
---|
1013 | else funcFinder.otypeKeys.insert(Mangle::mangle(argType, Mangle::NoGenericParams | Mangle::Type)); |
---|
1014 | } |
---|
1015 | } |
---|
1016 | } |
---|
1017 | // if candidates are already produced, do not fail |
---|
1018 | // xxx - is it possible that handleTupleAssignment and main finder both produce candidates? |
---|
1019 | // this means there exists ctor/assign functions with a tuple as first parameter. |
---|
1020 | ResolveMode mode = { |
---|
1021 | true, // adjust |
---|
1022 | !untypedExpr->func.as<ast::NameExpr>(), // prune if not calling by name |
---|
1023 | selfFinder.candidates.empty() // failfast if other options are not found |
---|
1024 | }; |
---|
1025 | funcFinder.find( untypedExpr->func, mode ); |
---|
1026 | // short-circuit if no candidates |
---|
1027 | // if ( funcFinder.candidates.empty() ) return; |
---|
1028 | |
---|
1029 | reason.code = NoMatch; |
---|
1030 | |
---|
1031 | // find function operators |
---|
1032 | ast::ptr< ast::Expr > opExpr = new ast::NameExpr{ untypedExpr->location, "?()" }; // ??? why not ?{} |
---|
1033 | CandidateFinder opFinder( context, tenv ); |
---|
1034 | // okay if there aren't any function operations |
---|
1035 | opFinder.find( opExpr, ResolveMode::withoutFailFast() ); |
---|
1036 | PRINT( |
---|
1037 | std::cerr << "known function ops:" << std::endl; |
---|
1038 | print( std::cerr, opFinder.candidates, 1 ); |
---|
1039 | ) |
---|
1040 | |
---|
1041 | // pre-explode arguments |
---|
1042 | ExplodedArgs argExpansions; |
---|
1043 | for ( const CandidateFinder & args : argCandidates ) { |
---|
1044 | argExpansions.emplace_back(); |
---|
1045 | auto & argE = argExpansions.back(); |
---|
1046 | for ( const CandidateRef & arg : args ) { argE.emplace_back( *arg, symtab ); } |
---|
1047 | } |
---|
1048 | |
---|
1049 | // Find function matches |
---|
1050 | CandidateList found; |
---|
1051 | SemanticErrorException errors; |
---|
1052 | |
---|
1053 | for ( CandidateRef & func : funcFinder ) { |
---|
1054 | try { |
---|
1055 | PRINT( |
---|
1056 | std::cerr << "working on alternative:" << std::endl; |
---|
1057 | print( std::cerr, *func, 2 ); |
---|
1058 | ) |
---|
1059 | |
---|
1060 | // check if the type is a pointer to function |
---|
1061 | const ast::Type * funcResult = func->expr->result->stripReferences(); |
---|
1062 | if ( auto pointer = dynamic_cast< const ast::PointerType * >( funcResult ) ) { |
---|
1063 | if ( auto function = pointer->base.as< ast::FunctionType >() ) { |
---|
1064 | // if (!selfFinder.allowVoid && function->returns.empty()) continue; |
---|
1065 | CandidateRef newFunc{ new Candidate{ *func } }; |
---|
1066 | newFunc->expr = |
---|
1067 | referenceToRvalueConversion( newFunc->expr, newFunc->cost ); |
---|
1068 | makeFunctionCandidates( untypedExpr->location, |
---|
1069 | newFunc, function, argExpansions, found ); |
---|
1070 | } |
---|
1071 | } else if ( |
---|
1072 | auto inst = dynamic_cast< const ast::TypeInstType * >( funcResult ) |
---|
1073 | ) { |
---|
1074 | if ( const ast::EqvClass * clz = func->env.lookup( *inst ) ) { |
---|
1075 | if ( auto function = clz->bound.as< ast::FunctionType >() ) { |
---|
1076 | CandidateRef newFunc( new Candidate( *func ) ); |
---|
1077 | newFunc->expr = |
---|
1078 | referenceToRvalueConversion( newFunc->expr, newFunc->cost ); |
---|
1079 | makeFunctionCandidates( untypedExpr->location, |
---|
1080 | newFunc, function, argExpansions, found ); |
---|
1081 | } |
---|
1082 | } |
---|
1083 | } |
---|
1084 | } catch ( SemanticErrorException & e ) { errors.append( e ); } |
---|
1085 | } |
---|
1086 | |
---|
1087 | // Find matches on function operators `?()` |
---|
1088 | if ( ! opFinder.candidates.empty() ) { |
---|
1089 | // add exploded function alternatives to front of argument list |
---|
1090 | std::vector< ExplodedArg > funcE; |
---|
1091 | funcE.reserve( funcFinder.candidates.size() ); |
---|
1092 | for ( const CandidateRef & func : funcFinder ) { |
---|
1093 | funcE.emplace_back( *func, symtab ); |
---|
1094 | } |
---|
1095 | argExpansions.emplace_front( std::move( funcE ) ); |
---|
1096 | |
---|
1097 | for ( const CandidateRef & op : opFinder ) { |
---|
1098 | try { |
---|
1099 | // check if type is pointer-to-function |
---|
1100 | const ast::Type * opResult = op->expr->result->stripReferences(); |
---|
1101 | if ( auto pointer = dynamic_cast< const ast::PointerType * >( opResult ) ) { |
---|
1102 | if ( auto function = pointer->base.as< ast::FunctionType >() ) { |
---|
1103 | CandidateRef newOp{ new Candidate{ *op} }; |
---|
1104 | newOp->expr = |
---|
1105 | referenceToRvalueConversion( newOp->expr, newOp->cost ); |
---|
1106 | makeFunctionCandidates( untypedExpr->location, |
---|
1107 | newOp, function, argExpansions, found ); |
---|
1108 | } |
---|
1109 | } |
---|
1110 | } catch ( SemanticErrorException & e ) { errors.append( e ); } |
---|
1111 | } |
---|
1112 | } |
---|
1113 | |
---|
1114 | // Implement SFINAE; resolution errors are only errors if there aren't any non-error |
---|
1115 | // candidates |
---|
1116 | if ( found.empty() && ! errors.isEmpty() ) { throw errors; } |
---|
1117 | |
---|
1118 | // only keep the best matching intrinsic result to match C semantics (no unexpected narrowing/widening) |
---|
1119 | // TODO: keep one for each set of argument candidates? |
---|
1120 | Cost intrinsicCost = Cost::infinity; |
---|
1121 | CandidateList intrinsicResult; |
---|
1122 | |
---|
1123 | // Compute conversion costs |
---|
1124 | for ( CandidateRef & withFunc : found ) { |
---|
1125 | Cost cvtCost = computeApplicationConversionCost( withFunc, symtab ); |
---|
1126 | |
---|
1127 | if (funcName == "?|?") { |
---|
1128 | PRINT( |
---|
1129 | auto appExpr = withFunc->expr.strict_as< ast::ApplicationExpr >(); |
---|
1130 | auto pointer = appExpr->func->result.strict_as< ast::PointerType >(); |
---|
1131 | auto function = pointer->base.strict_as< ast::FunctionType >(); |
---|
1132 | |
---|
1133 | std::cerr << "Case +++++++++++++ " << appExpr->func << std::endl; |
---|
1134 | std::cerr << "parameters are:" << std::endl; |
---|
1135 | ast::printAll( std::cerr, function->params, 2 ); |
---|
1136 | std::cerr << "arguments are:" << std::endl; |
---|
1137 | ast::printAll( std::cerr, appExpr->args, 2 ); |
---|
1138 | std::cerr << "bindings are:" << std::endl; |
---|
1139 | ast::print( std::cerr, withFunc->env, 2 ); |
---|
1140 | std::cerr << "cost is: " << withFunc->cost << std::endl; |
---|
1141 | std::cerr << "cost of conversion is:" << cvtCost << std::endl; |
---|
1142 | ) |
---|
1143 | } |
---|
1144 | if ( cvtCost != Cost::infinity ) { |
---|
1145 | withFunc->cvtCost = cvtCost; |
---|
1146 | withFunc->cost += cvtCost; |
---|
1147 | auto func = withFunc->expr.strict_as<ast::ApplicationExpr>()->func.as<ast::VariableExpr>(); |
---|
1148 | if (func && func->var->linkage == ast::Linkage::Intrinsic) { |
---|
1149 | if (withFunc->cost < intrinsicCost) { |
---|
1150 | intrinsicResult.clear(); |
---|
1151 | intrinsicCost = withFunc->cost; |
---|
1152 | } |
---|
1153 | if (withFunc->cost == intrinsicCost) { |
---|
1154 | intrinsicResult.emplace_back(std::move(withFunc)); |
---|
1155 | } |
---|
1156 | } else { |
---|
1157 | candidates.emplace_back( std::move( withFunc ) ); |
---|
1158 | } |
---|
1159 | } |
---|
1160 | } |
---|
1161 | spliceBegin( candidates, intrinsicResult ); |
---|
1162 | found = std::move( candidates ); |
---|
1163 | |
---|
1164 | // use a new list so that candidates are not examined by addAnonConversions twice |
---|
1165 | // CandidateList winners = findMinCost( found ); |
---|
1166 | // promoteCvtCost( winners ); |
---|
1167 | |
---|
1168 | // function may return a struct/union value, in which case we need to add candidates |
---|
1169 | // for implicit conversions to each of the anonymous members, which must happen after |
---|
1170 | // `findMinCost`, since anon conversions are never the cheapest |
---|
1171 | for ( const CandidateRef & c : found ) { |
---|
1172 | addAnonConversions( c ); |
---|
1173 | } |
---|
1174 | // would this be too slow when we don't check cost anymore? |
---|
1175 | spliceBegin( candidates, found ); |
---|
1176 | |
---|
1177 | if ( candidates.empty() && targetType && ! targetType->isVoid() && !selfFinder.strictMode ) { |
---|
1178 | // If resolution is unsuccessful with a target type, try again without, since it |
---|
1179 | // will sometimes succeed when it wouldn't with a target type binding. |
---|
1180 | // For example: |
---|
1181 | // forall( otype T ) T & ?[]( T *, ptrdiff_t ); |
---|
1182 | // const char * x = "hello world"; |
---|
1183 | // unsigned char ch = x[0]; |
---|
1184 | // Fails with simple return type binding (xxx -- check this!) as follows: |
---|
1185 | // * T is bound to unsigned char |
---|
1186 | // * (x: const char *) is unified with unsigned char *, which fails |
---|
1187 | // xxx -- fix this better |
---|
1188 | targetType = nullptr; |
---|
1189 | postvisit( untypedExpr ); |
---|
1190 | } |
---|
1191 | } |
---|
1192 | |
---|
1193 | void Finder::postvisit( const ast::AddressExpr * addressExpr ) { |
---|
1194 | CandidateFinder finder( context, tenv ); |
---|
1195 | finder.find( addressExpr->arg ); |
---|
1196 | |
---|
1197 | if ( finder.candidates.empty() ) return; |
---|
1198 | |
---|
1199 | reason.code = NoMatch; |
---|
1200 | |
---|
1201 | for ( CandidateRef & r : finder.candidates ) { |
---|
1202 | if ( !isLvalue( r->expr ) ) continue; |
---|
1203 | addCandidate( *r, new ast::AddressExpr{ addressExpr->location, r->expr } ); |
---|
1204 | } |
---|
1205 | } |
---|
1206 | |
---|
1207 | void Finder::postvisit( const ast::LabelAddressExpr * labelExpr ) { |
---|
1208 | addCandidate( labelExpr, tenv ); |
---|
1209 | } |
---|
1210 | |
---|
1211 | void Finder::postvisit( const ast::CastExpr * castExpr ) { |
---|
1212 | ast::ptr< ast::Type > toType = castExpr->result; |
---|
1213 | assert( toType ); |
---|
1214 | toType = resolveTypeof( toType, context ); |
---|
1215 | toType = adjustExprType( toType, tenv, symtab ); |
---|
1216 | |
---|
1217 | CandidateFinder finder( context, tenv, toType ); |
---|
1218 | if (toType->isVoid()) { |
---|
1219 | finder.allowVoid = true; |
---|
1220 | } |
---|
1221 | if ( castExpr->kind == ast::CastExpr::Return ) { |
---|
1222 | finder.strictMode = true; |
---|
1223 | finder.find( castExpr->arg, ResolveMode::withAdjustment() ); |
---|
1224 | |
---|
1225 | // return casts are eliminated (merely selecting an overload, no actual operation) |
---|
1226 | candidates = std::move(finder.candidates); |
---|
1227 | return; |
---|
1228 | } |
---|
1229 | else if (toType->isVoid()) { |
---|
1230 | finder.find( castExpr->arg ); // no adjust |
---|
1231 | } |
---|
1232 | else { |
---|
1233 | finder.find( castExpr->arg, ResolveMode::withAdjustment() ); |
---|
1234 | } |
---|
1235 | |
---|
1236 | if ( !finder.candidates.empty() ) reason.code = NoMatch; |
---|
1237 | |
---|
1238 | CandidateList matches; |
---|
1239 | Cost minExprCost = Cost::infinity; |
---|
1240 | Cost minCastCost = Cost::infinity; |
---|
1241 | for ( CandidateRef & cand : finder.candidates ) { |
---|
1242 | ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have; |
---|
1243 | ast::OpenVarSet open( cand->open ); |
---|
1244 | |
---|
1245 | cand->env.extractOpenVars( open ); |
---|
1246 | |
---|
1247 | // It is possible that a cast can throw away some values in a multiply-valued |
---|
1248 | // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of the |
---|
1249 | // subexpression results that are cast directly. The candidate is invalid if it |
---|
1250 | // has fewer results than there are types to cast to. |
---|
1251 | int discardedValues = cand->expr->result->size() - toType->size(); |
---|
1252 | if ( discardedValues < 0 ) continue; |
---|
1253 | |
---|
1254 | // unification run for side-effects |
---|
1255 | unify( toType, cand->expr->result, cand->env, need, have, open ); |
---|
1256 | Cost thisCost = |
---|
1257 | (castExpr->isGenerated == ast::GeneratedFlag::GeneratedCast) |
---|
1258 | ? conversionCost( cand->expr->result, toType, cand->expr->get_lvalue(), symtab, cand->env ) |
---|
1259 | : castCost( cand->expr->result, toType, cand->expr->get_lvalue(), symtab, cand->env ); |
---|
1260 | |
---|
1261 | // Redefine enum cast |
---|
1262 | auto argAsEnum = cand->expr->result.as<ast::EnumInstType>(); |
---|
1263 | auto toAsEnum = toType.as<ast::EnumInstType>(); |
---|
1264 | if ( argAsEnum && toAsEnum && argAsEnum->name != toAsEnum->name ) { |
---|
1265 | CandidateFinder subFinder(context, tenv); |
---|
1266 | ast::ptr<ast::Expr> offsetExpr = subFinder.makeEnumOffsetCast(argAsEnum, toAsEnum, cand->expr, thisCost); |
---|
1267 | cand->expr = offsetExpr; |
---|
1268 | } |
---|
1269 | |
---|
1270 | PRINT( |
---|
1271 | std::cerr << "working on cast with result: " << toType << std::endl; |
---|
1272 | std::cerr << "and expr type: " << cand->expr->result << std::endl; |
---|
1273 | std::cerr << "env: " << cand->env << std::endl; |
---|
1274 | ) |
---|
1275 | if ( thisCost != Cost::infinity ) { |
---|
1276 | PRINT( |
---|
1277 | std::cerr << "has finite cost." << std::endl; |
---|
1278 | ) |
---|
1279 | // count one safe conversion for each value that is thrown away |
---|
1280 | thisCost.incSafe( discardedValues ); |
---|
1281 | // select first on argument cost, then conversion cost |
---|
1282 | if ( cand->cost < minExprCost || ( cand->cost == minExprCost && thisCost < minCastCost ) ) { |
---|
1283 | minExprCost = cand->cost; |
---|
1284 | minCastCost = thisCost; |
---|
1285 | matches.clear(); |
---|
1286 | } |
---|
1287 | // ambigious case, still output candidates to print in error message |
---|
1288 | if ( cand->cost == minExprCost && thisCost == minCastCost ) { |
---|
1289 | CandidateRef newCand = std::make_shared<Candidate>( |
---|
1290 | restructureCast( cand->expr, toType, castExpr->isGenerated ), |
---|
1291 | copy( cand->env ), std::move( open ), std::move( need ), cand->cost + thisCost); |
---|
1292 | // currently assertions are always resolved immediately so this should have no effect. |
---|
1293 | // if this somehow changes in the future (e.g. delayed by indeterminate return type) |
---|
1294 | // we may need to revisit the logic. |
---|
1295 | inferParameters( newCand, matches ); |
---|
1296 | } |
---|
1297 | // else skip, better alternatives found |
---|
1298 | |
---|
1299 | } |
---|
1300 | } |
---|
1301 | candidates = std::move(matches); |
---|
1302 | //CandidateList minArgCost = findMinCost( matches ); |
---|
1303 | //promoteCvtCost( minArgCost ); |
---|
1304 | //candidates = findMinCost( minArgCost ); |
---|
1305 | } |
---|
1306 | |
---|
1307 | void Finder::postvisit( const ast::VirtualCastExpr * castExpr ) { |
---|
1308 | assertf( castExpr->result, "Implicit virtual cast targets not yet supported." ); |
---|
1309 | CandidateFinder finder( context, tenv ); |
---|
1310 | // don't prune here, all alternatives guaranteed to have same type |
---|
1311 | finder.find( castExpr->arg, ResolveMode::withoutPrune() ); |
---|
1312 | for ( CandidateRef & r : finder.candidates ) { |
---|
1313 | addCandidate( |
---|
1314 | *r, |
---|
1315 | new ast::VirtualCastExpr{ castExpr->location, r->expr, castExpr->result } ); |
---|
1316 | } |
---|
1317 | } |
---|
1318 | |
---|
1319 | void Finder::postvisit( const ast::KeywordCastExpr * castExpr ) { |
---|
1320 | const auto & loc = castExpr->location; |
---|
1321 | assertf( castExpr->result, "Cast target should have been set in Validate." ); |
---|
1322 | auto ref = castExpr->result.strict_as<ast::ReferenceType>(); |
---|
1323 | auto inst = ref->base.strict_as<ast::StructInstType>(); |
---|
1324 | auto target = inst->base.get(); |
---|
1325 | |
---|
1326 | CandidateFinder finder( context, tenv ); |
---|
1327 | |
---|
1328 | auto pick_alternatives = [target, this](CandidateList & found, bool expect_ref) { |
---|
1329 | for (auto & cand : found) { |
---|
1330 | const ast::Type * expr = cand->expr->result.get(); |
---|
1331 | if (expect_ref) { |
---|
1332 | auto res = dynamic_cast<const ast::ReferenceType*>(expr); |
---|
1333 | if (!res) { continue; } |
---|
1334 | expr = res->base.get(); |
---|
1335 | } |
---|
1336 | |
---|
1337 | if (auto insttype = dynamic_cast<const ast::TypeInstType*>(expr)) { |
---|
1338 | auto td = cand->env.lookup(*insttype); |
---|
1339 | if (!td) { continue; } |
---|
1340 | expr = td->bound.get(); |
---|
1341 | } |
---|
1342 | |
---|
1343 | if (auto base = dynamic_cast<const ast::StructInstType*>(expr)) { |
---|
1344 | if (base->base == target) { |
---|
1345 | candidates.push_back( std::move(cand) ); |
---|
1346 | reason.code = NoReason; |
---|
1347 | } |
---|
1348 | } |
---|
1349 | } |
---|
1350 | }; |
---|
1351 | |
---|
1352 | try { |
---|
1353 | // Attempt 1 : turn (thread&)X into (thread$&)X.__thrd |
---|
1354 | // Clone is purely for memory management |
---|
1355 | std::unique_ptr<const ast::Expr> tech1 { new ast::UntypedMemberExpr(loc, new ast::NameExpr(loc, castExpr->concrete_target.field), castExpr->arg) }; |
---|
1356 | |
---|
1357 | // don't prune here, since it's guaranteed all alternatives will have the same type |
---|
1358 | finder.find( tech1.get(), ResolveMode::withoutPrune() ); |
---|
1359 | pick_alternatives(finder.candidates, false); |
---|
1360 | |
---|
1361 | return; |
---|
1362 | } catch(SemanticErrorException & ) {} |
---|
1363 | |
---|
1364 | // Fallback : turn (thread&)X into (thread$&)get_thread(X) |
---|
1365 | 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 })) }; |
---|
1366 | // don't prune here, since it's guaranteed all alternatives will have the same type |
---|
1367 | finder.find( fallback.get(), ResolveMode::withoutPrune() ); |
---|
1368 | |
---|
1369 | pick_alternatives(finder.candidates, true); |
---|
1370 | |
---|
1371 | // Whatever happens here, we have no more fallbacks |
---|
1372 | } |
---|
1373 | |
---|
1374 | void Finder::postvisit( const ast::UntypedMemberExpr * memberExpr ) { |
---|
1375 | CandidateFinder aggFinder( context, tenv ); |
---|
1376 | aggFinder.find( memberExpr->aggregate, ResolveMode::withAdjustment() ); |
---|
1377 | for ( CandidateRef & agg : aggFinder.candidates ) { |
---|
1378 | // it's okay for the aggregate expression to have reference type -- cast it to the |
---|
1379 | // base type to treat the aggregate as the referenced value |
---|
1380 | Cost addedCost = Cost::zero; |
---|
1381 | agg->expr = referenceToRvalueConversion( agg->expr, addedCost ); |
---|
1382 | |
---|
1383 | // find member of the given type |
---|
1384 | if ( auto structInst = agg->expr->result.as< ast::StructInstType >() ) { |
---|
1385 | addAggMembers( |
---|
1386 | structInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) ); |
---|
1387 | } else if ( auto unionInst = agg->expr->result.as< ast::UnionInstType >() ) { |
---|
1388 | addAggMembers( |
---|
1389 | unionInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) ); |
---|
1390 | } else if ( auto tupleType = agg->expr->result.as< ast::TupleType >() ) { |
---|
1391 | addTupleMembers( tupleType, agg->expr, *agg, addedCost, memberExpr->member ); |
---|
1392 | } |
---|
1393 | } |
---|
1394 | } |
---|
1395 | |
---|
1396 | void Finder::postvisit( const ast::MemberExpr * memberExpr ) { |
---|
1397 | addCandidate( memberExpr, tenv ); |
---|
1398 | } |
---|
1399 | |
---|
1400 | void Finder::postvisit( const ast::NameExpr * nameExpr ) { |
---|
1401 | std::vector< ast::SymbolTable::IdData > declList; |
---|
1402 | if (!selfFinder.otypeKeys.empty()) { |
---|
1403 | auto kind = ast::SymbolTable::getSpecialFunctionKind(nameExpr->name); |
---|
1404 | assertf(kind != ast::SymbolTable::SpecialFunctionKind::NUMBER_OF_KINDS, "special lookup with non-special target: %s", nameExpr->name.c_str()); |
---|
1405 | |
---|
1406 | for (auto & otypeKey: selfFinder.otypeKeys) { |
---|
1407 | auto result = symtab.specialLookupId(kind, otypeKey); |
---|
1408 | declList.insert(declList.end(), std::make_move_iterator(result.begin()), std::make_move_iterator(result.end())); |
---|
1409 | } |
---|
1410 | } else { |
---|
1411 | declList = symtab.lookupIdIgnoreHidden( nameExpr->name ); |
---|
1412 | } |
---|
1413 | PRINT( std::cerr << "nameExpr is " << nameExpr->name << std::endl; ) |
---|
1414 | |
---|
1415 | if ( declList.empty() ) return; |
---|
1416 | |
---|
1417 | reason.code = NoMatch; |
---|
1418 | |
---|
1419 | for ( auto & data : declList ) { |
---|
1420 | Cost cost = Cost::zero; |
---|
1421 | ast::Expr * newExpr = data.combine( nameExpr->location, cost ); |
---|
1422 | |
---|
1423 | CandidateRef newCand = std::make_shared<Candidate>( |
---|
1424 | newExpr, copy( tenv ), ast::OpenVarSet{}, ast::AssertionSet{}, Cost::zero, |
---|
1425 | cost ); |
---|
1426 | if (newCand->expr->env) { |
---|
1427 | newCand->env.add(*newCand->expr->env); |
---|
1428 | auto mutExpr = newCand->expr.get_and_mutate(); |
---|
1429 | mutExpr->env = nullptr; |
---|
1430 | newCand->expr = mutExpr; |
---|
1431 | } |
---|
1432 | |
---|
1433 | PRINT( |
---|
1434 | std::cerr << "decl is "; |
---|
1435 | ast::print( std::cerr, data.id ); |
---|
1436 | std::cerr << std::endl; |
---|
1437 | std::cerr << "newExpr is "; |
---|
1438 | ast::print( std::cerr, newExpr ); |
---|
1439 | std::cerr << std::endl; |
---|
1440 | ) |
---|
1441 | newCand->expr = ast::mutate_field( |
---|
1442 | newCand->expr.get(), &ast::Expr::result, |
---|
1443 | renameTyVars( newCand->expr->result ) ); |
---|
1444 | // add anonymous member interpretations whenever an aggregate value type is seen |
---|
1445 | // as a name expression |
---|
1446 | addAnonConversions( newCand ); |
---|
1447 | candidates.emplace_back( std::move( newCand ) ); |
---|
1448 | } |
---|
1449 | } |
---|
1450 | |
---|
1451 | void Finder::postvisit(const ast::VariableExpr *variableExpr) { |
---|
1452 | // not sufficient to just pass `variableExpr` here, type might have changed |
---|
1453 | |
---|
1454 | auto cand = new Candidate(variableExpr, tenv); |
---|
1455 | candidates.emplace_back(cand); |
---|
1456 | } |
---|
1457 | |
---|
1458 | void Finder::postvisit( const ast::ConstantExpr * constantExpr ) { |
---|
1459 | addCandidate( constantExpr, tenv ); |
---|
1460 | } |
---|
1461 | |
---|
1462 | void Finder::postvisit( const ast::SizeofExpr * sizeofExpr ) { |
---|
1463 | if ( sizeofExpr->type ) { |
---|
1464 | addCandidate( |
---|
1465 | new ast::SizeofExpr{ |
---|
1466 | sizeofExpr->location, resolveTypeof( sizeofExpr->type, context ) }, |
---|
1467 | tenv ); |
---|
1468 | } else { |
---|
1469 | // find all candidates for the argument to sizeof |
---|
1470 | CandidateFinder finder( context, tenv ); |
---|
1471 | finder.find( sizeofExpr->expr ); |
---|
1472 | // find the lowest-cost candidate, otherwise ambiguous |
---|
1473 | CandidateList winners = findMinCost( finder.candidates ); |
---|
1474 | if ( winners.size() != 1 ) { |
---|
1475 | SemanticError( |
---|
1476 | sizeofExpr->expr.get(), "Ambiguous expression in sizeof operand: " ); |
---|
1477 | } |
---|
1478 | // return the lowest-cost candidate |
---|
1479 | CandidateRef & choice = winners.front(); |
---|
1480 | choice->expr = referenceToRvalueConversion( choice->expr, choice->cost ); |
---|
1481 | choice->cost = Cost::zero; |
---|
1482 | addCandidate( *choice, new ast::SizeofExpr{ sizeofExpr->location, choice->expr } ); |
---|
1483 | } |
---|
1484 | } |
---|
1485 | |
---|
1486 | void Finder::postvisit( const ast::CountExpr * countExpr ) { |
---|
1487 | const ast::UntypedExpr * untyped = nullptr; |
---|
1488 | if ( countExpr->type ) { |
---|
1489 | auto enumInst = countExpr->type.as<ast::EnumInstType>(); |
---|
1490 | if ( enumInst ) { |
---|
1491 | addCandidate( ast::ConstantExpr::from_ulong(countExpr->location, enumInst->base->members.size()), tenv ); |
---|
1492 | return; |
---|
1493 | } |
---|
1494 | auto untypedFirst = ast::UntypedExpr::createCall( countExpr->location, "lowerBound", {} ); |
---|
1495 | auto castFirst = new ast::CastExpr( countExpr->location, untypedFirst , countExpr->type ); |
---|
1496 | untyped = ast::UntypedExpr::createCall( |
---|
1497 | countExpr->location, "Countof", { castFirst } |
---|
1498 | ); |
---|
1499 | } |
---|
1500 | if (!untyped) untyped = ast::UntypedExpr::createCall( |
---|
1501 | countExpr->location, "Countof", { countExpr->expr } |
---|
1502 | ); |
---|
1503 | CandidateFinder finder( context, tenv ); |
---|
1504 | finder.find( untyped ); |
---|
1505 | CandidateList winners = findMinCost( finder.candidates ); |
---|
1506 | if ( winners.size() == 0 ) { |
---|
1507 | SemanticError( countExpr->expr, "Countof is not implemented for operand: " ); |
---|
1508 | } |
---|
1509 | if ( winners.size() != 1 ) { |
---|
1510 | SemanticError( countExpr->expr, "Ambiguous expression in countof operand: " ); |
---|
1511 | } |
---|
1512 | CandidateRef & choice = winners.front(); |
---|
1513 | choice->expr = referenceToRvalueConversion( choice->expr, choice->cost ); |
---|
1514 | addCandidate( *choice, choice->expr ); |
---|
1515 | } |
---|
1516 | |
---|
1517 | void Finder::postvisit( const ast::AlignofExpr * alignofExpr ) { |
---|
1518 | if ( alignofExpr->type ) { |
---|
1519 | addCandidate( |
---|
1520 | new ast::AlignofExpr{ |
---|
1521 | alignofExpr->location, resolveTypeof( alignofExpr->type, context ) }, |
---|
1522 | tenv ); |
---|
1523 | } else { |
---|
1524 | // find all candidates for the argument to alignof |
---|
1525 | CandidateFinder finder( context, tenv ); |
---|
1526 | finder.find( alignofExpr->expr ); |
---|
1527 | // find the lowest-cost candidate, otherwise ambiguous |
---|
1528 | CandidateList winners = findMinCost( finder.candidates ); |
---|
1529 | if ( winners.size() != 1 ) { |
---|
1530 | SemanticError( |
---|
1531 | alignofExpr->expr.get(), "Ambiguous expression in alignof operand: " ); |
---|
1532 | } |
---|
1533 | // return the lowest-cost candidate |
---|
1534 | CandidateRef & choice = winners.front(); |
---|
1535 | choice->expr = referenceToRvalueConversion( choice->expr, choice->cost ); |
---|
1536 | choice->cost = Cost::zero; |
---|
1537 | addCandidate( |
---|
1538 | *choice, new ast::AlignofExpr{ alignofExpr->location, choice->expr } ); |
---|
1539 | } |
---|
1540 | } |
---|
1541 | |
---|
1542 | void Finder::postvisit( const ast::UntypedOffsetofExpr * offsetofExpr ) { |
---|
1543 | const ast::BaseInstType * aggInst; |
---|
1544 | if (( aggInst = offsetofExpr->type.as< ast::StructInstType >() )) ; |
---|
1545 | else if (( aggInst = offsetofExpr->type.as< ast::UnionInstType >() )) ; |
---|
1546 | else return; |
---|
1547 | |
---|
1548 | for ( const ast::Decl * member : aggInst->lookup( offsetofExpr->member ) ) { |
---|
1549 | auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( member ); |
---|
1550 | addCandidate( |
---|
1551 | new ast::OffsetofExpr{ offsetofExpr->location, aggInst, dwt }, tenv ); |
---|
1552 | } |
---|
1553 | } |
---|
1554 | |
---|
1555 | void Finder::postvisit( const ast::OffsetofExpr * offsetofExpr ) { |
---|
1556 | addCandidate( offsetofExpr, tenv ); |
---|
1557 | } |
---|
1558 | |
---|
1559 | void Finder::postvisit( const ast::OffsetPackExpr * offsetPackExpr ) { |
---|
1560 | addCandidate( offsetPackExpr, tenv ); |
---|
1561 | } |
---|
1562 | |
---|
1563 | void Finder::postvisit( const ast::LogicalExpr * logicalExpr ) { |
---|
1564 | CandidateFinder finder1( context, tenv ); |
---|
1565 | ast::ptr<ast::Expr> arg1 = createCondExpr( logicalExpr->arg1 ); |
---|
1566 | finder1.find( arg1, ResolveMode::withAdjustment() ); |
---|
1567 | if ( finder1.candidates.empty() ) return; |
---|
1568 | |
---|
1569 | CandidateFinder finder2( context, tenv ); |
---|
1570 | ast::ptr<ast::Expr> arg2 = createCondExpr( logicalExpr->arg2 ); |
---|
1571 | finder2.find( arg2, ResolveMode::withAdjustment() ); |
---|
1572 | if ( finder2.candidates.empty() ) return; |
---|
1573 | |
---|
1574 | reason.code = NoMatch; |
---|
1575 | |
---|
1576 | for ( const CandidateRef & r1 : finder1.candidates ) { |
---|
1577 | for ( const CandidateRef & r2 : finder2.candidates ) { |
---|
1578 | ast::TypeEnvironment env{ r1->env }; |
---|
1579 | env.simpleCombine( r2->env ); |
---|
1580 | ast::OpenVarSet open{ r1->open }; |
---|
1581 | mergeOpenVars( open, r2->open ); |
---|
1582 | ast::AssertionSet need; |
---|
1583 | mergeAssertionSet( need, r1->need ); |
---|
1584 | mergeAssertionSet( need, r2->need ); |
---|
1585 | |
---|
1586 | addCandidate( |
---|
1587 | new ast::LogicalExpr{ |
---|
1588 | logicalExpr->location, r1->expr, r2->expr, logicalExpr->isAnd }, |
---|
1589 | std::move( env ), std::move( open ), std::move( need ), r1->cost + r2->cost ); |
---|
1590 | } |
---|
1591 | } |
---|
1592 | } |
---|
1593 | |
---|
1594 | void Finder::postvisit( const ast::ConditionalExpr * conditionalExpr ) { |
---|
1595 | // candidates for condition |
---|
1596 | ast::ptr<ast::Expr> arg1 = createCondExpr( conditionalExpr->arg1 ); |
---|
1597 | CandidateFinder finder1( context, tenv ); |
---|
1598 | finder1.find( arg1, ResolveMode::withAdjustment() ); |
---|
1599 | if ( finder1.candidates.empty() ) return; |
---|
1600 | |
---|
1601 | // candidates for true result |
---|
1602 | // FIX ME: resolves and runs arg1 twice when arg2 is missing. |
---|
1603 | ast::Expr const * arg2 = conditionalExpr->arg2; |
---|
1604 | arg2 = arg2 ? arg2 : conditionalExpr->arg1.get(); |
---|
1605 | CandidateFinder finder2( context, tenv ); |
---|
1606 | finder2.allowVoid = true; |
---|
1607 | finder2.find( arg2, ResolveMode::withAdjustment() ); |
---|
1608 | if ( finder2.candidates.empty() ) return; |
---|
1609 | |
---|
1610 | // candidates for false result |
---|
1611 | CandidateFinder finder3( context, tenv ); |
---|
1612 | finder3.allowVoid = true; |
---|
1613 | finder3.find( conditionalExpr->arg3, ResolveMode::withAdjustment() ); |
---|
1614 | if ( finder3.candidates.empty() ) return; |
---|
1615 | |
---|
1616 | reason.code = NoMatch; |
---|
1617 | |
---|
1618 | for ( const CandidateRef & r1 : finder1.candidates ) { |
---|
1619 | for ( const CandidateRef & r2 : finder2.candidates ) { |
---|
1620 | for ( const CandidateRef & r3 : finder3.candidates ) { |
---|
1621 | ast::TypeEnvironment env{ r1->env }; |
---|
1622 | env.simpleCombine( r2->env ); |
---|
1623 | env.simpleCombine( r3->env ); |
---|
1624 | ast::OpenVarSet open{ r1->open }; |
---|
1625 | mergeOpenVars( open, r2->open ); |
---|
1626 | mergeOpenVars( open, r3->open ); |
---|
1627 | ast::AssertionSet need; |
---|
1628 | mergeAssertionSet( need, r1->need ); |
---|
1629 | mergeAssertionSet( need, r2->need ); |
---|
1630 | mergeAssertionSet( need, r3->need ); |
---|
1631 | ast::AssertionSet have; |
---|
1632 | |
---|
1633 | // unify true and false results, then infer parameters to produce new |
---|
1634 | // candidates |
---|
1635 | ast::ptr< ast::Type > common; |
---|
1636 | if ( |
---|
1637 | unify( |
---|
1638 | r2->expr->result, r3->expr->result, env, need, have, open, |
---|
1639 | common ) |
---|
1640 | ) { |
---|
1641 | // generate typed expression |
---|
1642 | ast::ConditionalExpr * newExpr = new ast::ConditionalExpr{ |
---|
1643 | conditionalExpr->location, r1->expr, r2->expr, r3->expr }; |
---|
1644 | newExpr->result = common ? common : r2->expr->result; |
---|
1645 | // convert both options to result type |
---|
1646 | Cost cost = r1->cost + r2->cost + r3->cost; |
---|
1647 | newExpr->arg2 = computeExpressionConversionCost( |
---|
1648 | newExpr->arg2, newExpr->result, symtab, env, cost ); |
---|
1649 | newExpr->arg3 = computeExpressionConversionCost( |
---|
1650 | newExpr->arg3, newExpr->result, symtab, env, cost ); |
---|
1651 | // output candidate |
---|
1652 | CandidateRef newCand = std::make_shared<Candidate>( |
---|
1653 | newExpr, std::move( env ), std::move( open ), std::move( need ), cost ); |
---|
1654 | inferParameters( newCand, candidates ); |
---|
1655 | } |
---|
1656 | } |
---|
1657 | } |
---|
1658 | } |
---|
1659 | } |
---|
1660 | |
---|
1661 | void Finder::postvisit( const ast::CommaExpr * commaExpr ) { |
---|
1662 | ast::TypeEnvironment env{ tenv }; |
---|
1663 | ast::ptr< ast::Expr > arg1 = resolveInVoidContext( commaExpr->arg1, context, env ); |
---|
1664 | |
---|
1665 | CandidateFinder finder2( context, env ); |
---|
1666 | finder2.find( commaExpr->arg2, ResolveMode::withAdjustment() ); |
---|
1667 | |
---|
1668 | for ( const CandidateRef & r2 : finder2.candidates ) { |
---|
1669 | addCandidate( *r2, new ast::CommaExpr{ commaExpr->location, arg1, r2->expr } ); |
---|
1670 | } |
---|
1671 | } |
---|
1672 | |
---|
1673 | void Finder::postvisit( const ast::ImplicitCopyCtorExpr * ctorExpr ) { |
---|
1674 | addCandidate( ctorExpr, tenv ); |
---|
1675 | } |
---|
1676 | |
---|
1677 | void Finder::postvisit( const ast::ConstructorExpr * ctorExpr ) { |
---|
1678 | CandidateFinder finder( context, tenv ); |
---|
1679 | finder.allowVoid = true; |
---|
1680 | finder.find( ctorExpr->callExpr, ResolveMode::withoutPrune() ); |
---|
1681 | for ( CandidateRef & r : finder.candidates ) { |
---|
1682 | addCandidate( *r, new ast::ConstructorExpr{ ctorExpr->location, r->expr } ); |
---|
1683 | } |
---|
1684 | } |
---|
1685 | |
---|
1686 | void Finder::postvisit( const ast::RangeExpr * rangeExpr ) { |
---|
1687 | // resolve low and high, accept candidates where low and high types unify |
---|
1688 | CandidateFinder finder1( context, tenv ); |
---|
1689 | finder1.find( rangeExpr->low, ResolveMode::withAdjustment() ); |
---|
1690 | if ( finder1.candidates.empty() ) return; |
---|
1691 | |
---|
1692 | CandidateFinder finder2( context, tenv ); |
---|
1693 | finder2.find( rangeExpr->high, ResolveMode::withAdjustment() ); |
---|
1694 | if ( finder2.candidates.empty() ) return; |
---|
1695 | |
---|
1696 | reason.code = NoMatch; |
---|
1697 | |
---|
1698 | for ( const CandidateRef & r1 : finder1.candidates ) { |
---|
1699 | for ( const CandidateRef & r2 : finder2.candidates ) { |
---|
1700 | ast::TypeEnvironment env{ r1->env }; |
---|
1701 | env.simpleCombine( r2->env ); |
---|
1702 | ast::OpenVarSet open{ r1->open }; |
---|
1703 | mergeOpenVars( open, r2->open ); |
---|
1704 | ast::AssertionSet need; |
---|
1705 | mergeAssertionSet( need, r1->need ); |
---|
1706 | mergeAssertionSet( need, r2->need ); |
---|
1707 | ast::AssertionSet have; |
---|
1708 | |
---|
1709 | ast::ptr< ast::Type > common; |
---|
1710 | if ( |
---|
1711 | unify( |
---|
1712 | r1->expr->result, r2->expr->result, env, need, have, open, |
---|
1713 | common ) |
---|
1714 | ) { |
---|
1715 | // generate new expression |
---|
1716 | ast::RangeExpr * newExpr = |
---|
1717 | new ast::RangeExpr{ rangeExpr->location, r1->expr, r2->expr }; |
---|
1718 | newExpr->result = common ? common : r1->expr->result; |
---|
1719 | // add candidate |
---|
1720 | CandidateRef newCand = std::make_shared<Candidate>( |
---|
1721 | newExpr, std::move( env ), std::move( open ), std::move( need ), |
---|
1722 | r1->cost + r2->cost ); |
---|
1723 | inferParameters( newCand, candidates ); |
---|
1724 | } |
---|
1725 | } |
---|
1726 | } |
---|
1727 | } |
---|
1728 | |
---|
1729 | void Finder::postvisit( const ast::UntypedTupleExpr * tupleExpr ) { |
---|
1730 | std::vector< CandidateFinder > subCandidates = |
---|
1731 | selfFinder.findSubExprs( tupleExpr->exprs ); |
---|
1732 | std::vector< CandidateList > possibilities; |
---|
1733 | combos( subCandidates.begin(), subCandidates.end(), back_inserter( possibilities ) ); |
---|
1734 | |
---|
1735 | for ( const CandidateList & subs : possibilities ) { |
---|
1736 | std::vector< ast::ptr< ast::Expr > > exprs; |
---|
1737 | exprs.reserve( subs.size() ); |
---|
1738 | for ( const CandidateRef & sub : subs ) { exprs.emplace_back( sub->expr ); } |
---|
1739 | |
---|
1740 | ast::TypeEnvironment env; |
---|
1741 | ast::OpenVarSet open; |
---|
1742 | ast::AssertionSet need; |
---|
1743 | for ( const CandidateRef & sub : subs ) { |
---|
1744 | env.simpleCombine( sub->env ); |
---|
1745 | mergeOpenVars( open, sub->open ); |
---|
1746 | mergeAssertionSet( need, sub->need ); |
---|
1747 | } |
---|
1748 | |
---|
1749 | addCandidate( |
---|
1750 | new ast::TupleExpr{ tupleExpr->location, std::move( exprs ) }, |
---|
1751 | std::move( env ), std::move( open ), std::move( need ), sumCost( subs ) ); |
---|
1752 | } |
---|
1753 | } |
---|
1754 | |
---|
1755 | void Finder::postvisit( const ast::TupleExpr * tupleExpr ) { |
---|
1756 | addCandidate( tupleExpr, tenv ); |
---|
1757 | } |
---|
1758 | |
---|
1759 | void Finder::postvisit( const ast::TupleIndexExpr * tupleExpr ) { |
---|
1760 | addCandidate( tupleExpr, tenv ); |
---|
1761 | } |
---|
1762 | |
---|
1763 | void Finder::postvisit( const ast::TupleAssignExpr * tupleExpr ) { |
---|
1764 | addCandidate( tupleExpr, tenv ); |
---|
1765 | } |
---|
1766 | |
---|
1767 | void Finder::postvisit( const ast::UniqueExpr * unqExpr ) { |
---|
1768 | CandidateFinder finder( context, tenv ); |
---|
1769 | finder.find( unqExpr->expr, ResolveMode::withAdjustment() ); |
---|
1770 | for ( CandidateRef & r : finder.candidates ) { |
---|
1771 | // ensure that the the id is passed on so that the expressions are "linked" |
---|
1772 | addCandidate( *r, new ast::UniqueExpr{ unqExpr->location, r->expr, unqExpr->id } ); |
---|
1773 | } |
---|
1774 | } |
---|
1775 | |
---|
1776 | void Finder::postvisit( const ast::StmtExpr * stmtExpr ) { |
---|
1777 | addCandidate( resolveStmtExpr( stmtExpr, context ), tenv ); |
---|
1778 | } |
---|
1779 | |
---|
1780 | void Finder::postvisit( const ast::UntypedInitExpr * initExpr ) { |
---|
1781 | // handle each option like a cast |
---|
1782 | CandidateList matches; |
---|
1783 | PRINT( |
---|
1784 | std::cerr << "untyped init expr: " << initExpr << std::endl; |
---|
1785 | ) |
---|
1786 | // O(n^2) checks of d-types with e-types |
---|
1787 | for ( const ast::InitAlternative & initAlt : initExpr->initAlts ) { |
---|
1788 | // calculate target type |
---|
1789 | const ast::Type * toType = resolveTypeof( initAlt.type, context ); |
---|
1790 | toType = adjustExprType( toType, tenv, symtab ); |
---|
1791 | // The call to find must occur inside this loop, otherwise polymorphic return |
---|
1792 | // types are not bound to the initialization type, since return type variables are |
---|
1793 | // only open for the duration of resolving the UntypedExpr. |
---|
1794 | CandidateFinder finder( context, tenv, toType ); |
---|
1795 | finder.find( initExpr->expr, ResolveMode::withAdjustment() ); |
---|
1796 | |
---|
1797 | Cost minExprCost = Cost::infinity; |
---|
1798 | Cost minCastCost = Cost::infinity; |
---|
1799 | for ( CandidateRef & cand : finder.candidates ) { |
---|
1800 | if (reason.code == NotFound) reason.code = NoMatch; |
---|
1801 | |
---|
1802 | ast::TypeEnvironment env{ cand->env }; |
---|
1803 | ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have; |
---|
1804 | ast::OpenVarSet open{ cand->open }; |
---|
1805 | |
---|
1806 | PRINT( |
---|
1807 | std::cerr << " @ " << toType << " " << initAlt.designation << std::endl; |
---|
1808 | ) |
---|
1809 | |
---|
1810 | // It is possible that a cast can throw away some values in a multiply-valued |
---|
1811 | // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of |
---|
1812 | // the subexpression results that are cast directly. The candidate is invalid |
---|
1813 | // if it has fewer results than there are types to cast to. |
---|
1814 | int discardedValues = cand->expr->result->size() - toType->size(); |
---|
1815 | if ( discardedValues < 0 ) continue; |
---|
1816 | |
---|
1817 | // unification run for side-effects |
---|
1818 | ast::ptr<ast::Type> common; |
---|
1819 | bool canUnify = unify( toType, cand->expr->result, env, need, have, open, common ); |
---|
1820 | (void) canUnify; |
---|
1821 | Cost thisCost = computeConversionCost( cand->expr->result, toType, cand->expr->get_lvalue(), |
---|
1822 | symtab, env ); |
---|
1823 | PRINT( |
---|
1824 | Cost legacyCost = castCost( cand->expr->result, toType, cand->expr->get_lvalue(), |
---|
1825 | symtab, env ); |
---|
1826 | std::cerr << "Considering initialization:"; |
---|
1827 | std::cerr << std::endl << " FROM: " << cand->expr->result << std::endl; |
---|
1828 | std::cerr << std::endl << " TO: " << toType << std::endl; |
---|
1829 | std::cerr << std::endl << " Unification " << (canUnify ? "succeeded" : "failed"); |
---|
1830 | std::cerr << std::endl << " Legacy cost " << legacyCost; |
---|
1831 | std::cerr << std::endl << " New cost " << thisCost; |
---|
1832 | std::cerr << std::endl; |
---|
1833 | ) |
---|
1834 | if ( thisCost != Cost::infinity ) { |
---|
1835 | // count one safe conversion for each value that is thrown away |
---|
1836 | thisCost.incSafe( discardedValues ); |
---|
1837 | if ( cand->cost < minExprCost || ( cand->cost == minExprCost && thisCost < minCastCost ) ) { |
---|
1838 | minExprCost = cand->cost; |
---|
1839 | minCastCost = thisCost; |
---|
1840 | matches.clear(); |
---|
1841 | } |
---|
1842 | CandidateRef newCand = std::make_shared<Candidate>( |
---|
1843 | new ast::InitExpr{ |
---|
1844 | initExpr->location, |
---|
1845 | restructureCast( cand->expr, toType ), |
---|
1846 | initAlt.designation }, |
---|
1847 | std::move(env), std::move( open ), std::move( need ), cand->cost + thisCost ); |
---|
1848 | // currently assertions are always resolved immediately so this should have no effect. |
---|
1849 | // if this somehow changes in the future (e.g. delayed by indeterminate return type) |
---|
1850 | // we may need to revisit the logic. |
---|
1851 | inferParameters( newCand, matches ); |
---|
1852 | } |
---|
1853 | } |
---|
1854 | } |
---|
1855 | |
---|
1856 | // select first on argument cost, then conversion cost |
---|
1857 | // CandidateList minArgCost = findMinCost( matches ); |
---|
1858 | // promoteCvtCost( minArgCost ); |
---|
1859 | // candidates = findMinCost( minArgCost ); |
---|
1860 | candidates = std::move(matches); |
---|
1861 | } |
---|
1862 | |
---|
1863 | void Finder::postvisit( const ast::QualifiedNameExpr * expr ) { |
---|
1864 | std::vector< ast::SymbolTable::IdData > declList = symtab.lookupId( expr->name ); |
---|
1865 | if ( declList.empty() ) return; |
---|
1866 | |
---|
1867 | for ( ast::SymbolTable::IdData & data: declList ) { |
---|
1868 | const ast::Type * t = data.id->get_type()->stripReferences(); |
---|
1869 | if ( const ast::EnumInstType * enumInstType = |
---|
1870 | dynamic_cast<const ast::EnumInstType *>( t ) ) { |
---|
1871 | if ( (enumInstType->base->name == expr->type_name) |
---|
1872 | || (expr->type_decl && enumInstType->base->name == expr->type_decl->name) ) { |
---|
1873 | Cost cost = Cost::zero; |
---|
1874 | ast::Expr * newExpr = data.combine( expr->location, cost ); |
---|
1875 | CandidateRef newCand = |
---|
1876 | std::make_shared<Candidate>( |
---|
1877 | newExpr, copy( tenv ), ast::OpenVarSet{}, |
---|
1878 | ast::AssertionSet{}, Cost::zero, cost |
---|
1879 | ); |
---|
1880 | if (newCand->expr->env) { |
---|
1881 | newCand->env.add(*newCand->expr->env); |
---|
1882 | auto mutExpr = newCand->expr.get_and_mutate(); |
---|
1883 | mutExpr->env = nullptr; |
---|
1884 | newCand->expr = mutExpr; |
---|
1885 | } |
---|
1886 | |
---|
1887 | newCand->expr = ast::mutate_field( |
---|
1888 | newCand->expr.get(), &ast::Expr::result, |
---|
1889 | renameTyVars( newCand->expr->result ) ); |
---|
1890 | addAnonConversions( newCand ); |
---|
1891 | candidates.emplace_back( std::move( newCand ) ); |
---|
1892 | } |
---|
1893 | } |
---|
1894 | } |
---|
1895 | } |
---|
1896 | // size_t Finder::traceId = Stats::Heap::new_stacktrace_id("Finder"); |
---|
1897 | /// Prunes a list of candidates down to those that have the minimum conversion cost for a given |
---|
1898 | /// return type. Skips ambiguous candidates. |
---|
1899 | |
---|
1900 | } // anonymous namespace |
---|
1901 | |
---|
1902 | bool CandidateFinder::pruneCandidates( CandidateList & candidates, CandidateList & out, std::vector<std::string> & errors ) { |
---|
1903 | struct PruneStruct { |
---|
1904 | CandidateRef candidate; |
---|
1905 | bool ambiguous; |
---|
1906 | |
---|
1907 | PruneStruct() = default; |
---|
1908 | PruneStruct( const CandidateRef & c ) : candidate( c ), ambiguous( false ) {} |
---|
1909 | }; |
---|
1910 | |
---|
1911 | // find lowest-cost candidate for each type |
---|
1912 | std::unordered_map< std::string, PruneStruct > selected; |
---|
1913 | // attempt to skip satisfyAssertions on more expensive alternatives if better options have been found |
---|
1914 | std::sort(candidates.begin(), candidates.end(), [](const CandidateRef & x, const CandidateRef & y){return x->cost < y->cost;}); |
---|
1915 | for ( CandidateRef & candidate : candidates ) { |
---|
1916 | std::string mangleName; |
---|
1917 | { |
---|
1918 | ast::ptr< ast::Type > newType = candidate->expr->result; |
---|
1919 | assertf(candidate->expr->result, "Result of expression %p for candidate is null", candidate->expr.get()); |
---|
1920 | candidate->env.apply( newType ); |
---|
1921 | mangleName = Mangle::mangle( newType ); |
---|
1922 | } |
---|
1923 | |
---|
1924 | auto found = selected.find( mangleName ); |
---|
1925 | if (found != selected.end() && found->second.candidate->cost < candidate->cost) { |
---|
1926 | PRINT( |
---|
1927 | std::cerr << "cost " << candidate->cost << " loses to " |
---|
1928 | << found->second.candidate->cost << std::endl; |
---|
1929 | ) |
---|
1930 | continue; |
---|
1931 | } |
---|
1932 | |
---|
1933 | // xxx - when do satisfyAssertions produce more than 1 result? |
---|
1934 | // this should only happen when initial result type contains |
---|
1935 | // unbound type parameters, then it should never be pruned by |
---|
1936 | // the previous step, since renameTyVars guarantees the mangled name |
---|
1937 | // is unique. |
---|
1938 | CandidateList satisfied; |
---|
1939 | bool needRecomputeKey = false; |
---|
1940 | if (candidate->need.empty()) { |
---|
1941 | satisfied.emplace_back(candidate); |
---|
1942 | } |
---|
1943 | else { |
---|
1944 | satisfyAssertions(candidate, context.symtab, satisfied, errors); |
---|
1945 | needRecomputeKey = true; |
---|
1946 | } |
---|
1947 | |
---|
1948 | for (auto & newCand : satisfied) { |
---|
1949 | // recomputes type key, if satisfyAssertions changed it |
---|
1950 | if (needRecomputeKey) |
---|
1951 | { |
---|
1952 | ast::ptr< ast::Type > newType = newCand->expr->result; |
---|
1953 | assertf(newCand->expr->result, "Result of expression %p for candidate is null", newCand->expr.get()); |
---|
1954 | newCand->env.apply( newType ); |
---|
1955 | mangleName = Mangle::mangle( newType ); |
---|
1956 | } |
---|
1957 | auto found = selected.find( mangleName ); |
---|
1958 | if ( found != selected.end() ) { |
---|
1959 | // tiebreaking by picking the lower cost on CURRENT expression |
---|
1960 | // NOTE: this behavior is different from C semantics. |
---|
1961 | // Specific remediations are performed for C operators at postvisit(UntypedExpr). |
---|
1962 | // Further investigations may take place. |
---|
1963 | if ( newCand->cost < found->second.candidate->cost |
---|
1964 | || (newCand->cost == found->second.candidate->cost && newCand->cvtCost < found->second.candidate->cvtCost) ) { |
---|
1965 | PRINT( |
---|
1966 | std::cerr << "cost " << newCand->cost << " beats " |
---|
1967 | << found->second.candidate->cost << std::endl; |
---|
1968 | ) |
---|
1969 | |
---|
1970 | found->second = PruneStruct{ newCand }; |
---|
1971 | } else if ( newCand->cost == found->second.candidate->cost && newCand->cvtCost == found->second.candidate->cvtCost ) { |
---|
1972 | // if one of the candidates contains a deleted identifier, can pick the other, |
---|
1973 | // since deleted expressions should not be ambiguous if there is another option |
---|
1974 | // that is at least as good |
---|
1975 | if ( findDeletedExpr( newCand->expr ) ) { |
---|
1976 | // do nothing |
---|
1977 | PRINT( std::cerr << "candidate is deleted" << std::endl; ) |
---|
1978 | } else if ( findDeletedExpr( found->second.candidate->expr ) ) { |
---|
1979 | PRINT( std::cerr << "current is deleted" << std::endl; ) |
---|
1980 | found->second = PruneStruct{ newCand }; |
---|
1981 | } else { |
---|
1982 | PRINT( std::cerr << "marking ambiguous" << std::endl; ) |
---|
1983 | found->second.ambiguous = true; |
---|
1984 | } |
---|
1985 | } else { |
---|
1986 | // xxx - can satisfyAssertions increase the cost? |
---|
1987 | PRINT( |
---|
1988 | std::cerr << "cost " << newCand->cost << " loses to " |
---|
1989 | << found->second.candidate->cost << std::endl; |
---|
1990 | ) |
---|
1991 | } |
---|
1992 | } else { |
---|
1993 | selected.emplace_hint( found, mangleName, newCand ); |
---|
1994 | } |
---|
1995 | } |
---|
1996 | } |
---|
1997 | |
---|
1998 | // report unambiguous min-cost candidates |
---|
1999 | // CandidateList out; |
---|
2000 | for ( auto & target : selected ) { |
---|
2001 | if ( target.second.ambiguous ) continue; |
---|
2002 | |
---|
2003 | CandidateRef cand = target.second.candidate; |
---|
2004 | |
---|
2005 | ast::ptr< ast::Type > newResult = cand->expr->result; |
---|
2006 | cand->env.applyFree( newResult ); |
---|
2007 | cand->expr = ast::mutate_field( |
---|
2008 | cand->expr.get(), &ast::Expr::result, std::move( newResult ) ); |
---|
2009 | |
---|
2010 | out.emplace_back( cand ); |
---|
2011 | } |
---|
2012 | // if everything is lost in satisfyAssertions, report the error |
---|
2013 | return !selected.empty(); |
---|
2014 | } |
---|
2015 | |
---|
2016 | void CandidateFinder::find( const ast::Expr * expr, ResolveMode mode ) { |
---|
2017 | // Find alternatives for expression |
---|
2018 | ast::Pass<Finder> finder{ *this }; |
---|
2019 | expr->accept( finder ); |
---|
2020 | |
---|
2021 | if ( mode.failFast && candidates.empty() ) { |
---|
2022 | switch(finder.core.reason.code) { |
---|
2023 | case Finder::NotFound: |
---|
2024 | { SemanticError( expr, "No alternatives for expression " ); break; } |
---|
2025 | case Finder::NoMatch: |
---|
2026 | { SemanticError( expr, "Invalid application of existing declaration(s) in expression " ); break; } |
---|
2027 | case Finder::ArgsToFew: |
---|
2028 | case Finder::ArgsToMany: |
---|
2029 | case Finder::RetsToFew: |
---|
2030 | case Finder::RetsToMany: |
---|
2031 | case Finder::NoReason: |
---|
2032 | default: |
---|
2033 | { SemanticError( expr->location, "No reasonable alternatives for expression : reasons unkown" ); } |
---|
2034 | } |
---|
2035 | } |
---|
2036 | |
---|
2037 | /* |
---|
2038 | if ( mode.satisfyAssns || mode.prune ) { |
---|
2039 | // trim candidates to just those where the assertions are satisfiable |
---|
2040 | // - necessary pre-requisite to pruning |
---|
2041 | CandidateList satisfied; |
---|
2042 | std::vector< std::string > errors; |
---|
2043 | for ( CandidateRef & candidate : candidates ) { |
---|
2044 | satisfyAssertions( candidate, localSyms, satisfied, errors ); |
---|
2045 | } |
---|
2046 | |
---|
2047 | // fail early if none such |
---|
2048 | if ( mode.failFast && satisfied.empty() ) { |
---|
2049 | std::ostringstream stream; |
---|
2050 | stream << "No alternatives with satisfiable assertions for " << expr << "\n"; |
---|
2051 | for ( const auto& err : errors ) { |
---|
2052 | stream << err; |
---|
2053 | } |
---|
2054 | SemanticError( expr->location, stream.str() ); |
---|
2055 | } |
---|
2056 | |
---|
2057 | // reset candidates |
---|
2058 | candidates = move( satisfied ); |
---|
2059 | } |
---|
2060 | */ |
---|
2061 | |
---|
2062 | // optimization: don't prune for NameExpr since it never has cost |
---|
2063 | if ( mode.prune && !dynamic_cast<const ast::NameExpr *>(expr) ) { |
---|
2064 | // trim candidates to single best one |
---|
2065 | PRINT( |
---|
2066 | std::cerr << "alternatives before prune:" << std::endl; |
---|
2067 | print( std::cerr, candidates ); |
---|
2068 | ) |
---|
2069 | |
---|
2070 | CandidateList pruned; |
---|
2071 | std::vector<std::string> errors; |
---|
2072 | bool found = pruneCandidates( candidates, pruned, errors ); |
---|
2073 | |
---|
2074 | if ( mode.failFast && pruned.empty() ) { |
---|
2075 | std::ostringstream stream; |
---|
2076 | if (found) { |
---|
2077 | CandidateList winners = findMinCost( candidates ); |
---|
2078 | stream << "Cannot choose between " << winners.size() << " alternatives for " |
---|
2079 | "expression\n"; |
---|
2080 | ast::print( stream, expr ); |
---|
2081 | stream << " Alternatives are:\n"; |
---|
2082 | print( stream, winners, 1 ); |
---|
2083 | SemanticError( expr->location, stream.str() ); |
---|
2084 | } |
---|
2085 | else { |
---|
2086 | stream << "No alternatives with satisfiable assertions for " << expr << "\n"; |
---|
2087 | for ( const auto& err : errors ) { |
---|
2088 | stream << err; |
---|
2089 | } |
---|
2090 | SemanticError( expr->location, stream.str() ); |
---|
2091 | } |
---|
2092 | } |
---|
2093 | |
---|
2094 | auto oldsize = candidates.size(); |
---|
2095 | candidates = std::move( pruned ); |
---|
2096 | |
---|
2097 | PRINT( |
---|
2098 | std::cerr << "there are " << oldsize << " alternatives before elimination" << std::endl; |
---|
2099 | ) |
---|
2100 | PRINT( |
---|
2101 | std::cerr << "there are " << candidates.size() << " alternatives after elimination" |
---|
2102 | << std::endl; |
---|
2103 | ) |
---|
2104 | } |
---|
2105 | |
---|
2106 | // adjust types after pruning so that types substituted by pruneAlternatives are correctly |
---|
2107 | // adjusted |
---|
2108 | if ( mode.adjust ) { |
---|
2109 | for ( CandidateRef & r : candidates ) { |
---|
2110 | r->expr = ast::mutate_field( |
---|
2111 | r->expr.get(), &ast::Expr::result, |
---|
2112 | adjustExprType( r->expr->result, r->env, context.symtab ) ); |
---|
2113 | } |
---|
2114 | } |
---|
2115 | |
---|
2116 | // Central location to handle gcc extension keyword, etc. for all expressions |
---|
2117 | for ( CandidateRef & r : candidates ) { |
---|
2118 | if ( r->expr->extension != expr->extension ) { |
---|
2119 | r->expr.get_and_mutate()->extension = expr->extension; |
---|
2120 | } |
---|
2121 | } |
---|
2122 | } |
---|
2123 | |
---|
2124 | std::vector< CandidateFinder > CandidateFinder::findSubExprs( |
---|
2125 | const std::vector< ast::ptr< ast::Expr > > & xs |
---|
2126 | ) { |
---|
2127 | std::vector< CandidateFinder > out; |
---|
2128 | |
---|
2129 | for ( const auto & x : xs ) { |
---|
2130 | out.emplace_back( context, env ); |
---|
2131 | out.back().find( x, ResolveMode::withAdjustment() ); |
---|
2132 | |
---|
2133 | PRINT( |
---|
2134 | std::cerr << "findSubExprs" << std::endl; |
---|
2135 | print( std::cerr, out.back().candidates ); |
---|
2136 | ) |
---|
2137 | } |
---|
2138 | |
---|
2139 | return out; |
---|
2140 | } |
---|
2141 | |
---|
2142 | const ast::Expr * referenceToRvalueConversion( const ast::Expr * expr, Cost & cost ) { |
---|
2143 | if ( expr->result.as< ast::ReferenceType >() ) { |
---|
2144 | // cast away reference from expr |
---|
2145 | cost.incReference(); |
---|
2146 | return new ast::CastExpr{ expr, expr->result->stripReferences() }; |
---|
2147 | } |
---|
2148 | |
---|
2149 | return expr; |
---|
2150 | } |
---|
2151 | |
---|
2152 | const ast::Expr * CandidateFinder::makeEnumOffsetCast( const ast::EnumInstType * src, |
---|
2153 | const ast::EnumInstType * dst, |
---|
2154 | const ast::Expr * expr, |
---|
2155 | Cost minCost ) { |
---|
2156 | |
---|
2157 | auto srcDecl = src->base; |
---|
2158 | auto dstDecl = dst->base; |
---|
2159 | |
---|
2160 | if (srcDecl->name == dstDecl->name) return expr; |
---|
2161 | |
---|
2162 | for (auto& dstChild: dstDecl->inlinedDecl) { |
---|
2163 | Cost c = castCost(src, dstChild, false, context.symtab, env); |
---|
2164 | ast::CastExpr * castToDst; |
---|
2165 | if (c<minCost) { |
---|
2166 | unsigned offset = dstDecl->calChildOffset(dstChild.get()); |
---|
2167 | if (offset > 0) { |
---|
2168 | auto untyped = ast::UntypedExpr::createCall( |
---|
2169 | expr->location, |
---|
2170 | "?+?", |
---|
2171 | { new ast::CastExpr( expr->location, |
---|
2172 | expr, |
---|
2173 | new ast::BasicType(ast::BasicKind::SignedInt), |
---|
2174 | ast::GeneratedFlag::ExplicitCast ), |
---|
2175 | ast::ConstantExpr::from_int(expr->location, offset)} ); |
---|
2176 | CandidateFinder finder(context, env); |
---|
2177 | finder.find( untyped ); |
---|
2178 | CandidateList winners = findMinCost( finder.candidates ); |
---|
2179 | CandidateRef & choice = winners.front(); |
---|
2180 | choice->expr = new ast::CastExpr(expr->location, choice->expr, dstChild, ast::GeneratedFlag::ExplicitCast); |
---|
2181 | castToDst = new ast::CastExpr( |
---|
2182 | makeEnumOffsetCast( src, dstChild, choice->expr, minCost ), |
---|
2183 | dst); |
---|
2184 | } else { |
---|
2185 | castToDst = new ast::CastExpr( expr, dst ); |
---|
2186 | } |
---|
2187 | return castToDst; |
---|
2188 | } |
---|
2189 | } |
---|
2190 | SemanticError(expr, src->base->name + " is not a subtype of " + dst->base->name); |
---|
2191 | return nullptr; |
---|
2192 | } |
---|
2193 | |
---|
2194 | Cost computeConversionCost( |
---|
2195 | const ast::Type * argType, const ast::Type * paramType, bool argIsLvalue, |
---|
2196 | const ast::SymbolTable & symtab, const ast::TypeEnvironment & env |
---|
2197 | ) { |
---|
2198 | PRINT( |
---|
2199 | std::cerr << std::endl << "converting "; |
---|
2200 | ast::print( std::cerr, argType, 2 ); |
---|
2201 | std::cerr << std::endl << " to "; |
---|
2202 | ast::print( std::cerr, paramType, 2 ); |
---|
2203 | std::cerr << std::endl << "environment is: "; |
---|
2204 | ast::print( std::cerr, env, 2 ); |
---|
2205 | std::cerr << std::endl; |
---|
2206 | ) |
---|
2207 | Cost convCost = conversionCost( argType, paramType, argIsLvalue, symtab, env ); |
---|
2208 | PRINT( |
---|
2209 | std::cerr << std::endl << "cost is " << convCost << std::endl; |
---|
2210 | ) |
---|
2211 | if ( convCost == Cost::infinity ) return convCost; |
---|
2212 | convCost.incPoly( polyCost( paramType, symtab, env ) + polyCost( argType, symtab, env ) ); |
---|
2213 | PRINT( |
---|
2214 | std::cerr << "cost with polycost is " << convCost << std::endl; |
---|
2215 | ) |
---|
2216 | return convCost; |
---|
2217 | } |
---|
2218 | |
---|
2219 | const ast::Expr * createCondExpr( const ast::Expr * expr ) { |
---|
2220 | assert( expr ); |
---|
2221 | return new ast::CastExpr( expr->location, |
---|
2222 | ast::UntypedExpr::createCall( expr->location, |
---|
2223 | "?!=?", |
---|
2224 | { |
---|
2225 | expr, |
---|
2226 | new ast::ConstantExpr( expr->location, |
---|
2227 | new ast::ZeroType(), "0", std::make_optional( 0ull ) |
---|
2228 | ), |
---|
2229 | } |
---|
2230 | ), |
---|
2231 | new ast::BasicType( ast::BasicKind::SignedInt ) |
---|
2232 | ); |
---|
2233 | } |
---|
2234 | |
---|
2235 | } // namespace ResolvExpr |
---|
2236 | |
---|
2237 | // Local Variables: // |
---|
2238 | // tab-width: 4 // |
---|
2239 | // mode: c++ // |
---|
2240 | // compile-command: "make install" // |
---|
2241 | // End: // |
---|