source: src/SymTab/Validate.cc@ e5d9274

ADT ast-experimental pthread-emulation qualifiedEnum
Last change on this file since e5d9274 was 9939dc3, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Reduced the number of object files linked into the demangler. Some of the divisions are rather odd, Lvalue2 and FixMain2, but they should be a better base to work from. Also improved the calling of the impurity detector visitors slightly.

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