source: src/ResolvExpr/CandidateFinder.cpp @ 99da267

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 99da267 was 417117e, checked in by Aaron Moss <a3moss@…>, 5 years ago

Assorted cleanup

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