source: src/ResolvExpr/AlternativeFinder.cc @ a1e67dd

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

implement transformation for MemberTupleExprs?

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