source: src/ResolvExpr/AlternativeFinder.cc @ 665f432

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 665f432 was 1118b8b, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

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