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