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