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