source: src/ResolvExpr/AlternativeFinder.cc @ ac9ca96

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

consider tuples managed if a tuple constructor is declared, combine environments in tuple assignment

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