source: src/ResolvExpr/CandidateFinder.cpp @ d06273c

Last change on this file since d06273c was 2beaf9b, checked in by Andrew Beach <ajbeach@…>, 4 months ago

Forgot to update comments from the last commit.

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