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