source: src/ResolvExpr/CandidateFinder.cpp @ 3f3bfe5a

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 3f3bfe5a was cf32116, checked in by Andrew Beach <ajbeach@…>, 5 years ago

Implemented expression based lvalue resolution on new ast.

  • Property mode set to 100644
File size: 59.4 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// CandidateFinder.cpp --
8//
9// Author           : Aaron B. Moss
10// Created On       : Wed Jun 5 14:30:00 2019
11// Last Modified By : Andrew Beach
12// Last Modified On : Tue Oct  1 14:55:00 2019
13// Update Count     : 2
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 "Candidate.hpp"
26#include "CompilationState.h"
27#include "Cost.h"
28#include "ExplodedArg.hpp"
29#include "RenameVars.h"           // for renameTyVars
30#include "Resolver.h"
31#include "ResolveTypeof.h"
32#include "SatisfyAssertions.hpp"
33#include "typeops.h"              // for adjustExprType, conversionCost, polyCost, specCost
34#include "Unify.h"
35#include "AST/Expr.hpp"
36#include "AST/Node.hpp"
37#include "AST/Pass.hpp"
38#include "AST/Print.hpp"
39#include "AST/SymbolTable.hpp"
40#include "AST/Type.hpp"
41#include "Common/utility.h"       // for move, copy
42#include "SymTab/Mangler.h"
43#include "SymTab/Validate.h"      // for validateType
44#include "Tuples/Tuples.h"        // for handleTupleAssignment
45
46#define PRINT( text ) if ( resolvep ) { text }
47
48namespace ResolvExpr {
49
50const ast::Expr * referenceToRvalueConversion( const ast::Expr * expr, Cost & cost ) {
51        if ( expr->result.as< ast::ReferenceType >() ) {
52                // cast away reference from expr
53                cost.incReference();
54                return new ast::CastExpr{ expr, expr->result->stripReferences() };
55        }
56
57        return expr;
58}
59
60/// Unique identifier for matching expression resolutions to their requesting expression
61UniqueId globalResnSlot = 0;
62
63Cost computeConversionCost(
64        const ast::Type * argType, const ast::Type * paramType, bool argIsLvalue,
65        const ast::SymbolTable & symtab, const ast::TypeEnvironment & env
66) {
67        PRINT(
68                std::cerr << std::endl << "converting ";
69                ast::print( std::cerr, argType, 2 );
70                std::cerr << std::endl << " to ";
71                ast::print( std::cerr, paramType, 2 );
72                std::cerr << std::endl << "environment is: ";
73                ast::print( std::cerr, env, 2 );
74                std::cerr << std::endl;
75        )
76        Cost convCost = conversionCost( argType, paramType, argIsLvalue, symtab, env );
77        PRINT(
78                std::cerr << std::endl << "cost is " << convCost << std::endl;
79        )
80        if ( convCost == Cost::infinity ) return convCost;
81        convCost.incPoly( polyCost( paramType, symtab, env ) + polyCost( argType, symtab, env ) );
82        PRINT(
83                std::cerr << "cost with polycost is " << convCost << std::endl;
84        )
85        return convCost;
86}
87
88namespace {
89        /// First index is which argument, second is which alternative, third is which exploded element
90        using ExplodedArgs_new = std::deque< std::vector< ExplodedArg > >;
91
92        /// Returns a list of alternatives with the minimum cost in the given list
93        CandidateList findMinCost( const CandidateList & candidates ) {
94                CandidateList out;
95                Cost minCost = Cost::infinity;
96                for ( const CandidateRef & r : candidates ) {
97                        if ( r->cost < minCost ) {
98                                minCost = r->cost;
99                                out.clear();
100                                out.emplace_back( r );
101                        } else if ( r->cost == minCost ) {
102                                out.emplace_back( r );
103                        }
104                }
105                return out;
106        }
107
108        /// Computes conversion cost for a given expression to a given type
109        const ast::Expr * computeExpressionConversionCost(
110                const ast::Expr * arg, const ast::Type * paramType, const ast::SymbolTable & symtab, const ast::TypeEnvironment & env, Cost & outCost
111        ) {
112                Cost convCost = computeConversionCost(
113                                arg->result, paramType, arg->get_lvalue(), symtab, env );
114                outCost += convCost;
115
116                // If there is a non-zero conversion cost, ignoring poly cost, then the expression requires
117                // conversion. Ignore poly cost for now, since this requires resolution of the cast to
118                // infer parameters and this does not currently work for the reason stated below
119                Cost tmpCost = convCost;
120                tmpCost.incPoly( -tmpCost.get_polyCost() );
121                if ( tmpCost != Cost::zero ) {
122                        ast::ptr< ast::Type > newType = paramType;
123                        env.apply( newType );
124                        return new ast::CastExpr{ arg, newType };
125
126                        // xxx - *should* be able to resolve this cast, but at the moment pointers are not
127                        // castable to zero_t, but are implicitly convertible. This is clearly inconsistent,
128                        // once this is fixed it should be possible to resolve the cast.
129                        // xxx - this isn't working, it appears because type1 (parameter) is seen as widenable,
130                        // but it shouldn't be because this makes the conversion from DT* to DT* since
131                        // commontype(zero_t, DT*) is DT*, rather than nothing
132
133                        // CandidateFinder finder{ symtab, env };
134                        // finder.find( arg, ResolvMode::withAdjustment() );
135                        // assertf( finder.candidates.size() > 0,
136                        //      "Somehow castable expression failed to find alternatives." );
137                        // assertf( finder.candidates.size() == 1,
138                        //      "Somehow got multiple alternatives for known cast expression." );
139                        // return finder.candidates.front()->expr;
140                }
141
142                return arg;
143        }
144
145        /// Computes conversion cost for a given candidate
146        Cost computeApplicationConversionCost(
147                CandidateRef cand, const ast::SymbolTable & symtab
148        ) {
149                auto appExpr = cand->expr.strict_as< ast::ApplicationExpr >();
150                auto pointer = appExpr->func->result.strict_as< ast::PointerType >();
151                auto function = pointer->base.strict_as< ast::FunctionType >();
152
153                Cost convCost = Cost::zero;
154                const auto & params = function->params;
155                auto param = params.begin();
156                auto & args = appExpr->args;
157
158                for ( unsigned i = 0; i < args.size(); ++i ) {
159                        const ast::Type * argType = args[i]->result;
160                        PRINT(
161                                std::cerr << "arg expression:" << std::endl;
162                                ast::print( std::cerr, args[i], 2 );
163                                std::cerr << "--- results are" << std::endl;
164                                ast::print( std::cerr, argType, 2 );
165                        )
166
167                        if ( param == params.end() ) {
168                                if ( function->isVarArgs ) {
169                                        convCost.incUnsafe();
170                                        PRINT( std::cerr << "end of params with varargs function: inc unsafe: "
171                                                << convCost << std::endl; ; )
172                                        // convert reference-typed expressions into value-typed expressions
173                                        cand->expr = ast::mutate_field_index(
174                                                appExpr, &ast::ApplicationExpr::args, i,
175                                                referenceToRvalueConversion( args[i], convCost ) );
176                                        continue;
177                                } else return Cost::infinity;
178                        }
179
180                        if ( auto def = args[i].as< ast::DefaultArgExpr >() ) {
181                                // Default arguments should be free - don't include conversion cost.
182                                // Unwrap them here because they are not relevant to the rest of the system
183                                cand->expr = ast::mutate_field_index(
184                                        appExpr, &ast::ApplicationExpr::args, i, def->expr );
185                                ++param;
186                                continue;
187                        }
188
189                        // mark conversion cost and also specialization cost of param type
190                        const ast::Type * paramType = (*param)->get_type();
191                        cand->expr = ast::mutate_field_index(
192                                appExpr, &ast::ApplicationExpr::args, i,
193                                computeExpressionConversionCost(
194                                        args[i], paramType, symtab, cand->env, convCost ) );
195                        convCost.decSpec( specCost( paramType ) );
196                        ++param;  // can't be in for-loop update because of the continue
197                }
198
199                if ( param != params.end() ) return Cost::infinity;
200
201                // specialization cost of return types can't be accounted for directly, it disables
202                // otherwise-identical calls, like this example based on auto-newline in the I/O lib:
203                //
204                //   forall(otype OS) {
205                //     void ?|?(OS&, int);  // with newline
206                //     OS&  ?|?(OS&, int);  // no newline, always chosen due to more specialization
207                //   }
208
209                // mark type variable and specialization cost of forall clause
210                convCost.incVar( function->forall.size() );
211                for ( const ast::TypeDecl * td : function->forall ) {
212                        convCost.decSpec( td->assertions.size() );
213                }
214
215                return convCost;
216        }
217
218        void makeUnifiableVars(
219                const ast::ParameterizedType * type, ast::OpenVarSet & unifiableVars,
220                ast::AssertionSet & need
221        ) {
222                for ( const ast::TypeDecl * tyvar : type->forall ) {
223                        unifiableVars[ tyvar->name ] = ast::TypeDecl::Data{ tyvar };
224                        for ( const ast::DeclWithType * assn : tyvar->assertions ) {
225                                need[ assn ].isUsed = true;
226                        }
227                }
228        }
229
230        /// Gets a default value from an initializer, nullptr if not present
231        const ast::ConstantExpr * getDefaultValue( const ast::Init * init ) {
232                if ( auto si = dynamic_cast< const ast::SingleInit * >( init ) ) {
233                        if ( auto ce = si->value.as< ast::CastExpr >() ) {
234                                return ce->arg.as< ast::ConstantExpr >();
235                        } else {
236                                return si->value.as< ast::ConstantExpr >();
237                        }
238                }
239                return nullptr;
240        }
241
242        /// State to iteratively build a match of parameter expressions to arguments
243        struct ArgPack {
244                std::size_t parent;          ///< Index of parent pack
245                ast::ptr< ast::Expr > expr;  ///< The argument stored here
246                Cost cost;                   ///< The cost of this argument
247                ast::TypeEnvironment env;    ///< Environment for this pack
248                ast::AssertionSet need;      ///< Assertions outstanding for this pack
249                ast::AssertionSet have;      ///< Assertions found for this pack
250                ast::OpenVarSet open;        ///< Open variables for this pack
251                unsigned nextArg;            ///< Index of next argument in arguments list
252                unsigned tupleStart;         ///< Number of tuples that start at this index
253                unsigned nextExpl;           ///< Index of next exploded element
254                unsigned explAlt;            ///< Index of alternative for nextExpl > 0
255
256                ArgPack()
257                : parent( 0 ), expr(), cost( Cost::zero ), env(), need(), have(), open(), nextArg( 0 ),
258                  tupleStart( 0 ), nextExpl( 0 ), explAlt( 0 ) {}
259
260                ArgPack(
261                        const ast::TypeEnvironment & env, const ast::AssertionSet & need,
262                        const ast::AssertionSet & have, const ast::OpenVarSet & open )
263                : parent( 0 ), expr(), cost( Cost::zero ), env( env ), need( need ), have( have ),
264                  open( open ), nextArg( 0 ), tupleStart( 0 ), nextExpl( 0 ), explAlt( 0 ) {}
265
266                ArgPack(
267                        std::size_t parent, const ast::Expr * expr, ast::TypeEnvironment && env,
268                        ast::AssertionSet && need, ast::AssertionSet && have, ast::OpenVarSet && open,
269                        unsigned nextArg, unsigned tupleStart = 0, Cost cost = Cost::zero,
270                        unsigned nextExpl = 0, unsigned explAlt = 0 )
271                : parent(parent), expr( expr ), cost( cost ), env( move( env ) ), need( move( need ) ),
272                  have( move( have ) ), open( move( open ) ), nextArg( nextArg ), tupleStart( tupleStart ),
273                  nextExpl( nextExpl ), explAlt( explAlt ) {}
274
275                ArgPack(
276                        const ArgPack & o, ast::TypeEnvironment && env, ast::AssertionSet && need,
277                        ast::AssertionSet && have, ast::OpenVarSet && open, unsigned nextArg, Cost added )
278                : parent( o.parent ), expr( o.expr ), cost( o.cost + added ), env( move( env ) ),
279                  need( move( need ) ), have( move( have ) ), open( move( open ) ), nextArg( nextArg ),
280                  tupleStart( o.tupleStart ), nextExpl( 0 ), explAlt( 0 ) {}
281
282                /// true if this pack is in the middle of an exploded argument
283                bool hasExpl() const { return nextExpl > 0; }
284
285                /// Gets the list of exploded candidates for this pack
286                const ExplodedArg & getExpl( const ExplodedArgs_new & args ) const {
287                        return args[ nextArg-1 ][ explAlt ];
288                }
289
290                /// Ends a tuple expression, consolidating the appropriate args
291                void endTuple( const std::vector< ArgPack > & packs ) {
292                        // add all expressions in tuple to list, summing cost
293                        std::deque< const ast::Expr * > exprs;
294                        const ArgPack * pack = this;
295                        if ( expr ) { exprs.emplace_front( expr ); }
296                        while ( pack->tupleStart == 0 ) {
297                                pack = &packs[pack->parent];
298                                exprs.emplace_front( pack->expr );
299                                cost += pack->cost;
300                        }
301                        // reset pack to appropriate tuple
302                        std::vector< ast::ptr< ast::Expr > > exprv( exprs.begin(), exprs.end() );
303                        expr = new ast::TupleExpr{ expr->location, move( exprv ) };
304                        tupleStart = pack->tupleStart - 1;
305                        parent = pack->parent;
306                }
307        };
308
309        /// Instantiates an argument to match a parameter, returns false if no matching results left
310        bool instantiateArgument(
311                const ast::Type * paramType, const ast::Init * init, const ExplodedArgs_new & args,
312                std::vector< ArgPack > & results, std::size_t & genStart, const ast::SymbolTable & symtab,
313                unsigned nTuples = 0
314        ) {
315                if ( auto tupleType = dynamic_cast< const ast::TupleType * >( paramType ) ) {
316                        // paramType is a TupleType -- group args into a TupleExpr
317                        ++nTuples;
318                        for ( const ast::Type * type : *tupleType ) {
319                                // xxx - dropping initializer changes behaviour from previous, but seems correct
320                                // ^^^ need to handle the case where a tuple has a default argument
321                                if ( ! instantiateArgument(
322                                        type, nullptr, args, results, genStart, symtab, nTuples ) ) return false;
323                                nTuples = 0;
324                        }
325                        // re-constitute tuples for final generation
326                        for ( auto i = genStart; i < results.size(); ++i ) {
327                                results[i].endTuple( results );
328                        }
329                        return true;
330                } else if ( const ast::TypeInstType * ttype = Tuples::isTtype( paramType ) ) {
331                        // paramType is a ttype, consumes all remaining arguments
332
333                        // completed tuples; will be spliced to end of results to finish
334                        std::vector< ArgPack > finalResults{};
335
336                        // iterate until all results completed
337                        std::size_t genEnd;
338                        ++nTuples;
339                        do {
340                                genEnd = results.size();
341
342                                // add another argument to results
343                                for ( std::size_t i = genStart; i < genEnd; ++i ) {
344                                        unsigned nextArg = results[i].nextArg;
345
346                                        // use next element of exploded tuple if present
347                                        if ( results[i].hasExpl() ) {
348                                                const ExplodedArg & expl = results[i].getExpl( args );
349
350                                                unsigned nextExpl = results[i].nextExpl + 1;
351                                                if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
352
353                                                results.emplace_back(
354                                                        i, expl.exprs[ results[i].nextExpl ], copy( results[i].env ),
355                                                        copy( results[i].need ), copy( results[i].have ),
356                                                        copy( results[i].open ), nextArg, nTuples, Cost::zero, nextExpl,
357                                                        results[i].explAlt );
358
359                                                continue;
360                                        }
361
362                                        // finish result when out of arguments
363                                        if ( nextArg >= args.size() ) {
364                                                ArgPack newResult{
365                                                        results[i].env, results[i].need, results[i].have, results[i].open };
366                                                newResult.nextArg = nextArg;
367                                                const ast::Type * argType = nullptr;
368
369                                                if ( nTuples > 0 || ! results[i].expr ) {
370                                                        // first iteration or no expression to clone,
371                                                        // push empty tuple expression
372                                                        newResult.parent = i;
373                                                        newResult.expr = new ast::TupleExpr{ CodeLocation{}, {} };
374                                                        argType = newResult.expr->result;
375                                                } else {
376                                                        // clone result to collect tuple
377                                                        newResult.parent = results[i].parent;
378                                                        newResult.cost = results[i].cost;
379                                                        newResult.tupleStart = results[i].tupleStart;
380                                                        newResult.expr = results[i].expr;
381                                                        argType = newResult.expr->result;
382
383                                                        if ( results[i].tupleStart > 0 && Tuples::isTtype( argType ) ) {
384                                                                // the case where a ttype value is passed directly is special,
385                                                                // e.g. for argument forwarding purposes
386                                                                // xxx - what if passing multiple arguments, last of which is
387                                                                //       ttype?
388                                                                // xxx - what would happen if unify was changed so that unifying
389                                                                //       tuple
390                                                                // types flattened both before unifying lists? then pass in
391                                                                // TupleType (ttype) below.
392                                                                --newResult.tupleStart;
393                                                        } else {
394                                                                // collapse leftover arguments into tuple
395                                                                newResult.endTuple( results );
396                                                                argType = newResult.expr->result;
397                                                        }
398                                                }
399
400                                                // check unification for ttype before adding to final
401                                                if (
402                                                        unify(
403                                                                ttype, argType, newResult.env, newResult.need, newResult.have,
404                                                                newResult.open, symtab )
405                                                ) {
406                                                        finalResults.emplace_back( move( newResult ) );
407                                                }
408
409                                                continue;
410                                        }
411
412                                        // add each possible next argument
413                                        for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
414                                                const ExplodedArg & expl = args[nextArg][j];
415
416                                                // fresh copies of parent parameters for this iteration
417                                                ast::TypeEnvironment env = results[i].env;
418                                                ast::OpenVarSet open = results[i].open;
419
420                                                env.addActual( expl.env, open );
421
422                                                // skip empty tuple arguments by (nearly) cloning parent into next gen
423                                                if ( expl.exprs.empty() ) {
424                                                        results.emplace_back(
425                                                                results[i], move( env ), copy( results[i].need ),
426                                                                copy( results[i].have ), move( open ), nextArg + 1, expl.cost );
427
428                                                        continue;
429                                                }
430
431                                                // add new result
432                                                results.emplace_back(
433                                                        i, expl.exprs.front(), move( env ), copy( results[i].need ),
434                                                        copy( results[i].have ), move( open ), nextArg + 1, nTuples,
435                                                        expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
436                                        }
437                                }
438
439                                // reset for next round
440                                genStart = genEnd;
441                                nTuples = 0;
442                        } while ( genEnd != results.size() );
443
444                        // splice final results onto results
445                        for ( std::size_t i = 0; i < finalResults.size(); ++i ) {
446                                results.emplace_back( move( finalResults[i] ) );
447                        }
448                        return ! finalResults.empty();
449                }
450
451                // iterate each current subresult
452                std::size_t genEnd = results.size();
453                for ( std::size_t i = genStart; i < genEnd; ++i ) {
454                        unsigned nextArg = results[i].nextArg;
455
456                        // use remainder of exploded tuple if present
457                        if ( results[i].hasExpl() ) {
458                                const ExplodedArg & expl = results[i].getExpl( args );
459                                const ast::Expr * expr = expl.exprs[ results[i].nextExpl ];
460
461                                ast::TypeEnvironment env = results[i].env;
462                                ast::AssertionSet need = results[i].need, have = results[i].have;
463                                ast::OpenVarSet open = results[i].open;
464
465                                const ast::Type * argType = expr->result;
466
467                                PRINT(
468                                        std::cerr << "param type is ";
469                                        ast::print( std::cerr, paramType );
470                                        std::cerr << std::endl << "arg type is ";
471                                        ast::print( std::cerr, argType );
472                                        std::cerr << std::endl;
473                                )
474
475                                if ( unify( paramType, argType, env, need, have, open, symtab ) ) {
476                                        unsigned nextExpl = results[i].nextExpl + 1;
477                                        if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
478
479                                        results.emplace_back(
480                                                i, expr, move( env ), move( need ), move( have ), move( open ), nextArg,
481                                                nTuples, Cost::zero, nextExpl, results[i].explAlt );
482                                }
483
484                                continue;
485                        }
486
487                        // use default initializers if out of arguments
488                        if ( nextArg >= args.size() ) {
489                                if ( const ast::ConstantExpr * cnst = getDefaultValue( init ) ) {
490                                        ast::TypeEnvironment env = results[i].env;
491                                        ast::AssertionSet need = results[i].need, have = results[i].have;
492                                        ast::OpenVarSet open = results[i].open;
493
494                                        if ( unify( paramType, cnst->result, env, need, have, open, symtab ) ) {
495                                                results.emplace_back(
496                                                        i, new ast::DefaultArgExpr{ cnst->location, cnst }, move( env ),
497                                                        move( need ), move( have ), move( open ), nextArg, nTuples );
498                                        }
499                                }
500
501                                continue;
502                        }
503
504                        // Check each possible next argument
505                        for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
506                                const ExplodedArg & expl = args[nextArg][j];
507
508                                // fresh copies of parent parameters for this iteration
509                                ast::TypeEnvironment env = results[i].env;
510                                ast::AssertionSet need = results[i].need, have = results[i].have;
511                                ast::OpenVarSet open = results[i].open;
512
513                                env.addActual( expl.env, open );
514
515                                // skip empty tuple arguments by (nearly) cloning parent into next gen
516                                if ( expl.exprs.empty() ) {
517                                        results.emplace_back(
518                                                results[i], move( env ), move( need ), move( have ), move( open ),
519                                                nextArg + 1, expl.cost );
520
521                                        continue;
522                                }
523
524                                // consider only first exploded arg
525                                const ast::Expr * expr = expl.exprs.front();
526                                const ast::Type * argType = expr->result;
527
528                                PRINT(
529                                        std::cerr << "param type is ";
530                                        ast::print( std::cerr, paramType );
531                                        std::cerr << std::endl << "arg type is ";
532                                        ast::print( std::cerr, argType );
533                                        std::cerr << std::endl;
534                                )
535
536                                // attempt to unify types
537                                if ( unify( paramType, argType, env, need, have, open, symtab ) ) {
538                                        // add new result
539                                        results.emplace_back(
540                                                i, expr, move( env ), move( need ), move( have ), move( open ),
541                                                nextArg + 1, nTuples, expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
542                                }
543                        }
544                }
545
546                // reset for next parameter
547                genStart = genEnd;
548
549                return genEnd != results.size();  // were any new results added?
550        }
551
552        /// Generate a cast expression from `arg` to `toType`
553        const ast::Expr * restructureCast(
554                ast::ptr< ast::Expr > & arg, const ast::Type * toType, ast::GeneratedFlag isGenerated = ast::GeneratedCast
555        ) {
556                if (
557                        arg->result->size() > 1
558                        && ! toType->isVoid()
559                        && ! dynamic_cast< const ast::ReferenceType * >( toType )
560                ) {
561                        // Argument is a tuple and the target type is neither void nor a reference. Cast each
562                        // member of the tuple to its corresponding target type, producing the tuple of those
563                        // cast expressions. If there are more components of the tuple than components in the
564                        // target type, then excess components do not come out in the result expression (but
565                        // UniqueExpr ensures that the side effects will still be produced)
566                        if ( Tuples::maybeImpureIgnoreUnique( arg ) ) {
567                                // expressions which may contain side effects require a single unique instance of
568                                // the expression
569                                arg = new ast::UniqueExpr{ arg->location, arg };
570                        }
571                        std::vector< ast::ptr< ast::Expr > > components;
572                        for ( unsigned i = 0; i < toType->size(); ++i ) {
573                                // cast each component
574                                ast::ptr< ast::Expr > idx = new ast::TupleIndexExpr{ arg->location, arg, i };
575                                components.emplace_back(
576                                        restructureCast( idx, toType->getComponent( i ), isGenerated ) );
577                        }
578                        return new ast::TupleExpr{ arg->location, move( components ) };
579                } else {
580                        // handle normally
581                        return new ast::CastExpr{ arg->location, arg, toType, isGenerated };
582                }
583        }
584
585        /// Gets the name from an untyped member expression (must be NameExpr)
586        const std::string & getMemberName( const ast::UntypedMemberExpr * memberExpr ) {
587                if ( memberExpr->member.as< ast::ConstantExpr >() ) {
588                        SemanticError( memberExpr, "Indexed access to struct fields unsupported: " );
589                }
590
591                return memberExpr->member.strict_as< ast::NameExpr >()->name;
592        }
593
594        /// Actually visits expressions to find their candidate interpretations
595        class Finder final : public ast::WithShortCircuiting {
596                const ast::SymbolTable & symtab;
597        public:
598                CandidateFinder & selfFinder;
599                CandidateList & candidates;
600                const ast::TypeEnvironment & tenv;
601                ast::ptr< ast::Type > & targetType;
602
603                Finder( CandidateFinder & f )
604                : symtab( f.localSyms ), selfFinder( f ), candidates( f.candidates ), tenv( f.env ),
605                  targetType( f.targetType ) {}
606
607                void previsit( const ast::Node * ) { visit_children = false; }
608
609                /// Convenience to add candidate to list
610                template<typename... Args>
611                void addCandidate( Args &&... args ) {
612                        candidates.emplace_back( new Candidate{ std::forward<Args>( args )... } );
613                }
614
615                void postvisit( const ast::ApplicationExpr * applicationExpr ) {
616                        addCandidate( applicationExpr, tenv );
617                }
618
619                /// Set up candidate assertions for inference
620                void inferParameters( CandidateRef & newCand, CandidateList & out ) {
621                        // Set need bindings for any unbound assertions
622                        UniqueId crntResnSlot = 0; // matching ID for this expression's assertions
623                        for ( auto & assn : newCand->need ) {
624                                // skip already-matched assertions
625                                if ( assn.second.resnSlot != 0 ) continue;
626                                // assign slot for expression if needed
627                                if ( crntResnSlot == 0 ) { crntResnSlot = ++globalResnSlot; }
628                                // fix slot to assertion
629                                assn.second.resnSlot = crntResnSlot;
630                        }
631                        // pair slot to expression
632                        if ( crntResnSlot != 0 ) {
633                                newCand->expr.get_and_mutate()->inferred.resnSlots().emplace_back( crntResnSlot );
634                        }
635
636                        // add to output list; assertion satisfaction will occur later
637                        out.emplace_back( newCand );
638                }
639
640                /// Completes a function candidate with arguments located
641                void validateFunctionCandidate(
642                        const CandidateRef & func, ArgPack & result, const std::vector< ArgPack > & results,
643                        CandidateList & out
644                ) {
645                        ast::ApplicationExpr * appExpr =
646                                new ast::ApplicationExpr{ func->expr->location, func->expr };
647                        // sum cost and accumulate arguments
648                        std::deque< const ast::Expr * > args;
649                        Cost cost = func->cost;
650                        const ArgPack * pack = &result;
651                        while ( pack->expr ) {
652                                args.emplace_front( pack->expr );
653                                cost += pack->cost;
654                                pack = &results[pack->parent];
655                        }
656                        std::vector< ast::ptr< ast::Expr > > vargs( args.begin(), args.end() );
657                        appExpr->args = move( vargs );
658                        // build and validate new candidate
659                        auto newCand =
660                                std::make_shared<Candidate>( appExpr, result.env, result.open, result.need, cost );
661                        PRINT(
662                                std::cerr << "instantiate function success: " << appExpr << std::endl;
663                                std::cerr << "need assertions:" << std::endl;
664                                ast::print( std::cerr, result.need, 2 );
665                        )
666                        inferParameters( newCand, out );
667                }
668
669                /// Builds a list of candidates for a function, storing them in out
670                void makeFunctionCandidates(
671                        const CandidateRef & func, const ast::FunctionType * funcType,
672                        const ExplodedArgs_new & args, CandidateList & out
673                ) {
674                        ast::OpenVarSet funcOpen;
675                        ast::AssertionSet funcNeed, funcHave;
676                        ast::TypeEnvironment funcEnv{ func->env };
677                        makeUnifiableVars( funcType, funcOpen, funcNeed );
678                        // add all type variables as open variables now so that those not used in the
679                        // parameter list are still considered open
680                        funcEnv.add( funcType->forall );
681
682                        if ( targetType && ! targetType->isVoid() && ! funcType->returns.empty() ) {
683                                // attempt to narrow based on expected target type
684                                const ast::Type * returnType = funcType->returns.front()->get_type();
685                                if ( ! unify(
686                                        returnType, targetType, funcEnv, funcNeed, funcHave, funcOpen, symtab )
687                                ) {
688                                        // unification failed, do not pursue this candidate
689                                        return;
690                                }
691                        }
692
693                        // iteratively build matches, one parameter at a time
694                        std::vector< ArgPack > results;
695                        results.emplace_back( funcEnv, funcNeed, funcHave, funcOpen );
696                        std::size_t genStart = 0;
697
698                        for ( const ast::DeclWithType * param : funcType->params ) {
699                                auto obj = strict_dynamic_cast< const ast::ObjectDecl * >( param );
700                                // Try adding the arguments corresponding to the current parameter to the existing
701                                // matches
702                                if ( ! instantiateArgument(
703                                        obj->type, obj->init, args, results, genStart, symtab ) ) return;
704                        }
705
706                        if ( funcType->isVarArgs ) {
707                                // append any unused arguments to vararg pack
708                                std::size_t genEnd;
709                                do {
710                                        genEnd = results.size();
711
712                                        // iterate results
713                                        for ( std::size_t i = genStart; i < genEnd; ++i ) {
714                                                unsigned nextArg = results[i].nextArg;
715
716                                                // use remainder of exploded tuple if present
717                                                if ( results[i].hasExpl() ) {
718                                                        const ExplodedArg & expl = results[i].getExpl( args );
719
720                                                        unsigned nextExpl = results[i].nextExpl + 1;
721                                                        if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
722
723                                                        results.emplace_back(
724                                                                i, expl.exprs[ results[i].nextExpl ], copy( results[i].env ),
725                                                                copy( results[i].need ), copy( results[i].have ),
726                                                                copy( results[i].open ), nextArg, 0, Cost::zero, nextExpl,
727                                                                results[i].explAlt );
728
729                                                        continue;
730                                                }
731
732                                                // finish result when out of arguments
733                                                if ( nextArg >= args.size() ) {
734                                                        validateFunctionCandidate( func, results[i], results, out );
735
736                                                        continue;
737                                                }
738
739                                                // add each possible next argument
740                                                for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
741                                                        const ExplodedArg & expl = args[nextArg][j];
742
743                                                        // fresh copies of parent parameters for this iteration
744                                                        ast::TypeEnvironment env = results[i].env;
745                                                        ast::OpenVarSet open = results[i].open;
746
747                                                        env.addActual( expl.env, open );
748
749                                                        // skip empty tuple arguments by (nearly) cloning parent into next gen
750                                                        if ( expl.exprs.empty() ) {
751                                                                results.emplace_back(
752                                                                        results[i], move( env ), copy( results[i].need ),
753                                                                        copy( results[i].have ), move( open ), nextArg + 1,
754                                                                        expl.cost );
755
756                                                                continue;
757                                                        }
758
759                                                        // add new result
760                                                        results.emplace_back(
761                                                                i, expl.exprs.front(), move( env ), copy( results[i].need ),
762                                                                copy( results[i].have ), move( open ), nextArg + 1, 0, expl.cost,
763                                                                expl.exprs.size() == 1 ? 0 : 1, j );
764                                                }
765                                        }
766
767                                        genStart = genEnd;
768                                } while( genEnd != results.size() );
769                        } else {
770                                // filter out the results that don't use all the arguments
771                                for ( std::size_t i = genStart; i < results.size(); ++i ) {
772                                        ArgPack & result = results[i];
773                                        if ( ! result.hasExpl() && result.nextArg >= args.size() ) {
774                                                validateFunctionCandidate( func, result, results, out );
775                                        }
776                                }
777                        }
778                }
779
780                /// Adds implicit struct-conversions to the alternative list
781                void addAnonConversions( const CandidateRef & cand ) {
782                        // adds anonymous member interpretations whenever an aggregate value type is seen.
783                        // it's okay for the aggregate expression to have reference type -- cast it to the
784                        // base type to treat the aggregate as the referenced value
785                        ast::ptr< ast::Expr > aggrExpr( cand->expr );
786                        ast::ptr< ast::Type > & aggrType = aggrExpr.get_and_mutate()->result;
787                        cand->env.apply( aggrType );
788
789                        if ( aggrType.as< ast::ReferenceType >() ) {
790                                aggrExpr = new ast::CastExpr{ aggrExpr, aggrType->stripReferences() };
791                        }
792
793                        if ( auto structInst = aggrExpr->result.as< ast::StructInstType >() ) {
794                                addAggMembers( structInst, aggrExpr, *cand, Cost::safe, "" );
795                        } else if ( auto unionInst = aggrExpr->result.as< ast::UnionInstType >() ) {
796                                addAggMembers( unionInst, aggrExpr, *cand, Cost::safe, "" );
797                        }
798                }
799
800                /// Adds aggregate member interpretations
801                void addAggMembers(
802                        const ast::ReferenceToType * aggrInst, const ast::Expr * expr,
803                        const Candidate & cand, const Cost & addedCost, const std::string & name
804                ) {
805                        for ( const ast::Decl * decl : aggrInst->lookup( name ) ) {
806                                auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( decl );
807                                CandidateRef newCand = std::make_shared<Candidate>(
808                                        cand, new ast::MemberExpr{ expr->location, dwt, expr }, addedCost );
809                                // add anonymous member interpretations whenever an aggregate value type is seen
810                                // as a member expression
811                                addAnonConversions( newCand );
812                                candidates.emplace_back( move( newCand ) );
813                        }
814                }
815
816                /// Adds tuple member interpretations
817                void addTupleMembers(
818                        const ast::TupleType * tupleType, const ast::Expr * expr, const Candidate & cand,
819                        const Cost & addedCost, const ast::Expr * member
820                ) {
821                        if ( auto constantExpr = dynamic_cast< const ast::ConstantExpr * >( member ) ) {
822                                // get the value of the constant expression as an int, must be between 0 and the
823                                // length of the tuple to have meaning
824                                long long val = constantExpr->intValue();
825                                if ( val >= 0 && (unsigned long long)val < tupleType->size() ) {
826                                        addCandidate(
827                                                cand, new ast::TupleIndexExpr{ expr->location, expr, (unsigned)val },
828                                                addedCost );
829                                }
830                        }
831                }
832
833                void postvisit( const ast::UntypedExpr * untypedExpr ) {
834                        CandidateFinder funcFinder{ symtab, tenv };
835                        funcFinder.find( untypedExpr->func, ResolvMode::withAdjustment() );
836                        // short-circuit if no candidates
837                        if ( funcFinder.candidates.empty() ) return;
838
839                        std::vector< CandidateFinder > argCandidates =
840                                selfFinder.findSubExprs( untypedExpr->args );
841
842                        // take care of possible tuple assignments
843                        // if not tuple assignment, handled as normal function call
844                        Tuples::handleTupleAssignment( selfFinder, untypedExpr, argCandidates );
845
846                        // find function operators
847                        ast::ptr< ast::Expr > opExpr = new ast::NameExpr{ untypedExpr->location, "?()" };
848                        CandidateFinder opFinder{ symtab, tenv };
849                        // okay if there aren't any function operations
850                        opFinder.find( opExpr, ResolvMode::withoutFailFast() );
851                        PRINT(
852                                std::cerr << "known function ops:" << std::endl;
853                                print( std::cerr, opFinder.candidates, 1 );
854                        )
855
856                        // pre-explode arguments
857                        ExplodedArgs_new argExpansions;
858                        for ( const CandidateFinder & args : argCandidates ) {
859                                argExpansions.emplace_back();
860                                auto & argE = argExpansions.back();
861                                for ( const CandidateRef & arg : args ) { argE.emplace_back( *arg, symtab ); }
862                        }
863
864                        // Find function matches
865                        CandidateList found;
866                        SemanticErrorException errors;
867                        for ( CandidateRef & func : funcFinder ) {
868                                try {
869                                        PRINT(
870                                                std::cerr << "working on alternative:" << std::endl;
871                                                print( std::cerr, *func, 2 );
872                                        )
873
874                                        // check if the type is a pointer to function
875                                        const ast::Type * funcResult = func->expr->result->stripReferences();
876                                        if ( auto pointer = dynamic_cast< const ast::PointerType * >( funcResult ) ) {
877                                                if ( auto function = pointer->base.as< ast::FunctionType >() ) {
878                                                        CandidateRef newFunc{ new Candidate{ *func } };
879                                                        newFunc->expr =
880                                                                referenceToRvalueConversion( newFunc->expr, newFunc->cost );
881                                                        makeFunctionCandidates( newFunc, function, argExpansions, found );
882                                                }
883                                        } else if (
884                                                auto inst = dynamic_cast< const ast::TypeInstType * >( funcResult )
885                                        ) {
886                                                if ( const ast::EqvClass * clz = func->env.lookup( inst->name ) ) {
887                                                        if ( auto function = clz->bound.as< ast::FunctionType >() ) {
888                                                                CandidateRef newFunc{ new Candidate{ *func } };
889                                                                newFunc->expr =
890                                                                        referenceToRvalueConversion( newFunc->expr, newFunc->cost );
891                                                                makeFunctionCandidates( newFunc, function, argExpansions, found );
892                                                        }
893                                                }
894                                        }
895                                } catch ( SemanticErrorException & e ) { errors.append( e ); }
896                        }
897
898                        // Find matches on function operators `?()`
899                        if ( ! opFinder.candidates.empty() ) {
900                                // add exploded function alternatives to front of argument list
901                                std::vector< ExplodedArg > funcE;
902                                funcE.reserve( funcFinder.candidates.size() );
903                                for ( const CandidateRef & func : funcFinder ) {
904                                        funcE.emplace_back( *func, symtab );
905                                }
906                                argExpansions.emplace_front( move( funcE ) );
907
908                                for ( const CandidateRef & op : opFinder ) {
909                                        try {
910                                                // check if type is pointer-to-function
911                                                const ast::Type * opResult = op->expr->result->stripReferences();
912                                                if ( auto pointer = dynamic_cast< const ast::PointerType * >( opResult ) ) {
913                                                        if ( auto function = pointer->base.as< ast::FunctionType >() ) {
914                                                                CandidateRef newOp{ new Candidate{ *op} };
915                                                                newOp->expr =
916                                                                        referenceToRvalueConversion( newOp->expr, newOp->cost );
917                                                                makeFunctionCandidates( newOp, function, argExpansions, found );
918                                                        }
919                                                }
920                                        } catch ( SemanticErrorException & e ) { errors.append( e ); }
921                                }
922                        }
923
924                        // Implement SFINAE; resolution errors are only errors if there aren't any non-error
925                        // candidates
926                        if ( found.empty() && ! errors.isEmpty() ) { throw errors; }
927
928                        // Compute conversion costs
929                        for ( CandidateRef & withFunc : found ) {
930                                Cost cvtCost = computeApplicationConversionCost( withFunc, symtab );
931
932                                PRINT(
933                                        auto appExpr = withFunc->expr.strict_as< ast::ApplicationExpr >();
934                                        auto pointer = appExpr->func->result.strict_as< ast::PointerType >();
935                                        auto function = pointer->base.strict_as< ast::FunctionType >();
936
937                                        std::cerr << "Case +++++++++++++ " << appExpr->func << std::endl;
938                                        std::cerr << "parameters are:" << std::endl;
939                                        ast::printAll( std::cerr, function->params, 2 );
940                                        std::cerr << "arguments are:" << std::endl;
941                                        ast::printAll( std::cerr, appExpr->args, 2 );
942                                        std::cerr << "bindings are:" << std::endl;
943                                        ast::print( std::cerr, withFunc->env, 2 );
944                                        std::cerr << "cost is: " << withFunc->cost << std::endl;
945                                        std::cerr << "cost of conversion is:" << cvtCost << std::endl;
946                                )
947
948                                if ( cvtCost != Cost::infinity ) {
949                                        withFunc->cvtCost = cvtCost;
950                                        candidates.emplace_back( move( withFunc ) );
951                                }
952                        }
953                        found = move( candidates );
954
955                        // use a new list so that candidates are not examined by addAnonConversions twice
956                        CandidateList winners = findMinCost( found );
957                        promoteCvtCost( winners );
958
959                        // function may return a struct/union value, in which case we need to add candidates
960                        // for implicit conversions to each of the anonymous members, which must happen after
961                        // `findMinCost`, since anon conversions are never the cheapest
962                        for ( const CandidateRef & c : winners ) {
963                                addAnonConversions( c );
964                        }
965                        spliceBegin( candidates, winners );
966
967                        if ( candidates.empty() && targetType && ! targetType->isVoid() ) {
968                                // If resolution is unsuccessful with a target type, try again without, since it
969                                // will sometimes succeed when it wouldn't with a target type binding.
970                                // For example:
971                                //   forall( otype T ) T & ?[]( T *, ptrdiff_t );
972                                //   const char * x = "hello world";
973                                //   unsigned char ch = x[0];
974                                // Fails with simple return type binding (xxx -- check this!) as follows:
975                                // * T is bound to unsigned char
976                                // * (x: const char *) is unified with unsigned char *, which fails
977                                // xxx -- fix this better
978                                targetType = nullptr;
979                                postvisit( untypedExpr );
980                        }
981                }
982
983                /// true if expression is an lvalue
984                static bool isLvalue( const ast::Expr * x ) {
985                        return x->result && ( x->get_lvalue() || x->result.as< ast::ReferenceType >() );
986                }
987
988                void postvisit( const ast::AddressExpr * addressExpr ) {
989                        CandidateFinder finder{ symtab, tenv };
990                        finder.find( addressExpr->arg );
991                        for ( CandidateRef & r : finder.candidates ) {
992                                if ( ! isLvalue( r->expr ) ) continue;
993                                addCandidate( *r, new ast::AddressExpr{ addressExpr->location, r->expr } );
994                        }
995                }
996
997                void postvisit( const ast::LabelAddressExpr * labelExpr ) {
998                        addCandidate( labelExpr, tenv );
999                }
1000
1001                void postvisit( const ast::CastExpr * castExpr ) {
1002                        ast::ptr< ast::Type > toType = castExpr->result;
1003                        assert( toType );
1004                        toType = resolveTypeof( toType, symtab );
1005                        toType = SymTab::validateType( castExpr->location, toType, symtab );
1006                        toType = adjustExprType( toType, tenv, symtab );
1007
1008                        CandidateFinder finder{ symtab, tenv, toType };
1009                        finder.find( castExpr->arg, ResolvMode::withAdjustment() );
1010
1011                        CandidateList matches;
1012                        for ( CandidateRef & cand : finder.candidates ) {
1013                                ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have;
1014                                ast::OpenVarSet open( cand->open );
1015
1016                                cand->env.extractOpenVars( open );
1017
1018                                // It is possible that a cast can throw away some values in a multiply-valued
1019                                // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of the
1020                                // subexpression results that are cast directly. The candidate is invalid if it
1021                                // has fewer results than there are types to cast to.
1022                                int discardedValues = cand->expr->result->size() - toType->size();
1023                                if ( discardedValues < 0 ) continue;
1024
1025                                // unification run for side-effects
1026                                unify( toType, cand->expr->result, cand->env, need, have, open, symtab );
1027                                Cost thisCost = castCost( cand->expr->result, toType, cand->expr->get_lvalue(),
1028                                                symtab, cand->env );
1029                                PRINT(
1030                                        std::cerr << "working on cast with result: " << toType << std::endl;
1031                                        std::cerr << "and expr type: " << cand->expr->result << std::endl;
1032                                        std::cerr << "env: " << cand->env << std::endl;
1033                                )
1034                                if ( thisCost != Cost::infinity ) {
1035                                        PRINT(
1036                                                std::cerr << "has finite cost." << std::endl;
1037                                        )
1038                                        // count one safe conversion for each value that is thrown away
1039                                        thisCost.incSafe( discardedValues );
1040                                        CandidateRef newCand = std::make_shared<Candidate>(
1041                                                restructureCast( cand->expr, toType, castExpr->isGenerated ),
1042                                                copy( cand->env ), move( open ), move( need ), cand->cost,
1043                                                cand->cost + thisCost );
1044                                        inferParameters( newCand, matches );
1045                                }
1046                        }
1047
1048                        // select first on argument cost, then conversion cost
1049                        CandidateList minArgCost = findMinCost( matches );
1050                        promoteCvtCost( minArgCost );
1051                        candidates = findMinCost( minArgCost );
1052                }
1053
1054                void postvisit( const ast::VirtualCastExpr * castExpr ) {
1055                        assertf( castExpr->result, "Implicit virtual cast targets not yet supported." );
1056                        CandidateFinder finder{ symtab, tenv };
1057                        // don't prune here, all alternatives guaranteed to have same type
1058                        finder.find( castExpr->arg, ResolvMode::withoutPrune() );
1059                        for ( CandidateRef & r : finder.candidates ) {
1060                                addCandidate(
1061                                        *r,
1062                                        new ast::VirtualCastExpr{ castExpr->location, r->expr, castExpr->result } );
1063                        }
1064                }
1065
1066                void postvisit( const ast::UntypedMemberExpr * memberExpr ) {
1067                        CandidateFinder aggFinder{ symtab, tenv };
1068                        aggFinder.find( memberExpr->aggregate, ResolvMode::withAdjustment() );
1069                        for ( CandidateRef & agg : aggFinder.candidates ) {
1070                                // it's okay for the aggregate expression to have reference type -- cast it to the
1071                                // base type to treat the aggregate as the referenced value
1072                                Cost addedCost = Cost::zero;
1073                                agg->expr = referenceToRvalueConversion( agg->expr, addedCost );
1074
1075                                // find member of the given type
1076                                if ( auto structInst = agg->expr->result.as< ast::StructInstType >() ) {
1077                                        addAggMembers(
1078                                                structInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) );
1079                                } else if ( auto unionInst = agg->expr->result.as< ast::UnionInstType >() ) {
1080                                        addAggMembers(
1081                                                unionInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) );
1082                                } else if ( auto tupleType = agg->expr->result.as< ast::TupleType >() ) {
1083                                        addTupleMembers( tupleType, agg->expr, *agg, addedCost, memberExpr->member );
1084                                }
1085                        }
1086                }
1087
1088                void postvisit( const ast::MemberExpr * memberExpr ) {
1089                        addCandidate( memberExpr, tenv );
1090                }
1091
1092                void postvisit( const ast::NameExpr * nameExpr ) {
1093                        std::vector< ast::SymbolTable::IdData > declList = symtab.lookupId( nameExpr->name );
1094                        PRINT( std::cerr << "nameExpr is " << nameExpr->name << std::endl; )
1095                        for ( auto & data : declList ) {
1096                                Cost cost = Cost::zero;
1097                                ast::Expr * newExpr = data.combine( nameExpr->location, cost );
1098
1099                                CandidateRef newCand = std::make_shared<Candidate>(
1100                                        newExpr, copy( tenv ), ast::OpenVarSet{}, ast::AssertionSet{}, Cost::zero,
1101                                        cost );
1102                                PRINT(
1103                                        std::cerr << "decl is ";
1104                                        ast::print( std::cerr, data.id );
1105                                        std::cerr << std::endl;
1106                                        std::cerr << "newExpr is ";
1107                                        ast::print( std::cerr, newExpr );
1108                                        std::cerr << std::endl;
1109                                )
1110                                newCand->expr = ast::mutate_field(
1111                                        newCand->expr.get(), &ast::Expr::result,
1112                                        renameTyVars( newCand->expr->result ) );
1113                                // add anonymous member interpretations whenever an aggregate value type is seen
1114                                // as a name expression
1115                                addAnonConversions( newCand );
1116                                candidates.emplace_back( move( newCand ) );
1117                        }
1118                }
1119
1120                void postvisit( const ast::VariableExpr * variableExpr ) {
1121                        // not sufficient to just pass `variableExpr` here, type might have changed since
1122                        // creation
1123                        addCandidate(
1124                                new ast::VariableExpr{ variableExpr->location, variableExpr->var }, tenv );
1125                }
1126
1127                void postvisit( const ast::ConstantExpr * constantExpr ) {
1128                        addCandidate( constantExpr, tenv );
1129                }
1130
1131                void postvisit( const ast::SizeofExpr * sizeofExpr ) {
1132                        if ( sizeofExpr->type ) {
1133                                addCandidate(
1134                                        new ast::SizeofExpr{
1135                                                sizeofExpr->location, resolveTypeof( sizeofExpr->type, symtab ) },
1136                                        tenv );
1137                        } else {
1138                                // find all candidates for the argument to sizeof
1139                                CandidateFinder finder{ symtab, tenv };
1140                                finder.find( sizeofExpr->expr );
1141                                // find the lowest-cost candidate, otherwise ambiguous
1142                                CandidateList winners = findMinCost( finder.candidates );
1143                                if ( winners.size() != 1 ) {
1144                                        SemanticError(
1145                                                sizeofExpr->expr.get(), "Ambiguous expression in sizeof operand: " );
1146                                }
1147                                // return the lowest-cost candidate
1148                                CandidateRef & choice = winners.front();
1149                                choice->expr = referenceToRvalueConversion( choice->expr, choice->cost );
1150                                choice->cost = Cost::zero;
1151                                addCandidate( *choice, new ast::SizeofExpr{ sizeofExpr->location, choice->expr } );
1152                        }
1153                }
1154
1155                void postvisit( const ast::AlignofExpr * alignofExpr ) {
1156                        if ( alignofExpr->type ) {
1157                                addCandidate(
1158                                        new ast::AlignofExpr{
1159                                                alignofExpr->location, resolveTypeof( alignofExpr->type, symtab ) },
1160                                        tenv );
1161                        } else {
1162                                // find all candidates for the argument to alignof
1163                                CandidateFinder finder{ symtab, tenv };
1164                                finder.find( alignofExpr->expr );
1165                                // find the lowest-cost candidate, otherwise ambiguous
1166                                CandidateList winners = findMinCost( finder.candidates );
1167                                if ( winners.size() != 1 ) {
1168                                        SemanticError(
1169                                                alignofExpr->expr.get(), "Ambiguous expression in alignof operand: " );
1170                                }
1171                                // return the lowest-cost candidate
1172                                CandidateRef & choice = winners.front();
1173                                choice->expr = referenceToRvalueConversion( choice->expr, choice->cost );
1174                                choice->cost = Cost::zero;
1175                                addCandidate(
1176                                        *choice, new ast::AlignofExpr{ alignofExpr->location, choice->expr } );
1177                        }
1178                }
1179
1180                void postvisit( const ast::UntypedOffsetofExpr * offsetofExpr ) {
1181                        const ast::ReferenceToType * aggInst;
1182                        if (( aggInst = offsetofExpr->type.as< ast::StructInstType >() )) ;
1183                        else if (( aggInst = offsetofExpr->type.as< ast::UnionInstType >() )) ;
1184                        else return;
1185
1186                        for ( const ast::Decl * member : aggInst->lookup( offsetofExpr->member ) ) {
1187                                auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( member );
1188                                addCandidate(
1189                                        new ast::OffsetofExpr{ offsetofExpr->location, aggInst, dwt }, tenv );
1190                        }
1191                }
1192
1193                void postvisit( const ast::OffsetofExpr * offsetofExpr ) {
1194                        addCandidate( offsetofExpr, tenv );
1195                }
1196
1197                void postvisit( const ast::OffsetPackExpr * offsetPackExpr ) {
1198                        addCandidate( offsetPackExpr, tenv );
1199                }
1200
1201                void postvisit( const ast::LogicalExpr * logicalExpr ) {
1202                        CandidateFinder finder1{ symtab, tenv };
1203                        finder1.find( logicalExpr->arg1, ResolvMode::withAdjustment() );
1204                        if ( finder1.candidates.empty() ) return;
1205
1206                        CandidateFinder finder2{ symtab, tenv };
1207                        finder2.find( logicalExpr->arg2, ResolvMode::withAdjustment() );
1208                        if ( finder2.candidates.empty() ) return;
1209
1210                        for ( const CandidateRef & r1 : finder1.candidates ) {
1211                                for ( const CandidateRef & r2 : finder2.candidates ) {
1212                                        ast::TypeEnvironment env{ r1->env };
1213                                        env.simpleCombine( r2->env );
1214                                        ast::OpenVarSet open{ r1->open };
1215                                        mergeOpenVars( open, r2->open );
1216                                        ast::AssertionSet need;
1217                                        mergeAssertionSet( need, r1->need );
1218                                        mergeAssertionSet( need, r2->need );
1219
1220                                        addCandidate(
1221                                                new ast::LogicalExpr{
1222                                                        logicalExpr->location, r1->expr, r2->expr, logicalExpr->isAnd },
1223                                                move( env ), move( open ), move( need ), r1->cost + r2->cost );
1224                                }
1225                        }
1226                }
1227
1228                void postvisit( const ast::ConditionalExpr * conditionalExpr ) {
1229                        // candidates for condition
1230                        CandidateFinder finder1{ symtab, tenv };
1231                        finder1.find( conditionalExpr->arg1, ResolvMode::withAdjustment() );
1232                        if ( finder1.candidates.empty() ) return;
1233
1234                        // candidates for true result
1235                        CandidateFinder finder2{ symtab, tenv };
1236                        finder2.find( conditionalExpr->arg2, ResolvMode::withAdjustment() );
1237                        if ( finder2.candidates.empty() ) return;
1238
1239                        // candidates for false result
1240                        CandidateFinder finder3{ symtab, tenv };
1241                        finder3.find( conditionalExpr->arg3, ResolvMode::withAdjustment() );
1242                        if ( finder3.candidates.empty() ) return;
1243
1244                        for ( const CandidateRef & r1 : finder1.candidates ) {
1245                                for ( const CandidateRef & r2 : finder2.candidates ) {
1246                                        for ( const CandidateRef & r3 : finder3.candidates ) {
1247                                                ast::TypeEnvironment env{ r1->env };
1248                                                env.simpleCombine( r2->env );
1249                                                env.simpleCombine( r3->env );
1250                                                ast::OpenVarSet open{ r1->open };
1251                                                mergeOpenVars( open, r2->open );
1252                                                mergeOpenVars( open, r3->open );
1253                                                ast::AssertionSet need;
1254                                                mergeAssertionSet( need, r1->need );
1255                                                mergeAssertionSet( need, r2->need );
1256                                                mergeAssertionSet( need, r3->need );
1257                                                ast::AssertionSet have;
1258
1259                                                // unify true and false results, then infer parameters to produce new
1260                                                // candidates
1261                                                ast::ptr< ast::Type > common;
1262                                                if (
1263                                                        unify(
1264                                                                r2->expr->result, r3->expr->result, env, need, have, open, symtab,
1265                                                                common )
1266                                                ) {
1267                                                        // generate typed expression
1268                                                        ast::ConditionalExpr * newExpr = new ast::ConditionalExpr{
1269                                                                conditionalExpr->location, r1->expr, r2->expr, r3->expr };
1270                                                        newExpr->result = common ? common : r2->expr->result;
1271                                                        // convert both options to result type
1272                                                        Cost cost = r1->cost + r2->cost + r3->cost;
1273                                                        newExpr->arg2 = computeExpressionConversionCost(
1274                                                                newExpr->arg2, newExpr->result, symtab, env, cost );
1275                                                        newExpr->arg3 = computeExpressionConversionCost(
1276                                                                newExpr->arg3, newExpr->result, symtab, env, cost );
1277                                                        // output candidate
1278                                                        CandidateRef newCand = std::make_shared<Candidate>(
1279                                                                newExpr, move( env ), move( open ), move( need ), cost );
1280                                                        inferParameters( newCand, candidates );
1281                                                }
1282                                        }
1283                                }
1284                        }
1285                }
1286
1287                void postvisit( const ast::CommaExpr * commaExpr ) {
1288                        ast::TypeEnvironment env{ tenv };
1289                        ast::ptr< ast::Expr > arg1 = resolveInVoidContext( commaExpr->arg1, symtab, env );
1290
1291                        CandidateFinder finder2{ symtab, env };
1292                        finder2.find( commaExpr->arg2, ResolvMode::withAdjustment() );
1293
1294                        for ( const CandidateRef & r2 : finder2.candidates ) {
1295                                addCandidate( *r2, new ast::CommaExpr{ commaExpr->location, arg1, r2->expr } );
1296                        }
1297                }
1298
1299                void postvisit( const ast::ImplicitCopyCtorExpr * ctorExpr ) {
1300                        addCandidate( ctorExpr, tenv );
1301                }
1302
1303                void postvisit( const ast::ConstructorExpr * ctorExpr ) {
1304                        CandidateFinder finder{ symtab, tenv };
1305                        finder.find( ctorExpr->callExpr, ResolvMode::withoutPrune() );
1306                        for ( CandidateRef & r : finder.candidates ) {
1307                                addCandidate( *r, new ast::ConstructorExpr{ ctorExpr->location, r->expr } );
1308                        }
1309                }
1310
1311                void postvisit( const ast::RangeExpr * rangeExpr ) {
1312                        // resolve low and high, accept candidates where low and high types unify
1313                        CandidateFinder finder1{ symtab, tenv };
1314                        finder1.find( rangeExpr->low, ResolvMode::withAdjustment() );
1315                        if ( finder1.candidates.empty() ) return;
1316
1317                        CandidateFinder finder2{ symtab, tenv };
1318                        finder2.find( rangeExpr->high, ResolvMode::withAdjustment() );
1319                        if ( finder2.candidates.empty() ) return;
1320
1321                        for ( const CandidateRef & r1 : finder1.candidates ) {
1322                                for ( const CandidateRef & r2 : finder2.candidates ) {
1323                                        ast::TypeEnvironment env{ r1->env };
1324                                        env.simpleCombine( r2->env );
1325                                        ast::OpenVarSet open{ r1->open };
1326                                        mergeOpenVars( open, r2->open );
1327                                        ast::AssertionSet need;
1328                                        mergeAssertionSet( need, r1->need );
1329                                        mergeAssertionSet( need, r2->need );
1330                                        ast::AssertionSet have;
1331
1332                                        ast::ptr< ast::Type > common;
1333                                        if (
1334                                                unify(
1335                                                        r1->expr->result, r2->expr->result, env, need, have, open, symtab,
1336                                                        common )
1337                                        ) {
1338                                                // generate new expression
1339                                                ast::RangeExpr * newExpr =
1340                                                        new ast::RangeExpr{ rangeExpr->location, r1->expr, r2->expr };
1341                                                newExpr->result = common ? common : r1->expr->result;
1342                                                // add candidate
1343                                                CandidateRef newCand = std::make_shared<Candidate>(
1344                                                        newExpr, move( env ), move( open ), move( need ),
1345                                                        r1->cost + r2->cost );
1346                                                inferParameters( newCand, candidates );
1347                                        }
1348                                }
1349                        }
1350                }
1351
1352                void postvisit( const ast::UntypedTupleExpr * tupleExpr ) {
1353                        std::vector< CandidateFinder > subCandidates =
1354                                selfFinder.findSubExprs( tupleExpr->exprs );
1355                        std::vector< CandidateList > possibilities;
1356                        combos( subCandidates.begin(), subCandidates.end(), back_inserter( possibilities ) );
1357
1358                        for ( const CandidateList & subs : possibilities ) {
1359                                std::vector< ast::ptr< ast::Expr > > exprs;
1360                                exprs.reserve( subs.size() );
1361                                for ( const CandidateRef & sub : subs ) { exprs.emplace_back( sub->expr ); }
1362
1363                                ast::TypeEnvironment env;
1364                                ast::OpenVarSet open;
1365                                ast::AssertionSet need;
1366                                for ( const CandidateRef & sub : subs ) {
1367                                        env.simpleCombine( sub->env );
1368                                        mergeOpenVars( open, sub->open );
1369                                        mergeAssertionSet( need, sub->need );
1370                                }
1371
1372                                addCandidate(
1373                                        new ast::TupleExpr{ tupleExpr->location, move( exprs ) },
1374                                        move( env ), move( open ), move( need ), sumCost( subs ) );
1375                        }
1376                }
1377
1378                void postvisit( const ast::TupleExpr * tupleExpr ) {
1379                        addCandidate( tupleExpr, tenv );
1380                }
1381
1382                void postvisit( const ast::TupleIndexExpr * tupleExpr ) {
1383                        addCandidate( tupleExpr, tenv );
1384                }
1385
1386                void postvisit( const ast::TupleAssignExpr * tupleExpr ) {
1387                        addCandidate( tupleExpr, tenv );
1388                }
1389
1390                void postvisit( const ast::UniqueExpr * unqExpr ) {
1391                        CandidateFinder finder{ symtab, tenv };
1392                        finder.find( unqExpr->expr, ResolvMode::withAdjustment() );
1393                        for ( CandidateRef & r : finder.candidates ) {
1394                                // ensure that the the id is passed on so that the expressions are "linked"
1395                                addCandidate( *r, new ast::UniqueExpr{ unqExpr->location, r->expr, unqExpr->id } );
1396                        }
1397                }
1398
1399                void postvisit( const ast::StmtExpr * stmtExpr ) {
1400                        addCandidate( resolveStmtExpr( stmtExpr, symtab ), tenv );
1401                }
1402
1403                void postvisit( const ast::UntypedInitExpr * initExpr ) {
1404                        // handle each option like a cast
1405                        CandidateList matches;
1406                        PRINT(
1407                                std::cerr << "untyped init expr: " << initExpr << std::endl;
1408                        )
1409                        // O(n^2) checks of d-types with e-types
1410                        for ( const ast::InitAlternative & initAlt : initExpr->initAlts ) {
1411                                // calculate target type
1412                                const ast::Type * toType = resolveTypeof( initAlt.type, symtab );
1413                                toType = SymTab::validateType( initExpr->location, toType, symtab );
1414                                toType = adjustExprType( toType, tenv, symtab );
1415                                // The call to find must occur inside this loop, otherwise polymorphic return
1416                                // types are not bound to the initialization type, since return type variables are
1417                                // only open for the duration of resolving the UntypedExpr.
1418                                CandidateFinder finder{ symtab, tenv, toType };
1419                                finder.find( initExpr->expr, ResolvMode::withAdjustment() );
1420                                for ( CandidateRef & cand : finder.candidates ) {
1421                                        ast::TypeEnvironment env{ cand->env };
1422                                        ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have;
1423                                        ast::OpenVarSet open{ cand->open };
1424
1425                                        PRINT(
1426                                                std::cerr << "  @ " << toType << " " << initAlt.designation << std::endl;
1427                                        )
1428
1429                                        // It is possible that a cast can throw away some values in a multiply-valued
1430                                        // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of
1431                                        // the subexpression results that are cast directly. The candidate is invalid
1432                                        // if it has fewer results than there are types to cast to.
1433                                        int discardedValues = cand->expr->result->size() - toType->size();
1434                                        if ( discardedValues < 0 ) continue;
1435
1436                                        // unification run for side-effects
1437                                        unify( toType, cand->expr->result, env, need, have, open, symtab );
1438                                        Cost thisCost = castCost( cand->expr->result, toType, cand->expr->get_lvalue(),
1439                                                        symtab, env );
1440
1441                                        if ( thisCost != Cost::infinity ) {
1442                                                // count one safe conversion for each value that is thrown away
1443                                                thisCost.incSafe( discardedValues );
1444                                                CandidateRef newCand = std::make_shared<Candidate>(
1445                                                        new ast::InitExpr{
1446                                                                initExpr->location, restructureCast( cand->expr, toType ),
1447                                                                initAlt.designation },
1448                                                        copy( cand->env ), move( open ), move( need ), cand->cost, thisCost );
1449                                                inferParameters( newCand, matches );
1450                                        }
1451                                }
1452                        }
1453
1454                        // select first on argument cost, then conversion cost
1455                        CandidateList minArgCost = findMinCost( matches );
1456                        promoteCvtCost( minArgCost );
1457                        candidates = findMinCost( minArgCost );
1458                }
1459
1460                void postvisit( const ast::InitExpr * ) {
1461                        assertf( false, "CandidateFinder should never see a resolved InitExpr." );
1462                }
1463
1464                void postvisit( const ast::DeletedExpr * ) {
1465                        assertf( false, "CandidateFinder should never see a DeletedExpr." );
1466                }
1467
1468                void postvisit( const ast::GenericExpr * ) {
1469                        assertf( false, "_Generic is not yet supported." );
1470                }
1471        };
1472
1473        /// Prunes a list of candidates down to those that have the minimum conversion cost for a given
1474        /// return type. Skips ambiguous candidates.
1475        CandidateList pruneCandidates( CandidateList & candidates ) {
1476                struct PruneStruct {
1477                        CandidateRef candidate;
1478                        bool ambiguous;
1479
1480                        PruneStruct() = default;
1481                        PruneStruct( const CandidateRef & c ) : candidate( c ), ambiguous( false ) {}
1482                };
1483
1484                // find lowest-cost candidate for each type
1485                std::unordered_map< std::string, PruneStruct > selected;
1486                for ( CandidateRef & candidate : candidates ) {
1487                        std::string mangleName;
1488                        {
1489                                ast::ptr< ast::Type > newType = candidate->expr->result;
1490                                assertf(candidate->expr->result, "Result of expression %p for candidate is null", candidate->expr.get());
1491                                candidate->env.apply( newType );
1492                                mangleName = Mangle::mangle( newType );
1493                        }
1494
1495                        auto found = selected.find( mangleName );
1496                        if ( found != selected.end() ) {
1497                                if ( candidate->cost < found->second.candidate->cost ) {
1498                                        PRINT(
1499                                                std::cerr << "cost " << candidate->cost << " beats "
1500                                                        << found->second.candidate->cost << std::endl;
1501                                        )
1502
1503                                        found->second = PruneStruct{ candidate };
1504                                } else if ( candidate->cost == found->second.candidate->cost ) {
1505                                        // if one of the candidates contains a deleted identifier, can pick the other,
1506                                        // since deleted expressions should not be ambiguous if there is another option
1507                                        // that is at least as good
1508                                        if ( findDeletedExpr( candidate->expr ) ) {
1509                                                // do nothing
1510                                                PRINT( std::cerr << "candidate is deleted" << std::endl; )
1511                                        } else if ( findDeletedExpr( found->second.candidate->expr ) ) {
1512                                                PRINT( std::cerr << "current is deleted" << std::endl; )
1513                                                found->second = PruneStruct{ candidate };
1514                                        } else {
1515                                                PRINT( std::cerr << "marking ambiguous" << std::endl; )
1516                                                found->second.ambiguous = true;
1517                                        }
1518                                } else {
1519                                        PRINT(
1520                                                std::cerr << "cost " << candidate->cost << " loses to "
1521                                                        << found->second.candidate->cost << std::endl;
1522                                        )
1523                                }
1524                        } else {
1525                                selected.emplace_hint( found, mangleName, candidate );
1526                        }
1527                }
1528
1529                // report unambiguous min-cost candidates
1530                CandidateList out;
1531                for ( auto & target : selected ) {
1532                        if ( target.second.ambiguous ) continue;
1533
1534                        CandidateRef cand = target.second.candidate;
1535
1536                        ast::ptr< ast::Type > newResult = cand->expr->result;
1537                        cand->env.applyFree( newResult );
1538                        cand->expr = ast::mutate_field(
1539                                cand->expr.get(), &ast::Expr::result, move( newResult ) );
1540
1541                        out.emplace_back( cand );
1542                }
1543                return out;
1544        }
1545
1546} // anonymous namespace
1547
1548void CandidateFinder::find( const ast::Expr * expr, ResolvMode mode ) {
1549        // Find alternatives for expression
1550        ast::Pass<Finder> finder{ *this };
1551        expr->accept( finder );
1552
1553        if ( mode.failFast && candidates.empty() ) {
1554                SemanticError( expr, "No reasonable alternatives for expression " );
1555        }
1556
1557        if ( mode.satisfyAssns || mode.prune ) {
1558                // trim candidates to just those where the assertions are satisfiable
1559                // - necessary pre-requisite to pruning
1560                CandidateList satisfied;
1561                std::vector< std::string > errors;
1562                for ( CandidateRef & candidate : candidates ) {
1563                        satisfyAssertions( candidate, localSyms, satisfied, errors );
1564                }
1565
1566                // fail early if none such
1567                if ( mode.failFast && satisfied.empty() ) {
1568                        std::ostringstream stream;
1569                        stream << "No alternatives with satisfiable assertions for " << expr << "\n";
1570                        for ( const auto& err : errors ) {
1571                                stream << err;
1572                        }
1573                        SemanticError( expr->location, stream.str() );
1574                }
1575
1576                // reset candidates
1577                candidates = move( satisfied );
1578        }
1579
1580        if ( mode.prune ) {
1581                // trim candidates to single best one
1582                PRINT(
1583                        std::cerr << "alternatives before prune:" << std::endl;
1584                        print( std::cerr, candidates );
1585                )
1586
1587                CandidateList pruned = pruneCandidates( candidates );
1588
1589                if ( mode.failFast && pruned.empty() ) {
1590                        std::ostringstream stream;
1591                        CandidateList winners = findMinCost( candidates );
1592                        stream << "Cannot choose between " << winners.size() << " alternatives for "
1593                                "expression\n";
1594                        ast::print( stream, expr );
1595                        stream << " Alternatives are:\n";
1596                        print( stream, winners, 1 );
1597                        SemanticError( expr->location, stream.str() );
1598                }
1599
1600                auto oldsize = candidates.size();
1601                candidates = move( pruned );
1602
1603                PRINT(
1604                        std::cerr << "there are " << oldsize << " alternatives before elimination" << std::endl;
1605                )
1606                PRINT(
1607                        std::cerr << "there are " << candidates.size() << " alternatives after elimination"
1608                                << std::endl;
1609                )
1610        }
1611
1612        // adjust types after pruning so that types substituted by pruneAlternatives are correctly
1613        // adjusted
1614        if ( mode.adjust ) {
1615                for ( CandidateRef & r : candidates ) {
1616                        r->expr = ast::mutate_field(
1617                                r->expr.get(), &ast::Expr::result,
1618                                adjustExprType( r->expr->result, r->env, localSyms ) );
1619                }
1620        }
1621
1622        // Central location to handle gcc extension keyword, etc. for all expressions
1623        for ( CandidateRef & r : candidates ) {
1624                if ( r->expr->extension != expr->extension ) {
1625                        r->expr.get_and_mutate()->extension = expr->extension;
1626                }
1627        }
1628}
1629
1630std::vector< CandidateFinder > CandidateFinder::findSubExprs(
1631        const std::vector< ast::ptr< ast::Expr > > & xs
1632) {
1633        std::vector< CandidateFinder > out;
1634
1635        for ( const auto & x : xs ) {
1636                out.emplace_back( localSyms, env );
1637                out.back().find( x, ResolvMode::withAdjustment() );
1638
1639                PRINT(
1640                        std::cerr << "findSubExprs" << std::endl;
1641                        print( std::cerr, out.back().candidates );
1642                )
1643        }
1644
1645        return out;
1646}
1647
1648} // namespace ResolvExpr
1649
1650// Local Variables: //
1651// tab-width: 4 //
1652// mode: c++ //
1653// compile-command: "make install" //
1654// End: //
Note: See TracBrowser for help on using the repository browser.