source: src/ResolvExpr/CandidateFinder.cpp @ 9ddcee1

Last change on this file since 9ddcee1 was 9ddcee1, checked in by JiadaL <j82liang@…>, 5 months ago

Remove EnumPosExpr?, an early design that no longer used. The implementation of the feature has been replaced by ReplacePseudoFunc?

  • 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
675                void postvisit( const ast::InitExpr * ) {
676                        assertf( false, "CandidateFinder should never see a resolved InitExpr." );
677                }
678
679                void postvisit( const ast::DeletedExpr * ) {
680                        assertf( false, "CandidateFinder should never see a DeletedExpr." );
681                }
682
683                void postvisit( const ast::GenericExpr * ) {
684                        assertf( false, "_Generic is not yet supported." );
685                }
686        };
687
688        /// Set up candidate assertions for inference
689        void Finder::inferParameters( CandidateRef & newCand, CandidateList & out ) {
690                // Set need bindings for any unbound assertions
691                ast::UniqueId crntResnSlot = 0; // matching ID for this expression's assertions
692                for ( auto & assn : newCand->need ) {
693                        // skip already-matched assertions
694                        if ( assn.second.resnSlot != 0 ) continue;
695                        // assign slot for expression if needed
696                        if ( crntResnSlot == 0 ) { crntResnSlot = ++globalResnSlot; }
697                        // fix slot to assertion
698                        assn.second.resnSlot = crntResnSlot;
699                }
700                // pair slot to expression
701                if ( crntResnSlot != 0 ) {
702                        newCand->expr.get_and_mutate()->inferred.resnSlots().emplace_back( crntResnSlot );
703                }
704
705                // add to output list; assertion satisfaction will occur later
706                out.emplace_back( newCand );
707        }
708
709        /// Completes a function candidate with arguments located
710        void Finder::validateFunctionCandidate(
711                const CandidateRef & func, ArgPack & result, const std::vector< ArgPack > & results,
712                CandidateList & out
713        ) {
714                ast::ApplicationExpr * appExpr =
715                        new ast::ApplicationExpr{ func->expr->location, func->expr };
716                // sum cost and accumulate arguments
717                std::deque< const ast::Expr * > args;
718                Cost cost = func->cost;
719                const ArgPack * pack = &result;
720                while ( pack->expr ) {
721                        args.emplace_front( pack->expr );
722                        cost += pack->cost;
723                        pack = &results[pack->parent];
724                }
725                std::vector< ast::ptr< ast::Expr > > vargs( args.begin(), args.end() );
726                appExpr->args = std::move( vargs );
727                // build and validate new candidate
728                auto newCand =
729                        std::make_shared<Candidate>( appExpr, result.env, result.open, result.need, cost );
730                PRINT(
731                        std::cerr << "instantiate function success: " << appExpr << std::endl;
732                        std::cerr << "need assertions:" << std::endl;
733                        ast::print( std::cerr, result.need, 2 );
734                )
735                inferParameters( newCand, out );
736        }
737
738        /// Builds a list of candidates for a function, storing them in out
739        void Finder::makeFunctionCandidates(
740                const CodeLocation & location,
741                const CandidateRef & func, const ast::FunctionType * funcType,
742                const ExplodedArgs & args, CandidateList & out
743        ) {
744                ast::OpenVarSet funcOpen;
745                ast::AssertionSet funcNeed, funcHave;
746                ast::TypeEnvironment funcEnv{ func->env };
747                makeUnifiableVars( funcType, funcOpen, funcNeed );
748                // add all type variables as open variables now so that those not used in the
749                // parameter list are still considered open
750                funcEnv.add( funcType->forall );
751
752                if ( targetType && ! targetType->isVoid() && ! funcType->returns.empty() ) {
753                        // attempt to narrow based on expected target type
754                        const ast::Type * returnType = funcType->returns.front();
755                        if ( selfFinder.strictMode ) {
756                                if ( !unifyExact(
757                                        returnType, targetType, funcEnv, funcNeed, funcHave, funcOpen, noWiden() ) // xxx - is no widening correct?
758                                ) {
759                                        // unification failed, do not pursue this candidate
760                                        return;
761                                }
762                        } else {
763                                if ( !unify(
764                                        returnType, targetType, funcEnv, funcNeed, funcHave, funcOpen )
765                                ) {
766                                        // unification failed, do not pursue this candidate
767                                        return;
768                                }
769                        }
770                }
771
772                // iteratively build matches, one parameter at a time
773                std::vector< ArgPack > results;
774                results.emplace_back( funcEnv, funcNeed, funcHave, funcOpen );
775                std::size_t genStart = 0;
776
777                // xxx - how to handle default arg after change to ftype representation?
778                if (const ast::VariableExpr * varExpr = func->expr.as<ast::VariableExpr>()) {
779                        if (const ast::FunctionDecl * funcDecl = varExpr->var.as<ast::FunctionDecl>()) {
780                                // function may have default args only if directly calling by name
781                                // must use types on candidate however, due to RenameVars substitution
782                                auto nParams = funcType->params.size();
783
784                                for (size_t i=0; i<nParams; ++i) {
785                                        auto obj = funcDecl->params[i].strict_as<ast::ObjectDecl>();
786                                        if ( !instantiateArgument( location,
787                                                funcType->params[i], obj->init, args, results, genStart, symtab)) return;
788                                }
789                                goto endMatch;
790                        }
791                }
792                for ( const auto & param : funcType->params ) {
793                        // Try adding the arguments corresponding to the current parameter to the existing
794                        // matches
795                        // no default args for indirect calls
796                        if ( !instantiateArgument( location,
797                                param, nullptr, args, results, genStart, symtab ) ) return;
798                }
799
800                endMatch:
801                if ( funcType->isVarArgs ) {
802                        // append any unused arguments to vararg pack
803                        std::size_t genEnd;
804                        do {
805                                genEnd = results.size();
806
807                                // iterate results
808                                for ( std::size_t i = genStart; i < genEnd; ++i ) {
809                                        unsigned nextArg = results[i].nextArg;
810
811                                        // use remainder of exploded tuple if present
812                                        if ( results[i].hasExpl() ) {
813                                                const ExplodedArg & expl = results[i].getExpl( args );
814
815                                                unsigned nextExpl = results[i].nextExpl + 1;
816                                                if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
817
818                                                results.emplace_back(
819                                                        i, expl.exprs[ results[i].nextExpl ], copy( results[i].env ),
820                                                        copy( results[i].need ), copy( results[i].have ),
821                                                        copy( results[i].open ), nextArg, 0, Cost::zero, nextExpl,
822                                                        results[i].explAlt );
823
824                                                continue;
825                                        }
826
827                                        // finish result when out of arguments
828                                        if ( nextArg >= args.size() ) {
829                                                validateFunctionCandidate( func, results[i], results, out );
830
831                                                continue;
832                                        }
833
834                                        // add each possible next argument
835                                        for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
836                                                const ExplodedArg & expl = args[nextArg][j];
837
838                                                // fresh copies of parent parameters for this iteration
839                                                ast::TypeEnvironment env = results[i].env;
840                                                ast::OpenVarSet open = results[i].open;
841
842                                                env.addActual( expl.env, open );
843
844                                                // skip empty tuple arguments by (nearly) cloning parent into next gen
845                                                if ( expl.exprs.empty() ) {
846                                                        results.emplace_back(
847                                                                results[i], std::move( env ), copy( results[i].need ),
848                                                                copy( results[i].have ), std::move( open ), nextArg + 1,
849                                                                expl.cost );
850
851                                                        continue;
852                                                }
853
854                                                // add new result
855                                                results.emplace_back(
856                                                        i, expl.exprs.front(), std::move( env ), copy( results[i].need ),
857                                                        copy( results[i].have ), std::move( open ), nextArg + 1, 0, expl.cost,
858                                                        expl.exprs.size() == 1 ? 0 : 1, j );
859                                        }
860                                }
861
862                                genStart = genEnd;
863                        } while( genEnd != results.size() );
864                } else {
865                        // filter out the results that don't use all the arguments
866                        for ( std::size_t i = genStart; i < results.size(); ++i ) {
867                                ArgPack & result = results[i];
868                                if ( ! result.hasExpl() && result.nextArg >= args.size() ) {
869                                        validateFunctionCandidate( func, result, results, out );
870                                }
871                        }
872                }
873        }
874
875        /// Adds implicit struct-conversions to the alternative list
876        void Finder::addAnonConversions( const CandidateRef & cand ) {
877                // adds anonymous member interpretations whenever an aggregate value type is seen.
878                // it's okay for the aggregate expression to have reference type -- cast it to the
879                // base type to treat the aggregate as the referenced value
880                ast::ptr< ast::Expr > aggrExpr( cand->expr );
881                ast::ptr< ast::Type > & aggrType = aggrExpr.get_and_mutate()->result;
882                cand->env.apply( aggrType );
883
884                if ( aggrType.as< ast::ReferenceType >() ) {
885                        aggrExpr = new ast::CastExpr{ aggrExpr, aggrType->stripReferences() };
886                }
887
888                if ( auto structInst = aggrExpr->result.as< ast::StructInstType >() ) {
889                        addAggMembers( structInst, aggrExpr, *cand, Cost::unsafe, "" );
890                } else if ( auto unionInst = aggrExpr->result.as< ast::UnionInstType >() ) {
891                        addAggMembers( unionInst, aggrExpr, *cand, Cost::unsafe, "" );
892                } else if ( auto enumInst = aggrExpr->result.as< ast::EnumInstType >() ) {
893                        // The Attribute Arrays are not yet generated, need to proxy them
894                        // as attribute function call
895                        const CodeLocation & location = cand->expr->location;
896                        if ( enumInst->base && enumInst->base->base ) {
897                                auto valueName = new ast::NameExpr(location, "valueE");
898                                auto untypedValueCall = new ast::UntypedExpr( 
899                                        location, valueName, { aggrExpr } );
900                                auto result = ResolvExpr::findVoidExpression( untypedValueCall, context );
901                                assert( result.get() );
902                                CandidateRef newCand = std::make_shared<Candidate>(
903                                        *cand, result, Cost::safe );
904                                candidates.emplace_back( std::move( newCand ) );
905                        }
906                }
907        }
908
909        /// Adds aggregate member interpretations
910        void Finder::addAggMembers(
911                const ast::BaseInstType * aggrInst, const ast::Expr * expr,
912                const Candidate & cand, const Cost & addedCost, const std::string & name
913        ) {
914                for ( const ast::Decl * decl : aggrInst->lookup( name ) ) {
915                        auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( decl );
916                        CandidateRef newCand = std::make_shared<Candidate>(
917                                cand, new ast::MemberExpr{ expr->location, dwt, expr }, addedCost );
918                        // add anonymous member interpretations whenever an aggregate value type is seen
919                        // as a member expression
920                        addAnonConversions( newCand );
921                        candidates.emplace_back( std::move( newCand ) );
922                }
923        }
924
925        /// Adds tuple member interpretations
926        void Finder::addTupleMembers(
927                const ast::TupleType * tupleType, const ast::Expr * expr, const Candidate & cand,
928                const Cost & addedCost, const ast::Expr * member
929        ) {
930                if ( auto constantExpr = dynamic_cast< const ast::ConstantExpr * >( member ) ) {
931                        // get the value of the constant expression as an int, must be between 0 and the
932                        // length of the tuple to have meaning
933                        long long val = constantExpr->intValue();
934                        if ( val >= 0 && (unsigned long long)val < tupleType->size() ) {
935                                addCandidate(
936                                        cand, new ast::TupleIndexExpr{ expr->location, expr, (unsigned)val },
937                                        addedCost );
938                        }
939                }
940        }
941
942        void Finder::postvisit( const ast::UntypedExpr * untypedExpr ) {
943                std::vector< CandidateFinder > argCandidates =
944                        selfFinder.findSubExprs( untypedExpr->args );
945
946                // take care of possible tuple assignments
947                // if not tuple assignment, handled as normal function call
948                Tuples::handleTupleAssignment( selfFinder, untypedExpr, argCandidates );
949
950                CandidateFinder funcFinder( context, tenv );
951                if (auto nameExpr = untypedExpr->func.as<ast::NameExpr>()) {
952                        auto kind = ast::SymbolTable::getSpecialFunctionKind(nameExpr->name);
953                        if (kind != ast::SymbolTable::SpecialFunctionKind::NUMBER_OF_KINDS) {
954                                assertf(!argCandidates.empty(), "special function call without argument");
955                                for (auto & firstArgCand: argCandidates[0]) {
956                                        ast::ptr<ast::Type> argType = firstArgCand->expr->result;
957                                        firstArgCand->env.apply(argType);
958                                        // strip references
959                                        // xxx - is this correct?
960                                        while (argType.as<ast::ReferenceType>()) argType = argType.as<ast::ReferenceType>()->base;
961
962                                        // convert 1-tuple to plain type
963                                        if (auto tuple = argType.as<ast::TupleType>()) {
964                                                if (tuple->size() == 1) {
965                                                        argType = tuple->types[0];
966                                                }
967                                        }
968
969                                        // if argType is an unbound type parameter, all special functions need to be searched.
970                                        if (isUnboundType(argType)) {
971                                                funcFinder.otypeKeys.clear();
972                                                break;
973                                        }
974
975                                        if (argType.as<ast::PointerType>()) funcFinder.otypeKeys.insert(Mangle::Encoding::pointer);                                             
976                                        else funcFinder.otypeKeys.insert(Mangle::mangle(argType, Mangle::NoGenericParams | Mangle::Type));
977                                }
978                        }
979                }
980                // if candidates are already produced, do not fail
981                // xxx - is it possible that handleTupleAssignment and main finder both produce candidates?
982                // this means there exists ctor/assign functions with a tuple as first parameter.
983                ResolveMode mode = {
984                        true, // adjust
985                        !untypedExpr->func.as<ast::NameExpr>(), // prune if not calling by name
986                        selfFinder.candidates.empty() // failfast if other options are not found
987                };
988                funcFinder.find( untypedExpr->func, mode );
989                // short-circuit if no candidates
990                // if ( funcFinder.candidates.empty() ) return;
991
992                reason.code = NoMatch;
993
994                // find function operators
995                ast::ptr< ast::Expr > opExpr = new ast::NameExpr{ untypedExpr->location, "?()" }; // ??? why not ?{}
996                CandidateFinder opFinder( context, tenv );
997                // okay if there aren't any function operations
998                opFinder.find( opExpr, ResolveMode::withoutFailFast() );
999                PRINT(
1000                        std::cerr << "known function ops:" << std::endl;
1001                        print( std::cerr, opFinder.candidates, 1 );
1002                )
1003
1004                // pre-explode arguments
1005                ExplodedArgs argExpansions;
1006                for ( const CandidateFinder & args : argCandidates ) {
1007                        argExpansions.emplace_back();
1008                        auto & argE = argExpansions.back();
1009                        for ( const CandidateRef & arg : args ) { argE.emplace_back( *arg, symtab ); }
1010                }
1011
1012                // Find function matches
1013                CandidateList found;
1014                SemanticErrorException errors;
1015                for ( CandidateRef & func : funcFinder ) {
1016                        try {
1017                                PRINT(
1018                                        std::cerr << "working on alternative:" << std::endl;
1019                                        print( std::cerr, *func, 2 );
1020                                )
1021
1022                                // check if the type is a pointer to function
1023                                const ast::Type * funcResult = func->expr->result->stripReferences();
1024                                if ( auto pointer = dynamic_cast< const ast::PointerType * >( funcResult ) ) {
1025                                        if ( auto function = pointer->base.as< ast::FunctionType >() ) {
1026                                                // if (!selfFinder.allowVoid && function->returns.empty()) continue;
1027                                                CandidateRef newFunc{ new Candidate{ *func } };
1028                                                newFunc->expr =
1029                                                        referenceToRvalueConversion( newFunc->expr, newFunc->cost );
1030                                                makeFunctionCandidates( untypedExpr->location,
1031                                                        newFunc, function, argExpansions, found );
1032                                        }
1033                                } else if (
1034                                        auto inst = dynamic_cast< const ast::TypeInstType * >( funcResult )
1035                                ) {
1036                                        if ( const ast::EqvClass * clz = func->env.lookup( *inst ) ) {
1037                                                if ( auto function = clz->bound.as< ast::FunctionType >() ) {
1038                                                        CandidateRef newFunc( new Candidate( *func ) );
1039                                                        newFunc->expr =
1040                                                                referenceToRvalueConversion( newFunc->expr, newFunc->cost );
1041                                                        makeFunctionCandidates( untypedExpr->location,
1042                                                                newFunc, function, argExpansions, found );
1043                                                }
1044                                        }
1045                                }
1046                        } catch ( SemanticErrorException & e ) { errors.append( e ); }
1047                }
1048
1049                // Find matches on function operators `?()`
1050                if ( ! opFinder.candidates.empty() ) {
1051                        // add exploded function alternatives to front of argument list
1052                        std::vector< ExplodedArg > funcE;
1053                        funcE.reserve( funcFinder.candidates.size() );
1054                        for ( const CandidateRef & func : funcFinder ) {
1055                                funcE.emplace_back( *func, symtab );
1056                        }
1057                        argExpansions.emplace_front( std::move( funcE ) );
1058
1059                        for ( const CandidateRef & op : opFinder ) {
1060                                try {
1061                                        // check if type is pointer-to-function
1062                                        const ast::Type * opResult = op->expr->result->stripReferences();
1063                                        if ( auto pointer = dynamic_cast< const ast::PointerType * >( opResult ) ) {
1064                                                if ( auto function = pointer->base.as< ast::FunctionType >() ) {
1065                                                        CandidateRef newOp{ new Candidate{ *op} };
1066                                                        newOp->expr =
1067                                                                referenceToRvalueConversion( newOp->expr, newOp->cost );
1068                                                        makeFunctionCandidates( untypedExpr->location,
1069                                                                newOp, function, argExpansions, found );
1070                                                }
1071                                        }
1072                                } catch ( SemanticErrorException & e ) { errors.append( e ); }
1073                        }
1074                }
1075
1076                // Implement SFINAE; resolution errors are only errors if there aren't any non-error
1077                // candidates
1078                if ( found.empty() && ! errors.isEmpty() ) { throw errors; }
1079
1080                // only keep the best matching intrinsic result to match C semantics (no unexpected narrowing/widening)
1081                // TODO: keep one for each set of argument candidates?
1082                Cost intrinsicCost = Cost::infinity;
1083                CandidateList intrinsicResult;
1084
1085                // Compute conversion costs
1086                for ( CandidateRef & withFunc : found ) {
1087                        Cost cvtCost = computeApplicationConversionCost( withFunc, symtab );
1088
1089                        PRINT(
1090                                auto appExpr = withFunc->expr.strict_as< ast::ApplicationExpr >();
1091                                auto pointer = appExpr->func->result.strict_as< ast::PointerType >();
1092                                auto function = pointer->base.strict_as< ast::FunctionType >();
1093
1094                                std::cerr << "Case +++++++++++++ " << appExpr->func << std::endl;
1095                                std::cerr << "parameters are:" << std::endl;
1096                                ast::printAll( std::cerr, function->params, 2 );
1097                                std::cerr << "arguments are:" << std::endl;
1098                                ast::printAll( std::cerr, appExpr->args, 2 );
1099                                std::cerr << "bindings are:" << std::endl;
1100                                ast::print( std::cerr, withFunc->env, 2 );
1101                                std::cerr << "cost is: " << withFunc->cost << std::endl;
1102                                std::cerr << "cost of conversion is:" << cvtCost << std::endl;
1103                        )
1104
1105                        if ( cvtCost != Cost::infinity ) {
1106                                withFunc->cvtCost = cvtCost;
1107                                withFunc->cost += cvtCost;
1108                                auto func = withFunc->expr.strict_as<ast::ApplicationExpr>()->func.as<ast::VariableExpr>();
1109                                if (func && func->var->linkage == ast::Linkage::Intrinsic) {
1110                                        if (withFunc->cost < intrinsicCost) {
1111                                                intrinsicResult.clear();
1112                                                intrinsicCost = withFunc->cost;
1113                                        }
1114                                        if (withFunc->cost == intrinsicCost) {
1115                                                intrinsicResult.emplace_back(std::move(withFunc));
1116                                        }
1117                                } else {
1118                                        candidates.emplace_back( std::move( withFunc ) );
1119                                }
1120                        }
1121                }
1122                spliceBegin( candidates, intrinsicResult );
1123                found = std::move( candidates );
1124
1125                // use a new list so that candidates are not examined by addAnonConversions twice
1126                // CandidateList winners = findMinCost( found );
1127                // promoteCvtCost( winners );
1128
1129                // function may return a struct/union value, in which case we need to add candidates
1130                // for implicit conversions to each of the anonymous members, which must happen after
1131                // `findMinCost`, since anon conversions are never the cheapest
1132                for ( const CandidateRef & c : found ) {
1133                        addAnonConversions( c );
1134                }
1135                // would this be too slow when we don't check cost anymore?
1136                spliceBegin( candidates, found );
1137
1138                if ( candidates.empty() && targetType && ! targetType->isVoid() && !selfFinder.strictMode ) {
1139                        // If resolution is unsuccessful with a target type, try again without, since it
1140                        // will sometimes succeed when it wouldn't with a target type binding.
1141                        // For example:
1142                        //   forall( otype T ) T & ?[]( T *, ptrdiff_t );
1143                        //   const char * x = "hello world";
1144                        //   unsigned char ch = x[0];
1145                        // Fails with simple return type binding (xxx -- check this!) as follows:
1146                        // * T is bound to unsigned char
1147                        // * (x: const char *) is unified with unsigned char *, which fails
1148                        // xxx -- fix this better
1149                        targetType = nullptr;
1150                        postvisit( untypedExpr );
1151                }
1152        }
1153
1154        void Finder::postvisit( const ast::AddressExpr * addressExpr ) {
1155                CandidateFinder finder( context, tenv );
1156                finder.find( addressExpr->arg );
1157
1158                if ( finder.candidates.empty() ) return;
1159
1160                reason.code = NoMatch;
1161
1162                for ( CandidateRef & r : finder.candidates ) {
1163                        if ( !isLvalue( r->expr ) ) continue;
1164                        addCandidate( *r, new ast::AddressExpr{ addressExpr->location, r->expr } );
1165                }
1166        }
1167
1168        void Finder::postvisit( const ast::LabelAddressExpr * labelExpr ) {
1169                addCandidate( labelExpr, tenv );
1170        }
1171
1172        void Finder::postvisit( const ast::CastExpr * castExpr ) {
1173                ast::ptr< ast::Type > toType = castExpr->result;
1174                assert( toType );
1175                toType = resolveTypeof( toType, context );
1176                toType = adjustExprType( toType, tenv, symtab );
1177
1178                CandidateFinder finder( context, tenv, toType );
1179                if (toType->isVoid()) {
1180                        finder.allowVoid = true;
1181                }
1182                if ( castExpr->kind == ast::CastExpr::Return ) {
1183                        finder.strictMode = true;
1184                        finder.find( castExpr->arg, ResolveMode::withAdjustment() );
1185
1186                        // return casts are eliminated (merely selecting an overload, no actual operation)
1187                        candidates = std::move(finder.candidates);
1188                }
1189                finder.find( castExpr->arg, ResolveMode::withAdjustment() );
1190
1191                if ( !finder.candidates.empty() ) reason.code = NoMatch;
1192
1193                CandidateList matches;
1194                Cost minExprCost = Cost::infinity;
1195                Cost minCastCost = Cost::infinity;
1196                for ( CandidateRef & cand : finder.candidates ) {
1197                        ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have;
1198                        ast::OpenVarSet open( cand->open );
1199
1200                        cand->env.extractOpenVars( open );
1201
1202                        // It is possible that a cast can throw away some values in a multiply-valued
1203                        // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of the
1204                        // subexpression results that are cast directly. The candidate is invalid if it
1205                        // has fewer results than there are types to cast to.
1206                        int discardedValues = cand->expr->result->size() - toType->size();
1207                        if ( discardedValues < 0 ) continue;
1208
1209                        // unification run for side-effects
1210                        unify( toType, cand->expr->result, cand->env, need, have, open );
1211                        Cost thisCost =
1212                                (castExpr->isGenerated == ast::GeneratedFlag::GeneratedCast)
1213                                        ? conversionCost( cand->expr->result, toType, cand->expr->get_lvalue(), symtab, cand->env )
1214                                        : castCost( cand->expr->result, toType, cand->expr->get_lvalue(), symtab, cand->env );
1215
1216                        PRINT(
1217                                std::cerr << "working on cast with result: " << toType << std::endl;
1218                                std::cerr << "and expr type: " << cand->expr->result << std::endl;
1219                                std::cerr << "env: " << cand->env << std::endl;
1220                        )
1221                        if ( thisCost != Cost::infinity ) {
1222                                PRINT(
1223                                        std::cerr << "has finite cost." << std::endl;
1224                                )
1225                                // count one safe conversion for each value that is thrown away
1226                                thisCost.incSafe( discardedValues );
1227                                // select first on argument cost, then conversion cost
1228                                if ( cand->cost < minExprCost || ( cand->cost == minExprCost && thisCost < minCastCost ) ) {
1229                                        minExprCost = cand->cost;
1230                                        minCastCost = thisCost;
1231                                        matches.clear();
1232
1233
1234                                }
1235                                // ambiguous case, still output candidates to print in error message
1236                                if ( cand->cost == minExprCost && thisCost == minCastCost ) {
1237                                        CandidateRef newCand = std::make_shared<Candidate>(
1238                                                restructureCast( cand->expr, toType, castExpr->isGenerated ),
1239                                                copy( cand->env ), std::move( open ), std::move( need ), cand->cost + thisCost);
1240                                        // currently assertions are always resolved immediately so this should have no effect.
1241                                        // if this somehow changes in the future (e.g. delayed by indeterminate return type)
1242                                        // we may need to revisit the logic.
1243                                        inferParameters( newCand, matches );
1244                                }
1245                                // else skip, better alternatives found
1246
1247                        }
1248                }
1249                candidates = std::move(matches);
1250
1251                //CandidateList minArgCost = findMinCost( matches );
1252                //promoteCvtCost( minArgCost );
1253                //candidates = findMinCost( minArgCost );
1254        }
1255
1256        void Finder::postvisit( const ast::VirtualCastExpr * castExpr ) {
1257                assertf( castExpr->result, "Implicit virtual cast targets not yet supported." );
1258                CandidateFinder finder( context, tenv );
1259                // don't prune here, all alternatives guaranteed to have same type
1260                finder.find( castExpr->arg, ResolveMode::withoutPrune() );
1261                for ( CandidateRef & r : finder.candidates ) {
1262                        addCandidate(
1263                                *r,
1264                                new ast::VirtualCastExpr{ castExpr->location, r->expr, castExpr->result } );
1265                }
1266        }
1267
1268        void Finder::postvisit( const ast::KeywordCastExpr * castExpr ) {
1269                const auto & loc = castExpr->location;
1270                assertf( castExpr->result, "Cast target should have been set in Validate." );
1271                auto ref = castExpr->result.strict_as<ast::ReferenceType>();
1272                auto inst = ref->base.strict_as<ast::StructInstType>();
1273                auto target = inst->base.get();
1274
1275                CandidateFinder finder( context, tenv );
1276
1277                auto pick_alternatives = [target, this](CandidateList & found, bool expect_ref) {
1278                        for (auto & cand : found) {
1279                                const ast::Type * expr = cand->expr->result.get();
1280                                if (expect_ref) {
1281                                        auto res = dynamic_cast<const ast::ReferenceType*>(expr);
1282                                        if (!res) { continue; }
1283                                        expr = res->base.get();
1284                                }
1285
1286                                if (auto insttype = dynamic_cast<const ast::TypeInstType*>(expr)) {
1287                                        auto td = cand->env.lookup(*insttype);
1288                                        if (!td) { continue; }
1289                                        expr = td->bound.get();
1290                                }
1291
1292                                if (auto base = dynamic_cast<const ast::StructInstType*>(expr)) {
1293                                        if (base->base == target) {
1294                                                candidates.push_back( std::move(cand) );
1295                                                reason.code = NoReason;
1296                                        }
1297                                }
1298                        }
1299                };
1300
1301                try {
1302                        // Attempt 1 : turn (thread&)X into (thread$&)X.__thrd
1303                        // Clone is purely for memory management
1304                        std::unique_ptr<const ast::Expr> tech1 { new ast::UntypedMemberExpr(loc, new ast::NameExpr(loc, castExpr->concrete_target.field), castExpr->arg) };
1305
1306                        // don't prune here, since it's guaranteed all alternatives will have the same type
1307                        finder.find( tech1.get(), ResolveMode::withoutPrune() );
1308                        pick_alternatives(finder.candidates, false);
1309
1310                        return;
1311                } catch(SemanticErrorException & ) {}
1312
1313                // Fallback : turn (thread&)X into (thread$&)get_thread(X)
1314                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 })) };
1315                // don't prune here, since it's guaranteed all alternatives will have the same type
1316                finder.find( fallback.get(), ResolveMode::withoutPrune() );
1317
1318                pick_alternatives(finder.candidates, true);
1319
1320                // Whatever happens here, we have no more fallbacks
1321        }
1322
1323        void Finder::postvisit( const ast::UntypedMemberExpr * memberExpr ) {
1324                CandidateFinder aggFinder( context, tenv );
1325                aggFinder.find( memberExpr->aggregate, ResolveMode::withAdjustment() );
1326                for ( CandidateRef & agg : aggFinder.candidates ) {
1327                        // it's okay for the aggregate expression to have reference type -- cast it to the
1328                        // base type to treat the aggregate as the referenced value
1329                        Cost addedCost = Cost::zero;
1330                        agg->expr = referenceToRvalueConversion( agg->expr, addedCost );
1331
1332                        // find member of the given type
1333                        if ( auto structInst = agg->expr->result.as< ast::StructInstType >() ) {
1334                                addAggMembers(
1335                                        structInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) );
1336                        } else if ( auto unionInst = agg->expr->result.as< ast::UnionInstType >() ) {
1337                                addAggMembers(
1338                                        unionInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) );
1339                        } else if ( auto tupleType = agg->expr->result.as< ast::TupleType >() ) {
1340                                addTupleMembers( tupleType, agg->expr, *agg, addedCost, memberExpr->member );
1341                        }
1342                }
1343        }
1344
1345        void Finder::postvisit( const ast::MemberExpr * memberExpr ) {
1346                addCandidate( memberExpr, tenv );
1347        }
1348
1349        void Finder::postvisit( const ast::NameExpr * nameExpr ) {
1350                std::vector< ast::SymbolTable::IdData > declList;
1351                if (!selfFinder.otypeKeys.empty()) {
1352                        auto kind = ast::SymbolTable::getSpecialFunctionKind(nameExpr->name);
1353                        assertf(kind != ast::SymbolTable::SpecialFunctionKind::NUMBER_OF_KINDS, "special lookup with non-special target: %s", nameExpr->name.c_str());
1354
1355                        for (auto & otypeKey: selfFinder.otypeKeys) {
1356                                auto result = symtab.specialLookupId(kind, otypeKey);
1357                                declList.insert(declList.end(), std::make_move_iterator(result.begin()), std::make_move_iterator(result.end()));
1358                        }
1359                } else {
1360                        declList = symtab.lookupId( nameExpr->name );
1361                }
1362                PRINT( std::cerr << "nameExpr is " << nameExpr->name << std::endl; )
1363
1364                if ( declList.empty() ) return;
1365
1366                reason.code = NoMatch;
1367
1368                for ( auto & data : declList ) {
1369                        Cost cost = Cost::zero;
1370                        ast::Expr * newExpr = data.combine( nameExpr->location, cost );
1371
1372                        CandidateRef newCand = std::make_shared<Candidate>(
1373                                newExpr, copy( tenv ), ast::OpenVarSet{}, ast::AssertionSet{}, Cost::zero,
1374                                cost );
1375
1376                        if (newCand->expr->env) {
1377                                newCand->env.add(*newCand->expr->env);
1378                                auto mutExpr = newCand->expr.get_and_mutate();
1379                                mutExpr->env  = nullptr;
1380                                newCand->expr = mutExpr;
1381                        }
1382
1383                        PRINT(
1384                                std::cerr << "decl is ";
1385                                ast::print( std::cerr, data.id );
1386                                std::cerr << std::endl;
1387                                std::cerr << "newExpr is ";
1388                                ast::print( std::cerr, newExpr );
1389                                std::cerr << std::endl;
1390                        )
1391                        newCand->expr = ast::mutate_field(
1392                                newCand->expr.get(), &ast::Expr::result,
1393                                renameTyVars( newCand->expr->result ) );
1394                        // add anonymous member interpretations whenever an aggregate value type is seen
1395                        // as a name expression
1396                        addAnonConversions( newCand );
1397                        candidates.emplace_back( std::move( newCand ) );
1398                }
1399        }
1400
1401        void Finder::postvisit( const ast::VariableExpr * variableExpr ) {
1402                // not sufficient to just pass `variableExpr` here, type might have changed since
1403                // creation
1404                if ( auto obj = dynamic_cast<const ast::ObjectDecl *>( variableExpr->var.get() )) {
1405                        if ( auto enumInstType = dynamic_cast<const ast::EnumInstType *>( obj->type.get() ) ) {
1406                                if ( enumInstType->base && enumInstType->base->base ) {
1407                                        const CodeLocation & location = variableExpr->location;
1408                                        auto ids = symtab.lookupId( "valueE" );
1409                                                for ( ast::SymbolTable::IdData & id : ids ) {
1410                                                        if ( auto func = id.id.as<ast::FunctionDecl>() ) {
1411                                                                if ( func->params.size() == 1 ) {
1412                                                                        ast::ptr<ast::DeclWithType> valueEParam = func->params.front();
1413                                                                        auto valueEParamType = valueEParam->get_type();
1414                                                                        ast::OpenVarSet funcOpen;
1415                                                                        ast::AssertionSet funcNeed, funcHave;
1416                                                                        ast::TypeEnvironment funcEnv{ tenv };
1417                                                                        ast::ptr<ast::Type> common;
1418                                                                        if ( unifyInexact( valueEParamType, enumInstType, funcEnv, funcNeed, funcHave, funcOpen, WidenMode{ true, true }, common ) ) {
1419                                                                                auto appl = new ast::ApplicationExpr( location,
1420                                                                                        ast::VariableExpr::functionPointer( location,  func), { variableExpr } );
1421                                                                                // addCandidate( appl, copy( tenv ),  );
1422                                                                                Candidate cand {appl, copy( tenv )};
1423                                                                                addCandidate( cand, appl, Cost::safe );
1424                                                                        }
1425                                                                }
1426                                                        }
1427                                                }
1428                                }
1429                       
1430                        }
1431                } 
1432                addCandidate( variableExpr, tenv );
1433               
1434        }
1435
1436        void Finder::postvisit( const ast::ConstantExpr * constantExpr ) {
1437                addCandidate( constantExpr, tenv );
1438        }
1439
1440        void Finder::postvisit( const ast::SizeofExpr * sizeofExpr ) {
1441                if ( sizeofExpr->type ) {
1442                        addCandidate(
1443                                new ast::SizeofExpr{
1444                                        sizeofExpr->location, resolveTypeof( sizeofExpr->type, context ) },
1445                                tenv );
1446                } else {
1447                        // find all candidates for the argument to sizeof
1448                        CandidateFinder finder( context, tenv );
1449                        finder.find( sizeofExpr->expr );
1450                        // find the lowest-cost candidate, otherwise ambiguous
1451                        CandidateList winners = findMinCost( finder.candidates );
1452                        if ( winners.size() != 1 ) {
1453                                SemanticError(
1454                                        sizeofExpr->expr.get(), "Ambiguous expression in sizeof operand: " );
1455                        }
1456                        // return the lowest-cost candidate
1457                        CandidateRef & choice = winners.front();
1458                        choice->expr = referenceToRvalueConversion( choice->expr, choice->cost );
1459                        choice->cost = Cost::zero;
1460                        addCandidate( *choice, new ast::SizeofExpr{ sizeofExpr->location, choice->expr } );
1461                }
1462        }
1463
1464        void Finder::postvisit( const ast::AlignofExpr * alignofExpr ) {
1465                if ( alignofExpr->type ) {
1466                        addCandidate(
1467                                new ast::AlignofExpr{
1468                                        alignofExpr->location, resolveTypeof( alignofExpr->type, context ) },
1469                                tenv );
1470                } else {
1471                        // find all candidates for the argument to alignof
1472                        CandidateFinder finder( context, tenv );
1473                        finder.find( alignofExpr->expr );
1474                        // find the lowest-cost candidate, otherwise ambiguous
1475                        CandidateList winners = findMinCost( finder.candidates );
1476                        if ( winners.size() != 1 ) {
1477                                SemanticError(
1478                                        alignofExpr->expr.get(), "Ambiguous expression in alignof operand: " );
1479                        }
1480                        // return the lowest-cost candidate
1481                        CandidateRef & choice = winners.front();
1482                        choice->expr = referenceToRvalueConversion( choice->expr, choice->cost );
1483                        choice->cost = Cost::zero;
1484                        addCandidate(
1485                                *choice, new ast::AlignofExpr{ alignofExpr->location, choice->expr } );
1486                }
1487        }
1488
1489        void Finder::postvisit( const ast::UntypedOffsetofExpr * offsetofExpr ) {
1490                const ast::BaseInstType * aggInst;
1491                if (( aggInst = offsetofExpr->type.as< ast::StructInstType >() )) ;
1492                else if (( aggInst = offsetofExpr->type.as< ast::UnionInstType >() )) ;
1493                else return;
1494
1495                for ( const ast::Decl * member : aggInst->lookup( offsetofExpr->member ) ) {
1496                        auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( member );
1497                        addCandidate(
1498                                new ast::OffsetofExpr{ offsetofExpr->location, aggInst, dwt }, tenv );
1499                }
1500        }
1501
1502        void Finder::postvisit( const ast::OffsetofExpr * offsetofExpr ) {
1503                addCandidate( offsetofExpr, tenv );
1504        }
1505
1506        void Finder::postvisit( const ast::OffsetPackExpr * offsetPackExpr ) {
1507                addCandidate( offsetPackExpr, tenv );
1508        }
1509
1510        void Finder::postvisit( const ast::LogicalExpr * logicalExpr ) {
1511                CandidateFinder finder1( context, tenv );
1512                ast::ptr<ast::Expr> arg1 = notZeroExpr( logicalExpr->arg1 );
1513                finder1.find( arg1, ResolveMode::withAdjustment() );
1514                if ( finder1.candidates.empty() ) return;
1515
1516                CandidateFinder finder2( context, tenv );
1517                ast::ptr<ast::Expr> arg2 = notZeroExpr( logicalExpr->arg2 );
1518                finder2.find( arg2, ResolveMode::withAdjustment() );
1519                if ( finder2.candidates.empty() ) return;
1520
1521                reason.code = NoMatch;
1522
1523                for ( const CandidateRef & r1 : finder1.candidates ) {
1524                        for ( const CandidateRef & r2 : finder2.candidates ) {
1525                                ast::TypeEnvironment env{ r1->env };
1526                                env.simpleCombine( r2->env );
1527                                ast::OpenVarSet open{ r1->open };
1528                                mergeOpenVars( open, r2->open );
1529                                ast::AssertionSet need;
1530                                mergeAssertionSet( need, r1->need );
1531                                mergeAssertionSet( need, r2->need );
1532
1533                                addCandidate(
1534                                        new ast::LogicalExpr{
1535                                                logicalExpr->location, r1->expr, r2->expr, logicalExpr->isAnd },
1536                                        std::move( env ), std::move( open ), std::move( need ), r1->cost + r2->cost );
1537                        }
1538                }
1539        }
1540
1541        void Finder::postvisit( const ast::ConditionalExpr * conditionalExpr ) {
1542                // candidates for condition
1543                CandidateFinder finder1( context, tenv );
1544                ast::ptr<ast::Expr> arg1 = notZeroExpr( conditionalExpr->arg1 );
1545                finder1.find( arg1, ResolveMode::withAdjustment() );
1546                if ( finder1.candidates.empty() ) return;
1547
1548                // candidates for true result
1549                CandidateFinder finder2( context, tenv );
1550                finder2.allowVoid = true;
1551                finder2.find( conditionalExpr->arg2, ResolveMode::withAdjustment() );
1552                if ( finder2.candidates.empty() ) return;
1553
1554                // candidates for false result
1555                CandidateFinder finder3( context, tenv );
1556                finder3.allowVoid = true;
1557                finder3.find( conditionalExpr->arg3, ResolveMode::withAdjustment() );
1558                if ( finder3.candidates.empty() ) return;
1559
1560                reason.code = NoMatch;
1561
1562                for ( const CandidateRef & r1 : finder1.candidates ) {
1563                        for ( const CandidateRef & r2 : finder2.candidates ) {
1564                                for ( const CandidateRef & r3 : finder3.candidates ) {
1565                                        ast::TypeEnvironment env{ r1->env };
1566                                        env.simpleCombine( r2->env );
1567                                        env.simpleCombine( r3->env );
1568                                        ast::OpenVarSet open{ r1->open };
1569                                        mergeOpenVars( open, r2->open );
1570                                        mergeOpenVars( open, r3->open );
1571                                        ast::AssertionSet need;
1572                                        mergeAssertionSet( need, r1->need );
1573                                        mergeAssertionSet( need, r2->need );
1574                                        mergeAssertionSet( need, r3->need );
1575                                        ast::AssertionSet have;
1576
1577                                        // unify true and false results, then infer parameters to produce new
1578                                        // candidates
1579                                        ast::ptr< ast::Type > common;
1580                                        if (
1581                                                unify(
1582                                                        r2->expr->result, r3->expr->result, env, need, have, open,
1583                                                        common )
1584                                        ) {
1585                                                // generate typed expression
1586                                                ast::ConditionalExpr * newExpr = new ast::ConditionalExpr{
1587                                                        conditionalExpr->location, r1->expr, r2->expr, r3->expr };
1588                                                newExpr->result = common ? common : r2->expr->result;
1589                                                // convert both options to result type
1590                                                Cost cost = r1->cost + r2->cost + r3->cost;
1591                                                newExpr->arg2 = computeExpressionConversionCost(
1592                                                        newExpr->arg2, newExpr->result, symtab, env, cost );
1593                                                newExpr->arg3 = computeExpressionConversionCost(
1594                                                        newExpr->arg3, newExpr->result, symtab, env, cost );
1595                                                // output candidate
1596                                                CandidateRef newCand = std::make_shared<Candidate>(
1597                                                        newExpr, std::move( env ), std::move( open ), std::move( need ), cost );
1598                                                inferParameters( newCand, candidates );
1599                                        }
1600                                }
1601                        }
1602                }
1603        }
1604
1605        void Finder::postvisit( const ast::CommaExpr * commaExpr ) {
1606                ast::TypeEnvironment env{ tenv };
1607                ast::ptr< ast::Expr > arg1 = resolveInVoidContext( commaExpr->arg1, context, env );
1608
1609                CandidateFinder finder2( context, env );
1610                finder2.find( commaExpr->arg2, ResolveMode::withAdjustment() );
1611
1612                for ( const CandidateRef & r2 : finder2.candidates ) {
1613                        addCandidate( *r2, new ast::CommaExpr{ commaExpr->location, arg1, r2->expr } );
1614                }
1615        }
1616
1617        void Finder::postvisit( const ast::ImplicitCopyCtorExpr * ctorExpr ) {
1618                addCandidate( ctorExpr, tenv );
1619        }
1620
1621        void Finder::postvisit( const ast::ConstructorExpr * ctorExpr ) {
1622                CandidateFinder finder( context, tenv );
1623                finder.allowVoid = true;
1624                finder.find( ctorExpr->callExpr, ResolveMode::withoutPrune() );
1625                for ( CandidateRef & r : finder.candidates ) {
1626                        addCandidate( *r, new ast::ConstructorExpr{ ctorExpr->location, r->expr } );
1627                }
1628        }
1629
1630        void Finder::postvisit( const ast::RangeExpr * rangeExpr ) {
1631                // resolve low and high, accept candidates where low and high types unify
1632                CandidateFinder finder1( context, tenv );
1633                finder1.find( rangeExpr->low, ResolveMode::withAdjustment() );
1634                if ( finder1.candidates.empty() ) return;
1635
1636                CandidateFinder finder2( context, tenv );
1637                finder2.find( rangeExpr->high, ResolveMode::withAdjustment() );
1638                if ( finder2.candidates.empty() ) return;
1639
1640                reason.code = NoMatch;
1641
1642                for ( const CandidateRef & r1 : finder1.candidates ) {
1643                        for ( const CandidateRef & r2 : finder2.candidates ) {
1644                                ast::TypeEnvironment env{ r1->env };
1645                                env.simpleCombine( r2->env );
1646                                ast::OpenVarSet open{ r1->open };
1647                                mergeOpenVars( open, r2->open );
1648                                ast::AssertionSet need;
1649                                mergeAssertionSet( need, r1->need );
1650                                mergeAssertionSet( need, r2->need );
1651                                ast::AssertionSet have;
1652
1653                                ast::ptr< ast::Type > common;
1654                                if (
1655                                        unify(
1656                                                r1->expr->result, r2->expr->result, env, need, have, open,
1657                                                common )
1658                                ) {
1659                                        // generate new expression
1660                                        ast::RangeExpr * newExpr =
1661                                                new ast::RangeExpr{ rangeExpr->location, r1->expr, r2->expr };
1662                                        newExpr->result = common ? common : r1->expr->result;
1663                                        // add candidate
1664                                        CandidateRef newCand = std::make_shared<Candidate>(
1665                                                newExpr, std::move( env ), std::move( open ), std::move( need ),
1666                                                r1->cost + r2->cost );
1667                                        inferParameters( newCand, candidates );
1668                                }
1669                        }
1670                }
1671        }
1672
1673        void Finder::postvisit( const ast::UntypedTupleExpr * tupleExpr ) {
1674                std::vector< CandidateFinder > subCandidates =
1675                        selfFinder.findSubExprs( tupleExpr->exprs );
1676                std::vector< CandidateList > possibilities;
1677                combos( subCandidates.begin(), subCandidates.end(), back_inserter( possibilities ) );
1678
1679                for ( const CandidateList & subs : possibilities ) {
1680                        std::vector< ast::ptr< ast::Expr > > exprs;
1681                        exprs.reserve( subs.size() );
1682                        for ( const CandidateRef & sub : subs ) { exprs.emplace_back( sub->expr ); }
1683
1684                        ast::TypeEnvironment env;
1685                        ast::OpenVarSet open;
1686                        ast::AssertionSet need;
1687                        for ( const CandidateRef & sub : subs ) {
1688                                env.simpleCombine( sub->env );
1689                                mergeOpenVars( open, sub->open );
1690                                mergeAssertionSet( need, sub->need );
1691                        }
1692
1693                        addCandidate(
1694                                new ast::TupleExpr{ tupleExpr->location, std::move( exprs ) },
1695                                std::move( env ), std::move( open ), std::move( need ), sumCost( subs ) );
1696                }
1697        }
1698
1699        void Finder::postvisit( const ast::TupleExpr * tupleExpr ) {
1700                addCandidate( tupleExpr, tenv );
1701        }
1702
1703        void Finder::postvisit( const ast::TupleIndexExpr * tupleExpr ) {
1704                addCandidate( tupleExpr, tenv );
1705        }
1706
1707        void Finder::postvisit( const ast::TupleAssignExpr * tupleExpr ) {
1708                addCandidate( tupleExpr, tenv );
1709        }
1710
1711        void Finder::postvisit( const ast::UniqueExpr * unqExpr ) {
1712                CandidateFinder finder( context, tenv );
1713                finder.find( unqExpr->expr, ResolveMode::withAdjustment() );
1714                for ( CandidateRef & r : finder.candidates ) {
1715                        // ensure that the the id is passed on so that the expressions are "linked"
1716                        addCandidate( *r, new ast::UniqueExpr{ unqExpr->location, r->expr, unqExpr->id } );
1717                }
1718        }
1719
1720        void Finder::postvisit( const ast::StmtExpr * stmtExpr ) {
1721                addCandidate( resolveStmtExpr( stmtExpr, context ), tenv );
1722        }
1723
1724        void Finder::postvisit( const ast::UntypedInitExpr * initExpr ) {
1725                // handle each option like a cast
1726                CandidateList matches;
1727                PRINT(
1728                        std::cerr << "untyped init expr: " << initExpr << std::endl;
1729                )
1730                // O(n^2) checks of d-types with e-types
1731                for ( const ast::InitAlternative & initAlt : initExpr->initAlts ) {
1732                        // calculate target type
1733                        const ast::Type * toType = resolveTypeof( initAlt.type, context );
1734                        toType = adjustExprType( toType, tenv, symtab );
1735                        // The call to find must occur inside this loop, otherwise polymorphic return
1736                        // types are not bound to the initialization type, since return type variables are
1737                        // only open for the duration of resolving the UntypedExpr.
1738                        CandidateFinder finder( context, tenv, toType );
1739                        finder.find( initExpr->expr, ResolveMode::withAdjustment() );
1740
1741                        Cost minExprCost = Cost::infinity;
1742                        Cost minCastCost = Cost::infinity;
1743                        for ( CandidateRef & cand : finder.candidates ) {
1744                                if (reason.code == NotFound) reason.code = NoMatch;
1745
1746                                ast::TypeEnvironment env{ cand->env };
1747                                ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have;
1748                                ast::OpenVarSet open{ cand->open };
1749
1750                                PRINT(
1751                                        std::cerr << "  @ " << toType << " " << initAlt.designation << std::endl;
1752                                )
1753
1754                                // It is possible that a cast can throw away some values in a multiply-valued
1755                                // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of
1756                                // the subexpression results that are cast directly. The candidate is invalid
1757                                // if it has fewer results than there are types to cast to.
1758                                int discardedValues = cand->expr->result->size() - toType->size();
1759                                if ( discardedValues < 0 ) continue;
1760
1761                                // unification run for side-effects
1762                                bool canUnify = unify( toType, cand->expr->result, env, need, have, open );
1763                                (void) canUnify;
1764                                Cost thisCost = computeConversionCost( cand->expr->result, toType, cand->expr->get_lvalue(),
1765                                        symtab, env );
1766                                PRINT(
1767                                        Cost legacyCost = castCost( cand->expr->result, toType, cand->expr->get_lvalue(),
1768                                                symtab, env );
1769                                        std::cerr << "Considering initialization:";
1770                                        std::cerr << std::endl << "  FROM: " << cand->expr->result << std::endl;
1771                                        std::cerr << std::endl << "  TO: "   << toType             << std::endl;
1772                                        std::cerr << std::endl << "  Unification " << (canUnify ? "succeeded" : "failed");
1773                                        std::cerr << std::endl << "  Legacy cost " << legacyCost;
1774                                        std::cerr << std::endl << "  New cost " << thisCost;
1775                                        std::cerr << std::endl;
1776                                )
1777                                if ( thisCost != Cost::infinity ) {
1778                                        // count one safe conversion for each value that is thrown away
1779                                        thisCost.incSafe( discardedValues );
1780                                        if ( cand->cost < minExprCost || ( cand->cost == minExprCost && thisCost < minCastCost ) ) {
1781                                                minExprCost = cand->cost;
1782                                                minCastCost = thisCost;
1783                                                matches.clear();
1784                                        }
1785                                        // ambiguous case, still output candidates to print in error message
1786                                        if ( cand->cost == minExprCost && thisCost == minCastCost ) {
1787                                                CandidateRef newCand = std::make_shared<Candidate>(
1788                                                        new ast::InitExpr{
1789                                                                initExpr->location,
1790                                                                restructureCast( cand->expr, toType ),
1791                                                                initAlt.designation },
1792                                                        std::move(env), std::move( open ), std::move( need ), cand->cost + thisCost );
1793                                                // currently assertions are always resolved immediately so this should have no effect.
1794                                                // if this somehow changes in the future (e.g. delayed by indeterminate return type)
1795                                                // we may need to revisit the logic.
1796                                                inferParameters( newCand, matches );
1797                                        }
1798                                }
1799                        }
1800                }
1801
1802                // select first on argument cost, then conversion cost
1803                // CandidateList minArgCost = findMinCost( matches );
1804                // promoteCvtCost( minArgCost );
1805                // candidates = findMinCost( minArgCost );
1806                candidates = std::move(matches);
1807        }
1808
1809        // size_t Finder::traceId = Stats::Heap::new_stacktrace_id("Finder");
1810        /// Prunes a list of candidates down to those that have the minimum conversion cost for a given
1811        /// return type. Skips ambiguous candidates.
1812
1813} // anonymous namespace
1814
1815bool CandidateFinder::pruneCandidates( CandidateList & candidates, CandidateList & out, std::vector<std::string> & errors ) {
1816        struct PruneStruct {
1817                CandidateRef candidate;
1818                bool ambiguous;
1819
1820                PruneStruct() = default;
1821                PruneStruct( const CandidateRef & c ) : candidate( c ), ambiguous( false ) {}
1822        };
1823
1824        // find lowest-cost candidate for each type
1825        std::unordered_map< std::string, PruneStruct > selected;
1826        // attempt to skip satisfyAssertions on more expensive alternatives if better options have been found
1827        std::sort(candidates.begin(), candidates.end(), [](const CandidateRef & x, const CandidateRef & y){return x->cost < y->cost;});
1828        for ( CandidateRef & candidate : candidates ) {
1829                std::string mangleName;
1830                {
1831                        ast::ptr< ast::Type > newType = candidate->expr->result;
1832                        assertf(candidate->expr->result, "Result of expression %p for candidate is null", candidate->expr.get());
1833                        candidate->env.apply( newType );
1834                        mangleName = Mangle::mangle( newType );
1835                }
1836
1837                auto found = selected.find( mangleName );
1838                if (found != selected.end() && found->second.candidate->cost < candidate->cost) {
1839                        PRINT(
1840                                std::cerr << "cost " << candidate->cost << " loses to "
1841                                        << found->second.candidate->cost << std::endl;
1842                        )
1843                        continue;
1844                }
1845
1846                // xxx - when do satisfyAssertions produce more than 1 result?
1847                // this should only happen when initial result type contains
1848                // unbound type parameters, then it should never be pruned by
1849                // the previous step, since renameTyVars guarantees the mangled name
1850                // is unique.
1851                CandidateList satisfied;
1852                bool needRecomputeKey = false;
1853                if (candidate->need.empty()) {
1854                        satisfied.emplace_back(candidate);
1855                }
1856                else {
1857                        satisfyAssertions(candidate, context.symtab, satisfied, errors);
1858                        needRecomputeKey = true;
1859                }
1860
1861                for (auto & newCand : satisfied) {
1862                        // recomputes type key, if satisfyAssertions changed it
1863                        if (needRecomputeKey)
1864                        {
1865                                ast::ptr< ast::Type > newType = newCand->expr->result;
1866                                assertf(newCand->expr->result, "Result of expression %p for candidate is null", newCand->expr.get());
1867                                newCand->env.apply( newType );
1868                                mangleName = Mangle::mangle( newType );
1869                        }
1870                        auto found = selected.find( mangleName );
1871                        if ( found != selected.end() ) {
1872                                // tiebreaking by picking the lower cost on CURRENT expression
1873                                // NOTE: this behavior is different from C semantics.
1874                                // Specific remediations are performed for C operators at postvisit(UntypedExpr).
1875                                // Further investigations may take place.
1876                                if ( newCand->cost < found->second.candidate->cost
1877                                        || (newCand->cost == found->second.candidate->cost && newCand->cvtCost < found->second.candidate->cvtCost) ) {
1878                                        PRINT(
1879                                                std::cerr << "cost " << newCand->cost << " beats "
1880                                                        << found->second.candidate->cost << std::endl;
1881                                        )
1882
1883                                        found->second = PruneStruct{ newCand };
1884                                } else if ( newCand->cost == found->second.candidate->cost && newCand->cvtCost == found->second.candidate->cvtCost ) {
1885                                        // if one of the candidates contains a deleted identifier, can pick the other,
1886                                        // since deleted expressions should not be ambiguous if there is another option
1887                                        // that is at least as good
1888                                        if ( findDeletedExpr( newCand->expr ) ) {
1889                                                // do nothing
1890                                                PRINT( std::cerr << "candidate is deleted" << std::endl; )
1891                                        } else if ( findDeletedExpr( found->second.candidate->expr ) ) {
1892                                                PRINT( std::cerr << "current is deleted" << std::endl; )
1893                                                found->second = PruneStruct{ newCand };
1894                                        } else {
1895                                                PRINT( std::cerr << "marking ambiguous" << std::endl; )
1896                                                found->second.ambiguous = true;
1897                                        }
1898                                } else {
1899                                        // xxx - can satisfyAssertions increase the cost?
1900                                        PRINT(
1901                                                std::cerr << "cost " << newCand->cost << " loses to "
1902                                                        << found->second.candidate->cost << std::endl;
1903                                        )
1904                                }
1905                        } else {
1906                                selected.emplace_hint( found, mangleName, newCand );
1907                        }
1908                }
1909        }
1910
1911        // report unambiguous min-cost candidates
1912        // CandidateList out;
1913        for ( auto & target : selected ) {
1914                if ( target.second.ambiguous ) continue;
1915
1916                CandidateRef cand = target.second.candidate;
1917
1918                ast::ptr< ast::Type > newResult = cand->expr->result;
1919                cand->env.applyFree( newResult );
1920                cand->expr = ast::mutate_field(
1921                        cand->expr.get(), &ast::Expr::result, std::move( newResult ) );
1922
1923                out.emplace_back( cand );
1924        }
1925        // if everything is lost in satisfyAssertions, report the error
1926        return !selected.empty();
1927}
1928
1929void CandidateFinder::find( const ast::Expr * expr, ResolveMode mode ) {
1930        // Find alternatives for expression
1931        ast::Pass<Finder> finder{ *this };
1932        expr->accept( finder );
1933
1934        if ( mode.failFast && candidates.empty() ) {
1935                switch(finder.core.reason.code) {
1936                case Finder::NotFound:
1937                        { SemanticError( expr, "No alternatives for expression " ); break; }
1938                case Finder::NoMatch:
1939                        { SemanticError( expr, "Invalid application of existing declaration(s) in expression " ); break; }
1940                case Finder::ArgsToFew:
1941                case Finder::ArgsToMany:
1942                case Finder::RetsToFew:
1943                case Finder::RetsToMany:
1944                case Finder::NoReason:
1945                default:
1946                        { SemanticError( expr->location, "No reasonable alternatives for expression : reasons unkown" ); }
1947                }
1948        }
1949
1950        /*
1951        if ( mode.satisfyAssns || mode.prune ) {
1952                // trim candidates to just those where the assertions are satisfiable
1953                // - necessary pre-requisite to pruning
1954                CandidateList satisfied;
1955                std::vector< std::string > errors;
1956                for ( CandidateRef & candidate : candidates ) {
1957                        satisfyAssertions( candidate, localSyms, satisfied, errors );
1958                }
1959
1960                // fail early if none such
1961                if ( mode.failFast && satisfied.empty() ) {
1962                        std::ostringstream stream;
1963                        stream << "No alternatives with satisfiable assertions for " << expr << "\n";
1964                        for ( const auto& err : errors ) {
1965                                stream << err;
1966                        }
1967                        SemanticError( expr->location, stream.str() );
1968                }
1969
1970                // reset candidates
1971                candidates = move( satisfied );
1972        }
1973        */
1974
1975        // optimization: don't prune for NameExpr since it never has cost
1976        if ( mode.prune && !dynamic_cast<const ast::NameExpr *>(expr) ) {
1977                // trim candidates to single best one
1978                PRINT(
1979                        std::cerr << "alternatives before prune:" << std::endl;
1980                        print( std::cerr, candidates );
1981                )
1982
1983                CandidateList pruned;
1984                std::vector<std::string> errors;
1985                bool found = pruneCandidates( candidates, pruned, errors );
1986
1987                if ( mode.failFast && pruned.empty() ) {
1988                        std::ostringstream stream;
1989                        if (found) {
1990                                CandidateList winners = findMinCost( candidates );
1991                                stream << "Cannot choose between " << winners.size() << " alternatives for "
1992                                        "expression\n";
1993                                ast::print( stream, expr );
1994                                stream << " Alternatives are:\n";
1995                                print( stream, winners, 1 );
1996                                SemanticError( expr->location, stream.str() );
1997                        }
1998                        else {
1999                                stream << "No alternatives with satisfiable assertions for " << expr << "\n";
2000                                for ( const auto& err : errors ) {
2001                                        stream << err;
2002                                }
2003                                SemanticError( expr->location, stream.str() );
2004                        }
2005                }
2006
2007                auto oldsize = candidates.size();
2008                candidates = std::move( pruned );
2009
2010                PRINT(
2011                        std::cerr << "there are " << oldsize << " alternatives before elimination" << std::endl;
2012                )
2013                PRINT(
2014                        std::cerr << "there are " << candidates.size() << " alternatives after elimination"
2015                                << std::endl;
2016                )
2017        }
2018
2019        // adjust types after pruning so that types substituted by pruneAlternatives are correctly
2020        // adjusted
2021        if ( mode.adjust ) {
2022                for ( CandidateRef & r : candidates ) {
2023                        r->expr = ast::mutate_field(
2024                                r->expr.get(), &ast::Expr::result,
2025                                adjustExprType( r->expr->result, r->env, context.symtab ) );
2026                }
2027        }
2028
2029        // Central location to handle gcc extension keyword, etc. for all expressions
2030        for ( CandidateRef & r : candidates ) {
2031                if ( r->expr->extension != expr->extension ) {
2032                        r->expr.get_and_mutate()->extension = expr->extension;
2033                }
2034        }
2035}
2036
2037std::vector< CandidateFinder > CandidateFinder::findSubExprs(
2038        const std::vector< ast::ptr< ast::Expr > > & xs
2039) {
2040        std::vector< CandidateFinder > out;
2041
2042        for ( const auto & x : xs ) {
2043                out.emplace_back( context, env );
2044                out.back().find( x, ResolveMode::withAdjustment() );
2045
2046                PRINT(
2047                        std::cerr << "findSubExprs" << std::endl;
2048                        print( std::cerr, out.back().candidates );
2049                )
2050        }
2051
2052        return out;
2053}
2054
2055const ast::Expr * referenceToRvalueConversion( const ast::Expr * expr, Cost & cost ) {
2056        if ( expr->result.as< ast::ReferenceType >() ) {
2057                // cast away reference from expr
2058                cost.incReference();
2059                return new ast::CastExpr{ expr, expr->result->stripReferences() };
2060        }
2061
2062        return expr;
2063}
2064
2065Cost computeConversionCost(
2066        const ast::Type * argType, const ast::Type * paramType, bool argIsLvalue,
2067        const ast::SymbolTable & symtab, const ast::TypeEnvironment & env
2068) {
2069        PRINT(
2070                std::cerr << std::endl << "converting ";
2071                ast::print( std::cerr, argType, 2 );
2072                std::cerr << std::endl << " to ";
2073                ast::print( std::cerr, paramType, 2 );
2074                std::cerr << std::endl << "environment is: ";
2075                ast::print( std::cerr, env, 2 );
2076                std::cerr << std::endl;
2077        )
2078        Cost convCost = conversionCost( argType, paramType, argIsLvalue, symtab, env );
2079        PRINT(
2080                std::cerr << std::endl << "cost is " << convCost << std::endl;
2081        )
2082        if ( convCost == Cost::infinity ) return convCost;
2083        convCost.incPoly( polyCost( paramType, symtab, env ) + polyCost( argType, symtab, env ) );
2084        PRINT(
2085                std::cerr << "cost with polycost is " << convCost << std::endl;
2086        )
2087        return convCost;
2088}
2089
2090} // namespace ResolvExpr
2091
2092// Local Variables: //
2093// tab-width: 4 //
2094// mode: c++ //
2095// compile-command: "make install" //
2096// End: //
Note: See TracBrowser for help on using the repository browser.