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