source: src/ResolvExpr/Resolver.cc@ d40555e

ADT ast-experimental
Last change on this file since d40555e was 8f06277, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Some clean-up in Common/utility.h. Deleted some unused declarations and moved others to one of two new headers.

  • Property mode set to 100644
File size: 77.6 KB
RevLine 
[a32b204]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//
[71f4e4f]7// Resolver.cc --
[a32b204]8//
[d76c588]9// Author : Aaron B. Moss
[a32b204]10// Created On : Sun May 17 12:17:01 2015
[39d8950]11// Last Modified By : Andrew Beach
[f6e6a55]12// Last Modified On : Wed Apr 20 10:41:00 2022
13// Update Count : 248
[a32b204]14//
15
[e3e16bc]16#include <cassert> // for strict_dynamic_cast, assert
[ea6332d]17#include <memory> // for allocator, allocator_traits<...
18#include <tuple> // for get
[6d6e829]19#include <vector> // for vector
[ea6332d]20
21#include "Alternative.h" // for Alternative, AltList
22#include "AlternativeFinder.h" // for AlternativeFinder, resolveIn...
[99d4584]23#include "Candidate.hpp"
24#include "CandidateFinder.hpp"
[d76c588]25#include "CurrentObject.h" // for CurrentObject
26#include "RenameVars.h" // for RenameVars, global_renamer
27#include "Resolver.h"
[16ba4a6f]28#include "ResolveTypeof.h"
[d76c588]29#include "ResolvMode.h" // for ResolvMode
30#include "typeops.h" // for extractResultType
31#include "Unify.h" // for unify
[16ba4a6f]32#include "CompilationState.h"
[4864a73]33#include "AST/Chain.hpp"
[2a8f0c1]34#include "AST/Decl.hpp"
35#include "AST/Init.hpp"
[d76c588]36#include "AST/Pass.hpp"
[99d4584]37#include "AST/Print.hpp"
[d76c588]38#include "AST/SymbolTable.hpp"
[2773ab8]39#include "AST/Type.hpp"
[8f06277]40#include "Common/Eval.h" // for eval
[a4ca48c]41#include "Common/PassVisitor.h" // for PassVisitor
[ea6332d]42#include "Common/SemanticError.h" // for SemanticError
[57e0289]43#include "Common/Stats/ResolveTime.h" // for ResolveTime::start(), ResolveTime::stop()
[ea6332d]44#include "Common/utility.h" // for ValueGuard, group_iterate
[0a60c04]45#include "InitTweak/GenInit.h"
[ea6332d]46#include "InitTweak/InitTweak.h" // for isIntrinsicSingleArgCallStmt
47#include "ResolvExpr/TypeEnvironment.h" // for TypeEnvironment
48#include "SymTab/Autogen.h" // for SizeType
49#include "SymTab/Indexer.h" // for Indexer
[16ba4a6f]50#include "SymTab/Mangler.h" // for Mangler
[ea6332d]51#include "SynTree/Declaration.h" // for ObjectDecl, TypeDecl, Declar...
52#include "SynTree/Expression.h" // for Expression, CastExpr, InitExpr
53#include "SynTree/Initializer.h" // for ConstructorInit, SingleInit
54#include "SynTree/Statement.h" // for ForStmt, Statement, BranchStmt
55#include "SynTree/Type.h" // for Type, BasicType, PointerType
56#include "SynTree/TypeSubstitution.h" // for TypeSubstitution
57#include "SynTree/Visitor.h" // for acceptAll, maybeAccept
[0a60c04]58#include "Tuples/Tuples.h"
[2bfc6b2]59#include "Validate/FindSpecialDecls.h" // for SizeType
[51b73452]60
[d9a0e76]61using namespace std;
[51b73452]62
[d9a0e76]63namespace ResolvExpr {
[d76c588]64 struct Resolver_old final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver_old>, public WithShortCircuiting, public WithStmtsToAdd {
65 Resolver_old() {}
66 Resolver_old( const SymTab::Indexer & other ) {
[a4ca48c]67 indexer = other;
[1d2b64f]68 }
[71f4e4f]69
[5170d95]70 void previsit( FunctionDecl * functionDecl );
71 void postvisit( FunctionDecl * functionDecl );
72 void previsit( ObjectDecl * objectDecll );
[a4ca48c]73 void previsit( EnumDecl * enumDecl );
[bd87b138]74 void previsit( StaticAssertDecl * assertDecl );
[a4ca48c]75
76 void previsit( ArrayType * at );
77 void previsit( PointerType * at );
78
[5170d95]79 void previsit( ExprStmt * exprStmt );
80 void previsit( AsmExpr * asmExpr );
81 void previsit( AsmStmt * asmStmt );
82 void previsit( IfStmt * ifStmt );
[3b0bc16]83 void previsit( WhileDoStmt * whileDoStmt );
[5170d95]84 void previsit( ForStmt * forStmt );
85 void previsit( SwitchStmt * switchStmt );
86 void previsit( CaseStmt * caseStmt );
87 void previsit( BranchStmt * branchStmt );
88 void previsit( ReturnStmt * returnStmt );
89 void previsit( ThrowStmt * throwStmt );
90 void previsit( CatchStmt * catchStmt );
[3b9c674]91 void postvisit( CatchStmt * catchStmt );
[695e00d]92 void previsit( WaitForStmt * stmt );
[a4ca48c]93
[5170d95]94 void previsit( SingleInit * singleInit );
95 void previsit( ListInit * listInit );
96 void previsit( ConstructorInit * ctorInit );
[a32b204]97 private:
[c28a038d]98 typedef std::list< Initializer * >::iterator InitIterator;
[94b4364]99
[40e636a]100 template< typename PtrType >
101 void handlePtrType( PtrType * type );
102
[c28a038d]103 void fallbackInit( ConstructorInit * ctorInit );
[b726084]104
[77971f6]105 Type * functionReturn = nullptr;
[e4d829b]106 CurrentObject currentObject = nullptr;
[a436947]107 bool inEnumDecl = false;
[a32b204]108 };
[d9a0e76]109
[2a6292d]110 struct ResolveWithExprs : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveWithExprs>, public WithShortCircuiting, public WithStmtsToAdd {
111 void previsit( FunctionDecl * );
112 void previsit( WithStmt * );
113
114 void resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts );
115 };
116
[a32b204]117 void resolve( std::list< Declaration * > translationUnit ) {
[d76c588]118 PassVisitor<Resolver_old> resolver;
[a32b204]119 acceptAll( translationUnit, resolver );
[d9a0e76]120 }
121
[5170d95]122 void resolveDecl( Declaration * decl, const SymTab::Indexer & indexer ) {
[d76c588]123 PassVisitor<Resolver_old> resolver( indexer );
[8b11840]124 maybeAccept( decl, resolver );
125 }
126
[c71b256]127 namespace {
[99d4584]128 struct DeleteFinder_old : public WithShortCircuiting {
[c71b256]129 DeletedExpr * delExpr = nullptr;
130 void previsit( DeletedExpr * expr ) {
131 if ( delExpr ) visit_children = false;
132 else delExpr = expr;
133 }
134
135 void previsit( Expression * ) {
136 if ( delExpr ) visit_children = false;
137 }
138 };
139 }
140
141 DeletedExpr * findDeletedExpr( Expression * expr ) {
[99d4584]142 PassVisitor<DeleteFinder_old> finder;
[c71b256]143 expr->accept( finder );
144 return finder.pass.delExpr;
[d9a0e76]145 }
[a32b204]146
147 namespace {
[99d4584]148 struct StripCasts_old {
[cdb990a]149 Expression * postmutate( CastExpr * castExpr ) {
150 if ( castExpr->isGenerated && ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, SymTab::Indexer() ) ) {
151 // generated cast is to the same type as its argument, so it's unnecessary -- remove it
152 Expression * expr = castExpr->arg;
153 castExpr->arg = nullptr;
154 std::swap( expr->env, castExpr->env );
155 return expr;
156 }
157 return castExpr;
158 }
159
160 static void strip( Expression *& expr ) {
[99d4584]161 PassVisitor<StripCasts_old> stripper;
[cdb990a]162 expr = expr->acceptMutator( stripper );
163 }
164 };
165
[5170d95]166 void finishExpr( Expression *& expr, const TypeEnvironment & env, TypeSubstitution * oldenv = nullptr ) {
[7664fad]167 expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
[cdb990a]168 env.makeSubstitution( *expr->env );
[99d4584]169 StripCasts_old::strip( expr ); // remove unnecessary casts that may be buried in an expression
[a32b204]170 }
[0a22cda]171
172 void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) {
173 if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
[b7d92b96]174 if ( typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) {
[0a22cda]175 // cast is to the same type as its argument, so it's unnecessary -- remove it
176 expr = castExpr->arg;
177 castExpr->arg = nullptr;
178 std::swap( expr->env, castExpr->env );
179 delete castExpr;
180 }
181 }
182 }
[db4ecc5]183 } // namespace
[a32b204]184
[8f98b78]185 namespace {
[59cf83b]186 void findUnfinishedKindExpression(Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{} ) {
[c71b256]187 assertf( untyped, "expected a non-null expression." );
[6d6e829]188
189 // xxx - this isn't thread-safe, but should work until we parallelize the resolver
190 static unsigned recursion_level = 0;
191
192 ++recursion_level;
[8587878e]193 TypeEnvironment env;
194 AlternativeFinder finder( indexer, env );
[6d6e829]195 finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode );
196 --recursion_level;
[c71b256]197
198 #if 0
199 if ( finder.get_alternatives().size() != 1 ) {
200 std::cerr << "untyped expr is ";
201 untyped->print( std::cerr );
202 std::cerr << std::endl << "alternatives are:";
203 for ( const Alternative & alt : finder.get_alternatives() ) {
204 alt.print( std::cerr );
205 } // for
206 } // if
207 #endif
[8587878e]208
[6d6e829]209 // produce filtered list of alternatives
[8587878e]210 AltList candidates;
211 for ( Alternative & alt : finder.get_alternatives() ) {
[c71b256]212 if ( pred( alt ) ) {
[8587878e]213 candidates.push_back( std::move( alt ) );
214 }
215 }
216
[6d6e829]217 // produce invalid error if no candidates
218 if ( candidates.empty() ) {
[a16764a6]219 SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") );
[6d6e829]220 }
221
222 // search for cheapest candidate
223 AltList winners;
224 bool seen_undeleted = false;
225 for ( unsigned i = 0; i < candidates.size(); ++i ) {
226 int c = winners.empty() ? -1 : candidates[i].cost.compare( winners.front().cost );
227
228 if ( c > 0 ) continue; // skip more expensive than winner
229
230 if ( c < 0 ) {
231 // reset on new cheapest
232 seen_undeleted = ! findDeletedExpr( candidates[i].expr );
233 winners.clear();
234 } else /* if ( c == 0 ) */ {
235 if ( findDeletedExpr( candidates[i].expr ) ) {
236 // skip deleted expression if already seen one equivalent-cost not
237 if ( seen_undeleted ) continue;
238 } else if ( ! seen_undeleted ) {
239 // replace list of equivalent-cost deleted expressions with one non-deleted
240 winners.clear();
241 seen_undeleted = true;
242 }
243 }
244
[2fd9f24]245 winners.emplace_back( std::move( candidates[i] ) );
[6d6e829]246 }
247
248 // promote alternative.cvtCost to .cost
249 // xxx - I don't know why this is done, but I'm keeping the behaviour from findMinCost
250 for ( Alternative& winner : winners ) {
251 winner.cost = winner.cvtCost;
252 }
[cde3891]253
[6d6e829]254 // produce ambiguous errors, if applicable
255 if ( winners.size() != 1 ) {
[8587878e]256 std::ostringstream stream;
[c71b256]257 stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n";
[8587878e]258 untyped->print( stream );
[93401f8]259 stream << " Alternatives are:\n";
[8587878e]260 printAlts( winners, stream, 1 );
[a16764a6]261 SemanticError( untyped->location, stream.str() );
[8587878e]262 }
263
[6d6e829]264 // single selected choice
265 Alternative& choice = winners.front();
266
267 // fail on only expression deleted
268 if ( ! seen_undeleted ) {
[2a08c25]269 SemanticError( untyped->location, choice.expr, "Unique best alternative includes deleted identifier in " );
[c71b256]270 }
[6d6e829]271
272 // xxx - check for ambiguous expressions
[cde3891]273
[6d6e829]274 // output selected choice
[c71b256]275 alt = std::move( choice );
276 }
277
278 /// resolve `untyped` to the expression whose alternative satisfies `pred` with the lowest cost; kindStr is used for providing better error messages
[59cf83b]279 void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{}) {
[c71b256]280 if ( ! untyped ) return;
281 Alternative choice;
[59cf83b]282 findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, mode );
[c71b256]283 finishExpr( choice.expr, choice.env, untyped->env );
[8587878e]284 delete untyped;
[c71b256]285 untyped = choice.expr;
286 choice.expr = nullptr;
[8587878e]287 }
288
[c71b256]289 bool standardAlternativeFilter( const Alternative & ) {
290 // currently don't need to filter, under normal circumstances.
291 // in the future, this may be useful for removing deleted expressions
292 return true;
293 }
294 } // namespace
295
296 // used in resolveTypeof
[5170d95]297 Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer ) {
[c71b256]298 TypeEnvironment env;
299 return resolveInVoidContext( expr, indexer, env );
300 }
301
[5170d95]302 Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer, TypeEnvironment & env ) {
[c71b256]303 // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
304 // interpretations, an exception has already been thrown.
305 assertf( expr, "expected a non-null expression." );
306
[5170d95]307 CastExpr * untyped = new CastExpr( expr ); // cast to void
308 untyped->location = expr->location;
[c71b256]309
310 // set up and resolve expression cast to void
311 Alternative choice;
[5170d95]312 findUnfinishedKindExpression( untyped, choice, indexer, "", standardAlternativeFilter, ResolvMode::withAdjustment() );
[c71b256]313 CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr );
[5170d95]314 assert( castExpr );
[c71b256]315 env = std::move( choice.env );
316
317 // clean up resolved expression
318 Expression * ret = castExpr->arg;
319 castExpr->arg = nullptr;
320
321 // unlink the arg so that it isn't deleted twice at the end of the program
[5170d95]322 untyped->arg = nullptr;
[c71b256]323 return ret;
324 }
325
[5170d95]326 void findVoidExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
[c71b256]327 resetTyVarRenaming();
328 TypeEnvironment env;
329 Expression * newExpr = resolveInVoidContext( untyped, indexer, env );
330 finishExpr( newExpr, env, untyped->env );
331 delete untyped;
332 untyped = newExpr;
333 }
334
[5170d95]335 void findSingleExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
[c71b256]336 findKindExpression( untyped, indexer, "", standardAlternativeFilter );
337 }
338
339 void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) {
340 assert( untyped && type );
[2a08c25]341 // transfer location to generated cast for error purposes
342 CodeLocation location = untyped->location;
[c71b256]343 untyped = new CastExpr( untyped, type );
[2a08c25]344 untyped->location = location;
[c71b256]345 findSingleExpression( untyped, indexer );
346 removeExtraneousCast( untyped, indexer );
347 }
348
349 namespace {
350 bool isIntegralType( const Alternative & alt ) {
351 Type * type = alt.expr->result;
[a32b204]352 if ( dynamic_cast< EnumInstType * >( type ) ) {
353 return true;
[5170d95]354 } else if ( BasicType * bt = dynamic_cast< BasicType * >( type ) ) {
[a32b204]355 return bt->isInteger();
[89e6ffc]356 } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
357 return true;
[a32b204]358 } else {
359 return false;
360 } // if
361 }
[71f4e4f]362
[5170d95]363 void findIntegralExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
[8587878e]364 findKindExpression( untyped, indexer, "condition", isIntegralType );
[a32b204]365 }
366 }
[71f4e4f]367
[2a6292d]368
369 bool isStructOrUnion( const Alternative & alt ) {
370 Type * t = alt.expr->result->stripReferences();
371 return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t );
372 }
373
374 void resolveWithExprs( std::list< Declaration * > & translationUnit ) {
375 PassVisitor<ResolveWithExprs> resolver;
376 acceptAll( translationUnit, resolver );
377 }
378
379 void ResolveWithExprs::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) {
380 for ( Expression *& expr : withExprs ) {
381 // only struct- and union-typed expressions are viable candidates
382 findKindExpression( expr, indexer, "with statement", isStructOrUnion );
383
384 // if with expression might be impure, create a temporary so that it is evaluated once
385 if ( Tuples::maybeImpure( expr ) ) {
386 static UniqueName tmpNamer( "_with_tmp_" );
387 ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) );
388 expr = new VariableExpr( tmp );
389 newStmts.push_back( new DeclStmt( tmp ) );
390 if ( InitTweak::isConstructable( tmp->type ) ) {
391 // generate ctor/dtor and resolve them
392 tmp->init = InitTweak::genCtorInit( tmp );
393 tmp->accept( *visitor );
394 }
395 }
396 }
397 }
398
399 void ResolveWithExprs::previsit( WithStmt * withStmt ) {
400 resolveWithExprs( withStmt->exprs, stmtsToAddBefore );
401 }
402
403 void ResolveWithExprs::previsit( FunctionDecl * functionDecl ) {
404 {
405 // resolve with-exprs with parameters in scope and add any newly generated declarations to the
406 // front of the function body.
407 auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } );
408 indexer.addFunctionType( functionDecl->type );
409 std::list< Statement * > newStmts;
410 resolveWithExprs( functionDecl->withExprs, newStmts );
411 if ( functionDecl->statements ) {
412 functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts );
413 } else {
414 assertf( functionDecl->withExprs.empty() && newStmts.empty(), "Function %s without a body has with-clause and/or generated with declarations.", functionDecl->name.c_str() );
415 }
416 }
417 }
418
[d76c588]419 void Resolver_old::previsit( ObjectDecl * objectDecl ) {
[4864a73]420 // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that
421 // class-variable initContext is changed multiple time because the LHS is analysed twice.
422 // The second analysis changes initContext because of a function type can contain object
423 // declarations in the return and parameter types. So each value of initContext is
[6d6e829]424 // retained, so the type on the first analysis is preserved and used for selecting the RHS.
[a4ca48c]425 GuardValue( currentObject );
[e4d829b]426 currentObject = CurrentObject( objectDecl->get_type() );
427 if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
[a436947]428 // enumerator initializers should not use the enum type to initialize, since
429 // the enum type is still incomplete at this point. Use signed int instead.
[9e7236f4]430 // TODO: BasicType::SignedInt may not longer be true
[e4d829b]431 currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
[a436947]432 }
[bfbf97f]433 }
434
[40e636a]435 template< typename PtrType >
[d76c588]436 void Resolver_old::handlePtrType( PtrType * type ) {
[40e636a]437 if ( type->get_dimension() ) {
[2bfc6b2]438 findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
[d1d17f5]439 }
[40e636a]440 }
441
[d76c588]442 void Resolver_old::previsit( ArrayType * at ) {
[40e636a]443 handlePtrType( at );
[a32b204]444 }
[94b4364]445
[d76c588]446 void Resolver_old::previsit( PointerType * pt ) {
[40e636a]447 handlePtrType( pt );
448 }
449
[d76c588]450 void Resolver_old::previsit( FunctionDecl * functionDecl ) {
[d9a0e76]451#if 0
[a4ca48c]452 std::cerr << "resolver visiting functiondecl ";
453 functionDecl->print( std::cerr );
454 std::cerr << std::endl;
[d9a0e76]455#endif
[a4ca48c]456 GuardValue( functionReturn );
[60914351]457 functionReturn = ResolvExpr::extractResultType( functionDecl->type );
[a4ca48c]458 }
[88d1066]459
[d76c588]460 void Resolver_old::postvisit( FunctionDecl * functionDecl ) {
[4864a73]461 // default value expressions have an environment which shouldn't be there and trips up
[6d6e829]462 // later passes.
[cde3891]463 // xxx - it might be necessary to somehow keep the information from this environment, but I
[6d6e829]464 // can't currently see how it's useful.
[c28a038d]465 for ( Declaration * d : functionDecl->type->parameters ) {
[88d1066]466 if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
[c28a038d]467 if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
468 delete init->value->env;
469 init->value->env = nullptr;
[88d1066]470 }
471 }
472 }
[a32b204]473 }
[51b73452]474
[d76c588]475 void Resolver_old::previsit( EnumDecl * ) {
[a436947]476 // in case we decide to allow nested enums
[a4ca48c]477 GuardValue( inEnumDecl );
[a436947]478 inEnumDecl = true;
479 }
480
[d76c588]481 void Resolver_old::previsit( StaticAssertDecl * assertDecl ) {
[bd87b138]482 findIntegralExpression( assertDecl->condition, indexer );
483 }
484
[d76c588]485 void Resolver_old::previsit( ExprStmt * exprStmt ) {
[a4ca48c]486 visit_children = false;
[08da53d]487 assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
488 findVoidExpression( exprStmt->expr, indexer );
[a32b204]489 }
[51b73452]490
[d76c588]491 void Resolver_old::previsit( AsmExpr * asmExpr ) {
[a4ca48c]492 visit_children = false;
[08da53d]493 findVoidExpression( asmExpr->operand, indexer );
[7f5566b]494 }
495
[d76c588]496 void Resolver_old::previsit( AsmStmt * asmStmt ) {
[a4ca48c]497 visit_children = false;
498 acceptAll( asmStmt->get_input(), *visitor );
499 acceptAll( asmStmt->get_output(), *visitor );
[7f5566b]500 }
501
[d76c588]502 void Resolver_old::previsit( IfStmt * ifStmt ) {
[8587878e]503 findIntegralExpression( ifStmt->condition, indexer );
[a32b204]504 }
[51b73452]505
[3b0bc16]506 void Resolver_old::previsit( WhileDoStmt * whileDoStmt ) {
507 findIntegralExpression( whileDoStmt->condition, indexer );
[a32b204]508 }
[51b73452]509
[d76c588]510 void Resolver_old::previsit( ForStmt * forStmt ) {
[08da53d]511 if ( forStmt->condition ) {
[8587878e]512 findIntegralExpression( forStmt->condition, indexer );
[a32b204]513 } // if
[71f4e4f]514
[08da53d]515 if ( forStmt->increment ) {
516 findVoidExpression( forStmt->increment, indexer );
[a32b204]517 } // if
518 }
[51b73452]519
[d76c588]520 void Resolver_old::previsit( SwitchStmt * switchStmt ) {
[a4ca48c]521 GuardValue( currentObject );
[08da53d]522 findIntegralExpression( switchStmt->condition, indexer );
[71f4e4f]523
[08da53d]524 currentObject = CurrentObject( switchStmt->condition->result );
[a32b204]525 }
[51b73452]526
[d76c588]527 void Resolver_old::previsit( CaseStmt * caseStmt ) {
[cdb990a]528 if ( caseStmt->condition ) {
[e4d829b]529 std::list< InitAlternative > initAlts = currentObject.getOptions();
530 assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
[08da53d]531 // must remove cast from case statement because RangeExpr cannot be cast.
532 Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() );
533 findSingleExpression( newExpr, indexer );
[cdb990a]534 // case condition cannot have a cast in C, so it must be removed, regardless of whether it performs a conversion.
535 // Ideally we would perform the conversion internally here.
536 if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( newExpr ) ) {
537 newExpr = castExpr->arg;
538 castExpr->arg = nullptr;
539 std::swap( newExpr->env, castExpr->env );
540 delete castExpr;
541 }
542 caseStmt->condition = newExpr;
[32b8144]543 }
[a32b204]544 }
[51b73452]545
[d76c588]546 void Resolver_old::previsit( BranchStmt * branchStmt ) {
[a4ca48c]547 visit_children = false;
[de62360d]548 // must resolve the argument for a computed goto
549 if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
[08da53d]550 if ( branchStmt->computedTarget ) {
551 // computed goto argument is void *
552 findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
[de62360d]553 } // if
554 } // if
555 }
556
[d76c588]557 void Resolver_old::previsit( ReturnStmt * returnStmt ) {
[a4ca48c]558 visit_children = false;
[08da53d]559 if ( returnStmt->expr ) {
560 findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
[a32b204]561 } // if
562 }
[51b73452]563
[d76c588]564 void Resolver_old::previsit( ThrowStmt * throwStmt ) {
[a4ca48c]565 visit_children = false;
[cbce272]566 // TODO: Replace *exception type with &exception type.
[307a732]567 if ( throwStmt->get_expr() ) {
[3090127]568 const StructDecl * exception_decl = indexer.lookupStruct( "__cfaehm_base_exception_t" );
[cbce272]569 assert( exception_decl );
[8fd52e90]570 Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, const_cast<StructDecl *>(exception_decl) ) );
[08da53d]571 findSingleExpression( throwStmt->expr, exceptType, indexer );
[307a732]572 }
573 }
574
[d76c588]575 void Resolver_old::previsit( CatchStmt * catchStmt ) {
[3b0bc16]576 // Until we are very sure this invarent (ifs that move between passes have then)
[3b9c674]577 // holds, check it. This allows a check for when to decode the mangling.
578 if ( IfStmt * ifStmt = dynamic_cast<IfStmt *>( catchStmt->body ) ) {
[3b0bc16]579 assert( ifStmt->then );
[3b9c674]580 }
581 // Encode the catchStmt so the condition can see the declaration.
[08da53d]582 if ( catchStmt->cond ) {
[3b9c674]583 IfStmt * ifStmt = new IfStmt( catchStmt->cond, nullptr, catchStmt->body );
584 catchStmt->cond = nullptr;
585 catchStmt->body = ifStmt;
586 }
587 }
588
589 void Resolver_old::postvisit( CatchStmt * catchStmt ) {
590 // Decode the catchStmt so everything is stored properly.
591 IfStmt * ifStmt = dynamic_cast<IfStmt *>( catchStmt->body );
[3b0bc16]592 if ( nullptr != ifStmt && nullptr == ifStmt->then ) {
[3b9c674]593 assert( ifStmt->condition );
[3b0bc16]594 assert( ifStmt->else_ );
[3b9c674]595 catchStmt->cond = ifStmt->condition;
[3b0bc16]596 catchStmt->body = ifStmt->else_;
[3b9c674]597 ifStmt->condition = nullptr;
[3b0bc16]598 ifStmt->else_ = nullptr;
[3b9c674]599 delete ifStmt;
[cbce272]600 }
601 }
602
[1dcd9554]603 template< typename iterator_t >
604 inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
605 while( it != end && !(*it)->get_type()->get_mutex() ) {
606 it++;
607 }
608
609 return it != end;
610 }
611
[d76c588]612 void Resolver_old::previsit( WaitForStmt * stmt ) {
[8f98b78]613 visit_children = false;
[1dcd9554]614
615 // Resolve all clauses first
616 for( auto& clause : stmt->clauses ) {
617
618 TypeEnvironment env;
[8f98b78]619 AlternativeFinder funcFinder( indexer, env );
[1dcd9554]620
621 // Find all alternatives for a function in canonical form
622 funcFinder.findWithAdjustment( clause.target.function );
623
624 if ( funcFinder.get_alternatives().empty() ) {
625 stringstream ss;
626 ss << "Use of undeclared indentifier '";
627 ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
628 ss << "' in call to waitfor";
[a16764a6]629 SemanticError( stmt->location, ss.str() );
[1dcd9554]630 }
631
[b9f383f]632 if(clause.target.arguments.empty()) {
633 SemanticError( stmt->location, "Waitfor clause must have at least one mutex parameter");
634 }
635
[1dcd9554]636 // Find all alternatives for all arguments in canonical form
[bd4f2e9]637 std::vector< AlternativeFinder > argAlternatives;
[1dcd9554]638 funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
639
640 // List all combinations of arguments
[bd4f2e9]641 std::vector< AltList > possibilities;
[1dcd9554]642 combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
643
644 AltList func_candidates;
645 std::vector< AltList > args_candidates;
646
647 // For every possible function :
648 // try matching the arguments to the parameters
649 // not the other way around because we have more arguments than parameters
[a16764a6]650 SemanticErrorException errors;
[1dcd9554]651 for ( Alternative & func : funcFinder.get_alternatives() ) {
652 try {
653 PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
654 if( !pointer ) {
[a16764a6]655 SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" );
[1dcd9554]656 }
657
658 FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
659 if( !function ) {
[a16764a6]660 SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" );
[1dcd9554]661 }
662
663
664 {
665 auto param = function->parameters.begin();
666 auto param_end = function->parameters.end();
667
668 if( !advance_to_mutex( param, param_end ) ) {
[a16764a6]669 SemanticError(function, "candidate function not viable: no mutex parameters\n");
[1dcd9554]670 }
671 }
672
673 Alternative newFunc( func );
674 // Strip reference from function
[a181494]675 referenceToRvalueConversion( newFunc.expr, newFunc.cost );
[1dcd9554]676
677 // For all the set of arguments we have try to match it with the parameter of the current function alternative
678 for ( auto & argsList : possibilities ) {
679
680 try {
681 // Declare data structures need for resolution
682 OpenVarSet openVars;
683 AssertionSet resultNeed, resultHave;
[6f326b1]684 TypeEnvironment resultEnv( func.env );
685 makeUnifiableVars( function, openVars, resultNeed );
686 // add all type variables as open variables now so that those not used in the parameter
687 // list are still considered open.
688 resultEnv.add( function->forall );
[1dcd9554]689
690 // Load type variables from arguemnts into one shared space
691 simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );
692
693 // Make sure we don't widen any existing bindings
[d286cf68]694 resultEnv.forbidWidening();
[c5283ba]695
[1dcd9554]696 // Find any unbound type variables
697 resultEnv.extractOpenVars( openVars );
698
699 auto param = function->parameters.begin();
700 auto param_end = function->parameters.end();
701
[c5283ba]702 int n_mutex_param = 0;
[b9f383f]703
[1dcd9554]704 // For every arguments of its set, check if it matches one of the parameter
705 // The order is important
706 for( auto & arg : argsList ) {
707
708 // Ignore non-mutex arguments
709 if( !advance_to_mutex( param, param_end ) ) {
710 // We ran out of parameters but still have arguments
711 // this function doesn't match
[c5283ba]712 SemanticError( function, toString("candidate function not viable: too many mutex arguments, expected ", n_mutex_param, "\n" ));
[1dcd9554]713 }
714
[c5283ba]715 n_mutex_param++;
[b9f383f]716
[1dcd9554]717 // Check if the argument matches the parameter type in the current scope
[b9f383f]718 if( ! unify( arg.expr->get_result(), (*param)->get_type(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
[1dcd9554]719 // Type doesn't match
720 stringstream ss;
721 ss << "candidate function not viable: no known convertion from '";
722 (*param)->get_type()->print( ss );
[b9f383f]723 ss << "' to '";
724 arg.expr->get_result()->print( ss );
[5248789]725 ss << "' with env '";
726 resultEnv.print(ss);
[1dcd9554]727 ss << "'\n";
[a16764a6]728 SemanticError( function, ss.str() );
[1dcd9554]729 }
730
731 param++;
732 }
733
734 // All arguments match !
735
736 // Check if parameters are missing
737 if( advance_to_mutex( param, param_end ) ) {
[c5283ba]738 do {
739 n_mutex_param++;
740 param++;
741 } while( advance_to_mutex( param, param_end ) );
742
[1dcd9554]743 // We ran out of arguments but still have parameters left
744 // this function doesn't match
[c5283ba]745 SemanticError( function, toString("candidate function not viable: too few mutex arguments, expected ", n_mutex_param, "\n" ));
[1dcd9554]746 }
747
748 // All parameters match !
749
750 // Finish the expressions to tie in the proper environments
751 finishExpr( newFunc.expr, resultEnv );
752 for( Alternative & alt : argsList ) {
753 finishExpr( alt.expr, resultEnv );
754 }
755
756 // This is a match store it and save it for later
757 func_candidates.push_back( newFunc );
758 args_candidates.push_back( argsList );
759
760 }
[5170d95]761 catch( SemanticErrorException & e ) {
[1dcd9554]762 errors.append( e );
763 }
764 }
765 }
[5170d95]766 catch( SemanticErrorException & e ) {
[1dcd9554]767 errors.append( e );
768 }
769 }
770
771 // Make sure we got the right number of arguments
[a16764a6]772 if( func_candidates.empty() ) { SemanticErrorException top( stmt->location, "No alternatives for function in call to waitfor" ); top.append( errors ); throw top; }
773 if( args_candidates.empty() ) { SemanticErrorException top( stmt->location, "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
774 if( func_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous function in call to waitfor" ); top.append( errors ); throw top; }
775 if( args_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous arguments in call to waitfor" ); top.append( errors ); throw top; }
[c71b256]776 // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
[1dcd9554]777
778 // Swap the results from the alternative with the unresolved values.
779 // Alternatives will handle deletion on destruction
780 std::swap( clause.target.function, func_candidates.front().expr );
781 for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
782 std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
783 }
784
785 // Resolve the conditions as if it were an IfStmt
786 // Resolve the statments normally
[08da53d]787 findSingleExpression( clause.condition, this->indexer );
[8f98b78]788 clause.statement->accept( *visitor );
[1dcd9554]789 }
790
791
792 if( stmt->timeout.statement ) {
793 // Resolve the timeout as an size_t for now
794 // Resolve the conditions as if it were an IfStmt
795 // Resolve the statments normally
[08da53d]796 findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
797 findSingleExpression( stmt->timeout.condition, this->indexer );
[8f98b78]798 stmt->timeout.statement->accept( *visitor );
[1dcd9554]799 }
800
801 if( stmt->orelse.statement ) {
802 // Resolve the conditions as if it were an IfStmt
803 // Resolve the statments normally
[08da53d]804 findSingleExpression( stmt->orelse.condition, this->indexer );
[8f98b78]805 stmt->orelse.statement->accept( *visitor );
[1dcd9554]806 }
807 }
808
[60aaa51d]809 bool isCharType( Type * t ) {
[b5c5684]810 if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
[71f4e4f]811 return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
[b5c5684]812 bt->get_kind() == BasicType::UnsignedChar;
813 }
814 return false;
815 }
816
[d76c588]817 void Resolver_old::previsit( SingleInit * singleInit ) {
[a4ca48c]818 visit_children = false;
[62423350]819 // resolve initialization using the possibilities as determined by the currentObject cursor
[0a22cda]820 Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
[08da53d]821 findSingleExpression( newExpr, indexer );
[e3e16bc]822 InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
[62423350]823
824 // move cursor to the object that is actually initialized
[e4d829b]825 currentObject.setNext( initExpr->get_designation() );
[62423350]826
827 // discard InitExpr wrapper and retain relevant pieces
[08da53d]828 newExpr = initExpr->expr;
829 initExpr->expr = nullptr;
830 std::swap( initExpr->env, newExpr->env );
[cde3891]831 // InitExpr may have inferParams in the case where the expression specializes a function
832 // pointer, and newExpr may already have inferParams of its own, so a simple swap is not
[6d6e829]833 // sufficient.
[cdb990a]834 newExpr->spliceInferParams( initExpr );
[e4d829b]835 delete initExpr;
836
[cde3891]837 // get the actual object's type (may not exactly match what comes back from the resolver
[6d6e829]838 // due to conversions)
[62423350]839 Type * initContext = currentObject.getCurrentType();
840
[0a22cda]841 removeExtraneousCast( newExpr, indexer );
842
[62423350]843 // check if actual object's type is char[]
844 if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
845 if ( isCharType( at->get_base() ) ) {
846 // check if the resolved type is char *
847 if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
848 if ( isCharType( pt->get_base() ) ) {
[5170d95]849 if ( CastExpr * ce = dynamic_cast< CastExpr * >( newExpr ) ) {
[cde3891]850 // strip cast if we're initializing a char[] with a char *,
[6d6e829]851 // e.g. char x[] = "hello";
[0a22cda]852 newExpr = ce->get_arg();
853 ce->set_arg( nullptr );
854 std::swap( ce->env, newExpr->env );
855 delete ce;
856 }
[62423350]857 }
858 }
859 }
860 }
[94b4364]861
[62423350]862 // set initializer expr to resolved express
[0a22cda]863 singleInit->value = newExpr;
[62423350]864
865 // move cursor to next object in preparation for next initializer
866 currentObject.increment();
867 }
[94b4364]868
[d76c588]869 void Resolver_old::previsit( ListInit * listInit ) {
[a4ca48c]870 visit_children = false;
[62423350]871 // move cursor into brace-enclosed initializer-list
[e4d829b]872 currentObject.enterListInit();
[cde3891]873 // xxx - fix this so that the list isn't copied, iterator should be used to change current
[6d6e829]874 // element
[e4d829b]875 std::list<Designation *> newDesignations;
876 for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
[cde3891]877 // iterate designations and initializers in pairs, moving the cursor to the current
[6d6e829]878 // designated object and resolving the initializer against that object.
[e4d829b]879 Designation * des = std::get<0>(p);
880 Initializer * init = std::get<1>(p);
881 newDesignations.push_back( currentObject.findNext( des ) );
[a4ca48c]882 init->accept( *visitor );
[b5c5684]883 }
[62423350]884 // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
[e4d829b]885 listInit->get_designations() = newDesignations; // xxx - memory management
886 currentObject.exitListInit();
887
[62423350]888 // xxx - this part has not be folded into CurrentObject yet
[e4d829b]889 // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
890 // Type * base = tt->get_baseType()->get_base();
891 // if ( base ) {
892 // // know the implementation type, so try using that as the initContext
893 // ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
894 // currentObject = &tmpObj;
895 // visit( listInit );
896 // } else {
897 // // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
898 // Parent::visit( listInit );
899 // }
900 // } else {
[a32b204]901 }
[71f4e4f]902
[f1e012b]903 // ConstructorInit - fall back on C-style initializer
[d76c588]904 void Resolver_old::fallbackInit( ConstructorInit * ctorInit ) {
[f1e012b]905 // could not find valid constructor, or found an intrinsic constructor
906 // fall back on C-style initializer
907 delete ctorInit->get_ctor();
[6d6e829]908 ctorInit->set_ctor( nullptr );
[71a145de]909 delete ctorInit->get_dtor();
[6d6e829]910 ctorInit->set_dtor( nullptr );
[a4ca48c]911 maybeAccept( ctorInit->get_init(), *visitor );
[f1e012b]912 }
913
[1d2b64f]914 // needs to be callable from outside the resolver, so this is a standalone function
915 void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
916 assert( ctorInit );
[d76c588]917 PassVisitor<Resolver_old> resolver( indexer );
[1d2b64f]918 ctorInit->accept( resolver );
919 }
920
921 void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
922 assert( stmtExpr );
[d76c588]923 PassVisitor<Resolver_old> resolver( indexer );
[1d2b64f]924 stmtExpr->accept( resolver );
[5e2c348]925 stmtExpr->computeResult();
[dd05e12]926 // xxx - aggregate the environments from all statements? Possibly in AlternativeFinder instead?
[1d2b64f]927 }
928
[d76c588]929 void Resolver_old::previsit( ConstructorInit * ctorInit ) {
[a4ca48c]930 visit_children = false;
[1ba88a0]931 // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
[dd05e12]932 maybeAccept( ctorInit->ctor, *visitor );
933 maybeAccept( ctorInit->dtor, *visitor );
[071a31a]934
[5b2f5bb]935 // found a constructor - can get rid of C-style initializer
[dd05e12]936 delete ctorInit->init;
937 ctorInit->init = nullptr;
[ec79847]938
939 // intrinsic single parameter constructors and destructors do nothing. Since this was
940 // implicitly generated, there's no way for it to have side effects, so get rid of it
941 // to clean up generated code.
[dd05e12]942 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
943 delete ctorInit->ctor;
944 ctorInit->ctor = nullptr;
[ec79847]945 }
[f9cebb5]946
[dd05e12]947 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
948 delete ctorInit->dtor;
949 ctorInit->dtor = nullptr;
[ec79847]950 }
[a465caff]951
952 // xxx - todo -- what about arrays?
[6d6e829]953 // if ( dtor == nullptr && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
[a465caff]954 // // can reduce the constructor down to a SingleInit using the
955 // // second argument from the ctor call, since
956 // delete ctorInit->get_ctor();
[6d6e829]957 // ctorInit->set_ctor( nullptr );
[a465caff]958
959 // Expression * arg =
960 // ctorInit->set_init( new SingleInit( arg ) );
961 // }
[71f4e4f]962 }
[d76c588]963
964 ///////////////////////////////////////////////////////////////////////////
965 //
966 // *** NEW RESOLVER ***
967 //
968 ///////////////////////////////////////////////////////////////////////////
969
[99d4584]970 namespace {
971 /// Finds deleted expressions in an expression tree
[2dda05d]972 struct DeleteFinder_new final : public ast::WithShortCircuiting, public ast::WithVisitorRef<DeleteFinder_new> {
[e6b42e7]973 const ast::DeletedExpr * result = nullptr;
[99d4584]974
975 void previsit( const ast::DeletedExpr * expr ) {
[e6b42e7]976 if ( result ) { visit_children = false; }
977 else { result = expr; }
[99d4584]978 }
979
[361bf01]980 void previsit( const ast::Expr * expr ) {
[e6b42e7]981 if ( result ) { visit_children = false; }
[361bf01]982 if (expr->inferred.hasParams()) {
983 for (auto & imp : expr->inferred.inferParams() ) {
[2dda05d]984 imp.second.expr->accept(*visitor);
[361bf01]985 }
986 }
[99d4584]987 }
988 };
[d57e349]989 } // anonymous namespace
990 /// Check if this expression is or includes a deleted expression
991 const ast::DeletedExpr * findDeletedExpr( const ast::Expr * expr ) {
[e6b42e7]992 return ast::Pass<DeleteFinder_new>::read( expr );
[d57e349]993 }
[99d4584]994
[d57e349]995 namespace {
[b7d92b96]996 /// always-accept candidate filter
997 bool anyCandidate( const Candidate & ) { return true; }
998
[99d4584]999 /// Calls the CandidateFinder and finds the single best candidate
1000 CandidateRef findUnfinishedKindExpression(
[39d8950]1001 const ast::Expr * untyped, const ResolveContext & context, const std::string & kind,
[b7d92b96]1002 std::function<bool(const Candidate &)> pred = anyCandidate, ResolvMode mode = {}
[99d4584]1003 ) {
1004 if ( ! untyped ) return nullptr;
1005
1006 // xxx - this isn't thread-safe, but should work until we parallelize the resolver
1007 static unsigned recursion_level = 0;
1008
1009 ++recursion_level;
1010 ast::TypeEnvironment env;
[39d8950]1011 CandidateFinder finder( context, env );
[99d4584]1012 finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode );
1013 --recursion_level;
1014
1015 // produce a filtered list of candidates
1016 CandidateList candidates;
1017 for ( auto & cand : finder.candidates ) {
1018 if ( pred( *cand ) ) { candidates.emplace_back( cand ); }
1019 }
1020
1021 // produce invalid error if no candidates
1022 if ( candidates.empty() ) {
[ef5b828]1023 SemanticError( untyped,
1024 toString( "No reasonable alternatives for ", kind, (kind != "" ? " " : ""),
[99d4584]1025 "expression: ") );
1026 }
1027
1028 // search for cheapest candidate
1029 CandidateList winners;
1030 bool seen_undeleted = false;
1031 for ( CandidateRef & cand : candidates ) {
1032 int c = winners.empty() ? -1 : cand->cost.compare( winners.front()->cost );
1033
1034 if ( c > 0 ) continue; // skip more expensive than winner
1035
1036 if ( c < 0 ) {
1037 // reset on new cheapest
1038 seen_undeleted = ! findDeletedExpr( cand->expr );
1039 winners.clear();
1040 } else /* if ( c == 0 ) */ {
1041 if ( findDeletedExpr( cand->expr ) ) {
1042 // skip deleted expression if already seen one equivalent-cost not
1043 if ( seen_undeleted ) continue;
1044 } else if ( ! seen_undeleted ) {
1045 // replace list of equivalent-cost deleted expressions with one non-deleted
1046 winners.clear();
1047 seen_undeleted = true;
1048 }
1049 }
1050
1051 winners.emplace_back( std::move( cand ) );
1052 }
1053
1054 // promote candidate.cvtCost to .cost
[d57e349]1055 promoteCvtCost( winners );
[99d4584]1056
1057 // produce ambiguous errors, if applicable
1058 if ( winners.size() != 1 ) {
1059 std::ostringstream stream;
[ef5b828]1060 stream << "Cannot choose between " << winners.size() << " alternatives for "
[99d4584]1061 << kind << (kind != "" ? " " : "") << "expression\n";
1062 ast::print( stream, untyped );
1063 stream << " Alternatives are:\n";
1064 print( stream, winners, 1 );
1065 SemanticError( untyped->location, stream.str() );
1066 }
1067
1068 // single selected choice
1069 CandidateRef & choice = winners.front();
1070
1071 // fail on only expression deleted
1072 if ( ! seen_undeleted ) {
1073 SemanticError( untyped->location, choice->expr.get(), "Unique best alternative "
1074 "includes deleted identifier in " );
1075 }
1076
1077 return std::move( choice );
1078 }
1079
1080 /// Strips extraneous casts out of an expression
1081 struct StripCasts_new final {
[c408483]1082 const ast::Expr * postvisit( const ast::CastExpr * castExpr ) {
[ef5b828]1083 if (
[2890212]1084 castExpr->isGenerated == ast::GeneratedCast
[ef5b828]1085 && typesCompatible( castExpr->arg->result, castExpr->result )
[99d4584]1086 ) {
1087 // generated cast is the same type as its argument, remove it after keeping env
[ef5b828]1088 return ast::mutate_field(
[b7d92b96]1089 castExpr->arg.get(), &ast::Expr::env, castExpr->env );
[99d4584]1090 }
1091 return castExpr;
1092 }
1093
1094 static void strip( ast::ptr< ast::Expr > & expr ) {
1095 ast::Pass< StripCasts_new > stripper;
1096 expr = expr->accept( stripper );
1097 }
1098 };
1099
[60aaa51d]1100 /// Swaps argument into expression pointer, saving original environment
1101 void swap_and_save_env( ast::ptr< ast::Expr > & expr, const ast::Expr * newExpr ) {
1102 ast::ptr< ast::TypeSubstitution > env = expr->env;
1103 expr.set_and_mutate( newExpr )->env = env;
1104 }
1105
[b7d92b96]1106 /// Removes cast to type of argument (unlike StripCasts, also handles non-generated casts)
1107 void removeExtraneousCast( ast::ptr<ast::Expr> & expr, const ast::SymbolTable & symtab ) {
1108 if ( const ast::CastExpr * castExpr = expr.as< ast::CastExpr >() ) {
1109 if ( typesCompatible( castExpr->arg->result, castExpr->result, symtab ) ) {
1110 // cast is to the same type as its argument, remove it
[60aaa51d]1111 swap_and_save_env( expr, castExpr->arg );
[b7d92b96]1112 }
1113 }
1114 }
1115
[6668a3e]1116
[490fb92e]1117 } // anonymous namespace
1118/// Establish post-resolver invariants for expressions
[ef5b828]1119 void finishExpr(
1120 ast::ptr< ast::Expr > & expr, const ast::TypeEnvironment & env,
[99d4584]1121 const ast::TypeSubstitution * oldenv = nullptr
1122 ) {
1123 // set up new type substitution for expression
[ef5b828]1124 ast::ptr< ast::TypeSubstitution > newenv =
[99d4584]1125 oldenv ? oldenv : new ast::TypeSubstitution{};
1126 env.writeToSubstitution( *newenv.get_and_mutate() );
1127 expr.get_and_mutate()->env = std::move( newenv );
1128 // remove unncecessary casts
1129 StripCasts_new::strip( expr );
1130 }
[ef5b828]1131
[4b7cce6]1132 ast::ptr< ast::Expr > resolveInVoidContext(
[39d8950]1133 const ast::Expr * expr, const ResolveContext & context,
1134 ast::TypeEnvironment & env
[4b7cce6]1135 ) {
1136 assertf( expr, "expected a non-null expression" );
[ef5b828]1137
[4b7cce6]1138 // set up and resolve expression cast to void
[417117e]1139 ast::ptr< ast::CastExpr > untyped = new ast::CastExpr{ expr };
[ef5b828]1140 CandidateRef choice = findUnfinishedKindExpression(
[39d8950]1141 untyped, context, "", anyCandidate, ResolvMode::withAdjustment() );
[ef5b828]1142
[4b7cce6]1143 // a cast expression has either 0 or 1 interpretations (by language rules);
1144 // if 0, an exception has already been thrown, and this code will not run
1145 const ast::CastExpr * castExpr = choice->expr.strict_as< ast::CastExpr >();
1146 env = std::move( choice->env );
1147
1148 return castExpr->arg;
1149 }
[b7d92b96]1150
[490fb92e]1151 /// Resolve `untyped` to the expression whose candidate is the best match for a `void`
[b7d92b96]1152 /// context.
[ef5b828]1153 ast::ptr< ast::Expr > findVoidExpression(
[39d8950]1154 const ast::Expr * untyped, const ResolveContext & context
[b7d92b96]1155 ) {
1156 ast::TypeEnvironment env;
[39d8950]1157 ast::ptr< ast::Expr > newExpr = resolveInVoidContext( untyped, context, env );
[b7d92b96]1158 finishExpr( newExpr, env, untyped->env );
1159 return newExpr;
1160 }
1161
[490fb92e]1162 namespace {
[6668a3e]1163
[490fb92e]1164
[ef5b828]1165 /// resolve `untyped` to the expression whose candidate satisfies `pred` with the
[99d4584]1166 /// lowest cost, returning the resolved version
1167 ast::ptr< ast::Expr > findKindExpression(
[39d8950]1168 const ast::Expr * untyped, const ResolveContext & context,
[ef5b828]1169 std::function<bool(const Candidate &)> pred = anyCandidate,
[2b59f55]1170 const std::string & kind = "", ResolvMode mode = {}
[99d4584]1171 ) {
1172 if ( ! untyped ) return {};
[ef5b828]1173 CandidateRef choice =
[39d8950]1174 findUnfinishedKindExpression( untyped, context, kind, pred, mode );
[490fb92e]1175 ResolvExpr::finishExpr( choice->expr, choice->env, untyped->env );
[99d4584]1176 return std::move( choice->expr );
1177 }
1178
[2773ab8]1179 /// Resolve `untyped` to the single expression whose candidate is the best match
[ef5b828]1180 ast::ptr< ast::Expr > findSingleExpression(
[39d8950]1181 const ast::Expr * untyped, const ResolveContext & context
[2773ab8]1182 ) {
[57e0289]1183 Stats::ResolveTime::start( untyped );
[39d8950]1184 auto res = findKindExpression( untyped, context );
[57e0289]1185 Stats::ResolveTime::stop();
1186 return res;
[2773ab8]1187 }
[18e683b]1188 } // anonymous namespace
[2773ab8]1189
[16ba4a6f]1190 ast::ptr< ast::Expr > findSingleExpression(
[39d8950]1191 const ast::Expr * untyped, const ast::Type * type,
1192 const ResolveContext & context
[16ba4a6f]1193 ) {
1194 assert( untyped && type );
1195 ast::ptr< ast::Expr > castExpr = new ast::CastExpr{ untyped, type };
[39d8950]1196 ast::ptr< ast::Expr > newExpr = findSingleExpression( castExpr, context );
1197 removeExtraneousCast( newExpr, context.symtab );
[16ba4a6f]1198 return newExpr;
1199 }
[b7d92b96]1200
[18e683b]1201 namespace {
[16ba4a6f]1202 bool structOrUnion( const Candidate & i ) {
1203 const ast::Type * t = i.expr->result->stripReferences();
1204 return dynamic_cast< const ast::StructInstType * >( t ) || dynamic_cast< const ast::UnionInstType * >( t );
1205 }
[99d4584]1206 /// Predicate for "Candidate has integral type"
1207 bool hasIntegralType( const Candidate & i ) {
1208 const ast::Type * type = i.expr->result;
[ef5b828]1209
[99d4584]1210 if ( auto bt = dynamic_cast< const ast::BasicType * >( type ) ) {
1211 return bt->isInteger();
[ef5b828]1212 } else if (
1213 dynamic_cast< const ast::EnumInstType * >( type )
[99d4584]1214 || dynamic_cast< const ast::ZeroType * >( type )
1215 || dynamic_cast< const ast::OneType * >( type )
1216 ) {
1217 return true;
1218 } else return false;
1219 }
1220
1221 /// Resolve `untyped` as an integral expression, returning the resolved version
[ef5b828]1222 ast::ptr< ast::Expr > findIntegralExpression(
[39d8950]1223 const ast::Expr * untyped, const ResolveContext & context
[99d4584]1224 ) {
[39d8950]1225 return findKindExpression( untyped, context, hasIntegralType, "condition" );
[99d4584]1226 }
[60aaa51d]1227
1228 /// check if a type is a character type
1229 bool isCharType( const ast::Type * t ) {
1230 if ( auto bt = dynamic_cast< const ast::BasicType * >( t ) ) {
[ef5b828]1231 return bt->kind == ast::BasicType::Char
1232 || bt->kind == ast::BasicType::SignedChar
[60aaa51d]1233 || bt->kind == ast::BasicType::UnsignedChar;
1234 }
1235 return false;
1236 }
[2773ab8]1237
1238 /// Advance a type itertor to the next mutex parameter
1239 template<typename Iter>
1240 inline bool nextMutex( Iter & it, const Iter & end ) {
[954c954]1241 while ( it != end && ! (*it)->is_mutex() ) { ++it; }
[2773ab8]1242 return it != end;
1243 }
[99d4584]1244 }
1245
[4864a73]1246 class Resolver_new final
1247 : public ast::WithSymbolTable, public ast::WithGuards,
1248 public ast::WithVisitorRef<Resolver_new>, public ast::WithShortCircuiting,
[0e42794]1249 public ast::WithStmtsToAdd<> {
[4864a73]1250
[2a8f0c1]1251 ast::ptr< ast::Type > functionReturn = nullptr;
[2b59f55]1252 ast::CurrentObject currentObject;
[16ba4a6f]1253 // for work previously in GenInit
1254 static InitTweak::ManagedTypes_new managedTypes;
[3bc69f2]1255 ResolveContext context;
[16ba4a6f]1256
[99d4584]1257 bool inEnumDecl = false;
[2a8f0c1]1258
[4864a73]1259 public:
[c15085d]1260 static size_t traceId;
[3bc69f2]1261 Resolver_new( const ast::TranslationGlobal & global ) :
1262 context{ symtab, global } {}
1263 Resolver_new( const ResolveContext & context ) :
1264 ast::WithSymbolTable{ context.symtab },
1265 context{ symtab, context.global } {}
[d76c588]1266
[16ba4a6f]1267 const ast::FunctionDecl * previsit( const ast::FunctionDecl * );
[99d4584]1268 const ast::FunctionDecl * postvisit( const ast::FunctionDecl * );
[16ba4a6f]1269 const ast::ObjectDecl * previsit( const ast::ObjectDecl * );
1270 void previsit( const ast::AggregateDecl * );
1271 void previsit( const ast::StructDecl * );
[99d4584]1272 void previsit( const ast::EnumDecl * );
1273 const ast::StaticAssertDecl * previsit( const ast::StaticAssertDecl * );
1274
[0f6a7752]1275 const ast::ArrayType * previsit( const ast::ArrayType * );
1276 const ast::PointerType * previsit( const ast::PointerType * );
[99d4584]1277
[2773ab8]1278 const ast::ExprStmt * previsit( const ast::ExprStmt * );
1279 const ast::AsmExpr * previsit( const ast::AsmExpr * );
1280 const ast::AsmStmt * previsit( const ast::AsmStmt * );
1281 const ast::IfStmt * previsit( const ast::IfStmt * );
[3bc69f2]1282 const ast::WhileDoStmt * previsit( const ast::WhileDoStmt * );
[2773ab8]1283 const ast::ForStmt * previsit( const ast::ForStmt * );
1284 const ast::SwitchStmt * previsit( const ast::SwitchStmt * );
[400b8be]1285 const ast::CaseClause * previsit( const ast::CaseClause * );
[2773ab8]1286 const ast::BranchStmt * previsit( const ast::BranchStmt * );
1287 const ast::ReturnStmt * previsit( const ast::ReturnStmt * );
1288 const ast::ThrowStmt * previsit( const ast::ThrowStmt * );
[400b8be]1289 const ast::CatchClause * previsit( const ast::CatchClause * );
1290 const ast::CatchClause * postvisit( const ast::CatchClause * );
[2773ab8]1291 const ast::WaitForStmt * previsit( const ast::WaitForStmt * );
[16ba4a6f]1292 const ast::WithStmt * previsit( const ast::WithStmt * );
[99d4584]1293
[2d11663]1294 const ast::SingleInit * previsit( const ast::SingleInit * );
1295 const ast::ListInit * previsit( const ast::ListInit * );
1296 const ast::ConstructorInit * previsit( const ast::ConstructorInit * );
[16ba4a6f]1297
1298 void resolveWithExprs(std::vector<ast::ptr<ast::Expr>> & exprs, std::list<ast::ptr<ast::Stmt>> & stmtsToAdd);
1299
1300 void beginScope() { managedTypes.beginScope(); }
1301 void endScope() { managedTypes.endScope(); }
[e00c22f]1302 bool on_error(ast::ptr<ast::Decl> & decl);
[d76c588]1303 };
[0d070ca]1304 // size_t Resolver_new::traceId = Stats::Heap::new_stacktrace_id("Resolver");
[d76c588]1305
[16ba4a6f]1306 InitTweak::ManagedTypes_new Resolver_new::managedTypes;
1307
[293dc1c]1308 void resolve( ast::TranslationUnit& translationUnit ) {
[3bc69f2]1309 ast::Pass< Resolver_new >::run( translationUnit, translationUnit.global );
[d76c588]1310 }
1311
[ef5b828]1312 ast::ptr< ast::Init > resolveCtorInit(
[39d8950]1313 const ast::ConstructorInit * ctorInit, const ResolveContext & context
[234b1cb]1314 ) {
1315 assert( ctorInit );
[3bc69f2]1316 ast::Pass< Resolver_new > resolver( context );
[234b1cb]1317 return ctorInit->accept( resolver );
1318 }
1319
[302ef2a]1320 const ast::Expr * resolveStmtExpr(
[39d8950]1321 const ast::StmtExpr * stmtExpr, const ResolveContext & context
[17a0ede2]1322 ) {
1323 assert( stmtExpr );
[3bc69f2]1324 ast::Pass< Resolver_new > resolver( context );
[302ef2a]1325 auto ret = mutate(stmtExpr->accept(resolver));
1326 strict_dynamic_cast< ast::StmtExpr * >( ret )->computeResult();
[17a0ede2]1327 return ret;
1328 }
1329
[16ba4a6f]1330 namespace {
[39d8950]1331 const ast::Attribute * handleAttribute(const CodeLocation & loc, const ast::Attribute * attr, const ResolveContext & context) {
[16ba4a6f]1332 std::string name = attr->normalizedName();
1333 if (name == "constructor" || name == "destructor") {
1334 if (attr->params.size() == 1) {
1335 auto arg = attr->params.front();
[39d8950]1336 auto resolved = ResolvExpr::findSingleExpression( arg, new ast::BasicType( ast::BasicType::LongLongSignedInt ), context );
[16ba4a6f]1337 auto result = eval(arg);
1338
1339 auto mutAttr = mutate(attr);
1340 mutAttr->params.front() = resolved;
1341 if (! result.second) {
1342 SemanticWarning(loc, Warning::GccAttributes,
1343 toCString( name, " priorities must be integers from 0 to 65535 inclusive: ", arg ) );
1344 }
1345 else {
1346 auto priority = result.first;
1347 if (priority < 101) {
1348 SemanticWarning(loc, Warning::GccAttributes,
1349 toCString( name, " priorities from 0 to 100 are reserved for the implementation" ) );
1350 } else if (priority < 201 && ! buildingLibrary()) {
1351 SemanticWarning(loc, Warning::GccAttributes,
1352 toCString( name, " priorities from 101 to 200 are reserved for the implementation" ) );
1353 }
1354 }
1355 return mutAttr;
1356 } else if (attr->params.size() > 1) {
1357 SemanticWarning(loc, Warning::GccAttributes, toCString( "too many arguments to ", name, " attribute" ) );
1358 } else {
1359 SemanticWarning(loc, Warning::GccAttributes, toCString( "too few arguments to ", name, " attribute" ) );
1360 }
1361 }
1362 return attr;
1363 }
1364 }
1365
1366 const ast::FunctionDecl * Resolver_new::previsit( const ast::FunctionDecl * functionDecl ) {
[2a8f0c1]1367 GuardValue( functionReturn );
[16ba4a6f]1368
1369 assert (functionDecl->unique());
1370 if (!functionDecl->has_body() && !functionDecl->withExprs.empty()) {
1371 SemanticError(functionDecl->location, functionDecl, "Function without body has with declarations");
1372 }
1373
1374 if (!functionDecl->isTypeFixed) {
1375 auto mutDecl = mutate(functionDecl);
1376 auto mutType = mutDecl->type.get_and_mutate();
1377
1378 for (auto & attr: mutDecl->attributes) {
[3bc69f2]1379 attr = handleAttribute(mutDecl->location, attr, context );
[16ba4a6f]1380 }
1381
[3e5dd913]1382 // handle assertions
[16ba4a6f]1383
1384 symtab.enterScope();
[3e5dd913]1385 mutType->forall.clear();
1386 mutType->assertions.clear();
1387 for (auto & typeParam : mutDecl->type_params) {
1388 symtab.addType(typeParam);
[b230091]1389 mutType->forall.emplace_back(new ast::TypeInstType(typeParam));
[3e5dd913]1390 }
1391 for (auto & asst : mutDecl->assertions) {
[3bc69f2]1392 asst = fixObjectType(asst.strict_as<ast::ObjectDecl>(), context);
[3e5dd913]1393 symtab.addId(asst);
1394 mutType->assertions.emplace_back(new ast::VariableExpr(functionDecl->location, asst));
[16ba4a6f]1395 }
1396
1397 // temporarily adds params to symbol table.
1398 // actual scoping rules for params and withexprs differ - see Pass::visit(FunctionDecl)
1399
1400 std::vector<ast::ptr<ast::Type>> paramTypes;
1401 std::vector<ast::ptr<ast::Type>> returnTypes;
1402
1403 for (auto & param : mutDecl->params) {
[3bc69f2]1404 param = fixObjectType(param.strict_as<ast::ObjectDecl>(), context);
[16ba4a6f]1405 symtab.addId(param);
1406 paramTypes.emplace_back(param->get_type());
1407 }
1408 for (auto & ret : mutDecl->returns) {
[3bc69f2]1409 ret = fixObjectType(ret.strict_as<ast::ObjectDecl>(), context);
[16ba4a6f]1410 returnTypes.emplace_back(ret->get_type());
1411 }
1412 // since function type in decl is just a view of param types, need to update that as well
1413 mutType->params = std::move(paramTypes);
1414 mutType->returns = std::move(returnTypes);
1415
[3e5dd913]1416 auto renamedType = strict_dynamic_cast<const ast::FunctionType *>(renameTyVars(mutType, RenameMode::GEN_EXPR_ID));
1417
[16ba4a6f]1418 std::list<ast::ptr<ast::Stmt>> newStmts;
1419 resolveWithExprs (mutDecl->withExprs, newStmts);
1420
1421 if (mutDecl->stmts) {
1422 auto mutStmt = mutDecl->stmts.get_and_mutate();
1423 mutStmt->kids.splice(mutStmt->kids.begin(), std::move(newStmts));
1424 mutDecl->stmts = mutStmt;
1425 }
1426
1427 symtab.leaveScope();
1428
[3e5dd913]1429 mutDecl->type = renamedType;
[16ba4a6f]1430 mutDecl->mangleName = Mangle::mangle(mutDecl);
1431 mutDecl->isTypeFixed = true;
1432 functionDecl = mutDecl;
1433 }
1434 managedTypes.handleDWT(functionDecl);
1435
[2a8f0c1]1436 functionReturn = extractResultType( functionDecl->type );
[16ba4a6f]1437 return functionDecl;
[d76c588]1438 }
1439
[2a8f0c1]1440 const ast::FunctionDecl * Resolver_new::postvisit( const ast::FunctionDecl * functionDecl ) {
[4864a73]1441 // default value expressions have an environment which shouldn't be there and trips up
[2a8f0c1]1442 // later passes.
[e068c8a]1443 assert( functionDecl->unique() );
1444 ast::FunctionType * mutType = mutate( functionDecl->type.get() );
1445
1446 for ( unsigned i = 0 ; i < mutType->params.size() ; ++i ) {
1447 if ( const ast::ObjectDecl * obj = mutType->params[i].as< ast::ObjectDecl >() ) {
1448 if ( const ast::SingleInit * init = obj->init.as< ast::SingleInit >() ) {
1449 if ( init->value->env == nullptr ) continue;
1450 // clone initializer minus the initializer environment
1451 auto mutParam = mutate( mutType->params[i].strict_as< ast::ObjectDecl >() );
1452 auto mutInit = mutate( mutParam->init.strict_as< ast::SingleInit >() );
1453 auto mutValue = mutate( mutInit->value.get() );
1454
1455 mutValue->env = nullptr;
1456 mutInit->value = mutValue;
1457 mutParam->init = mutInit;
1458 mutType->params[i] = mutParam;
1459
1460 assert( ! mutType->params[i].strict_as< ast::ObjectDecl >()->init.strict_as< ast::SingleInit >()->value->env);
1461 }
1462 }
[2a8f0c1]1463 }
[73973b6]1464 mutate_field(functionDecl, &ast::FunctionDecl::type, mutType);
1465 return functionDecl;
[d76c588]1466 }
1467
[16ba4a6f]1468 const ast::ObjectDecl * Resolver_new::previsit( const ast::ObjectDecl * objectDecl ) {
[ef5b828]1469 // To handle initialization of routine pointers [e.g. int (*fp)(int) = foo()],
1470 // class-variable `initContext` is changed multiple times because the LHS is analyzed
1471 // twice. The second analysis changes `initContext` because a function type can contain
1472 // object declarations in the return and parameter types. Therefore each value of
1473 // `initContext` is retained so the type on the first analysis is preserved and used for
[b7d92b96]1474 // selecting the RHS.
1475 GuardValue( currentObject );
[16ba4a6f]1476
[b7d92b96]1477 if ( inEnumDecl && dynamic_cast< const ast::EnumInstType * >( objectDecl->get_type() ) ) {
[ef5b828]1478 // enumerator initializers should not use the enum type to initialize, since the
[b7d92b96]1479 // enum type is still incomplete at this point. Use `int` instead.
[4559b34]1480
[12df6fe]1481 if ( auto enumBase = dynamic_cast< const ast::EnumInstType * >
1482 ( objectDecl->get_type() )->base->base ) {
[5bb1ac1]1483 objectDecl = fixObjectType( objectDecl, context );
1484 currentObject = ast::CurrentObject{
1485 objectDecl->location,
1486 enumBase
1487 };
[4559b34]1488 } else {
[5bb1ac1]1489 objectDecl = fixObjectType( objectDecl, context );
[4559b34]1490 currentObject = ast::CurrentObject{
1491 objectDecl->location, new ast::BasicType{ ast::BasicType::SignedInt } };
1492 }
1493
[b7d92b96]1494 }
[16ba4a6f]1495 else {
[12df6fe]1496 if ( !objectDecl->isTypeFixed ) {
[3bc69f2]1497 auto newDecl = fixObjectType(objectDecl, context);
[16ba4a6f]1498 auto mutDecl = mutate(newDecl);
[4a8f150]1499
[16ba4a6f]1500 // generate CtorInit wrapper when necessary.
1501 // in certain cases, fixObjectType is called before reaching
1502 // this object in visitor pass, thus disabling CtorInit codegen.
1503 // this happens on aggregate members and function parameters.
1504 if ( InitTweak::tryConstruct( mutDecl ) && ( managedTypes.isManaged( mutDecl ) || ((! isInFunction() || mutDecl->storage.is_static ) && ! InitTweak::isConstExpr( mutDecl->init ) ) ) ) {
1505 // constructed objects cannot be designated
1506 if ( InitTweak::isDesignated( mutDecl->init ) ) SemanticError( mutDecl, "Cannot include designations in the initializer for a managed Object. If this is really what you want, then initialize with @=.\n" );
1507 // constructed objects should not have initializers nested too deeply
1508 if ( ! InitTweak::checkInitDepth( mutDecl ) ) SemanticError( mutDecl, "Managed object's initializer is too deep " );
1509
1510 mutDecl->init = InitTweak::genCtorInit( mutDecl->location, mutDecl );
1511 }
1512
1513 objectDecl = mutDecl;
1514 }
1515 currentObject = ast::CurrentObject{ objectDecl->location, objectDecl->get_type() };
1516 }
[4a8f150]1517
[16ba4a6f]1518 return objectDecl;
1519 }
1520
1521 void Resolver_new::previsit( const ast::AggregateDecl * _aggDecl ) {
1522 auto aggDecl = mutate(_aggDecl);
1523 assertf(aggDecl == _aggDecl, "type declarations must be unique");
1524
1525 for (auto & member: aggDecl->members) {
1526 // nested type decls are hoisted already. no need to do anything
1527 if (auto obj = member.as<ast::ObjectDecl>()) {
[3bc69f2]1528 member = fixObjectType(obj, context);
[16ba4a6f]1529 }
1530 }
1531 }
1532
1533 void Resolver_new::previsit( const ast::StructDecl * structDecl ) {
1534 previsit(static_cast<const ast::AggregateDecl *>(structDecl));
1535 managedTypes.handleStruct(structDecl);
[d76c588]1536 }
1537
[99d4584]1538 void Resolver_new::previsit( const ast::EnumDecl * ) {
1539 // in case we decide to allow nested enums
1540 GuardValue( inEnumDecl );
[2890212]1541 inEnumDecl = true;
[16ba4a6f]1542 // don't need to fix types for enum fields
[d76c588]1543 }
1544
[ef5b828]1545 const ast::StaticAssertDecl * Resolver_new::previsit(
1546 const ast::StaticAssertDecl * assertDecl
[99d4584]1547 ) {
[ef5b828]1548 return ast::mutate_field(
1549 assertDecl, &ast::StaticAssertDecl::cond,
[3bc69f2]1550 findIntegralExpression( assertDecl->cond, context ) );
[b7d92b96]1551 }
1552
1553 template< typename PtrType >
[39d8950]1554 const PtrType * handlePtrType( const PtrType * type, const ResolveContext & context ) {
[0f6a7752]1555 if ( type->dimension ) {
[5cf1228]1556 const ast::Type * sizeType = context.global.sizeType.get();
[9e23b446]1557 ast::ptr< ast::Expr > dimension = findSingleExpression( type->dimension, sizeType, context );
1558 assertf(dimension->env->empty(), "array dimension expr has nonempty env");
1559 dimension.get_and_mutate()->env = nullptr;
[5cf1228]1560 ast::mutate_field( type, &PtrType::dimension, dimension );
[0f6a7752]1561 }
1562 return type;
[d76c588]1563 }
1564
[0f6a7752]1565 const ast::ArrayType * Resolver_new::previsit( const ast::ArrayType * at ) {
[3bc69f2]1566 return handlePtrType( at, context );
[d76c588]1567 }
1568
[0f6a7752]1569 const ast::PointerType * Resolver_new::previsit( const ast::PointerType * pt ) {
[3bc69f2]1570 return handlePtrType( pt, context );
[d76c588]1571 }
1572
[b7d92b96]1573 const ast::ExprStmt * Resolver_new::previsit( const ast::ExprStmt * exprStmt ) {
1574 visit_children = false;
1575 assertf( exprStmt->expr, "ExprStmt has null expression in resolver" );
[ef5b828]1576
1577 return ast::mutate_field(
[3bc69f2]1578 exprStmt, &ast::ExprStmt::expr, findVoidExpression( exprStmt->expr, context ) );
[d76c588]1579 }
1580
[b7d92b96]1581 const ast::AsmExpr * Resolver_new::previsit( const ast::AsmExpr * asmExpr ) {
1582 visit_children = false;
1583
[ef5b828]1584 asmExpr = ast::mutate_field(
[3bc69f2]1585 asmExpr, &ast::AsmExpr::operand, findVoidExpression( asmExpr->operand, context ) );
[ef5b828]1586
[b7d92b96]1587 return asmExpr;
[d76c588]1588 }
1589
[2b59f55]1590 const ast::AsmStmt * Resolver_new::previsit( const ast::AsmStmt * asmStmt ) {
1591 visitor->maybe_accept( asmStmt, &ast::AsmStmt::input );
1592 visitor->maybe_accept( asmStmt, &ast::AsmStmt::output );
1593 visit_children = false;
1594 return asmStmt;
[d76c588]1595 }
1596
[b7d92b96]1597 const ast::IfStmt * Resolver_new::previsit( const ast::IfStmt * ifStmt ) {
1598 return ast::mutate_field(
[3bc69f2]1599 ifStmt, &ast::IfStmt::cond, findIntegralExpression( ifStmt->cond, context ) );
[d76c588]1600 }
1601
[3b0bc16]1602 const ast::WhileDoStmt * Resolver_new::previsit( const ast::WhileDoStmt * whileDoStmt ) {
[ef5b828]1603 return ast::mutate_field(
[3bc69f2]1604 whileDoStmt, &ast::WhileDoStmt::cond, findIntegralExpression( whileDoStmt->cond, context ) );
[d76c588]1605 }
1606
[b7d92b96]1607 const ast::ForStmt * Resolver_new::previsit( const ast::ForStmt * forStmt ) {
1608 if ( forStmt->cond ) {
1609 forStmt = ast::mutate_field(
[3bc69f2]1610 forStmt, &ast::ForStmt::cond, findIntegralExpression( forStmt->cond, context ) );
[b7d92b96]1611 }
1612
1613 if ( forStmt->inc ) {
1614 forStmt = ast::mutate_field(
[3bc69f2]1615 forStmt, &ast::ForStmt::inc, findVoidExpression( forStmt->inc, context ) );
[b7d92b96]1616 }
1617
1618 return forStmt;
[d76c588]1619 }
1620
[b7d92b96]1621 const ast::SwitchStmt * Resolver_new::previsit( const ast::SwitchStmt * switchStmt ) {
1622 GuardValue( currentObject );
1623 switchStmt = ast::mutate_field(
[ef5b828]1624 switchStmt, &ast::SwitchStmt::cond,
[3bc69f2]1625 findIntegralExpression( switchStmt->cond, context ) );
[2b59f55]1626 currentObject = ast::CurrentObject{ switchStmt->location, switchStmt->cond->result };
[b7d92b96]1627 return switchStmt;
[d76c588]1628 }
1629
[400b8be]1630 const ast::CaseClause * Resolver_new::previsit( const ast::CaseClause * caseStmt ) {
[b7d92b96]1631 if ( caseStmt->cond ) {
[60aaa51d]1632 std::deque< ast::InitAlternative > initAlts = currentObject.getOptions();
[2b59f55]1633 assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral "
1634 "expression." );
[ef5b828]1635
1636 ast::ptr< ast::Expr > untyped =
[2b59f55]1637 new ast::CastExpr{ caseStmt->location, caseStmt->cond, initAlts.front().type };
[3bc69f2]1638 ast::ptr< ast::Expr > newExpr = findSingleExpression( untyped, context );
[ef5b828]1639
1640 // case condition cannot have a cast in C, so it must be removed here, regardless of
[2b59f55]1641 // whether it would perform a conversion.
1642 if ( const ast::CastExpr * castExpr = newExpr.as< ast::CastExpr >() ) {
[60aaa51d]1643 swap_and_save_env( newExpr, castExpr->arg );
[2b59f55]1644 }
[ef5b828]1645
[400b8be]1646 caseStmt = ast::mutate_field( caseStmt, &ast::CaseClause::cond, newExpr );
[b7d92b96]1647 }
1648 return caseStmt;
[d76c588]1649 }
1650
[b7d92b96]1651 const ast::BranchStmt * Resolver_new::previsit( const ast::BranchStmt * branchStmt ) {
1652 visit_children = false;
1653 // must resolve the argument of a computed goto
1654 if ( branchStmt->kind == ast::BranchStmt::Goto && branchStmt->computedTarget ) {
1655 // computed goto argument is void*
[2773ab8]1656 ast::ptr< ast::Type > target = new ast::PointerType{ new ast::VoidType{} };
[b7d92b96]1657 branchStmt = ast::mutate_field(
[ef5b828]1658 branchStmt, &ast::BranchStmt::computedTarget,
[3bc69f2]1659 findSingleExpression( branchStmt->computedTarget, target, context ) );
[b7d92b96]1660 }
1661 return branchStmt;
[d76c588]1662 }
1663
[2b59f55]1664 const ast::ReturnStmt * Resolver_new::previsit( const ast::ReturnStmt * returnStmt ) {
1665 visit_children = false;
1666 if ( returnStmt->expr ) {
1667 returnStmt = ast::mutate_field(
[ef5b828]1668 returnStmt, &ast::ReturnStmt::expr,
[3bc69f2]1669 findSingleExpression( returnStmt->expr, functionReturn, context ) );
[2b59f55]1670 }
1671 return returnStmt;
[d76c588]1672 }
1673
[2b59f55]1674 const ast::ThrowStmt * Resolver_new::previsit( const ast::ThrowStmt * throwStmt ) {
1675 visit_children = false;
1676 if ( throwStmt->expr ) {
[ef5b828]1677 const ast::StructDecl * exceptionDecl =
[3090127]1678 symtab.lookupStruct( "__cfaehm_base_exception_t" );
[2b59f55]1679 assert( exceptionDecl );
[ef5b828]1680 ast::ptr< ast::Type > exceptType =
[2b59f55]1681 new ast::PointerType{ new ast::StructInstType{ exceptionDecl } };
1682 throwStmt = ast::mutate_field(
[ef5b828]1683 throwStmt, &ast::ThrowStmt::expr,
[3bc69f2]1684 findSingleExpression( throwStmt->expr, exceptType, context ) );
[2b59f55]1685 }
1686 return throwStmt;
[d76c588]1687 }
1688
[400b8be]1689 const ast::CatchClause * Resolver_new::previsit( const ast::CatchClause * catchClause ) {
[3b0bc16]1690 // Until we are very sure this invarent (ifs that move between passes have then)
[b9fa85b]1691 // holds, check it. This allows a check for when to decode the mangling.
[400b8be]1692 if ( auto ifStmt = catchClause->body.as<ast::IfStmt>() ) {
[3b0bc16]1693 assert( ifStmt->then );
[b9fa85b]1694 }
1695 // Encode the catchStmt so the condition can see the declaration.
[400b8be]1696 if ( catchClause->cond ) {
1697 ast::CatchClause * clause = mutate( catchClause );
1698 clause->body = new ast::IfStmt( clause->location, clause->cond, nullptr, clause->body );
1699 clause->cond = nullptr;
1700 return clause;
[b9fa85b]1701 }
[400b8be]1702 return catchClause;
[b9fa85b]1703 }
1704
[400b8be]1705 const ast::CatchClause * Resolver_new::postvisit( const ast::CatchClause * catchClause ) {
[b9fa85b]1706 // Decode the catchStmt so everything is stored properly.
[400b8be]1707 const ast::IfStmt * ifStmt = catchClause->body.as<ast::IfStmt>();
[3b0bc16]1708 if ( nullptr != ifStmt && nullptr == ifStmt->then ) {
[b9fa85b]1709 assert( ifStmt->cond );
[3b0bc16]1710 assert( ifStmt->else_ );
[400b8be]1711 ast::CatchClause * clause = ast::mutate( catchClause );
1712 clause->cond = ifStmt->cond;
1713 clause->body = ifStmt->else_;
[b9fa85b]1714 // ifStmt should be implicately deleted here.
[400b8be]1715 return clause;
[2b59f55]1716 }
[400b8be]1717 return catchClause;
[d76c588]1718 }
1719
[2773ab8]1720 const ast::WaitForStmt * Resolver_new::previsit( const ast::WaitForStmt * stmt ) {
1721 visit_children = false;
1722
1723 // Resolve all clauses first
1724 for ( unsigned i = 0; i < stmt->clauses.size(); ++i ) {
[f6e6a55]1725 const ast::WaitForClause & clause = *stmt->clauses[i];
[2773ab8]1726
1727 ast::TypeEnvironment env;
[3bc69f2]1728 CandidateFinder funcFinder( context, env );
[2773ab8]1729
1730 // Find all candidates for a function in canonical form
[f6e6a55]1731 funcFinder.find( clause.target_func, ResolvMode::withAdjustment() );
[2773ab8]1732
1733 if ( funcFinder.candidates.empty() ) {
1734 stringstream ss;
1735 ss << "Use of undeclared indentifier '";
[f6e6a55]1736 ss << clause.target_func.strict_as< ast::NameExpr >()->name;
[2773ab8]1737 ss << "' in call to waitfor";
1738 SemanticError( stmt->location, ss.str() );
1739 }
1740
[f6e6a55]1741 if ( clause.target_args.empty() ) {
[ef5b828]1742 SemanticError( stmt->location,
[2773ab8]1743 "Waitfor clause must have at least one mutex parameter");
1744 }
1745
1746 // Find all alternatives for all arguments in canonical form
[ef5b828]1747 std::vector< CandidateFinder > argFinders =
[f6e6a55]1748 funcFinder.findSubExprs( clause.target_args );
[ef5b828]1749
[2773ab8]1750 // List all combinations of arguments
1751 std::vector< CandidateList > possibilities;
1752 combos( argFinders.begin(), argFinders.end(), back_inserter( possibilities ) );
1753
1754 // For every possible function:
[ef5b828]1755 // * try matching the arguments to the parameters, not the other way around because
[2773ab8]1756 // more arguments than parameters
1757 CandidateList funcCandidates;
1758 std::vector< CandidateList > argsCandidates;
1759 SemanticErrorException errors;
1760 for ( CandidateRef & func : funcFinder.candidates ) {
1761 try {
[ef5b828]1762 auto pointerType = dynamic_cast< const ast::PointerType * >(
[2773ab8]1763 func->expr->result->stripReferences() );
1764 if ( ! pointerType ) {
[ef5b828]1765 SemanticError( stmt->location, func->expr->result.get(),
[2773ab8]1766 "candidate not viable: not a pointer type\n" );
1767 }
1768
1769 auto funcType = pointerType->base.as< ast::FunctionType >();
1770 if ( ! funcType ) {
[ef5b828]1771 SemanticError( stmt->location, func->expr->result.get(),
[2773ab8]1772 "candidate not viable: not a function type\n" );
1773 }
1774
1775 {
1776 auto param = funcType->params.begin();
1777 auto paramEnd = funcType->params.end();
1778
1779 if( ! nextMutex( param, paramEnd ) ) {
[ef5b828]1780 SemanticError( stmt->location, funcType,
[2773ab8]1781 "candidate function not viable: no mutex parameters\n");
1782 }
1783 }
1784
1785 CandidateRef func2{ new Candidate{ *func } };
1786 // strip reference from function
1787 func2->expr = referenceToRvalueConversion( func->expr, func2->cost );
1788
1789 // Each argument must be matched with a parameter of the current candidate
1790 for ( auto & argsList : possibilities ) {
1791 try {
1792 // Declare data structures needed for resolution
1793 ast::OpenVarSet open;
1794 ast::AssertionSet need, have;
1795 ast::TypeEnvironment resultEnv{ func->env };
[ef5b828]1796 // Add all type variables as open so that those not used in the
[2773ab8]1797 // parameter list are still considered open
1798 resultEnv.add( funcType->forall );
1799
1800 // load type variables from arguments into one shared space
1801 for ( auto & arg : argsList ) {
1802 resultEnv.simpleCombine( arg->env );
1803 }
1804
1805 // Make sure we don't widen any existing bindings
1806 resultEnv.forbidWidening();
1807
1808 // Find any unbound type variables
1809 resultEnv.extractOpenVars( open );
1810
1811 auto param = funcType->params.begin();
1812 auto paramEnd = funcType->params.end();
1813
1814 unsigned n_mutex_param = 0;
1815
[ef5b828]1816 // For every argument of its set, check if it matches one of the
[2773ab8]1817 // parameters. The order is important
1818 for ( auto & arg : argsList ) {
1819 // Ignore non-mutex arguments
1820 if ( ! nextMutex( param, paramEnd ) ) {
1821 // We ran out of parameters but still have arguments.
1822 // This function doesn't match
[ef5b828]1823 SemanticError( stmt->location, funcType,
[2773ab8]1824 toString("candidate function not viable: too many mutex "
1825 "arguments, expected ", n_mutex_param, "\n" ) );
1826 }
1827
1828 ++n_mutex_param;
1829
[ef5b828]1830 // Check if the argument matches the parameter type in the current
[2773ab8]1831 // scope
[954c954]1832 // ast::ptr< ast::Type > paramType = (*param)->get_type();
[ef5b828]1833 if (
1834 ! unify(
[954c954]1835 arg->expr->result, *param, resultEnv, need, have, open,
[ef5b828]1836 symtab )
[2773ab8]1837 ) {
1838 // Type doesn't match
1839 stringstream ss;
1840 ss << "candidate function not viable: no known conversion "
1841 "from '";
[954c954]1842 ast::print( ss, *param );
[2773ab8]1843 ss << "' to '";
1844 ast::print( ss, arg->expr->result );
1845 ss << "' with env '";
1846 ast::print( ss, resultEnv );
1847 ss << "'\n";
1848 SemanticError( stmt->location, funcType, ss.str() );
1849 }
1850
1851 ++param;
1852 }
1853
1854 // All arguments match!
1855
1856 // Check if parameters are missing
1857 if ( nextMutex( param, paramEnd ) ) {
1858 do {
1859 ++n_mutex_param;
1860 ++param;
1861 } while ( nextMutex( param, paramEnd ) );
1862
[ef5b828]1863 // We ran out of arguments but still have parameters left; this
[2773ab8]1864 // function doesn't match
[ef5b828]1865 SemanticError( stmt->location, funcType,
[2773ab8]1866 toString( "candidate function not viable: too few mutex "
1867 "arguments, expected ", n_mutex_param, "\n" ) );
1868 }
1869
1870 // All parameters match!
1871
1872 // Finish the expressions to tie in proper environments
1873 finishExpr( func2->expr, resultEnv );
1874 for ( CandidateRef & arg : argsList ) {
1875 finishExpr( arg->expr, resultEnv );
1876 }
1877
1878 // This is a match, store it and save it for later
1879 funcCandidates.emplace_back( std::move( func2 ) );
1880 argsCandidates.emplace_back( std::move( argsList ) );
1881
1882 } catch ( SemanticErrorException & e ) {
1883 errors.append( e );
1884 }
1885 }
1886 } catch ( SemanticErrorException & e ) {
1887 errors.append( e );
1888 }
1889 }
1890
1891 // Make sure correct number of arguments
1892 if( funcCandidates.empty() ) {
[ef5b828]1893 SemanticErrorException top( stmt->location,
[2773ab8]1894 "No alternatives for function in call to waitfor" );
1895 top.append( errors );
1896 throw top;
1897 }
1898
1899 if( argsCandidates.empty() ) {
[ef5b828]1900 SemanticErrorException top( stmt->location,
1901 "No alternatives for arguments in call to waitfor" );
[2773ab8]1902 top.append( errors );
1903 throw top;
1904 }
1905
1906 if( funcCandidates.size() > 1 ) {
[ef5b828]1907 SemanticErrorException top( stmt->location,
[2773ab8]1908 "Ambiguous function in call to waitfor" );
1909 top.append( errors );
1910 throw top;
1911 }
1912 if( argsCandidates.size() > 1 ) {
1913 SemanticErrorException top( stmt->location,
1914 "Ambiguous arguments in call to waitfor" );
1915 top.append( errors );
1916 throw top;
1917 }
1918 // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
1919
1920 // build new clause
[f6e6a55]1921 auto clause2 = new ast::WaitForClause( clause.location );
[ef5b828]1922
[f6e6a55]1923 clause2->target_func = funcCandidates.front()->expr;
[ef5b828]1924
[f6e6a55]1925 clause2->target_args.reserve( clause.target_args.size() );
[6668a3e]1926 const ast::StructDecl * decl_monitor = symtab.lookupStruct( "monitor$" );
[2773ab8]1927 for ( auto arg : argsCandidates.front() ) {
[6668a3e]1928 const auto & loc = stmt->location;
1929
1930 ast::Expr * init = new ast::CastExpr( loc,
1931 new ast::UntypedExpr( loc,
1932 new ast::NameExpr( loc, "get_monitor" ),
1933 { arg->expr }
1934 ),
1935 new ast::PointerType(
1936 new ast::StructInstType(
1937 decl_monitor
1938 )
1939 )
1940 );
1941
[f6e6a55]1942 clause2->target_args.emplace_back( findSingleExpression( init, context ) );
[2773ab8]1943 }
1944
1945 // Resolve the conditions as if it were an IfStmt, statements normally
[f6e6a55]1946 clause2->cond = findSingleExpression( clause.cond, context );
1947 clause2->stmt = clause.stmt->accept( *visitor );
[2773ab8]1948
1949 // set results into stmt
1950 auto n = mutate( stmt );
[f6e6a55]1951 n->clauses[i] = clause2;
[2773ab8]1952 stmt = n;
1953 }
1954
[f6e6a55]1955 if ( stmt->timeout_stmt ) {
[2773ab8]1956 // resolve the timeout as a size_t, the conditions like IfStmt, and stmts normally
[ef5b828]1957 ast::ptr< ast::Type > target =
[2773ab8]1958 new ast::BasicType{ ast::BasicType::LongLongUnsignedInt };
[f6e6a55]1959 auto timeout_time = findSingleExpression( stmt->timeout_time, target, context );
1960 auto timeout_cond = findSingleExpression( stmt->timeout_cond, context );
1961 auto timeout_stmt = stmt->timeout_stmt->accept( *visitor );
[2773ab8]1962
1963 // set results into stmt
1964 auto n = mutate( stmt );
[f6e6a55]1965 n->timeout_time = std::move( timeout_time );
1966 n->timeout_cond = std::move( timeout_cond );
1967 n->timeout_stmt = std::move( timeout_stmt );
[2773ab8]1968 stmt = n;
1969 }
1970
[f6e6a55]1971 if ( stmt->else_stmt ) {
[2773ab8]1972 // resolve the condition like IfStmt, stmts normally
[f6e6a55]1973 auto else_cond = findSingleExpression( stmt->else_cond, context );
1974 auto else_stmt = stmt->else_stmt->accept( *visitor );
[2773ab8]1975
1976 // set results into stmt
1977 auto n = mutate( stmt );
[f6e6a55]1978 n->else_cond = std::move( else_cond );
1979 n->else_stmt = std::move( else_stmt );
[2773ab8]1980 stmt = n;
1981 }
1982
1983 return stmt;
[d76c588]1984 }
1985
[16ba4a6f]1986 const ast::WithStmt * Resolver_new::previsit( const ast::WithStmt * withStmt ) {
1987 auto mutStmt = mutate(withStmt);
1988 resolveWithExprs(mutStmt->exprs, stmtsToAddBefore);
1989 return mutStmt;
1990 }
1991
1992 void Resolver_new::resolveWithExprs(std::vector<ast::ptr<ast::Expr>> & exprs, std::list<ast::ptr<ast::Stmt>> & stmtsToAdd) {
1993 for (auto & expr : exprs) {
1994 // only struct- and union-typed expressions are viable candidates
[3bc69f2]1995 expr = findKindExpression( expr, context, structOrUnion, "with expression" );
[16ba4a6f]1996
1997 // if with expression might be impure, create a temporary so that it is evaluated once
1998 if ( Tuples::maybeImpure( expr ) ) {
1999 static UniqueName tmpNamer( "_with_tmp_" );
2000 const CodeLocation loc = expr->location;
2001 auto tmp = new ast::ObjectDecl(loc, tmpNamer.newName(), expr->result, new ast::SingleInit(loc, expr ) );
2002 expr = new ast::VariableExpr( loc, tmp );
2003 stmtsToAdd.push_back( new ast::DeclStmt(loc, tmp ) );
2004 if ( InitTweak::isConstructable( tmp->type ) ) {
2005 // generate ctor/dtor and resolve them
2006 tmp->init = InitTweak::genCtorInit( loc, tmp );
2007 }
2008 // since tmp is freshly created, this should modify tmp in-place
2009 tmp->accept( *visitor );
2010 }
[9e23b446]2011 else if (expr->env && expr->env->empty()) {
2012 expr = ast::mutate_field(expr.get(), &ast::Expr::env, nullptr);
2013 }
[16ba4a6f]2014 }
2015 }
[60aaa51d]2016
2017
2018 const ast::SingleInit * Resolver_new::previsit( const ast::SingleInit * singleInit ) {
2019 visit_children = false;
[ef5b828]2020 // resolve initialization using the possibilities as determined by the `currentObject`
[60aaa51d]2021 // cursor.
[ef5b828]2022 ast::ptr< ast::Expr > untyped = new ast::UntypedInitExpr{
[60aaa51d]2023 singleInit->location, singleInit->value, currentObject.getOptions() };
[3bc69f2]2024 ast::ptr<ast::Expr> newExpr = findSingleExpression( untyped, context );
[60aaa51d]2025 const ast::InitExpr * initExpr = newExpr.strict_as< ast::InitExpr >();
2026
2027 // move cursor to the object that is actually initialized
2028 currentObject.setNext( initExpr->designation );
2029
2030 // discard InitExpr wrapper and retain relevant pieces.
[ef5b828]2031 // `initExpr` may have inferred params in the case where the expression specialized a
2032 // function pointer, and newExpr may already have inferParams of its own, so a simple
[60aaa51d]2033 // swap is not sufficient
2034 ast::Expr::InferUnion inferred = initExpr->inferred;
2035 swap_and_save_env( newExpr, initExpr->expr );
2036 newExpr.get_and_mutate()->inferred.splice( std::move(inferred) );
2037
[ef5b828]2038 // get the actual object's type (may not exactly match what comes back from the resolver
[60aaa51d]2039 // due to conversions)
2040 const ast::Type * initContext = currentObject.getCurrentType();
2041
2042 removeExtraneousCast( newExpr, symtab );
2043
2044 // check if actual object's type is char[]
2045 if ( auto at = dynamic_cast< const ast::ArrayType * >( initContext ) ) {
2046 if ( isCharType( at->base ) ) {
2047 // check if the resolved type is char*
2048 if ( auto pt = newExpr->result.as< ast::PointerType >() ) {
2049 if ( isCharType( pt->base ) ) {
[ef5b828]2050 // strip cast if we're initializing a char[] with a char*
[60aaa51d]2051 // e.g. char x[] = "hello"
2052 if ( auto ce = newExpr.as< ast::CastExpr >() ) {
2053 swap_and_save_env( newExpr, ce->arg );
2054 }
2055 }
2056 }
2057 }
2058 }
2059
2060 // move cursor to next object in preparation for next initializer
2061 currentObject.increment();
2062
2063 // set initializer expression to resolved expression
2064 return ast::mutate_field( singleInit, &ast::SingleInit::value, std::move(newExpr) );
[d76c588]2065 }
2066
[60aaa51d]2067 const ast::ListInit * Resolver_new::previsit( const ast::ListInit * listInit ) {
2068 // move cursor into brace-enclosed initializer-list
2069 currentObject.enterListInit( listInit->location );
2070
2071 assert( listInit->designations.size() == listInit->initializers.size() );
2072 for ( unsigned i = 0; i < listInit->designations.size(); ++i ) {
[ef5b828]2073 // iterate designations and initializers in pairs, moving the cursor to the current
[60aaa51d]2074 // designated object and resolving the initializer against that object
[2d11663]2075 listInit = ast::mutate_field_index(
[ef5b828]2076 listInit, &ast::ListInit::designations, i,
[2d11663]2077 currentObject.findNext( listInit->designations[i] ) );
2078 listInit = ast::mutate_field_index(
2079 listInit, &ast::ListInit::initializers, i,
2080 listInit->initializers[i]->accept( *visitor ) );
[60aaa51d]2081 }
2082
[2d11663]2083 // move cursor out of brace-enclosed initializer-list
2084 currentObject.exitListInit();
2085
[60aaa51d]2086 visit_children = false;
2087 return listInit;
[d76c588]2088 }
2089
[2d11663]2090 const ast::ConstructorInit * Resolver_new::previsit( const ast::ConstructorInit * ctorInit ) {
2091 visitor->maybe_accept( ctorInit, &ast::ConstructorInit::ctor );
2092 visitor->maybe_accept( ctorInit, &ast::ConstructorInit::dtor );
2093
2094 // found a constructor - can get rid of C-style initializer
2095 // xxx - Rob suggests this field is dead code
2096 ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::init, nullptr );
2097
[ef5b828]2098 // intrinsic single-parameter constructors and destructors do nothing. Since this was
2099 // implicitly generated, there's no way for it to have side effects, so get rid of it to
[2d11663]2100 // clean up generated code
2101 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
2102 ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::ctor, nullptr );
2103 }
2104 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
2105 ctorInit = ast::mutate_field( ctorInit, &ast::ConstructorInit::dtor, nullptr );
2106 }
2107
2108 return ctorInit;
[d76c588]2109 }
2110
[0dd9a5e]2111 // suppress error on autogen functions and mark invalid autogen as deleted.
[e00c22f]2112 bool Resolver_new::on_error(ast::ptr<ast::Decl> & decl) {
[0dd9a5e]2113 if (auto functionDecl = decl.as<ast::FunctionDecl>()) {
2114 // xxx - can intrinsic gen ever fail?
[6668a3e]2115 if (functionDecl->linkage == ast::Linkage::AutoGen) {
[0dd9a5e]2116 auto mutDecl = mutate(functionDecl);
2117 mutDecl->isDeleted = true;
2118 mutDecl->stmts = nullptr;
2119 decl = mutDecl;
2120 return false;
2121 }
2122 }
2123 return true;
2124 }
2125
[51b73452]2126} // namespace ResolvExpr
[a32b204]2127
2128// Local Variables: //
2129// tab-width: 4 //
2130// mode: c++ //
2131// compile-command: "make install" //
2132// End: //
Note: See TracBrowser for help on using the repository browser.