source: src/ResolvExpr/CandidateFinder.cpp @ da87eaf

Last change on this file since da87eaf was ab780e6, checked in by Andrew Beach <ajbeach@…>, 7 months ago

notZeroExpr (in the parser) has become createCondExpr (in the resolver). A small part of this, with expressions, had been done previously.

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