source: src/ResolvExpr/CandidateFinder.cpp @ 09f34a84

ADTast-experimentalpthread-emulation
Last change on this file since 09f34a84 was 09f34a84, checked in by Thierry Delisle <tdelisle@…>, 19 months ago

Remove some of the warnings on the new clang

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