source: src/ResolvExpr/AlternativeFinder.cc @ f1b1e4c

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since f1b1e4c was 70f89d00, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

function scoped const objects can be constructed, add missing copy constructors to Initializer.cc

  • Property mode set to 100644
File size: 41.0 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
[6ed1d4b]11// Last Modified By : Rob Schluntz
[dc2e7e0]12// Last Modified On : Wed Apr 20 14:24:03 2016
[6ed1d4b]13// Update Count     : 24
[a32b204]14//
15
[51b7345]16#include <list>
17#include <iterator>
18#include <algorithm>
19#include <functional>
20#include <cassert>
21
22#include "AlternativeFinder.h"
23#include "Alternative.h"
24#include "Cost.h"
25#include "typeops.h"
26#include "Unify.h"
27#include "RenameVars.h"
28#include "SynTree/Type.h"
29#include "SynTree/Declaration.h"
30#include "SynTree/Expression.h"
31#include "SynTree/Initializer.h"
32#include "SynTree/Visitor.h"
33#include "SymTab/Indexer.h"
34#include "SymTab/Mangler.h"
35#include "SynTree/TypeSubstitution.h"
36#include "SymTab/Validate.h"
37#include "Designators/Processor.h"
38#include "Tuples/TupleAssignment.h"
39#include "Tuples/NameMatcher.h"
[d3b7937]40#include "Common/utility.h"
[70f89d00]41#include "InitTweak/InitTweak.h"
[51b7345]42
[b87a5ed]43extern bool resolvep;
[6ed1d4b]44#define PRINT( text ) if ( resolvep ) { text }
[51b7345]45//#define DEBUG_COST
46
47namespace ResolvExpr {
[a32b204]48        Expression *resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer, TypeEnvironment &env ) {
49                CastExpr *castToVoid = new CastExpr( expr );
50
51                AlternativeFinder finder( indexer, env );
52                finder.findWithAdjustment( castToVoid );
53
54                // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
55                // interpretations, an exception has already been thrown.
56                assert( finder.get_alternatives().size() == 1 );
57                CastExpr *newExpr = dynamic_cast< CastExpr* >( finder.get_alternatives().front().expr );
58                assert( newExpr );
59                env = finder.get_alternatives().front().env;
60                return newExpr->get_arg()->clone();
61        }
62
63        namespace {
64                void printAlts( const AltList &list, std::ostream &os, int indent = 0 ) {
65                        for ( AltList::const_iterator i = list.begin(); i != list.end(); ++i ) {
66                                i->print( os, indent );
67                                os << std::endl;
68                        }
69                }
[d9a0e76]70
[a32b204]71                void makeExprList( const AltList &in, std::list< Expression* > &out ) {
72                        for ( AltList::const_iterator i = in.begin(); i != in.end(); ++i ) {
73                                out.push_back( i->expr->clone() );
74                        }
75                }
[d9a0e76]76
[a32b204]77                Cost sumCost( const AltList &in ) {
78                        Cost total;
79                        for ( AltList::const_iterator i = in.begin(); i != in.end(); ++i ) {
80                                total += i->cost;
81                        }
82                        return total;
83                }
[d9a0e76]84
[a32b204]85                struct PruneStruct {
86                        bool isAmbiguous;
87                        AltList::iterator candidate;
88                        PruneStruct() {}
89                        PruneStruct( AltList::iterator candidate ): isAmbiguous( false ), candidate( candidate ) {}
90                };
91
[0f19d763]92                /// Prunes a list of alternatives down to those that have the minimum conversion cost for a given return type; skips ambiguous interpretations
[a32b204]93                template< typename InputIterator, typename OutputIterator >
94                void pruneAlternatives( InputIterator begin, InputIterator end, OutputIterator out, const SymTab::Indexer &indexer ) {
95                        // select the alternatives that have the minimum conversion cost for a particular set of result types
96                        std::map< std::string, PruneStruct > selected;
97                        for ( AltList::iterator candidate = begin; candidate != end; ++candidate ) {
98                                PruneStruct current( candidate );
99                                std::string mangleName;
100                                for ( std::list< Type* >::const_iterator retType = candidate->expr->get_results().begin(); retType != candidate->expr->get_results().end(); ++retType ) {
101                                        Type *newType = (*retType)->clone();
102                                        candidate->env.apply( newType );
103                                        mangleName += SymTab::Mangler::mangle( newType );
104                                        delete newType;
105                                }
106                                std::map< std::string, PruneStruct >::iterator mapPlace = selected.find( mangleName );
107                                if ( mapPlace != selected.end() ) {
108                                        if ( candidate->cost < mapPlace->second.candidate->cost ) {
109                                                PRINT(
[6ed1d4b]110                                                        std::cerr << "cost " << candidate->cost << " beats " << mapPlace->second.candidate->cost << std::endl;
[7c64920]111                                                )
[0f19d763]112                                                selected[ mangleName ] = current;
[a32b204]113                                        } else if ( candidate->cost == mapPlace->second.candidate->cost ) {
114                                                PRINT(
[6ed1d4b]115                                                        std::cerr << "marking ambiguous" << std::endl;
[7c64920]116                                                )
[0f19d763]117                                                mapPlace->second.isAmbiguous = true;
[a32b204]118                                        }
119                                } else {
120                                        selected[ mangleName ] = current;
121                                }
122                        }
[d9a0e76]123
124                        PRINT(
[6ed1d4b]125                                std::cerr << "there are " << selected.size() << " alternatives before elimination" << std::endl;
[7c64920]126                        )
[a32b204]127
[0f19d763]128                        // accept the alternatives that were unambiguous
129                        for ( std::map< std::string, PruneStruct >::iterator target = selected.begin(); target != selected.end(); ++target ) {
130                                if ( ! target->second.isAmbiguous ) {
131                                        Alternative &alt = *target->second.candidate;
132                                        for ( std::list< Type* >::iterator result = alt.expr->get_results().begin(); result != alt.expr->get_results().end(); ++result ) {
133                                                alt.env.applyFree( *result );
[a32b204]134                                        }
[0f19d763]135                                        *out++ = alt;
[a32b204]136                                }
[0f19d763]137                        }
[a32b204]138
[d9a0e76]139                }
[a32b204]140
141                template< typename InputIterator, typename OutputIterator >
142                void findMinCost( InputIterator begin, InputIterator end, OutputIterator out ) {
143                        AltList alternatives;
144
145                        // select the alternatives that have the minimum parameter cost
146                        Cost minCost = Cost::infinity;
147                        for ( AltList::iterator i = begin; i != end; ++i ) {
148                                if ( i->cost < minCost ) {
149                                        minCost = i->cost;
150                                        i->cost = i->cvtCost;
151                                        alternatives.clear();
152                                        alternatives.push_back( *i );
153                                } else if ( i->cost == minCost ) {
154                                        i->cost = i->cvtCost;
155                                        alternatives.push_back( *i );
156                                }
157                        }
158                        std::copy( alternatives.begin(), alternatives.end(), out );
[d9a0e76]159                }
160
[a32b204]161                template< typename InputIterator >
162                void simpleCombineEnvironments( InputIterator begin, InputIterator end, TypeEnvironment &result ) {
163                        while ( begin != end ) {
164                                result.simpleCombine( (*begin++).env );
165                        }
166                }
[d9a0e76]167
[a32b204]168                void renameTypes( Expression *expr ) {
169                        for ( std::list< Type* >::iterator i = expr->get_results().begin(); i != expr->get_results().end(); ++i ) {
170                                (*i)->accept( global_renamer );
171                        }
[d9a0e76]172                }
173        }
174
[a32b204]175        template< typename InputIterator, typename OutputIterator >
176        void AlternativeFinder::findSubExprs( InputIterator begin, InputIterator end, OutputIterator out ) {
177                while ( begin != end ) {
178                        AlternativeFinder finder( indexer, env );
179                        finder.findWithAdjustment( *begin );
180                        // XXX  either this
181                        //Designators::fixDesignations( finder, (*begin++)->get_argName() );
182                        // or XXX this
183                        begin++;
184                        PRINT(
[6ed1d4b]185                                std::cerr << "findSubExprs" << std::endl;
186                                printAlts( finder.alternatives, std::cerr );
[7c64920]187                        )
[0f19d763]188                        *out++ = finder;
[a32b204]189                }
[d9a0e76]190        }
191
[a32b204]192        AlternativeFinder::AlternativeFinder( const SymTab::Indexer &indexer, const TypeEnvironment &env )
193                : indexer( indexer ), env( env ) {
[d9a0e76]194        }
[51b7345]195
[a32b204]196        void AlternativeFinder::find( Expression *expr, bool adjust ) {
197                expr->accept( *this );
198                if ( alternatives.empty() ) {
199                        throw SemanticError( "No reasonable alternatives for expression ", expr );
200                }
201                for ( AltList::iterator i = alternatives.begin(); i != alternatives.end(); ++i ) {
202                        if ( adjust ) {
203                                adjustExprTypeList( i->expr->get_results().begin(), i->expr->get_results().end(), i->env, indexer );
204                        }
205                }
206                PRINT(
[6ed1d4b]207                        std::cerr << "alternatives before prune:" << std::endl;
208                        printAlts( alternatives, std::cerr );
[7c64920]209                )
[0f19d763]210                AltList::iterator oldBegin = alternatives.begin();
[a32b204]211                pruneAlternatives( alternatives.begin(), alternatives.end(), front_inserter( alternatives ), indexer );
212                if ( alternatives.begin() == oldBegin ) {
[5f2f2d7]213                        std::ostringstream stream;
[a32b204]214                        stream << "Can't choose between alternatives for expression ";
215                        expr->print( stream );
216                        stream << "Alternatives are:";
217                        AltList winners;
218                        findMinCost( alternatives.begin(), alternatives.end(), back_inserter( winners ) );
219                        printAlts( winners, stream, 8 );
[5f2f2d7]220                        throw SemanticError( stream.str() );
[a32b204]221                }
222                alternatives.erase( oldBegin, alternatives.end() );
223                PRINT(
[6ed1d4b]224                        std::cerr << "there are " << alternatives.size() << " alternatives after elimination" << std::endl;
[7c64920]225                )
[0f19d763]226        }
[d9a0e76]227
[a32b204]228        void AlternativeFinder::findWithAdjustment( Expression *expr ) {
229                find( expr, true );
[d9a0e76]230        }
[a32b204]231
232        template< typename StructOrUnionType >
233        void AlternativeFinder::addAggMembers( StructOrUnionType *aggInst, Expression *expr, const Cost &newCost, const std::string &name ) {
234                std::list< Declaration* > members;
235                aggInst->lookup( name, members );
236                for ( std::list< Declaration* >::const_iterator i = members.begin(); i != members.end(); ++i ) {
237                        if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType* >( *i ) ) {
238                                alternatives.push_back( Alternative( new MemberExpr( dwt->clone(), expr->clone() ), env, newCost ) );
239                                renameTypes( alternatives.back().expr );
240                        } else {
241                                assert( false );
242                        }
243                }
[d9a0e76]244        }
[a32b204]245
246        void AlternativeFinder::visit( ApplicationExpr *applicationExpr ) {
247                alternatives.push_back( Alternative( applicationExpr->clone(), env, Cost::zero ) );
[d9a0e76]248        }
249
[a32b204]250        Cost computeConversionCost( Alternative &alt, const SymTab::Indexer &indexer ) {
251                ApplicationExpr *appExpr = dynamic_cast< ApplicationExpr* >( alt.expr );
252                assert( appExpr );
253                PointerType *pointer = dynamic_cast< PointerType* >( appExpr->get_function()->get_results().front() );
254                assert( pointer );
255                FunctionType *function = dynamic_cast< FunctionType* >( pointer->get_base() );
256                assert( function );
257
258                Cost convCost( 0, 0, 0 );
259                std::list< DeclarationWithType* >& formals = function->get_parameters();
260                std::list< DeclarationWithType* >::iterator formal = formals.begin();
261                std::list< Expression* >& actuals = appExpr->get_args();
262                for ( std::list< Expression* >::iterator actualExpr = actuals.begin(); actualExpr != actuals.end(); ++actualExpr ) {
263                        PRINT(
[6ed1d4b]264                                std::cerr << "actual expression:" << std::endl;
265                                (*actualExpr)->print( std::cerr, 8 );
266                                std::cerr << "--- results are" << std::endl;
267                                printAll( (*actualExpr)->get_results(), std::cerr, 8 );
[7c64920]268                        )
269                        std::list< DeclarationWithType* >::iterator startFormal = formal;
[a32b204]270                        Cost actualCost;
271                        for ( std::list< Type* >::iterator actual = (*actualExpr)->get_results().begin(); actual != (*actualExpr)->get_results().end(); ++actual ) {
272                                if ( formal == formals.end() ) {
273                                        if ( function->get_isVarArgs() ) {
274                                                convCost += Cost( 1, 0, 0 );
275                                                break;
276                                        } else {
277                                                return Cost::infinity;
278                                        }
279                                }
280                                PRINT(
[6ed1d4b]281                                        std::cerr << std::endl << "converting ";
282                                        (*actual)->print( std::cerr, 8 );
283                                        std::cerr << std::endl << " to ";
284                                        (*formal)->get_type()->print( std::cerr, 8 );
[7c64920]285                                )
286                                Cost newCost = conversionCost( *actual, (*formal)->get_type(), indexer, alt.env );
[a32b204]287                                PRINT(
[6ed1d4b]288                                        std::cerr << std::endl << "cost is" << newCost << std::endl;
[7c64920]289                                )
[a32b204]290
[7c64920]291                                if ( newCost == Cost::infinity ) {
292                                        return newCost;
293                                }
[a32b204]294                                convCost += newCost;
295                                actualCost += newCost;
296
297                                convCost += Cost( 0, polyCost( (*formal)->get_type(), alt.env, indexer ) + polyCost( *actual, alt.env, indexer ), 0 );
298
299                                formal++;
300                        }
301                        if ( actualCost != Cost( 0, 0, 0 ) ) {
302                                std::list< DeclarationWithType* >::iterator startFormalPlusOne = startFormal;
303                                startFormalPlusOne++;
304                                if ( formal == startFormalPlusOne ) {
305                                        // not a tuple type
306                                        Type *newType = (*startFormal)->get_type()->clone();
307                                        alt.env.apply( newType );
308                                        *actualExpr = new CastExpr( *actualExpr, newType );
309                                } else {
310                                        TupleType *newType = new TupleType( Type::Qualifiers() );
311                                        for ( std::list< DeclarationWithType* >::iterator i = startFormal; i != formal; ++i ) {
312                                                newType->get_types().push_back( (*i)->get_type()->clone() );
313                                        }
314                                        alt.env.apply( newType );
315                                        *actualExpr = new CastExpr( *actualExpr, newType );
316                                }
317                        }
318
[d9a0e76]319                }
[a32b204]320                if ( formal != formals.end() ) {
321                        return Cost::infinity;
[d9a0e76]322                }
323
[a32b204]324                for ( InferredParams::const_iterator assert = appExpr->get_inferParams().begin(); assert != appExpr->get_inferParams().end(); ++assert ) {
325                        PRINT(
[6ed1d4b]326                                std::cerr << std::endl << "converting ";
327                                assert->second.actualType->print( std::cerr, 8 );
328                                std::cerr << std::endl << " to ";
329                                assert->second.formalType->print( std::cerr, 8 );
[a32b204]330                                )
331                                Cost newCost = conversionCost( assert->second.actualType, assert->second.formalType, indexer, alt.env );
332                        PRINT(
[6ed1d4b]333                                std::cerr << std::endl << "cost of conversion is " << newCost << std::endl;
[a32b204]334                                )
335                                if ( newCost == Cost::infinity ) {
336                                        return newCost;
337                                }
338                        convCost += newCost;
[d9a0e76]339
[a32b204]340                        convCost += Cost( 0, polyCost( assert->second.formalType, alt.env, indexer ) + polyCost( assert->second.actualType, alt.env, indexer ), 0 );
341                }
[d9a0e76]342
[a32b204]343                return convCost;
344        }
[d9a0e76]345
[8c84ebd]346        /// Adds type variables to the open variable set and marks their assertions
[a32b204]347        void makeUnifiableVars( Type *type, OpenVarSet &unifiableVars, AssertionSet &needAssertions ) {
348                for ( std::list< TypeDecl* >::const_iterator tyvar = type->get_forall().begin(); tyvar != type->get_forall().end(); ++tyvar ) {
349                        unifiableVars[ (*tyvar)->get_name() ] = (*tyvar)->get_kind();
350                        for ( std::list< DeclarationWithType* >::iterator assert = (*tyvar)->get_assertions().begin(); assert != (*tyvar)->get_assertions().end(); ++assert ) {
351                                needAssertions[ *assert ] = true;
352                        }
[d9a0e76]353///     needAssertions.insert( needAssertions.end(), (*tyvar)->get_assertions().begin(), (*tyvar)->get_assertions().end() );
354                }
355        }
[a32b204]356
357        bool AlternativeFinder::instantiateFunction( std::list< DeclarationWithType* >& formals, /*const*/ AltList &actuals, bool isVarArgs, OpenVarSet& openVars, TypeEnvironment &resultEnv, AssertionSet &resultNeed, AssertionSet &resultHave ) {
358                simpleCombineEnvironments( actuals.begin(), actuals.end(), resultEnv );
359                // make sure we don't widen any existing bindings
360                for ( TypeEnvironment::iterator i = resultEnv.begin(); i != resultEnv.end(); ++i ) {
361                        i->allowWidening = false;
362                }
363                resultEnv.extractOpenVars( openVars );
364
365                /*
366                  Tuples::NameMatcher matcher( formals );
367                  try {
368                  matcher.match( actuals );
369                  } catch ( Tuples::NoMatch &e ) {
370                  std::cerr << "Alternative doesn't match: " << e.message << std::endl;
371                  }
372                */
373                std::list< DeclarationWithType* >::iterator formal = formals.begin();
374                for ( AltList::const_iterator actualExpr = actuals.begin(); actualExpr != actuals.end(); ++actualExpr ) {
375                        for ( std::list< Type* >::iterator actual = actualExpr->expr->get_results().begin(); actual != actualExpr->expr->get_results().end(); ++actual ) {
376                                if ( formal == formals.end() ) {
377                                        return isVarArgs;
378                                }
379                                PRINT(
380                                        std::cerr << "formal type is ";
381                                        (*formal)->get_type()->print( std::cerr );
382                                        std::cerr << std::endl << "actual type is ";
383                                        (*actual)->print( std::cerr );
384                                        std::cerr << std::endl;
[7c64920]385                                )
[0f19d763]386                                if ( ! unify( (*formal)->get_type(), *actual, resultEnv, resultNeed, resultHave, openVars, indexer ) ) {
387                                        return false;
388                                }
[d9a0e76]389                                formal++;
[a32b204]390                        }
391                }
392                // Handling of default values
393                while ( formal != formals.end() ) {
394                        if ( ObjectDecl *od = dynamic_cast<ObjectDecl *>( *formal ) )
395                                if ( SingleInit *si = dynamic_cast<SingleInit *>( od->get_init() ))
396                                        // so far, only constant expressions are accepted as default values
397                                        if ( ConstantExpr *cnstexpr = dynamic_cast<ConstantExpr *>( si->get_value()) )
398                                                if ( Constant *cnst = dynamic_cast<Constant *>( cnstexpr->get_constant() ) )
399                                                        if ( unify( (*formal)->get_type(), cnst->get_type(), resultEnv, resultNeed, resultHave, openVars, indexer ) ) {
400                                                                // XXX Don't know if this is right
401                                                                actuals.push_back( Alternative( cnstexpr->clone(), env, Cost::zero ) );
402                                                                formal++;
403                                                                if ( formal == formals.end()) break;
404                                                        }
405                        return false;
406                }
407                return true;
[d9a0e76]408        }
[51b7345]409
[a32b204]410        static const int recursionLimit = 10;
[51b7345]411
[a32b204]412        void addToIndexer( AssertionSet &assertSet, SymTab::Indexer &indexer ) {
413                for ( AssertionSet::iterator i = assertSet.begin(); i != assertSet.end(); ++i ) {
414                        if ( i->second == true ) {
415                                i->first->accept( indexer );
416                        }
417                }
[d9a0e76]418        }
419
[a32b204]420        template< typename ForwardIterator, typename OutputIterator >
421        void inferRecursive( ForwardIterator begin, ForwardIterator end, const Alternative &newAlt, OpenVarSet &openVars, const SymTab::Indexer &decls, const AssertionSet &newNeed, int level, const SymTab::Indexer &indexer, OutputIterator out ) {
422                if ( begin == end ) {
423                        if ( newNeed.empty() ) {
424                                *out++ = newAlt;
425                                return;
426                        } else if ( level >= recursionLimit ) {
427                                throw SemanticError( "Too many recursive assertions" );
428                        } else {
429                                AssertionSet newerNeed;
430                                PRINT(
431                                        std::cerr << "recursing with new set:" << std::endl;
432                                        printAssertionSet( newNeed, std::cerr, 8 );
[7c64920]433                                )
[0f19d763]434                                inferRecursive( newNeed.begin(), newNeed.end(), newAlt, openVars, decls, newerNeed, level+1, indexer, out );
[a32b204]435                                return;
436                        }
437                }
438
439                ForwardIterator cur = begin++;
440                if ( ! cur->second ) {
441                        inferRecursive( begin, end, newAlt, openVars, decls, newNeed, level, indexer, out );
442                }
443                DeclarationWithType *curDecl = cur->first;
[d9a0e76]444                PRINT(
[a32b204]445                        std::cerr << "inferRecursive: assertion is ";
446                        curDecl->print( std::cerr );
447                        std::cerr << std::endl;
[7c64920]448                )
[0f19d763]449                std::list< DeclarationWithType* > candidates;
[a32b204]450                decls.lookupId( curDecl->get_name(), candidates );
[6ed1d4b]451///   if ( candidates.empty() ) { std::cerr << "no candidates!" << std::endl; }
[a32b204]452                for ( std::list< DeclarationWithType* >::const_iterator candidate = candidates.begin(); candidate != candidates.end(); ++candidate ) {
453                        PRINT(
[6ed1d4b]454                                std::cerr << "inferRecursive: candidate is ";
455                                (*candidate)->print( std::cerr );
456                                std::cerr << std::endl;
[7c64920]457                        )
[0f19d763]458                        AssertionSet newHave, newerNeed( newNeed );
[a32b204]459                        TypeEnvironment newEnv( newAlt.env );
460                        OpenVarSet newOpenVars( openVars );
461                        Type *adjType = (*candidate)->get_type()->clone();
462                        adjustExprType( adjType, newEnv, indexer );
463                        adjType->accept( global_renamer );
464                        PRINT(
465                                std::cerr << "unifying ";
466                                curDecl->get_type()->print( std::cerr );
467                                std::cerr << " with ";
468                                adjType->print( std::cerr );
469                                std::cerr << std::endl;
[7c64920]470                        )
[0f19d763]471                        if ( unify( curDecl->get_type(), adjType, newEnv, newerNeed, newHave, newOpenVars, indexer ) ) {
472                                PRINT(
473                                        std::cerr << "success!" << std::endl;
[a32b204]474                                )
[0f19d763]475                                SymTab::Indexer newDecls( decls );
476                                addToIndexer( newHave, newDecls );
477                                Alternative newerAlt( newAlt );
478                                newerAlt.env = newEnv;
479                                assert( (*candidate)->get_uniqueId() );
480                                Expression *varExpr = new VariableExpr( static_cast< DeclarationWithType* >( Declaration::declFromId( (*candidate)->get_uniqueId() ) ) );
481                                deleteAll( varExpr->get_results() );
482                                varExpr->get_results().clear();
483                                varExpr->get_results().push_front( adjType->clone() );
484                                PRINT(
[6ed1d4b]485                                        std::cerr << "satisfying assertion " << curDecl->get_uniqueId() << " ";
486                                        curDecl->print( std::cerr );
487                                        std::cerr << " with declaration " << (*candidate)->get_uniqueId() << " ";
488                                        (*candidate)->print( std::cerr );
489                                        std::cerr << std::endl;
[7c64920]490                                )
[0f19d763]491                                ApplicationExpr *appExpr = static_cast< ApplicationExpr* >( newerAlt.expr );
492                                // XXX: this is a memory leak, but adjType can't be deleted because it might contain assertions
493                                appExpr->get_inferParams()[ curDecl->get_uniqueId() ] = ParamEntry( (*candidate)->get_uniqueId(), adjType->clone(), curDecl->get_type()->clone(), varExpr );
494                                inferRecursive( begin, end, newerAlt, newOpenVars, newDecls, newerNeed, level, indexer, out );
495                        } else {
496                                delete adjType;
497                        }
[a32b204]498                }
[d9a0e76]499        }
500
[a32b204]501        template< typename OutputIterator >
502        void AlternativeFinder::inferParameters( const AssertionSet &need, AssertionSet &have, const Alternative &newAlt, OpenVarSet &openVars, OutputIterator out ) {
[d9a0e76]503//      PRINT(
[6ed1d4b]504//          std::cerr << "inferParameters: assertions needed are" << std::endl;
505//          printAll( need, std::cerr, 8 );
[d9a0e76]506//          )
[a32b204]507                SymTab::Indexer decls( indexer );
508                PRINT(
[6ed1d4b]509                        std::cerr << "============= original indexer" << std::endl;
510                        indexer.print( std::cerr );
511                        std::cerr << "============= new indexer" << std::endl;
512                        decls.print( std::cerr );
[7c64920]513                )
[0f19d763]514                addToIndexer( have, decls );
[a32b204]515                AssertionSet newNeed;
516                inferRecursive( need.begin(), need.end(), newAlt, openVars, decls, newNeed, 0, indexer, out );
[d9a0e76]517//      PRINT(
[6ed1d4b]518//          std::cerr << "declaration 14 is ";
[d9a0e76]519//          Declaration::declFromId
520//          *out++ = newAlt;
521//          )
522        }
523
[a32b204]524        template< typename OutputIterator >
525        void AlternativeFinder::makeFunctionAlternatives( const Alternative &func, FunctionType *funcType, AltList &actualAlt, OutputIterator out ) {
526                OpenVarSet openVars;
527                AssertionSet resultNeed, resultHave;
528                TypeEnvironment resultEnv;
529                makeUnifiableVars( funcType, openVars, resultNeed );
530                if ( instantiateFunction( funcType->get_parameters(), actualAlt, funcType->get_isVarArgs(), openVars, resultEnv, resultNeed, resultHave ) ) {
531                        ApplicationExpr *appExpr = new ApplicationExpr( func.expr->clone() );
532                        Alternative newAlt( appExpr, resultEnv, sumCost( actualAlt ) );
533                        makeExprList( actualAlt, appExpr->get_args() );
534                        PRINT(
[6ed1d4b]535                                std::cerr << "need assertions:" << std::endl;
536                                printAssertionSet( resultNeed, std::cerr, 8 );
[7c64920]537                        )
[0f19d763]538                        inferParameters( resultNeed, resultHave, newAlt, openVars, out );
[d9a0e76]539                }
540        }
541
[a32b204]542        void AlternativeFinder::visit( UntypedExpr *untypedExpr ) {
543                bool doneInit = false;
544                AlternativeFinder funcOpFinder( indexer, env );
[d9a0e76]545
[6ed1d4b]546                AlternativeFinder funcFinder( indexer, env );
547
548                {
[70f89d00]549                        std::string fname = InitTweak::getFunctionName( untypedExpr );
550                        if ( fname == "&&" ) {
[2871210]551                                VoidType v = Type::Qualifiers();                // resolve to type void *
552                                PointerType pt( Type::Qualifiers(), v.clone() );
553                                UntypedExpr *vexpr = untypedExpr->clone();
554                                vexpr->get_results().push_front( pt.clone() );
555                                alternatives.push_back( Alternative( vexpr, env, Cost()) );
[a32b204]556                                return;
557                        }
558                }
[d9a0e76]559
[a32b204]560                funcFinder.findWithAdjustment( untypedExpr->get_function() );
561                std::list< AlternativeFinder > argAlternatives;
562                findSubExprs( untypedExpr->begin_args(), untypedExpr->end_args(), back_inserter( argAlternatives ) );
[d9a0e76]563
[a32b204]564                std::list< AltList > possibilities;
565                combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
[d9a0e76]566
[a32b204]567                Tuples::TupleAssignSpotter tassign( this );
568                if ( tassign.isTupleAssignment( untypedExpr, possibilities ) ) {
569                        // take care of possible tuple assignments, or discard expression
570                        return;
571                } // else ...
[d9a0e76]572
[a32b204]573                AltList candidates;
[91b8a17]574                SemanticError errors;
[d9a0e76]575
[a32b204]576                for ( AltList::const_iterator func = funcFinder.alternatives.begin(); func != funcFinder.alternatives.end(); ++func ) {
[91b8a17]577                        try {
578                                PRINT(
579                                        std::cerr << "working on alternative: " << std::endl;
580                                        func->print( std::cerr, 8 );
581                                )
582                                // check if the type is pointer to function
583                                PointerType *pointer;
584                                if ( func->expr->get_results().size() == 1 && ( pointer = dynamic_cast< PointerType* >( func->expr->get_results().front() ) ) ) {
585                                        if ( FunctionType *function = dynamic_cast< FunctionType* >( pointer->get_base() ) ) {
586                                                for ( std::list< AltList >::iterator actualAlt = possibilities.begin(); actualAlt != possibilities.end(); ++actualAlt ) {
587                                                        // XXX
588                                                        //Designators::check_alternative( function, *actualAlt );
589                                                        makeFunctionAlternatives( *func, function, *actualAlt, std::back_inserter( candidates ) );
590                                                }
591                                        } else if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( pointer->get_base() ) ) {
592                                                EqvClass eqvClass;
593                                                if ( func->env.lookup( typeInst->get_name(), eqvClass ) && eqvClass.type ) {
594                                                        if ( FunctionType *function = dynamic_cast< FunctionType* >( eqvClass.type ) ) {
595                                                                for ( std::list< AltList >::iterator actualAlt = possibilities.begin(); actualAlt != possibilities.end(); ++actualAlt ) {
596                                                                        makeFunctionAlternatives( *func, function, *actualAlt, std::back_inserter( candidates ) );
597                                                                } // for
598                                                        } // if
[a32b204]599                                                } // if
600                                        } // if
[91b8a17]601                                } else {
602                                        // seek a function operator that's compatible
603                                        if ( ! doneInit ) {
604                                                doneInit = true;
605                                                NameExpr *opExpr = new NameExpr( "?()" );
606                                                try {
607                                                        funcOpFinder.findWithAdjustment( opExpr );
608                                                } catch( SemanticError &e ) {
609                                                        // it's ok if there aren't any defined function ops
610                                                }
611                                                PRINT(
612                                                        std::cerr << "known function ops:" << std::endl;
613                                                        printAlts( funcOpFinder.alternatives, std::cerr, 8 );
614                                                )
[a32b204]615                                        }
616
[91b8a17]617                                        for ( AltList::const_iterator funcOp = funcOpFinder.alternatives.begin(); funcOp != funcOpFinder.alternatives.end(); ++funcOp ) {
618                                                // check if the type is pointer to function
619                                                PointerType *pointer;
620                                                if ( funcOp->expr->get_results().size() == 1
621                                                        && ( pointer = dynamic_cast< PointerType* >( funcOp->expr->get_results().front() ) ) ) {
622                                                        if ( FunctionType *function = dynamic_cast< FunctionType* >( pointer->get_base() ) ) {
623                                                                for ( std::list< AltList >::iterator actualAlt = possibilities.begin(); actualAlt != possibilities.end(); ++actualAlt ) {
624                                                                        AltList currentAlt;
625                                                                        currentAlt.push_back( *func );
626                                                                        currentAlt.insert( currentAlt.end(), actualAlt->begin(), actualAlt->end() );
627                                                                        makeFunctionAlternatives( *funcOp, function, currentAlt, std::back_inserter( candidates ) );
628                                                                } // for
629                                                        } // if
[a32b204]630                                                } // if
[91b8a17]631                                        } // for
632                                } // if
633                        } catch ( SemanticError &e ) {
634                                errors.append( e );
635                        }
[a32b204]636                } // for
637
[91b8a17]638                // Implement SFINAE; resolution errors are only errors if there aren't any non-erroneous resolutions
639                if ( candidates.empty() && ! errors.isEmpty() ) { throw errors; }
640
[a32b204]641                for ( AltList::iterator withFunc = candidates.begin(); withFunc != candidates.end(); ++withFunc ) {
642                        Cost cvtCost = computeConversionCost( *withFunc, indexer );
643
644                        PRINT(
645                                ApplicationExpr *appExpr = dynamic_cast< ApplicationExpr* >( withFunc->expr );
646                                assert( appExpr );
647                                PointerType *pointer = dynamic_cast< PointerType* >( appExpr->get_function()->get_results().front() );
648                                assert( pointer );
649                                FunctionType *function = dynamic_cast< FunctionType* >( pointer->get_base() );
650                                assert( function );
[6ed1d4b]651                                std::cerr << "Case +++++++++++++" << std::endl;
652                                std::cerr << "formals are:" << std::endl;
653                                printAll( function->get_parameters(), std::cerr, 8 );
654                                std::cerr << "actuals are:" << std::endl;
655                                printAll( appExpr->get_args(), std::cerr, 8 );
656                                std::cerr << "bindings are:" << std::endl;
657                                withFunc->env.print( std::cerr, 8 );
658                                std::cerr << "cost of conversion is:" << cvtCost << std::endl;
[7c64920]659                        )
660                        if ( cvtCost != Cost::infinity ) {
661                                withFunc->cvtCost = cvtCost;
662                                alternatives.push_back( *withFunc );
663                        } // if
[a32b204]664                } // for
665                candidates.clear();
666                candidates.splice( candidates.end(), alternatives );
667
668                findMinCost( candidates.begin(), candidates.end(), std::back_inserter( alternatives ) );
669        }
670
671        bool isLvalue( Expression *expr ) {
672                for ( std::list< Type* >::const_iterator i = expr->get_results().begin(); i != expr->get_results().end(); ++i ) {
673                        if ( !(*i)->get_isLvalue() ) return false;
674                } // for
675                return true;
676        }
677
678        void AlternativeFinder::visit( AddressExpr *addressExpr ) {
679                AlternativeFinder finder( indexer, env );
680                finder.find( addressExpr->get_arg() );
681                for ( std::list< Alternative >::iterator i = finder.alternatives.begin(); i != finder.alternatives.end(); ++i ) {
682                        if ( isLvalue( i->expr ) ) {
683                                alternatives.push_back( Alternative( new AddressExpr( i->expr->clone() ), i->env, i->cost ) );
684                        } // if
685                } // for
686        }
687
688        void AlternativeFinder::visit( CastExpr *castExpr ) {
689                for ( std::list< Type* >::iterator i = castExpr->get_results().begin(); i != castExpr->get_results().end(); ++i ) {
690                        SymTab::validateType( *i, &indexer );
691                        adjustExprType( *i, env, indexer );
692                } // for
693
694                AlternativeFinder finder( indexer, env );
695                finder.findWithAdjustment( castExpr->get_arg() );
696
697                AltList candidates;
698                for ( std::list< Alternative >::iterator i = finder.alternatives.begin(); i != finder.alternatives.end(); ++i ) {
699                        AssertionSet needAssertions, haveAssertions;
700                        OpenVarSet openVars;
701
702                        // It's possible that a cast can throw away some values in a multiply-valued expression.  (An example is a
703                        // cast-to-void, which casts from one value to zero.)  Figure out the prefix of the subexpression results
704                        // that are cast directly.  The candidate is invalid if it has fewer results than there are types to cast
705                        // to.
706                        int discardedValues = (*i).expr->get_results().size() - castExpr->get_results().size();
707                        if ( discardedValues < 0 ) continue;
708                        std::list< Type* >::iterator candidate_end = (*i).expr->get_results().begin();
709                        std::advance( candidate_end, castExpr->get_results().size() );
[adcdd2f]710                        // unification run for side-effects
711                        unifyList( castExpr->get_results().begin(), castExpr->get_results().end(),
712                                           (*i).expr->get_results().begin(), candidate_end,
713                                   i->env, needAssertions, haveAssertions, openVars, indexer );
[a32b204]714                        Cost thisCost = castCostList( (*i).expr->get_results().begin(), candidate_end,
[adcdd2f]715                                                                                  castExpr->get_results().begin(), castExpr->get_results().end(),
716                                                                                  indexer, i->env );
[a32b204]717                        if ( thisCost != Cost::infinity ) {
718                                // count one safe conversion for each value that is thrown away
719                                thisCost += Cost( 0, 0, discardedValues );
720                                CastExpr *newExpr = castExpr->clone();
721                                newExpr->set_arg( i->expr->clone() );
722                                candidates.push_back( Alternative( newExpr, i->env, i->cost, thisCost ) );
723                        } // if
724                } // for
725
726                // findMinCost selects the alternatives with the lowest "cost" members, but has the side effect of copying the
727                // cvtCost member to the cost member (since the old cost is now irrelevant).  Thus, calling findMinCost twice
728                // selects first based on argument cost, then on conversion cost.
729                AltList minArgCost;
730                findMinCost( candidates.begin(), candidates.end(), std::back_inserter( minArgCost ) );
731                findMinCost( minArgCost.begin(), minArgCost.end(), std::back_inserter( alternatives ) );
732        }
733
734        void AlternativeFinder::visit( UntypedMemberExpr *memberExpr ) {
735                AlternativeFinder funcFinder( indexer, env );
736                funcFinder.findWithAdjustment( memberExpr->get_aggregate() );
737
738                for ( AltList::const_iterator agg = funcFinder.alternatives.begin(); agg != funcFinder.alternatives.end(); ++agg ) {
739                        if ( agg->expr->get_results().size() == 1 ) {
740                                if ( StructInstType *structInst = dynamic_cast< StructInstType* >( agg->expr->get_results().front() ) ) {
741                                        addAggMembers( structInst, agg->expr, agg->cost, memberExpr->get_member() );
742                                } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( agg->expr->get_results().front() ) ) {
743                                        addAggMembers( unionInst, agg->expr, agg->cost, memberExpr->get_member() );
744                                } // if
745                        } // if
746                } // for
747        }
748
749        void AlternativeFinder::visit( MemberExpr *memberExpr ) {
750                alternatives.push_back( Alternative( memberExpr->clone(), env, Cost::zero ) );
751        }
752
753        void AlternativeFinder::visit( NameExpr *nameExpr ) {
754                std::list< DeclarationWithType* > declList;
755                indexer.lookupId( nameExpr->get_name(), declList );
756                PRINT( std::cerr << "nameExpr is " << nameExpr->get_name() << std::endl; )
[0f19d763]757                for ( std::list< DeclarationWithType* >::iterator i = declList.begin(); i != declList.end(); ++i ) {
758                        VariableExpr newExpr( *i, nameExpr->get_argName() );
759                        alternatives.push_back( Alternative( newExpr.clone(), env, Cost() ) );
760                        PRINT(
761                                std::cerr << "decl is ";
762                                (*i)->print( std::cerr );
763                                std::cerr << std::endl;
764                                std::cerr << "newExpr is ";
765                                newExpr.print( std::cerr );
766                                std::cerr << std::endl;
[7c64920]767                        )
[0f19d763]768                        renameTypes( alternatives.back().expr );
769                        if ( StructInstType *structInst = dynamic_cast< StructInstType* >( (*i)->get_type() ) ) {
770                                addAggMembers( structInst, &newExpr, Cost( 0, 0, 1 ), "" );
771                        } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( (*i)->get_type() ) ) {
772                                addAggMembers( unionInst, &newExpr, Cost( 0, 0, 1 ), "" );
773                        } // if
774                } // for
[a32b204]775        }
776
777        void AlternativeFinder::visit( VariableExpr *variableExpr ) {
778                alternatives.push_back( Alternative( variableExpr->clone(), env, Cost::zero ) );
779        }
780
781        void AlternativeFinder::visit( ConstantExpr *constantExpr ) {
782                alternatives.push_back( Alternative( constantExpr->clone(), env, Cost::zero ) );
783        }
784
785        void AlternativeFinder::visit( SizeofExpr *sizeofExpr ) {
786                if ( sizeofExpr->get_isType() ) {
787                        alternatives.push_back( Alternative( sizeofExpr->clone(), env, Cost::zero ) );
788                } else {
789                        // find all alternatives for the argument to sizeof
790                        AlternativeFinder finder( indexer, env );
791                        finder.find( sizeofExpr->get_expr() );
792                        // find the lowest cost alternative among the alternatives, otherwise ambiguous
793                        AltList winners;
794                        findMinCost( finder.alternatives.begin(), finder.alternatives.end(), back_inserter( winners ) );
795                        if ( winners.size() != 1 ) {
796                                throw SemanticError( "Ambiguous expression in sizeof operand: ", sizeofExpr->get_expr() );
797                        } // if
798                        // return the lowest cost alternative for the argument
799                        Alternative &choice = winners.front();
800                        alternatives.push_back( Alternative( new SizeofExpr( choice.expr->clone() ), choice.env, Cost::zero ) );
[47534159]801                } // if
802        }
803
804        void AlternativeFinder::visit( AlignofExpr *alignofExpr ) {
805                if ( alignofExpr->get_isType() ) {
806                        alternatives.push_back( Alternative( alignofExpr->clone(), env, Cost::zero ) );
807                } else {
808                        // find all alternatives for the argument to sizeof
809                        AlternativeFinder finder( indexer, env );
810                        finder.find( alignofExpr->get_expr() );
811                        // find the lowest cost alternative among the alternatives, otherwise ambiguous
812                        AltList winners;
813                        findMinCost( finder.alternatives.begin(), finder.alternatives.end(), back_inserter( winners ) );
814                        if ( winners.size() != 1 ) {
815                                throw SemanticError( "Ambiguous expression in alignof operand: ", alignofExpr->get_expr() );
816                        } // if
817                        // return the lowest cost alternative for the argument
818                        Alternative &choice = winners.front();
819                        alternatives.push_back( Alternative( new AlignofExpr( choice.expr->clone() ), choice.env, Cost::zero ) );
[a32b204]820                } // if
821        }
822
[2a4b088]823        template< typename StructOrUnionType >
824        void AlternativeFinder::addOffsetof( StructOrUnionType *aggInst, const std::string &name ) {
825                std::list< Declaration* > members;
826                aggInst->lookup( name, members );
827                for ( std::list< Declaration* >::const_iterator i = members.begin(); i != members.end(); ++i ) {
828                        if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType* >( *i ) ) {
829                                alternatives.push_back( Alternative( new OffsetofExpr( aggInst->clone(), dwt->clone() ), env, Cost::zero ) );
830                                renameTypes( alternatives.back().expr );
831                        } else {
832                                assert( false );
833                        }
834                }
835        }
[6ed1d4b]836
[2a4b088]837        void AlternativeFinder::visit( UntypedOffsetofExpr *offsetofExpr ) {
838                AlternativeFinder funcFinder( indexer, env );
839                if ( StructInstType *structInst = dynamic_cast< StructInstType* >( offsetofExpr->get_type() ) ) {
840                        addOffsetof( structInst, offsetofExpr->get_member() );
841                } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( offsetofExpr->get_type() ) ) {
842                        addOffsetof( unionInst, offsetofExpr->get_member() );
843                }
844        }
[6ed1d4b]845
[25a054f]846        void AlternativeFinder::visit( OffsetofExpr *offsetofExpr ) {
847                alternatives.push_back( Alternative( offsetofExpr->clone(), env, Cost::zero ) );
[afc1045]848        }
849
850        void AlternativeFinder::visit( OffsetPackExpr *offsetPackExpr ) {
851                alternatives.push_back( Alternative( offsetPackExpr->clone(), env, Cost::zero ) );
[25a054f]852        }
853
[a32b204]854        void AlternativeFinder::resolveAttr( DeclarationWithType *funcDecl, FunctionType *function, Type *argType, const TypeEnvironment &env ) {
855                // assume no polymorphism
856                // assume no implicit conversions
857                assert( function->get_parameters().size() == 1 );
858                PRINT(
[6ed1d4b]859                        std::cerr << "resolvAttr: funcDecl is ";
860                        funcDecl->print( std::cerr );
861                        std::cerr << " argType is ";
862                        argType->print( std::cerr );
863                        std::cerr << std::endl;
[7c64920]864                )
865                if ( typesCompatibleIgnoreQualifiers( argType, function->get_parameters().front()->get_type(), indexer, env ) ) {
866                        alternatives.push_back( Alternative( new AttrExpr( new VariableExpr( funcDecl ), argType->clone() ), env, Cost::zero ) );
867                        for ( std::list< DeclarationWithType* >::iterator i = function->get_returnVals().begin(); i != function->get_returnVals().end(); ++i ) {
868                                alternatives.back().expr->get_results().push_back( (*i)->get_type()->clone() );
869                        } // for
870                } // if
[a32b204]871        }
872
873        void AlternativeFinder::visit( AttrExpr *attrExpr ) {
874                // assume no 'pointer-to-attribute'
875                NameExpr *nameExpr = dynamic_cast< NameExpr* >( attrExpr->get_attr() );
876                assert( nameExpr );
877                std::list< DeclarationWithType* > attrList;
878                indexer.lookupId( nameExpr->get_name(), attrList );
879                if ( attrExpr->get_isType() || attrExpr->get_expr() ) {
880                        for ( std::list< DeclarationWithType* >::iterator i = attrList.begin(); i != attrList.end(); ++i ) {
881                                // check if the type is function
882                                if ( FunctionType *function = dynamic_cast< FunctionType* >( (*i)->get_type() ) ) {
883                                        // assume exactly one parameter
884                                        if ( function->get_parameters().size() == 1 ) {
885                                                if ( attrExpr->get_isType() ) {
886                                                        resolveAttr( *i, function, attrExpr->get_type(), env );
887                                                } else {
888                                                        AlternativeFinder finder( indexer, env );
889                                                        finder.find( attrExpr->get_expr() );
890                                                        for ( AltList::iterator choice = finder.alternatives.begin(); choice != finder.alternatives.end(); ++choice ) {
891                                                                if ( choice->expr->get_results().size() == 1 ) {
892                                                                        resolveAttr(*i, function, choice->expr->get_results().front(), choice->env );
893                                                                } // fi
894                                                        } // for
895                                                } // if
896                                        } // if
897                                } // if
898                        } // for
899                } else {
900                        for ( std::list< DeclarationWithType* >::iterator i = attrList.begin(); i != attrList.end(); ++i ) {
901                                VariableExpr newExpr( *i );
902                                alternatives.push_back( Alternative( newExpr.clone(), env, Cost() ) );
903                                renameTypes( alternatives.back().expr );
904                        } // for
905                } // if
906        }
907
908        void AlternativeFinder::visit( LogicalExpr *logicalExpr ) {
909                AlternativeFinder firstFinder( indexer, env );
910                firstFinder.findWithAdjustment( logicalExpr->get_arg1() );
911                for ( AltList::const_iterator first = firstFinder.alternatives.begin(); first != firstFinder.alternatives.end(); ++first ) {
912                        AlternativeFinder secondFinder( indexer, first->env );
913                        secondFinder.findWithAdjustment( logicalExpr->get_arg2() );
914                        for ( AltList::const_iterator second = secondFinder.alternatives.begin(); second != secondFinder.alternatives.end(); ++second ) {
915                                LogicalExpr *newExpr = new LogicalExpr( first->expr->clone(), second->expr->clone(), logicalExpr->get_isAnd() );
916                                alternatives.push_back( Alternative( newExpr, second->env, first->cost + second->cost ) );
[d9a0e76]917                        }
918                }
919        }
[51b7345]920
[a32b204]921        void AlternativeFinder::visit( ConditionalExpr *conditionalExpr ) {
922                AlternativeFinder firstFinder( indexer, env );
923                firstFinder.findWithAdjustment( conditionalExpr->get_arg1() );
924                for ( AltList::const_iterator first = firstFinder.alternatives.begin(); first != firstFinder.alternatives.end(); ++first ) {
925                        AlternativeFinder secondFinder( indexer, first->env );
926                        secondFinder.findWithAdjustment( conditionalExpr->get_arg2() );
927                        for ( AltList::const_iterator second = secondFinder.alternatives.begin(); second != secondFinder.alternatives.end(); ++second ) {
928                                AlternativeFinder thirdFinder( indexer, second->env );
929                                thirdFinder.findWithAdjustment( conditionalExpr->get_arg3() );
930                                for ( AltList::const_iterator third = thirdFinder.alternatives.begin(); third != thirdFinder.alternatives.end(); ++third ) {
931                                        OpenVarSet openVars;
932                                        AssertionSet needAssertions, haveAssertions;
933                                        Alternative newAlt( 0, third->env, first->cost + second->cost + third->cost );
934                                        std::list< Type* > commonTypes;
935                                        if ( unifyList( second->expr->get_results().begin(), second->expr->get_results().end(), third->expr->get_results().begin(), third->expr->get_results().end(), newAlt.env, needAssertions, haveAssertions, openVars, indexer, commonTypes ) ) {
936                                                ConditionalExpr *newExpr = new ConditionalExpr( first->expr->clone(), second->expr->clone(), third->expr->clone() );
937                                                std::list< Type* >::const_iterator original = second->expr->get_results().begin();
938                                                std::list< Type* >::const_iterator commonType = commonTypes.begin();
939                                                for ( ; original != second->expr->get_results().end() && commonType != commonTypes.end(); ++original, ++commonType ) {
940                                                        if ( *commonType ) {
941                                                                newExpr->get_results().push_back( *commonType );
942                                                        } else {
943                                                                newExpr->get_results().push_back( (*original)->clone() );
944                                                        } // if
945                                                } // for
946                                                newAlt.expr = newExpr;
947                                                inferParameters( needAssertions, haveAssertions, newAlt, openVars, back_inserter( alternatives ) );
948                                        } // if
949                                } // for
950                        } // for
951                } // for
952        }
953
954        void AlternativeFinder::visit( CommaExpr *commaExpr ) {
955                TypeEnvironment newEnv( env );
956                Expression *newFirstArg = resolveInVoidContext( commaExpr->get_arg1(), indexer, newEnv );
957                AlternativeFinder secondFinder( indexer, newEnv );
958                secondFinder.findWithAdjustment( commaExpr->get_arg2() );
959                for ( AltList::const_iterator alt = secondFinder.alternatives.begin(); alt != secondFinder.alternatives.end(); ++alt ) {
960                        alternatives.push_back( Alternative( new CommaExpr( newFirstArg->clone(), alt->expr->clone() ), alt->env, alt->cost ) );
961                } // for
962                delete newFirstArg;
963        }
964
965        void AlternativeFinder::visit( TupleExpr *tupleExpr ) {
966                std::list< AlternativeFinder > subExprAlternatives;
967                findSubExprs( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end(), back_inserter( subExprAlternatives ) );
968                std::list< AltList > possibilities;
969                combos( subExprAlternatives.begin(), subExprAlternatives.end(), back_inserter( possibilities ) );
970                for ( std::list< AltList >::const_iterator i = possibilities.begin(); i != possibilities.end(); ++i ) {
971                        TupleExpr *newExpr = new TupleExpr;
972                        makeExprList( *i, newExpr->get_exprs() );
973                        for ( std::list< Expression* >::const_iterator resultExpr = newExpr->get_exprs().begin(); resultExpr != newExpr->get_exprs().end(); ++resultExpr ) {
974                                for ( std::list< Type* >::const_iterator resultType = (*resultExpr)->get_results().begin(); resultType != (*resultExpr)->get_results().end(); ++resultType ) {
975                                        newExpr->get_results().push_back( (*resultType)->clone() );
976                                } // for
977                        } // for
978
979                        TypeEnvironment compositeEnv;
980                        simpleCombineEnvironments( i->begin(), i->end(), compositeEnv );
981                        alternatives.push_back( Alternative( newExpr, compositeEnv, sumCost( *i ) ) );
982                } // for
[d9a0e76]983        }
[dc2e7e0]984
985        void AlternativeFinder::visit( ImplicitCopyCtorExpr * impCpCtorExpr ) {
986                alternatives.push_back( Alternative( impCpCtorExpr->clone(), env, Cost::zero ) );
987        }
[51b7345]988} // namespace ResolvExpr
[a32b204]989
990// Local Variables: //
991// tab-width: 4 //
992// mode: c++ //
993// compile-command: "make install" //
994// End: //
Note: See TracBrowser for help on using the repository browser.