source: src/ResolvExpr/CandidateFinder.cpp @ e0e9a0b

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

Somewhat deeper clone for types with forall qualifiers.

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