source: src/ResolvExpr/AlternativeFinder.cc @ 907eccb

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

added UntypedTupleExpr? to better differentiate typed and untyped contexts, simplifying some code

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