source: src/ResolvExpr/CandidateFinder.cpp @ 714e206

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