source: src/ResolvExpr/CandidateFinder.cpp @ 4c19647

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 4c19647 was 3e5dd913, checked in by Fangren Yu <f37yu@…>, 3 years ago

reimplement function type and eliminate deep copy

  • Property mode set to 100644
File size: 67.7 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// CandidateFinder.cpp --
8//
9// Author           : Aaron B. Moss
10// Created On       : Wed Jun 5 14:30:00 2019
11// Last Modified By : Andrew Beach
12// Last Modified On : Tue Oct  1 14:55:00 2019
13// Update Count     : 2
14//
15
16#include "CandidateFinder.hpp"
17
18#include <deque>
19#include <iterator>               // for back_inserter
20#include <sstream>
21#include <string>
22#include <unordered_map>
23#include <vector>
24
25#include "Candidate.hpp"
26#include "CompilationState.h"
27#include "Cost.h"
28#include "ExplodedArg.hpp"
29#include "RenameVars.h"           // for renameTyVars
30#include "Resolver.h"
31#include "ResolveTypeof.h"
32#include "SatisfyAssertions.hpp"
33#include "typeops.h"              // for adjustExprType, conversionCost, polyCost, specCost
34#include "Unify.h"
35#include "AST/Expr.hpp"
36#include "AST/Node.hpp"
37#include "AST/Pass.hpp"
38#include "AST/Print.hpp"
39#include "AST/SymbolTable.hpp"
40#include "AST/Type.hpp"
41#include "Common/utility.h"       // for move, copy
42#include "SymTab/Mangler.h"
43#include "SymTab/Validate.h"      // for validateType
44#include "Tuples/Tuples.h"        // for handleTupleAssignment
45#include "InitTweak/InitTweak.h"  // for getPointerBase
46
47#include "Common/Stats/Counter.h"
48
49#define PRINT( text ) if ( resolvep ) { text }
50
51namespace ResolvExpr {
52
53const ast::Expr * referenceToRvalueConversion( const ast::Expr * expr, Cost & cost ) {
54        if ( expr->result.as< ast::ReferenceType >() ) {
55                // cast away reference from expr
56                cost.incReference();
57                return new ast::CastExpr{ expr, expr->result->stripReferences() };
58        }
59
60        return expr;
61}
62
63/// Unique identifier for matching expression resolutions to their requesting expression
64UniqueId globalResnSlot = 0;
65
66Cost computeConversionCost(
67        const ast::Type * argType, const ast::Type * paramType, bool argIsLvalue,
68        const ast::SymbolTable & symtab, const ast::TypeEnvironment & env
69) {
70        PRINT(
71                std::cerr << std::endl << "converting ";
72                ast::print( std::cerr, argType, 2 );
73                std::cerr << std::endl << " to ";
74                ast::print( std::cerr, paramType, 2 );
75                std::cerr << std::endl << "environment is: ";
76                ast::print( std::cerr, env, 2 );
77                std::cerr << std::endl;
78        )
79        Cost convCost = conversionCost( argType, paramType, argIsLvalue, symtab, env );
80        PRINT(
81                std::cerr << std::endl << "cost is " << convCost << std::endl;
82        )
83        if ( convCost == Cost::infinity ) return convCost;
84        convCost.incPoly( polyCost( paramType, symtab, env ) + polyCost( argType, symtab, env ) );
85        PRINT(
86                std::cerr << "cost with polycost is " << convCost << std::endl;
87        )
88        return convCost;
89}
90
91namespace {
92        /// First index is which argument, second is which alternative, third is which exploded element
93        using ExplodedArgs_new = std::deque< std::vector< ExplodedArg > >;
94
95        /// Returns a list of alternatives with the minimum cost in the given list
96        CandidateList findMinCost( const CandidateList & candidates ) {
97                CandidateList out;
98                Cost minCost = Cost::infinity;
99                for ( const CandidateRef & r : candidates ) {
100                        if ( r->cost < minCost ) {
101                                minCost = r->cost;
102                                out.clear();
103                                out.emplace_back( r );
104                        } else if ( r->cost == minCost ) {
105                                out.emplace_back( r );
106                        }
107                }
108                return out;
109        }
110
111        /// Computes conversion cost for a given expression to a given type
112        const ast::Expr * computeExpressionConversionCost(
113                const ast::Expr * arg, const ast::Type * paramType, const ast::SymbolTable & symtab, const ast::TypeEnvironment & env, Cost & outCost
114        ) {
115                Cost convCost = computeConversionCost(
116                                arg->result, paramType, arg->get_lvalue(), symtab, env );
117                outCost += convCost;
118
119                // If there is a non-zero conversion cost, ignoring poly cost, then the expression requires
120                // conversion. Ignore poly cost for now, since this requires resolution of the cast to
121                // infer parameters and this does not currently work for the reason stated below
122                Cost tmpCost = convCost;
123                tmpCost.incPoly( -tmpCost.get_polyCost() );
124                if ( tmpCost != Cost::zero ) {
125                        ast::ptr< ast::Type > newType = paramType;
126                        env.apply( newType );
127                        return new ast::CastExpr{ arg, newType };
128
129                        // xxx - *should* be able to resolve this cast, but at the moment pointers are not
130                        // castable to zero_t, but are implicitly convertible. This is clearly inconsistent,
131                        // once this is fixed it should be possible to resolve the cast.
132                        // xxx - this isn't working, it appears because type1 (parameter) is seen as widenable,
133                        // but it shouldn't be because this makes the conversion from DT* to DT* since
134                        // commontype(zero_t, DT*) is DT*, rather than nothing
135
136                        // CandidateFinder finder{ symtab, env };
137                        // finder.find( arg, ResolvMode::withAdjustment() );
138                        // assertf( finder.candidates.size() > 0,
139                        //      "Somehow castable expression failed to find alternatives." );
140                        // assertf( finder.candidates.size() == 1,
141                        //      "Somehow got multiple alternatives for known cast expression." );
142                        // return finder.candidates.front()->expr;
143                }
144
145                return arg;
146        }
147
148        /// Computes conversion cost for a given candidate
149        Cost computeApplicationConversionCost(
150                CandidateRef cand, const ast::SymbolTable & symtab
151        ) {
152                auto appExpr = cand->expr.strict_as< ast::ApplicationExpr >();
153                auto pointer = appExpr->func->result.strict_as< ast::PointerType >();
154                auto function = pointer->base.strict_as< ast::FunctionType >();
155
156                Cost convCost = Cost::zero;
157                const auto & params = function->params;
158                auto param = params.begin();
159                auto & args = appExpr->args;
160
161                for ( unsigned i = 0; i < args.size(); ++i ) {
162                        const ast::Type * argType = args[i]->result;
163                        PRINT(
164                                std::cerr << "arg expression:" << std::endl;
165                                ast::print( std::cerr, args[i], 2 );
166                                std::cerr << "--- results are" << std::endl;
167                                ast::print( std::cerr, argType, 2 );
168                        )
169
170                        if ( param == params.end() ) {
171                                if ( function->isVarArgs ) {
172                                        convCost.incUnsafe();
173                                        PRINT( std::cerr << "end of params with varargs function: inc unsafe: "
174                                                << convCost << std::endl; ; )
175                                        // convert reference-typed expressions into value-typed expressions
176                                        cand->expr = ast::mutate_field_index(
177                                                appExpr, &ast::ApplicationExpr::args, i,
178                                                referenceToRvalueConversion( args[i], convCost ) );
179                                        continue;
180                                } else return Cost::infinity;
181                        }
182
183                        if ( auto def = args[i].as< ast::DefaultArgExpr >() ) {
184                                // Default arguments should be free - don't include conversion cost.
185                                // Unwrap them here because they are not relevant to the rest of the system
186                                cand->expr = ast::mutate_field_index(
187                                        appExpr, &ast::ApplicationExpr::args, i, def->expr );
188                                ++param;
189                                continue;
190                        }
191
192                        // mark conversion cost and also specialization cost of param type
193                        // const ast::Type * paramType = (*param)->get_type();
194                        cand->expr = ast::mutate_field_index(
195                                appExpr, &ast::ApplicationExpr::args, i,
196                                computeExpressionConversionCost(
197                                        args[i], *param, symtab, cand->env, convCost ) );
198                        convCost.decSpec( specCost( *param ) );
199                        ++param;  // can't be in for-loop update because of the continue
200                }
201
202                if ( param != params.end() ) return Cost::infinity;
203
204                // specialization cost of return types can't be accounted for directly, it disables
205                // otherwise-identical calls, like this example based on auto-newline in the I/O lib:
206                //
207                //   forall(otype OS) {
208                //     void ?|?(OS&, int);  // with newline
209                //     OS&  ?|?(OS&, int);  // no newline, always chosen due to more specialization
210                //   }
211
212                // mark type variable and specialization cost of forall clause
213                convCost.incVar( function->forall.size() );
214                convCost.decSpec( function->assertions.size() );
215
216                return convCost;
217        }
218
219        void makeUnifiableVars(
220                const ast::FunctionType * type, ast::OpenVarSet & unifiableVars,
221                ast::AssertionSet & need
222        ) {
223                for ( auto & tyvar : type->forall ) {
224                        unifiableVars[ *tyvar ] = ast::TypeDecl::Data{ tyvar->base };
225                }
226                for ( auto & assn : type->assertions ) {
227                        need[ assn ].isUsed = true;
228                }
229        }
230
231        /// Gets a default value from an initializer, nullptr if not present
232        const ast::ConstantExpr * getDefaultValue( const ast::Init * init ) {
233                if ( auto si = dynamic_cast< const ast::SingleInit * >( init ) ) {
234                        if ( auto ce = si->value.as< ast::CastExpr >() ) {
235                                return ce->arg.as< ast::ConstantExpr >();
236                        } else {
237                                return si->value.as< ast::ConstantExpr >();
238                        }
239                }
240                return nullptr;
241        }
242
243        /// State to iteratively build a match of parameter expressions to arguments
244        struct ArgPack {
245                std::size_t parent;          ///< Index of parent pack
246                ast::ptr< ast::Expr > expr;  ///< The argument stored here
247                Cost cost;                   ///< The cost of this argument
248                ast::TypeEnvironment env;    ///< Environment for this pack
249                ast::AssertionSet need;      ///< Assertions outstanding for this pack
250                ast::AssertionSet have;      ///< Assertions found for this pack
251                ast::OpenVarSet open;        ///< Open variables for this pack
252                unsigned nextArg;            ///< Index of next argument in arguments list
253                unsigned tupleStart;         ///< Number of tuples that start at this index
254                unsigned nextExpl;           ///< Index of next exploded element
255                unsigned explAlt;            ///< Index of alternative for nextExpl > 0
256
257                ArgPack()
258                : parent( 0 ), expr(), cost( Cost::zero ), env(), need(), have(), open(), nextArg( 0 ),
259                  tupleStart( 0 ), nextExpl( 0 ), explAlt( 0 ) {}
260
261                ArgPack(
262                        const ast::TypeEnvironment & env, const ast::AssertionSet & need,
263                        const ast::AssertionSet & have, const ast::OpenVarSet & open )
264                : parent( 0 ), expr(), cost( Cost::zero ), env( env ), need( need ), have( have ),
265                  open( open ), nextArg( 0 ), tupleStart( 0 ), nextExpl( 0 ), explAlt( 0 ) {}
266
267                ArgPack(
268                        std::size_t parent, const ast::Expr * expr, ast::TypeEnvironment && env,
269                        ast::AssertionSet && need, ast::AssertionSet && have, ast::OpenVarSet && open,
270                        unsigned nextArg, unsigned tupleStart = 0, Cost cost = Cost::zero,
271                        unsigned nextExpl = 0, unsigned explAlt = 0 )
272                : parent(parent), expr( expr ), cost( cost ), env( move( env ) ), need( move( need ) ),
273                  have( move( have ) ), open( move( open ) ), nextArg( nextArg ), tupleStart( tupleStart ),
274                  nextExpl( nextExpl ), explAlt( explAlt ) {}
275
276                ArgPack(
277                        const ArgPack & o, ast::TypeEnvironment && env, ast::AssertionSet && need,
278                        ast::AssertionSet && have, ast::OpenVarSet && open, unsigned nextArg, Cost added )
279                : parent( o.parent ), expr( o.expr ), cost( o.cost + added ), env( move( env ) ),
280                  need( move( need ) ), have( move( have ) ), open( move( open ) ), nextArg( nextArg ),
281                  tupleStart( o.tupleStart ), nextExpl( 0 ), explAlt( 0 ) {}
282
283                /// true if this pack is in the middle of an exploded argument
284                bool hasExpl() const { return nextExpl > 0; }
285
286                /// Gets the list of exploded candidates for this pack
287                const ExplodedArg & getExpl( const ExplodedArgs_new & args ) const {
288                        return args[ nextArg-1 ][ explAlt ];
289                }
290
291                /// Ends a tuple expression, consolidating the appropriate args
292                void endTuple( const std::vector< ArgPack > & packs ) {
293                        // add all expressions in tuple to list, summing cost
294                        std::deque< const ast::Expr * > exprs;
295                        const ArgPack * pack = this;
296                        if ( expr ) { exprs.emplace_front( expr ); }
297                        while ( pack->tupleStart == 0 ) {
298                                pack = &packs[pack->parent];
299                                exprs.emplace_front( pack->expr );
300                                cost += pack->cost;
301                        }
302                        // reset pack to appropriate tuple
303                        std::vector< ast::ptr< ast::Expr > > exprv( exprs.begin(), exprs.end() );
304                        expr = new ast::TupleExpr{ expr->location, move( exprv ) };
305                        tupleStart = pack->tupleStart - 1;
306                        parent = pack->parent;
307                }
308        };
309
310        /// Instantiates an argument to match a parameter, returns false if no matching results left
311        bool instantiateArgument(
312                const ast::Type * paramType, const ast::Init * init, const ExplodedArgs_new & args,
313                std::vector< ArgPack > & results, std::size_t & genStart, const ast::SymbolTable & symtab,
314                unsigned nTuples = 0
315        ) {
316                if ( auto tupleType = dynamic_cast< const ast::TupleType * >( paramType ) ) {
317                        // paramType is a TupleType -- group args into a TupleExpr
318                        ++nTuples;
319                        for ( const ast::Type * type : *tupleType ) {
320                                // xxx - dropping initializer changes behaviour from previous, but seems correct
321                                // ^^^ need to handle the case where a tuple has a default argument
322                                if ( ! instantiateArgument(
323                                        type, nullptr, args, results, genStart, symtab, nTuples ) ) return false;
324                                nTuples = 0;
325                        }
326                        // re-constitute tuples for final generation
327                        for ( auto i = genStart; i < results.size(); ++i ) {
328                                results[i].endTuple( results );
329                        }
330                        return true;
331                } else if ( const ast::TypeInstType * ttype = Tuples::isTtype( paramType ) ) {
332                        // paramType is a ttype, consumes all remaining arguments
333
334                        // completed tuples; will be spliced to end of results to finish
335                        std::vector< ArgPack > finalResults{};
336
337                        // iterate until all results completed
338                        std::size_t genEnd;
339                        ++nTuples;
340                        do {
341                                genEnd = results.size();
342
343                                // add another argument to results
344                                for ( std::size_t i = genStart; i < genEnd; ++i ) {
345                                        unsigned nextArg = results[i].nextArg;
346
347                                        // use next element of exploded tuple if present
348                                        if ( results[i].hasExpl() ) {
349                                                const ExplodedArg & expl = results[i].getExpl( args );
350
351                                                unsigned nextExpl = results[i].nextExpl + 1;
352                                                if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
353
354                                                results.emplace_back(
355                                                        i, expl.exprs[ results[i].nextExpl ], copy( results[i].env ),
356                                                        copy( results[i].need ), copy( results[i].have ),
357                                                        copy( results[i].open ), nextArg, nTuples, Cost::zero, nextExpl,
358                                                        results[i].explAlt );
359
360                                                continue;
361                                        }
362
363                                        // finish result when out of arguments
364                                        if ( nextArg >= args.size() ) {
365                                                ArgPack newResult{
366                                                        results[i].env, results[i].need, results[i].have, results[i].open };
367                                                newResult.nextArg = nextArg;
368                                                const ast::Type * argType = nullptr;
369
370                                                if ( nTuples > 0 || ! results[i].expr ) {
371                                                        // first iteration or no expression to clone,
372                                                        // push empty tuple expression
373                                                        newResult.parent = i;
374                                                        newResult.expr = new ast::TupleExpr{ CodeLocation{}, {} };
375                                                        argType = newResult.expr->result;
376                                                } else {
377                                                        // clone result to collect tuple
378                                                        newResult.parent = results[i].parent;
379                                                        newResult.cost = results[i].cost;
380                                                        newResult.tupleStart = results[i].tupleStart;
381                                                        newResult.expr = results[i].expr;
382                                                        argType = newResult.expr->result;
383
384                                                        if ( results[i].tupleStart > 0 && Tuples::isTtype( argType ) ) {
385                                                                // the case where a ttype value is passed directly is special,
386                                                                // e.g. for argument forwarding purposes
387                                                                // xxx - what if passing multiple arguments, last of which is
388                                                                //       ttype?
389                                                                // xxx - what would happen if unify was changed so that unifying
390                                                                //       tuple
391                                                                // types flattened both before unifying lists? then pass in
392                                                                // TupleType (ttype) below.
393                                                                --newResult.tupleStart;
394                                                        } else {
395                                                                // collapse leftover arguments into tuple
396                                                                newResult.endTuple( results );
397                                                                argType = newResult.expr->result;
398                                                        }
399                                                }
400
401                                                // check unification for ttype before adding to final
402                                                if (
403                                                        unify(
404                                                                ttype, argType, newResult.env, newResult.need, newResult.have,
405                                                                newResult.open, symtab )
406                                                ) {
407                                                        finalResults.emplace_back( move( newResult ) );
408                                                }
409
410                                                continue;
411                                        }
412
413                                        // add each possible next argument
414                                        for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
415                                                const ExplodedArg & expl = args[nextArg][j];
416
417                                                // fresh copies of parent parameters for this iteration
418                                                ast::TypeEnvironment env = results[i].env;
419                                                ast::OpenVarSet open = results[i].open;
420
421                                                env.addActual( expl.env, open );
422
423                                                // skip empty tuple arguments by (nearly) cloning parent into next gen
424                                                if ( expl.exprs.empty() ) {
425                                                        results.emplace_back(
426                                                                results[i], move( env ), copy( results[i].need ),
427                                                                copy( results[i].have ), move( open ), nextArg + 1, expl.cost );
428
429                                                        continue;
430                                                }
431
432                                                // add new result
433                                                results.emplace_back(
434                                                        i, expl.exprs.front(), move( env ), copy( results[i].need ),
435                                                        copy( results[i].have ), move( open ), nextArg + 1, nTuples,
436                                                        expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
437                                        }
438                                }
439
440                                // reset for next round
441                                genStart = genEnd;
442                                nTuples = 0;
443                        } while ( genEnd != results.size() );
444
445                        // splice final results onto results
446                        for ( std::size_t i = 0; i < finalResults.size(); ++i ) {
447                                results.emplace_back( move( finalResults[i] ) );
448                        }
449                        return ! finalResults.empty();
450                }
451
452                // iterate each current subresult
453                std::size_t genEnd = results.size();
454                for ( std::size_t i = genStart; i < genEnd; ++i ) {
455                        unsigned nextArg = results[i].nextArg;
456
457                        // use remainder of exploded tuple if present
458                        if ( results[i].hasExpl() ) {
459                                const ExplodedArg & expl = results[i].getExpl( args );
460                                const ast::Expr * expr = expl.exprs[ results[i].nextExpl ];
461
462                                ast::TypeEnvironment env = results[i].env;
463                                ast::AssertionSet need = results[i].need, have = results[i].have;
464                                ast::OpenVarSet open = results[i].open;
465
466                                const ast::Type * argType = expr->result;
467
468                                PRINT(
469                                        std::cerr << "param type is ";
470                                        ast::print( std::cerr, paramType );
471                                        std::cerr << std::endl << "arg type is ";
472                                        ast::print( std::cerr, argType );
473                                        std::cerr << std::endl;
474                                )
475
476                                if ( unify( paramType, argType, env, need, have, open, symtab ) ) {
477                                        unsigned nextExpl = results[i].nextExpl + 1;
478                                        if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
479
480                                        results.emplace_back(
481                                                i, expr, move( env ), move( need ), move( have ), move( open ), nextArg,
482                                                nTuples, Cost::zero, nextExpl, results[i].explAlt );
483                                }
484
485                                continue;
486                        }
487
488                        // use default initializers if out of arguments
489                        if ( nextArg >= args.size() ) {
490                                if ( const ast::ConstantExpr * cnst = getDefaultValue( init ) ) {
491                                        ast::TypeEnvironment env = results[i].env;
492                                        ast::AssertionSet need = results[i].need, have = results[i].have;
493                                        ast::OpenVarSet open = results[i].open;
494
495                                        if ( unify( paramType, cnst->result, env, need, have, open, symtab ) ) {
496                                                results.emplace_back(
497                                                        i, new ast::DefaultArgExpr{ cnst->location, cnst }, move( env ),
498                                                        move( need ), move( have ), move( open ), nextArg, nTuples );
499                                        }
500                                }
501
502                                continue;
503                        }
504
505                        // Check each possible next argument
506                        for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
507                                const ExplodedArg & expl = args[nextArg][j];
508
509                                // fresh copies of parent parameters for this iteration
510                                ast::TypeEnvironment env = results[i].env;
511                                ast::AssertionSet need = results[i].need, have = results[i].have;
512                                ast::OpenVarSet open = results[i].open;
513
514                                env.addActual( expl.env, open );
515
516                                // skip empty tuple arguments by (nearly) cloning parent into next gen
517                                if ( expl.exprs.empty() ) {
518                                        results.emplace_back(
519                                                results[i], move( env ), move( need ), move( have ), move( open ),
520                                                nextArg + 1, expl.cost );
521
522                                        continue;
523                                }
524
525                                // consider only first exploded arg
526                                const ast::Expr * expr = expl.exprs.front();
527                                const ast::Type * argType = expr->result;
528
529                                PRINT(
530                                        std::cerr << "param type is ";
531                                        ast::print( std::cerr, paramType );
532                                        std::cerr << std::endl << "arg type is ";
533                                        ast::print( std::cerr, argType );
534                                        std::cerr << std::endl;
535                                )
536
537                                // attempt to unify types
538                                if ( unify( paramType, argType, env, need, have, open, symtab ) ) {
539                                        // add new result
540                                        results.emplace_back(
541                                                i, expr, move( env ), move( need ), move( have ), move( open ),
542                                                nextArg + 1, nTuples, expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
543                                }
544                        }
545                }
546
547                // reset for next parameter
548                genStart = genEnd;
549
550                return genEnd != results.size();  // were any new results added?
551        }
552
553        /// Generate a cast expression from `arg` to `toType`
554        const ast::Expr * restructureCast(
555                ast::ptr< ast::Expr > & arg, const ast::Type * toType, ast::GeneratedFlag isGenerated = ast::GeneratedCast
556        ) {
557                if (
558                        arg->result->size() > 1
559                        && ! toType->isVoid()
560                        && ! dynamic_cast< const ast::ReferenceType * >( toType )
561                ) {
562                        // Argument is a tuple and the target type is neither void nor a reference. Cast each
563                        // member of the tuple to its corresponding target type, producing the tuple of those
564                        // cast expressions. If there are more components of the tuple than components in the
565                        // target type, then excess components do not come out in the result expression (but
566                        // UniqueExpr ensures that the side effects will still be produced)
567                        if ( Tuples::maybeImpureIgnoreUnique( arg ) ) {
568                                // expressions which may contain side effects require a single unique instance of
569                                // the expression
570                                arg = new ast::UniqueExpr{ arg->location, arg };
571                        }
572                        std::vector< ast::ptr< ast::Expr > > components;
573                        for ( unsigned i = 0; i < toType->size(); ++i ) {
574                                // cast each component
575                                ast::ptr< ast::Expr > idx = new ast::TupleIndexExpr{ arg->location, arg, i };
576                                components.emplace_back(
577                                        restructureCast( idx, toType->getComponent( i ), isGenerated ) );
578                        }
579                        return new ast::TupleExpr{ arg->location, move( components ) };
580                } else {
581                        // handle normally
582                        return new ast::CastExpr{ arg->location, arg, toType, isGenerated };
583                }
584        }
585
586        /// Gets the name from an untyped member expression (must be NameExpr)
587        const std::string & getMemberName( const ast::UntypedMemberExpr * memberExpr ) {
588                if ( memberExpr->member.as< ast::ConstantExpr >() ) {
589                        SemanticError( memberExpr, "Indexed access to struct fields unsupported: " );
590                }
591
592                return memberExpr->member.strict_as< ast::NameExpr >()->name;
593        }
594
595        /// Actually visits expressions to find their candidate interpretations
596        class Finder final : public ast::WithShortCircuiting {
597                const ast::SymbolTable & symtab;
598        public:
599                static size_t traceId;
600                CandidateFinder & selfFinder;
601                CandidateList & candidates;
602                const ast::TypeEnvironment & tenv;
603                ast::ptr< ast::Type > & targetType;
604
605                enum Errors {
606                        NotFound,
607                        NoMatch,
608                        ArgsToFew,
609                        ArgsToMany,
610                        RetsToFew,
611                        RetsToMany,
612                        NoReason
613                };
614
615                struct {
616                        Errors code = NotFound;
617                } reason;
618
619                Finder( CandidateFinder & f )
620                : symtab( f.localSyms ), selfFinder( f ), candidates( f.candidates ), tenv( f.env ),
621                  targetType( f.targetType ) {}
622
623                void previsit( const ast::Node * ) { visit_children = false; }
624
625                /// Convenience to add candidate to list
626                template<typename... Args>
627                void addCandidate( Args &&... args ) {
628                        candidates.emplace_back( new Candidate{ std::forward<Args>( args )... } );
629                        reason.code = NoReason;
630                }
631
632                void postvisit( const ast::ApplicationExpr * applicationExpr ) {
633                        addCandidate( applicationExpr, tenv );
634                }
635
636                /// Set up candidate assertions for inference
637                void inferParameters( CandidateRef & newCand, CandidateList & out ) {
638                        // Set need bindings for any unbound assertions
639                        UniqueId crntResnSlot = 0; // matching ID for this expression's assertions
640                        for ( auto & assn : newCand->need ) {
641                                // skip already-matched assertions
642                                if ( assn.second.resnSlot != 0 ) continue;
643                                // assign slot for expression if needed
644                                if ( crntResnSlot == 0 ) { crntResnSlot = ++globalResnSlot; }
645                                // fix slot to assertion
646                                assn.second.resnSlot = crntResnSlot;
647                        }
648                        // pair slot to expression
649                        if ( crntResnSlot != 0 ) {
650                                newCand->expr.get_and_mutate()->inferred.resnSlots().emplace_back( crntResnSlot );
651                        }
652
653                        // add to output list; assertion satisfaction will occur later
654                        out.emplace_back( newCand );
655                }
656
657                /// Completes a function candidate with arguments located
658                void validateFunctionCandidate(
659                        const CandidateRef & func, ArgPack & result, const std::vector< ArgPack > & results,
660                        CandidateList & out
661                ) {
662                        ast::ApplicationExpr * appExpr =
663                                new ast::ApplicationExpr{ func->expr->location, func->expr };
664                        // sum cost and accumulate arguments
665                        std::deque< const ast::Expr * > args;
666                        Cost cost = func->cost;
667                        const ArgPack * pack = &result;
668                        while ( pack->expr ) {
669                                args.emplace_front( pack->expr );
670                                cost += pack->cost;
671                                pack = &results[pack->parent];
672                        }
673                        std::vector< ast::ptr< ast::Expr > > vargs( args.begin(), args.end() );
674                        appExpr->args = move( vargs );
675                        // build and validate new candidate
676                        auto newCand =
677                                std::make_shared<Candidate>( appExpr, result.env, result.open, result.need, cost );
678                        PRINT(
679                                std::cerr << "instantiate function success: " << appExpr << std::endl;
680                                std::cerr << "need assertions:" << std::endl;
681                                ast::print( std::cerr, result.need, 2 );
682                        )
683                        inferParameters( newCand, out );
684                }
685
686                /// Builds a list of candidates for a function, storing them in out
687                void makeFunctionCandidates(
688                        const CandidateRef & func, const ast::FunctionType * funcType,
689                        const ExplodedArgs_new & args, CandidateList & out
690                ) {
691                        ast::OpenVarSet funcOpen;
692                        ast::AssertionSet funcNeed, funcHave;
693                        ast::TypeEnvironment funcEnv{ func->env };
694                        makeUnifiableVars( funcType, funcOpen, funcNeed );
695                        // add all type variables as open variables now so that those not used in the
696                        // parameter list are still considered open
697                        funcEnv.add( funcType->forall );
698
699                        if ( targetType && ! targetType->isVoid() && ! funcType->returns.empty() ) {
700                                // attempt to narrow based on expected target type
701                                const ast::Type * returnType = funcType->returns.front();
702                                if ( ! unify(
703                                        returnType, targetType, funcEnv, funcNeed, funcHave, funcOpen, symtab )
704                                ) {
705                                        // unification failed, do not pursue this candidate
706                                        return;
707                                }
708                        }
709
710                        // iteratively build matches, one parameter at a time
711                        std::vector< ArgPack > results;
712                        results.emplace_back( funcEnv, funcNeed, funcHave, funcOpen );
713                        std::size_t genStart = 0;
714
715                        // xxx - how to handle default arg after change to ftype representation?
716                        if (const ast::VariableExpr * varExpr = func->expr.as<ast::VariableExpr>()) {
717                                if (const ast::FunctionDecl * funcDecl = varExpr->var.as<ast::FunctionDecl>()) {
718                                        // function may have default args only if directly calling by name
719                                        // must use types on candidate however, due to RenameVars substitution
720                                        auto nParams = funcType->params.size();
721
722                                        for (size_t i=0; i<nParams; ++i) {
723                                                auto obj = funcDecl->params[i].strict_as<ast::ObjectDecl>();
724                                                if (!instantiateArgument(
725                                                        funcType->params[i], obj->init, args, results, genStart, symtab)) return;
726                                        }
727                                        goto endMatch;
728                                }
729                        }
730                        for ( const auto & param : funcType->params ) {
731                                // Try adding the arguments corresponding to the current parameter to the existing
732                                // matches
733                                // no default args for indirect calls
734                                if ( ! instantiateArgument(
735                                        param, nullptr, args, results, genStart, symtab ) ) return;
736                        }
737
738                        endMatch:
739                        if ( funcType->isVarArgs ) {
740                                // append any unused arguments to vararg pack
741                                std::size_t genEnd;
742                                do {
743                                        genEnd = results.size();
744
745                                        // iterate results
746                                        for ( std::size_t i = genStart; i < genEnd; ++i ) {
747                                                unsigned nextArg = results[i].nextArg;
748
749                                                // use remainder of exploded tuple if present
750                                                if ( results[i].hasExpl() ) {
751                                                        const ExplodedArg & expl = results[i].getExpl( args );
752
753                                                        unsigned nextExpl = results[i].nextExpl + 1;
754                                                        if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
755
756                                                        results.emplace_back(
757                                                                i, expl.exprs[ results[i].nextExpl ], copy( results[i].env ),
758                                                                copy( results[i].need ), copy( results[i].have ),
759                                                                copy( results[i].open ), nextArg, 0, Cost::zero, nextExpl,
760                                                                results[i].explAlt );
761
762                                                        continue;
763                                                }
764
765                                                // finish result when out of arguments
766                                                if ( nextArg >= args.size() ) {
767                                                        validateFunctionCandidate( func, results[i], results, out );
768
769                                                        continue;
770                                                }
771
772                                                // add each possible next argument
773                                                for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
774                                                        const ExplodedArg & expl = args[nextArg][j];
775
776                                                        // fresh copies of parent parameters for this iteration
777                                                        ast::TypeEnvironment env = results[i].env;
778                                                        ast::OpenVarSet open = results[i].open;
779
780                                                        env.addActual( expl.env, open );
781
782                                                        // skip empty tuple arguments by (nearly) cloning parent into next gen
783                                                        if ( expl.exprs.empty() ) {
784                                                                results.emplace_back(
785                                                                        results[i], move( env ), copy( results[i].need ),
786                                                                        copy( results[i].have ), move( open ), nextArg + 1,
787                                                                        expl.cost );
788
789                                                                continue;
790                                                        }
791
792                                                        // add new result
793                                                        results.emplace_back(
794                                                                i, expl.exprs.front(), move( env ), copy( results[i].need ),
795                                                                copy( results[i].have ), move( open ), nextArg + 1, 0, expl.cost,
796                                                                expl.exprs.size() == 1 ? 0 : 1, j );
797                                                }
798                                        }
799
800                                        genStart = genEnd;
801                                } while( genEnd != results.size() );
802                        } else {
803                                // filter out the results that don't use all the arguments
804                                for ( std::size_t i = genStart; i < results.size(); ++i ) {
805                                        ArgPack & result = results[i];
806                                        if ( ! result.hasExpl() && result.nextArg >= args.size() ) {
807                                                validateFunctionCandidate( func, result, results, out );
808                                        }
809                                }
810                        }
811                }
812
813                /// Adds implicit struct-conversions to the alternative list
814                void addAnonConversions( const CandidateRef & cand ) {
815                        // adds anonymous member interpretations whenever an aggregate value type is seen.
816                        // it's okay for the aggregate expression to have reference type -- cast it to the
817                        // base type to treat the aggregate as the referenced value
818                        ast::ptr< ast::Expr > aggrExpr( cand->expr );
819                        ast::ptr< ast::Type > & aggrType = aggrExpr.get_and_mutate()->result;
820                        cand->env.apply( aggrType );
821
822                        if ( aggrType.as< ast::ReferenceType >() ) {
823                                aggrExpr = new ast::CastExpr{ aggrExpr, aggrType->stripReferences() };
824                        }
825
826                        if ( auto structInst = aggrExpr->result.as< ast::StructInstType >() ) {
827                                addAggMembers( structInst, aggrExpr, *cand, Cost::safe, "" );
828                        } else if ( auto unionInst = aggrExpr->result.as< ast::UnionInstType >() ) {
829                                addAggMembers( unionInst, aggrExpr, *cand, Cost::safe, "" );
830                        }
831                }
832
833                /// Adds aggregate member interpretations
834                void addAggMembers(
835                        const ast::BaseInstType * aggrInst, const ast::Expr * expr,
836                        const Candidate & cand, const Cost & addedCost, const std::string & name
837                ) {
838                        for ( const ast::Decl * decl : aggrInst->lookup( name ) ) {
839                                auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( decl );
840                                CandidateRef newCand = std::make_shared<Candidate>(
841                                        cand, new ast::MemberExpr{ expr->location, dwt, expr }, addedCost );
842                                // add anonymous member interpretations whenever an aggregate value type is seen
843                                // as a member expression
844                                addAnonConversions( newCand );
845                                candidates.emplace_back( move( newCand ) );
846                        }
847                }
848
849                /// Adds tuple member interpretations
850                void addTupleMembers(
851                        const ast::TupleType * tupleType, const ast::Expr * expr, const Candidate & cand,
852                        const Cost & addedCost, const ast::Expr * member
853                ) {
854                        if ( auto constantExpr = dynamic_cast< const ast::ConstantExpr * >( member ) ) {
855                                // get the value of the constant expression as an int, must be between 0 and the
856                                // length of the tuple to have meaning
857                                long long val = constantExpr->intValue();
858                                if ( val >= 0 && (unsigned long long)val < tupleType->size() ) {
859                                        addCandidate(
860                                                cand, new ast::TupleIndexExpr{ expr->location, expr, (unsigned)val },
861                                                addedCost );
862                                }
863                        }
864                }
865
866                void postvisit( const ast::UntypedExpr * untypedExpr ) {
867                        std::vector< CandidateFinder > argCandidates =
868                                selfFinder.findSubExprs( untypedExpr->args );
869
870                        // take care of possible tuple assignments
871                        // if not tuple assignment, handled as normal function call
872                        Tuples::handleTupleAssignment( selfFinder, untypedExpr, argCandidates );
873
874                        CandidateFinder funcFinder{ symtab, tenv };
875                        if (auto nameExpr = untypedExpr->func.as<ast::NameExpr>()) {
876                                auto kind = ast::SymbolTable::getSpecialFunctionKind(nameExpr->name);
877                                if (kind != ast::SymbolTable::SpecialFunctionKind::NUMBER_OF_KINDS) {
878                                        assertf(!argCandidates.empty(), "special function call without argument");
879                                        for (auto & firstArgCand: argCandidates[0]) {
880                                                ast::ptr<ast::Type> argType = firstArgCand->expr->result;
881                                                firstArgCand->env.apply(argType);
882                                                // strip references
883                                                // xxx - is this correct?
884                                                while (argType.as<ast::ReferenceType>()) argType = argType.as<ast::ReferenceType>()->base;
885
886                                                // convert 1-tuple to plain type
887                                                if (auto tuple = argType.as<ast::TupleType>()) {
888                                                        if (tuple->size() == 1) {
889                                                                argType = tuple->types[0];
890                                                        }
891                                                }
892                                               
893                                                // if argType is an unbound type parameter, all special functions need to be searched.
894                                                if (isUnboundType(argType)) {
895                                                        funcFinder.otypeKeys.clear();
896                                                        break;
897                                                }
898
899                                                if (argType.as<ast::PointerType>()) funcFinder.otypeKeys.insert(Mangle::Encoding::pointer);
900                                                else funcFinder.otypeKeys.insert(Mangle::mangle(argType, Mangle::NoGenericParams | Mangle::Type));
901                                        }
902                                }
903                        }
904                        // if candidates are already produced, do not fail
905                        // xxx - is it possible that handleTupleAssignment and main finder both produce candidates?
906                        // this means there exists ctor/assign functions with a tuple as first parameter.
907                        funcFinder.find( untypedExpr->func, selfFinder.candidates.empty() ? ResolvMode::withAdjustment() : ResolvMode::withoutFailFast() );
908                        // short-circuit if no candidates
909                        // if ( funcFinder.candidates.empty() ) return;
910
911                        reason.code = NoMatch;
912
913                        // find function operators
914                        ast::ptr< ast::Expr > opExpr = new ast::NameExpr{ untypedExpr->location, "?()" };
915                        CandidateFinder opFinder{ symtab, tenv };
916                        // okay if there aren't any function operations
917                        opFinder.find( opExpr, ResolvMode::withoutFailFast() );
918                        PRINT(
919                                std::cerr << "known function ops:" << std::endl;
920                                print( std::cerr, opFinder.candidates, 1 );
921                        )
922
923                        // pre-explode arguments
924                        ExplodedArgs_new argExpansions;
925                        for ( const CandidateFinder & args : argCandidates ) {
926                                argExpansions.emplace_back();
927                                auto & argE = argExpansions.back();
928                                for ( const CandidateRef & arg : args ) { argE.emplace_back( *arg, symtab ); }
929                        }
930
931                        // Find function matches
932                        CandidateList found;
933                        SemanticErrorException errors;
934                        for ( CandidateRef & func : funcFinder ) {
935                                try {
936                                        PRINT(
937                                                std::cerr << "working on alternative:" << std::endl;
938                                                print( std::cerr, *func, 2 );
939                                        )
940
941                                        // check if the type is a pointer to function
942                                        const ast::Type * funcResult = func->expr->result->stripReferences();
943                                        if ( auto pointer = dynamic_cast< const ast::PointerType * >( funcResult ) ) {
944                                                if ( auto function = pointer->base.as< ast::FunctionType >() ) {
945                                                        CandidateRef newFunc{ new Candidate{ *func } };
946                                                        newFunc->expr =
947                                                                referenceToRvalueConversion( newFunc->expr, newFunc->cost );
948                                                        makeFunctionCandidates( newFunc, function, argExpansions, found );
949                                                }
950                                        } else if (
951                                                auto inst = dynamic_cast< const ast::TypeInstType * >( funcResult )
952                                        ) {
953                                                if ( const ast::EqvClass * clz = func->env.lookup( *inst ) ) {
954                                                        if ( auto function = clz->bound.as< ast::FunctionType >() ) {
955                                                                CandidateRef newFunc{ new Candidate{ *func } };
956                                                                newFunc->expr =
957                                                                        referenceToRvalueConversion( newFunc->expr, newFunc->cost );
958                                                                makeFunctionCandidates( newFunc, function, argExpansions, found );
959                                                        }
960                                                }
961                                        }
962                                } catch ( SemanticErrorException & e ) { errors.append( e ); }
963                        }
964
965                        // Find matches on function operators `?()`
966                        if ( ! opFinder.candidates.empty() ) {
967                                // add exploded function alternatives to front of argument list
968                                std::vector< ExplodedArg > funcE;
969                                funcE.reserve( funcFinder.candidates.size() );
970                                for ( const CandidateRef & func : funcFinder ) {
971                                        funcE.emplace_back( *func, symtab );
972                                }
973                                argExpansions.emplace_front( move( funcE ) );
974
975                                for ( const CandidateRef & op : opFinder ) {
976                                        try {
977                                                // check if type is pointer-to-function
978                                                const ast::Type * opResult = op->expr->result->stripReferences();
979                                                if ( auto pointer = dynamic_cast< const ast::PointerType * >( opResult ) ) {
980                                                        if ( auto function = pointer->base.as< ast::FunctionType >() ) {
981                                                                CandidateRef newOp{ new Candidate{ *op} };
982                                                                newOp->expr =
983                                                                        referenceToRvalueConversion( newOp->expr, newOp->cost );
984                                                                makeFunctionCandidates( newOp, function, argExpansions, found );
985                                                        }
986                                                }
987                                        } catch ( SemanticErrorException & e ) { errors.append( e ); }
988                                }
989                        }
990
991                        // Implement SFINAE; resolution errors are only errors if there aren't any non-error
992                        // candidates
993                        if ( found.empty() && ! errors.isEmpty() ) { throw errors; }
994
995                        // Compute conversion costs
996                        for ( CandidateRef & withFunc : found ) {
997                                Cost cvtCost = computeApplicationConversionCost( withFunc, symtab );
998
999                                PRINT(
1000                                        auto appExpr = withFunc->expr.strict_as< ast::ApplicationExpr >();
1001                                        auto pointer = appExpr->func->result.strict_as< ast::PointerType >();
1002                                        auto function = pointer->base.strict_as< ast::FunctionType >();
1003
1004                                        std::cerr << "Case +++++++++++++ " << appExpr->func << std::endl;
1005                                        std::cerr << "parameters are:" << std::endl;
1006                                        ast::printAll( std::cerr, function->params, 2 );
1007                                        std::cerr << "arguments are:" << std::endl;
1008                                        ast::printAll( std::cerr, appExpr->args, 2 );
1009                                        std::cerr << "bindings are:" << std::endl;
1010                                        ast::print( std::cerr, withFunc->env, 2 );
1011                                        std::cerr << "cost is: " << withFunc->cost << std::endl;
1012                                        std::cerr << "cost of conversion is:" << cvtCost << std::endl;
1013                                )
1014
1015                                if ( cvtCost != Cost::infinity ) {
1016                                        withFunc->cvtCost = cvtCost;
1017                                        candidates.emplace_back( move( withFunc ) );
1018                                }
1019                        }
1020                        found = move( candidates );
1021
1022                        // use a new list so that candidates are not examined by addAnonConversions twice
1023                        CandidateList winners = findMinCost( found );
1024                        promoteCvtCost( winners );
1025
1026                        // function may return a struct/union value, in which case we need to add candidates
1027                        // for implicit conversions to each of the anonymous members, which must happen after
1028                        // `findMinCost`, since anon conversions are never the cheapest
1029                        for ( const CandidateRef & c : winners ) {
1030                                addAnonConversions( c );
1031                        }
1032                        spliceBegin( candidates, winners );
1033
1034                        if ( candidates.empty() && targetType && ! targetType->isVoid() ) {
1035                                // If resolution is unsuccessful with a target type, try again without, since it
1036                                // will sometimes succeed when it wouldn't with a target type binding.
1037                                // For example:
1038                                //   forall( otype T ) T & ?[]( T *, ptrdiff_t );
1039                                //   const char * x = "hello world";
1040                                //   unsigned char ch = x[0];
1041                                // Fails with simple return type binding (xxx -- check this!) as follows:
1042                                // * T is bound to unsigned char
1043                                // * (x: const char *) is unified with unsigned char *, which fails
1044                                // xxx -- fix this better
1045                                targetType = nullptr;
1046                                postvisit( untypedExpr );
1047                        }
1048                }
1049
1050                /// true if expression is an lvalue
1051                static bool isLvalue( const ast::Expr * x ) {
1052                        return x->result && ( x->get_lvalue() || x->result.as< ast::ReferenceType >() );
1053                }
1054
1055                void postvisit( const ast::AddressExpr * addressExpr ) {
1056                        CandidateFinder finder{ symtab, tenv };
1057                        finder.find( addressExpr->arg );
1058
1059                        if( finder.candidates.empty() ) return;
1060
1061                        reason.code = NoMatch;
1062
1063                        for ( CandidateRef & r : finder.candidates ) {
1064                                if ( ! isLvalue( r->expr ) ) continue;
1065                                addCandidate( *r, new ast::AddressExpr{ addressExpr->location, r->expr } );
1066                        }
1067                }
1068
1069                void postvisit( const ast::LabelAddressExpr * labelExpr ) {
1070                        addCandidate( labelExpr, tenv );
1071                }
1072
1073                void postvisit( const ast::CastExpr * castExpr ) {
1074                        ast::ptr< ast::Type > toType = castExpr->result;
1075                        assert( toType );
1076                        toType = resolveTypeof( toType, symtab );
1077                        // toType = SymTab::validateType( castExpr->location, toType, symtab );
1078                        toType = adjustExprType( toType, tenv, symtab );
1079
1080                        CandidateFinder finder{ symtab, tenv, toType };
1081                        finder.find( castExpr->arg, ResolvMode::withAdjustment() );
1082
1083                        if( !finder.candidates.empty() ) reason.code = NoMatch;
1084
1085                        CandidateList matches;
1086                        for ( CandidateRef & cand : finder.candidates ) {
1087                                ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have;
1088                                ast::OpenVarSet open( cand->open );
1089
1090                                cand->env.extractOpenVars( open );
1091
1092                                // It is possible that a cast can throw away some values in a multiply-valued
1093                                // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of the
1094                                // subexpression results that are cast directly. The candidate is invalid if it
1095                                // has fewer results than there are types to cast to.
1096                                int discardedValues = cand->expr->result->size() - toType->size();
1097                                if ( discardedValues < 0 ) continue;
1098
1099                                // unification run for side-effects
1100                                unify( toType, cand->expr->result, cand->env, need, have, open, symtab );
1101                                Cost thisCost = 
1102                                        (castExpr->isGenerated == ast::GeneratedFlag::GeneratedCast)
1103                            ? conversionCost( cand->expr->result, toType, cand->expr->get_lvalue(), symtab, cand->env )
1104                            : castCost( cand->expr->result, toType, cand->expr->get_lvalue(), symtab, cand->env );
1105
1106                                PRINT(
1107                                        std::cerr << "working on cast with result: " << toType << std::endl;
1108                                        std::cerr << "and expr type: " << cand->expr->result << std::endl;
1109                                        std::cerr << "env: " << cand->env << std::endl;
1110                                )
1111                                if ( thisCost != Cost::infinity ) {
1112                                        PRINT(
1113                                                std::cerr << "has finite cost." << std::endl;
1114                                        )
1115                                        // count one safe conversion for each value that is thrown away
1116                                        thisCost.incSafe( discardedValues );
1117                                        CandidateRef newCand = std::make_shared<Candidate>(
1118                                                restructureCast( cand->expr, toType, castExpr->isGenerated ),
1119                                                copy( cand->env ), move( open ), move( need ), cand->cost,
1120                                                cand->cost + thisCost );
1121                                        inferParameters( newCand, matches );
1122                                }
1123                        }
1124
1125                        // select first on argument cost, then conversion cost
1126                        CandidateList minArgCost = findMinCost( matches );
1127                        promoteCvtCost( minArgCost );
1128                        candidates = findMinCost( minArgCost );
1129                }
1130
1131                void postvisit( const ast::VirtualCastExpr * castExpr ) {
1132                        assertf( castExpr->result, "Implicit virtual cast targets not yet supported." );
1133                        CandidateFinder finder{ symtab, tenv };
1134                        // don't prune here, all alternatives guaranteed to have same type
1135                        finder.find( castExpr->arg, ResolvMode::withoutPrune() );
1136                        for ( CandidateRef & r : finder.candidates ) {
1137                                addCandidate(
1138                                        *r,
1139                                        new ast::VirtualCastExpr{ castExpr->location, r->expr, castExpr->result } );
1140                        }
1141                }
1142
1143                void postvisit( const ast::KeywordCastExpr * castExpr ) {
1144                        const auto & loc = castExpr->location;
1145                        assertf( castExpr->result, "Cast target should have been set in Validate." );
1146                        auto ref = castExpr->result.strict_as<ast::ReferenceType>();
1147                        auto inst = ref->base.strict_as<ast::StructInstType>();
1148                        auto target = inst->base.get();
1149
1150                        CandidateFinder finder{ symtab, tenv };
1151
1152                        auto pick_alternatives = [target, this](CandidateList & found, bool expect_ref) {
1153                                for(auto & cand : found) {
1154                                        const ast::Type * expr = cand->expr->result.get();
1155                                        if(expect_ref) {
1156                                                auto res = dynamic_cast<const ast::ReferenceType*>(expr);
1157                                                if(!res) { continue; }
1158                                                expr = res->base.get();
1159                                        }
1160
1161                                        if(auto insttype = dynamic_cast<const ast::TypeInstType*>(expr)) {
1162                                                auto td = cand->env.lookup(*insttype);
1163                                                if(!td) { continue; }
1164                                                expr = td->bound.get();
1165                                        }
1166
1167                                        if(auto base = dynamic_cast<const ast::StructInstType*>(expr)) {
1168                                                if(base->base == target) {
1169                                                        candidates.push_back( std::move(cand) );
1170                                                        reason.code = NoReason;
1171                                                }
1172                                        }
1173                                }
1174                        };
1175
1176                        try {
1177                                // Attempt 1 : turn (thread&)X into ($thread&)X.__thrd
1178                                // Clone is purely for memory management
1179                                std::unique_ptr<const ast::Expr> tech1 { new ast::UntypedMemberExpr(loc, new ast::NameExpr(loc, castExpr->concrete_target.field), castExpr->arg) };
1180
1181                                // don't prune here, since it's guaranteed all alternatives will have the same type
1182                                finder.find( tech1.get(), ResolvMode::withoutPrune() );
1183                                pick_alternatives(finder.candidates, false);
1184
1185                                return;
1186                        } catch(SemanticErrorException & ) {}
1187
1188                        // Fallback : turn (thread&)X into ($thread&)get_thread(X)
1189                        std::unique_ptr<const ast::Expr> fallback { ast::UntypedExpr::createDeref(loc,  new ast::UntypedExpr(loc, new ast::NameExpr(loc, castExpr->concrete_target.getter), { castExpr->arg })) };
1190                        // don't prune here, since it's guaranteed all alternatives will have the same type
1191                        finder.find( fallback.get(), ResolvMode::withoutPrune() );
1192
1193                        pick_alternatives(finder.candidates, true);
1194
1195                        // Whatever happens here, we have no more fallbacks
1196                }
1197
1198                void postvisit( const ast::UntypedMemberExpr * memberExpr ) {
1199                        CandidateFinder aggFinder{ symtab, tenv };
1200                        aggFinder.find( memberExpr->aggregate, ResolvMode::withAdjustment() );
1201                        for ( CandidateRef & agg : aggFinder.candidates ) {
1202                                // it's okay for the aggregate expression to have reference type -- cast it to the
1203                                // base type to treat the aggregate as the referenced value
1204                                Cost addedCost = Cost::zero;
1205                                agg->expr = referenceToRvalueConversion( agg->expr, addedCost );
1206
1207                                // find member of the given type
1208                                if ( auto structInst = agg->expr->result.as< ast::StructInstType >() ) {
1209                                        addAggMembers(
1210                                                structInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) );
1211                                } else if ( auto unionInst = agg->expr->result.as< ast::UnionInstType >() ) {
1212                                        addAggMembers(
1213                                                unionInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) );
1214                                } else if ( auto tupleType = agg->expr->result.as< ast::TupleType >() ) {
1215                                        addTupleMembers( tupleType, agg->expr, *agg, addedCost, memberExpr->member );
1216                                }
1217                        }
1218                }
1219
1220                void postvisit( const ast::MemberExpr * memberExpr ) {
1221                        addCandidate( memberExpr, tenv );
1222                }
1223
1224                void postvisit( const ast::NameExpr * nameExpr ) {
1225                        std::vector< ast::SymbolTable::IdData > declList;
1226                        if (!selfFinder.otypeKeys.empty()) {
1227                                auto kind = ast::SymbolTable::getSpecialFunctionKind(nameExpr->name);
1228                                assertf(kind != ast::SymbolTable::SpecialFunctionKind::NUMBER_OF_KINDS, "special lookup with non-special target: %s", nameExpr->name.c_str());
1229
1230                                for (auto & otypeKey: selfFinder.otypeKeys) {
1231                                        auto result = symtab.specialLookupId(kind, otypeKey);
1232                                        declList.insert(declList.end(), std::make_move_iterator(result.begin()), std::make_move_iterator(result.end()));
1233                                }
1234                        }
1235                        else {
1236                                declList = symtab.lookupId( nameExpr->name );
1237                        }
1238                        PRINT( std::cerr << "nameExpr is " << nameExpr->name << std::endl; )
1239
1240                        if( declList.empty() ) return;
1241
1242                        reason.code = NoMatch;
1243
1244                        for ( auto & data : declList ) {
1245                                Cost cost = Cost::zero;
1246                                ast::Expr * newExpr = data.combine( nameExpr->location, cost );
1247
1248                                CandidateRef newCand = std::make_shared<Candidate>(
1249                                        newExpr, copy( tenv ), ast::OpenVarSet{}, ast::AssertionSet{}, Cost::zero,
1250                                        cost );
1251                                PRINT(
1252                                        std::cerr << "decl is ";
1253                                        ast::print( std::cerr, data.id );
1254                                        std::cerr << std::endl;
1255                                        std::cerr << "newExpr is ";
1256                                        ast::print( std::cerr, newExpr );
1257                                        std::cerr << std::endl;
1258                                )
1259                                newCand->expr = ast::mutate_field(
1260                                        newCand->expr.get(), &ast::Expr::result,
1261                                        renameTyVars( newCand->expr->result ) );
1262                                // add anonymous member interpretations whenever an aggregate value type is seen
1263                                // as a name expression
1264                                addAnonConversions( newCand );
1265                                candidates.emplace_back( move( newCand ) );
1266                        }
1267                }
1268
1269                void postvisit( const ast::VariableExpr * variableExpr ) {
1270                        // not sufficient to just pass `variableExpr` here, type might have changed since
1271                        // creation
1272                        addCandidate(
1273                                new ast::VariableExpr{ variableExpr->location, variableExpr->var }, tenv );
1274                }
1275
1276                void postvisit( const ast::ConstantExpr * constantExpr ) {
1277                        addCandidate( constantExpr, tenv );
1278                }
1279
1280                void postvisit( const ast::SizeofExpr * sizeofExpr ) {
1281                        if ( sizeofExpr->type ) {
1282                                addCandidate(
1283                                        new ast::SizeofExpr{
1284                                                sizeofExpr->location, resolveTypeof( sizeofExpr->type, symtab ) },
1285                                        tenv );
1286                        } else {
1287                                // find all candidates for the argument to sizeof
1288                                CandidateFinder finder{ symtab, tenv };
1289                                finder.find( sizeofExpr->expr );
1290                                // find the lowest-cost candidate, otherwise ambiguous
1291                                CandidateList winners = findMinCost( finder.candidates );
1292                                if ( winners.size() != 1 ) {
1293                                        SemanticError(
1294                                                sizeofExpr->expr.get(), "Ambiguous expression in sizeof operand: " );
1295                                }
1296                                // return the lowest-cost candidate
1297                                CandidateRef & choice = winners.front();
1298                                choice->expr = referenceToRvalueConversion( choice->expr, choice->cost );
1299                                choice->cost = Cost::zero;
1300                                addCandidate( *choice, new ast::SizeofExpr{ sizeofExpr->location, choice->expr } );
1301                        }
1302                }
1303
1304                void postvisit( const ast::AlignofExpr * alignofExpr ) {
1305                        if ( alignofExpr->type ) {
1306                                addCandidate(
1307                                        new ast::AlignofExpr{
1308                                                alignofExpr->location, resolveTypeof( alignofExpr->type, symtab ) },
1309                                        tenv );
1310                        } else {
1311                                // find all candidates for the argument to alignof
1312                                CandidateFinder finder{ symtab, tenv };
1313                                finder.find( alignofExpr->expr );
1314                                // find the lowest-cost candidate, otherwise ambiguous
1315                                CandidateList winners = findMinCost( finder.candidates );
1316                                if ( winners.size() != 1 ) {
1317                                        SemanticError(
1318                                                alignofExpr->expr.get(), "Ambiguous expression in alignof operand: " );
1319                                }
1320                                // return the lowest-cost candidate
1321                                CandidateRef & choice = winners.front();
1322                                choice->expr = referenceToRvalueConversion( choice->expr, choice->cost );
1323                                choice->cost = Cost::zero;
1324                                addCandidate(
1325                                        *choice, new ast::AlignofExpr{ alignofExpr->location, choice->expr } );
1326                        }
1327                }
1328
1329                void postvisit( const ast::UntypedOffsetofExpr * offsetofExpr ) {
1330                        const ast::BaseInstType * aggInst;
1331                        if (( aggInst = offsetofExpr->type.as< ast::StructInstType >() )) ;
1332                        else if (( aggInst = offsetofExpr->type.as< ast::UnionInstType >() )) ;
1333                        else return;
1334
1335                        for ( const ast::Decl * member : aggInst->lookup( offsetofExpr->member ) ) {
1336                                auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( member );
1337                                addCandidate(
1338                                        new ast::OffsetofExpr{ offsetofExpr->location, aggInst, dwt }, tenv );
1339                        }
1340                }
1341
1342                void postvisit( const ast::OffsetofExpr * offsetofExpr ) {
1343                        addCandidate( offsetofExpr, tenv );
1344                }
1345
1346                void postvisit( const ast::OffsetPackExpr * offsetPackExpr ) {
1347                        addCandidate( offsetPackExpr, tenv );
1348                }
1349
1350                void postvisit( const ast::LogicalExpr * logicalExpr ) {
1351                        CandidateFinder finder1{ symtab, tenv };
1352                        finder1.find( logicalExpr->arg1, ResolvMode::withAdjustment() );
1353                        if ( finder1.candidates.empty() ) return;
1354
1355                        CandidateFinder finder2{ symtab, tenv };
1356                        finder2.find( logicalExpr->arg2, ResolvMode::withAdjustment() );
1357                        if ( finder2.candidates.empty() ) return;
1358
1359                        reason.code = NoMatch;
1360
1361                        for ( const CandidateRef & r1 : finder1.candidates ) {
1362                                for ( const CandidateRef & r2 : finder2.candidates ) {
1363                                        ast::TypeEnvironment env{ r1->env };
1364                                        env.simpleCombine( r2->env );
1365                                        ast::OpenVarSet open{ r1->open };
1366                                        mergeOpenVars( open, r2->open );
1367                                        ast::AssertionSet need;
1368                                        mergeAssertionSet( need, r1->need );
1369                                        mergeAssertionSet( need, r2->need );
1370
1371                                        addCandidate(
1372                                                new ast::LogicalExpr{
1373                                                        logicalExpr->location, r1->expr, r2->expr, logicalExpr->isAnd },
1374                                                move( env ), move( open ), move( need ), r1->cost + r2->cost );
1375                                }
1376                        }
1377                }
1378
1379                void postvisit( const ast::ConditionalExpr * conditionalExpr ) {
1380                        // candidates for condition
1381                        CandidateFinder finder1{ symtab, tenv };
1382                        finder1.find( conditionalExpr->arg1, ResolvMode::withAdjustment() );
1383                        if ( finder1.candidates.empty() ) return;
1384
1385                        // candidates for true result
1386                        CandidateFinder finder2{ symtab, tenv };
1387                        finder2.find( conditionalExpr->arg2, ResolvMode::withAdjustment() );
1388                        if ( finder2.candidates.empty() ) return;
1389
1390                        // candidates for false result
1391                        CandidateFinder finder3{ symtab, tenv };
1392                        finder3.find( conditionalExpr->arg3, ResolvMode::withAdjustment() );
1393                        if ( finder3.candidates.empty() ) return;
1394
1395                        reason.code = NoMatch;
1396
1397                        for ( const CandidateRef & r1 : finder1.candidates ) {
1398                                for ( const CandidateRef & r2 : finder2.candidates ) {
1399                                        for ( const CandidateRef & r3 : finder3.candidates ) {
1400                                                ast::TypeEnvironment env{ r1->env };
1401                                                env.simpleCombine( r2->env );
1402                                                env.simpleCombine( r3->env );
1403                                                ast::OpenVarSet open{ r1->open };
1404                                                mergeOpenVars( open, r2->open );
1405                                                mergeOpenVars( open, r3->open );
1406                                                ast::AssertionSet need;
1407                                                mergeAssertionSet( need, r1->need );
1408                                                mergeAssertionSet( need, r2->need );
1409                                                mergeAssertionSet( need, r3->need );
1410                                                ast::AssertionSet have;
1411
1412                                                // unify true and false results, then infer parameters to produce new
1413                                                // candidates
1414                                                ast::ptr< ast::Type > common;
1415                                                if (
1416                                                        unify(
1417                                                                r2->expr->result, r3->expr->result, env, need, have, open, symtab,
1418                                                                common )
1419                                                ) {
1420                                                        // generate typed expression
1421                                                        ast::ConditionalExpr * newExpr = new ast::ConditionalExpr{
1422                                                                conditionalExpr->location, r1->expr, r2->expr, r3->expr };
1423                                                        newExpr->result = common ? common : r2->expr->result;
1424                                                        // convert both options to result type
1425                                                        Cost cost = r1->cost + r2->cost + r3->cost;
1426                                                        newExpr->arg2 = computeExpressionConversionCost(
1427                                                                newExpr->arg2, newExpr->result, symtab, env, cost );
1428                                                        newExpr->arg3 = computeExpressionConversionCost(
1429                                                                newExpr->arg3, newExpr->result, symtab, env, cost );
1430                                                        // output candidate
1431                                                        CandidateRef newCand = std::make_shared<Candidate>(
1432                                                                newExpr, move( env ), move( open ), move( need ), cost );
1433                                                        inferParameters( newCand, candidates );
1434                                                }
1435                                        }
1436                                }
1437                        }
1438                }
1439
1440                void postvisit( const ast::CommaExpr * commaExpr ) {
1441                        ast::TypeEnvironment env{ tenv };
1442                        ast::ptr< ast::Expr > arg1 = resolveInVoidContext( commaExpr->arg1, symtab, env );
1443
1444                        CandidateFinder finder2{ symtab, env };
1445                        finder2.find( commaExpr->arg2, ResolvMode::withAdjustment() );
1446
1447                        for ( const CandidateRef & r2 : finder2.candidates ) {
1448                                addCandidate( *r2, new ast::CommaExpr{ commaExpr->location, arg1, r2->expr } );
1449                        }
1450                }
1451
1452                void postvisit( const ast::ImplicitCopyCtorExpr * ctorExpr ) {
1453                        addCandidate( ctorExpr, tenv );
1454                }
1455
1456                void postvisit( const ast::ConstructorExpr * ctorExpr ) {
1457                        CandidateFinder finder{ symtab, tenv };
1458                        finder.find( ctorExpr->callExpr, ResolvMode::withoutPrune() );
1459                        for ( CandidateRef & r : finder.candidates ) {
1460                                addCandidate( *r, new ast::ConstructorExpr{ ctorExpr->location, r->expr } );
1461                        }
1462                }
1463
1464                void postvisit( const ast::RangeExpr * rangeExpr ) {
1465                        // resolve low and high, accept candidates where low and high types unify
1466                        CandidateFinder finder1{ symtab, tenv };
1467                        finder1.find( rangeExpr->low, ResolvMode::withAdjustment() );
1468                        if ( finder1.candidates.empty() ) return;
1469
1470                        CandidateFinder finder2{ symtab, tenv };
1471                        finder2.find( rangeExpr->high, ResolvMode::withAdjustment() );
1472                        if ( finder2.candidates.empty() ) return;
1473
1474                        reason.code = NoMatch;
1475
1476                        for ( const CandidateRef & r1 : finder1.candidates ) {
1477                                for ( const CandidateRef & r2 : finder2.candidates ) {
1478                                        ast::TypeEnvironment env{ r1->env };
1479                                        env.simpleCombine( r2->env );
1480                                        ast::OpenVarSet open{ r1->open };
1481                                        mergeOpenVars( open, r2->open );
1482                                        ast::AssertionSet need;
1483                                        mergeAssertionSet( need, r1->need );
1484                                        mergeAssertionSet( need, r2->need );
1485                                        ast::AssertionSet have;
1486
1487                                        ast::ptr< ast::Type > common;
1488                                        if (
1489                                                unify(
1490                                                        r1->expr->result, r2->expr->result, env, need, have, open, symtab,
1491                                                        common )
1492                                        ) {
1493                                                // generate new expression
1494                                                ast::RangeExpr * newExpr =
1495                                                        new ast::RangeExpr{ rangeExpr->location, r1->expr, r2->expr };
1496                                                newExpr->result = common ? common : r1->expr->result;
1497                                                // add candidate
1498                                                CandidateRef newCand = std::make_shared<Candidate>(
1499                                                        newExpr, move( env ), move( open ), move( need ),
1500                                                        r1->cost + r2->cost );
1501                                                inferParameters( newCand, candidates );
1502                                        }
1503                                }
1504                        }
1505                }
1506
1507                void postvisit( const ast::UntypedTupleExpr * tupleExpr ) {
1508                        std::vector< CandidateFinder > subCandidates =
1509                                selfFinder.findSubExprs( tupleExpr->exprs );
1510                        std::vector< CandidateList > possibilities;
1511                        combos( subCandidates.begin(), subCandidates.end(), back_inserter( possibilities ) );
1512
1513                        for ( const CandidateList & subs : possibilities ) {
1514                                std::vector< ast::ptr< ast::Expr > > exprs;
1515                                exprs.reserve( subs.size() );
1516                                for ( const CandidateRef & sub : subs ) { exprs.emplace_back( sub->expr ); }
1517
1518                                ast::TypeEnvironment env;
1519                                ast::OpenVarSet open;
1520                                ast::AssertionSet need;
1521                                for ( const CandidateRef & sub : subs ) {
1522                                        env.simpleCombine( sub->env );
1523                                        mergeOpenVars( open, sub->open );
1524                                        mergeAssertionSet( need, sub->need );
1525                                }
1526
1527                                addCandidate(
1528                                        new ast::TupleExpr{ tupleExpr->location, move( exprs ) },
1529                                        move( env ), move( open ), move( need ), sumCost( subs ) );
1530                        }
1531                }
1532
1533                void postvisit( const ast::TupleExpr * tupleExpr ) {
1534                        addCandidate( tupleExpr, tenv );
1535                }
1536
1537                void postvisit( const ast::TupleIndexExpr * tupleExpr ) {
1538                        addCandidate( tupleExpr, tenv );
1539                }
1540
1541                void postvisit( const ast::TupleAssignExpr * tupleExpr ) {
1542                        addCandidate( tupleExpr, tenv );
1543                }
1544
1545                void postvisit( const ast::UniqueExpr * unqExpr ) {
1546                        CandidateFinder finder{ symtab, tenv };
1547                        finder.find( unqExpr->expr, ResolvMode::withAdjustment() );
1548                        for ( CandidateRef & r : finder.candidates ) {
1549                                // ensure that the the id is passed on so that the expressions are "linked"
1550                                addCandidate( *r, new ast::UniqueExpr{ unqExpr->location, r->expr, unqExpr->id } );
1551                        }
1552                }
1553
1554                void postvisit( const ast::StmtExpr * stmtExpr ) {
1555                        addCandidate( resolveStmtExpr( stmtExpr, symtab ), tenv );
1556                }
1557
1558                void postvisit( const ast::UntypedInitExpr * initExpr ) {
1559                        // handle each option like a cast
1560                        CandidateList matches;
1561                        PRINT(
1562                                std::cerr << "untyped init expr: " << initExpr << std::endl;
1563                        )
1564                        // O(n^2) checks of d-types with e-types
1565                        for ( const ast::InitAlternative & initAlt : initExpr->initAlts ) {
1566                                // calculate target type
1567                                const ast::Type * toType = resolveTypeof( initAlt.type, symtab );
1568                                // toType = SymTab::validateType( initExpr->location, toType, symtab );
1569                                toType = adjustExprType( toType, tenv, symtab );
1570                                // The call to find must occur inside this loop, otherwise polymorphic return
1571                                // types are not bound to the initialization type, since return type variables are
1572                                // only open for the duration of resolving the UntypedExpr.
1573                                CandidateFinder finder{ symtab, tenv, toType };
1574                                finder.find( initExpr->expr, ResolvMode::withAdjustment() );
1575                                for ( CandidateRef & cand : finder.candidates ) {
1576                                        if(reason.code == NotFound) reason.code = NoMatch;
1577
1578                                        ast::TypeEnvironment env{ cand->env };
1579                                        ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have;
1580                                        ast::OpenVarSet open{ cand->open };
1581
1582                                        PRINT(
1583                                                std::cerr << "  @ " << toType << " " << initAlt.designation << std::endl;
1584                                        )
1585
1586                                        // It is possible that a cast can throw away some values in a multiply-valued
1587                                        // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of
1588                                        // the subexpression results that are cast directly. The candidate is invalid
1589                                        // if it has fewer results than there are types to cast to.
1590                                        int discardedValues = cand->expr->result->size() - toType->size();
1591                                        if ( discardedValues < 0 ) continue;
1592
1593                                        // unification run for side-effects
1594                                        bool canUnify = unify( toType, cand->expr->result, env, need, have, open, symtab );
1595                                        (void) canUnify;
1596                                        Cost thisCost = computeConversionCost( cand->expr->result, toType, cand->expr->get_lvalue(),
1597                                                symtab, env );
1598                                        PRINT(
1599                                                Cost legacyCost = castCost( cand->expr->result, toType, cand->expr->get_lvalue(),
1600                                                        symtab, env );
1601                                                std::cerr << "Considering initialization:";
1602                                                std::cerr << std::endl << "  FROM: " << cand->expr->result << std::endl;
1603                                                std::cerr << std::endl << "  TO: "   << toType             << std::endl;
1604                                                std::cerr << std::endl << "  Unification " << (canUnify ? "succeeded" : "failed");
1605                                                std::cerr << std::endl << "  Legacy cost " << legacyCost;
1606                                                std::cerr << std::endl << "  New cost " << thisCost;
1607                                                std::cerr << std::endl;
1608                                        )
1609                                        if ( thisCost != Cost::infinity ) {
1610                                                // count one safe conversion for each value that is thrown away
1611                                                thisCost.incSafe( discardedValues );
1612                                                CandidateRef newCand = std::make_shared<Candidate>(
1613                                                        new ast::InitExpr{
1614                                                                initExpr->location, restructureCast( cand->expr, toType ),
1615                                                                initAlt.designation },
1616                                                        move(env), move( open ), move( need ), cand->cost, thisCost );
1617                                                inferParameters( newCand, matches );
1618                                        }
1619                                }
1620
1621                        }
1622
1623                        // select first on argument cost, then conversion cost
1624                        CandidateList minArgCost = findMinCost( matches );
1625                        promoteCvtCost( minArgCost );
1626                        candidates = findMinCost( minArgCost );
1627                }
1628
1629                void postvisit( const ast::InitExpr * ) {
1630                        assertf( false, "CandidateFinder should never see a resolved InitExpr." );
1631                }
1632
1633                void postvisit( const ast::DeletedExpr * ) {
1634                        assertf( false, "CandidateFinder should never see a DeletedExpr." );
1635                }
1636
1637                void postvisit( const ast::GenericExpr * ) {
1638                        assertf( false, "_Generic is not yet supported." );
1639                }
1640        };
1641
1642        // size_t Finder::traceId = Stats::Heap::new_stacktrace_id("Finder");
1643        /// Prunes a list of candidates down to those that have the minimum conversion cost for a given
1644        /// return type. Skips ambiguous candidates.
1645
1646} // anonymous namespace
1647
1648bool CandidateFinder::pruneCandidates( CandidateList & candidates, CandidateList & out, std::vector<std::string> & errors ) {
1649        struct PruneStruct {
1650                CandidateRef candidate;
1651                bool ambiguous;
1652
1653                PruneStruct() = default;
1654                PruneStruct( const CandidateRef & c ) : candidate( c ), ambiguous( false ) {}
1655        };
1656
1657        // find lowest-cost candidate for each type
1658        std::unordered_map< std::string, PruneStruct > selected;
1659        // attempt to skip satisfyAssertions on more expensive alternatives if better options have been found
1660        std::sort(candidates.begin(), candidates.end(), [](const CandidateRef & x, const CandidateRef & y){return x->cost < y->cost;});
1661        for ( CandidateRef & candidate : candidates ) {
1662                std::string mangleName;
1663                {
1664                        ast::ptr< ast::Type > newType = candidate->expr->result;
1665                        assertf(candidate->expr->result, "Result of expression %p for candidate is null", candidate->expr.get());
1666                        candidate->env.apply( newType );
1667                        mangleName = Mangle::mangle( newType );
1668                }
1669
1670                auto found = selected.find( mangleName );
1671                if (found != selected.end() && found->second.candidate->cost < candidate->cost) {
1672                        PRINT(
1673                                std::cerr << "cost " << candidate->cost << " loses to "
1674                                        << found->second.candidate->cost << std::endl;
1675                        )
1676                        continue;
1677                }
1678
1679                // xxx - when do satisfyAssertions produce more than 1 result?
1680                // this should only happen when initial result type contains
1681                // unbound type parameters, then it should never be pruned by
1682                // the previous step, since renameTyVars guarantees the mangled name
1683                // is unique.
1684                CandidateList satisfied;
1685                bool needRecomputeKey = false;
1686                if (candidate->need.empty()) {
1687                        satisfied.emplace_back(candidate);
1688                }
1689                else {
1690                        satisfyAssertions(candidate, localSyms, satisfied, errors);
1691                        needRecomputeKey = true;
1692                }
1693
1694                for (auto & newCand : satisfied) {
1695                        // recomputes type key, if satisfyAssertions changed it
1696                        if (needRecomputeKey)
1697                        {
1698                                ast::ptr< ast::Type > newType = newCand->expr->result;
1699                                assertf(newCand->expr->result, "Result of expression %p for candidate is null", newCand->expr.get());
1700                                newCand->env.apply( newType );
1701                                mangleName = Mangle::mangle( newType );
1702                        }
1703                        auto found = selected.find( mangleName );
1704                        if ( found != selected.end() ) {
1705                                if ( newCand->cost < found->second.candidate->cost ) {
1706                                        PRINT(
1707                                                std::cerr << "cost " << newCand->cost << " beats "
1708                                                        << found->second.candidate->cost << std::endl;
1709                                        )
1710
1711                                        found->second = PruneStruct{ newCand };
1712                                } else if ( newCand->cost == found->second.candidate->cost ) {
1713                                        // if one of the candidates contains a deleted identifier, can pick the other,
1714                                        // since deleted expressions should not be ambiguous if there is another option
1715                                        // that is at least as good
1716                                        if ( findDeletedExpr( newCand->expr ) ) {
1717                                                // do nothing
1718                                                PRINT( std::cerr << "candidate is deleted" << std::endl; )
1719                                        } else if ( findDeletedExpr( found->second.candidate->expr ) ) {
1720                                                PRINT( std::cerr << "current is deleted" << std::endl; )
1721                                                found->second = PruneStruct{ newCand };
1722                                        } else {
1723                                                PRINT( std::cerr << "marking ambiguous" << std::endl; )
1724                                                found->second.ambiguous = true;
1725                                        }
1726                                } else { 
1727                                        // xxx - can satisfyAssertions increase the cost?
1728                                        PRINT(
1729                                                std::cerr << "cost " << newCand->cost << " loses to "
1730                                                        << found->second.candidate->cost << std::endl;
1731                                        )       
1732                                }
1733                        } else {
1734                                selected.emplace_hint( found, mangleName, newCand );
1735                        }
1736                }
1737        }
1738
1739        // report unambiguous min-cost candidates
1740        // CandidateList out;
1741        for ( auto & target : selected ) {
1742                if ( target.second.ambiguous ) continue;
1743
1744                CandidateRef cand = target.second.candidate;
1745
1746                ast::ptr< ast::Type > newResult = cand->expr->result;
1747                cand->env.applyFree( newResult );
1748                cand->expr = ast::mutate_field(
1749                        cand->expr.get(), &ast::Expr::result, move( newResult ) );
1750
1751                out.emplace_back( cand );
1752        }
1753        // if everything is lost in satisfyAssertions, report the error
1754        return !selected.empty();
1755}
1756
1757void CandidateFinder::find( const ast::Expr * expr, ResolvMode mode ) {
1758        // Find alternatives for expression
1759        ast::Pass<Finder> finder{ *this };
1760        expr->accept( finder );
1761
1762        if ( mode.failFast && candidates.empty() ) {
1763                switch(finder.core.reason.code) {
1764                case Finder::NotFound:
1765                        { SemanticError( expr, "No alternatives for expression " ); break; }
1766                case Finder::NoMatch:
1767                        { SemanticError( expr, "Invalid application of existing declaration(s) in expression " ); break; }
1768                case Finder::ArgsToFew:
1769                case Finder::ArgsToMany:
1770                case Finder::RetsToFew:
1771                case Finder::RetsToMany:
1772                case Finder::NoReason:
1773                default:
1774                        { SemanticError( expr->location, "No reasonable alternatives for expression : reasons unkown" ); }
1775                }
1776        }
1777
1778        /*
1779        if ( mode.satisfyAssns || mode.prune ) {
1780                // trim candidates to just those where the assertions are satisfiable
1781                // - necessary pre-requisite to pruning
1782                CandidateList satisfied;
1783                std::vector< std::string > errors;
1784                for ( CandidateRef & candidate : candidates ) {
1785                        satisfyAssertions( candidate, localSyms, satisfied, errors );
1786                }
1787
1788                // fail early if none such
1789                if ( mode.failFast && satisfied.empty() ) {
1790                        std::ostringstream stream;
1791                        stream << "No alternatives with satisfiable assertions for " << expr << "\n";
1792                        for ( const auto& err : errors ) {
1793                                stream << err;
1794                        }
1795                        SemanticError( expr->location, stream.str() );
1796                }
1797
1798                // reset candidates
1799                candidates = move( satisfied );
1800        }
1801        */
1802
1803        if ( mode.prune ) {
1804                // trim candidates to single best one
1805                PRINT(
1806                        std::cerr << "alternatives before prune:" << std::endl;
1807                        print( std::cerr, candidates );
1808                )
1809
1810                CandidateList pruned;
1811                std::vector<std::string> errors;
1812                bool found = pruneCandidates( candidates, pruned, errors );
1813
1814                if ( mode.failFast && pruned.empty() ) {
1815                        std::ostringstream stream;
1816                        if (found) {           
1817                                CandidateList winners = findMinCost( candidates );
1818                                stream << "Cannot choose between " << winners.size() << " alternatives for "
1819                                        "expression\n";
1820                                ast::print( stream, expr );
1821                                stream << " Alternatives are:\n";
1822                                print( stream, winners, 1 );
1823                                SemanticError( expr->location, stream.str() );
1824                        }
1825                        else {
1826                                stream << "No alternatives with satisfiable assertions for " << expr << "\n";
1827                                for ( const auto& err : errors ) {
1828                                        stream << err;
1829                                }
1830                                SemanticError( expr->location, stream.str() );
1831                        }
1832                }
1833
1834                auto oldsize = candidates.size();
1835                candidates = move( pruned );
1836
1837                PRINT(
1838                        std::cerr << "there are " << oldsize << " alternatives before elimination" << std::endl;
1839                )
1840                PRINT(
1841                        std::cerr << "there are " << candidates.size() << " alternatives after elimination"
1842                                << std::endl;
1843                )
1844        }
1845
1846        // adjust types after pruning so that types substituted by pruneAlternatives are correctly
1847        // adjusted
1848        if ( mode.adjust ) {
1849                for ( CandidateRef & r : candidates ) {
1850                        r->expr = ast::mutate_field(
1851                                r->expr.get(), &ast::Expr::result,
1852                                adjustExprType( r->expr->result, r->env, localSyms ) );
1853                }
1854        }
1855
1856        // Central location to handle gcc extension keyword, etc. for all expressions
1857        for ( CandidateRef & r : candidates ) {
1858                if ( r->expr->extension != expr->extension ) {
1859                        r->expr.get_and_mutate()->extension = expr->extension;
1860                }
1861        }
1862}
1863
1864std::vector< CandidateFinder > CandidateFinder::findSubExprs(
1865        const std::vector< ast::ptr< ast::Expr > > & xs
1866) {
1867        std::vector< CandidateFinder > out;
1868
1869        for ( const auto & x : xs ) {
1870                out.emplace_back( localSyms, env );
1871                out.back().find( x, ResolvMode::withAdjustment() );
1872
1873                PRINT(
1874                        std::cerr << "findSubExprs" << std::endl;
1875                        print( std::cerr, out.back().candidates );
1876                )
1877        }
1878
1879        return out;
1880}
1881
1882} // namespace ResolvExpr
1883
1884// Local Variables: //
1885// tab-width: 4 //
1886// mode: c++ //
1887// compile-command: "make install" //
1888// End: //
Note: See TracBrowser for help on using the repository browser.