source: src/ResolvExpr/AlternativeFinder.cc @ 6eb8948

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 6eb8948 was 6eb8948, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

make TupleAssignment? generate temporaries, add StmtExpr? for GCC statement expressions, expand tuple assignment expressions, collapse SolvedTupleExpr?, MassAssignExpr?, and MultipleAssignExpr? into TupleAssignExpr?

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