source: src/ResolvExpr/CandidateFinder.cpp @ 8c55d34

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