source: src/ResolvExpr/CandidateFinder.cpp @ 85855b0

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