source: src/ResolvExpr/AlternativeFinder.cc @ a5294af

ast-experimental
Last change on this file since a5294af was 5bf3976, checked in by Andrew Beach <ajbeach@…>, 18 months ago

Header Clean-Up: Created new headers for new AST typeops and moved declarations.

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