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