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 | // Resolver.cc -- |
---|
8 | // |
---|
9 | // Author : Aaron B. Moss |
---|
10 | // Created On : Sun May 17 12:17:01 2015 |
---|
11 | // Last Modified By : Aaron B. Moss |
---|
12 | // Last Modified On : Wed May 29 11:00:00 2019 |
---|
13 | // Update Count : 241 |
---|
14 | // |
---|
15 | |
---|
16 | #include <cassert> // for strict_dynamic_cast, assert |
---|
17 | #include <memory> // for allocator, allocator_traits<... |
---|
18 | #include <tuple> // for get |
---|
19 | #include <vector> // for vector |
---|
20 | |
---|
21 | #include "Alternative.h" // for Alternative, AltList |
---|
22 | #include "AlternativeFinder.h" // for AlternativeFinder, resolveIn... |
---|
23 | #include "Candidate.hpp" |
---|
24 | #include "CandidateFinder.hpp" |
---|
25 | #include "CurrentObject.h" // for CurrentObject |
---|
26 | #include "RenameVars.h" // for RenameVars, global_renamer |
---|
27 | #include "Resolver.h" |
---|
28 | #include "ResolvMode.h" // for ResolvMode |
---|
29 | #include "typeops.h" // for extractResultType |
---|
30 | #include "Unify.h" // for unify |
---|
31 | #include "AST/Decl.hpp" |
---|
32 | #include "AST/Init.hpp" |
---|
33 | #include "AST/Pass.hpp" |
---|
34 | #include "AST/Print.hpp" |
---|
35 | #include "AST/SymbolTable.hpp" |
---|
36 | #include "Common/PassVisitor.h" // for PassVisitor |
---|
37 | #include "Common/SemanticError.h" // for SemanticError |
---|
38 | #include "Common/utility.h" // for ValueGuard, group_iterate |
---|
39 | #include "InitTweak/GenInit.h" |
---|
40 | #include "InitTweak/InitTweak.h" // for isIntrinsicSingleArgCallStmt |
---|
41 | #include "ResolvExpr/TypeEnvironment.h" // for TypeEnvironment |
---|
42 | #include "SymTab/Autogen.h" // for SizeType |
---|
43 | #include "SymTab/Indexer.h" // for Indexer |
---|
44 | #include "SynTree/Declaration.h" // for ObjectDecl, TypeDecl, Declar... |
---|
45 | #include "SynTree/Expression.h" // for Expression, CastExpr, InitExpr |
---|
46 | #include "SynTree/Initializer.h" // for ConstructorInit, SingleInit |
---|
47 | #include "SynTree/Statement.h" // for ForStmt, Statement, BranchStmt |
---|
48 | #include "SynTree/Type.h" // for Type, BasicType, PointerType |
---|
49 | #include "SynTree/TypeSubstitution.h" // for TypeSubstitution |
---|
50 | #include "SynTree/Visitor.h" // for acceptAll, maybeAccept |
---|
51 | #include "Tuples/Tuples.h" |
---|
52 | #include "Validate/FindSpecialDecls.h" // for SizeType |
---|
53 | |
---|
54 | using namespace std; |
---|
55 | |
---|
56 | namespace ResolvExpr { |
---|
57 | struct Resolver_old final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver_old>, public WithShortCircuiting, public WithStmtsToAdd { |
---|
58 | Resolver_old() {} |
---|
59 | Resolver_old( const SymTab::Indexer & other ) { |
---|
60 | indexer = other; |
---|
61 | } |
---|
62 | |
---|
63 | void previsit( FunctionDecl * functionDecl ); |
---|
64 | void postvisit( FunctionDecl * functionDecl ); |
---|
65 | void previsit( ObjectDecl * objectDecll ); |
---|
66 | void previsit( EnumDecl * enumDecl ); |
---|
67 | void previsit( StaticAssertDecl * assertDecl ); |
---|
68 | |
---|
69 | void previsit( ArrayType * at ); |
---|
70 | void previsit( PointerType * at ); |
---|
71 | |
---|
72 | void previsit( ExprStmt * exprStmt ); |
---|
73 | void previsit( AsmExpr * asmExpr ); |
---|
74 | void previsit( AsmStmt * asmStmt ); |
---|
75 | void previsit( IfStmt * ifStmt ); |
---|
76 | void previsit( WhileStmt * whileStmt ); |
---|
77 | void previsit( ForStmt * forStmt ); |
---|
78 | void previsit( SwitchStmt * switchStmt ); |
---|
79 | void previsit( CaseStmt * caseStmt ); |
---|
80 | void previsit( BranchStmt * branchStmt ); |
---|
81 | void previsit( ReturnStmt * returnStmt ); |
---|
82 | void previsit( ThrowStmt * throwStmt ); |
---|
83 | void previsit( CatchStmt * catchStmt ); |
---|
84 | void previsit( WaitForStmt * stmt ); |
---|
85 | |
---|
86 | void previsit( SingleInit * singleInit ); |
---|
87 | void previsit( ListInit * listInit ); |
---|
88 | void previsit( ConstructorInit * ctorInit ); |
---|
89 | private: |
---|
90 | typedef std::list< Initializer * >::iterator InitIterator; |
---|
91 | |
---|
92 | template< typename PtrType > |
---|
93 | void handlePtrType( PtrType * type ); |
---|
94 | |
---|
95 | void fallbackInit( ConstructorInit * ctorInit ); |
---|
96 | |
---|
97 | Type * functionReturn = nullptr; |
---|
98 | CurrentObject currentObject = nullptr; |
---|
99 | bool inEnumDecl = false; |
---|
100 | }; |
---|
101 | |
---|
102 | struct ResolveWithExprs : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveWithExprs>, public WithShortCircuiting, public WithStmtsToAdd { |
---|
103 | void previsit( FunctionDecl * ); |
---|
104 | void previsit( WithStmt * ); |
---|
105 | |
---|
106 | void resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ); |
---|
107 | }; |
---|
108 | |
---|
109 | void resolve( std::list< Declaration * > translationUnit ) { |
---|
110 | PassVisitor<Resolver_old> resolver; |
---|
111 | acceptAll( translationUnit, resolver ); |
---|
112 | } |
---|
113 | |
---|
114 | void resolveDecl( Declaration * decl, const SymTab::Indexer & indexer ) { |
---|
115 | PassVisitor<Resolver_old> resolver( indexer ); |
---|
116 | maybeAccept( decl, resolver ); |
---|
117 | } |
---|
118 | |
---|
119 | namespace { |
---|
120 | struct DeleteFinder_old : public WithShortCircuiting { |
---|
121 | DeletedExpr * delExpr = nullptr; |
---|
122 | void previsit( DeletedExpr * expr ) { |
---|
123 | if ( delExpr ) visit_children = false; |
---|
124 | else delExpr = expr; |
---|
125 | } |
---|
126 | |
---|
127 | void previsit( Expression * ) { |
---|
128 | if ( delExpr ) visit_children = false; |
---|
129 | } |
---|
130 | }; |
---|
131 | } |
---|
132 | |
---|
133 | DeletedExpr * findDeletedExpr( Expression * expr ) { |
---|
134 | PassVisitor<DeleteFinder_old> finder; |
---|
135 | expr->accept( finder ); |
---|
136 | return finder.pass.delExpr; |
---|
137 | } |
---|
138 | |
---|
139 | namespace { |
---|
140 | struct StripCasts_old { |
---|
141 | Expression * postmutate( CastExpr * castExpr ) { |
---|
142 | if ( castExpr->isGenerated && ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, SymTab::Indexer() ) ) { |
---|
143 | // generated cast is to the same type as its argument, so it's unnecessary -- remove it |
---|
144 | Expression * expr = castExpr->arg; |
---|
145 | castExpr->arg = nullptr; |
---|
146 | std::swap( expr->env, castExpr->env ); |
---|
147 | return expr; |
---|
148 | } |
---|
149 | return castExpr; |
---|
150 | } |
---|
151 | |
---|
152 | static void strip( Expression *& expr ) { |
---|
153 | PassVisitor<StripCasts_old> stripper; |
---|
154 | expr = expr->acceptMutator( stripper ); |
---|
155 | } |
---|
156 | }; |
---|
157 | |
---|
158 | void finishExpr( Expression *& expr, const TypeEnvironment & env, TypeSubstitution * oldenv = nullptr ) { |
---|
159 | expr->env = oldenv ? oldenv->clone() : new TypeSubstitution; |
---|
160 | env.makeSubstitution( *expr->env ); |
---|
161 | StripCasts_old::strip( expr ); // remove unnecessary casts that may be buried in an expression |
---|
162 | } |
---|
163 | |
---|
164 | void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) { |
---|
165 | if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) { |
---|
166 | if ( ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) { |
---|
167 | // cast is to the same type as its argument, so it's unnecessary -- remove it |
---|
168 | expr = castExpr->arg; |
---|
169 | castExpr->arg = nullptr; |
---|
170 | std::swap( expr->env, castExpr->env ); |
---|
171 | delete castExpr; |
---|
172 | } |
---|
173 | } |
---|
174 | } |
---|
175 | } // namespace |
---|
176 | |
---|
177 | namespace { |
---|
178 | void findUnfinishedKindExpression(Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{} ) { |
---|
179 | assertf( untyped, "expected a non-null expression." ); |
---|
180 | |
---|
181 | // xxx - this isn't thread-safe, but should work until we parallelize the resolver |
---|
182 | static unsigned recursion_level = 0; |
---|
183 | |
---|
184 | ++recursion_level; |
---|
185 | TypeEnvironment env; |
---|
186 | AlternativeFinder finder( indexer, env ); |
---|
187 | finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode ); |
---|
188 | --recursion_level; |
---|
189 | |
---|
190 | #if 0 |
---|
191 | if ( finder.get_alternatives().size() != 1 ) { |
---|
192 | std::cerr << "untyped expr is "; |
---|
193 | untyped->print( std::cerr ); |
---|
194 | std::cerr << std::endl << "alternatives are:"; |
---|
195 | for ( const Alternative & alt : finder.get_alternatives() ) { |
---|
196 | alt.print( std::cerr ); |
---|
197 | } // for |
---|
198 | } // if |
---|
199 | #endif |
---|
200 | |
---|
201 | // produce filtered list of alternatives |
---|
202 | AltList candidates; |
---|
203 | for ( Alternative & alt : finder.get_alternatives() ) { |
---|
204 | if ( pred( alt ) ) { |
---|
205 | candidates.push_back( std::move( alt ) ); |
---|
206 | } |
---|
207 | } |
---|
208 | |
---|
209 | // produce invalid error if no candidates |
---|
210 | if ( candidates.empty() ) { |
---|
211 | SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") ); |
---|
212 | } |
---|
213 | |
---|
214 | // search for cheapest candidate |
---|
215 | AltList winners; |
---|
216 | bool seen_undeleted = false; |
---|
217 | for ( unsigned i = 0; i < candidates.size(); ++i ) { |
---|
218 | int c = winners.empty() ? -1 : candidates[i].cost.compare( winners.front().cost ); |
---|
219 | |
---|
220 | if ( c > 0 ) continue; // skip more expensive than winner |
---|
221 | |
---|
222 | if ( c < 0 ) { |
---|
223 | // reset on new cheapest |
---|
224 | seen_undeleted = ! findDeletedExpr( candidates[i].expr ); |
---|
225 | winners.clear(); |
---|
226 | } else /* if ( c == 0 ) */ { |
---|
227 | if ( findDeletedExpr( candidates[i].expr ) ) { |
---|
228 | // skip deleted expression if already seen one equivalent-cost not |
---|
229 | if ( seen_undeleted ) continue; |
---|
230 | } else if ( ! seen_undeleted ) { |
---|
231 | // replace list of equivalent-cost deleted expressions with one non-deleted |
---|
232 | winners.clear(); |
---|
233 | seen_undeleted = true; |
---|
234 | } |
---|
235 | } |
---|
236 | |
---|
237 | winners.emplace_back( std::move( candidates[i] ) ); |
---|
238 | } |
---|
239 | |
---|
240 | // promote alternative.cvtCost to .cost |
---|
241 | // xxx - I don't know why this is done, but I'm keeping the behaviour from findMinCost |
---|
242 | for ( Alternative& winner : winners ) { |
---|
243 | winner.cost = winner.cvtCost; |
---|
244 | } |
---|
245 | |
---|
246 | // produce ambiguous errors, if applicable |
---|
247 | if ( winners.size() != 1 ) { |
---|
248 | std::ostringstream stream; |
---|
249 | stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n"; |
---|
250 | untyped->print( stream ); |
---|
251 | stream << " Alternatives are:\n"; |
---|
252 | printAlts( winners, stream, 1 ); |
---|
253 | SemanticError( untyped->location, stream.str() ); |
---|
254 | } |
---|
255 | |
---|
256 | // single selected choice |
---|
257 | Alternative& choice = winners.front(); |
---|
258 | |
---|
259 | // fail on only expression deleted |
---|
260 | if ( ! seen_undeleted ) { |
---|
261 | SemanticError( untyped->location, choice.expr, "Unique best alternative includes deleted identifier in " ); |
---|
262 | } |
---|
263 | |
---|
264 | // xxx - check for ambiguous expressions |
---|
265 | |
---|
266 | // output selected choice |
---|
267 | alt = std::move( choice ); |
---|
268 | } |
---|
269 | |
---|
270 | /// resolve `untyped` to the expression whose alternative satisfies `pred` with the lowest cost; kindStr is used for providing better error messages |
---|
271 | void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{}) { |
---|
272 | if ( ! untyped ) return; |
---|
273 | Alternative choice; |
---|
274 | findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, mode ); |
---|
275 | finishExpr( choice.expr, choice.env, untyped->env ); |
---|
276 | delete untyped; |
---|
277 | untyped = choice.expr; |
---|
278 | choice.expr = nullptr; |
---|
279 | } |
---|
280 | |
---|
281 | bool standardAlternativeFilter( const Alternative & ) { |
---|
282 | // currently don't need to filter, under normal circumstances. |
---|
283 | // in the future, this may be useful for removing deleted expressions |
---|
284 | return true; |
---|
285 | } |
---|
286 | } // namespace |
---|
287 | |
---|
288 | // used in resolveTypeof |
---|
289 | Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer ) { |
---|
290 | TypeEnvironment env; |
---|
291 | return resolveInVoidContext( expr, indexer, env ); |
---|
292 | } |
---|
293 | |
---|
294 | Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer, TypeEnvironment & env ) { |
---|
295 | // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0 |
---|
296 | // interpretations, an exception has already been thrown. |
---|
297 | assertf( expr, "expected a non-null expression." ); |
---|
298 | |
---|
299 | CastExpr * untyped = new CastExpr( expr ); // cast to void |
---|
300 | untyped->location = expr->location; |
---|
301 | |
---|
302 | // set up and resolve expression cast to void |
---|
303 | Alternative choice; |
---|
304 | findUnfinishedKindExpression( untyped, choice, indexer, "", standardAlternativeFilter, ResolvMode::withAdjustment() ); |
---|
305 | CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr ); |
---|
306 | assert( castExpr ); |
---|
307 | env = std::move( choice.env ); |
---|
308 | |
---|
309 | // clean up resolved expression |
---|
310 | Expression * ret = castExpr->arg; |
---|
311 | castExpr->arg = nullptr; |
---|
312 | |
---|
313 | // unlink the arg so that it isn't deleted twice at the end of the program |
---|
314 | untyped->arg = nullptr; |
---|
315 | return ret; |
---|
316 | } |
---|
317 | |
---|
318 | void findVoidExpression( Expression *& untyped, const SymTab::Indexer & indexer ) { |
---|
319 | resetTyVarRenaming(); |
---|
320 | TypeEnvironment env; |
---|
321 | Expression * newExpr = resolveInVoidContext( untyped, indexer, env ); |
---|
322 | finishExpr( newExpr, env, untyped->env ); |
---|
323 | delete untyped; |
---|
324 | untyped = newExpr; |
---|
325 | } |
---|
326 | |
---|
327 | void findSingleExpression( Expression *& untyped, const SymTab::Indexer & indexer ) { |
---|
328 | findKindExpression( untyped, indexer, "", standardAlternativeFilter ); |
---|
329 | } |
---|
330 | |
---|
331 | void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) { |
---|
332 | assert( untyped && type ); |
---|
333 | // transfer location to generated cast for error purposes |
---|
334 | CodeLocation location = untyped->location; |
---|
335 | untyped = new CastExpr( untyped, type ); |
---|
336 | untyped->location = location; |
---|
337 | findSingleExpression( untyped, indexer ); |
---|
338 | removeExtraneousCast( untyped, indexer ); |
---|
339 | } |
---|
340 | |
---|
341 | namespace { |
---|
342 | bool isIntegralType( const Alternative & alt ) { |
---|
343 | Type * type = alt.expr->result; |
---|
344 | if ( dynamic_cast< EnumInstType * >( type ) ) { |
---|
345 | return true; |
---|
346 | } else if ( BasicType * bt = dynamic_cast< BasicType * >( type ) ) { |
---|
347 | return bt->isInteger(); |
---|
348 | } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) { |
---|
349 | return true; |
---|
350 | } else { |
---|
351 | return false; |
---|
352 | } // if |
---|
353 | } |
---|
354 | |
---|
355 | void findIntegralExpression( Expression *& untyped, const SymTab::Indexer & indexer ) { |
---|
356 | findKindExpression( untyped, indexer, "condition", isIntegralType ); |
---|
357 | } |
---|
358 | } |
---|
359 | |
---|
360 | |
---|
361 | bool isStructOrUnion( const Alternative & alt ) { |
---|
362 | Type * t = alt.expr->result->stripReferences(); |
---|
363 | return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t ); |
---|
364 | } |
---|
365 | |
---|
366 | void resolveWithExprs( std::list< Declaration * > & translationUnit ) { |
---|
367 | PassVisitor<ResolveWithExprs> resolver; |
---|
368 | acceptAll( translationUnit, resolver ); |
---|
369 | } |
---|
370 | |
---|
371 | void ResolveWithExprs::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) { |
---|
372 | for ( Expression *& expr : withExprs ) { |
---|
373 | // only struct- and union-typed expressions are viable candidates |
---|
374 | findKindExpression( expr, indexer, "with statement", isStructOrUnion ); |
---|
375 | |
---|
376 | // if with expression might be impure, create a temporary so that it is evaluated once |
---|
377 | if ( Tuples::maybeImpure( expr ) ) { |
---|
378 | static UniqueName tmpNamer( "_with_tmp_" ); |
---|
379 | ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) ); |
---|
380 | expr = new VariableExpr( tmp ); |
---|
381 | newStmts.push_back( new DeclStmt( tmp ) ); |
---|
382 | if ( InitTweak::isConstructable( tmp->type ) ) { |
---|
383 | // generate ctor/dtor and resolve them |
---|
384 | tmp->init = InitTweak::genCtorInit( tmp ); |
---|
385 | tmp->accept( *visitor ); |
---|
386 | } |
---|
387 | } |
---|
388 | } |
---|
389 | } |
---|
390 | |
---|
391 | void ResolveWithExprs::previsit( WithStmt * withStmt ) { |
---|
392 | resolveWithExprs( withStmt->exprs, stmtsToAddBefore ); |
---|
393 | } |
---|
394 | |
---|
395 | void ResolveWithExprs::previsit( FunctionDecl * functionDecl ) { |
---|
396 | { |
---|
397 | // resolve with-exprs with parameters in scope and add any newly generated declarations to the |
---|
398 | // front of the function body. |
---|
399 | auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } ); |
---|
400 | indexer.addFunctionType( functionDecl->type ); |
---|
401 | std::list< Statement * > newStmts; |
---|
402 | resolveWithExprs( functionDecl->withExprs, newStmts ); |
---|
403 | if ( functionDecl->statements ) { |
---|
404 | functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts ); |
---|
405 | } else { |
---|
406 | assertf( functionDecl->withExprs.empty() && newStmts.empty(), "Function %s without a body has with-clause and/or generated with declarations.", functionDecl->name.c_str() ); |
---|
407 | } |
---|
408 | } |
---|
409 | } |
---|
410 | |
---|
411 | void Resolver_old::previsit( ObjectDecl * objectDecl ) { |
---|
412 | // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that |
---|
413 | // class-variable initContext is changed multiple time because the LHS is analysed twice. |
---|
414 | // The second analysis changes initContext because of a function type can contain object |
---|
415 | // declarations in the return and parameter types. So each value of initContext is |
---|
416 | // retained, so the type on the first analysis is preserved and used for selecting the RHS. |
---|
417 | GuardValue( currentObject ); |
---|
418 | currentObject = CurrentObject( objectDecl->get_type() ); |
---|
419 | if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) { |
---|
420 | // enumerator initializers should not use the enum type to initialize, since |
---|
421 | // the enum type is still incomplete at this point. Use signed int instead. |
---|
422 | currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) ); |
---|
423 | } |
---|
424 | } |
---|
425 | |
---|
426 | template< typename PtrType > |
---|
427 | void Resolver_old::handlePtrType( PtrType * type ) { |
---|
428 | if ( type->get_dimension() ) { |
---|
429 | findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer ); |
---|
430 | } |
---|
431 | } |
---|
432 | |
---|
433 | void Resolver_old::previsit( ArrayType * at ) { |
---|
434 | handlePtrType( at ); |
---|
435 | } |
---|
436 | |
---|
437 | void Resolver_old::previsit( PointerType * pt ) { |
---|
438 | handlePtrType( pt ); |
---|
439 | } |
---|
440 | |
---|
441 | void Resolver_old::previsit( FunctionDecl * functionDecl ) { |
---|
442 | #if 0 |
---|
443 | std::cerr << "resolver visiting functiondecl "; |
---|
444 | functionDecl->print( std::cerr ); |
---|
445 | std::cerr << std::endl; |
---|
446 | #endif |
---|
447 | GuardValue( functionReturn ); |
---|
448 | functionReturn = ResolvExpr::extractResultType( functionDecl->type ); |
---|
449 | } |
---|
450 | |
---|
451 | void Resolver_old::postvisit( FunctionDecl * functionDecl ) { |
---|
452 | // default value expressions have an environment which shouldn't be there and trips up |
---|
453 | // later passes. |
---|
454 | // xxx - it might be necessary to somehow keep the information from this environment, but I |
---|
455 | // can't currently see how it's useful. |
---|
456 | for ( Declaration * d : functionDecl->type->parameters ) { |
---|
457 | if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) { |
---|
458 | if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) { |
---|
459 | delete init->value->env; |
---|
460 | init->value->env = nullptr; |
---|
461 | } |
---|
462 | } |
---|
463 | } |
---|
464 | } |
---|
465 | |
---|
466 | void Resolver_old::previsit( EnumDecl * ) { |
---|
467 | // in case we decide to allow nested enums |
---|
468 | GuardValue( inEnumDecl ); |
---|
469 | inEnumDecl = true; |
---|
470 | } |
---|
471 | |
---|
472 | void Resolver_old::previsit( StaticAssertDecl * assertDecl ) { |
---|
473 | findIntegralExpression( assertDecl->condition, indexer ); |
---|
474 | } |
---|
475 | |
---|
476 | void Resolver_old::previsit( ExprStmt * exprStmt ) { |
---|
477 | visit_children = false; |
---|
478 | assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" ); |
---|
479 | findVoidExpression( exprStmt->expr, indexer ); |
---|
480 | } |
---|
481 | |
---|
482 | void Resolver_old::previsit( AsmExpr * asmExpr ) { |
---|
483 | visit_children = false; |
---|
484 | findVoidExpression( asmExpr->operand, indexer ); |
---|
485 | if ( asmExpr->get_inout() ) { |
---|
486 | findVoidExpression( asmExpr->inout, indexer ); |
---|
487 | } // if |
---|
488 | } |
---|
489 | |
---|
490 | void Resolver_old::previsit( AsmStmt * asmStmt ) { |
---|
491 | visit_children = false; |
---|
492 | acceptAll( asmStmt->get_input(), *visitor ); |
---|
493 | acceptAll( asmStmt->get_output(), *visitor ); |
---|
494 | } |
---|
495 | |
---|
496 | void Resolver_old::previsit( IfStmt * ifStmt ) { |
---|
497 | findIntegralExpression( ifStmt->condition, indexer ); |
---|
498 | } |
---|
499 | |
---|
500 | void Resolver_old::previsit( WhileStmt * whileStmt ) { |
---|
501 | findIntegralExpression( whileStmt->condition, indexer ); |
---|
502 | } |
---|
503 | |
---|
504 | void Resolver_old::previsit( ForStmt * forStmt ) { |
---|
505 | if ( forStmt->condition ) { |
---|
506 | findIntegralExpression( forStmt->condition, indexer ); |
---|
507 | } // if |
---|
508 | |
---|
509 | if ( forStmt->increment ) { |
---|
510 | findVoidExpression( forStmt->increment, indexer ); |
---|
511 | } // if |
---|
512 | } |
---|
513 | |
---|
514 | void Resolver_old::previsit( SwitchStmt * switchStmt ) { |
---|
515 | GuardValue( currentObject ); |
---|
516 | findIntegralExpression( switchStmt->condition, indexer ); |
---|
517 | |
---|
518 | currentObject = CurrentObject( switchStmt->condition->result ); |
---|
519 | } |
---|
520 | |
---|
521 | void Resolver_old::previsit( CaseStmt * caseStmt ) { |
---|
522 | if ( caseStmt->condition ) { |
---|
523 | std::list< InitAlternative > initAlts = currentObject.getOptions(); |
---|
524 | assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." ); |
---|
525 | // must remove cast from case statement because RangeExpr cannot be cast. |
---|
526 | Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() ); |
---|
527 | findSingleExpression( newExpr, indexer ); |
---|
528 | // case condition cannot have a cast in C, so it must be removed, regardless of whether it performs a conversion. |
---|
529 | // Ideally we would perform the conversion internally here. |
---|
530 | if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( newExpr ) ) { |
---|
531 | newExpr = castExpr->arg; |
---|
532 | castExpr->arg = nullptr; |
---|
533 | std::swap( newExpr->env, castExpr->env ); |
---|
534 | delete castExpr; |
---|
535 | } |
---|
536 | caseStmt->condition = newExpr; |
---|
537 | } |
---|
538 | } |
---|
539 | |
---|
540 | void Resolver_old::previsit( BranchStmt * branchStmt ) { |
---|
541 | visit_children = false; |
---|
542 | // must resolve the argument for a computed goto |
---|
543 | if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement |
---|
544 | if ( branchStmt->computedTarget ) { |
---|
545 | // computed goto argument is void * |
---|
546 | findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer ); |
---|
547 | } // if |
---|
548 | } // if |
---|
549 | } |
---|
550 | |
---|
551 | void Resolver_old::previsit( ReturnStmt * returnStmt ) { |
---|
552 | visit_children = false; |
---|
553 | if ( returnStmt->expr ) { |
---|
554 | findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer ); |
---|
555 | } // if |
---|
556 | } |
---|
557 | |
---|
558 | void Resolver_old::previsit( ThrowStmt * throwStmt ) { |
---|
559 | visit_children = false; |
---|
560 | // TODO: Replace *exception type with &exception type. |
---|
561 | if ( throwStmt->get_expr() ) { |
---|
562 | StructDecl * exception_decl = |
---|
563 | indexer.lookupStruct( "__cfaabi_ehm__base_exception_t" ); |
---|
564 | assert( exception_decl ); |
---|
565 | Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, exception_decl ) ); |
---|
566 | findSingleExpression( throwStmt->expr, exceptType, indexer ); |
---|
567 | } |
---|
568 | } |
---|
569 | |
---|
570 | void Resolver_old::previsit( CatchStmt * catchStmt ) { |
---|
571 | if ( catchStmt->cond ) { |
---|
572 | findSingleExpression( catchStmt->cond, new BasicType( noQualifiers, BasicType::Bool ), indexer ); |
---|
573 | } |
---|
574 | } |
---|
575 | |
---|
576 | template< typename iterator_t > |
---|
577 | inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) { |
---|
578 | while( it != end && !(*it)->get_type()->get_mutex() ) { |
---|
579 | it++; |
---|
580 | } |
---|
581 | |
---|
582 | return it != end; |
---|
583 | } |
---|
584 | |
---|
585 | void Resolver_old::previsit( WaitForStmt * stmt ) { |
---|
586 | visit_children = false; |
---|
587 | |
---|
588 | // Resolve all clauses first |
---|
589 | for( auto& clause : stmt->clauses ) { |
---|
590 | |
---|
591 | TypeEnvironment env; |
---|
592 | AlternativeFinder funcFinder( indexer, env ); |
---|
593 | |
---|
594 | // Find all alternatives for a function in canonical form |
---|
595 | funcFinder.findWithAdjustment( clause.target.function ); |
---|
596 | |
---|
597 | if ( funcFinder.get_alternatives().empty() ) { |
---|
598 | stringstream ss; |
---|
599 | ss << "Use of undeclared indentifier '"; |
---|
600 | ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name; |
---|
601 | ss << "' in call to waitfor"; |
---|
602 | SemanticError( stmt->location, ss.str() ); |
---|
603 | } |
---|
604 | |
---|
605 | if(clause.target.arguments.empty()) { |
---|
606 | SemanticError( stmt->location, "Waitfor clause must have at least one mutex parameter"); |
---|
607 | } |
---|
608 | |
---|
609 | // Find all alternatives for all arguments in canonical form |
---|
610 | std::vector< AlternativeFinder > argAlternatives; |
---|
611 | funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) ); |
---|
612 | |
---|
613 | // List all combinations of arguments |
---|
614 | std::vector< AltList > possibilities; |
---|
615 | combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) ); |
---|
616 | |
---|
617 | AltList func_candidates; |
---|
618 | std::vector< AltList > args_candidates; |
---|
619 | |
---|
620 | // For every possible function : |
---|
621 | // try matching the arguments to the parameters |
---|
622 | // not the other way around because we have more arguments than parameters |
---|
623 | SemanticErrorException errors; |
---|
624 | for ( Alternative & func : funcFinder.get_alternatives() ) { |
---|
625 | try { |
---|
626 | PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() ); |
---|
627 | if( !pointer ) { |
---|
628 | SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" ); |
---|
629 | } |
---|
630 | |
---|
631 | FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() ); |
---|
632 | if( !function ) { |
---|
633 | SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" ); |
---|
634 | } |
---|
635 | |
---|
636 | |
---|
637 | { |
---|
638 | auto param = function->parameters.begin(); |
---|
639 | auto param_end = function->parameters.end(); |
---|
640 | |
---|
641 | if( !advance_to_mutex( param, param_end ) ) { |
---|
642 | SemanticError(function, "candidate function not viable: no mutex parameters\n"); |
---|
643 | } |
---|
644 | } |
---|
645 | |
---|
646 | Alternative newFunc( func ); |
---|
647 | // Strip reference from function |
---|
648 | referenceToRvalueConversion( newFunc.expr, newFunc.cost ); |
---|
649 | |
---|
650 | // For all the set of arguments we have try to match it with the parameter of the current function alternative |
---|
651 | for ( auto & argsList : possibilities ) { |
---|
652 | |
---|
653 | try { |
---|
654 | // Declare data structures need for resolution |
---|
655 | OpenVarSet openVars; |
---|
656 | AssertionSet resultNeed, resultHave; |
---|
657 | TypeEnvironment resultEnv( func.env ); |
---|
658 | makeUnifiableVars( function, openVars, resultNeed ); |
---|
659 | // add all type variables as open variables now so that those not used in the parameter |
---|
660 | // list are still considered open. |
---|
661 | resultEnv.add( function->forall ); |
---|
662 | |
---|
663 | // Load type variables from arguemnts into one shared space |
---|
664 | simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv ); |
---|
665 | |
---|
666 | // Make sure we don't widen any existing bindings |
---|
667 | resultEnv.forbidWidening(); |
---|
668 | |
---|
669 | // Find any unbound type variables |
---|
670 | resultEnv.extractOpenVars( openVars ); |
---|
671 | |
---|
672 | auto param = function->parameters.begin(); |
---|
673 | auto param_end = function->parameters.end(); |
---|
674 | |
---|
675 | int n_mutex_param = 0; |
---|
676 | |
---|
677 | // For every arguments of its set, check if it matches one of the parameter |
---|
678 | // The order is important |
---|
679 | for( auto & arg : argsList ) { |
---|
680 | |
---|
681 | // Ignore non-mutex arguments |
---|
682 | if( !advance_to_mutex( param, param_end ) ) { |
---|
683 | // We ran out of parameters but still have arguments |
---|
684 | // this function doesn't match |
---|
685 | SemanticError( function, toString("candidate function not viable: too many mutex arguments, expected ", n_mutex_param, "\n" )); |
---|
686 | } |
---|
687 | |
---|
688 | n_mutex_param++; |
---|
689 | |
---|
690 | // Check if the argument matches the parameter type in the current scope |
---|
691 | if( ! unify( arg.expr->get_result(), (*param)->get_type(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) { |
---|
692 | // Type doesn't match |
---|
693 | stringstream ss; |
---|
694 | ss << "candidate function not viable: no known convertion from '"; |
---|
695 | (*param)->get_type()->print( ss ); |
---|
696 | ss << "' to '"; |
---|
697 | arg.expr->get_result()->print( ss ); |
---|
698 | ss << "' with env '"; |
---|
699 | resultEnv.print(ss); |
---|
700 | ss << "'\n"; |
---|
701 | SemanticError( function, ss.str() ); |
---|
702 | } |
---|
703 | |
---|
704 | param++; |
---|
705 | } |
---|
706 | |
---|
707 | // All arguments match ! |
---|
708 | |
---|
709 | // Check if parameters are missing |
---|
710 | if( advance_to_mutex( param, param_end ) ) { |
---|
711 | do { |
---|
712 | n_mutex_param++; |
---|
713 | param++; |
---|
714 | } while( advance_to_mutex( param, param_end ) ); |
---|
715 | |
---|
716 | // We ran out of arguments but still have parameters left |
---|
717 | // this function doesn't match |
---|
718 | SemanticError( function, toString("candidate function not viable: too few mutex arguments, expected ", n_mutex_param, "\n" )); |
---|
719 | } |
---|
720 | |
---|
721 | // All parameters match ! |
---|
722 | |
---|
723 | // Finish the expressions to tie in the proper environments |
---|
724 | finishExpr( newFunc.expr, resultEnv ); |
---|
725 | for( Alternative & alt : argsList ) { |
---|
726 | finishExpr( alt.expr, resultEnv ); |
---|
727 | } |
---|
728 | |
---|
729 | // This is a match store it and save it for later |
---|
730 | func_candidates.push_back( newFunc ); |
---|
731 | args_candidates.push_back( argsList ); |
---|
732 | |
---|
733 | } |
---|
734 | catch( SemanticErrorException & e ) { |
---|
735 | errors.append( e ); |
---|
736 | } |
---|
737 | } |
---|
738 | } |
---|
739 | catch( SemanticErrorException & e ) { |
---|
740 | errors.append( e ); |
---|
741 | } |
---|
742 | } |
---|
743 | |
---|
744 | // Make sure we got the right number of arguments |
---|
745 | if( func_candidates.empty() ) { SemanticErrorException top( stmt->location, "No alternatives for function in call to waitfor" ); top.append( errors ); throw top; } |
---|
746 | if( args_candidates.empty() ) { SemanticErrorException top( stmt->location, "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; } |
---|
747 | if( func_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous function in call to waitfor" ); top.append( errors ); throw top; } |
---|
748 | if( args_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous arguments in call to waitfor" ); top.append( errors ); throw top; } |
---|
749 | // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used. |
---|
750 | |
---|
751 | // Swap the results from the alternative with the unresolved values. |
---|
752 | // Alternatives will handle deletion on destruction |
---|
753 | std::swap( clause.target.function, func_candidates.front().expr ); |
---|
754 | for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) { |
---|
755 | std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr ); |
---|
756 | } |
---|
757 | |
---|
758 | // Resolve the conditions as if it were an IfStmt |
---|
759 | // Resolve the statments normally |
---|
760 | findSingleExpression( clause.condition, this->indexer ); |
---|
761 | clause.statement->accept( *visitor ); |
---|
762 | } |
---|
763 | |
---|
764 | |
---|
765 | if( stmt->timeout.statement ) { |
---|
766 | // Resolve the timeout as an size_t for now |
---|
767 | // Resolve the conditions as if it were an IfStmt |
---|
768 | // Resolve the statments normally |
---|
769 | findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer ); |
---|
770 | findSingleExpression( stmt->timeout.condition, this->indexer ); |
---|
771 | stmt->timeout.statement->accept( *visitor ); |
---|
772 | } |
---|
773 | |
---|
774 | if( stmt->orelse.statement ) { |
---|
775 | // Resolve the conditions as if it were an IfStmt |
---|
776 | // Resolve the statments normally |
---|
777 | findSingleExpression( stmt->orelse.condition, this->indexer ); |
---|
778 | stmt->orelse.statement->accept( *visitor ); |
---|
779 | } |
---|
780 | } |
---|
781 | |
---|
782 | template< typename T > |
---|
783 | bool isCharType( T t ) { |
---|
784 | if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) { |
---|
785 | return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar || |
---|
786 | bt->get_kind() == BasicType::UnsignedChar; |
---|
787 | } |
---|
788 | return false; |
---|
789 | } |
---|
790 | |
---|
791 | void Resolver_old::previsit( SingleInit * singleInit ) { |
---|
792 | visit_children = false; |
---|
793 | // resolve initialization using the possibilities as determined by the currentObject cursor |
---|
794 | Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() ); |
---|
795 | findSingleExpression( newExpr, indexer ); |
---|
796 | InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr ); |
---|
797 | |
---|
798 | // move cursor to the object that is actually initialized |
---|
799 | currentObject.setNext( initExpr->get_designation() ); |
---|
800 | |
---|
801 | // discard InitExpr wrapper and retain relevant pieces |
---|
802 | newExpr = initExpr->expr; |
---|
803 | initExpr->expr = nullptr; |
---|
804 | std::swap( initExpr->env, newExpr->env ); |
---|
805 | // InitExpr may have inferParams in the case where the expression specializes a function |
---|
806 | // pointer, and newExpr may already have inferParams of its own, so a simple swap is not |
---|
807 | // sufficient. |
---|
808 | newExpr->spliceInferParams( initExpr ); |
---|
809 | delete initExpr; |
---|
810 | |
---|
811 | // get the actual object's type (may not exactly match what comes back from the resolver |
---|
812 | // due to conversions) |
---|
813 | Type * initContext = currentObject.getCurrentType(); |
---|
814 | |
---|
815 | removeExtraneousCast( newExpr, indexer ); |
---|
816 | |
---|
817 | // check if actual object's type is char[] |
---|
818 | if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) { |
---|
819 | if ( isCharType( at->get_base() ) ) { |
---|
820 | // check if the resolved type is char * |
---|
821 | if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) { |
---|
822 | if ( isCharType( pt->get_base() ) ) { |
---|
823 | if ( CastExpr * ce = dynamic_cast< CastExpr * >( newExpr ) ) { |
---|
824 | // strip cast if we're initializing a char[] with a char *, |
---|
825 | // e.g. char x[] = "hello"; |
---|
826 | newExpr = ce->get_arg(); |
---|
827 | ce->set_arg( nullptr ); |
---|
828 | std::swap( ce->env, newExpr->env ); |
---|
829 | delete ce; |
---|
830 | } |
---|
831 | } |
---|
832 | } |
---|
833 | } |
---|
834 | } |
---|
835 | |
---|
836 | // set initializer expr to resolved express |
---|
837 | singleInit->value = newExpr; |
---|
838 | |
---|
839 | // move cursor to next object in preparation for next initializer |
---|
840 | currentObject.increment(); |
---|
841 | } |
---|
842 | |
---|
843 | void Resolver_old::previsit( ListInit * listInit ) { |
---|
844 | visit_children = false; |
---|
845 | // move cursor into brace-enclosed initializer-list |
---|
846 | currentObject.enterListInit(); |
---|
847 | // xxx - fix this so that the list isn't copied, iterator should be used to change current |
---|
848 | // element |
---|
849 | std::list<Designation *> newDesignations; |
---|
850 | for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) { |
---|
851 | // iterate designations and initializers in pairs, moving the cursor to the current |
---|
852 | // designated object and resolving the initializer against that object. |
---|
853 | Designation * des = std::get<0>(p); |
---|
854 | Initializer * init = std::get<1>(p); |
---|
855 | newDesignations.push_back( currentObject.findNext( des ) ); |
---|
856 | init->accept( *visitor ); |
---|
857 | } |
---|
858 | // set the set of 'resolved' designations and leave the brace-enclosed initializer-list |
---|
859 | listInit->get_designations() = newDesignations; // xxx - memory management |
---|
860 | currentObject.exitListInit(); |
---|
861 | |
---|
862 | // xxx - this part has not be folded into CurrentObject yet |
---|
863 | // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) { |
---|
864 | // Type * base = tt->get_baseType()->get_base(); |
---|
865 | // if ( base ) { |
---|
866 | // // know the implementation type, so try using that as the initContext |
---|
867 | // ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr ); |
---|
868 | // currentObject = &tmpObj; |
---|
869 | // visit( listInit ); |
---|
870 | // } else { |
---|
871 | // // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context |
---|
872 | // Parent::visit( listInit ); |
---|
873 | // } |
---|
874 | // } else { |
---|
875 | } |
---|
876 | |
---|
877 | // ConstructorInit - fall back on C-style initializer |
---|
878 | void Resolver_old::fallbackInit( ConstructorInit * ctorInit ) { |
---|
879 | // could not find valid constructor, or found an intrinsic constructor |
---|
880 | // fall back on C-style initializer |
---|
881 | delete ctorInit->get_ctor(); |
---|
882 | ctorInit->set_ctor( nullptr ); |
---|
883 | delete ctorInit->get_dtor(); |
---|
884 | ctorInit->set_dtor( nullptr ); |
---|
885 | maybeAccept( ctorInit->get_init(), *visitor ); |
---|
886 | } |
---|
887 | |
---|
888 | // needs to be callable from outside the resolver, so this is a standalone function |
---|
889 | void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) { |
---|
890 | assert( ctorInit ); |
---|
891 | PassVisitor<Resolver_old> resolver( indexer ); |
---|
892 | ctorInit->accept( resolver ); |
---|
893 | } |
---|
894 | |
---|
895 | void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) { |
---|
896 | assert( stmtExpr ); |
---|
897 | PassVisitor<Resolver_old> resolver( indexer ); |
---|
898 | stmtExpr->accept( resolver ); |
---|
899 | stmtExpr->computeResult(); |
---|
900 | // xxx - aggregate the environments from all statements? Possibly in AlternativeFinder instead? |
---|
901 | } |
---|
902 | |
---|
903 | void Resolver_old::previsit( ConstructorInit * ctorInit ) { |
---|
904 | visit_children = false; |
---|
905 | // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit |
---|
906 | maybeAccept( ctorInit->ctor, *visitor ); |
---|
907 | maybeAccept( ctorInit->dtor, *visitor ); |
---|
908 | |
---|
909 | // found a constructor - can get rid of C-style initializer |
---|
910 | delete ctorInit->init; |
---|
911 | ctorInit->init = nullptr; |
---|
912 | |
---|
913 | // intrinsic single parameter constructors and destructors do nothing. Since this was |
---|
914 | // implicitly generated, there's no way for it to have side effects, so get rid of it |
---|
915 | // to clean up generated code. |
---|
916 | if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) { |
---|
917 | delete ctorInit->ctor; |
---|
918 | ctorInit->ctor = nullptr; |
---|
919 | } |
---|
920 | |
---|
921 | if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) { |
---|
922 | delete ctorInit->dtor; |
---|
923 | ctorInit->dtor = nullptr; |
---|
924 | } |
---|
925 | |
---|
926 | // xxx - todo -- what about arrays? |
---|
927 | // if ( dtor == nullptr && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) { |
---|
928 | // // can reduce the constructor down to a SingleInit using the |
---|
929 | // // second argument from the ctor call, since |
---|
930 | // delete ctorInit->get_ctor(); |
---|
931 | // ctorInit->set_ctor( nullptr ); |
---|
932 | |
---|
933 | // Expression * arg = |
---|
934 | // ctorInit->set_init( new SingleInit( arg ) ); |
---|
935 | // } |
---|
936 | } |
---|
937 | |
---|
938 | /////////////////////////////////////////////////////////////////////////// |
---|
939 | // |
---|
940 | // *** NEW RESOLVER *** |
---|
941 | // |
---|
942 | /////////////////////////////////////////////////////////////////////////// |
---|
943 | |
---|
944 | namespace { |
---|
945 | /// Finds deleted expressions in an expression tree |
---|
946 | struct DeleteFinder_new final : public ast::WithShortCircuiting { |
---|
947 | const ast::DeletedExpr * delExpr = nullptr; |
---|
948 | |
---|
949 | void previsit( const ast::DeletedExpr * expr ) { |
---|
950 | if ( delExpr ) { visit_children = false; } |
---|
951 | else { delExpr = expr; } |
---|
952 | } |
---|
953 | |
---|
954 | void previsit( const ast::Expr * ) { |
---|
955 | if ( delExpr ) { visit_children = false; } |
---|
956 | } |
---|
957 | }; |
---|
958 | |
---|
959 | /// Check if this expression is or includes a deleted expression |
---|
960 | const ast::DeletedExpr * findDeletedExpr( const ast::Expr * expr ) { |
---|
961 | ast::Pass<DeleteFinder_new> finder; |
---|
962 | expr->accept( finder ); |
---|
963 | return finder.pass.delExpr; |
---|
964 | } |
---|
965 | |
---|
966 | /// Calls the CandidateFinder and finds the single best candidate |
---|
967 | CandidateRef findUnfinishedKindExpression( |
---|
968 | const ast::Expr * untyped, const ast::SymbolTable & symtab, const std::string & kind, |
---|
969 | std::function<bool(const Candidate &)> pred, ResolvMode mode = {} |
---|
970 | ) { |
---|
971 | if ( ! untyped ) return nullptr; |
---|
972 | |
---|
973 | // xxx - this isn't thread-safe, but should work until we parallelize the resolver |
---|
974 | static unsigned recursion_level = 0; |
---|
975 | |
---|
976 | ++recursion_level; |
---|
977 | ast::TypeEnvironment env; |
---|
978 | CandidateFinder finder{ symtab, env }; |
---|
979 | finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode ); |
---|
980 | --recursion_level; |
---|
981 | |
---|
982 | // produce a filtered list of candidates |
---|
983 | CandidateList candidates; |
---|
984 | for ( auto & cand : finder.candidates ) { |
---|
985 | if ( pred( *cand ) ) { candidates.emplace_back( cand ); } |
---|
986 | } |
---|
987 | |
---|
988 | // produce invalid error if no candidates |
---|
989 | if ( candidates.empty() ) { |
---|
990 | SemanticError( untyped, |
---|
991 | toString( "No reasonable alternatives for ", kind, (kind != "" ? " " : ""), |
---|
992 | "expression: ") ); |
---|
993 | } |
---|
994 | |
---|
995 | // search for cheapest candidate |
---|
996 | CandidateList winners; |
---|
997 | bool seen_undeleted = false; |
---|
998 | for ( CandidateRef & cand : candidates ) { |
---|
999 | int c = winners.empty() ? -1 : cand->cost.compare( winners.front()->cost ); |
---|
1000 | |
---|
1001 | if ( c > 0 ) continue; // skip more expensive than winner |
---|
1002 | |
---|
1003 | if ( c < 0 ) { |
---|
1004 | // reset on new cheapest |
---|
1005 | seen_undeleted = ! findDeletedExpr( cand->expr ); |
---|
1006 | winners.clear(); |
---|
1007 | } else /* if ( c == 0 ) */ { |
---|
1008 | if ( findDeletedExpr( cand->expr ) ) { |
---|
1009 | // skip deleted expression if already seen one equivalent-cost not |
---|
1010 | if ( seen_undeleted ) continue; |
---|
1011 | } else if ( ! seen_undeleted ) { |
---|
1012 | // replace list of equivalent-cost deleted expressions with one non-deleted |
---|
1013 | winners.clear(); |
---|
1014 | seen_undeleted = true; |
---|
1015 | } |
---|
1016 | } |
---|
1017 | |
---|
1018 | winners.emplace_back( std::move( cand ) ); |
---|
1019 | } |
---|
1020 | |
---|
1021 | // promote candidate.cvtCost to .cost |
---|
1022 | for ( CandidateRef & cand : winners ) { |
---|
1023 | cand->cost = cand->cvtCost; |
---|
1024 | } |
---|
1025 | |
---|
1026 | // produce ambiguous errors, if applicable |
---|
1027 | if ( winners.size() != 1 ) { |
---|
1028 | std::ostringstream stream; |
---|
1029 | stream << "Cannot choose between " << winners.size() << " alternatives for " |
---|
1030 | << kind << (kind != "" ? " " : "") << "expression\n"; |
---|
1031 | ast::print( stream, untyped ); |
---|
1032 | stream << " Alternatives are:\n"; |
---|
1033 | print( stream, winners, 1 ); |
---|
1034 | SemanticError( untyped->location, stream.str() ); |
---|
1035 | } |
---|
1036 | |
---|
1037 | // single selected choice |
---|
1038 | CandidateRef & choice = winners.front(); |
---|
1039 | |
---|
1040 | // fail on only expression deleted |
---|
1041 | if ( ! seen_undeleted ) { |
---|
1042 | SemanticError( untyped->location, choice->expr.get(), "Unique best alternative " |
---|
1043 | "includes deleted identifier in " ); |
---|
1044 | } |
---|
1045 | |
---|
1046 | return std::move( choice ); |
---|
1047 | } |
---|
1048 | |
---|
1049 | /// Strips extraneous casts out of an expression |
---|
1050 | struct StripCasts_new final { |
---|
1051 | const ast::Expr * postmutate( const ast::CastExpr * castExpr ) { |
---|
1052 | if ( |
---|
1053 | castExpr->isGenerated |
---|
1054 | && typesCompatible( castExpr->arg->result, castExpr->result ) |
---|
1055 | ) { |
---|
1056 | // generated cast is the same type as its argument, remove it after keeping env |
---|
1057 | ast::ptr<ast::Expr> arg = castExpr->arg; |
---|
1058 | arg.get_and_mutate()->env = castExpr->env; |
---|
1059 | return arg; |
---|
1060 | } |
---|
1061 | return castExpr; |
---|
1062 | } |
---|
1063 | |
---|
1064 | static void strip( ast::ptr< ast::Expr > & expr ) { |
---|
1065 | ast::Pass< StripCasts_new > stripper; |
---|
1066 | expr = expr->accept( stripper ); |
---|
1067 | } |
---|
1068 | }; |
---|
1069 | |
---|
1070 | /// Establish post-resolver invariants for expressions |
---|
1071 | void finishExpr( |
---|
1072 | ast::ptr< ast::Expr > & expr, const ast::TypeEnvironment & env, |
---|
1073 | const ast::TypeSubstitution * oldenv = nullptr |
---|
1074 | ) { |
---|
1075 | // set up new type substitution for expression |
---|
1076 | ast::ptr< ast::TypeSubstitution > newenv = |
---|
1077 | oldenv ? oldenv : new ast::TypeSubstitution{}; |
---|
1078 | env.writeToSubstitution( *newenv.get_and_mutate() ); |
---|
1079 | expr.get_and_mutate()->env = std::move( newenv ); |
---|
1080 | // remove unncecessary casts |
---|
1081 | StripCasts_new::strip( expr ); |
---|
1082 | } |
---|
1083 | |
---|
1084 | /// resolve `untyped` to the expression whose candidate satisfies `pred` with the |
---|
1085 | /// lowest cost, returning the resolved version |
---|
1086 | ast::ptr< ast::Expr > findKindExpression( |
---|
1087 | const ast::Expr * untyped, const ast::SymbolTable & symtab, const std::string & kind, |
---|
1088 | std::function<bool(const Candidate &)> pred, ResolvMode mode = {} |
---|
1089 | ) { |
---|
1090 | if ( ! untyped ) return {}; |
---|
1091 | CandidateRef choice = |
---|
1092 | findUnfinishedKindExpression( untyped, symtab, kind, pred, mode ); |
---|
1093 | finishExpr( choice->expr, choice->env, untyped->env ); |
---|
1094 | return std::move( choice->expr ); |
---|
1095 | } |
---|
1096 | |
---|
1097 | /// Predicate for "Candidate has integral type" |
---|
1098 | bool hasIntegralType( const Candidate & i ) { |
---|
1099 | const ast::Type * type = i.expr->result; |
---|
1100 | |
---|
1101 | if ( auto bt = dynamic_cast< const ast::BasicType * >( type ) ) { |
---|
1102 | return bt->isInteger(); |
---|
1103 | } else if ( |
---|
1104 | dynamic_cast< const ast::EnumInstType * >( type ) |
---|
1105 | || dynamic_cast< const ast::ZeroType * >( type ) |
---|
1106 | || dynamic_cast< const ast::OneType * >( type ) |
---|
1107 | ) { |
---|
1108 | return true; |
---|
1109 | } else return false; |
---|
1110 | } |
---|
1111 | |
---|
1112 | /// Resolve `untyped` as an integral expression, returning the resolved version |
---|
1113 | ast::ptr< ast::Expr > findIntegralExpression( |
---|
1114 | const ast::Expr * untyped, const ast::SymbolTable & symtab |
---|
1115 | ) { |
---|
1116 | return findKindExpression( untyped, symtab, "condition", hasIntegralType ); |
---|
1117 | } |
---|
1118 | } |
---|
1119 | |
---|
1120 | class Resolver_new final |
---|
1121 | : public ast::WithSymbolTable, public ast::WithGuards, |
---|
1122 | public ast::WithVisitorRef<Resolver_new>, public ast::WithShortCircuiting, |
---|
1123 | public ast::WithStmtsToAdd<> { |
---|
1124 | |
---|
1125 | ast::ptr< ast::Type > functionReturn = nullptr; |
---|
1126 | // ast::CurrentObject currentObject = nullptr; |
---|
1127 | bool inEnumDecl = false; |
---|
1128 | |
---|
1129 | public: |
---|
1130 | Resolver_new() = default; |
---|
1131 | Resolver_new( const ast::SymbolTable & syms ) { symtab = syms; } |
---|
1132 | |
---|
1133 | void previsit( const ast::FunctionDecl * ); |
---|
1134 | const ast::FunctionDecl * postvisit( const ast::FunctionDecl * ); |
---|
1135 | void previsit( const ast::ObjectDecl * ); |
---|
1136 | void previsit( const ast::EnumDecl * ); |
---|
1137 | const ast::StaticAssertDecl * previsit( const ast::StaticAssertDecl * ); |
---|
1138 | |
---|
1139 | void previsit( const ast::ArrayType * ); |
---|
1140 | void previsit( const ast::PointerType * ); |
---|
1141 | |
---|
1142 | void previsit( const ast::ExprStmt * ); |
---|
1143 | void previsit( const ast::AsmExpr * ); |
---|
1144 | void previsit( const ast::AsmStmt * ); |
---|
1145 | void previsit( const ast::IfStmt * ); |
---|
1146 | void previsit( const ast::WhileStmt * ); |
---|
1147 | void previsit( const ast::ForStmt * ); |
---|
1148 | void previsit( const ast::SwitchStmt * ); |
---|
1149 | void previsit( const ast::CaseStmt * ); |
---|
1150 | void previsit( const ast::BranchStmt * ); |
---|
1151 | void previsit( const ast::ReturnStmt * ); |
---|
1152 | void previsit( const ast::ThrowStmt * ); |
---|
1153 | void previsit( const ast::CatchStmt * ); |
---|
1154 | void previsit( const ast::WaitForStmt * ); |
---|
1155 | |
---|
1156 | void previsit( const ast::SingleInit * ); |
---|
1157 | void previsit( const ast::ListInit * ); |
---|
1158 | void previsit( const ast::ConstructorInit * ); |
---|
1159 | }; |
---|
1160 | |
---|
1161 | void resolve( std::list< ast::ptr<ast::Decl> >& translationUnit ) { |
---|
1162 | ast::Pass<Resolver_new> resolver; |
---|
1163 | accept_all( translationUnit, resolver ); |
---|
1164 | } |
---|
1165 | |
---|
1166 | void Resolver_new::previsit( const ast::FunctionDecl * functionDecl ) { |
---|
1167 | GuardValue( functionReturn ); |
---|
1168 | functionReturn = extractResultType( functionDecl->type ); |
---|
1169 | } |
---|
1170 | |
---|
1171 | const ast::FunctionDecl * Resolver_new::postvisit( const ast::FunctionDecl * functionDecl ) { |
---|
1172 | // default value expressions have an environment which shouldn't be there and trips up |
---|
1173 | // later passes. |
---|
1174 | ast::ptr< ast::FunctionDecl > ret = functionDecl; |
---|
1175 | for ( unsigned i = 0; i < functionDecl->type->params.size(); ++i ) { |
---|
1176 | const ast::ptr<ast::DeclWithType> & d = functionDecl->type->params[i]; |
---|
1177 | |
---|
1178 | if ( const ast::ObjectDecl * obj = d.as< ast::ObjectDecl >() ) { |
---|
1179 | if ( const ast::SingleInit * init = obj->init.as< ast::SingleInit >() ) { |
---|
1180 | if ( init->value->env == nullptr ) continue; |
---|
1181 | // clone initializer minus the initializer environment |
---|
1182 | strict_dynamic_cast< ast::SingleInit * >( |
---|
1183 | strict_dynamic_cast< ast::ObjectDecl * >( |
---|
1184 | ret.get_and_mutate()->type.get_and_mutate()->params[i].get_and_mutate() |
---|
1185 | )->init.get_and_mutate() |
---|
1186 | )->value.get_and_mutate()->env = nullptr; |
---|
1187 | } |
---|
1188 | } |
---|
1189 | } |
---|
1190 | return ret.get(); |
---|
1191 | } |
---|
1192 | |
---|
1193 | void Resolver_new::previsit( const ast::ObjectDecl * objectDecl ) { |
---|
1194 | #warning unimplemented; Resolver port in progress |
---|
1195 | (void)objectDecl; |
---|
1196 | assert(false); |
---|
1197 | } |
---|
1198 | |
---|
1199 | void Resolver_new::previsit( const ast::EnumDecl * ) { |
---|
1200 | // in case we decide to allow nested enums |
---|
1201 | GuardValue( inEnumDecl ); |
---|
1202 | inEnumDecl = false; |
---|
1203 | } |
---|
1204 | |
---|
1205 | const ast::StaticAssertDecl * Resolver_new::previsit( |
---|
1206 | const ast::StaticAssertDecl * assertDecl |
---|
1207 | ) { |
---|
1208 | ast::ptr< ast::Expr > cond = findIntegralExpression( assertDecl->cond, symtab ); |
---|
1209 | if ( cond == assertDecl->cond ) return assertDecl; |
---|
1210 | |
---|
1211 | ast::StaticAssertDecl * ret = mutate( assertDecl ); |
---|
1212 | ret->cond = cond; |
---|
1213 | return ret; |
---|
1214 | } |
---|
1215 | |
---|
1216 | void Resolver_new::previsit( const ast::ArrayType * at ) { |
---|
1217 | #warning unimplemented; Resolver port in progress |
---|
1218 | (void)at; |
---|
1219 | assert(false); |
---|
1220 | } |
---|
1221 | |
---|
1222 | void Resolver_new::previsit( const ast::PointerType * pt ) { |
---|
1223 | #warning unimplemented; Resolver port in progress |
---|
1224 | (void)pt; |
---|
1225 | assert(false); |
---|
1226 | } |
---|
1227 | |
---|
1228 | void Resolver_new::previsit( const ast::ExprStmt * exprStmt ) { |
---|
1229 | #warning unimplemented; Resolver port in progress |
---|
1230 | (void)exprStmt; |
---|
1231 | assert(false); |
---|
1232 | } |
---|
1233 | |
---|
1234 | void Resolver_new::previsit( const ast::AsmExpr * asmExpr ) { |
---|
1235 | #warning unimplemented; Resolver port in progress |
---|
1236 | (void)asmExpr; |
---|
1237 | assert(false); |
---|
1238 | } |
---|
1239 | |
---|
1240 | void Resolver_new::previsit( const ast::AsmStmt * asmStmt ) { |
---|
1241 | #warning unimplemented; Resolver port in progress |
---|
1242 | (void)asmStmt; |
---|
1243 | assert(false); |
---|
1244 | } |
---|
1245 | |
---|
1246 | void Resolver_new::previsit( const ast::IfStmt * ifStmt ) { |
---|
1247 | #warning unimplemented; Resolver port in progress |
---|
1248 | (void)ifStmt; |
---|
1249 | assert(false); |
---|
1250 | } |
---|
1251 | |
---|
1252 | void Resolver_new::previsit( const ast::WhileStmt * whileStmt ) { |
---|
1253 | #warning unimplemented; Resolver port in progress |
---|
1254 | (void)whileStmt; |
---|
1255 | assert(false); |
---|
1256 | } |
---|
1257 | |
---|
1258 | void Resolver_new::previsit( const ast::ForStmt * forStmt ) { |
---|
1259 | #warning unimplemented; Resolver port in progress |
---|
1260 | (void)forStmt; |
---|
1261 | assert(false); |
---|
1262 | } |
---|
1263 | |
---|
1264 | void Resolver_new::previsit( const ast::SwitchStmt * switchStmt ) { |
---|
1265 | #warning unimplemented; Resolver port in progress |
---|
1266 | (void)switchStmt; |
---|
1267 | assert(false); |
---|
1268 | } |
---|
1269 | |
---|
1270 | void Resolver_new::previsit( const ast::CaseStmt * caseStmt ) { |
---|
1271 | #warning unimplemented; Resolver port in progress |
---|
1272 | (void)caseStmt; |
---|
1273 | assert(false); |
---|
1274 | } |
---|
1275 | |
---|
1276 | void Resolver_new::previsit( const ast::BranchStmt * branchStmt ) { |
---|
1277 | #warning unimplemented; Resolver port in progress |
---|
1278 | (void)branchStmt; |
---|
1279 | assert(false); |
---|
1280 | } |
---|
1281 | |
---|
1282 | void Resolver_new::previsit( const ast::ReturnStmt * returnStmt ) { |
---|
1283 | #warning unimplemented; Resolver port in progress |
---|
1284 | (void)returnStmt; |
---|
1285 | assert(false); |
---|
1286 | } |
---|
1287 | |
---|
1288 | void Resolver_new::previsit( const ast::ThrowStmt * throwStmt ) { |
---|
1289 | #warning unimplemented; Resolver port in progress |
---|
1290 | (void)throwStmt; |
---|
1291 | assert(false); |
---|
1292 | } |
---|
1293 | |
---|
1294 | void Resolver_new::previsit( const ast::CatchStmt * catchStmt ) { |
---|
1295 | #warning unimplemented; Resolver port in progress |
---|
1296 | (void)catchStmt; |
---|
1297 | assert(false); |
---|
1298 | } |
---|
1299 | |
---|
1300 | void Resolver_new::previsit( const ast::WaitForStmt * stmt ) { |
---|
1301 | #warning unimplemented; Resolver port in progress |
---|
1302 | (void)stmt; |
---|
1303 | assert(false); |
---|
1304 | } |
---|
1305 | |
---|
1306 | void Resolver_new::previsit( const ast::SingleInit * singleInit ) { |
---|
1307 | #warning unimplemented; Resolver port in progress |
---|
1308 | (void)singleInit; |
---|
1309 | assert(false); |
---|
1310 | } |
---|
1311 | |
---|
1312 | void Resolver_new::previsit( const ast::ListInit * listInit ) { |
---|
1313 | #warning unimplemented; Resolver port in progress |
---|
1314 | (void)listInit; |
---|
1315 | assert(false); |
---|
1316 | } |
---|
1317 | |
---|
1318 | void Resolver_new::previsit( const ast::ConstructorInit * ctorInit ) { |
---|
1319 | #warning unimplemented; Resolver port in progress |
---|
1320 | (void)ctorInit; |
---|
1321 | assert(false); |
---|
1322 | } |
---|
1323 | |
---|
1324 | } // namespace ResolvExpr |
---|
1325 | |
---|
1326 | // Local Variables: // |
---|
1327 | // tab-width: 4 // |
---|
1328 | // mode: c++ // |
---|
1329 | // compile-command: "make install" // |
---|
1330 | // End: // |
---|