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

Last change on this file since 4c0b674 was a4da45e, checked in by JiadaL <j82liang@…>, 4 months ago

Resolve conflict

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