source: src/SymTab/Validate.cc@ ffec1bf

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

Removed the validate sub-pass interface. This also showed an extra include in CandidateFinder, also removed.

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