source: src/SymTab/Validate.cc@ fb2bde4

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since fb2bde4 was 18e683b, checked in by Aaron Moss <a3moss@…>, 6 years ago

Port LinkReferenceToTypes pass

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