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