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 | // Validate.cc -- |
---|
8 | // |
---|
9 | // Author : Richard C. Bilson |
---|
10 | // Created On : Sun May 17 21:50:04 2015 |
---|
11 | // Last Modified By : Andrew Beach |
---|
12 | // Last Modified On : Tue Jul 12 15:00:00 2022 |
---|
13 | // Update Count : 367 |
---|
14 | // |
---|
15 | |
---|
16 | // The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be |
---|
17 | // as regular in structure as possible. Some assumptions can be made regarding the state of the tree after this pass is |
---|
18 | // complete, including: |
---|
19 | // |
---|
20 | // - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or |
---|
21 | // union. |
---|
22 | // |
---|
23 | // - All enumeration constants have type EnumInstType. |
---|
24 | // |
---|
25 | // - The type "void" never occurs in lists of function parameter or return types. A function |
---|
26 | // taking no arguments has no argument types. |
---|
27 | // |
---|
28 | // - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated |
---|
29 | // by the particular set of type arguments. |
---|
30 | // |
---|
31 | // - Every declaration is assigned a unique id. |
---|
32 | // |
---|
33 | // - No typedef declarations or instances exist; the actual type is substituted for each instance. |
---|
34 | // |
---|
35 | // - Each type, struct, and union definition is followed by an appropriate assignment operator. |
---|
36 | // |
---|
37 | // - Each use of a struct or union is connected to a complete definition of that struct or union, even if that |
---|
38 | // definition occurs later in the input. |
---|
39 | |
---|
40 | #include "Validate.h" |
---|
41 | |
---|
42 | #include <cassert> // for assertf, assert |
---|
43 | #include <cstddef> // for size_t |
---|
44 | #include <list> // for list |
---|
45 | #include <string> // for string |
---|
46 | #include <unordered_map> // for unordered_map |
---|
47 | #include <utility> // for pair |
---|
48 | |
---|
49 | #include "AST/Chain.hpp" |
---|
50 | #include "AST/Decl.hpp" |
---|
51 | #include "AST/Node.hpp" |
---|
52 | #include "AST/Pass.hpp" |
---|
53 | #include "AST/SymbolTable.hpp" |
---|
54 | #include "AST/Type.hpp" |
---|
55 | #include "AST/TypeSubstitution.hpp" |
---|
56 | #include "CodeGen/CodeGenerator.h" // for genName |
---|
57 | #include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign |
---|
58 | #include "ControlStruct/Mutate.h" // for ForExprMutator |
---|
59 | #include "Common/CodeLocation.h" // for CodeLocation |
---|
60 | #include "Common/Stats.h" // for Stats::Heap |
---|
61 | #include "Common/PassVisitor.h" // for PassVisitor, WithDeclsToAdd |
---|
62 | #include "Common/ScopedMap.h" // for ScopedMap |
---|
63 | #include "Common/SemanticError.h" // for SemanticError |
---|
64 | #include "Common/UniqueName.h" // for UniqueName |
---|
65 | #include "Common/utility.h" // for operator+, cloneAll, deleteAll |
---|
66 | #include "CompilationState.h" // skip some passes in new-ast build |
---|
67 | #include "Concurrency/Keywords.h" // for applyKeywords |
---|
68 | #include "FixFunction.h" // for FixFunction |
---|
69 | #include "Indexer.h" // for Indexer |
---|
70 | #include "InitTweak/GenInit.h" // for fixReturnStatements |
---|
71 | #include "InitTweak/InitTweak.h" // for isCtorDtorAssign |
---|
72 | #include "ResolvExpr/typeops.h" // for typesCompatible |
---|
73 | #include "ResolvExpr/Resolver.h" // for findSingleExpression |
---|
74 | #include "ResolvExpr/ResolveTypeof.h" // for resolveTypeof |
---|
75 | #include "SymTab/Autogen.h" // for SizeType |
---|
76 | #include "SymTab/ValidateType.h" // for decayEnumsAndPointers, decayFo... |
---|
77 | #include "SynTree/LinkageSpec.h" // for C |
---|
78 | #include "SynTree/Attribute.h" // for noAttributes, Attribute |
---|
79 | #include "SynTree/Constant.h" // for Constant |
---|
80 | #include "SynTree/Declaration.h" // for ObjectDecl, DeclarationWithType |
---|
81 | #include "SynTree/Expression.h" // for CompoundLiteralExpr, Expressio... |
---|
82 | #include "SynTree/Initializer.h" // for ListInit, Initializer |
---|
83 | #include "SynTree/Label.h" // for operator==, Label |
---|
84 | #include "SynTree/Mutator.h" // for Mutator |
---|
85 | #include "SynTree/Type.h" // for Type, TypeInstType, EnumInstType |
---|
86 | #include "SynTree/TypeSubstitution.h" // for TypeSubstitution |
---|
87 | #include "SynTree/Visitor.h" // for Visitor |
---|
88 | #include "Validate/HandleAttributes.h" // for handleAttributes |
---|
89 | #include "Validate/FindSpecialDecls.h" // for FindSpecialDecls |
---|
90 | |
---|
91 | class CompoundStmt; |
---|
92 | class ReturnStmt; |
---|
93 | class SwitchStmt; |
---|
94 | |
---|
95 | #define debugPrint( x ) if ( doDebug ) x |
---|
96 | |
---|
97 | namespace SymTab { |
---|
98 | /// hoists declarations that are difficult to hoist while parsing |
---|
99 | struct HoistTypeDecls final : public WithDeclsToAdd { |
---|
100 | void previsit( SizeofExpr * ); |
---|
101 | void previsit( AlignofExpr * ); |
---|
102 | void previsit( UntypedOffsetofExpr * ); |
---|
103 | void previsit( CompoundLiteralExpr * ); |
---|
104 | void handleType( Type * ); |
---|
105 | }; |
---|
106 | |
---|
107 | struct FixQualifiedTypes final : public WithIndexer { |
---|
108 | FixQualifiedTypes() : WithIndexer(false) {} |
---|
109 | Type * postmutate( QualifiedType * ); |
---|
110 | }; |
---|
111 | |
---|
112 | struct HoistStruct final : public WithDeclsToAdd, public WithGuards { |
---|
113 | /// Flattens nested struct types |
---|
114 | static void hoistStruct( std::list< Declaration * > &translationUnit ); |
---|
115 | |
---|
116 | void previsit( StructDecl * aggregateDecl ); |
---|
117 | void previsit( UnionDecl * aggregateDecl ); |
---|
118 | void previsit( StaticAssertDecl * assertDecl ); |
---|
119 | void previsit( StructInstType * type ); |
---|
120 | void previsit( UnionInstType * type ); |
---|
121 | void previsit( EnumInstType * type ); |
---|
122 | |
---|
123 | private: |
---|
124 | template< typename AggDecl > void handleAggregate( AggDecl * aggregateDecl ); |
---|
125 | |
---|
126 | AggregateDecl * parentAggr = nullptr; |
---|
127 | }; |
---|
128 | |
---|
129 | /// Fix return types so that every function returns exactly one value |
---|
130 | struct ReturnTypeFixer { |
---|
131 | static void fix( std::list< Declaration * > &translationUnit ); |
---|
132 | |
---|
133 | void postvisit( FunctionDecl * functionDecl ); |
---|
134 | void postvisit( FunctionType * ftype ); |
---|
135 | }; |
---|
136 | |
---|
137 | /// Does early resolution on the expressions that give enumeration constants their values |
---|
138 | struct ResolveEnumInitializers final : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveEnumInitializers>, public WithShortCircuiting { |
---|
139 | ResolveEnumInitializers( const Indexer * indexer ); |
---|
140 | void postvisit( EnumDecl * enumDecl ); |
---|
141 | |
---|
142 | private: |
---|
143 | const Indexer * local_indexer; |
---|
144 | |
---|
145 | }; |
---|
146 | |
---|
147 | /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID. |
---|
148 | struct ForallPointerDecay_old final { |
---|
149 | void previsit( ObjectDecl * object ); |
---|
150 | void previsit( FunctionDecl * func ); |
---|
151 | void previsit( FunctionType * ftype ); |
---|
152 | void previsit( StructDecl * aggrDecl ); |
---|
153 | void previsit( UnionDecl * aggrDecl ); |
---|
154 | }; |
---|
155 | |
---|
156 | struct ReturnChecker : public WithGuards { |
---|
157 | /// Checks that return statements return nothing if their return type is void |
---|
158 | /// and return something if the return type is non-void. |
---|
159 | static void checkFunctionReturns( std::list< Declaration * > & translationUnit ); |
---|
160 | |
---|
161 | void previsit( FunctionDecl * functionDecl ); |
---|
162 | void previsit( ReturnStmt * returnStmt ); |
---|
163 | |
---|
164 | typedef std::list< DeclarationWithType * > ReturnVals; |
---|
165 | ReturnVals returnVals; |
---|
166 | }; |
---|
167 | |
---|
168 | struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd { |
---|
169 | ReplaceTypedef() : scopeLevel( 0 ) {} |
---|
170 | /// Replaces typedefs by forward declarations |
---|
171 | static void replaceTypedef( std::list< Declaration * > &translationUnit ); |
---|
172 | |
---|
173 | void premutate( QualifiedType * ); |
---|
174 | Type * postmutate( QualifiedType * qualType ); |
---|
175 | Type * postmutate( TypeInstType * aggregateUseType ); |
---|
176 | Declaration * postmutate( TypedefDecl * typeDecl ); |
---|
177 | void premutate( TypeDecl * typeDecl ); |
---|
178 | void premutate( FunctionDecl * funcDecl ); |
---|
179 | void premutate( ObjectDecl * objDecl ); |
---|
180 | DeclarationWithType * postmutate( ObjectDecl * objDecl ); |
---|
181 | |
---|
182 | void premutate( CastExpr * castExpr ); |
---|
183 | |
---|
184 | void premutate( CompoundStmt * compoundStmt ); |
---|
185 | |
---|
186 | void premutate( StructDecl * structDecl ); |
---|
187 | void premutate( UnionDecl * unionDecl ); |
---|
188 | void premutate( EnumDecl * enumDecl ); |
---|
189 | void premutate( TraitDecl * ); |
---|
190 | |
---|
191 | void premutate( FunctionType * ftype ); |
---|
192 | |
---|
193 | private: |
---|
194 | template<typename AggDecl> |
---|
195 | void addImplicitTypedef( AggDecl * aggDecl ); |
---|
196 | template< typename AggDecl > |
---|
197 | void handleAggregate( AggDecl * aggr ); |
---|
198 | |
---|
199 | typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr; |
---|
200 | typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap; |
---|
201 | typedef ScopedMap< std::string, TypeDecl * > TypeDeclMap; |
---|
202 | TypedefMap typedefNames; |
---|
203 | TypeDeclMap typedeclNames; |
---|
204 | int scopeLevel; |
---|
205 | bool inFunctionType = false; |
---|
206 | }; |
---|
207 | |
---|
208 | struct EliminateTypedef { |
---|
209 | /// removes TypedefDecls from the AST |
---|
210 | static void eliminateTypedef( std::list< Declaration * > &translationUnit ); |
---|
211 | |
---|
212 | template<typename AggDecl> |
---|
213 | void handleAggregate( AggDecl * aggregateDecl ); |
---|
214 | |
---|
215 | void previsit( StructDecl * aggregateDecl ); |
---|
216 | void previsit( UnionDecl * aggregateDecl ); |
---|
217 | void previsit( CompoundStmt * compoundStmt ); |
---|
218 | }; |
---|
219 | |
---|
220 | struct VerifyCtorDtorAssign { |
---|
221 | /// ensure that constructors, destructors, and assignment have at least one |
---|
222 | /// parameter, the first of which must be a pointer, and that ctor/dtors have no |
---|
223 | /// return values. |
---|
224 | static void verify( std::list< Declaration * > &translationUnit ); |
---|
225 | |
---|
226 | void previsit( FunctionDecl * funcDecl ); |
---|
227 | }; |
---|
228 | |
---|
229 | /// ensure that generic types have the correct number of type arguments |
---|
230 | struct ValidateGenericParameters { |
---|
231 | void previsit( StructInstType * inst ); |
---|
232 | void previsit( UnionInstType * inst ); |
---|
233 | }; |
---|
234 | |
---|
235 | /// desugar declarations and uses of dimension paramaters like [N], |
---|
236 | /// from type-system managed values, to tunnneling via ordinary types, |
---|
237 | /// as char[-] in and sizeof(-) out |
---|
238 | struct TranslateDimensionGenericParameters : public WithIndexer, public WithGuards { |
---|
239 | static void translateDimensions( std::list< Declaration * > &translationUnit ); |
---|
240 | TranslateDimensionGenericParameters(); |
---|
241 | |
---|
242 | bool nextVisitedNodeIsChildOfSUIT = false; // SUIT = Struct or Union -Inst Type |
---|
243 | bool visitingChildOfSUIT = false; |
---|
244 | void changeState_ChildOfSUIT( bool newVal ); |
---|
245 | void premutate( StructInstType * sit ); |
---|
246 | void premutate( UnionInstType * uit ); |
---|
247 | void premutate( BaseSyntaxNode * node ); |
---|
248 | |
---|
249 | TypeDecl * postmutate( TypeDecl * td ); |
---|
250 | Expression * postmutate( DimensionExpr * de ); |
---|
251 | Expression * postmutate( Expression * e ); |
---|
252 | }; |
---|
253 | |
---|
254 | struct FixObjectType : public WithIndexer { |
---|
255 | /// resolves typeof type in object, function, and type declarations |
---|
256 | static void fix( std::list< Declaration * > & translationUnit ); |
---|
257 | |
---|
258 | void previsit( ObjectDecl * ); |
---|
259 | void previsit( FunctionDecl * ); |
---|
260 | void previsit( TypeDecl * ); |
---|
261 | }; |
---|
262 | |
---|
263 | struct InitializerLength { |
---|
264 | /// for array types without an explicit length, compute the length and store it so that it |
---|
265 | /// is known to the rest of the phases. For example, |
---|
266 | /// int x[] = { 1, 2, 3 }; |
---|
267 | /// int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } }; |
---|
268 | /// here x and y are known at compile-time to have length 3, so change this into |
---|
269 | /// int x[3] = { 1, 2, 3 }; |
---|
270 | /// int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } }; |
---|
271 | static void computeLength( std::list< Declaration * > & translationUnit ); |
---|
272 | |
---|
273 | void previsit( ObjectDecl * objDecl ); |
---|
274 | }; |
---|
275 | |
---|
276 | struct ArrayLength : public WithIndexer { |
---|
277 | static void computeLength( std::list< Declaration * > & translationUnit ); |
---|
278 | |
---|
279 | void previsit( ArrayType * arrayType ); |
---|
280 | }; |
---|
281 | |
---|
282 | struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> { |
---|
283 | Type::StorageClasses storageClasses; |
---|
284 | |
---|
285 | void premutate( ObjectDecl * objectDecl ); |
---|
286 | Expression * postmutate( CompoundLiteralExpr * compLitExpr ); |
---|
287 | }; |
---|
288 | |
---|
289 | struct LabelAddressFixer final : public WithGuards { |
---|
290 | std::set< Label > labels; |
---|
291 | |
---|
292 | void premutate( FunctionDecl * funcDecl ); |
---|
293 | Expression * postmutate( AddressExpr * addrExpr ); |
---|
294 | }; |
---|
295 | |
---|
296 | void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) { |
---|
297 | PassVisitor<HoistTypeDecls> hoistDecls; |
---|
298 | { |
---|
299 | Stats::Heap::newPass("validate-A"); |
---|
300 | Stats::Time::BlockGuard guard("validate-A"); |
---|
301 | VerifyCtorDtorAssign::verify( translationUnit ); // must happen before autogen, because autogen examines existing ctor/dtors |
---|
302 | acceptAll( translationUnit, hoistDecls ); |
---|
303 | ReplaceTypedef::replaceTypedef( translationUnit ); |
---|
304 | ReturnTypeFixer::fix( translationUnit ); // must happen before autogen |
---|
305 | decayEnumsAndPointers( translationUnit ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes_old because it is an indexer and needs correct types for mangling |
---|
306 | } |
---|
307 | PassVisitor<FixQualifiedTypes> fixQual; |
---|
308 | { |
---|
309 | Stats::Heap::newPass("validate-B"); |
---|
310 | Stats::Time::BlockGuard guard("validate-B"); |
---|
311 | linkReferenceToTypes( translationUnit ); // Must happen before auto-gen, because it uses the sized flag. |
---|
312 | mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes_old, because aggregate members are accessed |
---|
313 | HoistStruct::hoistStruct( translationUnit ); |
---|
314 | EliminateTypedef::eliminateTypedef( translationUnit ); |
---|
315 | } |
---|
316 | PassVisitor<ValidateGenericParameters> genericParams; |
---|
317 | PassVisitor<ResolveEnumInitializers> rei( nullptr ); |
---|
318 | { |
---|
319 | Stats::Heap::newPass("validate-C"); |
---|
320 | Stats::Time::BlockGuard guard("validate-C"); |
---|
321 | Stats::Time::TimeBlock("Validate Generic Parameters", [&]() { |
---|
322 | acceptAll( translationUnit, genericParams ); // check as early as possible - can't happen before LinkReferenceToTypes_old; observed failing when attempted before eliminateTypedef |
---|
323 | }); |
---|
324 | Stats::Time::TimeBlock("Translate Dimensions", [&]() { |
---|
325 | TranslateDimensionGenericParameters::translateDimensions( translationUnit ); |
---|
326 | }); |
---|
327 | if (!useNewAST) { |
---|
328 | Stats::Time::TimeBlock("Resolve Enum Initializers", [&]() { |
---|
329 | acceptAll( translationUnit, rei ); // must happen after translateDimensions because rei needs identifier lookup, which needs name mangling |
---|
330 | }); |
---|
331 | } |
---|
332 | Stats::Time::TimeBlock("Check Function Returns", [&]() { |
---|
333 | ReturnChecker::checkFunctionReturns( translationUnit ); |
---|
334 | }); |
---|
335 | Stats::Time::TimeBlock("Fix Return Statements", [&]() { |
---|
336 | InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen |
---|
337 | }); |
---|
338 | } |
---|
339 | { |
---|
340 | Stats::Heap::newPass("validate-D"); |
---|
341 | Stats::Time::BlockGuard guard("validate-D"); |
---|
342 | Stats::Time::TimeBlock("Apply Concurrent Keywords", [&]() { |
---|
343 | Concurrency::applyKeywords( translationUnit ); |
---|
344 | }); |
---|
345 | Stats::Time::TimeBlock("Forall Pointer Decay", [&]() { |
---|
346 | decayForallPointers( translationUnit ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution |
---|
347 | }); |
---|
348 | Stats::Time::TimeBlock("Hoist Control Declarations", [&]() { |
---|
349 | ControlStruct::hoistControlDecls( translationUnit ); // hoist initialization out of for statements; must happen before autogenerateRoutines |
---|
350 | }); |
---|
351 | Stats::Time::TimeBlock("Generate Autogen routines", [&]() { |
---|
352 | autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay_old |
---|
353 | }); |
---|
354 | } |
---|
355 | PassVisitor<CompoundLiteral> compoundliteral; |
---|
356 | { |
---|
357 | Stats::Heap::newPass("validate-E"); |
---|
358 | Stats::Time::BlockGuard guard("validate-E"); |
---|
359 | Stats::Time::TimeBlock("Implement Mutex Func", [&]() { |
---|
360 | Concurrency::implementMutexFuncs( translationUnit ); |
---|
361 | }); |
---|
362 | Stats::Time::TimeBlock("Implement Thread Start", [&]() { |
---|
363 | Concurrency::implementThreadStarter( translationUnit ); |
---|
364 | }); |
---|
365 | Stats::Time::TimeBlock("Compound Literal", [&]() { |
---|
366 | mutateAll( translationUnit, compoundliteral ); |
---|
367 | }); |
---|
368 | if (!useNewAST) { |
---|
369 | Stats::Time::TimeBlock("Resolve With Expressions", [&]() { |
---|
370 | ResolvExpr::resolveWithExprs( translationUnit ); // must happen before FixObjectType because user-code is resolved and may contain with variables |
---|
371 | }); |
---|
372 | } |
---|
373 | } |
---|
374 | PassVisitor<LabelAddressFixer> labelAddrFixer; |
---|
375 | { |
---|
376 | Stats::Heap::newPass("validate-F"); |
---|
377 | Stats::Time::BlockGuard guard("validate-F"); |
---|
378 | if (!useNewAST) { |
---|
379 | Stats::Time::TimeCall("Fix Object Type", |
---|
380 | FixObjectType::fix, translationUnit); |
---|
381 | } |
---|
382 | Stats::Time::TimeCall("Initializer Length", |
---|
383 | InitializerLength::computeLength, translationUnit); |
---|
384 | if (!useNewAST) { |
---|
385 | Stats::Time::TimeCall("Array Length", |
---|
386 | ArrayLength::computeLength, translationUnit); |
---|
387 | } |
---|
388 | Stats::Time::TimeCall("Find Special Declarations", |
---|
389 | Validate::findSpecialDecls, translationUnit); |
---|
390 | Stats::Time::TimeCall("Fix Label Address", |
---|
391 | mutateAll<LabelAddressFixer>, translationUnit, labelAddrFixer); |
---|
392 | if (!useNewAST) { |
---|
393 | Stats::Time::TimeCall("Handle Attributes", |
---|
394 | Validate::handleAttributes, translationUnit); |
---|
395 | } |
---|
396 | } |
---|
397 | } |
---|
398 | |
---|
399 | void HoistTypeDecls::handleType( Type * type ) { |
---|
400 | // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here |
---|
401 | AggregateDecl * aggr = nullptr; |
---|
402 | if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) { |
---|
403 | aggr = inst->baseStruct; |
---|
404 | } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) { |
---|
405 | aggr = inst->baseUnion; |
---|
406 | } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) { |
---|
407 | aggr = inst->baseEnum; |
---|
408 | } |
---|
409 | if ( aggr && aggr->body ) { |
---|
410 | declsToAddBefore.push_front( aggr ); |
---|
411 | } |
---|
412 | } |
---|
413 | |
---|
414 | void HoistTypeDecls::previsit( SizeofExpr * expr ) { |
---|
415 | handleType( expr->type ); |
---|
416 | } |
---|
417 | |
---|
418 | void HoistTypeDecls::previsit( AlignofExpr * expr ) { |
---|
419 | handleType( expr->type ); |
---|
420 | } |
---|
421 | |
---|
422 | void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) { |
---|
423 | handleType( expr->type ); |
---|
424 | } |
---|
425 | |
---|
426 | void HoistTypeDecls::previsit( CompoundLiteralExpr * expr ) { |
---|
427 | handleType( expr->result ); |
---|
428 | } |
---|
429 | |
---|
430 | |
---|
431 | Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) { |
---|
432 | Type * parent = qualType->parent; |
---|
433 | Type * child = qualType->child; |
---|
434 | if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) { |
---|
435 | // .T => lookup T at global scope |
---|
436 | if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) { |
---|
437 | auto td = indexer.globalLookupType( inst->name ); |
---|
438 | if ( ! td ) { |
---|
439 | SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) ); |
---|
440 | } |
---|
441 | auto base = td->base; |
---|
442 | assert( base ); |
---|
443 | Type * ret = base->clone(); |
---|
444 | ret->get_qualifiers() = qualType->get_qualifiers(); |
---|
445 | return ret; |
---|
446 | } else { |
---|
447 | // .T => T is not a type name |
---|
448 | assertf( false, "unhandled global qualified child type: %s", toCString(child) ); |
---|
449 | } |
---|
450 | } else { |
---|
451 | // S.T => S must be an aggregate type, find the declaration for T in S. |
---|
452 | AggregateDecl * aggr = nullptr; |
---|
453 | if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) { |
---|
454 | aggr = inst->baseStruct; |
---|
455 | } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) { |
---|
456 | aggr = inst->baseUnion; |
---|
457 | } else { |
---|
458 | SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) ); |
---|
459 | } |
---|
460 | assert( aggr ); // TODO: need to handle forward declarations |
---|
461 | for ( Declaration * member : aggr->members ) { |
---|
462 | if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) { |
---|
463 | // name on the right is a typedef |
---|
464 | if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) { |
---|
465 | if ( aggr->name == inst->name ) { |
---|
466 | assert( aggr->base ); |
---|
467 | Type * ret = aggr->base->clone(); |
---|
468 | ret->get_qualifiers() = qualType->get_qualifiers(); |
---|
469 | TypeSubstitution sub = parent->genericSubstitution(); |
---|
470 | sub.apply(ret); |
---|
471 | return ret; |
---|
472 | } |
---|
473 | } |
---|
474 | } else { |
---|
475 | // S.T - S is not an aggregate => error |
---|
476 | assertf( false, "unhandled qualified child type: %s", toCString(qualType) ); |
---|
477 | } |
---|
478 | } |
---|
479 | // failed to find a satisfying definition of type |
---|
480 | SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) ); |
---|
481 | } |
---|
482 | |
---|
483 | // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup? |
---|
484 | } |
---|
485 | |
---|
486 | |
---|
487 | void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) { |
---|
488 | PassVisitor<HoistStruct> hoister; |
---|
489 | acceptAll( translationUnit, hoister ); |
---|
490 | } |
---|
491 | |
---|
492 | bool shouldHoist( Declaration * decl ) { |
---|
493 | return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl ); |
---|
494 | } |
---|
495 | |
---|
496 | namespace { |
---|
497 | void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) { |
---|
498 | if ( aggr->parent ) qualifiedName( aggr->parent, ss ); |
---|
499 | ss << "__" << aggr->name; |
---|
500 | } |
---|
501 | |
---|
502 | // mangle nested type names using entire parent chain |
---|
503 | std::string qualifiedName( AggregateDecl * aggr ) { |
---|
504 | std::ostringstream ss; |
---|
505 | qualifiedName( aggr, ss ); |
---|
506 | return ss.str(); |
---|
507 | } |
---|
508 | } |
---|
509 | |
---|
510 | template< typename AggDecl > |
---|
511 | void HoistStruct::handleAggregate( AggDecl * aggregateDecl ) { |
---|
512 | if ( parentAggr ) { |
---|
513 | aggregateDecl->parent = parentAggr; |
---|
514 | aggregateDecl->name = qualifiedName( aggregateDecl ); |
---|
515 | // Add elements in stack order corresponding to nesting structure. |
---|
516 | declsToAddBefore.push_front( aggregateDecl ); |
---|
517 | } else { |
---|
518 | GuardValue( parentAggr ); |
---|
519 | parentAggr = aggregateDecl; |
---|
520 | } // if |
---|
521 | // Always remove the hoisted aggregate from the inner structure. |
---|
522 | GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } ); |
---|
523 | } |
---|
524 | |
---|
525 | void HoistStruct::previsit( StaticAssertDecl * assertDecl ) { |
---|
526 | if ( parentAggr ) { |
---|
527 | declsToAddBefore.push_back( assertDecl ); |
---|
528 | } |
---|
529 | } |
---|
530 | |
---|
531 | void HoistStruct::previsit( StructDecl * aggregateDecl ) { |
---|
532 | handleAggregate( aggregateDecl ); |
---|
533 | } |
---|
534 | |
---|
535 | void HoistStruct::previsit( UnionDecl * aggregateDecl ) { |
---|
536 | handleAggregate( aggregateDecl ); |
---|
537 | } |
---|
538 | |
---|
539 | void HoistStruct::previsit( StructInstType * type ) { |
---|
540 | // need to reset type name after expanding to qualified name |
---|
541 | assert( type->baseStruct ); |
---|
542 | type->name = type->baseStruct->name; |
---|
543 | } |
---|
544 | |
---|
545 | void HoistStruct::previsit( UnionInstType * type ) { |
---|
546 | assert( type->baseUnion ); |
---|
547 | type->name = type->baseUnion->name; |
---|
548 | } |
---|
549 | |
---|
550 | void HoistStruct::previsit( EnumInstType * type ) { |
---|
551 | assert( type->baseEnum ); |
---|
552 | type->name = type->baseEnum->name; |
---|
553 | } |
---|
554 | |
---|
555 | |
---|
556 | bool isTypedef( Declaration * decl ) { |
---|
557 | return dynamic_cast< TypedefDecl * >( decl ); |
---|
558 | } |
---|
559 | |
---|
560 | void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) { |
---|
561 | PassVisitor<EliminateTypedef> eliminator; |
---|
562 | acceptAll( translationUnit, eliminator ); |
---|
563 | filter( translationUnit, isTypedef, true ); |
---|
564 | } |
---|
565 | |
---|
566 | template< typename AggDecl > |
---|
567 | void EliminateTypedef::handleAggregate( AggDecl * aggregateDecl ) { |
---|
568 | filter( aggregateDecl->members, isTypedef, true ); |
---|
569 | } |
---|
570 | |
---|
571 | void EliminateTypedef::previsit( StructDecl * aggregateDecl ) { |
---|
572 | handleAggregate( aggregateDecl ); |
---|
573 | } |
---|
574 | |
---|
575 | void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) { |
---|
576 | handleAggregate( aggregateDecl ); |
---|
577 | } |
---|
578 | |
---|
579 | void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) { |
---|
580 | // remove and delete decl stmts |
---|
581 | filter( compoundStmt->kids, [](Statement * stmt) { |
---|
582 | if ( DeclStmt * declStmt = dynamic_cast< DeclStmt * >( stmt ) ) { |
---|
583 | if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) { |
---|
584 | return true; |
---|
585 | } // if |
---|
586 | } // if |
---|
587 | return false; |
---|
588 | }, true); |
---|
589 | } |
---|
590 | |
---|
591 | // expand assertions from trait instance, performing the appropriate type variable substitutions |
---|
592 | template< typename Iterator > |
---|
593 | void expandAssertions( TraitInstType * inst, Iterator out ) { |
---|
594 | assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) ); |
---|
595 | std::list< DeclarationWithType * > asserts; |
---|
596 | for ( Declaration * decl : inst->baseTrait->members ) { |
---|
597 | asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) ); |
---|
598 | } |
---|
599 | // substitute trait decl parameters for instance parameters |
---|
600 | applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out ); |
---|
601 | } |
---|
602 | |
---|
603 | ResolveEnumInitializers::ResolveEnumInitializers( const Indexer * other_indexer ) : WithIndexer( true ) { |
---|
604 | if ( other_indexer ) { |
---|
605 | local_indexer = other_indexer; |
---|
606 | } else { |
---|
607 | local_indexer = &indexer; |
---|
608 | } // if |
---|
609 | } |
---|
610 | |
---|
611 | void ResolveEnumInitializers::postvisit( EnumDecl * enumDecl ) { |
---|
612 | if ( enumDecl->body ) { |
---|
613 | for ( Declaration * member : enumDecl->members ) { |
---|
614 | ObjectDecl * field = strict_dynamic_cast<ObjectDecl *>( member ); |
---|
615 | if ( field->init ) { |
---|
616 | // need to resolve enumerator initializers early so that other passes that determine if an expression is constexpr have the appropriate information. |
---|
617 | SingleInit * init = strict_dynamic_cast<SingleInit *>( field->init ); |
---|
618 | if ( !enumDecl->base || dynamic_cast<BasicType *>(enumDecl->base)) |
---|
619 | ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer ); |
---|
620 | else { |
---|
621 | if (dynamic_cast<PointerType *>(enumDecl->base)) { |
---|
622 | auto typePtr = dynamic_cast<PointerType *>(enumDecl->base); |
---|
623 | ResolvExpr::findSingleExpression( init->value, |
---|
624 | new PointerType( Type::Qualifiers(), typePtr->base ), indexer ); |
---|
625 | } else { |
---|
626 | ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer ); |
---|
627 | } |
---|
628 | } |
---|
629 | } |
---|
630 | } |
---|
631 | |
---|
632 | } // if |
---|
633 | } |
---|
634 | |
---|
635 | /// Fix up assertions - flattens assertion lists, removing all trait instances |
---|
636 | void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) { |
---|
637 | for ( TypeDecl * type : forall ) { |
---|
638 | std::list< DeclarationWithType * > asserts; |
---|
639 | asserts.splice( asserts.end(), type->assertions ); |
---|
640 | // expand trait instances into their members |
---|
641 | for ( DeclarationWithType * assertion : asserts ) { |
---|
642 | if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) { |
---|
643 | // expand trait instance into all of its members |
---|
644 | expandAssertions( traitInst, back_inserter( type->assertions ) ); |
---|
645 | delete traitInst; |
---|
646 | } else { |
---|
647 | // pass other assertions through |
---|
648 | type->assertions.push_back( assertion ); |
---|
649 | } // if |
---|
650 | } // for |
---|
651 | // apply FixFunction to every assertion to check for invalid void type |
---|
652 | for ( DeclarationWithType *& assertion : type->assertions ) { |
---|
653 | bool isVoid = fixFunction( assertion ); |
---|
654 | if ( isVoid ) { |
---|
655 | SemanticError( node, "invalid type void in assertion of function " ); |
---|
656 | } // if |
---|
657 | } // for |
---|
658 | // normalizeAssertions( type->assertions ); |
---|
659 | } // for |
---|
660 | } |
---|
661 | |
---|
662 | /// Replace all traits in assertion lists with their assertions. |
---|
663 | void expandTraits( std::list< TypeDecl * > & forall ) { |
---|
664 | for ( TypeDecl * type : forall ) { |
---|
665 | std::list< DeclarationWithType * > asserts; |
---|
666 | asserts.splice( asserts.end(), type->assertions ); |
---|
667 | // expand trait instances into their members |
---|
668 | for ( DeclarationWithType * assertion : asserts ) { |
---|
669 | if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) { |
---|
670 | // expand trait instance into all of its members |
---|
671 | expandAssertions( traitInst, back_inserter( type->assertions ) ); |
---|
672 | delete traitInst; |
---|
673 | } else { |
---|
674 | // pass other assertions through |
---|
675 | type->assertions.push_back( assertion ); |
---|
676 | } // if |
---|
677 | } // for |
---|
678 | } |
---|
679 | } |
---|
680 | |
---|
681 | /// Fix each function in the assertion list and check for invalid void type. |
---|
682 | void fixAssertions( |
---|
683 | std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) { |
---|
684 | for ( TypeDecl * type : forall ) { |
---|
685 | for ( DeclarationWithType *& assertion : type->assertions ) { |
---|
686 | bool isVoid = fixFunction( assertion ); |
---|
687 | if ( isVoid ) { |
---|
688 | SemanticError( node, "invalid type void in assertion of function " ); |
---|
689 | } // if |
---|
690 | } // for |
---|
691 | } |
---|
692 | } |
---|
693 | |
---|
694 | void ForallPointerDecay_old::previsit( ObjectDecl * object ) { |
---|
695 | // ensure that operator names only apply to functions or function pointers |
---|
696 | if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) { |
---|
697 | SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." ) ); |
---|
698 | } |
---|
699 | object->fixUniqueId(); |
---|
700 | } |
---|
701 | |
---|
702 | void ForallPointerDecay_old::previsit( FunctionDecl * func ) { |
---|
703 | func->fixUniqueId(); |
---|
704 | } |
---|
705 | |
---|
706 | void ForallPointerDecay_old::previsit( FunctionType * ftype ) { |
---|
707 | forallFixer( ftype->forall, ftype ); |
---|
708 | } |
---|
709 | |
---|
710 | void ForallPointerDecay_old::previsit( StructDecl * aggrDecl ) { |
---|
711 | forallFixer( aggrDecl->parameters, aggrDecl ); |
---|
712 | } |
---|
713 | |
---|
714 | void ForallPointerDecay_old::previsit( UnionDecl * aggrDecl ) { |
---|
715 | forallFixer( aggrDecl->parameters, aggrDecl ); |
---|
716 | } |
---|
717 | |
---|
718 | void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) { |
---|
719 | PassVisitor<ReturnChecker> checker; |
---|
720 | acceptAll( translationUnit, checker ); |
---|
721 | } |
---|
722 | |
---|
723 | void ReturnChecker::previsit( FunctionDecl * functionDecl ) { |
---|
724 | GuardValue( returnVals ); |
---|
725 | returnVals = functionDecl->get_functionType()->get_returnVals(); |
---|
726 | } |
---|
727 | |
---|
728 | void ReturnChecker::previsit( ReturnStmt * returnStmt ) { |
---|
729 | // Previously this also checked for the existence of an expr paired with no return values on |
---|
730 | // the function return type. This is incorrect, since you can have an expression attached to |
---|
731 | // a return statement in a void-returning function in C. The expression is treated as if it |
---|
732 | // were cast to void. |
---|
733 | if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) { |
---|
734 | SemanticError( returnStmt, "Non-void function returns no values: " ); |
---|
735 | } |
---|
736 | } |
---|
737 | |
---|
738 | |
---|
739 | void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) { |
---|
740 | PassVisitor<ReplaceTypedef> eliminator; |
---|
741 | mutateAll( translationUnit, eliminator ); |
---|
742 | if ( eliminator.pass.typedefNames.count( "size_t" ) ) { |
---|
743 | // grab and remember declaration of size_t |
---|
744 | Validate::SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone(); |
---|
745 | } else { |
---|
746 | // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong |
---|
747 | // eventually should have a warning for this case. |
---|
748 | Validate::SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ); |
---|
749 | } |
---|
750 | } |
---|
751 | |
---|
752 | void ReplaceTypedef::premutate( QualifiedType * ) { |
---|
753 | visit_children = false; |
---|
754 | } |
---|
755 | |
---|
756 | Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) { |
---|
757 | // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type |
---|
758 | qualType->parent = qualType->parent->acceptMutator( * visitor ); |
---|
759 | return qualType; |
---|
760 | } |
---|
761 | |
---|
762 | static bool isNonParameterAttribute( Attribute * attr ) { |
---|
763 | static const std::vector<std::string> bad_names = { |
---|
764 | "aligned", "__aligned__", |
---|
765 | }; |
---|
766 | for ( auto name : bad_names ) { |
---|
767 | if ( name == attr->name ) { |
---|
768 | return true; |
---|
769 | } |
---|
770 | } |
---|
771 | return false; |
---|
772 | } |
---|
773 | |
---|
774 | Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) { |
---|
775 | // instances of typedef types will come here. If it is an instance |
---|
776 | // of a typdef type, link the instance to its actual type. |
---|
777 | TypedefMap::const_iterator def = typedefNames.find( typeInst->name ); |
---|
778 | if ( def != typedefNames.end() ) { |
---|
779 | Type * ret = def->second.first->base->clone(); |
---|
780 | ret->location = typeInst->location; |
---|
781 | ret->get_qualifiers() |= typeInst->get_qualifiers(); |
---|
782 | // GCC ignores certain attributes if they arrive by typedef, this mimics that. |
---|
783 | if ( inFunctionType ) { |
---|
784 | ret->attributes.remove_if( isNonParameterAttribute ); |
---|
785 | } |
---|
786 | ret->attributes.splice( ret->attributes.end(), typeInst->attributes ); |
---|
787 | // place instance parameters on the typedef'd type |
---|
788 | if ( ! typeInst->parameters.empty() ) { |
---|
789 | ReferenceToType * rtt = dynamic_cast<ReferenceToType *>(ret); |
---|
790 | if ( ! rtt ) { |
---|
791 | SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name ); |
---|
792 | } |
---|
793 | rtt->parameters.clear(); |
---|
794 | cloneAll( typeInst->parameters, rtt->parameters ); |
---|
795 | mutateAll( rtt->parameters, * visitor ); // recursively fix typedefs on parameters |
---|
796 | } // if |
---|
797 | delete typeInst; |
---|
798 | return ret; |
---|
799 | } else { |
---|
800 | TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name ); |
---|
801 | if ( base == typedeclNames.end() ) { |
---|
802 | SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) ); |
---|
803 | } |
---|
804 | typeInst->set_baseType( base->second ); |
---|
805 | return typeInst; |
---|
806 | } // if |
---|
807 | assert( false ); |
---|
808 | } |
---|
809 | |
---|
810 | struct VarLenChecker : WithShortCircuiting { |
---|
811 | void previsit( FunctionType * ) { visit_children = false; } |
---|
812 | void previsit( ArrayType * at ) { |
---|
813 | isVarLen |= at->isVarLen; |
---|
814 | } |
---|
815 | bool isVarLen = false; |
---|
816 | }; |
---|
817 | |
---|
818 | bool isVariableLength( Type * t ) { |
---|
819 | PassVisitor<VarLenChecker> varLenChecker; |
---|
820 | maybeAccept( t, varLenChecker ); |
---|
821 | return varLenChecker.pass.isVarLen; |
---|
822 | } |
---|
823 | |
---|
824 | Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) { |
---|
825 | if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) { |
---|
826 | // typedef to the same name from the same scope |
---|
827 | // must be from the same type |
---|
828 | |
---|
829 | Type * t1 = tyDecl->base; |
---|
830 | Type * t2 = typedefNames[ tyDecl->name ].first->base; |
---|
831 | if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) { |
---|
832 | SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name ); |
---|
833 | } |
---|
834 | // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs |
---|
835 | // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs |
---|
836 | // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required |
---|
837 | // to fix this corner case likely outweighs the utility of allowing it. |
---|
838 | if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) { |
---|
839 | SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name ); |
---|
840 | } |
---|
841 | } else { |
---|
842 | typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel ); |
---|
843 | } // if |
---|
844 | |
---|
845 | // When a typedef is a forward declaration: |
---|
846 | // typedef struct screen SCREEN; |
---|
847 | // the declaration portion must be retained: |
---|
848 | // struct screen; |
---|
849 | // because the expansion of the typedef is: |
---|
850 | // void rtn( SCREEN * p ) => void rtn( struct screen * p ) |
---|
851 | // hence the type-name "screen" must be defined. |
---|
852 | // Note, qualifiers on the typedef are superfluous for the forward declaration. |
---|
853 | |
---|
854 | Type * designatorType = tyDecl->base->stripDeclarator(); |
---|
855 | if ( StructInstType * aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) { |
---|
856 | declsToAddBefore.push_back( new StructDecl( aggDecl->name, AggregateDecl::Struct, noAttributes, tyDecl->linkage ) ); |
---|
857 | } else if ( UnionInstType * aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) { |
---|
858 | declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) ); |
---|
859 | } else if ( EnumInstType * enumInst = dynamic_cast< EnumInstType * >( designatorType ) ) { |
---|
860 | // declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, tyDecl->linkage, enumDecl->baseEnum->base ) ); |
---|
861 | if ( enumInst->baseEnum ) { |
---|
862 | const EnumDecl * enumDecl = enumInst->baseEnum; |
---|
863 | declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, enumDecl->isTyped, tyDecl->linkage, enumDecl->base ) ); |
---|
864 | } else { |
---|
865 | declsToAddBefore.push_back( new EnumDecl( enumInst->name, noAttributes, tyDecl->linkage ) ); |
---|
866 | } |
---|
867 | } // if |
---|
868 | return tyDecl->clone(); |
---|
869 | } |
---|
870 | |
---|
871 | void ReplaceTypedef::premutate( TypeDecl * typeDecl ) { |
---|
872 | TypedefMap::iterator i = typedefNames.find( typeDecl->name ); |
---|
873 | if ( i != typedefNames.end() ) { |
---|
874 | typedefNames.erase( i ) ; |
---|
875 | } // if |
---|
876 | |
---|
877 | typedeclNames.insert( typeDecl->name, typeDecl ); |
---|
878 | } |
---|
879 | |
---|
880 | void ReplaceTypedef::premutate( FunctionDecl * ) { |
---|
881 | GuardScope( typedefNames ); |
---|
882 | GuardScope( typedeclNames ); |
---|
883 | } |
---|
884 | |
---|
885 | void ReplaceTypedef::premutate( ObjectDecl * ) { |
---|
886 | GuardScope( typedefNames ); |
---|
887 | GuardScope( typedeclNames ); |
---|
888 | } |
---|
889 | |
---|
890 | DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) { |
---|
891 | if ( FunctionType * funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type? |
---|
892 | // replace the current object declaration with a function declaration |
---|
893 | FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() ); |
---|
894 | objDecl->attributes.clear(); |
---|
895 | objDecl->set_type( nullptr ); |
---|
896 | delete objDecl; |
---|
897 | return newDecl; |
---|
898 | } // if |
---|
899 | return objDecl; |
---|
900 | } |
---|
901 | |
---|
902 | void ReplaceTypedef::premutate( CastExpr * ) { |
---|
903 | GuardScope( typedefNames ); |
---|
904 | GuardScope( typedeclNames ); |
---|
905 | } |
---|
906 | |
---|
907 | void ReplaceTypedef::premutate( CompoundStmt * ) { |
---|
908 | GuardScope( typedefNames ); |
---|
909 | GuardScope( typedeclNames ); |
---|
910 | scopeLevel += 1; |
---|
911 | GuardAction( [this](){ scopeLevel -= 1; } ); |
---|
912 | } |
---|
913 | |
---|
914 | template<typename AggDecl> |
---|
915 | void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) { |
---|
916 | if ( typedefNames.count( aggDecl->get_name() ) == 0 ) { |
---|
917 | Type * type = nullptr; |
---|
918 | if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) { |
---|
919 | type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() ); |
---|
920 | } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) { |
---|
921 | type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() ); |
---|
922 | } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl ) ) { |
---|
923 | type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() ); |
---|
924 | } // if |
---|
925 | TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) ); |
---|
926 | typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel ); |
---|
927 | // add the implicit typedef to the AST |
---|
928 | declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) ); |
---|
929 | } // if |
---|
930 | } |
---|
931 | |
---|
932 | template< typename AggDecl > |
---|
933 | void ReplaceTypedef::handleAggregate( AggDecl * aggr ) { |
---|
934 | SemanticErrorException errors; |
---|
935 | |
---|
936 | ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore ); |
---|
937 | ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter ); |
---|
938 | declsToAddBefore.clear(); |
---|
939 | declsToAddAfter.clear(); |
---|
940 | |
---|
941 | GuardScope( typedefNames ); |
---|
942 | GuardScope( typedeclNames ); |
---|
943 | mutateAll( aggr->parameters, * visitor ); |
---|
944 | mutateAll( aggr->attributes, * visitor ); |
---|
945 | |
---|
946 | // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body. |
---|
947 | for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) { |
---|
948 | if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); } |
---|
949 | |
---|
950 | try { |
---|
951 | * i = maybeMutate( * i, * visitor ); |
---|
952 | } catch ( SemanticErrorException &e ) { |
---|
953 | errors.append( e ); |
---|
954 | } |
---|
955 | |
---|
956 | if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); } |
---|
957 | } |
---|
958 | |
---|
959 | if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); } |
---|
960 | if ( !errors.isEmpty() ) { throw errors; } |
---|
961 | } |
---|
962 | |
---|
963 | void ReplaceTypedef::premutate( StructDecl * structDecl ) { |
---|
964 | visit_children = false; |
---|
965 | addImplicitTypedef( structDecl ); |
---|
966 | handleAggregate( structDecl ); |
---|
967 | } |
---|
968 | |
---|
969 | void ReplaceTypedef::premutate( UnionDecl * unionDecl ) { |
---|
970 | visit_children = false; |
---|
971 | addImplicitTypedef( unionDecl ); |
---|
972 | handleAggregate( unionDecl ); |
---|
973 | } |
---|
974 | |
---|
975 | void ReplaceTypedef::premutate( EnumDecl * enumDecl ) { |
---|
976 | addImplicitTypedef( enumDecl ); |
---|
977 | } |
---|
978 | |
---|
979 | void ReplaceTypedef::premutate( FunctionType * ) { |
---|
980 | GuardValue( inFunctionType ); |
---|
981 | inFunctionType = true; |
---|
982 | } |
---|
983 | |
---|
984 | void ReplaceTypedef::premutate( TraitDecl * ) { |
---|
985 | GuardScope( typedefNames ); |
---|
986 | GuardScope( typedeclNames); |
---|
987 | } |
---|
988 | |
---|
989 | void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) { |
---|
990 | PassVisitor<VerifyCtorDtorAssign> verifier; |
---|
991 | acceptAll( translationUnit, verifier ); |
---|
992 | } |
---|
993 | |
---|
994 | void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) { |
---|
995 | FunctionType * funcType = funcDecl->get_functionType(); |
---|
996 | std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals(); |
---|
997 | std::list< DeclarationWithType * > ¶ms = funcType->get_parameters(); |
---|
998 | |
---|
999 | if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc. |
---|
1000 | if ( params.size() == 0 ) { |
---|
1001 | SemanticError( funcDecl->location, "Constructors, destructors, and assignment functions require at least one parameter." ); |
---|
1002 | } |
---|
1003 | ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() ); |
---|
1004 | if ( ! refType ) { |
---|
1005 | SemanticError( funcDecl->location, "First parameter of a constructor, destructor, or assignment function must be a reference." ); |
---|
1006 | } |
---|
1007 | if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) { |
---|
1008 | if(!returnVals.front()->get_type()->isVoid()) { |
---|
1009 | SemanticError( funcDecl->location, "Constructors and destructors cannot have explicit return values." ); |
---|
1010 | } |
---|
1011 | } |
---|
1012 | } |
---|
1013 | } |
---|
1014 | |
---|
1015 | // Test for special name on a generic parameter. Special treatment for the |
---|
1016 | // special name is a bootstrapping hack. In most cases, the worlds of T's |
---|
1017 | // and of N's don't overlap (normal treamtemt). The foundations in |
---|
1018 | // array.hfa use tagging for both types and dimensions. Tagging treats |
---|
1019 | // its subject parameter even more opaquely than T&, which assumes it is |
---|
1020 | // possible to have a pointer/reference to such an object. Tagging only |
---|
1021 | // seeks to identify the type-system resident at compile time. Both N's |
---|
1022 | // and T's can make tags. The tag definition uses the special name, which |
---|
1023 | // is treated as "an N or a T." This feature is not inteded to be used |
---|
1024 | // outside of the definition and immediate uses of a tag. |
---|
1025 | static inline bool isReservedTysysIdOnlyName( const std::string & name ) { |
---|
1026 | // name's prefix was __CFA_tysys_id_only, before it got wrapped in __..._generic |
---|
1027 | int foundAt = name.find("__CFA_tysys_id_only"); |
---|
1028 | if (foundAt == 0) return true; |
---|
1029 | if (foundAt == 2 && name[0] == '_' && name[1] == '_') return true; |
---|
1030 | return false; |
---|
1031 | } |
---|
1032 | |
---|
1033 | template< typename Aggr > |
---|
1034 | void validateGeneric( Aggr * inst ) { |
---|
1035 | std::list< TypeDecl * > * params = inst->get_baseParameters(); |
---|
1036 | if ( params ) { |
---|
1037 | std::list< Expression * > & args = inst->get_parameters(); |
---|
1038 | |
---|
1039 | // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list). |
---|
1040 | // A substitution is used to ensure that defaults are replaced correctly, e.g., |
---|
1041 | // forall(otype T, otype alloc = heap_allocator(T)) struct vector; |
---|
1042 | // vector(int) v; |
---|
1043 | // after insertion of default values becomes |
---|
1044 | // vector(int, heap_allocator(T)) |
---|
1045 | // and the substitution is built with T=int so that after substitution, the result is |
---|
1046 | // vector(int, heap_allocator(int)) |
---|
1047 | TypeSubstitution sub; |
---|
1048 | auto paramIter = params->begin(); |
---|
1049 | auto argIter = args.begin(); |
---|
1050 | for ( ; paramIter != params->end(); ++paramIter, ++argIter ) { |
---|
1051 | if ( argIter != args.end() ) { |
---|
1052 | TypeExpr * expr = dynamic_cast< TypeExpr * >( * argIter ); |
---|
1053 | if ( expr ) { |
---|
1054 | sub.add( (* paramIter)->get_name(), expr->get_type()->clone() ); |
---|
1055 | } |
---|
1056 | } else { |
---|
1057 | Type * defaultType = (* paramIter)->get_init(); |
---|
1058 | if ( defaultType ) { |
---|
1059 | args.push_back( new TypeExpr( defaultType->clone() ) ); |
---|
1060 | sub.add( (* paramIter)->get_name(), defaultType->clone() ); |
---|
1061 | argIter = std::prev(args.end()); |
---|
1062 | } else { |
---|
1063 | SemanticError( inst, "Too few type arguments in generic type " ); |
---|
1064 | } |
---|
1065 | } |
---|
1066 | assert( argIter != args.end() ); |
---|
1067 | bool typeParamDeclared = (*paramIter)->kind != TypeDecl::Kind::Dimension; |
---|
1068 | bool typeArgGiven; |
---|
1069 | if ( isReservedTysysIdOnlyName( (*paramIter)->name ) ) { |
---|
1070 | // coerce a match when declaration is reserved name, which means "either" |
---|
1071 | typeArgGiven = typeParamDeclared; |
---|
1072 | } else { |
---|
1073 | typeArgGiven = dynamic_cast< TypeExpr * >( * argIter ); |
---|
1074 | } |
---|
1075 | if ( ! typeParamDeclared && typeArgGiven ) SemanticError( inst, "Type argument given for value parameter: " ); |
---|
1076 | if ( typeParamDeclared && ! typeArgGiven ) SemanticError( inst, "Expression argument given for type parameter: " ); |
---|
1077 | } |
---|
1078 | |
---|
1079 | sub.apply( inst ); |
---|
1080 | if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " ); |
---|
1081 | } |
---|
1082 | } |
---|
1083 | |
---|
1084 | void ValidateGenericParameters::previsit( StructInstType * inst ) { |
---|
1085 | validateGeneric( inst ); |
---|
1086 | } |
---|
1087 | |
---|
1088 | void ValidateGenericParameters::previsit( UnionInstType * inst ) { |
---|
1089 | validateGeneric( inst ); |
---|
1090 | } |
---|
1091 | |
---|
1092 | void TranslateDimensionGenericParameters::translateDimensions( std::list< Declaration * > &translationUnit ) { |
---|
1093 | PassVisitor<TranslateDimensionGenericParameters> translator; |
---|
1094 | mutateAll( translationUnit, translator ); |
---|
1095 | } |
---|
1096 | |
---|
1097 | TranslateDimensionGenericParameters::TranslateDimensionGenericParameters() : WithIndexer( false ) {} |
---|
1098 | |
---|
1099 | // Declaration of type variable: forall( [N] ) -> forall( N & | sized( N ) ) |
---|
1100 | TypeDecl * TranslateDimensionGenericParameters::postmutate( TypeDecl * td ) { |
---|
1101 | if ( td->kind == TypeDecl::Dimension ) { |
---|
1102 | td->kind = TypeDecl::Dtype; |
---|
1103 | if ( ! isReservedTysysIdOnlyName( td->name ) ) { |
---|
1104 | td->sized = true; |
---|
1105 | } |
---|
1106 | } |
---|
1107 | return td; |
---|
1108 | } |
---|
1109 | |
---|
1110 | // Situational awareness: |
---|
1111 | // array( float, [[currentExpr]] ) has visitingChildOfSUIT == true |
---|
1112 | // array( float, [[currentExpr]] - 1 ) has visitingChildOfSUIT == false |
---|
1113 | // size_t x = [[currentExpr]] has visitingChildOfSUIT == false |
---|
1114 | void TranslateDimensionGenericParameters::changeState_ChildOfSUIT( bool newVal ) { |
---|
1115 | GuardValue( nextVisitedNodeIsChildOfSUIT ); |
---|
1116 | GuardValue( visitingChildOfSUIT ); |
---|
1117 | visitingChildOfSUIT = nextVisitedNodeIsChildOfSUIT; |
---|
1118 | nextVisitedNodeIsChildOfSUIT = newVal; |
---|
1119 | } |
---|
1120 | void TranslateDimensionGenericParameters::premutate( StructInstType * sit ) { |
---|
1121 | (void) sit; |
---|
1122 | changeState_ChildOfSUIT(true); |
---|
1123 | } |
---|
1124 | void TranslateDimensionGenericParameters::premutate( UnionInstType * uit ) { |
---|
1125 | (void) uit; |
---|
1126 | changeState_ChildOfSUIT(true); |
---|
1127 | } |
---|
1128 | void TranslateDimensionGenericParameters::premutate( BaseSyntaxNode * node ) { |
---|
1129 | (void) node; |
---|
1130 | changeState_ChildOfSUIT(false); |
---|
1131 | } |
---|
1132 | |
---|
1133 | // Passing values as dimension arguments: array( float, 7 ) -> array( float, char[ 7 ] ) |
---|
1134 | // Consuming dimension parameters: size_t x = N - 1 ; -> size_t x = sizeof(N) - 1 ; |
---|
1135 | // Intertwined reality: array( float, N ) -> array( float, N ) |
---|
1136 | // array( float, N - 1 ) -> array( float, char[ sizeof(N) - 1 ] ) |
---|
1137 | // Intertwined case 1 is not just an optimization. |
---|
1138 | // Avoiding char[sizeof(-)] is necessary to enable the call of f to bind the value of N, in: |
---|
1139 | // forall([N]) void f( array(float, N) & ); |
---|
1140 | // array(float, 7) a; |
---|
1141 | // f(a); |
---|
1142 | |
---|
1143 | Expression * TranslateDimensionGenericParameters::postmutate( DimensionExpr * de ) { |
---|
1144 | // Expression de is an occurrence of N in LHS of above examples. |
---|
1145 | // Look up the name that de references. |
---|
1146 | // If we are in a struct body, then this reference can be to an entry of the stuct's forall list. |
---|
1147 | // Whether or not we are in a struct body, this reference can be to an entry of a containing function's forall list. |
---|
1148 | // If we are in a struct body, then the stuct's forall declarations are innermost (functions don't occur in structs). |
---|
1149 | // Thus, a potential struct's declaration is highest priority. |
---|
1150 | // A struct's forall declarations are already renamed with _generic_ suffix. Try that name variant first. |
---|
1151 | |
---|
1152 | std::string useName = "__" + de->name + "_generic_"; |
---|
1153 | TypeDecl * namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) ); |
---|
1154 | |
---|
1155 | if ( ! namedParamDecl ) { |
---|
1156 | useName = de->name; |
---|
1157 | namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) ); |
---|
1158 | } |
---|
1159 | |
---|
1160 | // Expect to find it always. A misspelled name would have been parsed as an identifier. |
---|
1161 | assert( namedParamDecl && "Type-system-managed value name not found in symbol table" ); |
---|
1162 | |
---|
1163 | delete de; |
---|
1164 | |
---|
1165 | TypeInstType * refToDecl = new TypeInstType( 0, useName, namedParamDecl ); |
---|
1166 | |
---|
1167 | if ( visitingChildOfSUIT ) { |
---|
1168 | // As in postmutate( Expression * ), topmost expression needs a TypeExpr wrapper |
---|
1169 | // But avoid ArrayType-Sizeof |
---|
1170 | return new TypeExpr( refToDecl ); |
---|
1171 | } else { |
---|
1172 | // the N occurrence is being used directly as a runtime value, |
---|
1173 | // if we are in a type instantiation, then the N is within a bigger value computation |
---|
1174 | return new SizeofExpr( refToDecl ); |
---|
1175 | } |
---|
1176 | } |
---|
1177 | |
---|
1178 | Expression * TranslateDimensionGenericParameters::postmutate( Expression * e ) { |
---|
1179 | if ( visitingChildOfSUIT ) { |
---|
1180 | // e is an expression used as an argument to instantiate a type |
---|
1181 | if (! dynamic_cast< TypeExpr * >( e ) ) { |
---|
1182 | // e is a value expression |
---|
1183 | // but not a DimensionExpr, which has a distinct postmutate |
---|
1184 | Type * typeExprContent = new ArrayType( 0, new BasicType( 0, BasicType::Char ), e, true, false ); |
---|
1185 | TypeExpr * result = new TypeExpr( typeExprContent ); |
---|
1186 | return result; |
---|
1187 | } |
---|
1188 | } |
---|
1189 | return e; |
---|
1190 | } |
---|
1191 | |
---|
1192 | void CompoundLiteral::premutate( ObjectDecl * objectDecl ) { |
---|
1193 | storageClasses = objectDecl->get_storageClasses(); |
---|
1194 | } |
---|
1195 | |
---|
1196 | Expression * CompoundLiteral::postmutate( CompoundLiteralExpr * compLitExpr ) { |
---|
1197 | // transform [storage_class] ... (struct S){ 3, ... }; |
---|
1198 | // into [storage_class] struct S temp = { 3, ... }; |
---|
1199 | static UniqueName indexName( "_compLit" ); |
---|
1200 | |
---|
1201 | ObjectDecl * tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() ); |
---|
1202 | compLitExpr->set_result( nullptr ); |
---|
1203 | compLitExpr->set_initializer( nullptr ); |
---|
1204 | delete compLitExpr; |
---|
1205 | declsToAddBefore.push_back( tempvar ); // add modified temporary to current block |
---|
1206 | return new VariableExpr( tempvar ); |
---|
1207 | } |
---|
1208 | |
---|
1209 | void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) { |
---|
1210 | PassVisitor<ReturnTypeFixer> fixer; |
---|
1211 | acceptAll( translationUnit, fixer ); |
---|
1212 | } |
---|
1213 | |
---|
1214 | void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) { |
---|
1215 | FunctionType * ftype = functionDecl->get_functionType(); |
---|
1216 | std::list< DeclarationWithType * > & retVals = ftype->get_returnVals(); |
---|
1217 | assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() ); |
---|
1218 | if ( retVals.size() == 1 ) { |
---|
1219 | // ensure all function return values have a name - use the name of the function to disambiguate (this also provides a nice bit of help for debugging). |
---|
1220 | // ensure other return values have a name. |
---|
1221 | DeclarationWithType * ret = retVals.front(); |
---|
1222 | if ( ret->get_name() == "" ) { |
---|
1223 | ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) ); |
---|
1224 | } |
---|
1225 | ret->get_attributes().push_back( new Attribute( "unused" ) ); |
---|
1226 | } |
---|
1227 | } |
---|
1228 | |
---|
1229 | void ReturnTypeFixer::postvisit( FunctionType * ftype ) { |
---|
1230 | // xxx - need to handle named return values - this information needs to be saved somehow |
---|
1231 | // so that resolution has access to the names. |
---|
1232 | // Note that this pass needs to happen early so that other passes which look for tuple types |
---|
1233 | // find them in all of the right places, including function return types. |
---|
1234 | std::list< DeclarationWithType * > & retVals = ftype->get_returnVals(); |
---|
1235 | if ( retVals.size() > 1 ) { |
---|
1236 | // generate a single return parameter which is the tuple of all of the return values |
---|
1237 | TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) ); |
---|
1238 | // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false. |
---|
1239 | ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer *>(), noDesignators, false ) ); |
---|
1240 | deleteAll( retVals ); |
---|
1241 | retVals.clear(); |
---|
1242 | retVals.push_back( newRet ); |
---|
1243 | } |
---|
1244 | } |
---|
1245 | |
---|
1246 | void FixObjectType::fix( std::list< Declaration * > & translationUnit ) { |
---|
1247 | PassVisitor<FixObjectType> fixer; |
---|
1248 | acceptAll( translationUnit, fixer ); |
---|
1249 | } |
---|
1250 | |
---|
1251 | void FixObjectType::previsit( ObjectDecl * objDecl ) { |
---|
1252 | Type * new_type = ResolvExpr::resolveTypeof( objDecl->get_type(), indexer ); |
---|
1253 | objDecl->set_type( new_type ); |
---|
1254 | } |
---|
1255 | |
---|
1256 | void FixObjectType::previsit( FunctionDecl * funcDecl ) { |
---|
1257 | Type * new_type = ResolvExpr::resolveTypeof( funcDecl->type, indexer ); |
---|
1258 | funcDecl->set_type( new_type ); |
---|
1259 | } |
---|
1260 | |
---|
1261 | void FixObjectType::previsit( TypeDecl * typeDecl ) { |
---|
1262 | if ( typeDecl->get_base() ) { |
---|
1263 | Type * new_type = ResolvExpr::resolveTypeof( typeDecl->get_base(), indexer ); |
---|
1264 | typeDecl->set_base( new_type ); |
---|
1265 | } // if |
---|
1266 | } |
---|
1267 | |
---|
1268 | void InitializerLength::computeLength( std::list< Declaration * > & translationUnit ) { |
---|
1269 | PassVisitor<InitializerLength> len; |
---|
1270 | acceptAll( translationUnit, len ); |
---|
1271 | } |
---|
1272 | |
---|
1273 | void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) { |
---|
1274 | PassVisitor<ArrayLength> len; |
---|
1275 | acceptAll( translationUnit, len ); |
---|
1276 | } |
---|
1277 | |
---|
1278 | void InitializerLength::previsit( ObjectDecl * objDecl ) { |
---|
1279 | if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) { |
---|
1280 | if ( at->dimension ) return; |
---|
1281 | if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) { |
---|
1282 | at->dimension = new ConstantExpr( Constant::from_ulong( init->initializers.size() ) ); |
---|
1283 | } |
---|
1284 | } |
---|
1285 | } |
---|
1286 | |
---|
1287 | void ArrayLength::previsit( ArrayType * type ) { |
---|
1288 | if ( type->dimension ) { |
---|
1289 | // need to resolve array dimensions early so that constructor code can correctly determine |
---|
1290 | // if a type is a VLA (and hence whether its elements need to be constructed) |
---|
1291 | ResolvExpr::findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer ); |
---|
1292 | |
---|
1293 | // must re-evaluate whether a type is a VLA, now that more information is available |
---|
1294 | // (e.g. the dimension may have been an enumerator, which was unknown prior to this step) |
---|
1295 | type->isVarLen = ! InitTweak::isConstExpr( type->dimension ); |
---|
1296 | } |
---|
1297 | } |
---|
1298 | |
---|
1299 | struct LabelFinder { |
---|
1300 | std::set< Label > & labels; |
---|
1301 | LabelFinder( std::set< Label > & labels ) : labels( labels ) {} |
---|
1302 | void previsit( Statement * stmt ) { |
---|
1303 | for ( Label & l : stmt->labels ) { |
---|
1304 | labels.insert( l ); |
---|
1305 | } |
---|
1306 | } |
---|
1307 | }; |
---|
1308 | |
---|
1309 | void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) { |
---|
1310 | GuardValue( labels ); |
---|
1311 | PassVisitor<LabelFinder> finder( labels ); |
---|
1312 | funcDecl->accept( finder ); |
---|
1313 | } |
---|
1314 | |
---|
1315 | Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) { |
---|
1316 | // convert &&label into label address |
---|
1317 | if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) { |
---|
1318 | if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) { |
---|
1319 | if ( labels.count( nameExpr->name ) ) { |
---|
1320 | Label name = nameExpr->name; |
---|
1321 | delete addrExpr; |
---|
1322 | return new LabelAddressExpr( name ); |
---|
1323 | } |
---|
1324 | } |
---|
1325 | } |
---|
1326 | return addrExpr; |
---|
1327 | } |
---|
1328 | |
---|
1329 | namespace { |
---|
1330 | /// Replaces enum types by int, and function/array types in function parameter and return |
---|
1331 | /// lists by appropriate pointers |
---|
1332 | /* |
---|
1333 | struct EnumAndPointerDecay_new { |
---|
1334 | const ast::EnumDecl * previsit( const ast::EnumDecl * enumDecl ) { |
---|
1335 | // set the type of each member of the enumeration to be EnumConstant |
---|
1336 | for ( unsigned i = 0; i < enumDecl->members.size(); ++i ) { |
---|
1337 | // build new version of object with EnumConstant |
---|
1338 | ast::ptr< ast::ObjectDecl > obj = |
---|
1339 | enumDecl->members[i].strict_as< ast::ObjectDecl >(); |
---|
1340 | obj.get_and_mutate()->type = |
---|
1341 | new ast::EnumInstType{ enumDecl->name, ast::CV::Const }; |
---|
1342 | |
---|
1343 | // set into decl |
---|
1344 | ast::EnumDecl * mut = mutate( enumDecl ); |
---|
1345 | mut->members[i] = obj.get(); |
---|
1346 | enumDecl = mut; |
---|
1347 | } |
---|
1348 | return enumDecl; |
---|
1349 | } |
---|
1350 | |
---|
1351 | static const ast::FunctionType * fixFunctionList( |
---|
1352 | const ast::FunctionType * func, |
---|
1353 | std::vector< ast::ptr< ast::DeclWithType > > ast::FunctionType::* field, |
---|
1354 | ast::ArgumentFlag isVarArgs = ast::FixedArgs |
---|
1355 | ) { |
---|
1356 | const auto & dwts = func->* field; |
---|
1357 | unsigned nvals = dwts.size(); |
---|
1358 | bool hasVoid = false; |
---|
1359 | for ( unsigned i = 0; i < nvals; ++i ) { |
---|
1360 | func = ast::mutate_field_index( func, field, i, fixFunction( dwts[i], hasVoid ) ); |
---|
1361 | } |
---|
1362 | |
---|
1363 | // the only case in which "void" is valid is where it is the only one in the list |
---|
1364 | if ( hasVoid && ( nvals > 1 || isVarArgs ) ) { |
---|
1365 | SemanticError( |
---|
1366 | dwts.front()->location, func, "invalid type void in function type" ); |
---|
1367 | } |
---|
1368 | |
---|
1369 | // one void is the only thing in the list, remove it |
---|
1370 | if ( hasVoid ) { |
---|
1371 | func = ast::mutate_field( |
---|
1372 | func, field, std::vector< ast::ptr< ast::DeclWithType > >{} ); |
---|
1373 | } |
---|
1374 | |
---|
1375 | return func; |
---|
1376 | } |
---|
1377 | |
---|
1378 | const ast::FunctionType * previsit( const ast::FunctionType * func ) { |
---|
1379 | func = fixFunctionList( func, &ast::FunctionType::params, func->isVarArgs ); |
---|
1380 | return fixFunctionList( func, &ast::FunctionType::returns ); |
---|
1381 | } |
---|
1382 | }; |
---|
1383 | |
---|
1384 | /// expand assertions from a trait instance, performing appropriate type variable substitutions |
---|
1385 | void expandAssertions( |
---|
1386 | const ast::TraitInstType * inst, std::vector< ast::ptr< ast::DeclWithType > > & out |
---|
1387 | ) { |
---|
1388 | assertf( inst->base, "Trait instance not linked to base trait: %s", toCString( inst ) ); |
---|
1389 | |
---|
1390 | // build list of trait members, substituting trait decl parameters for instance parameters |
---|
1391 | ast::TypeSubstitution sub{ |
---|
1392 | inst->base->params.begin(), inst->base->params.end(), inst->params.begin() }; |
---|
1393 | // deliberately take ast::ptr by-value to ensure this does not mutate inst->base |
---|
1394 | for ( ast::ptr< ast::Decl > decl : inst->base->members ) { |
---|
1395 | auto member = decl.strict_as< ast::DeclWithType >(); |
---|
1396 | sub.apply( member ); |
---|
1397 | out.emplace_back( member ); |
---|
1398 | } |
---|
1399 | } |
---|
1400 | |
---|
1401 | /// Associates forward declarations of aggregates with their definitions |
---|
1402 | class LinkReferenceToTypes_new final |
---|
1403 | : public ast::WithSymbolTable, public ast::WithGuards, public |
---|
1404 | ast::WithVisitorRef<LinkReferenceToTypes_new>, public ast::WithShortCircuiting { |
---|
1405 | |
---|
1406 | // these maps of uses of forward declarations of types need to have the actual type |
---|
1407 | // declaration switched in * after * they have been traversed. To enable this in the |
---|
1408 | // ast::Pass framework, any node that needs to be so mutated has mutate() called on it |
---|
1409 | // before it is placed in the map, properly updating its parents in the usual traversal, |
---|
1410 | // then can have the actual mutation applied later |
---|
1411 | using ForwardEnumsType = std::unordered_multimap< std::string, ast::EnumInstType * >; |
---|
1412 | using ForwardStructsType = std::unordered_multimap< std::string, ast::StructInstType * >; |
---|
1413 | using ForwardUnionsType = std::unordered_multimap< std::string, ast::UnionInstType * >; |
---|
1414 | |
---|
1415 | const CodeLocation & location; |
---|
1416 | const ast::SymbolTable * localSymtab; |
---|
1417 | |
---|
1418 | ForwardEnumsType forwardEnums; |
---|
1419 | ForwardStructsType forwardStructs; |
---|
1420 | ForwardUnionsType forwardUnions; |
---|
1421 | |
---|
1422 | /// true if currently in a generic type body, so that type parameter instances can be |
---|
1423 | /// renamed appropriately |
---|
1424 | bool inGeneric = false; |
---|
1425 | |
---|
1426 | public: |
---|
1427 | /// contstruct using running symbol table |
---|
1428 | LinkReferenceToTypes_new( const CodeLocation & loc ) |
---|
1429 | : location( loc ), localSymtab( &symtab ) {} |
---|
1430 | |
---|
1431 | /// construct using provided symbol table |
---|
1432 | LinkReferenceToTypes_new( const CodeLocation & loc, const ast::SymbolTable & syms ) |
---|
1433 | : location( loc ), localSymtab( &syms ) {} |
---|
1434 | |
---|
1435 | const ast::Type * postvisit( const ast::TypeInstType * typeInst ) { |
---|
1436 | // ensure generic parameter instances are renamed like the base type |
---|
1437 | if ( inGeneric && typeInst->base ) { |
---|
1438 | typeInst = ast::mutate_field( |
---|
1439 | typeInst, &ast::TypeInstType::name, typeInst->base->name ); |
---|
1440 | } |
---|
1441 | |
---|
1442 | if ( |
---|
1443 | auto typeDecl = dynamic_cast< const ast::TypeDecl * >( |
---|
1444 | localSymtab->lookupType( typeInst->name ) ) |
---|
1445 | ) { |
---|
1446 | typeInst = ast::mutate_field( typeInst, &ast::TypeInstType::kind, typeDecl->kind ); |
---|
1447 | } |
---|
1448 | |
---|
1449 | return typeInst; |
---|
1450 | } |
---|
1451 | |
---|
1452 | const ast::Type * postvisit( const ast::EnumInstType * inst ) { |
---|
1453 | const ast::EnumDecl * decl = localSymtab->lookupEnum( inst->name ); |
---|
1454 | // not a semantic error if the enum is not found, just an implicit forward declaration |
---|
1455 | if ( decl ) { |
---|
1456 | inst = ast::mutate_field( inst, &ast::EnumInstType::base, decl ); |
---|
1457 | } |
---|
1458 | if ( ! decl || ! decl->body ) { |
---|
1459 | // forward declaration |
---|
1460 | auto mut = mutate( inst ); |
---|
1461 | forwardEnums.emplace( inst->name, mut ); |
---|
1462 | inst = mut; |
---|
1463 | } |
---|
1464 | return inst; |
---|
1465 | } |
---|
1466 | |
---|
1467 | void checkGenericParameters( const ast::BaseInstType * inst ) { |
---|
1468 | for ( const ast::Expr * param : inst->params ) { |
---|
1469 | if ( ! dynamic_cast< const ast::TypeExpr * >( param ) ) { |
---|
1470 | SemanticError( |
---|
1471 | location, inst, "Expression parameters for generic types are currently " |
---|
1472 | "unsupported: " ); |
---|
1473 | } |
---|
1474 | } |
---|
1475 | } |
---|
1476 | |
---|
1477 | const ast::StructInstType * postvisit( const ast::StructInstType * inst ) { |
---|
1478 | const ast::StructDecl * decl = localSymtab->lookupStruct( inst->name ); |
---|
1479 | // not a semantic error if the struct is not found, just an implicit forward declaration |
---|
1480 | if ( decl ) { |
---|
1481 | inst = ast::mutate_field( inst, &ast::StructInstType::base, decl ); |
---|
1482 | } |
---|
1483 | if ( ! decl || ! decl->body ) { |
---|
1484 | // forward declaration |
---|
1485 | auto mut = mutate( inst ); |
---|
1486 | forwardStructs.emplace( inst->name, mut ); |
---|
1487 | inst = mut; |
---|
1488 | } |
---|
1489 | checkGenericParameters( inst ); |
---|
1490 | return inst; |
---|
1491 | } |
---|
1492 | |
---|
1493 | const ast::UnionInstType * postvisit( const ast::UnionInstType * inst ) { |
---|
1494 | const ast::UnionDecl * decl = localSymtab->lookupUnion( inst->name ); |
---|
1495 | // not a semantic error if the struct is not found, just an implicit forward declaration |
---|
1496 | if ( decl ) { |
---|
1497 | inst = ast::mutate_field( inst, &ast::UnionInstType::base, decl ); |
---|
1498 | } |
---|
1499 | if ( ! decl || ! decl->body ) { |
---|
1500 | // forward declaration |
---|
1501 | auto mut = mutate( inst ); |
---|
1502 | forwardUnions.emplace( inst->name, mut ); |
---|
1503 | inst = mut; |
---|
1504 | } |
---|
1505 | checkGenericParameters( inst ); |
---|
1506 | return inst; |
---|
1507 | } |
---|
1508 | |
---|
1509 | const ast::Type * postvisit( const ast::TraitInstType * traitInst ) { |
---|
1510 | // handle other traits |
---|
1511 | const ast::TraitDecl * traitDecl = localSymtab->lookupTrait( traitInst->name ); |
---|
1512 | if ( ! traitDecl ) { |
---|
1513 | SemanticError( location, "use of undeclared trait " + traitInst->name ); |
---|
1514 | } |
---|
1515 | if ( traitDecl->params.size() != traitInst->params.size() ) { |
---|
1516 | SemanticError( location, traitInst, "incorrect number of trait parameters: " ); |
---|
1517 | } |
---|
1518 | traitInst = ast::mutate_field( traitInst, &ast::TraitInstType::base, traitDecl ); |
---|
1519 | |
---|
1520 | // need to carry over the "sized" status of each decl in the instance |
---|
1521 | for ( unsigned i = 0; i < traitDecl->params.size(); ++i ) { |
---|
1522 | auto expr = traitInst->params[i].as< ast::TypeExpr >(); |
---|
1523 | if ( ! expr ) { |
---|
1524 | SemanticError( |
---|
1525 | traitInst->params[i].get(), "Expression parameters for trait instances " |
---|
1526 | "are currently unsupported: " ); |
---|
1527 | } |
---|
1528 | |
---|
1529 | if ( auto inst = expr->type.as< ast::TypeInstType >() ) { |
---|
1530 | if ( traitDecl->params[i]->sized && ! inst->base->sized ) { |
---|
1531 | // traitInst = ast::mutate_field_index( |
---|
1532 | // traitInst, &ast::TraitInstType::params, i, |
---|
1533 | // ... |
---|
1534 | // ); |
---|
1535 | ast::TraitInstType * mut = ast::mutate( traitInst ); |
---|
1536 | ast::chain_mutate( mut->params[i] ) |
---|
1537 | ( &ast::TypeExpr::type ) |
---|
1538 | ( &ast::TypeInstType::base )->sized = true; |
---|
1539 | traitInst = mut; |
---|
1540 | } |
---|
1541 | } |
---|
1542 | } |
---|
1543 | |
---|
1544 | return traitInst; |
---|
1545 | } |
---|
1546 | |
---|
1547 | void previsit( const ast::QualifiedType * ) { visit_children = false; } |
---|
1548 | |
---|
1549 | const ast::Type * postvisit( const ast::QualifiedType * qualType ) { |
---|
1550 | // linking only makes sense for the "oldest ancestor" of the qualified type |
---|
1551 | return ast::mutate_field( |
---|
1552 | qualType, &ast::QualifiedType::parent, qualType->parent->accept( * visitor ) ); |
---|
1553 | } |
---|
1554 | |
---|
1555 | const ast::Decl * postvisit( const ast::EnumDecl * enumDecl ) { |
---|
1556 | // visit enum members first so that the types of self-referencing members are updated |
---|
1557 | // properly |
---|
1558 | if ( ! enumDecl->body ) return enumDecl; |
---|
1559 | |
---|
1560 | // update forward declarations to point here |
---|
1561 | auto fwds = forwardEnums.equal_range( enumDecl->name ); |
---|
1562 | if ( fwds.first != fwds.second ) { |
---|
1563 | auto inst = fwds.first; |
---|
1564 | do { |
---|
1565 | // forward decl is stored * mutably * in map, can thus be updated |
---|
1566 | inst->second->base = enumDecl; |
---|
1567 | } while ( ++inst != fwds.second ); |
---|
1568 | forwardEnums.erase( fwds.first, fwds.second ); |
---|
1569 | } |
---|
1570 | |
---|
1571 | // ensure that enumerator initializers are properly set |
---|
1572 | for ( unsigned i = 0; i < enumDecl->members.size(); ++i ) { |
---|
1573 | auto field = enumDecl->members[i].strict_as< ast::ObjectDecl >(); |
---|
1574 | if ( field->init ) { |
---|
1575 | // need to resolve enumerator initializers early so that other passes that |
---|
1576 | // determine if an expression is constexpr have appropriate information |
---|
1577 | auto init = field->init.strict_as< ast::SingleInit >(); |
---|
1578 | |
---|
1579 | enumDecl = ast::mutate_field_index( |
---|
1580 | enumDecl, &ast::EnumDecl::members, i, |
---|
1581 | ast::mutate_field( field, &ast::ObjectDecl::init, |
---|
1582 | ast::mutate_field( init, &ast::SingleInit::value, |
---|
1583 | ResolvExpr::findSingleExpression( |
---|
1584 | init->value, new ast::BasicType{ ast::BasicType::SignedInt }, |
---|
1585 | symtab ) ) ) ); |
---|
1586 | } |
---|
1587 | } |
---|
1588 | |
---|
1589 | return enumDecl; |
---|
1590 | } |
---|
1591 | |
---|
1592 | /// rename generic type parameters uniquely so that they do not conflict with user defined |
---|
1593 | /// function forall parameters, e.g. the T in Box and the T in f, below |
---|
1594 | /// forall(otype T) |
---|
1595 | /// struct Box { |
---|
1596 | /// T x; |
---|
1597 | /// }; |
---|
1598 | /// forall(otype T) |
---|
1599 | /// void f(Box(T) b) { |
---|
1600 | /// ... |
---|
1601 | /// } |
---|
1602 | template< typename AggrDecl > |
---|
1603 | const AggrDecl * renameGenericParams( const AggrDecl * aggr ) { |
---|
1604 | GuardValue( inGeneric ); |
---|
1605 | inGeneric = ! aggr->params.empty(); |
---|
1606 | |
---|
1607 | for ( unsigned i = 0; i < aggr->params.size(); ++i ) { |
---|
1608 | const ast::TypeDecl * td = aggr->params[i]; |
---|
1609 | |
---|
1610 | aggr = ast::mutate_field_index( |
---|
1611 | aggr, &AggrDecl::params, i, |
---|
1612 | ast::mutate_field( td, &ast::TypeDecl::name, "__" + td->name + "_generic_" ) ); |
---|
1613 | } |
---|
1614 | return aggr; |
---|
1615 | } |
---|
1616 | |
---|
1617 | const ast::StructDecl * previsit( const ast::StructDecl * structDecl ) { |
---|
1618 | return renameGenericParams( structDecl ); |
---|
1619 | } |
---|
1620 | |
---|
1621 | void postvisit( const ast::StructDecl * structDecl ) { |
---|
1622 | // visit struct members first so that the types of self-referencing members are |
---|
1623 | // updated properly |
---|
1624 | if ( ! structDecl->body ) return; |
---|
1625 | |
---|
1626 | // update forward declarations to point here |
---|
1627 | auto fwds = forwardStructs.equal_range( structDecl->name ); |
---|
1628 | if ( fwds.first != fwds.second ) { |
---|
1629 | auto inst = fwds.first; |
---|
1630 | do { |
---|
1631 | // forward decl is stored * mutably * in map, can thus be updated |
---|
1632 | inst->second->base = structDecl; |
---|
1633 | } while ( ++inst != fwds.second ); |
---|
1634 | forwardStructs.erase( fwds.first, fwds.second ); |
---|
1635 | } |
---|
1636 | } |
---|
1637 | |
---|
1638 | const ast::UnionDecl * previsit( const ast::UnionDecl * unionDecl ) { |
---|
1639 | return renameGenericParams( unionDecl ); |
---|
1640 | } |
---|
1641 | |
---|
1642 | void postvisit( const ast::UnionDecl * unionDecl ) { |
---|
1643 | // visit union members first so that the types of self-referencing members are updated |
---|
1644 | // properly |
---|
1645 | if ( ! unionDecl->body ) return; |
---|
1646 | |
---|
1647 | // update forward declarations to point here |
---|
1648 | auto fwds = forwardUnions.equal_range( unionDecl->name ); |
---|
1649 | if ( fwds.first != fwds.second ) { |
---|
1650 | auto inst = fwds.first; |
---|
1651 | do { |
---|
1652 | // forward decl is stored * mutably * in map, can thus be updated |
---|
1653 | inst->second->base = unionDecl; |
---|
1654 | } while ( ++inst != fwds.second ); |
---|
1655 | forwardUnions.erase( fwds.first, fwds.second ); |
---|
1656 | } |
---|
1657 | } |
---|
1658 | |
---|
1659 | const ast::Decl * postvisit( const ast::TraitDecl * traitDecl ) { |
---|
1660 | // set the "sized" status for the special "sized" trait |
---|
1661 | if ( traitDecl->name == "sized" ) { |
---|
1662 | assertf( traitDecl->params.size() == 1, "Built-in trait 'sized' has incorrect " |
---|
1663 | "number of parameters: %zd", traitDecl->params.size() ); |
---|
1664 | |
---|
1665 | traitDecl = ast::mutate_field_index( |
---|
1666 | traitDecl, &ast::TraitDecl::params, 0, |
---|
1667 | ast::mutate_field( |
---|
1668 | traitDecl->params.front().get(), &ast::TypeDecl::sized, true ) ); |
---|
1669 | } |
---|
1670 | |
---|
1671 | // move assertions from type parameters into the body of the trait |
---|
1672 | std::vector< ast::ptr< ast::DeclWithType > > added; |
---|
1673 | for ( const ast::TypeDecl * td : traitDecl->params ) { |
---|
1674 | for ( const ast::DeclWithType * assn : td->assertions ) { |
---|
1675 | auto inst = dynamic_cast< const ast::TraitInstType * >( assn->get_type() ); |
---|
1676 | if ( inst ) { |
---|
1677 | expandAssertions( inst, added ); |
---|
1678 | } else { |
---|
1679 | added.emplace_back( assn ); |
---|
1680 | } |
---|
1681 | } |
---|
1682 | } |
---|
1683 | if ( ! added.empty() ) { |
---|
1684 | auto mut = mutate( traitDecl ); |
---|
1685 | for ( const ast::DeclWithType * decl : added ) { |
---|
1686 | mut->members.emplace_back( decl ); |
---|
1687 | } |
---|
1688 | traitDecl = mut; |
---|
1689 | } |
---|
1690 | |
---|
1691 | return traitDecl; |
---|
1692 | } |
---|
1693 | }; |
---|
1694 | |
---|
1695 | /// Replaces array and function types in forall lists by appropriate pointer type and assigns |
---|
1696 | /// each object and function declaration a unique ID |
---|
1697 | class ForallPointerDecay_new { |
---|
1698 | const CodeLocation & location; |
---|
1699 | public: |
---|
1700 | ForallPointerDecay_new( const CodeLocation & loc ) : location( loc ) {} |
---|
1701 | |
---|
1702 | const ast::ObjectDecl * previsit( const ast::ObjectDecl * obj ) { |
---|
1703 | // ensure that operator names only apply to functions or function pointers |
---|
1704 | if ( |
---|
1705 | CodeGen::isOperator( obj->name ) |
---|
1706 | && ! dynamic_cast< const ast::FunctionType * >( obj->type->stripDeclarator() ) |
---|
1707 | ) { |
---|
1708 | SemanticError( obj->location, toCString( "operator ", obj->name.c_str(), " is not " |
---|
1709 | "a function or function pointer." ) ); |
---|
1710 | } |
---|
1711 | |
---|
1712 | // ensure object has unique ID |
---|
1713 | if ( obj->uniqueId ) return obj; |
---|
1714 | auto mut = mutate( obj ); |
---|
1715 | mut->fixUniqueId(); |
---|
1716 | return mut; |
---|
1717 | } |
---|
1718 | |
---|
1719 | const ast::FunctionDecl * previsit( const ast::FunctionDecl * func ) { |
---|
1720 | // ensure function has unique ID |
---|
1721 | if ( func->uniqueId ) return func; |
---|
1722 | auto mut = mutate( func ); |
---|
1723 | mut->fixUniqueId(); |
---|
1724 | return mut; |
---|
1725 | } |
---|
1726 | |
---|
1727 | /// Fix up assertions -- flattens assertion lists, removing all trait instances |
---|
1728 | template< typename node_t, typename parent_t > |
---|
1729 | static const node_t * forallFixer( |
---|
1730 | const CodeLocation & loc, const node_t * node, |
---|
1731 | ast::FunctionType::ForallList parent_t::* forallField |
---|
1732 | ) { |
---|
1733 | for ( unsigned i = 0; i < (node->* forallField).size(); ++i ) { |
---|
1734 | const ast::TypeDecl * type = (node->* forallField)[i]; |
---|
1735 | if ( type->assertions.empty() ) continue; |
---|
1736 | |
---|
1737 | std::vector< ast::ptr< ast::DeclWithType > > asserts; |
---|
1738 | asserts.reserve( type->assertions.size() ); |
---|
1739 | |
---|
1740 | // expand trait instances into their members |
---|
1741 | for ( const ast::DeclWithType * assn : type->assertions ) { |
---|
1742 | auto traitInst = |
---|
1743 | dynamic_cast< const ast::TraitInstType * >( assn->get_type() ); |
---|
1744 | if ( traitInst ) { |
---|
1745 | // expand trait instance to all its members |
---|
1746 | expandAssertions( traitInst, asserts ); |
---|
1747 | } else { |
---|
1748 | // pass other assertions through |
---|
1749 | asserts.emplace_back( assn ); |
---|
1750 | } |
---|
1751 | } |
---|
1752 | |
---|
1753 | // apply FixFunction to every assertion to check for invalid void type |
---|
1754 | for ( ast::ptr< ast::DeclWithType > & assn : asserts ) { |
---|
1755 | bool isVoid = false; |
---|
1756 | assn = fixFunction( assn, isVoid ); |
---|
1757 | if ( isVoid ) { |
---|
1758 | SemanticError( loc, node, "invalid type void in assertion of function " ); |
---|
1759 | } |
---|
1760 | } |
---|
1761 | |
---|
1762 | // place mutated assertion list in node |
---|
1763 | auto mut = mutate( type ); |
---|
1764 | mut->assertions = move( asserts ); |
---|
1765 | node = ast::mutate_field_index( node, forallField, i, mut ); |
---|
1766 | } |
---|
1767 | return node; |
---|
1768 | } |
---|
1769 | |
---|
1770 | const ast::FunctionType * previsit( const ast::FunctionType * ftype ) { |
---|
1771 | return forallFixer( location, ftype, &ast::FunctionType::forall ); |
---|
1772 | } |
---|
1773 | |
---|
1774 | const ast::StructDecl * previsit( const ast::StructDecl * aggrDecl ) { |
---|
1775 | return forallFixer( aggrDecl->location, aggrDecl, &ast::StructDecl::params ); |
---|
1776 | } |
---|
1777 | |
---|
1778 | const ast::UnionDecl * previsit( const ast::UnionDecl * aggrDecl ) { |
---|
1779 | return forallFixer( aggrDecl->location, aggrDecl, &ast::UnionDecl::params ); |
---|
1780 | } |
---|
1781 | }; |
---|
1782 | */ |
---|
1783 | } // anonymous namespace |
---|
1784 | |
---|
1785 | /* |
---|
1786 | const ast::Type * validateType( |
---|
1787 | const CodeLocation & loc, const ast::Type * type, const ast::SymbolTable & symtab ) { |
---|
1788 | // ast::Pass< EnumAndPointerDecay_new > epc; |
---|
1789 | ast::Pass< LinkReferenceToTypes_new > lrt{ loc, symtab }; |
---|
1790 | ast::Pass< ForallPointerDecay_new > fpd{ loc }; |
---|
1791 | |
---|
1792 | return type->accept( lrt )->accept( fpd ); |
---|
1793 | } |
---|
1794 | */ |
---|
1795 | |
---|
1796 | } // namespace SymTab |
---|
1797 | |
---|
1798 | // Local Variables: // |
---|
1799 | // tab-width: 4 // |
---|
1800 | // mode: c++ // |
---|
1801 | // compile-command: "make install" // |
---|
1802 | // End: // |
---|