source: src/ResolvExpr/AlternativeFinder.cc @ 9236060

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 9236060 was 9236060, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Merge branch 'master' into references

  • Property mode set to 100644
File size: 57.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
[a5f0529]11// Last Modified By : Andrew Beach
12// Last Modified On : Wed Jul 26 11:33:00 2017
13// Update Count     : 31
[a32b204]14//
15
[51b7345]16#include <list>
17#include <iterator>
18#include <algorithm>
19#include <functional>
20#include <cassert>
[ebf5689]21#include <unordered_map>
22#include <utility>
23#include <vector>
[51b7345]24
25#include "AlternativeFinder.h"
26#include "Alternative.h"
27#include "Cost.h"
28#include "typeops.h"
29#include "Unify.h"
30#include "RenameVars.h"
31#include "SynTree/Type.h"
32#include "SynTree/Declaration.h"
33#include "SynTree/Expression.h"
34#include "SynTree/Initializer.h"
35#include "SynTree/Visitor.h"
36#include "SymTab/Indexer.h"
37#include "SymTab/Mangler.h"
38#include "SynTree/TypeSubstitution.h"
39#include "SymTab/Validate.h"
[6eb8948]40#include "Tuples/Tuples.h"
[141b786]41#include "Tuples/Explode.h"
[d3b7937]42#include "Common/utility.h"
[70f89d00]43#include "InitTweak/InitTweak.h"
[77971f6]44#include "InitTweak/GenInit.h"
[85517ddb]45#include "ResolveTypeof.h"
[722617d]46#include "Resolver.h"
[51b7345]47
[b87a5ed]48extern bool resolvep;
[6ed1d4b]49#define PRINT( text ) if ( resolvep ) { text }
[51b7345]50//#define DEBUG_COST
51
52namespace ResolvExpr {
[a32b204]53        Expression *resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer, TypeEnvironment &env ) {
54                CastExpr *castToVoid = new CastExpr( expr );
55
56                AlternativeFinder finder( indexer, env );
57                finder.findWithAdjustment( castToVoid );
58
59                // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
60                // interpretations, an exception has already been thrown.
61                assert( finder.get_alternatives().size() == 1 );
62                CastExpr *newExpr = dynamic_cast< CastExpr* >( finder.get_alternatives().front().expr );
63                assert( newExpr );
64                env = finder.get_alternatives().front().env;
65                return newExpr->get_arg()->clone();
66        }
67
[908cc83]68        Cost sumCost( const AltList &in ) {
[89be1c68]69                Cost total = Cost::zero;
[908cc83]70                for ( AltList::const_iterator i = in.begin(); i != in.end(); ++i ) {
71                        total += i->cost;
72                }
73                return total;
74        }
75
[a32b204]76        namespace {
77                void printAlts( const AltList &list, std::ostream &os, int indent = 0 ) {
78                        for ( AltList::const_iterator i = list.begin(); i != list.end(); ++i ) {
79                                i->print( os, indent );
80                                os << std::endl;
81                        }
82                }
[d9a0e76]83
[a32b204]84                void makeExprList( const AltList &in, std::list< Expression* > &out ) {
85                        for ( AltList::const_iterator i = in.begin(); i != in.end(); ++i ) {
86                                out.push_back( i->expr->clone() );
87                        }
88                }
[d9a0e76]89
[a32b204]90                struct PruneStruct {
91                        bool isAmbiguous;
92                        AltList::iterator candidate;
93                        PruneStruct() {}
94                        PruneStruct( AltList::iterator candidate ): isAmbiguous( false ), candidate( candidate ) {}
95                };
96
[0f19d763]97                /// Prunes a list of alternatives down to those that have the minimum conversion cost for a given return type; skips ambiguous interpretations
[a32b204]98                template< typename InputIterator, typename OutputIterator >
[d7dc824]99                void pruneAlternatives( InputIterator begin, InputIterator end, OutputIterator out ) {
[a32b204]100                        // select the alternatives that have the minimum conversion cost for a particular set of result types
101                        std::map< std::string, PruneStruct > selected;
102                        for ( AltList::iterator candidate = begin; candidate != end; ++candidate ) {
103                                PruneStruct current( candidate );
104                                std::string mangleName;
[906e24d]105                                {
106                                        Type * newType = candidate->expr->get_result()->clone();
[a32b204]107                                        candidate->env.apply( newType );
[906e24d]108                                        mangleName = SymTab::Mangler::mangle( newType );
[a32b204]109                                        delete newType;
110                                }
111                                std::map< std::string, PruneStruct >::iterator mapPlace = selected.find( mangleName );
112                                if ( mapPlace != selected.end() ) {
113                                        if ( candidate->cost < mapPlace->second.candidate->cost ) {
114                                                PRINT(
[6ed1d4b]115                                                        std::cerr << "cost " << candidate->cost << " beats " << mapPlace->second.candidate->cost << std::endl;
[7c64920]116                                                )
[0f19d763]117                                                selected[ mangleName ] = current;
[a32b204]118                                        } else if ( candidate->cost == mapPlace->second.candidate->cost ) {
119                                                PRINT(
[6ed1d4b]120                                                        std::cerr << "marking ambiguous" << std::endl;
[7c64920]121                                                )
[0f19d763]122                                                mapPlace->second.isAmbiguous = true;
[a32b204]123                                        }
124                                } else {
125                                        selected[ mangleName ] = current;
126                                }
127                        }
[d9a0e76]128
129                        PRINT(
[6ed1d4b]130                                std::cerr << "there are " << selected.size() << " alternatives before elimination" << std::endl;
[7c64920]131                        )
[a32b204]132
[0f19d763]133                        // accept the alternatives that were unambiguous
134                        for ( std::map< std::string, PruneStruct >::iterator target = selected.begin(); target != selected.end(); ++target ) {
135                                if ( ! target->second.isAmbiguous ) {
136                                        Alternative &alt = *target->second.candidate;
[906e24d]137                                        alt.env.applyFree( alt.expr->get_result() );
[0f19d763]138                                        *out++ = alt;
[a32b204]139                                }
[0f19d763]140                        }
[d9a0e76]141                }
[a32b204]142
143                void renameTypes( Expression *expr ) {
[906e24d]144                        expr->get_result()->accept( global_renamer );
[e76acbe]145                }
[b1bead1]146
147                void referenceToRvalueConversion( Expression *& expr ) {
148                        if ( dynamic_cast< ReferenceType * >( expr->get_result() ) ) {
149                                // cast away reference from expr
150                                expr = new CastExpr( expr, expr->get_result()->stripReferences()->clone() );
151                        }
152                }
153        } // namespace
[d9a0e76]154
[a32b204]155        template< typename InputIterator, typename OutputIterator >
156        void AlternativeFinder::findSubExprs( InputIterator begin, InputIterator end, OutputIterator out ) {
157                while ( begin != end ) {
158                        AlternativeFinder finder( indexer, env );
159                        finder.findWithAdjustment( *begin );
160                        // XXX  either this
161                        //Designators::fixDesignations( finder, (*begin++)->get_argName() );
162                        // or XXX this
163                        begin++;
164                        PRINT(
[6ed1d4b]165                                std::cerr << "findSubExprs" << std::endl;
166                                printAlts( finder.alternatives, std::cerr );
[7c64920]167                        )
[0f19d763]168                        *out++ = finder;
[a32b204]169                }
[d9a0e76]170        }
171
[a32b204]172        AlternativeFinder::AlternativeFinder( const SymTab::Indexer &indexer, const TypeEnvironment &env )
173                : indexer( indexer ), env( env ) {
[d9a0e76]174        }
[51b7345]175
[b6fe7e6]176        void AlternativeFinder::find( Expression *expr, bool adjust, bool prune ) {
[a32b204]177                expr->accept( *this );
178                if ( alternatives.empty() ) {
179                        throw SemanticError( "No reasonable alternatives for expression ", expr );
180                }
181                for ( AltList::iterator i = alternatives.begin(); i != alternatives.end(); ++i ) {
182                        if ( adjust ) {
[906e24d]183                                adjustExprType( i->expr->get_result(), i->env, indexer );
[a32b204]184                        }
185                }
[b6fe7e6]186                if ( prune ) {
187                        PRINT(
188                                std::cerr << "alternatives before prune:" << std::endl;
189                                printAlts( alternatives, std::cerr );
190                        )
191                        AltList::iterator oldBegin = alternatives.begin();
[d7dc824]192                        pruneAlternatives( alternatives.begin(), alternatives.end(), front_inserter( alternatives ) );
[b6fe7e6]193                        if ( alternatives.begin() == oldBegin ) {
194                                std::ostringstream stream;
[7933351]195                                stream << "Can't choose between " << alternatives.size() << " alternatives for expression ";
[b6fe7e6]196                                expr->print( stream );
197                                stream << "Alternatives are:";
198                                AltList winners;
199                                findMinCost( alternatives.begin(), alternatives.end(), back_inserter( winners ) );
200                                printAlts( winners, stream, 8 );
201                                throw SemanticError( stream.str() );
202                        }
203                        alternatives.erase( oldBegin, alternatives.end() );
204                        PRINT(
205                                std::cerr << "there are " << alternatives.size() << " alternatives after elimination" << std::endl;
206                        )
[a32b204]207                }
[8e9cbb2]208
[64ac636]209                // Central location to handle gcc extension keyword, etc. for all expression types.
[8e9cbb2]210                for ( Alternative &iter: alternatives ) {
211                        iter.expr->set_extension( expr->get_extension() );
[64ac636]212                        iter.expr->location = expr->location;
[8e9cbb2]213                } // for
[0f19d763]214        }
[d9a0e76]215
[b6fe7e6]216        void AlternativeFinder::findWithAdjustment( Expression *expr, bool prune ) {
217                find( expr, true, prune );
[d9a0e76]218        }
[a32b204]219
[4b0f997]220        void AlternativeFinder::addAnonConversions( const Alternative & alt ) {
221                // adds anonymous member interpretations whenever an aggregate value type is seen.
[d1685588]222                // 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
223                std::unique_ptr<Expression> aggrExpr( alt.expr->clone() );
224                alt.env.apply( aggrExpr->get_result() );
225                Type * aggrType = aggrExpr->get_result();
226                if ( dynamic_cast< ReferenceType * >( aggrType ) ) {
227                        aggrType = aggrType->stripReferences();
228                        aggrExpr.reset( new CastExpr( aggrExpr.release(), aggrType->clone() ) );
229                }
230
231                if ( StructInstType *structInst = dynamic_cast< StructInstType* >( aggrExpr->get_result() ) ) {
[4b0f997]232                        NameExpr nameExpr( "" );
[d1685588]233                        addAggMembers( structInst, aggrExpr.get(), alt.cost+Cost::safe, alt.env, &nameExpr );
234                } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( aggrExpr->get_result() ) ) {
[4b0f997]235                        NameExpr nameExpr( "" );
[d1685588]236                        addAggMembers( unionInst, aggrExpr.get(), alt.cost+Cost::safe, alt.env, &nameExpr );
[4b0f997]237                } // if
238        }
[77971f6]239
[a32b204]240        template< typename StructOrUnionType >
[add7117]241        void AlternativeFinder::addAggMembers( StructOrUnionType *aggInst, Expression *expr, const Cost &newCost, const TypeEnvironment & env, Expression * member ) {
[bf32bb8]242                // by this point, member must be a name expr
243                NameExpr * nameExpr = safe_dynamic_cast< NameExpr * >( member );
244                const std::string & name = nameExpr->get_name();
245                std::list< Declaration* > members;
246                aggInst->lookup( name, members );
[4b0f997]247
[bf32bb8]248                for ( std::list< Declaration* >::const_iterator i = members.begin(); i != members.end(); ++i ) {
249                        if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType* >( *i ) ) {
[d9fa60a]250                                alternatives.push_back( Alternative( new MemberExpr( dwt, expr->clone() ), env, newCost ) );
[bf32bb8]251                                renameTypes( alternatives.back().expr );
[4b0f997]252                                addAnonConversions( alternatives.back() ); // add anonymous member interpretations whenever an aggregate value type is seen as a member expression.
[bf32bb8]253                        } else {
254                                assert( false );
[a32b204]255                        }
256                }
[d9a0e76]257        }
[a32b204]258
[848ce71]259        void AlternativeFinder::addTupleMembers( TupleType * tupleType, Expression *expr, const Cost &newCost, const TypeEnvironment & env, Expression * member ) {
260                if ( ConstantExpr * constantExpr = dynamic_cast< ConstantExpr * >( member ) ) {
261                        // get the value of the constant expression as an int, must be between 0 and the length of the tuple type to have meaning
262                        // xxx - this should be improved by memoizing the value of constant exprs
263                        // during parsing and reusing that information here.
264                        std::stringstream ss( constantExpr->get_constant()->get_value() );
265                        int val;
266                        std::string tmp;
267                        if ( ss >> val && ! (ss >> tmp) ) {
268                                if ( val >= 0 && (unsigned int)val < tupleType->size() ) {
269                                        alternatives.push_back( Alternative( new TupleIndexExpr( expr->clone(), val ), env, newCost ) );
270                                } // if
271                        } // if
[141b786]272                } else if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( member ) ) {
273                        // xxx - temporary hack until 0/1 are int constants
274                        if ( nameExpr->get_name() == "0" || nameExpr->get_name() == "1" ) {
275                                std::stringstream ss( nameExpr->get_name() );
276                                int val;
277                                ss >> val;
278                                alternatives.push_back( Alternative( new TupleIndexExpr( expr->clone(), val ), env, newCost ) );
279                        }
[848ce71]280                } // if
281        }
282
[a32b204]283        void AlternativeFinder::visit( ApplicationExpr *applicationExpr ) {
284                alternatives.push_back( Alternative( applicationExpr->clone(), env, Cost::zero ) );
[d9a0e76]285        }
286
[a32b204]287        Cost computeConversionCost( Alternative &alt, const SymTab::Indexer &indexer ) {
[8f7cea1]288                ApplicationExpr *appExpr = safe_dynamic_cast< ApplicationExpr* >( alt.expr );
[906e24d]289                PointerType *pointer = safe_dynamic_cast< PointerType* >( appExpr->get_function()->get_result() );
[8f7cea1]290                FunctionType *function = safe_dynamic_cast< FunctionType* >( pointer->get_base() );
[a32b204]291
[89be1c68]292                Cost convCost = Cost::zero;
[a32b204]293                std::list< DeclarationWithType* >& formals = function->get_parameters();
294                std::list< DeclarationWithType* >::iterator formal = formals.begin();
295                std::list< Expression* >& actuals = appExpr->get_args();
[0362d42]296
[a32b204]297                for ( std::list< Expression* >::iterator actualExpr = actuals.begin(); actualExpr != actuals.end(); ++actualExpr ) {
[53e3b4a]298                        Type * actualType = (*actualExpr)->get_result();
[a32b204]299                        PRINT(
[6ed1d4b]300                                std::cerr << "actual expression:" << std::endl;
301                                (*actualExpr)->print( std::cerr, 8 );
302                                std::cerr << "--- results are" << std::endl;
[53e3b4a]303                                actualType->print( std::cerr, 8 );
[7c64920]304                        )
[89be1c68]305                        Cost actualCost = Cost::zero;
[53e3b4a]306                        if ( formal == formals.end() ) {
307                                if ( function->get_isVarArgs() ) {
[89be1c68]308                                        convCost.incUnsafe();
[b1bead1]309                                        // convert reference-typed expressions to value-typed expressions
310                                        referenceToRvalueConversion( *actualExpr );
[53e3b4a]311                                        continue;
312                                } else {
313                                        return Cost::infinity;
[7c64920]314                                }
[53e3b4a]315                        }
316                        Type * formalType = (*formal)->get_type();
317                        PRINT(
318                                std::cerr << std::endl << "converting ";
319                                actualType->print( std::cerr, 8 );
320                                std::cerr << std::endl << " to ";
321                                formalType->print( std::cerr, 8 );
[a61ad31]322                                std::cerr << std::endl << "environment is: ";
323                                alt.env.print( std::cerr, 8 );
324                                std::cerr << std::endl;
[53e3b4a]325                        )
326                        Cost newCost = conversionCost( actualType, formalType, indexer, alt.env );
327                        PRINT(
328                                std::cerr << std::endl << "cost is" << newCost << std::endl;
329                        )
[a32b204]330
[53e3b4a]331                        if ( newCost == Cost::infinity ) {
332                                return newCost;
[a32b204]333                        }
[53e3b4a]334                        convCost += newCost;
335                        actualCost += newCost;
[89be1c68]336                        if ( actualCost != Cost::zero ) {
[53e3b4a]337                                Type *newType = formalType->clone();
338                                alt.env.apply( newType );
339                                *actualExpr = new CastExpr( *actualExpr, newType );
[a32b204]340                        }
[89be1c68]341                        convCost.incPoly( polyCost( formalType, alt.env, indexer ) + polyCost( actualType, alt.env, indexer ) );
[53e3b4a]342                        ++formal; // can't be in for-loop update because of the continue
[d9a0e76]343                }
[a32b204]344                if ( formal != formals.end() ) {
345                        return Cost::infinity;
[d9a0e76]346                }
347
[a32b204]348                for ( InferredParams::const_iterator assert = appExpr->get_inferParams().begin(); assert != appExpr->get_inferParams().end(); ++assert ) {
349                        PRINT(
[6ed1d4b]350                                std::cerr << std::endl << "converting ";
351                                assert->second.actualType->print( std::cerr, 8 );
352                                std::cerr << std::endl << " to ";
353                                assert->second.formalType->print( std::cerr, 8 );
[02cea2d]354                        )
355                        Cost newCost = conversionCost( assert->second.actualType, assert->second.formalType, indexer, alt.env );
[a32b204]356                        PRINT(
[6ed1d4b]357                                std::cerr << std::endl << "cost of conversion is " << newCost << std::endl;
[02cea2d]358                        )
359                        if ( newCost == Cost::infinity ) {
360                                return newCost;
361                        }
[a32b204]362                        convCost += newCost;
[89be1c68]363                        convCost.incPoly( polyCost( assert->second.formalType, alt.env, indexer ) + polyCost( assert->second.actualType, alt.env, indexer ) );
[a32b204]364                }
[d9a0e76]365
[a32b204]366                return convCost;
367        }
[d9a0e76]368
[8c84ebd]369        /// Adds type variables to the open variable set and marks their assertions
[a32b204]370        void makeUnifiableVars( Type *type, OpenVarSet &unifiableVars, AssertionSet &needAssertions ) {
[8c49c0e]371                for ( Type::ForallList::const_iterator tyvar = type->get_forall().begin(); tyvar != type->get_forall().end(); ++tyvar ) {
[2c57025]372                        unifiableVars[ (*tyvar)->get_name() ] = TypeDecl::Data{ *tyvar };
[a32b204]373                        for ( std::list< DeclarationWithType* >::iterator assert = (*tyvar)->get_assertions().begin(); assert != (*tyvar)->get_assertions().end(); ++assert ) {
[6c3a988f]374                                needAssertions[ *assert ].isUsed = true;
[a32b204]375                        }
[d9a0e76]376///     needAssertions.insert( needAssertions.end(), (*tyvar)->get_assertions().begin(), (*tyvar)->get_assertions().end() );
377                }
378        }
[a32b204]379
[aefcc3b]380        /// instantiate a single argument by matching actuals from [actualIt, actualEnd) against formalType,
381        /// producing expression(s) in out and their total cost in cost.
382        template< typename AltIterator, typename OutputIterator >
383        bool instantiateArgument( Type * formalType, Initializer * defaultValue, AltIterator & actualIt, AltIterator actualEnd, OpenVarSet & openVars, TypeEnvironment & resultEnv, AssertionSet & resultNeed, AssertionSet & resultHave, const SymTab::Indexer & indexer, Cost & cost, OutputIterator out ) {
384                if ( TupleType * tupleType = dynamic_cast< TupleType * >( formalType ) ) {
385                        // formalType is a TupleType - group actuals into a TupleExpr whose type unifies with the TupleType
[907eccb]386                        std::list< Expression * > exprs;
[aefcc3b]387                        for ( Type * type : *tupleType ) {
[907eccb]388                                if ( ! instantiateArgument( type, defaultValue, actualIt, actualEnd, openVars, resultEnv, resultNeed, resultHave, indexer, cost, back_inserter( exprs ) ) ) {
389                                        deleteAll( exprs );
[aefcc3b]390                                        return false;
391                                }
392                        }
[907eccb]393                        *out++ = new TupleExpr( exprs );
[4c8621ac]394                } else if ( TypeInstType * ttype = Tuples::isTtype( formalType ) ) {
395                        // xxx - mixing default arguments with variadic??
396                        std::list< Expression * > exprs;
397                        for ( ; actualIt != actualEnd; ++actualIt ) {
398                                exprs.push_back( actualIt->expr->clone() );
399                                cost += actualIt->cost;
[53e3b4a]400                        }
[4c8621ac]401                        Expression * arg = nullptr;
402                        if ( exprs.size() == 1 && Tuples::isTtype( exprs.front()->get_result() ) ) {
403                                // the case where a ttype value is passed directly is special, e.g. for argument forwarding purposes
404                                // xxx - what if passing multiple arguments, last of which is ttype?
405                                // xxx - what would happen if unify was changed so that unifying tuple types flattened both before unifying lists? then pass in TupleType(ttype) below.
406                                arg = exprs.front();
407                        } else {
408                                arg = new TupleExpr( exprs );
409                        }
410                        assert( arg && arg->get_result() );
411                        if ( ! unify( ttype, arg->get_result(), resultEnv, resultNeed, resultHave, openVars, indexer ) ) {
412                                return false;
413                        }
414                        *out++ = arg;
415                } else if ( actualIt != actualEnd ) {
[aefcc3b]416                        // both actualType and formalType are atomic (non-tuple) types - if they unify
417                        // then accept actual as an argument, otherwise return false (fail to instantiate argument)
418                        Expression * actual = actualIt->expr;
419                        Type * actualType = actual->get_result();
[a61ad31]420
[aefcc3b]421                        PRINT(
422                                std::cerr << "formal type is ";
423                                formalType->print( std::cerr );
424                                std::cerr << std::endl << "actual type is ";
425                                actualType->print( std::cerr );
426                                std::cerr << std::endl;
427                        )
428                        if ( ! unify( formalType, actualType, resultEnv, resultNeed, resultHave, openVars, indexer ) ) {
[d1685588]429                                // std::cerr << "unify failed" << std::endl;
[aefcc3b]430                                return false;
431                        }
432                        // move the expression from the alternative to the output iterator
433                        *out++ = actual;
434                        actualIt->expr = nullptr;
435                        cost += actualIt->cost;
436                        ++actualIt;
437                } else {
438                        // End of actuals - Handle default values
439                        if ( SingleInit *si = dynamic_cast<SingleInit *>( defaultValue )) {
[064cb18]440                                if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( si->get_value() ) ) {
441                                        // so far, only constant expressions are accepted as default values
442                                        if ( ConstantExpr *cnstexpr = dynamic_cast<ConstantExpr *>( castExpr->get_arg() ) ) {
443                                                if ( Constant *cnst = dynamic_cast<Constant *>( cnstexpr->get_constant() ) ) {
444                                                        if ( unify( formalType, cnst->get_type(), resultEnv, resultNeed, resultHave, openVars, indexer ) ) {
445                                                                *out++ = cnstexpr->clone();
446                                                                return true;
447                                                        } // if
[aefcc3b]448                                                } // if
449                                        } // if
[064cb18]450                                }
[aefcc3b]451                        } // if
452                        return false;
453                } // if
454                return true;
455        }
456
457        bool AlternativeFinder::instantiateFunction( std::list< DeclarationWithType* >& formals, const AltList &actuals, bool isVarArgs, OpenVarSet& openVars, TypeEnvironment &resultEnv, AssertionSet &resultNeed, AssertionSet &resultHave, AltList & out ) {
[a32b204]458                simpleCombineEnvironments( actuals.begin(), actuals.end(), resultEnv );
459                // make sure we don't widen any existing bindings
460                for ( TypeEnvironment::iterator i = resultEnv.begin(); i != resultEnv.end(); ++i ) {
461                        i->allowWidening = false;
462                }
463                resultEnv.extractOpenVars( openVars );
464
[aefcc3b]465                // flatten actuals so that each actual has an atomic (non-tuple) type
466                AltList exploded;
[77971f6]467                Tuples::explode( actuals, indexer, back_inserter( exploded ) );
[aefcc3b]468
469                AltList::iterator actualExpr = exploded.begin();
470                AltList::iterator actualEnd = exploded.end();
471                for ( DeclarationWithType * formal : formals ) {
472                        // match flattened actuals with formal parameters - actuals will be grouped to match
473                        // with formals as appropriate
[89be1c68]474                        Cost cost = Cost::zero;
[aefcc3b]475                        std::list< Expression * > newExprs;
476                        ObjectDecl * obj = safe_dynamic_cast< ObjectDecl * >( formal );
477                        if ( ! instantiateArgument( obj->get_type(), obj->get_init(), actualExpr, actualEnd, openVars, resultEnv, resultNeed, resultHave, indexer, cost, back_inserter( newExprs ) ) ) {
478                                deleteAll( newExprs );
479                                return false;
[a32b204]480                        }
[aefcc3b]481                        // success - produce argument as a new alternative
482                        assert( newExprs.size() == 1 );
483                        out.push_back( Alternative( newExprs.front(), resultEnv, cost ) );
[a32b204]484                }
[aefcc3b]485                if ( actualExpr != actualEnd ) {
486                        // there are still actuals remaining, but we've run out of formal parameters to match against
487                        // this is okay only if the function is variadic
488                        if ( ! isVarArgs ) {
489                                return false;
490                        }
491                        out.splice( out.end(), exploded, actualExpr, actualEnd );
[a32b204]492                }
493                return true;
[d9a0e76]494        }
[51b7345]495
[89b686a]496        // /// Map of declaration uniqueIds (intended to be the assertions in an AssertionSet) to their parents and the number of times they've been included
497        //typedef std::unordered_map< UniqueId, std::unordered_map< UniqueId, unsigned > > AssertionParentSet;
[79970ed]498
[a1d7679]499        static const int recursionLimit = /*10*/ 4;  ///< Limit to depth of recursion satisfaction
[89b686a]500        //static const unsigned recursionParentLimit = 1;  ///< Limit to the number of times an assertion can recursively use itself
[51b7345]501
[a32b204]502        void addToIndexer( AssertionSet &assertSet, SymTab::Indexer &indexer ) {
503                for ( AssertionSet::iterator i = assertSet.begin(); i != assertSet.end(); ++i ) {
[6c3a988f]504                        if ( i->second.isUsed ) {
[a32b204]505                                i->first->accept( indexer );
506                        }
507                }
[d9a0e76]508        }
[79970ed]509
[a32b204]510        template< typename ForwardIterator, typename OutputIterator >
[79970ed]511        void inferRecursive( ForwardIterator begin, ForwardIterator end, const Alternative &newAlt, OpenVarSet &openVars, const SymTab::Indexer &decls, const AssertionSet &newNeed, /*const AssertionParentSet &needParents,*/
[ebf5689]512                                                 int level, const SymTab::Indexer &indexer, OutputIterator out ) {
[a32b204]513                if ( begin == end ) {
514                        if ( newNeed.empty() ) {
[6c3a988f]515                                PRINT(
516                                        std::cerr << "all assertions satisfied, output alternative: ";
517                                        newAlt.print( std::cerr );
518                                        std::cerr << std::endl;
519                                );
[a32b204]520                                *out++ = newAlt;
521                                return;
522                        } else if ( level >= recursionLimit ) {
523                                throw SemanticError( "Too many recursive assertions" );
524                        } else {
525                                AssertionSet newerNeed;
526                                PRINT(
527                                        std::cerr << "recursing with new set:" << std::endl;
528                                        printAssertionSet( newNeed, std::cerr, 8 );
[7c64920]529                                )
[89b686a]530                                inferRecursive( newNeed.begin(), newNeed.end(), newAlt, openVars, decls, newerNeed, /*needParents,*/ level+1, indexer, out );
[a32b204]531                                return;
532                        }
533                }
534
535                ForwardIterator cur = begin++;
[6c3a988f]536                if ( ! cur->second.isUsed ) {
[89b686a]537                        inferRecursive( begin, end, newAlt, openVars, decls, newNeed, /*needParents,*/ level, indexer, out );
[7933351]538                        return; // xxx - should this continue? previously this wasn't here, and it looks like it should be
[a32b204]539                }
540                DeclarationWithType *curDecl = cur->first;
[7933351]541
[d9a0e76]542                PRINT(
[a32b204]543                        std::cerr << "inferRecursive: assertion is ";
544                        curDecl->print( std::cerr );
545                        std::cerr << std::endl;
[7c64920]546                )
[0f19d763]547                std::list< DeclarationWithType* > candidates;
[a32b204]548                decls.lookupId( curDecl->get_name(), candidates );
[6ed1d4b]549///   if ( candidates.empty() ) { std::cerr << "no candidates!" << std::endl; }
[a32b204]550                for ( std::list< DeclarationWithType* >::const_iterator candidate = candidates.begin(); candidate != candidates.end(); ++candidate ) {
551                        PRINT(
[6ed1d4b]552                                std::cerr << "inferRecursive: candidate is ";
553                                (*candidate)->print( std::cerr );
554                                std::cerr << std::endl;
[7c64920]555                        )
[79970ed]556
[0f19d763]557                        AssertionSet newHave, newerNeed( newNeed );
[a32b204]558                        TypeEnvironment newEnv( newAlt.env );
559                        OpenVarSet newOpenVars( openVars );
560                        Type *adjType = (*candidate)->get_type()->clone();
561                        adjustExprType( adjType, newEnv, indexer );
562                        adjType->accept( global_renamer );
563                        PRINT(
564                                std::cerr << "unifying ";
565                                curDecl->get_type()->print( std::cerr );
566                                std::cerr << " with ";
567                                adjType->print( std::cerr );
568                                std::cerr << std::endl;
[7c64920]569                        )
[0f19d763]570                        if ( unify( curDecl->get_type(), adjType, newEnv, newerNeed, newHave, newOpenVars, indexer ) ) {
571                                PRINT(
572                                        std::cerr << "success!" << std::endl;
[a32b204]573                                )
[0f19d763]574                                SymTab::Indexer newDecls( decls );
575                                addToIndexer( newHave, newDecls );
576                                Alternative newerAlt( newAlt );
577                                newerAlt.env = newEnv;
578                                assert( (*candidate)->get_uniqueId() );
[22cad76]579                                DeclarationWithType *candDecl = static_cast< DeclarationWithType* >( Declaration::declFromId( (*candidate)->get_uniqueId() ) );
[6c3a988f]580
581                                // everything with an empty idChain was pulled in by the current assertion.
582                                // add current assertion's idChain + current assertion's ID so that the correct inferParameters can be found.
583                                for ( auto & a : newerNeed ) {
584                                        if ( a.second.idChain.empty() ) {
585                                                a.second.idChain = cur->second.idChain;
586                                                a.second.idChain.push_back( curDecl->get_uniqueId() );
587                                        }
588                                }
589
[89b686a]590                                //AssertionParentSet newNeedParents( needParents );
[22cad76]591                                // skip repeatingly-self-recursive assertion satisfaction
[89b686a]592                                // DOESN'T WORK: grandchild nodes conflict with their cousins
593                                //if ( newNeedParents[ curDecl->get_uniqueId() ][ candDecl->get_uniqueId() ]++ > recursionParentLimit ) continue;
[22cad76]594                                Expression *varExpr = new VariableExpr( candDecl );
[906e24d]595                                delete varExpr->get_result();
596                                varExpr->set_result( adjType->clone() );
[0f19d763]597                                PRINT(
[6ed1d4b]598                                        std::cerr << "satisfying assertion " << curDecl->get_uniqueId() << " ";
599                                        curDecl->print( std::cerr );
600                                        std::cerr << " with declaration " << (*candidate)->get_uniqueId() << " ";
601                                        (*candidate)->print( std::cerr );
602                                        std::cerr << std::endl;
[7c64920]603                                )
[0f19d763]604                                ApplicationExpr *appExpr = static_cast< ApplicationExpr* >( newerAlt.expr );
[6c3a988f]605                                // follow the current assertion's ID chain to find the correct set of inferred parameters to add the candidate to (i.e. the set of inferred parameters belonging to the entity which requested the assertion parameter).
606                                InferredParams * inferParameters = &appExpr->get_inferParams();
607                                for ( UniqueId id : cur->second.idChain ) {
608                                        inferParameters = (*inferParameters)[ id ].inferParams.get();
609                                }
[0f19d763]610                                // XXX: this is a memory leak, but adjType can't be deleted because it might contain assertions
[6c3a988f]611                                (*inferParameters)[ curDecl->get_uniqueId() ] = ParamEntry( (*candidate)->get_uniqueId(), adjType->clone(), curDecl->get_type()->clone(), varExpr );
[89b686a]612                                inferRecursive( begin, end, newerAlt, newOpenVars, newDecls, newerNeed, /*newNeedParents,*/ level, indexer, out );
[0f19d763]613                        } else {
614                                delete adjType;
615                        }
[a32b204]616                }
[d9a0e76]617        }
618
[a32b204]619        template< typename OutputIterator >
620        void AlternativeFinder::inferParameters( const AssertionSet &need, AssertionSet &have, const Alternative &newAlt, OpenVarSet &openVars, OutputIterator out ) {
[d9a0e76]621//      PRINT(
[6ed1d4b]622//          std::cerr << "inferParameters: assertions needed are" << std::endl;
623//          printAll( need, std::cerr, 8 );
[d9a0e76]624//          )
[a32b204]625                SymTab::Indexer decls( indexer );
[e4d829b]626                // PRINT(
627                //      std::cerr << "============= original indexer" << std::endl;
628                //      indexer.print( std::cerr );
629                //      std::cerr << "============= new indexer" << std::endl;
630                //      decls.print( std::cerr );
631                // )
[0f19d763]632                addToIndexer( have, decls );
[a32b204]633                AssertionSet newNeed;
[89b686a]634                //AssertionParentSet needParents;
635                inferRecursive( need.begin(), need.end(), newAlt, openVars, decls, newNeed, /*needParents,*/ 0, indexer, out );
[d9a0e76]636//      PRINT(
[6ed1d4b]637//          std::cerr << "declaration 14 is ";
[d9a0e76]638//          Declaration::declFromId
639//          *out++ = newAlt;
640//          )
641        }
642
[a32b204]643        template< typename OutputIterator >
[aefcc3b]644        void AlternativeFinder::makeFunctionAlternatives( const Alternative &func, FunctionType *funcType, const AltList &actualAlt, OutputIterator out ) {
[a32b204]645                OpenVarSet openVars;
646                AssertionSet resultNeed, resultHave;
647                TypeEnvironment resultEnv;
648                makeUnifiableVars( funcType, openVars, resultNeed );
[7f623d6f]649                resultEnv.add( funcType->get_forall() ); // add all type variables as open variables now so that those not used in the parameter list are still considered open
[aefcc3b]650                AltList instantiatedActuals; // filled by instantiate function
[53e3b4a]651                if ( targetType && ! targetType->isVoid() && ! funcType->get_returnVals().empty() ) {
[ea83e00a]652                        // attempt to narrow based on expected target type
653                        Type * returnType = funcType->get_returnVals().front()->get_type();
654                        if ( ! unify( returnType, targetType, resultEnv, resultNeed, resultHave, openVars, indexer ) ) {
655                                // unification failed, don't pursue this alternative
656                                return;
657                        }
658                }
659
[aefcc3b]660                if ( instantiateFunction( funcType->get_parameters(), actualAlt, funcType->get_isVarArgs(), openVars, resultEnv, resultNeed, resultHave, instantiatedActuals ) ) {
[a32b204]661                        ApplicationExpr *appExpr = new ApplicationExpr( func.expr->clone() );
[aefcc3b]662                        Alternative newAlt( appExpr, resultEnv, sumCost( instantiatedActuals ) );
663                        makeExprList( instantiatedActuals, appExpr->get_args() );
[a32b204]664                        PRINT(
[a61ad31]665                                std::cerr << "instantiate function success: " << appExpr << std::endl;
[6ed1d4b]666                                std::cerr << "need assertions:" << std::endl;
667                                printAssertionSet( resultNeed, std::cerr, 8 );
[7c64920]668                        )
[0f19d763]669                        inferParameters( resultNeed, resultHave, newAlt, openVars, out );
[d9a0e76]670                }
671        }
672
[a32b204]673        void AlternativeFinder::visit( UntypedExpr *untypedExpr ) {
674                bool doneInit = false;
675                AlternativeFinder funcOpFinder( indexer, env );
[d9a0e76]676
[6ed1d4b]677                AlternativeFinder funcFinder( indexer, env );
678
679                {
[70f89d00]680                        std::string fname = InitTweak::getFunctionName( untypedExpr );
681                        if ( fname == "&&" ) {
[2871210]682                                VoidType v = Type::Qualifiers();                // resolve to type void *
683                                PointerType pt( Type::Qualifiers(), v.clone() );
684                                UntypedExpr *vexpr = untypedExpr->clone();
[906e24d]685                                vexpr->set_result( pt.clone() );
[89be1c68]686                                alternatives.push_back( Alternative( vexpr, env, Cost::zero) );
[a32b204]687                                return;
688                        }
689                }
[d9a0e76]690
[a32b204]691                funcFinder.findWithAdjustment( untypedExpr->get_function() );
692                std::list< AlternativeFinder > argAlternatives;
693                findSubExprs( untypedExpr->begin_args(), untypedExpr->end_args(), back_inserter( argAlternatives ) );
[d9a0e76]694
[a32b204]695                std::list< AltList > possibilities;
696                combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
[d9a0e76]697
[5af62f1]698                // take care of possible tuple assignments
699                // if not tuple assignment, assignment is taken care of as a normal function call
700                Tuples::handleTupleAssignment( *this, untypedExpr, possibilities );
[d9a0e76]701
[a32b204]702                AltList candidates;
[91b8a17]703                SemanticError errors;
[b1bead1]704                for ( AltList::iterator func = funcFinder.alternatives.begin(); func != funcFinder.alternatives.end(); ++func ) {
[91b8a17]705                        try {
706                                PRINT(
707                                        std::cerr << "working on alternative: " << std::endl;
708                                        func->print( std::cerr, 8 );
709                                )
710                                // check if the type is pointer to function
[b1bead1]711                                if ( PointerType *pointer = dynamic_cast< PointerType* >( func->expr->get_result()->stripReferences() ) ) {
[91b8a17]712                                        if ( FunctionType *function = dynamic_cast< FunctionType* >( pointer->get_base() ) ) {
[b1bead1]713                                                referenceToRvalueConversion( func->expr );
[91b8a17]714                                                for ( std::list< AltList >::iterator actualAlt = possibilities.begin(); actualAlt != possibilities.end(); ++actualAlt ) {
715                                                        // XXX
716                                                        //Designators::check_alternative( function, *actualAlt );
717                                                        makeFunctionAlternatives( *func, function, *actualAlt, std::back_inserter( candidates ) );
718                                                }
[b1bead1]719                                        }
720                                } else if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( func->expr->get_result()->stripReferences() ) ) { // handle ftype (e.g. *? on function pointer)
721                                        referenceToRvalueConversion( func->expr );
722                                        EqvClass eqvClass;
723                                        if ( func->env.lookup( typeInst->get_name(), eqvClass ) && eqvClass.type ) {
724                                                if ( FunctionType *function = dynamic_cast< FunctionType* >( eqvClass.type ) ) {
725                                                        for ( std::list< AltList >::iterator actualAlt = possibilities.begin(); actualAlt != possibilities.end(); ++actualAlt ) {
726                                                                makeFunctionAlternatives( *func, function, *actualAlt, std::back_inserter( candidates ) );
727                                                        } // for
[a32b204]728                                                } // if
729                                        } // if
[91b8a17]730                                } else {
731                                        // seek a function operator that's compatible
732                                        if ( ! doneInit ) {
733                                                doneInit = true;
734                                                NameExpr *opExpr = new NameExpr( "?()" );
735                                                try {
736                                                        funcOpFinder.findWithAdjustment( opExpr );
737                                                } catch( SemanticError &e ) {
738                                                        // it's ok if there aren't any defined function ops
739                                                }
740                                                PRINT(
741                                                        std::cerr << "known function ops:" << std::endl;
742                                                        printAlts( funcOpFinder.alternatives, std::cerr, 8 );
743                                                )
[a32b204]744                                        }
745
[b1bead1]746                                        for ( AltList::iterator funcOp = funcOpFinder.alternatives.begin(); funcOp != funcOpFinder.alternatives.end(); ++funcOp ) {
[91b8a17]747                                                // check if the type is pointer to function
[b1bead1]748                                                if ( PointerType *pointer = dynamic_cast< PointerType* >( funcOp->expr->get_result()->stripReferences() ) ) {
[91b8a17]749                                                        if ( FunctionType *function = dynamic_cast< FunctionType* >( pointer->get_base() ) ) {
[b1bead1]750                                                                referenceToRvalueConversion( funcOp->expr );
[91b8a17]751                                                                for ( std::list< AltList >::iterator actualAlt = possibilities.begin(); actualAlt != possibilities.end(); ++actualAlt ) {
752                                                                        AltList currentAlt;
753                                                                        currentAlt.push_back( *func );
754                                                                        currentAlt.insert( currentAlt.end(), actualAlt->begin(), actualAlt->end() );
755                                                                        makeFunctionAlternatives( *funcOp, function, currentAlt, std::back_inserter( candidates ) );
756                                                                } // for
757                                                        } // if
[a32b204]758                                                } // if
[91b8a17]759                                        } // for
760                                } // if
761                        } catch ( SemanticError &e ) {
762                                errors.append( e );
763                        }
[a32b204]764                } // for
765
[91b8a17]766                // Implement SFINAE; resolution errors are only errors if there aren't any non-erroneous resolutions
767                if ( candidates.empty() && ! errors.isEmpty() ) { throw errors; }
768
[4b0f997]769                // compute conversionsion costs
[a32b204]770                for ( AltList::iterator withFunc = candidates.begin(); withFunc != candidates.end(); ++withFunc ) {
771                        Cost cvtCost = computeConversionCost( *withFunc, indexer );
772
773                        PRINT(
[8f7cea1]774                                ApplicationExpr *appExpr = safe_dynamic_cast< ApplicationExpr* >( withFunc->expr );
[906e24d]775                                PointerType *pointer = safe_dynamic_cast< PointerType* >( appExpr->get_function()->get_result() );
[8f7cea1]776                                FunctionType *function = safe_dynamic_cast< FunctionType* >( pointer->get_base() );
[a61ad31]777                                std::cerr << "Case +++++++++++++ " << appExpr->get_function() << std::endl;
[6ed1d4b]778                                std::cerr << "formals are:" << std::endl;
779                                printAll( function->get_parameters(), std::cerr, 8 );
780                                std::cerr << "actuals are:" << std::endl;
781                                printAll( appExpr->get_args(), std::cerr, 8 );
782                                std::cerr << "bindings are:" << std::endl;
783                                withFunc->env.print( std::cerr, 8 );
784                                std::cerr << "cost of conversion is:" << cvtCost << std::endl;
[7c64920]785                        )
786                        if ( cvtCost != Cost::infinity ) {
787                                withFunc->cvtCost = cvtCost;
788                                alternatives.push_back( *withFunc );
789                        } // if
[a32b204]790                } // for
[4b0f997]791
[a32b204]792                candidates.clear();
793                candidates.splice( candidates.end(), alternatives );
794
795                findMinCost( candidates.begin(), candidates.end(), std::back_inserter( alternatives ) );
[ea83e00a]796
[ca946a4]797                // function may return struct or union value, in which case we need to add alternatives for implicit
798                // conversions to each of the anonymous members, must happen after findMinCost since anon conversions
799                // are never the cheapest expression
800                for ( const Alternative & alt : alternatives ) {
801                        addAnonConversions( alt );
802                }
803
[ea83e00a]804                if ( alternatives.empty() && targetType && ! targetType->isVoid() ) {
805                        // xxx - this is a temporary hack. If resolution is unsuccessful with a target type, try again without a
806                        // target type, since it will sometimes succeed when it wouldn't easily with target type binding. For example,
807                        //   forall( otype T ) lvalue T ?[?]( T *, ptrdiff_t );
808                        //   const char * x = "hello world";
809                        //   unsigned char ch = x[0];
810                        // Fails with simple return type binding. First, T is bound to unsigned char, then (x: const char *) is unified
811                        // with unsigned char *, which fails because pointer base types must be unified exactly. The new resolver should
812                        // fix this issue in a more robust way.
813                        targetType = nullptr;
814                        visit( untypedExpr );
815                }
[a32b204]816        }
817
818        bool isLvalue( Expression *expr ) {
[906e24d]819                // xxx - recurse into tuples?
[a61ad31]820                return expr->has_result() && ( expr->get_result()->get_lvalue() || dynamic_cast< ReferenceType * >( expr->get_result() ) );
[a32b204]821        }
822
823        void AlternativeFinder::visit( AddressExpr *addressExpr ) {
824                AlternativeFinder finder( indexer, env );
825                finder.find( addressExpr->get_arg() );
826                for ( std::list< Alternative >::iterator i = finder.alternatives.begin(); i != finder.alternatives.end(); ++i ) {
827                        if ( isLvalue( i->expr ) ) {
828                                alternatives.push_back( Alternative( new AddressExpr( i->expr->clone() ), i->env, i->cost ) );
829                        } // if
830                } // for
831        }
832
[62423350]833        Expression * restructureCast( Expression * argExpr, Type * toType ) {
[e6cee92]834                if ( argExpr->get_result()->size() > 1 && ! toType->isVoid() && ! dynamic_cast<ReferenceType *>( toType ) ) {
835                        // Argument expression is a tuple and the target type is not void and not a reference type.
836                        // Cast each member of the tuple to its corresponding target type, producing the tuple of those
837                        // cast expressions. If there are more components of the tuple than components in the target type,
838                        // then excess components do not come out in the result expression (but UniqueExprs ensure that
839                        // side effects will still be done).
[62423350]840                        if ( Tuples::maybeImpure( argExpr ) && ! dynamic_cast< UniqueExpr * >( argExpr ) ) {
841                                // expressions which may contain side effects require a single unique instance of the expression.
842                                argExpr = new UniqueExpr( argExpr );
843                        }
844                        std::list< Expression * > componentExprs;
845                        for ( unsigned int i = 0; i < toType->size(); i++ ) {
846                                // cast each component
847                                TupleIndexExpr * idx = new TupleIndexExpr( argExpr->clone(), i );
848                                componentExprs.push_back( restructureCast( idx, toType->getComponent( i ) ) );
849                        }
850                        delete argExpr;
851                        assert( componentExprs.size() > 0 );
852                        // produce the tuple of casts
853                        return new TupleExpr( componentExprs );
854                } else {
855                        // handle normally
856                        return new CastExpr( argExpr, toType->clone() );
857                }
858        }
859
[a32b204]860        void AlternativeFinder::visit( CastExpr *castExpr ) {
[906e24d]861                Type *& toType = castExpr->get_result();
[7933351]862                assert( toType );
[906e24d]863                toType = resolveTypeof( toType, indexer );
864                SymTab::validateType( toType, &indexer );
865                adjustExprType( toType, env, indexer );
[a32b204]866
867                AlternativeFinder finder( indexer, env );
[7933351]868                finder.targetType = toType;
[a32b204]869                finder.findWithAdjustment( castExpr->get_arg() );
870
871                AltList candidates;
872                for ( std::list< Alternative >::iterator i = finder.alternatives.begin(); i != finder.alternatives.end(); ++i ) {
873                        AssertionSet needAssertions, haveAssertions;
874                        OpenVarSet openVars;
875
876                        // It's possible that a cast can throw away some values in a multiply-valued expression.  (An example is a
877                        // cast-to-void, which casts from one value to zero.)  Figure out the prefix of the subexpression results
878                        // that are cast directly.  The candidate is invalid if it has fewer results than there are types to cast
879                        // to.
[b1bead1]880                        int discardedValues = i->expr->get_result()->size() - castExpr->get_result()->size();
[a32b204]881                        if ( discardedValues < 0 ) continue;
[7933351]882                        // xxx - may need to go into tuple types and extract relevant types and use unifyList. Note that currently, this does not
883                        // allow casting a tuple to an atomic type (e.g. (int)([1, 2, 3]))
[adcdd2f]884                        // unification run for side-effects
[b1bead1]885                        unify( castExpr->get_result(), i->expr->get_result(), i->env, needAssertions, haveAssertions, openVars, indexer );
886                        Cost thisCost = castCost( i->expr->get_result(), castExpr->get_result(), indexer, i->env );
[a32b204]887                        if ( thisCost != Cost::infinity ) {
888                                // count one safe conversion for each value that is thrown away
[89be1c68]889                                thisCost.incSafe( discardedValues );
[7933351]890
[62423350]891                                candidates.push_back( Alternative( restructureCast( i->expr->clone(), toType ), i->env, i->cost, thisCost ) );
[a32b204]892                        } // if
893                } // for
894
895                // findMinCost selects the alternatives with the lowest "cost" members, but has the side effect of copying the
896                // cvtCost member to the cost member (since the old cost is now irrelevant).  Thus, calling findMinCost twice
897                // selects first based on argument cost, then on conversion cost.
898                AltList minArgCost;
899                findMinCost( candidates.begin(), candidates.end(), std::back_inserter( minArgCost ) );
900                findMinCost( minArgCost.begin(), minArgCost.end(), std::back_inserter( alternatives ) );
901        }
902
[a5f0529]903        void AlternativeFinder::visit( VirtualCastExpr * castExpr ) {
904                assertf( castExpr->get_result(), "Implicate virtual cast targets not yet supported." );
905                AlternativeFinder finder( indexer, env );
906                // don't prune here, since it's guaranteed all alternatives will have the same type
907                // (giving the alternatives different types is half of the point of ConstructorExpr nodes)
908                finder.findWithAdjustment( castExpr->get_arg(), false );
909                for ( Alternative & alt : finder.alternatives ) {
910                        alternatives.push_back( Alternative(
911                                new VirtualCastExpr( alt.expr->clone(), castExpr->get_result()->clone() ),
912                                alt.env, alt.cost ) );
913                }
914        }
915
[a32b204]916        void AlternativeFinder::visit( UntypedMemberExpr *memberExpr ) {
917                AlternativeFinder funcFinder( indexer, env );
918                funcFinder.findWithAdjustment( memberExpr->get_aggregate() );
919                for ( AltList::const_iterator agg = funcFinder.alternatives.begin(); agg != funcFinder.alternatives.end(); ++agg ) {
[a61ad31]920                        // 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
921                        std::unique_ptr<Expression> aggrExpr( agg->expr->clone() );
922                        Type * aggrType = aggrExpr->get_result();
923                        if ( dynamic_cast< ReferenceType * >( aggrType ) ) {
924                                aggrType = aggrType->stripReferences();
925                                aggrExpr.reset( new CastExpr( aggrExpr.release(), aggrType->clone() ) );
926                        }
927                        // find member of the given type
928                        if ( StructInstType *structInst = dynamic_cast< StructInstType* >( aggrExpr->get_result() ) ) {
929                                addAggMembers( structInst, aggrExpr.get(), agg->cost, agg->env, memberExpr->get_member() );
930                        } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( aggrExpr->get_result() ) ) {
931                                addAggMembers( unionInst, aggrExpr.get(), agg->cost, agg->env, memberExpr->get_member() );
932                        } else if ( TupleType * tupleType = dynamic_cast< TupleType * >( aggrExpr->get_result() ) ) {
933                                addTupleMembers( tupleType, aggrExpr.get(), agg->cost, agg->env, memberExpr->get_member() );
[a32b204]934                        } // if
935                } // for
936        }
937
938        void AlternativeFinder::visit( MemberExpr *memberExpr ) {
939                alternatives.push_back( Alternative( memberExpr->clone(), env, Cost::zero ) );
940        }
941
942        void AlternativeFinder::visit( NameExpr *nameExpr ) {
943                std::list< DeclarationWithType* > declList;
944                indexer.lookupId( nameExpr->get_name(), declList );
945                PRINT( std::cerr << "nameExpr is " << nameExpr->get_name() << std::endl; )
[0f19d763]946                for ( std::list< DeclarationWithType* >::iterator i = declList.begin(); i != declList.end(); ++i ) {
947                        VariableExpr newExpr( *i, nameExpr->get_argName() );
[89be1c68]948                        alternatives.push_back( Alternative( newExpr.clone(), env, Cost::zero ) );
[0f19d763]949                        PRINT(
950                                std::cerr << "decl is ";
951                                (*i)->print( std::cerr );
952                                std::cerr << std::endl;
953                                std::cerr << "newExpr is ";
954                                newExpr.print( std::cerr );
955                                std::cerr << std::endl;
[7c64920]956                        )
[0f19d763]957                        renameTypes( alternatives.back().expr );
[4b0f997]958                        addAnonConversions( alternatives.back() ); // add anonymous member interpretations whenever an aggregate value type is seen as a name expression.
[0f19d763]959                } // for
[a32b204]960        }
961
962        void AlternativeFinder::visit( VariableExpr *variableExpr ) {
[85517ddb]963                // not sufficient to clone here, because variable's type may have changed
964                // since the VariableExpr was originally created.
965                alternatives.push_back( Alternative( new VariableExpr( variableExpr->get_var() ), env, Cost::zero ) );
[a32b204]966        }
967
968        void AlternativeFinder::visit( ConstantExpr *constantExpr ) {
969                alternatives.push_back( Alternative( constantExpr->clone(), env, Cost::zero ) );
970        }
971
972        void AlternativeFinder::visit( SizeofExpr *sizeofExpr ) {
973                if ( sizeofExpr->get_isType() ) {
[85517ddb]974                        // xxx - resolveTypeof?
[a32b204]975                        alternatives.push_back( Alternative( sizeofExpr->clone(), env, Cost::zero ) );
976                } else {
977                        // find all alternatives for the argument to sizeof
978                        AlternativeFinder finder( indexer, env );
979                        finder.find( sizeofExpr->get_expr() );
980                        // find the lowest cost alternative among the alternatives, otherwise ambiguous
981                        AltList winners;
982                        findMinCost( finder.alternatives.begin(), finder.alternatives.end(), back_inserter( winners ) );
983                        if ( winners.size() != 1 ) {
984                                throw SemanticError( "Ambiguous expression in sizeof operand: ", sizeofExpr->get_expr() );
985                        } // if
986                        // return the lowest cost alternative for the argument
987                        Alternative &choice = winners.front();
988                        alternatives.push_back( Alternative( new SizeofExpr( choice.expr->clone() ), choice.env, Cost::zero ) );
[47534159]989                } // if
990        }
991
992        void AlternativeFinder::visit( AlignofExpr *alignofExpr ) {
993                if ( alignofExpr->get_isType() ) {
[85517ddb]994                        // xxx - resolveTypeof?
[47534159]995                        alternatives.push_back( Alternative( alignofExpr->clone(), env, Cost::zero ) );
996                } else {
997                        // find all alternatives for the argument to sizeof
998                        AlternativeFinder finder( indexer, env );
999                        finder.find( alignofExpr->get_expr() );
1000                        // find the lowest cost alternative among the alternatives, otherwise ambiguous
1001                        AltList winners;
1002                        findMinCost( finder.alternatives.begin(), finder.alternatives.end(), back_inserter( winners ) );
1003                        if ( winners.size() != 1 ) {
1004                                throw SemanticError( "Ambiguous expression in alignof operand: ", alignofExpr->get_expr() );
1005                        } // if
1006                        // return the lowest cost alternative for the argument
1007                        Alternative &choice = winners.front();
1008                        alternatives.push_back( Alternative( new AlignofExpr( choice.expr->clone() ), choice.env, Cost::zero ) );
[a32b204]1009                } // if
1010        }
1011
[2a4b088]1012        template< typename StructOrUnionType >
1013        void AlternativeFinder::addOffsetof( StructOrUnionType *aggInst, const std::string &name ) {
1014                std::list< Declaration* > members;
1015                aggInst->lookup( name, members );
1016                for ( std::list< Declaration* >::const_iterator i = members.begin(); i != members.end(); ++i ) {
1017                        if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType* >( *i ) ) {
[79970ed]1018                                alternatives.push_back( Alternative( new OffsetofExpr( aggInst->clone(), dwt ), env, Cost::zero ) );
[2a4b088]1019                                renameTypes( alternatives.back().expr );
1020                        } else {
1021                                assert( false );
1022                        }
1023                }
1024        }
[6ed1d4b]1025
[2a4b088]1026        void AlternativeFinder::visit( UntypedOffsetofExpr *offsetofExpr ) {
1027                AlternativeFinder funcFinder( indexer, env );
[85517ddb]1028                // xxx - resolveTypeof?
[2a4b088]1029                if ( StructInstType *structInst = dynamic_cast< StructInstType* >( offsetofExpr->get_type() ) ) {
1030                        addOffsetof( structInst, offsetofExpr->get_member() );
1031                } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( offsetofExpr->get_type() ) ) {
1032                        addOffsetof( unionInst, offsetofExpr->get_member() );
1033                }
1034        }
[6ed1d4b]1035
[25a054f]1036        void AlternativeFinder::visit( OffsetofExpr *offsetofExpr ) {
1037                alternatives.push_back( Alternative( offsetofExpr->clone(), env, Cost::zero ) );
[afc1045]1038        }
1039
1040        void AlternativeFinder::visit( OffsetPackExpr *offsetPackExpr ) {
1041                alternatives.push_back( Alternative( offsetPackExpr->clone(), env, Cost::zero ) );
[25a054f]1042        }
1043
[a32b204]1044        void AlternativeFinder::resolveAttr( DeclarationWithType *funcDecl, FunctionType *function, Type *argType, const TypeEnvironment &env ) {
1045                // assume no polymorphism
1046                // assume no implicit conversions
1047                assert( function->get_parameters().size() == 1 );
1048                PRINT(
[6ed1d4b]1049                        std::cerr << "resolvAttr: funcDecl is ";
1050                        funcDecl->print( std::cerr );
1051                        std::cerr << " argType is ";
1052                        argType->print( std::cerr );
1053                        std::cerr << std::endl;
[7c64920]1054                )
1055                if ( typesCompatibleIgnoreQualifiers( argType, function->get_parameters().front()->get_type(), indexer, env ) ) {
1056                        alternatives.push_back( Alternative( new AttrExpr( new VariableExpr( funcDecl ), argType->clone() ), env, Cost::zero ) );
1057                        for ( std::list< DeclarationWithType* >::iterator i = function->get_returnVals().begin(); i != function->get_returnVals().end(); ++i ) {
[906e24d]1058                                alternatives.back().expr->set_result( (*i)->get_type()->clone() );
[7c64920]1059                        } // for
1060                } // if
[a32b204]1061        }
1062
1063        void AlternativeFinder::visit( AttrExpr *attrExpr ) {
1064                // assume no 'pointer-to-attribute'
1065                NameExpr *nameExpr = dynamic_cast< NameExpr* >( attrExpr->get_attr() );
1066                assert( nameExpr );
1067                std::list< DeclarationWithType* > attrList;
1068                indexer.lookupId( nameExpr->get_name(), attrList );
1069                if ( attrExpr->get_isType() || attrExpr->get_expr() ) {
1070                        for ( std::list< DeclarationWithType* >::iterator i = attrList.begin(); i != attrList.end(); ++i ) {
1071                                // check if the type is function
1072                                if ( FunctionType *function = dynamic_cast< FunctionType* >( (*i)->get_type() ) ) {
1073                                        // assume exactly one parameter
1074                                        if ( function->get_parameters().size() == 1 ) {
1075                                                if ( attrExpr->get_isType() ) {
1076                                                        resolveAttr( *i, function, attrExpr->get_type(), env );
1077                                                } else {
1078                                                        AlternativeFinder finder( indexer, env );
1079                                                        finder.find( attrExpr->get_expr() );
1080                                                        for ( AltList::iterator choice = finder.alternatives.begin(); choice != finder.alternatives.end(); ++choice ) {
[906e24d]1081                                                                if ( choice->expr->get_result()->size() == 1 ) {
1082                                                                        resolveAttr(*i, function, choice->expr->get_result(), choice->env );
[a32b204]1083                                                                } // fi
1084                                                        } // for
1085                                                } // if
1086                                        } // if
1087                                } // if
1088                        } // for
1089                } else {
1090                        for ( std::list< DeclarationWithType* >::iterator i = attrList.begin(); i != attrList.end(); ++i ) {
1091                                VariableExpr newExpr( *i );
[89be1c68]1092                                alternatives.push_back( Alternative( newExpr.clone(), env, Cost::zero ) );
[a32b204]1093                                renameTypes( alternatives.back().expr );
1094                        } // for
1095                } // if
1096        }
1097
1098        void AlternativeFinder::visit( LogicalExpr *logicalExpr ) {
1099                AlternativeFinder firstFinder( indexer, env );
1100                firstFinder.findWithAdjustment( logicalExpr->get_arg1() );
1101                for ( AltList::const_iterator first = firstFinder.alternatives.begin(); first != firstFinder.alternatives.end(); ++first ) {
1102                        AlternativeFinder secondFinder( indexer, first->env );
1103                        secondFinder.findWithAdjustment( logicalExpr->get_arg2() );
1104                        for ( AltList::const_iterator second = secondFinder.alternatives.begin(); second != secondFinder.alternatives.end(); ++second ) {
1105                                LogicalExpr *newExpr = new LogicalExpr( first->expr->clone(), second->expr->clone(), logicalExpr->get_isAnd() );
1106                                alternatives.push_back( Alternative( newExpr, second->env, first->cost + second->cost ) );
[d9a0e76]1107                        }
1108                }
1109        }
[51b7345]1110
[a32b204]1111        void AlternativeFinder::visit( ConditionalExpr *conditionalExpr ) {
[32b8144]1112                // find alternatives for condition
[a32b204]1113                AlternativeFinder firstFinder( indexer, env );
1114                firstFinder.findWithAdjustment( conditionalExpr->get_arg1() );
1115                for ( AltList::const_iterator first = firstFinder.alternatives.begin(); first != firstFinder.alternatives.end(); ++first ) {
[32b8144]1116                        // find alternatives for true expression
[a32b204]1117                        AlternativeFinder secondFinder( indexer, first->env );
1118                        secondFinder.findWithAdjustment( conditionalExpr->get_arg2() );
1119                        for ( AltList::const_iterator second = secondFinder.alternatives.begin(); second != secondFinder.alternatives.end(); ++second ) {
[32b8144]1120                                // find alterantives for false expression
[a32b204]1121                                AlternativeFinder thirdFinder( indexer, second->env );
1122                                thirdFinder.findWithAdjustment( conditionalExpr->get_arg3() );
1123                                for ( AltList::const_iterator third = thirdFinder.alternatives.begin(); third != thirdFinder.alternatives.end(); ++third ) {
[32b8144]1124                                        // unify true and false types, then infer parameters to produce new alternatives
[a32b204]1125                                        OpenVarSet openVars;
1126                                        AssertionSet needAssertions, haveAssertions;
1127                                        Alternative newAlt( 0, third->env, first->cost + second->cost + third->cost );
[668e971a]1128                                        Type* commonType = nullptr;
[906e24d]1129                                        if ( unify( second->expr->get_result(), third->expr->get_result(), newAlt.env, needAssertions, haveAssertions, openVars, indexer, commonType ) ) {
[a32b204]1130                                                ConditionalExpr *newExpr = new ConditionalExpr( first->expr->clone(), second->expr->clone(), third->expr->clone() );
[906e24d]1131                                                newExpr->set_result( commonType ? commonType : second->expr->get_result()->clone() );
[a32b204]1132                                                newAlt.expr = newExpr;
1133                                                inferParameters( needAssertions, haveAssertions, newAlt, openVars, back_inserter( alternatives ) );
1134                                        } // if
1135                                } // for
1136                        } // for
1137                } // for
1138        }
1139
1140        void AlternativeFinder::visit( CommaExpr *commaExpr ) {
1141                TypeEnvironment newEnv( env );
1142                Expression *newFirstArg = resolveInVoidContext( commaExpr->get_arg1(), indexer, newEnv );
1143                AlternativeFinder secondFinder( indexer, newEnv );
1144                secondFinder.findWithAdjustment( commaExpr->get_arg2() );
1145                for ( AltList::const_iterator alt = secondFinder.alternatives.begin(); alt != secondFinder.alternatives.end(); ++alt ) {
1146                        alternatives.push_back( Alternative( new CommaExpr( newFirstArg->clone(), alt->expr->clone() ), alt->env, alt->cost ) );
1147                } // for
1148                delete newFirstArg;
1149        }
1150
[32b8144]1151        void AlternativeFinder::visit( RangeExpr * rangeExpr ) {
1152                // resolve low and high, accept alternatives whose low and high types unify
1153                AlternativeFinder firstFinder( indexer, env );
1154                firstFinder.findWithAdjustment( rangeExpr->get_low() );
1155                for ( AltList::const_iterator first = firstFinder.alternatives.begin(); first != firstFinder.alternatives.end(); ++first ) {
1156                        AlternativeFinder secondFinder( indexer, first->env );
1157                        secondFinder.findWithAdjustment( rangeExpr->get_high() );
1158                        for ( AltList::const_iterator second = secondFinder.alternatives.begin(); second != secondFinder.alternatives.end(); ++second ) {
1159                                OpenVarSet openVars;
1160                                AssertionSet needAssertions, haveAssertions;
1161                                Alternative newAlt( 0, second->env, first->cost + second->cost );
1162                                Type* commonType = nullptr;
1163                                if ( unify( first->expr->get_result(), second->expr->get_result(), newAlt.env, needAssertions, haveAssertions, openVars, indexer, commonType ) ) {
1164                                        RangeExpr *newExpr = new RangeExpr( first->expr->clone(), second->expr->clone() );
1165                                        newExpr->set_result( commonType ? commonType : first->expr->get_result()->clone() );
1166                                        newAlt.expr = newExpr;
1167                                        inferParameters( needAssertions, haveAssertions, newAlt, openVars, back_inserter( alternatives ) );
1168                                } // if
1169                        } // for
1170                } // for
1171        }
1172
[907eccb]1173        void AlternativeFinder::visit( UntypedTupleExpr *tupleExpr ) {
[a32b204]1174                std::list< AlternativeFinder > subExprAlternatives;
1175                findSubExprs( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end(), back_inserter( subExprAlternatives ) );
1176                std::list< AltList > possibilities;
1177                combos( subExprAlternatives.begin(), subExprAlternatives.end(), back_inserter( possibilities ) );
1178                for ( std::list< AltList >::const_iterator i = possibilities.begin(); i != possibilities.end(); ++i ) {
[907eccb]1179                        std::list< Expression * > exprs;
1180                        makeExprList( *i, exprs );
[a32b204]1181
1182                        TypeEnvironment compositeEnv;
1183                        simpleCombineEnvironments( i->begin(), i->end(), compositeEnv );
[907eccb]1184                        alternatives.push_back( Alternative( new TupleExpr( exprs ) , compositeEnv, sumCost( *i ) ) );
[a32b204]1185                } // for
[d9a0e76]1186        }
[dc2e7e0]1187
[907eccb]1188        void AlternativeFinder::visit( TupleExpr *tupleExpr ) {
1189                alternatives.push_back( Alternative( tupleExpr->clone(), env, Cost::zero ) );
1190        }
1191
[dc2e7e0]1192        void AlternativeFinder::visit( ImplicitCopyCtorExpr * impCpCtorExpr ) {
1193                alternatives.push_back( Alternative( impCpCtorExpr->clone(), env, Cost::zero ) );
1194        }
[b6fe7e6]1195
1196        void AlternativeFinder::visit( ConstructorExpr * ctorExpr ) {
1197                AlternativeFinder finder( indexer, env );
1198                // don't prune here, since it's guaranteed all alternatives will have the same type
1199                // (giving the alternatives different types is half of the point of ConstructorExpr nodes)
1200                finder.findWithAdjustment( ctorExpr->get_callExpr(), false );
1201                for ( Alternative & alt : finder.alternatives ) {
1202                        alternatives.push_back( Alternative( new ConstructorExpr( alt.expr->clone() ), alt.env, alt.cost ) );
1203                }
1204        }
[8f7cea1]1205
1206        void AlternativeFinder::visit( TupleIndexExpr *tupleExpr ) {
1207                alternatives.push_back( Alternative( tupleExpr->clone(), env, Cost::zero ) );
1208        }
[aa8f9df]1209
1210        void AlternativeFinder::visit( TupleAssignExpr *tupleAssignExpr ) {
1211                alternatives.push_back( Alternative( tupleAssignExpr->clone(), env, Cost::zero ) );
1212        }
[bf32bb8]1213
1214        void AlternativeFinder::visit( UniqueExpr *unqExpr ) {
1215                AlternativeFinder finder( indexer, env );
1216                finder.findWithAdjustment( unqExpr->get_expr() );
1217                for ( Alternative & alt : finder.alternatives ) {
[141b786]1218                        // ensure that the id is passed on to the UniqueExpr alternative so that the expressions are "linked"
[77971f6]1219                        UniqueExpr * newUnqExpr = new UniqueExpr( alt.expr->clone(), unqExpr->get_id() );
[141b786]1220                        alternatives.push_back( Alternative( newUnqExpr, alt.env, alt.cost ) );
[bf32bb8]1221                }
1222        }
1223
[722617d]1224        void AlternativeFinder::visit( StmtExpr *stmtExpr ) {
1225                StmtExpr * newStmtExpr = stmtExpr->clone();
1226                ResolvExpr::resolveStmtExpr( newStmtExpr, indexer );
1227                // xxx - this env is almost certainly wrong, and needs to somehow contain the combined environments from all of the statements in the stmtExpr...
1228                alternatives.push_back( Alternative( newStmtExpr, env, Cost::zero ) );
1229        }
1230
[e4d829b]1231        void AlternativeFinder::visit( UntypedInitExpr *initExpr ) {
[62423350]1232                // handle each option like a cast
[e4d829b]1233                AltList candidates;
[62423350]1234                PRINT( std::cerr << "untyped init expr: " << initExpr << std::endl; )
[e4d829b]1235                // O(N^2) checks of d-types with e-types
[62423350]1236                for ( InitAlternative & initAlt : initExpr->get_initAlts() ) {
1237                        Type * toType = resolveTypeof( initAlt.type, indexer );
1238                        SymTab::validateType( toType, &indexer );
1239                        adjustExprType( toType, env, indexer );
1240                        // Ideally the call to findWithAdjustment could be moved out of the loop, but unfortunately it currently has to occur inside or else
1241                        // polymorphic return types are not properly bound to the initialization type, since return type variables are only open for the duration of resolving
1242                        // the UntypedExpr. This is only actually an issue in initialization contexts that allow more than one possible initialization type, but it is still suboptimal.
1243                        AlternativeFinder finder( indexer, env );
1244                        finder.targetType = toType;
1245                        finder.findWithAdjustment( initExpr->get_expr() );
1246                        for ( Alternative & alt : finder.get_alternatives() ) {
1247                                TypeEnvironment newEnv( alt.env );
[e4d829b]1248                                AssertionSet needAssertions, haveAssertions;
[62423350]1249                                OpenVarSet openVars;  // find things in env that don't have a "representative type" and claim those are open vars?
1250                                PRINT( std::cerr << "  @ " << toType << " " << initAlt.designation << std::endl; )
[e4d829b]1251                                // It's possible that a cast can throw away some values in a multiply-valued expression.  (An example is a
1252                                // cast-to-void, which casts from one value to zero.)  Figure out the prefix of the subexpression results
1253                                // that are cast directly.  The candidate is invalid if it has fewer results than there are types to cast
1254                                // to.
[62423350]1255                                int discardedValues = alt.expr->get_result()->size() - toType->size();
[e4d829b]1256                                if ( discardedValues < 0 ) continue;
1257                                // xxx - may need to go into tuple types and extract relevant types and use unifyList. Note that currently, this does not
1258                                // allow casting a tuple to an atomic type (e.g. (int)([1, 2, 3]))
1259                                // unification run for side-effects
[62423350]1260                                unify( toType, alt.expr->get_result(), newEnv, needAssertions, haveAssertions, openVars, indexer ); // xxx - do some inspecting on this line... why isn't result bound to initAlt.type??
[e4d829b]1261
[62423350]1262                                Cost thisCost = castCost( alt.expr->get_result(), toType, indexer, newEnv );
[e4d829b]1263                                if ( thisCost != Cost::infinity ) {
1264                                        // count one safe conversion for each value that is thrown away
[89be1c68]1265                                        thisCost.incSafe( discardedValues );
[62423350]1266                                        candidates.push_back( Alternative( new InitExpr( restructureCast( alt.expr->clone(), toType ), initAlt.designation->clone() ), newEnv, alt.cost, thisCost ) );
[e4d829b]1267                                }
1268                        }
1269                }
1270
1271                // findMinCost selects the alternatives with the lowest "cost" members, but has the side effect of copying the
1272                // cvtCost member to the cost member (since the old cost is now irrelevant).  Thus, calling findMinCost twice
1273                // selects first based on argument cost, then on conversion cost.
1274                AltList minArgCost;
1275                findMinCost( candidates.begin(), candidates.end(), std::back_inserter( minArgCost ) );
1276                findMinCost( minArgCost.begin(), minArgCost.end(), std::back_inserter( alternatives ) );
1277        }
[51b7345]1278} // namespace ResolvExpr
[a32b204]1279
1280// Local Variables: //
1281// tab-width: 4 //
1282// mode: c++ //
1283// compile-command: "make install" //
1284// End: //
Note: See TracBrowser for help on using the repository browser.