source: src/SymTab/Validate.cc@ 572a02f

ADT ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 572a02f was 798a8b3, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Attributes are now correctly visited when replacing typedefs

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