source: src/SymTab/Validate.cc@ 062e8df

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr no_list persistent-indexer pthread-emulation qualifiedEnum stuck-waitfor-destruct
Last change on this file since 062e8df was 062e8df, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Add error checks for nested types

  • Property mode set to 100644
File size: 49.1 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Validate.cc --
8//
9// Author : Richard C. Bilson
10// Created On : Sun May 17 21:50:04 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Mon Aug 28 13:47:23 2017
13// Update Count : 359
14//
15
16// The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be
17// as regular in structure as possible. Some assumptions can be made regarding the state of the tree after this pass is
18// complete, including:
19//
20// - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or
21// union.
22//
23// - All enumeration constants have type EnumInstType.
24//
25// - The type "void" never occurs in lists of function parameter or return types. A function
26// taking no arguments has no argument types.
27//
28// - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated
29// by the particular set of type arguments.
30//
31// - Every declaration is assigned a unique id.
32//
33// - No typedef declarations or instances exist; the actual type is substituted for each instance.
34//
35// - Each type, struct, and union definition is followed by an appropriate assignment operator.
36//
37// - Each use of a struct or union is connected to a complete definition of that struct or union, even if that
38// definition occurs later in the input.
39
40#include "Validate.h"
41
42#include <cassert> // for assertf, assert
43#include <cstddef> // for size_t
44#include <list> // for list
45#include <string> // for string
46#include <utility> // for pair
47
48#include "CodeGen/CodeGenerator.h" // for genName
49#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
50#include "ControlStruct/Mutate.h" // for ForExprMutator
51#include "Common/PassVisitor.h" // for PassVisitor, WithDeclsToAdd
52#include "Common/ScopedMap.h" // for ScopedMap
53#include "Common/SemanticError.h" // for SemanticError
54#include "Common/UniqueName.h" // for UniqueName
55#include "Common/utility.h" // for operator+, cloneAll, deleteAll
56#include "Concurrency/Keywords.h" // for applyKeywords
57#include "FixFunction.h" // for FixFunction
58#include "Indexer.h" // for Indexer
59#include "InitTweak/GenInit.h" // for fixReturnStatements
60#include "InitTweak/InitTweak.h" // for isCtorDtorAssign
61#include "Parser/LinkageSpec.h" // for C
62#include "ResolvExpr/typeops.h" // for typesCompatible
63#include "SymTab/Autogen.h" // for SizeType
64#include "SynTree/Attribute.h" // for noAttributes, Attribute
65#include "SynTree/Constant.h" // for Constant
66#include "SynTree/Declaration.h" // for ObjectDecl, DeclarationWithType
67#include "SynTree/Expression.h" // for CompoundLiteralExpr, Expressio...
68#include "SynTree/Initializer.h" // for ListInit, Initializer
69#include "SynTree/Label.h" // for operator==, Label
70#include "SynTree/Mutator.h" // for Mutator
71#include "SynTree/Type.h" // for Type, TypeInstType, EnumInstType
72#include "SynTree/TypeSubstitution.h" // for TypeSubstitution
73#include "SynTree/Visitor.h" // for Visitor
74
75class CompoundStmt;
76class ReturnStmt;
77class SwitchStmt;
78
79#define debugPrint( x ) if ( doDebug ) x
80
81namespace SymTab {
82 /// hoists declarations that are difficult to hoist while parsing
83 struct HoistTypeDecls final : public WithDeclsToAdd {
84 void previsit( SizeofExpr * );
85 void previsit( AlignofExpr * );
86 void previsit( UntypedOffsetofExpr * );
87 void handleType( Type * );
88 };
89
90 struct FixQualifiedTypes final : public WithIndexer {
91 Type * postmutate( QualifiedType * );
92 };
93
94 struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
95 /// Flattens nested struct types
96 static void hoistStruct( std::list< Declaration * > &translationUnit );
97
98 void previsit( StructDecl * aggregateDecl );
99 void previsit( UnionDecl * aggregateDecl );
100 void previsit( StaticAssertDecl * assertDecl );
101 void previsit( StructInstType * type );
102 void previsit( UnionInstType * type );
103 void previsit( EnumInstType * type );
104
105 private:
106 template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
107
108 AggregateDecl * parentAggr = nullptr;
109 };
110
111 /// Fix return types so that every function returns exactly one value
112 struct ReturnTypeFixer {
113 static void fix( std::list< Declaration * > &translationUnit );
114
115 void postvisit( FunctionDecl * functionDecl );
116 void postvisit( FunctionType * ftype );
117 };
118
119 /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
120 struct EnumAndPointerDecay {
121 void previsit( EnumDecl *aggregateDecl );
122 void previsit( FunctionType *func );
123 };
124
125 /// Associates forward declarations of aggregates with their definitions
126 struct LinkReferenceToTypes final : public WithIndexer, public WithGuards, public WithVisitorRef<LinkReferenceToTypes>, public WithShortCircuiting {
127 LinkReferenceToTypes( const Indexer *indexer );
128 void postvisit( TypeInstType *typeInst );
129
130 void postvisit( EnumInstType *enumInst );
131 void postvisit( StructInstType *structInst );
132 void postvisit( UnionInstType *unionInst );
133 void postvisit( TraitInstType *traitInst );
134 void previsit( QualifiedType * qualType );
135 void postvisit( QualifiedType * qualType );
136
137 void postvisit( EnumDecl *enumDecl );
138 void postvisit( StructDecl *structDecl );
139 void postvisit( UnionDecl *unionDecl );
140 void postvisit( TraitDecl * traitDecl );
141
142 void previsit( StructDecl *structDecl );
143 void previsit( UnionDecl *unionDecl );
144
145 void renameGenericParams( std::list< TypeDecl * > & params );
146
147 private:
148 const Indexer *local_indexer;
149
150 typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
151 typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
152 typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
153 ForwardEnumsType forwardEnums;
154 ForwardStructsType forwardStructs;
155 ForwardUnionsType forwardUnions;
156 /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
157 bool inGeneric = false;
158 };
159
160 /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
161 struct ForallPointerDecay final {
162 void previsit( ObjectDecl * object );
163 void previsit( FunctionDecl * func );
164 void previsit( FunctionType * ftype );
165 void previsit( StructDecl * aggrDecl );
166 void previsit( UnionDecl * aggrDecl );
167 };
168
169 struct ReturnChecker : public WithGuards {
170 /// Checks that return statements return nothing if their return type is void
171 /// and return something if the return type is non-void.
172 static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
173
174 void previsit( FunctionDecl * functionDecl );
175 void previsit( ReturnStmt * returnStmt );
176
177 typedef std::list< DeclarationWithType * > ReturnVals;
178 ReturnVals returnVals;
179 };
180
181 struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd {
182 ReplaceTypedef() : scopeLevel( 0 ) {}
183 /// Replaces typedefs by forward declarations
184 static void replaceTypedef( std::list< Declaration * > &translationUnit );
185
186 void premutate( QualifiedType * );
187 Type * postmutate( QualifiedType * qualType );
188 Type * postmutate( TypeInstType * aggregateUseType );
189 Declaration * postmutate( TypedefDecl * typeDecl );
190 void premutate( TypeDecl * typeDecl );
191 void premutate( FunctionDecl * funcDecl );
192 void premutate( ObjectDecl * objDecl );
193 DeclarationWithType * postmutate( ObjectDecl * objDecl );
194
195 void premutate( CastExpr * castExpr );
196
197 void premutate( CompoundStmt * compoundStmt );
198
199 void premutate( StructDecl * structDecl );
200 void premutate( UnionDecl * unionDecl );
201 void premutate( EnumDecl * enumDecl );
202
203 void premutate( FunctionType * ftype );
204
205 private:
206 template<typename AggDecl>
207 void addImplicitTypedef( AggDecl * aggDecl );
208 template< typename AggDecl >
209 void handleAggregate( AggDecl * aggr );
210
211 typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
212 typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
213 typedef std::map< std::string, TypeDecl * > TypeDeclMap; // xxx - convert to ScopedMap
214 TypedefMap typedefNames;
215 TypeDeclMap typedeclNames;
216 int scopeLevel;
217 bool inFunctionType = false;
218 };
219
220 struct EliminateTypedef {
221 /// removes TypedefDecls from the AST
222 static void eliminateTypedef( std::list< Declaration * > &translationUnit );
223
224 template<typename AggDecl>
225 void handleAggregate( AggDecl *aggregateDecl );
226
227 void previsit( StructDecl * aggregateDecl );
228 void previsit( UnionDecl * aggregateDecl );
229 void previsit( CompoundStmt * compoundStmt );
230 };
231
232 struct VerifyCtorDtorAssign {
233 /// ensure that constructors, destructors, and assignment have at least one
234 /// parameter, the first of which must be a pointer, and that ctor/dtors have no
235 /// return values.
236 static void verify( std::list< Declaration * > &translationUnit );
237
238 void previsit( FunctionDecl *funcDecl );
239 };
240
241 /// ensure that generic types have the correct number of type arguments
242 struct ValidateGenericParameters {
243 void previsit( StructInstType * inst );
244 void previsit( UnionInstType * inst );
245 };
246
247 struct ArrayLength {
248 /// for array types without an explicit length, compute the length and store it so that it
249 /// is known to the rest of the phases. For example,
250 /// int x[] = { 1, 2, 3 };
251 /// int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
252 /// here x and y are known at compile-time to have length 3, so change this into
253 /// int x[3] = { 1, 2, 3 };
254 /// int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
255 static void computeLength( std::list< Declaration * > & translationUnit );
256
257 void previsit( ObjectDecl * objDecl );
258 };
259
260 struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
261 Type::StorageClasses storageClasses;
262
263 void premutate( ObjectDecl *objectDecl );
264 Expression * postmutate( CompoundLiteralExpr *compLitExpr );
265 };
266
267 struct LabelAddressFixer final : public WithGuards {
268 std::set< Label > labels;
269
270 void premutate( FunctionDecl * funcDecl );
271 Expression * postmutate( AddressExpr * addrExpr );
272 };
273
274 FunctionDecl * dereferenceOperator = nullptr;
275 struct FindSpecialDeclarations final {
276 void previsit( FunctionDecl * funcDecl );
277 };
278
279 void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
280 PassVisitor<EnumAndPointerDecay> epc;
281 PassVisitor<LinkReferenceToTypes> lrt( nullptr );
282 PassVisitor<ForallPointerDecay> fpd;
283 PassVisitor<CompoundLiteral> compoundliteral;
284 PassVisitor<ValidateGenericParameters> genericParams;
285 PassVisitor<FindSpecialDeclarations> finder;
286 PassVisitor<LabelAddressFixer> labelAddrFixer;
287 PassVisitor<HoistTypeDecls> hoistDecls;
288 PassVisitor<FixQualifiedTypes> fixQual;
289
290 acceptAll( translationUnit, hoistDecls );
291 ReplaceTypedef::replaceTypedef( translationUnit );
292 ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
293 acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes because it is an indexer and needs correct types for mangling
294 acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
295 mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes, because aggregate members are accessed
296 HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order
297 EliminateTypedef::eliminateTypedef( translationUnit ); //
298 acceptAll( translationUnit, genericParams ); // check as early as possible - can't happen before LinkReferenceToTypes
299 VerifyCtorDtorAssign::verify( translationUnit ); // must happen before autogen, because autogen examines existing ctor/dtors
300 ReturnChecker::checkFunctionReturns( translationUnit );
301 InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
302 Concurrency::applyKeywords( translationUnit );
303 acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
304 ControlStruct::hoistControlDecls( translationUnit ); // hoist initialization out of for statements; must happen before autogenerateRoutines
305 autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay
306 Concurrency::implementMutexFuncs( translationUnit );
307 Concurrency::implementThreadStarter( translationUnit );
308 mutateAll( translationUnit, compoundliteral );
309 ArrayLength::computeLength( translationUnit );
310 acceptAll( translationUnit, finder ); // xxx - remove this pass soon
311 mutateAll( translationUnit, labelAddrFixer );
312 }
313
314 void validateType( Type *type, const Indexer *indexer ) {
315 PassVisitor<EnumAndPointerDecay> epc;
316 PassVisitor<LinkReferenceToTypes> lrt( indexer );
317 PassVisitor<ForallPointerDecay> fpd;
318 type->accept( epc );
319 type->accept( lrt );
320 type->accept( fpd );
321 }
322
323
324 void HoistTypeDecls::handleType( Type * type ) {
325 // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here
326 AggregateDecl * aggr = nullptr;
327 if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) {
328 aggr = inst->baseStruct;
329 } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) {
330 aggr = inst->baseUnion;
331 } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) {
332 aggr = inst->baseEnum;
333 }
334 if ( aggr && aggr->body ) {
335 declsToAddBefore.push_front( aggr );
336 }
337 }
338
339 void HoistTypeDecls::previsit( SizeofExpr * expr ) {
340 handleType( expr->type );
341 }
342
343 void HoistTypeDecls::previsit( AlignofExpr * expr ) {
344 handleType( expr->type );
345 }
346
347 void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) {
348 handleType( expr->type );
349 }
350
351
352 Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) {
353 Type * parent = qualType->parent;
354 Type * child = qualType->child;
355 if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) {
356 // .T => lookup T at global scope
357 if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
358 auto td = indexer.globalLookupType( inst->name );
359 if ( ! td ) {
360 SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) );
361 }
362 auto base = td->base;
363 assert( base );
364 return base->clone();
365 } else {
366 // .T => T is not a type name
367 assertf( false, "unhandled global qualified child type: %s", toCString(child) );
368 }
369 } else {
370 // S.T => S must be an aggregate type, find the declaration for T in S.
371 AggregateDecl * aggr = nullptr;
372 if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) {
373 aggr = inst->baseStruct;
374 } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) {
375 aggr = inst->baseUnion;
376 } else {
377 SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) );
378 }
379 assert( aggr ); // TODO: need to handle forward declarations
380 for ( Declaration * member : aggr->members ) {
381 if ( StructInstType * inst = dynamic_cast< StructInstType * >( child ) ) {
382 if ( StructDecl * aggr = dynamic_cast< StructDecl * >( member ) ) {
383 if ( aggr->name == inst->name ) {
384 return new StructInstType( qualType->get_qualifiers(), aggr );
385 }
386 }
387 } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( child ) ) {
388 if ( UnionDecl * aggr = dynamic_cast< UnionDecl * > ( member ) ) {
389 if ( aggr->name == inst->name ) {
390 return new UnionInstType( qualType->get_qualifiers(), aggr );
391 }
392 }
393 } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( child ) ) {
394 if ( EnumDecl * aggr = dynamic_cast< EnumDecl * > ( member ) ) {
395 if ( aggr->name == inst->name ) {
396 return new EnumInstType( qualType->get_qualifiers(), aggr );
397 }
398 }
399 } else if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
400 // struct typedefs are being replaced by forward decls too early; move it to hoist struct
401 if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) {
402 if ( aggr->name == inst->name ) {
403 assert( aggr->base );
404 return aggr->base->clone();
405 }
406 }
407 } else {
408 // S.T - S is not an aggregate => error
409 assertf( false, "unhandled qualified child type: %s", toCString(qualType) );
410 }
411 }
412 // failed to find a satisfying definition of type
413 SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) );
414 }
415
416 // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup?
417 }
418
419
420 void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
421 PassVisitor<HoistStruct> hoister;
422 acceptAll( translationUnit, hoister );
423 }
424
425 bool shouldHoist( Declaration *decl ) {
426 return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl );
427 }
428
429 namespace {
430 void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) {
431 if ( aggr->parent ) qualifiedName( aggr->parent, ss );
432 ss << "__" << aggr->name;
433 }
434
435 // mangle nested type names using entire parent chain
436 std::string qualifiedName( AggregateDecl * aggr ) {
437 std::ostringstream ss;
438 qualifiedName( aggr, ss );
439 return ss.str();
440 }
441 }
442
443 template< typename AggDecl >
444 void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
445 if ( parentAggr ) {
446 aggregateDecl->parent = parentAggr;
447 aggregateDecl->name = qualifiedName( aggregateDecl );
448 // Add elements in stack order corresponding to nesting structure.
449 declsToAddBefore.push_front( aggregateDecl );
450 } else {
451 GuardValue( parentAggr );
452 parentAggr = aggregateDecl;
453 } // if
454 // Always remove the hoisted aggregate from the inner structure.
455 GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } );
456 }
457
458 void HoistStruct::previsit( StaticAssertDecl * assertDecl ) {
459 if ( parentAggr ) {
460 declsToAddBefore.push_back( assertDecl );
461 }
462 }
463
464 void HoistStruct::previsit( StructDecl * aggregateDecl ) {
465 handleAggregate( aggregateDecl );
466 }
467
468 void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
469 handleAggregate( aggregateDecl );
470 }
471
472 void HoistStruct::previsit( StructInstType * type ) {
473 // need to reset type name after expanding to qualified name
474 assert( type->baseStruct );
475 type->name = type->baseStruct->name;
476 }
477
478 void HoistStruct::previsit( UnionInstType * type ) {
479 assert( type->baseUnion );
480 type->name = type->baseUnion->name;
481 }
482
483 void HoistStruct::previsit( EnumInstType * type ) {
484 assert( type->baseEnum );
485 type->name = type->baseEnum->name;
486 }
487
488
489 bool isTypedef( Declaration *decl ) {
490 return dynamic_cast< TypedefDecl * >( decl );
491 }
492
493 void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
494 PassVisitor<EliminateTypedef> eliminator;
495 acceptAll( translationUnit, eliminator );
496 filter( translationUnit, isTypedef, true );
497 }
498
499 template< typename AggDecl >
500 void EliminateTypedef::handleAggregate( AggDecl *aggregateDecl ) {
501 filter( aggregateDecl->members, isTypedef, true );
502 }
503
504 void EliminateTypedef::previsit( StructDecl * aggregateDecl ) {
505 handleAggregate( aggregateDecl );
506 }
507
508 void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) {
509 handleAggregate( aggregateDecl );
510 }
511
512 void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) {
513 // remove and delete decl stmts
514 filter( compoundStmt->kids, [](Statement * stmt) {
515 if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
516 if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) {
517 return true;
518 } // if
519 } // if
520 return false;
521 }, true);
522 }
523
524 void EnumAndPointerDecay::previsit( EnumDecl *enumDecl ) {
525 // Set the type of each member of the enumeration to be EnumConstant
526 for ( std::list< Declaration * >::iterator i = enumDecl->members.begin(); i != enumDecl->members.end(); ++i ) {
527 ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
528 assert( obj );
529 obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->name ) );
530 } // for
531 }
532
533 namespace {
534 template< typename DWTList >
535 void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
536 auto nvals = dwts.size();
537 bool containsVoid = false;
538 for ( auto & dwt : dwts ) {
539 // fix each DWT and record whether a void was found
540 containsVoid |= fixFunction( dwt );
541 }
542
543 // the only case in which "void" is valid is where it is the only one in the list
544 if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
545 SemanticError( func, "invalid type void in function type " );
546 }
547
548 // one void is the only thing in the list; remove it.
549 if ( containsVoid ) {
550 delete dwts.front();
551 dwts.clear();
552 }
553 }
554 }
555
556 void EnumAndPointerDecay::previsit( FunctionType *func ) {
557 // Fix up parameters and return types
558 fixFunctionList( func->parameters, func->isVarArgs, func );
559 fixFunctionList( func->returnVals, false, func );
560 }
561
562 LinkReferenceToTypes::LinkReferenceToTypes( const Indexer *other_indexer ) {
563 if ( other_indexer ) {
564 local_indexer = other_indexer;
565 } else {
566 local_indexer = &indexer;
567 } // if
568 }
569
570 void LinkReferenceToTypes::postvisit( EnumInstType *enumInst ) {
571 EnumDecl *st = local_indexer->lookupEnum( enumInst->name );
572 // it's not a semantic error if the enum is not found, just an implicit forward declaration
573 if ( st ) {
574 enumInst->baseEnum = st;
575 } // if
576 if ( ! st || ! st->body ) {
577 // use of forward declaration
578 forwardEnums[ enumInst->name ].push_back( enumInst );
579 } // if
580 }
581
582 void checkGenericParameters( ReferenceToType * inst ) {
583 for ( Expression * param : inst->parameters ) {
584 if ( ! dynamic_cast< TypeExpr * >( param ) ) {
585 SemanticError( inst, "Expression parameters for generic types are currently unsupported: " );
586 }
587 }
588 }
589
590 void LinkReferenceToTypes::postvisit( StructInstType *structInst ) {
591 StructDecl *st = local_indexer->lookupStruct( structInst->name );
592 // it's not a semantic error if the struct is not found, just an implicit forward declaration
593 if ( st ) {
594 structInst->baseStruct = st;
595 } // if
596 if ( ! st || ! st->body ) {
597 // use of forward declaration
598 forwardStructs[ structInst->name ].push_back( structInst );
599 } // if
600 checkGenericParameters( structInst );
601 }
602
603 void LinkReferenceToTypes::postvisit( UnionInstType *unionInst ) {
604 UnionDecl *un = local_indexer->lookupUnion( unionInst->name );
605 // it's not a semantic error if the union is not found, just an implicit forward declaration
606 if ( un ) {
607 unionInst->baseUnion = un;
608 } // if
609 if ( ! un || ! un->body ) {
610 // use of forward declaration
611 forwardUnions[ unionInst->name ].push_back( unionInst );
612 } // if
613 checkGenericParameters( unionInst );
614 }
615
616 void LinkReferenceToTypes::previsit( QualifiedType * ) {
617 visit_children = false;
618 }
619
620 void LinkReferenceToTypes::postvisit( QualifiedType * qualType ) {
621 // linking only makes sense for the 'oldest ancestor' of the qualified type
622 qualType->parent->accept( *visitor );
623 }
624
625 template< typename Decl >
626 void normalizeAssertions( std::list< Decl * > & assertions ) {
627 // ensure no duplicate trait members after the clone
628 auto pred = [](Decl * d1, Decl * d2) {
629 // only care if they're equal
630 DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
631 DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
632 if ( dwt1 && dwt2 ) {
633 if ( dwt1->name == dwt2->name && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
634 // std::cerr << "=========== equal:" << std::endl;
635 // std::cerr << "d1: " << d1 << std::endl;
636 // std::cerr << "d2: " << d2 << std::endl;
637 return false;
638 }
639 }
640 return d1 < d2;
641 };
642 std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
643 // if ( unique_members.size() != assertions.size() ) {
644 // std::cerr << "============different" << std::endl;
645 // std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
646 // }
647
648 std::list< Decl * > order;
649 order.splice( order.end(), assertions );
650 std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
651 return unique_members.count( decl );
652 });
653 }
654
655 // expand assertions from trait instance, performing the appropriate type variable substitutions
656 template< typename Iterator >
657 void expandAssertions( TraitInstType * inst, Iterator out ) {
658 assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
659 std::list< DeclarationWithType * > asserts;
660 for ( Declaration * decl : inst->baseTrait->members ) {
661 asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
662 }
663 // substitute trait decl parameters for instance parameters
664 applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
665 }
666
667 void LinkReferenceToTypes::postvisit( TraitDecl * traitDecl ) {
668 if ( traitDecl->name == "sized" ) {
669 // "sized" is a special trait - flick the sized status on for the type variable
670 assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
671 TypeDecl * td = traitDecl->parameters.front();
672 td->set_sized( true );
673 }
674
675 // move assertions from type parameters into the body of the trait
676 for ( TypeDecl * td : traitDecl->parameters ) {
677 for ( DeclarationWithType * assert : td->assertions ) {
678 if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
679 expandAssertions( inst, back_inserter( traitDecl->members ) );
680 } else {
681 traitDecl->members.push_back( assert->clone() );
682 }
683 }
684 deleteAll( td->assertions );
685 td->assertions.clear();
686 } // for
687 }
688
689 void LinkReferenceToTypes::postvisit( TraitInstType * traitInst ) {
690 // handle other traits
691 TraitDecl *traitDecl = local_indexer->lookupTrait( traitInst->name );
692 if ( ! traitDecl ) {
693 SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
694 } // if
695 if ( traitDecl->parameters.size() != traitInst->parameters.size() ) {
696 SemanticError( traitInst, "incorrect number of trait parameters: " );
697 } // if
698 traitInst->baseTrait = traitDecl;
699
700 // need to carry over the 'sized' status of each decl in the instance
701 for ( auto p : group_iterate( traitDecl->parameters, traitInst->parameters ) ) {
702 TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
703 if ( ! expr ) {
704 SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
705 }
706 if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
707 TypeDecl * formalDecl = std::get<0>(p);
708 TypeDecl * instDecl = inst->baseType;
709 if ( formalDecl->get_sized() ) instDecl->set_sized( true );
710 }
711 }
712 // normalizeAssertions( traitInst->members );
713 }
714
715 void LinkReferenceToTypes::postvisit( EnumDecl *enumDecl ) {
716 // visit enum members first so that the types of self-referencing members are updated properly
717 if ( enumDecl->body ) {
718 ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->name );
719 if ( fwds != forwardEnums.end() ) {
720 for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
721 (*inst)->baseEnum = enumDecl;
722 } // for
723 forwardEnums.erase( fwds );
724 } // if
725 } // if
726 }
727
728 void LinkReferenceToTypes::renameGenericParams( std::list< TypeDecl * > & params ) {
729 // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
730 // forall(otype T)
731 // struct Box {
732 // T x;
733 // };
734 // forall(otype T)
735 // void f(Box(T) b) {
736 // ...
737 // }
738 // The T in Box and the T in f are different, so internally the naming must reflect that.
739 GuardValue( inGeneric );
740 inGeneric = ! params.empty();
741 for ( TypeDecl * td : params ) {
742 td->name = "__" + td->name + "_generic_";
743 }
744 }
745
746 void LinkReferenceToTypes::previsit( StructDecl * structDecl ) {
747 renameGenericParams( structDecl->parameters );
748 }
749
750 void LinkReferenceToTypes::previsit( UnionDecl * unionDecl ) {
751 renameGenericParams( unionDecl->parameters );
752 }
753
754 void LinkReferenceToTypes::postvisit( StructDecl *structDecl ) {
755 // visit struct members first so that the types of self-referencing members are updated properly
756 // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
757 if ( structDecl->body ) {
758 ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->name );
759 if ( fwds != forwardStructs.end() ) {
760 for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
761 (*inst)->baseStruct = structDecl;
762 } // for
763 forwardStructs.erase( fwds );
764 } // if
765 } // if
766 }
767
768 void LinkReferenceToTypes::postvisit( UnionDecl *unionDecl ) {
769 if ( unionDecl->body ) {
770 ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->name );
771 if ( fwds != forwardUnions.end() ) {
772 for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
773 (*inst)->baseUnion = unionDecl;
774 } // for
775 forwardUnions.erase( fwds );
776 } // if
777 } // if
778 }
779
780 void LinkReferenceToTypes::postvisit( TypeInstType *typeInst ) {
781 // ensure generic parameter instances are renamed like the base type
782 if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
783 if ( NamedTypeDecl *namedTypeDecl = local_indexer->lookupType( typeInst->name ) ) {
784 if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
785 typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
786 } // if
787 } // if
788 }
789
790 /// Fix up assertions - flattens assertion lists, removing all trait instances
791 void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
792 for ( TypeDecl * type : forall ) {
793 std::list< DeclarationWithType * > asserts;
794 asserts.splice( asserts.end(), type->assertions );
795 // expand trait instances into their members
796 for ( DeclarationWithType * assertion : asserts ) {
797 if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
798 // expand trait instance into all of its members
799 expandAssertions( traitInst, back_inserter( type->assertions ) );
800 delete traitInst;
801 } else {
802 // pass other assertions through
803 type->assertions.push_back( assertion );
804 } // if
805 } // for
806 // apply FixFunction to every assertion to check for invalid void type
807 for ( DeclarationWithType *& assertion : type->assertions ) {
808 bool isVoid = fixFunction( assertion );
809 if ( isVoid ) {
810 SemanticError( node, "invalid type void in assertion of function " );
811 } // if
812 } // for
813 // normalizeAssertions( type->assertions );
814 } // for
815 }
816
817 void ForallPointerDecay::previsit( ObjectDecl *object ) {
818 // ensure that operator names only apply to functions or function pointers
819 if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
820 SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." ) );
821 }
822 object->fixUniqueId();
823 }
824
825 void ForallPointerDecay::previsit( FunctionDecl *func ) {
826 func->fixUniqueId();
827 }
828
829 void ForallPointerDecay::previsit( FunctionType * ftype ) {
830 forallFixer( ftype->forall, ftype );
831 }
832
833 void ForallPointerDecay::previsit( StructDecl * aggrDecl ) {
834 forallFixer( aggrDecl->parameters, aggrDecl );
835 }
836
837 void ForallPointerDecay::previsit( UnionDecl * aggrDecl ) {
838 forallFixer( aggrDecl->parameters, aggrDecl );
839 }
840
841 void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
842 PassVisitor<ReturnChecker> checker;
843 acceptAll( translationUnit, checker );
844 }
845
846 void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
847 GuardValue( returnVals );
848 returnVals = functionDecl->get_functionType()->get_returnVals();
849 }
850
851 void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
852 // Previously this also checked for the existence of an expr paired with no return values on
853 // the function return type. This is incorrect, since you can have an expression attached to
854 // a return statement in a void-returning function in C. The expression is treated as if it
855 // were cast to void.
856 if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
857 SemanticError( returnStmt, "Non-void function returns no values: " );
858 }
859 }
860
861
862 void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) {
863 PassVisitor<ReplaceTypedef> eliminator;
864 mutateAll( translationUnit, eliminator );
865 if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
866 // grab and remember declaration of size_t
867 SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone();
868 } else {
869 // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
870 // eventually should have a warning for this case.
871 SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
872 }
873 }
874
875 void ReplaceTypedef::premutate( QualifiedType * ) {
876 visit_children = false;
877 }
878
879 Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) {
880 // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type
881 qualType->parent = qualType->parent->acceptMutator( *visitor );
882 return qualType;
883 }
884
885 Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) {
886 // instances of typedef types will come here. If it is an instance
887 // of a typdef type, link the instance to its actual type.
888 TypedefMap::const_iterator def = typedefNames.find( typeInst->name );
889 if ( def != typedefNames.end() ) {
890 Type *ret = def->second.first->base->clone();
891 ret->get_qualifiers() |= typeInst->get_qualifiers();
892 // attributes are not carried over from typedef to function parameters/return values
893 if ( ! inFunctionType ) {
894 ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
895 } else {
896 deleteAll( ret->attributes );
897 ret->attributes.clear();
898 }
899 // place instance parameters on the typedef'd type
900 if ( ! typeInst->parameters.empty() ) {
901 ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
902 if ( ! rtt ) {
903 SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
904 }
905 rtt->parameters.clear();
906 cloneAll( typeInst->parameters, rtt->parameters );
907 mutateAll( rtt->parameters, *visitor ); // recursively fix typedefs on parameters
908 } // if
909 delete typeInst;
910 return ret;
911 } else {
912 TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name );
913 if ( base == typedeclNames.end() ) {
914 SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) );
915 }
916 typeInst->set_baseType( base->second );
917 return typeInst;
918 } // if
919 assert( false );
920 }
921
922 struct VarLenChecker : WithShortCircuiting {
923 void previsit( FunctionType * ) { visit_children = false; }
924 void previsit( ArrayType * at ) {
925 isVarLen |= at->isVarLen;
926 }
927 bool isVarLen = false;
928 };
929
930 bool isVariableLength( Type * t ) {
931 PassVisitor<VarLenChecker> varLenChecker;
932 maybeAccept( t, varLenChecker );
933 return varLenChecker.pass.isVarLen;
934 }
935
936 Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) {
937 if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) {
938 // typedef to the same name from the same scope
939 // must be from the same type
940
941 Type * t1 = tyDecl->base;
942 Type * t2 = typedefNames[ tyDecl->name ].first->base;
943 if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
944 SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
945 }
946 // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
947 // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
948 // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
949 // to fix this corner case likely outweighs the utility of allowing it.
950 if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
951 SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
952 }
953 } else {
954 typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
955 } // if
956
957 // When a typedef is a forward declaration:
958 // typedef struct screen SCREEN;
959 // the declaration portion must be retained:
960 // struct screen;
961 // because the expansion of the typedef is:
962 // void rtn( SCREEN *p ) => void rtn( struct screen *p )
963 // hence the type-name "screen" must be defined.
964 // Note, qualifiers on the typedef are superfluous for the forward declaration.
965
966 Type *designatorType = tyDecl->base->stripDeclarator();
967 if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
968 declsToAddBefore.push_back( new StructDecl( aggDecl->name, DeclarationNode::Struct, noAttributes, tyDecl->linkage ) );
969 } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
970 declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) );
971 } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
972 declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, tyDecl->linkage ) );
973 } // if
974 return tyDecl->clone();
975 }
976
977 void ReplaceTypedef::premutate( TypeDecl * typeDecl ) {
978 TypedefMap::iterator i = typedefNames.find( typeDecl->name );
979 if ( i != typedefNames.end() ) {
980 typedefNames.erase( i ) ;
981 } // if
982
983 typedeclNames[ typeDecl->name ] = typeDecl;
984 }
985
986 void ReplaceTypedef::premutate( FunctionDecl * ) {
987 GuardScope( typedefNames );
988 }
989
990 void ReplaceTypedef::premutate( ObjectDecl * ) {
991 GuardScope( typedefNames );
992 }
993
994 DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) {
995 if ( FunctionType *funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type?
996 // replace the current object declaration with a function declaration
997 FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() );
998 objDecl->attributes.clear();
999 objDecl->set_type( nullptr );
1000 delete objDecl;
1001 return newDecl;
1002 } // if
1003 return objDecl;
1004 }
1005
1006 void ReplaceTypedef::premutate( CastExpr * ) {
1007 GuardScope( typedefNames );
1008 }
1009
1010 void ReplaceTypedef::premutate( CompoundStmt * ) {
1011 GuardScope( typedefNames );
1012 scopeLevel += 1;
1013 GuardAction( [this](){ scopeLevel -= 1; } );
1014 }
1015
1016 template<typename AggDecl>
1017 void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
1018 if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
1019 Type *type = nullptr;
1020 if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
1021 type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
1022 } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
1023 type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
1024 } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl ) ) {
1025 type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
1026 } // if
1027 TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
1028 typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
1029 // add the implicit typedef to the AST
1030 declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) );
1031 } // if
1032 }
1033
1034 template< typename AggDecl >
1035 void ReplaceTypedef::handleAggregate( AggDecl * aggr ) {
1036 SemanticErrorException errors;
1037
1038 ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore );
1039 ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter );
1040 declsToAddBefore.clear();
1041 declsToAddAfter.clear();
1042
1043 GuardScope( typedefNames );
1044 mutateAll( aggr->parameters, *visitor );
1045
1046 // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body.
1047 for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) {
1048 if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); }
1049
1050 try {
1051 *i = maybeMutate( *i, *visitor );
1052 } catch ( SemanticErrorException &e ) {
1053 errors.append( e );
1054 }
1055
1056 if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); }
1057 }
1058
1059 if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); }
1060 if ( !errors.isEmpty() ) { throw errors; }
1061 }
1062
1063 void ReplaceTypedef::premutate( StructDecl * structDecl ) {
1064 visit_children = false;
1065 addImplicitTypedef( structDecl );
1066 handleAggregate( structDecl );
1067 }
1068
1069 void ReplaceTypedef::premutate( UnionDecl * unionDecl ) {
1070 visit_children = false;
1071 addImplicitTypedef( unionDecl );
1072 handleAggregate( unionDecl );
1073 }
1074
1075 void ReplaceTypedef::premutate( EnumDecl * enumDecl ) {
1076 addImplicitTypedef( enumDecl );
1077 }
1078
1079 void ReplaceTypedef::premutate( FunctionType * ) {
1080 GuardValue( inFunctionType );
1081 inFunctionType = true;
1082 }
1083
1084 void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
1085 PassVisitor<VerifyCtorDtorAssign> verifier;
1086 acceptAll( translationUnit, verifier );
1087 }
1088
1089 void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
1090 FunctionType * funcType = funcDecl->get_functionType();
1091 std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
1092 std::list< DeclarationWithType * > &params = funcType->get_parameters();
1093
1094 if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
1095 if ( params.size() == 0 ) {
1096 SemanticError( funcDecl, "Constructors, destructors, and assignment functions require at least one parameter " );
1097 }
1098 ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
1099 if ( ! refType ) {
1100 SemanticError( funcDecl, "First parameter of a constructor, destructor, or assignment function must be a reference " );
1101 }
1102 if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
1103 SemanticError( funcDecl, "Constructors and destructors cannot have explicit return values " );
1104 }
1105 }
1106 }
1107
1108 template< typename Aggr >
1109 void validateGeneric( Aggr * inst ) {
1110 std::list< TypeDecl * > * params = inst->get_baseParameters();
1111 if ( params ) {
1112 std::list< Expression * > & args = inst->get_parameters();
1113
1114 // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
1115 // A substitution is used to ensure that defaults are replaced correctly, e.g.,
1116 // forall(otype T, otype alloc = heap_allocator(T)) struct vector;
1117 // vector(int) v;
1118 // after insertion of default values becomes
1119 // vector(int, heap_allocator(T))
1120 // and the substitution is built with T=int so that after substitution, the result is
1121 // vector(int, heap_allocator(int))
1122 TypeSubstitution sub;
1123 auto paramIter = params->begin();
1124 for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) {
1125 if ( i < args.size() ) {
1126 TypeExpr * expr = strict_dynamic_cast< TypeExpr * >( *std::next( args.begin(), i ) );
1127 sub.add( (*paramIter)->get_name(), expr->get_type()->clone() );
1128 } else if ( i == args.size() ) {
1129 Type * defaultType = (*paramIter)->get_init();
1130 if ( defaultType ) {
1131 args.push_back( new TypeExpr( defaultType->clone() ) );
1132 sub.add( (*paramIter)->get_name(), defaultType->clone() );
1133 }
1134 }
1135 }
1136
1137 sub.apply( inst );
1138 if ( args.size() < params->size() ) SemanticError( inst, "Too few type arguments in generic type " );
1139 if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
1140 }
1141 }
1142
1143 void ValidateGenericParameters::previsit( StructInstType * inst ) {
1144 validateGeneric( inst );
1145 }
1146
1147 void ValidateGenericParameters::previsit( UnionInstType * inst ) {
1148 validateGeneric( inst );
1149 }
1150
1151 void CompoundLiteral::premutate( ObjectDecl *objectDecl ) {
1152 storageClasses = objectDecl->get_storageClasses();
1153 }
1154
1155 Expression *CompoundLiteral::postmutate( CompoundLiteralExpr *compLitExpr ) {
1156 // transform [storage_class] ... (struct S){ 3, ... };
1157 // into [storage_class] struct S temp = { 3, ... };
1158 static UniqueName indexName( "_compLit" );
1159
1160 ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
1161 compLitExpr->set_result( nullptr );
1162 compLitExpr->set_initializer( nullptr );
1163 delete compLitExpr;
1164 declsToAddBefore.push_back( tempvar ); // add modified temporary to current block
1165 return new VariableExpr( tempvar );
1166 }
1167
1168 void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
1169 PassVisitor<ReturnTypeFixer> fixer;
1170 acceptAll( translationUnit, fixer );
1171 }
1172
1173 void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
1174 FunctionType * ftype = functionDecl->get_functionType();
1175 std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1176 assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
1177 if ( retVals.size() == 1 ) {
1178 // 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).
1179 // ensure other return values have a name.
1180 DeclarationWithType * ret = retVals.front();
1181 if ( ret->get_name() == "" ) {
1182 ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1183 }
1184 ret->get_attributes().push_back( new Attribute( "unused" ) );
1185 }
1186 }
1187
1188 void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
1189 // xxx - need to handle named return values - this information needs to be saved somehow
1190 // so that resolution has access to the names.
1191 // Note that this pass needs to happen early so that other passes which look for tuple types
1192 // find them in all of the right places, including function return types.
1193 std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1194 if ( retVals.size() > 1 ) {
1195 // generate a single return parameter which is the tuple of all of the return values
1196 TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
1197 // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
1198 ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
1199 deleteAll( retVals );
1200 retVals.clear();
1201 retVals.push_back( newRet );
1202 }
1203 }
1204
1205 void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
1206 PassVisitor<ArrayLength> len;
1207 acceptAll( translationUnit, len );
1208 }
1209
1210 void ArrayLength::previsit( ObjectDecl * objDecl ) {
1211 if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) {
1212 if ( at->get_dimension() ) return;
1213 if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) {
1214 at->set_dimension( new ConstantExpr( Constant::from_ulong( init->initializers.size() ) ) );
1215 }
1216 }
1217 }
1218
1219 struct LabelFinder {
1220 std::set< Label > & labels;
1221 LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1222 void previsit( Statement * stmt ) {
1223 for ( Label & l : stmt->labels ) {
1224 labels.insert( l );
1225 }
1226 }
1227 };
1228
1229 void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1230 GuardValue( labels );
1231 PassVisitor<LabelFinder> finder( labels );
1232 funcDecl->accept( finder );
1233 }
1234
1235 Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1236 // convert &&label into label address
1237 if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1238 if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1239 if ( labels.count( nameExpr->name ) ) {
1240 Label name = nameExpr->name;
1241 delete addrExpr;
1242 return new LabelAddressExpr( name );
1243 }
1244 }
1245 }
1246 return addrExpr;
1247 }
1248
1249 void FindSpecialDeclarations::previsit( FunctionDecl * funcDecl ) {
1250 if ( ! dereferenceOperator ) {
1251 if ( funcDecl->get_name() == "*?" && funcDecl->get_linkage() == LinkageSpec::Intrinsic ) {
1252 FunctionType * ftype = funcDecl->get_functionType();
1253 if ( ftype->get_parameters().size() == 1 && ftype->get_parameters().front()->get_type()->get_qualifiers() == Type::Qualifiers() ) {
1254 dereferenceOperator = funcDecl;
1255 }
1256 }
1257 }
1258 }
1259} // namespace SymTab
1260
1261// Local Variables: //
1262// tab-width: 4 //
1263// mode: c++ //
1264// compile-command: "make install" //
1265// End: //
Note: See TracBrowser for help on using the repository browser.