Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/ResolvExpr/AlternativeFinder.cc

    r83882e9 r11094d9  
    1616#include <algorithm>               // for copy
    1717#include <cassert>                 // for strict_dynamic_cast, assert, assertf
    18 #include <cstddef>                 // for size_t
    1918#include <iostream>                // for operator<<, cerr, ostream, endl
    2019#include <iterator>                // for back_insert_iterator, back_inserter
    2120#include <list>                    // for _List_iterator, list, _List_const_...
    2221#include <map>                     // for _Rb_tree_iterator, map, _Rb_tree_c...
    23 #include <memory>                  // for allocator_traits<>::value_type, unique_ptr
     22#include <memory>                  // for allocator_traits<>::value_type
    2423#include <utility>                 // for pair
    2524#include <vector>                  // for vector
     
    5251//#define DEBUG_COST
    5352
    54 using std::move;
    55 
    56 /// copies any copyable type
    57 template<typename T>
    58 T copy(const T& x) { return x; }
    59 
    6053namespace ResolvExpr {
    6154        Expression *resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer, TypeEnvironment &env ) {
     
    186179                expr->accept( *this );
    187180                if ( failFast && alternatives.empty() ) {
    188                         PRINT(
    189                                 std::cerr << "No reasonable alternatives for expression " << expr << std::endl;
    190                         )
    191181                        throw SemanticError( "No reasonable alternatives for expression ", expr );
    192182                }
     
    197187                                printAlts( alternatives, std::cerr );
    198188                        )
    199                         AltList pruned;
    200                         pruneAlternatives( alternatives.begin(), alternatives.end(), back_inserter( pruned ) );
    201                         if ( failFast && pruned.empty() ) {
     189                        AltList::iterator oldBegin = alternatives.begin();
     190                        pruneAlternatives( alternatives.begin(), alternatives.end(), front_inserter( alternatives ) );
     191                        if ( failFast && alternatives.begin() == oldBegin ) {
    202192                                std::ostringstream stream;
    203193                                AltList winners;
     
    209199                                throw SemanticError( stream.str() );
    210200                        }
    211                         alternatives = move(pruned);
     201                        alternatives.erase( oldBegin, alternatives.end() );
    212202                        PRINT(
    213203                                std::cerr << "there are " << oldsize << " alternatives before elimination" << std::endl;
     
    581571        /// State to iteratively build a match of parameter expressions to arguments
    582572        struct ArgPack {
    583                 std::size_t parent;                ///< Index of parent pack
    584                 std::unique_ptr<Expression> expr;  ///< The argument stored here
    585                 Cost cost;                         ///< The cost of this argument
    586                 TypeEnvironment env;               ///< Environment for this pack
    587                 AssertionSet need;                 ///< Assertions outstanding for this pack
    588                 AssertionSet have;                 ///< Assertions found for this pack
    589                 OpenVarSet openVars;               ///< Open variables for this pack
    590                 unsigned nextArg;                  ///< Index of next argument in arguments list
    591                 unsigned tupleStart;               ///< Number of tuples that start at this index
    592                 // TODO fix this somehow
    593                 std::vector<Alternative> expls;    ///< Exploded actuals left over from last match
    594 
    595                 ArgPack()
    596                         : parent(0), expr(), cost(Cost::zero), env(), need(), have(), openVars(), nextArg(0),
    597                           tupleStart(0), expls() {}
     573                AltList actuals;                 ///< Arguments included in this pack
     574                TypeEnvironment env;             ///< Environment for this pack
     575                AssertionSet need;               ///< Assertions outstanding for this pack
     576                AssertionSet have;               ///< Assertions found for this pack
     577                OpenVarSet openVars;             ///< Open variables for this pack
     578                unsigned nextArg;                ///< Index of next argument in arguments list
     579                std::vector<Alternative> expls;  ///< Exploded actuals left over from last match
     580                unsigned nextExpl;               ///< Index of next exploded alternative to use
     581                std::vector<unsigned> tupleEls;  /// Number of elements in current tuple element(s)
    598582
    599583                ArgPack(const TypeEnvironment& env, const AssertionSet& need, const AssertionSet& have,
    600584                                const OpenVarSet& openVars)
    601                         : parent(0), expr(), cost(Cost::zero), env(env), need(need), have(have),
    602                           openVars(openVars), nextArg(0), tupleStart(0), expls() {}
    603 
    604                 ArgPack(std::size_t parent, Expression* expr, TypeEnvironment&& env, AssertionSet&& need,
    605                                 AssertionSet&& have, OpenVarSet&& openVars, unsigned nextArg,
    606                                 unsigned tupleStart = 0, Cost cost = Cost::zero,
    607                                 std::vector<Alternative>&& expls = std::vector<Alternative>{} )
    608                         : parent(parent), expr(expr->clone()), cost(cost), env(move(env)), need(move(need)),
    609                           have(move(have)), openVars(move(openVars)), nextArg(nextArg), tupleStart(tupleStart),
    610                           expls(move(expls)) {}
    611 
    612                 ArgPack(const ArgPack& o, TypeEnvironment&& env, AssertionSet&& need, AssertionSet&& have,
    613                                 OpenVarSet&& openVars, unsigned nextArg, Cost added )
    614                         : parent(o.parent), expr(o.expr ? o.expr->clone() : nullptr), cost(o.cost + added),
    615                           env(move(env)), need(move(need)), have(move(have)), openVars(move(openVars)),
    616                           nextArg(nextArg), tupleStart(o.tupleStart), expls() {}
    617 
    618 
    619                 // ArgPack(const ArgPack& o)
    620                 //      : parent(o.parent), expr(o.expr ? o.expr->clone() : nullptr), env(o.env),
    621                 //        need(o.need), have(o.have), openVars(o.openVars), nextArg(o.nextArg),
    622                 //        tupleStart(o.tupleStart), expls(o.expls) {}
    623 
    624                 // ArgPack(ArgPack&&) = default;
     585                        : actuals(), env(env), need(need), have(have), openVars(openVars), nextArg(0),
     586                          expls(), nextExpl(0), tupleEls() {}
     587
     588                /// Starts a new tuple expression
     589                void beginTuple() {
     590                        if ( ! tupleEls.empty() ) ++tupleEls.back();
     591                        tupleEls.push_back(0);
     592                }
    625593
    626594                /// Ends a tuple expression, consolidating the appropriate actuals
    627                 void endTuple( const std::vector<ArgPack>& packs ) {
    628                         // add all expressions in tuple to list, summing cost
     595                void endTuple() {
     596                        // set up new Tuple alternative
    629597                        std::list<Expression*> exprs;
    630                         const ArgPack* pack = this;
    631                         if ( expr ) { exprs.push_front( expr.release() ); }
    632                         while ( pack->tupleStart == 0 ) {
    633                                 pack = &packs[pack->parent];
    634                                 exprs.push_front( pack->expr->clone() );
    635                                 cost += pack->cost;
    636                         }
    637                         // reset pack to appropriate tuple
    638                         expr.reset( new TupleExpr( exprs ) );
    639                         tupleStart = pack->tupleStart - 1;
    640                         parent = pack->parent;
     598                        Cost cost = Cost::zero;
     599
     600                        // transfer elements into alternative
     601                        for (unsigned i = 0; i < tupleEls.back(); ++i) {
     602                                exprs.push_front( actuals.back().expr );
     603                                actuals.back().expr = nullptr;
     604                                cost += actuals.back().cost;
     605                                actuals.pop_back();
     606                        }
     607                        tupleEls.pop_back();
     608
     609                        // build new alternative
     610                        actuals.emplace_back( new TupleExpr( exprs ), this->env, cost );
     611                }
     612
     613                /// Clones and adds an actual, returns this
     614                ArgPack& withArg( Expression* expr, Cost cost = Cost::zero ) {
     615                        actuals.emplace_back( expr->clone(), this->env, cost );
     616                        if ( ! tupleEls.empty() ) ++tupleEls.back();
     617                        return *this;
    641618                }
    642619        };
     
    644621        /// Instantiates an argument to match a formal, returns false if no results left
    645622        bool instantiateArgument( Type* formalType, Initializer* initializer,
    646                         const std::vector< AlternativeFinder >& args, std::vector<ArgPack>& results,
    647                         std::size_t& genStart, const SymTab::Indexer& indexer, unsigned nTuples = 0 ) {
     623                        const std::vector< AlternativeFinder >& args,
     624                        std::vector<ArgPack>& results, std::vector<ArgPack>& nextResults,
     625                        const SymTab::Indexer& indexer ) {
    648626                if ( TupleType* tupleType = dynamic_cast<TupleType*>( formalType ) ) {
    649627                        // formalType is a TupleType - group actuals into a TupleExpr
    650                         ++nTuples;
     628                        for ( ArgPack& result : results ) { result.beginTuple(); }
    651629                        for ( Type* type : *tupleType ) {
    652630                                // xxx - dropping initializer changes behaviour from previous, but seems correct
    653                                 if ( ! instantiateArgument(
    654                                                 type, nullptr, args, results, genStart, indexer, nTuples ) )
     631                                if ( ! instantiateArgument( type, nullptr, args, results, nextResults, indexer ) )
    655632                                        return false;
    656                                 nTuples = 0;
    657                         }
    658                         // re-consititute tuples for final generation
    659                         for ( auto i = genStart; i < results.size(); ++i ) {
    660                                 results[i].endTuple( results );
    661                         }
     633                        }
     634                        for ( ArgPack& result : results ) { result.endTuple(); }
    662635                        return true;
    663636                } else if ( TypeInstType* ttype = Tuples::isTtype( formalType ) ) {
    664637                        // formalType is a ttype, consumes all remaining arguments
    665638                        // xxx - mixing default arguments with variadic??
    666 
    667                         // completed tuples; will be spliced to end of results to finish
    668                         std::vector<ArgPack> finalResults{};
    669 
     639                        std::vector<ArgPack> finalResults{};  /// list of completed tuples
     640                        // start tuples
     641                        for ( ArgPack& result : results ) {
     642                                result.beginTuple();
     643
     644                                // use rest of exploded tuple if present
     645                                while ( result.nextExpl < result.expls.size() ) {
     646                                        const Alternative& actual = result.expls[result.nextExpl];
     647                                        result.env.addActual( actual.env, result.openVars );
     648                                        result.withArg( actual.expr );
     649                                        ++result.nextExpl;
     650                                }
     651                        }
    670652                        // iterate until all results completed
    671                         std::size_t genEnd;
    672                         ++nTuples;
    673                         do {
    674                                 genEnd = results.size();
    675 
     653                        while ( ! results.empty() ) {
    676654                                // add another argument to results
    677                                 for ( std::size_t i = genStart; i < genEnd; ++i ) {
    678                                         // use remainder of exploded tuple if present
    679                                         if ( ! results[i].expls.empty() ) {
    680                                                 const Alternative& actual = results[i].expls.front();
    681 
    682                                                 TypeEnvironment env = results[i].env;
    683                                                 OpenVarSet openVars = results[i].openVars;
    684 
    685                                                 env.addActual( actual.env, openVars );
    686 
    687                                                 std::vector<Alternative> newExpls(
    688                                                         std::next( results[i].expls.begin() ), results[i].expls.end() );
    689                                                 results.emplace_back(
    690                                                         i, actual.expr, move(env), copy(results[i].need),
    691                                                         copy(results[i].have), move(openVars), results[i].nextArg, nTuples,
    692                                                         Cost::zero, move(newExpls) );
    693 
     655                                for ( ArgPack& result : results ) {
     656                                        // finish result when out of arguments
     657                                        if ( result.nextArg >= args.size() ) {
     658                                                Type* argType = result.actuals.back().expr->get_result();
     659                                                if ( result.tupleEls.back() == 1 && Tuples::isTtype( argType ) ) {
     660                                                        // the case where a ttype value is passed directly is special, e.g. for
     661                                                        // argument forwarding purposes
     662                                                        // xxx - what if passing multiple arguments, last of which is ttype?
     663                                                        // xxx - what would happen if unify was changed so that unifying tuple
     664                                                        // types flattened both before unifying lists? then pass in TupleType
     665                                                        // (ttype) below.
     666                                                        result.tupleEls.pop_back();
     667                                                } else {
     668                                                        // collapse leftover arguments into tuple
     669                                                        result.endTuple();
     670                                                        argType = result.actuals.back().expr->get_result();
     671                                                }
     672                                                // check unification for ttype before adding to final
     673                                                if ( unify( ttype, argType, result.env, result.need, result.have,
     674                                                                result.openVars, indexer ) ) {
     675                                                        finalResults.push_back( std::move(result) );
     676                                                }
    694677                                                continue;
    695678                                        }
    696679
    697                                         // finish result when out of arguments
    698                                         if ( results[i].nextArg >= args.size() ) {
    699                                                 ArgPack newResult{
    700                                                         results[i].env, results[i].need, results[i].have,
    701                                                         results[i].openVars };
    702                                                 newResult.nextArg = results[i].nextArg;
    703                                                 Type* argType;
    704 
    705                                                 if ( nTuples > 0 ) {
    706                                                         // first iteration, push empty tuple expression
    707                                                         newResult.parent = i;
    708                                                         std::list<Expression*> emptyList;
    709                                                         newResult.expr.reset( new TupleExpr( emptyList ) );
    710                                                         argType = newResult.expr->get_result();
    711                                                 } else {
    712                                                         // clone result to collect tuple
    713                                                         newResult.parent = results[i].parent;
    714                                                         newResult.cost = results[i].cost;
    715                                                         newResult.tupleStart = results[i].tupleStart;
    716                                                         newResult.expr.reset( results[i].expr->clone() );
    717                                                         argType = newResult.expr->get_result();
    718 
    719                                                         if ( results[i].tupleStart > 0 && Tuples::isTtype( argType ) ) {
    720                                                                 // the case where a ttype value is passed directly is special,
    721                                                                 // e.g. for argument forwarding purposes
    722                                                                 // xxx - what if passing multiple arguments, last of which is
    723                                                                 //       ttype?
    724                                                                 // xxx - what would happen if unify was changed so that unifying
    725                                                                 //       tuple
    726                                                                 // types flattened both before unifying lists? then pass in
    727                                                                 // TupleType (ttype) below.
    728                                                                 --newResult.tupleStart;
    729                                                         } else {
    730                                                                 // collapse leftover arguments into tuple
    731                                                                 newResult.endTuple( results );
    732                                                                 argType = newResult.expr->get_result();
    733                                                         }
    734                                                 }
    735 
    736                                                 // check unification for ttype before adding to final
    737                                                 if ( unify( ttype, argType, newResult.env, newResult.need, newResult.have,
    738                                                                 newResult.openVars, indexer ) ) {
    739                                                         finalResults.push_back( move(newResult) );
    740                                                 }
    741 
    742                                                 continue;
    743                                         }
    744 
    745680                                        // add each possible next argument
    746                                         auto j = results[i].nextArg;
    747                                         for ( const Alternative& actual : args[j] ) {
    748                                                 // fresh copies of parent parameters for this iteration
    749                                                 TypeEnvironment env = results[i].env;
    750                                                 OpenVarSet openVars = results[i].openVars;
    751 
    752                                                 env.addActual( actual.env, openVars );
     681                                        for ( const Alternative& actual : args[result.nextArg] ) {
     682                                                ArgPack aResult = result;  // copy to clone everything
     683                                                // add details of actual to result
     684                                                aResult.env.addActual( actual.env, aResult.openVars );
     685                                                Cost cost = actual.cost;
    753686
    754687                                                // explode argument
    755688                                                std::vector<Alternative> exploded;
    756689                                                Tuples::explode( actual, indexer, back_inserter( exploded ) );
    757                                                 if ( exploded.empty() ) {
    758                                                         // skip empty tuple arguments by (near-)cloning parent into next gen
    759                                                         results.emplace_back(
    760                                                                 results[i], move(env), copy(results[i].need),
    761                                                                 copy(results[i].have), move(openVars), j + 1, actual.cost );
    762 
    763                                                         continue;
     690
     691                                                // add exploded argument to tuple
     692                                                for ( Alternative& aActual : exploded ) {
     693                                                        aResult.withArg( aActual.expr, cost );
     694                                                        cost = Cost::zero;
    764695                                                }
    765 
    766                                                 // trim first element from exploded
    767                                                 std::vector<Alternative> newExpls;
    768                                                 newExpls.reserve( exploded.size() - 1 );
    769                                                 for ( std::size_t i = 1; i < exploded.size(); ++i ) {
    770                                                         newExpls.push_back( move(exploded[i]) );
    771                                                 }
    772                                                 // add new result
    773                                                 results.emplace_back(
    774                                                         i, exploded.front().expr, move(env), copy(results[i].need),
    775                                                         copy(results[i].have), move(openVars), results[i].nextArg + 1,
    776                                                         nTuples, actual.cost, move(newExpls) );
     696                                                ++aResult.nextArg;
     697                                                nextResults.push_back( std::move(aResult) );
    777698                                        }
    778699                                }
    779700
    780701                                // reset for next round
    781                                 genStart = genEnd;
    782                                 nTuples = 0;
    783                         } while ( genEnd != results.size() );
    784 
    785                         // splice final results onto results
    786                         for ( std::size_t i = 0; i < finalResults.size(); ++i ) {
    787                                 results.push_back( move(finalResults[i]) );
    788                         }
    789                         return ! finalResults.empty();
     702                                results.swap( nextResults );
     703                                nextResults.clear();
     704                        }
     705                        results.swap( finalResults );
     706                        return ! results.empty();
    790707                }
    791708
    792709                // iterate each current subresult
    793                 std::size_t genEnd = results.size();
    794                 for ( std::size_t i = genStart; i < genEnd; ++i ) {
    795                         // use remainder of exploded tuple if present
    796                         if ( ! results[i].expls.empty() ) {
    797                                 const Alternative& actual = results[i].expls.front();
    798 
    799                                 TypeEnvironment env = results[i].env;
    800                                 AssertionSet need = results[i].need, have = results[i].have;
    801                                 OpenVarSet openVars = results[i].openVars;
    802 
    803                                 env.addActual( actual.env, openVars );
     710                for ( unsigned iResult = 0; iResult < results.size(); ++iResult ) {
     711                        ArgPack& result = results[iResult];
     712
     713                        if ( result.nextExpl < result.expls.size() ) {
     714                                // use remainder of exploded tuple if present
     715                                const Alternative& actual = result.expls[result.nextExpl];
     716                                result.env.addActual( actual.env, result.openVars );
    804717                                Type* actualType = actual.expr->get_result();
    805718
     
    812725                                )
    813726
    814                                 if ( unify( formalType, actualType, env, need, have, openVars, indexer ) ) {
    815                                         std::vector<Alternative> newExpls(
    816                                                 std::next( results[i].expls.begin() ), results[i].expls.end() );
    817                                         results.emplace_back(
    818                                                 i, actual.expr, move(env), move(need), move(have), move(openVars),
    819                                                 results[i].nextArg, nTuples, Cost::zero, move(newExpls) );;
     727                                if ( unify( formalType, actualType, result.env, result.need, result.have,
     728                                                result.openVars, indexer ) ) {
     729                                        ++result.nextExpl;
     730                                        nextResults.push_back( std::move(result.withArg( actual.expr )) );
    820731                                }
    821732
    822733                                continue;
    823                         }
    824 
    825                         // use default initializers if out of arguments
    826                         if ( results[i].nextArg >= args.size() ) {
     734                        } else if ( result.nextArg >= args.size() ) {
     735                                // use default initializers if out of arguments
    827736                                if ( ConstantExpr* cnstExpr = getDefaultValue( initializer ) ) {
    828737                                        if ( Constant* cnst = dynamic_cast<Constant*>( cnstExpr->get_constant() ) ) {
    829                                                 TypeEnvironment env = results[i].env;
    830                                                 AssertionSet need = results[i].need, have = results[i].have;
    831                                                 OpenVarSet openVars = results[i].openVars;
    832 
    833                                                 if ( unify( formalType, cnst->get_type(), env, need, have, openVars,
    834                                                                 indexer ) ) {
    835                                                         results.emplace_back(
    836                                                                 i, cnstExpr, move(env), move(need), move(have),
    837                                                                 move(openVars), results[i].nextArg, nTuples );
     738                                                if ( unify( formalType, cnst->get_type(), result.env, result.need,
     739                                                                result.have, result.openVars, indexer ) ) {
     740                                                        nextResults.push_back( std::move(result.withArg( cnstExpr )) );
    838741                                                }
    839742                                        }
    840743                                }
    841 
    842744                                continue;
    843745                        }
    844746
    845747                        // Check each possible next argument
    846                         auto j = results[i].nextArg;
    847                         for ( const Alternative& actual : args[j] ) {
    848                                 // fresh copies of parent parameters for this iteration
    849                                 TypeEnvironment env = results[i].env;
    850                                 AssertionSet need = results[i].need, have = results[i].have;
    851                                 OpenVarSet openVars = results[i].openVars;
    852 
    853                                 env.addActual( actual.env, openVars );
     748                        for ( const Alternative& actual : args[result.nextArg] ) {
     749                                ArgPack aResult = result;  // copy to clone everything
     750                                // add details of actual to result
     751                                aResult.env.addActual( actual.env, aResult.openVars );
    854752
    855753                                // explode argument
     
    857755                                Tuples::explode( actual, indexer, back_inserter( exploded ) );
    858756                                if ( exploded.empty() ) {
    859                                         // skip empty tuple arguments by (near-)cloning parent into next gen
    860                                         results.emplace_back(
    861                                                 results[i], move(env), move(need), move(have), move(openVars), j + 1,
    862                                                 actual.cost );
    863 
     757                                        // skip empty tuple arguments
     758                                        ++aResult.nextArg;
     759                                        results.push_back( std::move(aResult) );
    864760                                        continue;
    865761                                }
     
    878774
    879775                                // attempt to unify types
    880                                 if ( unify( formalType, actualType, env, need, have, openVars, indexer ) ) {
    881                                         // trim first element from exploded
    882                                         std::vector<Alternative> newExpls;
    883                                         newExpls.reserve( exploded.size() - 1 );
    884                                         for ( std::size_t i = 1; i < exploded.size(); ++i ) {
    885                                                 newExpls.push_back( move(exploded[i]) );
     776                                if ( unify( formalType, actualType, aResult.env, aResult.need, aResult.have, aResult.openVars, indexer ) ) {
     777                                        // add argument
     778                                        aResult.withArg( aActual.expr, actual.cost );
     779                                        ++aResult.nextArg;
     780                                        if ( exploded.size() > 1 ) {
     781                                                // other parts of tuple left over
     782                                                aResult.expls = std::move( exploded );
     783                                                aResult.nextExpl = 1;
    886784                                        }
    887                                         // add new result
    888                                         results.emplace_back(
    889                                                 i, aActual.expr, move(env), move(need), move(have), move(openVars),
    890                                                 j + 1, nTuples, actual.cost, move(newExpls) );
     785                                        nextResults.push_back( std::move(aResult) );
    891786                                }
    892787                        }
     
    894789
    895790                // reset for next parameter
    896                 genStart = genEnd;
    897 
    898                 return genEnd != results.size();
    899         }
    900 
    901         template<typename OutputIterator>
    902         void AlternativeFinder::validateFunctionAlternative( const Alternative &func, ArgPack& result,
    903                         const std::vector<ArgPack>& results, OutputIterator out ) {
    904                 ApplicationExpr *appExpr = new ApplicationExpr( func.expr->clone() );
    905                 // sum cost and accumulate actuals
    906                 std::list<Expression*>& args = appExpr->get_args();
    907                 Cost cost = Cost::zero;
    908                 const ArgPack* pack = &result;
    909                 while ( pack->expr ) {
    910                         args.push_front( pack->expr->clone() );
    911                         cost += pack->cost;
    912                         pack = &results[pack->parent];
    913                 }
    914                 // build and validate new alternative
    915                 Alternative newAlt( appExpr, result.env, cost );
    916                 PRINT(
    917                         std::cerr << "instantiate function success: " << appExpr << std::endl;
    918                         std::cerr << "need assertions:" << std::endl;
    919                         printAssertionSet( result.need, std::cerr, 8 );
    920                 )
    921                 inferParameters( result.need, result.have, newAlt, result.openVars, out );
     791                results.swap( nextResults );
     792                nextResults.clear();
     793
     794                return ! results.empty();
    922795        }
    923796
     
    945818
    946819                // iteratively build matches, one parameter at a time
    947                 std::vector<ArgPack> results;
    948                 results.push_back( ArgPack{ funcEnv, funcNeed, funcHave, funcOpenVars } );
    949                 std::size_t genStart = 0;
    950 
     820                std::vector<ArgPack> results{ ArgPack{ funcEnv, funcNeed, funcHave, funcOpenVars } };
     821                std::vector<ArgPack> nextResults{};
    951822                for ( DeclarationWithType* formal : funcType->get_parameters() ) {
    952823                        ObjectDecl* obj = strict_dynamic_cast< ObjectDecl* >( formal );
    953824                        if ( ! instantiateArgument(
    954                                         obj->get_type(), obj->get_init(), args, results, genStart, indexer ) )
     825                                        obj->get_type(), obj->get_init(), args, results, nextResults, indexer ) )
    955826                                return;
    956827                }
    957828
     829                // filter out results that don't use all the arguments, and aren't variadic
     830                std::vector<ArgPack> finalResults{};
    958831                if ( funcType->get_isVarArgs() ) {
    959                         // append any unused arguments to vararg pack
    960                         std::size_t genEnd;
    961                         do {
    962                                 genEnd = results.size();
    963 
    964                                 // iterate results
    965                                 for ( std::size_t i = genStart; i < genEnd; ++i ) {
    966                                         // use remainder of exploded tuple if present
    967                                         if ( ! results[i].expls.empty() ) {
    968                                                 const Alternative& actual = results[i].expls.front();
    969 
    970                                                 TypeEnvironment env = results[i].env;
    971                                                 OpenVarSet openVars = results[i].openVars;
    972 
    973                                                 env.addActual( actual.env, openVars );
    974 
    975                                                 std::vector<Alternative> newExpls(
    976                                                         std::next( results[i].expls.begin() ), results[i].expls.end() );
    977                                                 results.emplace_back(
    978                                                         i, actual.expr, move(env), copy(results[i].need),
    979                                                         copy(results[i].have), move(openVars), results[i].nextArg, 0,
    980                                                         Cost::zero, move(newExpls) );
    981 
     832                        for ( ArgPack& result : results ) {
     833                                // use rest of exploded tuple if present
     834                                while ( result.nextExpl < result.expls.size() ) {
     835                                        const Alternative& actual = result.expls[result.nextExpl];
     836                                        result.env.addActual( actual.env, result.openVars );
     837                                        result.withArg( actual.expr );
     838                                        ++result.nextExpl;
     839                                }
     840                        }
     841
     842                        while ( ! results.empty() ) {
     843                                // build combinations for all remaining arguments
     844                                for ( ArgPack& result : results ) {
     845                                        // keep if used all arguments
     846                                        if ( result.nextArg >= args.size() ) {
     847                                                finalResults.push_back( std::move(result) );
    982848                                                continue;
    983849                                        }
    984850
    985                                         // finish result when out of arguments
    986                                         if ( results[i].nextArg >= args.size() ) {
    987                                                 validateFunctionAlternative( func, results[i], results, out );
    988 
    989                                                 continue;
    990                                         }
    991 
    992851                                        // add each possible next argument
    993                                         auto j = results[i].nextArg;
    994                                         for ( const Alternative& actual : args[j] ) {
    995                                                 // fresh copies of parent parameters for this iteration
    996                                                 TypeEnvironment env = results[i].env;
    997                                                 OpenVarSet openVars = results[i].openVars;
    998 
    999                                                 env.addActual( actual.env, openVars );
     852                                        for ( const Alternative& actual : args[result.nextArg] ) {
     853                                                ArgPack aResult = result; // copy to clone everything
     854                                                // add details of actual to result
     855                                                aResult.env.addActual( actual.env, aResult.openVars );
     856                                                Cost cost = actual.cost;
    1000857
    1001858                                                // explode argument
    1002859                                                std::vector<Alternative> exploded;
    1003860                                                Tuples::explode( actual, indexer, back_inserter( exploded ) );
    1004                                                 if ( exploded.empty() ) {
    1005                                                         // skip empty tuple arguments by (near-)cloning parent into next gen
    1006                                                         results.emplace_back(
    1007                                                                 results[i], move(env), copy(results[i].need),
    1008                                                                 copy(results[i].have), move(openVars), j + 1, actual.cost );
    1009                                                         continue;
     861
     862                                                // add exploded argument to arg list
     863                                                for ( Alternative& aActual : exploded ) {
     864                                                        aResult.withArg( aActual.expr, cost );
     865                                                        cost = Cost::zero;
    1010866                                                }
    1011 
    1012                                                 // trim first element from exploded
    1013                                                 std::vector<Alternative> newExpls;
    1014                                                 newExpls.reserve( exploded.size() - 1 );
    1015                                                 for ( std::size_t i = 1; i < exploded.size(); ++i ) {
    1016                                                         newExpls.push_back( move(exploded[i]) );
    1017                                                 }
    1018                                                 // add new result
    1019                                                 results.emplace_back(
    1020                                                         i, exploded.front().expr, move(env), copy(results[i].need),
    1021                                                         copy(results[i].have), move(openVars), j + 1, 0,
    1022                                                         actual.cost, move(newExpls) );
     867                                                ++aResult.nextArg;
     868                                                nextResults.push_back( std::move(aResult) );
    1023869                                        }
    1024870                                }
    1025871
    1026                                 genStart = genEnd;
    1027                         } while ( genEnd != results.size() );
     872                                // reset for next round
     873                                results.swap( nextResults );
     874                                nextResults.clear();
     875                        }
    1028876                } else {
    1029877                        // filter out results that don't use all the arguments
    1030                         for ( std::size_t i = genStart; i < results.size(); ++i ) {
    1031                                 ArgPack& result = results[i];
    1032                                 if ( result.expls.empty() && result.nextArg >= args.size() ) {
    1033                                         validateFunctionAlternative( func, result, results, out );
    1034                                 }
    1035                         }
     878                        for ( ArgPack& result : results ) {
     879                                if ( result.nextExpl >= result.expls.size() && result.nextArg >= args.size() ) {
     880                                        finalResults.push_back( std::move(result) );
     881                                }
     882                        }
     883                }
     884
     885                // validate matching combos, add to final result list
     886                for ( ArgPack& result : finalResults ) {
     887                        ApplicationExpr *appExpr = new ApplicationExpr( func.expr->clone() );
     888                        Alternative newAlt( appExpr, result.env, sumCost( result.actuals ) );
     889                        makeExprList( result.actuals, appExpr->get_args() );
     890                        PRINT(
     891                                std::cerr << "instantiate function success: " << appExpr << std::endl;
     892                                std::cerr << "need assertions:" << std::endl;
     893                                printAssertionSet( result.need, std::cerr, 8 );
     894                        )
     895                        inferParameters( result.need, result.have, newAlt, result.openVars, out );
    1036896                }
    1037897        }
     
    1096956                if ( ! funcOpFinder.alternatives.empty() ) {
    1097957                        // add function alternatives to front of argument list
    1098                         argAlternatives.insert( argAlternatives.begin(), move(funcFinder) );
     958                        argAlternatives.insert( argAlternatives.begin(), std::move(funcFinder) );
    1099959
    1100960                        for ( AltList::iterator funcOp = funcOpFinder.alternatives.begin();
     
    1122982
    1123983                // compute conversionsion costs
    1124                 for ( Alternative& withFunc : candidates ) {
    1125                         Cost cvtCost = computeApplicationConversionCost( withFunc, indexer );
     984                for ( AltList::iterator withFunc = candidates.begin(); withFunc != candidates.end(); ++withFunc ) {
     985                        Cost cvtCost = computeApplicationConversionCost( *withFunc, indexer );
    1126986
    1127987                        PRINT(
    1128                                 ApplicationExpr *appExpr = strict_dynamic_cast< ApplicationExpr* >( withFunc.expr );
     988                                ApplicationExpr *appExpr = strict_dynamic_cast< ApplicationExpr* >( withFunc->expr );
    1129989                                PointerType *pointer = strict_dynamic_cast< PointerType* >( appExpr->get_function()->get_result() );
    1130990                                FunctionType *function = strict_dynamic_cast< FunctionType* >( pointer->get_base() );
     
    1135995                                printAll( appExpr->get_args(), std::cerr, 8 );
    1136996                                std::cerr << "bindings are:" << std::endl;
    1137                                 withFunc.env.print( std::cerr, 8 );
     997                                withFunc->env.print( std::cerr, 8 );
    1138998                                std::cerr << "cost of conversion is:" << cvtCost << std::endl;
    1139999                        )
    11401000                        if ( cvtCost != Cost::infinity ) {
    1141                                 withFunc.cvtCost = cvtCost;
    1142                                 alternatives.push_back( withFunc );
     1001                                withFunc->cvtCost = cvtCost;
     1002                                alternatives.push_back( *withFunc );
    11431003                        } // if
    11441004                } // for
    11451005
    1146                 candidates = move(alternatives);
     1006                candidates.clear();
     1007                candidates.splice( candidates.end(), alternatives );
    11471008
    11481009                // use a new list so that alternatives are not examined by addAnonConversions twice.
     
    11501011                findMinCost( candidates.begin(), candidates.end(), std::back_inserter( winners ) );
    11511012
    1152                 // function may return struct or union value, in which case we need to add alternatives
    1153                 // for implicitconversions to each of the anonymous members, must happen after findMinCost
    1154                 // since anon conversions are never the cheapest expression
     1013                // function may return struct or union value, in which case we need to add alternatives for implicit
     1014                // conversions to each of the anonymous members, must happen after findMinCost since anon conversions
     1015                // are never the cheapest expression
    11551016                for ( const Alternative & alt : winners ) {
    11561017                        addAnonConversions( alt );
    11571018                }
    1158                 spliceBegin( alternatives, winners );
     1019                alternatives.splice( alternatives.begin(), winners );
    11591020
    11601021                if ( alternatives.empty() && targetType && ! targetType->isVoid() ) {
     
    11801041                AlternativeFinder finder( indexer, env );
    11811042                finder.find( addressExpr->get_arg() );
    1182                 for ( Alternative& alt : finder.alternatives ) {
    1183                         if ( isLvalue( alt.expr ) ) {
    1184                                 alternatives.push_back(
    1185                                         Alternative{ new AddressExpr( alt.expr->clone() ), alt.env, alt.cost } );
     1043                for ( std::list< Alternative >::iterator i = finder.alternatives.begin(); i != finder.alternatives.end(); ++i ) {
     1044                        if ( isLvalue( i->expr ) ) {
     1045                                alternatives.push_back( Alternative( new AddressExpr( i->expr->clone() ), i->env, i->cost ) );
    11861046                        } // if
    11871047                } // for
     
    11891049
    11901050        void AlternativeFinder::visit( LabelAddressExpr * expr ) {
    1191                 alternatives.push_back( Alternative{ expr->clone(), env, Cost::zero } );
     1051                alternatives.push_back( Alternative( expr->clone(), env, Cost::zero) );
    11921052        }
    11931053
     
    12311091
    12321092                AltList candidates;
    1233                 for ( Alternative & alt : finder.alternatives ) {
     1093                for ( std::list< Alternative >::iterator i = finder.alternatives.begin(); i != finder.alternatives.end(); ++i ) {
    12341094                        AssertionSet needAssertions, haveAssertions;
    12351095                        OpenVarSet openVars;
     
    12391099                        // that are cast directly.  The candidate is invalid if it has fewer results than there are types to cast
    12401100                        // to.
    1241                         int discardedValues = alt.expr->get_result()->size() - castExpr->get_result()->size();
     1101                        int discardedValues = i->expr->get_result()->size() - castExpr->get_result()->size();
    12421102                        if ( discardedValues < 0 ) continue;
    12431103                        // xxx - may need to go into tuple types and extract relevant types and use unifyList. Note that currently, this does not
    12441104                        // allow casting a tuple to an atomic type (e.g. (int)([1, 2, 3]))
    12451105                        // unification run for side-effects
    1246                         unify( castExpr->get_result(), alt.expr->get_result(), alt.env, needAssertions,
    1247                                 haveAssertions, openVars, indexer );
    1248                         Cost thisCost = castCost( alt.expr->get_result(), castExpr->get_result(), indexer,
    1249                                 alt.env );
    1250                         PRINT(
    1251                                 std::cerr << "working on cast with result: " << castExpr->result << std::endl;
    1252                                 std::cerr << "and expr type: " << alt.expr->result << std::endl;
    1253                                 std::cerr << "env: " << alt.env << std::endl;
    1254                         )
     1106                        unify( castExpr->get_result(), i->expr->get_result(), i->env, needAssertions, haveAssertions, openVars, indexer );
     1107                        Cost thisCost = castCost( i->expr->get_result(), castExpr->get_result(), indexer, i->env );
    12551108                        if ( thisCost != Cost::infinity ) {
    1256                                 PRINT(
    1257                                         std::cerr << "has finite cost." << std::endl;
    1258                                 )
    12591109                                // count one safe conversion for each value that is thrown away
    12601110                                thisCost.incSafe( discardedValues );
    1261                                 Alternative newAlt( restructureCast( alt.expr->clone(), toType ), alt.env,
    1262                                         alt.cost, thisCost );
    1263                                 inferParameters( needAssertions, haveAssertions, newAlt, openVars,
    1264                                         back_inserter( candidates ) );
     1111                                Alternative newAlt( restructureCast( i->expr->clone(), toType ), i->env, i->cost, thisCost );
     1112                                inferParameters( needAssertions, haveAssertions, newAlt, openVars, back_inserter( candidates ) );
    12651113                        } // if
    12661114                } // for
     
    15491397
    15501398        void AlternativeFinder::visit( UntypedTupleExpr *tupleExpr ) {
    1551                 std::vector< AlternativeFinder > subExprAlternatives;
    1552                 findSubExprs( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end(),
    1553                         back_inserter( subExprAlternatives ) );
    1554                 std::vector< AltList > possibilities;
    1555                 combos( subExprAlternatives.begin(), subExprAlternatives.end(),
    1556                         back_inserter( possibilities ) );
    1557                 for ( const AltList& alts : possibilities ) {
     1399                std::list< AlternativeFinder > subExprAlternatives;
     1400                findSubExprs( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end(), back_inserter( subExprAlternatives ) );
     1401                std::list< AltList > possibilities;
     1402                combos( subExprAlternatives.begin(), subExprAlternatives.end(), back_inserter( possibilities ) );
     1403                for ( std::list< AltList >::const_iterator i = possibilities.begin(); i != possibilities.end(); ++i ) {
    15581404                        std::list< Expression * > exprs;
    1559                         makeExprList( alts, exprs );
     1405                        makeExprList( *i, exprs );
    15601406
    15611407                        TypeEnvironment compositeEnv;
    1562                         simpleCombineEnvironments( alts.begin(), alts.end(), compositeEnv );
    1563                         alternatives.push_back(
    1564                                 Alternative{ new TupleExpr( exprs ), compositeEnv, sumCost( alts ) } );
     1408                        simpleCombineEnvironments( i->begin(), i->end(), compositeEnv );
     1409                        alternatives.push_back( Alternative( new TupleExpr( exprs ) , compositeEnv, sumCost( *i ) ) );
    15651410                } // for
    15661411        }
Note: See TracChangeset for help on using the changeset viewer.