source: src/ResolvExpr/CandidateFinder.cpp @ 61e362f

Last change on this file since 61e362f was 61e362f, checked in by Andrew Beach <ajbeach@…>, 5 months ago

Changed notZeroExpr so that expressions with conditional contexts are handled in the resolver instead of the parser. Bugs kept the same from being done with statements. (Also a bit of clean-up from the last commit and a small fix in code-gen.)

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