source: src/Parser/DeclarationNode.cpp@ 14c31eb

Last change on this file since 14c31eb was 16ba4897, checked in by Andrew Beach <ajbeach@…>, 12 months ago

Replaced SemanticErrorException::isEmpty with ...::throwIfNonEmpty. This is how it was used in every context and it saves a bit of text (if not two lines) at every use. I considered putting this function in the header for better inlining, but this should have at least the same preformance as the last version.

  • Property mode set to 100644
File size: 33.5 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// DeclarationNode.cpp --
8//
9// Author : Rodolfo G. Esteves
10// Created On : Sat May 16 12:34:05 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Aug 22 14:11:47 2024
13// Update Count : 1555
14//
15
16#include "DeclarationNode.hpp"
17
18#include <cassert> // for assert, assertf, strict_dynami...
19#include <iterator> // for back_insert_iterator
20#include <list> // for list
21#include <memory> // for unique_ptr
22#include <ostream> // for operator<<, ostream, basic_ost...
23#include <string> // for string, operator+, allocator, ...
24
25#include "AST/Attribute.hpp" // for Attribute
26#include "AST/Copy.hpp" // for shallowCopy
27#include "AST/Decl.hpp" // for Decl
28#include "AST/Expr.hpp" // for Expr
29#include "AST/Print.hpp" // for print
30#include "AST/Stmt.hpp" // for AsmStmt, DirectiveStmt
31#include "AST/StorageClasses.hpp" // for Storage::Class
32#include "AST/Type.hpp" // for Type
33#include "Common/CodeLocation.hpp" // for CodeLocation
34#include "Common/Iterate.hpp" // for reverseIterate
35#include "Common/SemanticError.hpp" // for SemanticError
36#include "Common/UniqueName.hpp" // for UniqueName
37#include "Common/Utility.hpp" // for copy, spliceBegin
38#include "Parser/ExpressionNode.hpp" // for ExpressionNode
39#include "Parser/InitializerNode.hpp" // for InitializerNode
40#include "Parser/StatementNode.hpp" // for StatementNode
41#include "TypeData.hpp" // for TypeData, TypeData::Aggregate_t
42#include "TypedefTable.hpp" // for TypedefTable
43
44extern TypedefTable typedefTable;
45
46using namespace std;
47
48UniqueName DeclarationNode::anonymous( "__anonymous" );
49
50extern ast::Linkage::Spec linkage; // defined in parser.yy
51
52DeclarationNode::DeclarationNode() :
53 linkage( ::linkage ) {
54
55 variable.tyClass = ast::TypeDecl::NUMBER_OF_KINDS;
56 variable.assertions = nullptr;
57 variable.initializer = nullptr;
58
59 assert.condition = nullptr;
60 assert.message = nullptr;
61}
62
63DeclarationNode::~DeclarationNode() {
64 delete name;
65
66 delete variable.assertions;
67 delete variable.initializer;
68
69 delete type;
70 delete bitfieldWidth;
71
72 delete asmStmt;
73 // asmName, no delete, passed to next stage
74 delete initializer;
75
76 delete assert.condition;
77 delete assert.message;
78}
79
80DeclarationNode * DeclarationNode::clone() const {
81 DeclarationNode * newnode = new DeclarationNode;
82 newnode->next = maybeCopy( next );
83 newnode->name = name ? new string( *name ) : nullptr;
84
85 newnode->type = maybeCopy( type );
86 newnode->inLine = inLine;
87 newnode->storageClasses = storageClasses;
88 newnode->funcSpecs = funcSpecs;
89 newnode->bitfieldWidth = maybeCopy( bitfieldWidth );
90 newnode->enumeratorValue.reset( maybeCopy( enumeratorValue.get() ) );
91 newnode->hasEllipsis = hasEllipsis;
92 newnode->linkage = linkage;
93 newnode->asmName = maybeCopy( asmName );
94 newnode->attributes = attributes;
95 newnode->initializer = maybeCopy( initializer );
96 newnode->extension = extension;
97 newnode->asmStmt = maybeCopy( asmStmt );
98 newnode->error = error;
99
100 newnode->variable.tyClass = variable.tyClass;
101 newnode->variable.assertions = maybeCopy( variable.assertions );
102 newnode->variable.initializer = maybeCopy( variable.initializer );
103
104 newnode->assert.condition = maybeCopy( assert.condition );
105 newnode->assert.message = maybeCopy( assert.message );
106 return newnode;
107} // DeclarationNode::clone
108
109void DeclarationNode::print( std::ostream & os, int indent ) const {
110 os << string( indent, ' ' );
111 if ( name ) {
112 os << *name << ": ";
113 } // if
114
115 if ( linkage != ast::Linkage::Cforall ) {
116 os << ast::Linkage::name( linkage ) << " ";
117 } // if
118
119 ast::print( os, storageClasses );
120 ast::print( os, funcSpecs );
121
122 if ( type ) {
123 type->print( os, indent );
124 } else {
125 os << "untyped entity ";
126 } // if
127
128 if ( bitfieldWidth ) {
129 os << endl << string( indent + 2, ' ' ) << "with bitfield width ";
130 bitfieldWidth->printOneLine( os );
131 } // if
132
133 if ( initializer ) {
134 os << endl << string( indent + 2, ' ' ) << "with initializer ";
135 initializer->printOneLine( os );
136 if ( ! initializer->get_maybeConstructed() ) {
137 os << " constructed with @= ";
138 } // if
139 } // if
140
141 if ( ! attributes.empty() ) {
142 os << string( indent + 2, ' ' ) << "with attributes" << endl;
143 for ( ast::ptr<ast::Attribute> const & attr : reverseIterate( attributes ) ) {
144 os << string( indent + 4, ' ' );
145 ast::print( os, attr, indent + 2 );
146 } // for
147 } // if
148
149 os << endl;
150}
151
152void DeclarationNode::printList( std::ostream & os, int indent ) const {
153 ParseList::printList( os, indent );
154 if ( hasEllipsis ) {
155 os << string( indent, ' ' ) << "and a variable number of other arguments" << endl;
156 } // if
157}
158
159DeclarationNode * DeclarationNode::newFromTypeData( TypeData * type ) {
160 DeclarationNode * newnode = new DeclarationNode;
161 newnode->type = type;
162 return newnode;
163} // DeclarationNode::newFromTypeData
164
165DeclarationNode * DeclarationNode::newStorageClass( ast::Storage::Classes sc ) {
166 DeclarationNode * newnode = new DeclarationNode;
167 newnode->storageClasses = sc;
168 return newnode;
169} // DeclarationNode::newStorageClass
170
171DeclarationNode * DeclarationNode::newFuncSpecifier( ast::Function::Specs fs ) {
172 DeclarationNode * newnode = new DeclarationNode;
173 newnode->funcSpecs = fs;
174 return newnode;
175} // DeclarationNode::newFuncSpecifier
176
177DeclarationNode * DeclarationNode::newAggregate( ast::AggregateDecl::Aggregate kind, const string * name, ExpressionNode * actuals, DeclarationNode * fields, bool body ) {
178 DeclarationNode * newnode = new DeclarationNode;
179 newnode->type = new TypeData( TypeData::Aggregate );
180 newnode->type->aggregate.kind = kind;
181 newnode->type->aggregate.anon = name == nullptr;
182 newnode->type->aggregate.name = newnode->type->aggregate.anon ? new string( DeclarationNode::anonymous.newName() ) : name;
183 newnode->type->aggregate.actuals = actuals;
184 newnode->type->aggregate.fields = fields;
185 newnode->type->aggregate.body = body;
186 return newnode;
187} // DeclarationNode::newAggregate
188
189DeclarationNode * DeclarationNode::newEnum( const string * name, DeclarationNode * constants, bool body, bool isCfa, DeclarationNode * base, EnumHiding hiding ) {
190 DeclarationNode * newnode = newAggregate( ast::AggregateDecl::Enum, name, nullptr, constants, body );
191 newnode->type->aggregate.isCfa = isCfa;
192 newnode->type->aggregate.hiding = hiding;
193 if ( base ) {
194 assert( isCfa );
195 assert( base->type );
196 newnode->type->base = base->type;
197 base->type = nullptr;
198 delete base;
199 } // if
200
201 return newnode;
202} // DeclarationNode::newEnum
203
204DeclarationNode * DeclarationNode::newName( const string * name ) {
205 DeclarationNode * newnode = new DeclarationNode;
206 assert( ! newnode->name );
207 newnode->name = name;
208 return newnode;
209} // DeclarationNode::newName
210
211DeclarationNode * DeclarationNode::newEnumConstant( const string * name, ExpressionNode * constant ) {
212 DeclarationNode * newnode = newName( name );
213 newnode->enumeratorValue.reset( constant );
214 return newnode;
215} // DeclarationNode::newEnumConstant
216
217DeclarationNode * DeclarationNode::newEnumValueGeneric( const string * name, InitializerNode * init ) {
218 if ( nullptr == init ) {
219 return newName( name );
220 } else if ( init->get_expression() ) {
221 return newEnumConstant( name, init->get_expression() );
222 } else {
223 DeclarationNode * newnode = newName( name );
224 newnode->initializer = init;
225 return newnode;
226 } // if
227} // DeclarationNode::newEnumValueGeneric
228
229DeclarationNode * DeclarationNode::newEnumInLine( const std::string * name ) {
230 DeclarationNode * newnode = newName( name );
231 newnode->enumInLine = true;
232 return newnode;
233}
234
235DeclarationNode * DeclarationNode::newTypeParam( ast::TypeDecl::Kind tc, const string * name ) {
236 DeclarationNode * newnode = newName( name );
237 newnode->type = nullptr;
238 newnode->variable.tyClass = tc;
239 newnode->variable.assertions = nullptr;
240 return newnode;
241} // DeclarationNode::newTypeParam
242
243DeclarationNode * DeclarationNode::newTrait( const string * name, DeclarationNode * params, DeclarationNode * asserts ) {
244 DeclarationNode * newnode = new DeclarationNode;
245 newnode->type = new TypeData( TypeData::Aggregate );
246 newnode->type->aggregate.name = name;
247 newnode->type->aggregate.kind = ast::AggregateDecl::Trait;
248 newnode->type->aggregate.params = params;
249 newnode->type->aggregate.fields = asserts;
250 return newnode;
251} // DeclarationNode::newTrait
252
253DeclarationNode * DeclarationNode::newTraitUse( const string * name, ExpressionNode * params ) {
254 DeclarationNode * newnode = new DeclarationNode;
255 newnode->type = new TypeData( TypeData::AggregateInst );
256 newnode->type->aggInst.aggregate = new TypeData( TypeData::Aggregate );
257 newnode->type->aggInst.aggregate->aggregate.kind = ast::AggregateDecl::Trait;
258 newnode->type->aggInst.aggregate->aggregate.name = name;
259 newnode->type->aggInst.params = params;
260 return newnode;
261} // DeclarationNode::newTraitUse
262
263DeclarationNode * DeclarationNode::newTypeDecl( const string * name, DeclarationNode * typeParams ) {
264 DeclarationNode * newnode = newName( name );
265 newnode->type = new TypeData( TypeData::Symbolic );
266 newnode->type->symbolic.isTypedef = false;
267 newnode->type->symbolic.params = typeParams;
268 return newnode;
269} // DeclarationNode::newTypeDecl
270
271DeclarationNode * DeclarationNode::newPointer( DeclarationNode * qualifiers, OperKinds kind ) {
272 DeclarationNode * newnode = new DeclarationNode;
273 newnode->type = new TypeData( kind == OperKinds::PointTo ? TypeData::Pointer : TypeData::Reference );
274 if ( kind == OperKinds::And ) {
275 // T && is parsed as 'And' operator rather than two references => add a second reference type
276 TypeData * td = new TypeData( TypeData::Reference );
277 td->base = newnode->type;
278 newnode->type = td;
279 }
280 if ( qualifiers ) {
281 return newnode->addQualifiers( qualifiers );
282 } else {
283 return newnode;
284 } // if
285} // DeclarationNode::newPointer
286
287DeclarationNode * DeclarationNode::newArray( ExpressionNode * size, DeclarationNode * qualifiers, bool isStatic ) {
288 DeclarationNode * newnode = new DeclarationNode;
289 newnode->type = new TypeData( TypeData::Array );
290 newnode->type->array.dimension = size;
291 newnode->type->array.isStatic = isStatic;
292 newnode->type->array.isVarLen = size && !size->isExpressionType<ast::ConstantExpr *>();
293 return newnode->addQualifiers( qualifiers );
294} // DeclarationNode::newArray
295
296DeclarationNode * DeclarationNode::newVarArray( DeclarationNode * qualifiers ) {
297 DeclarationNode * newnode = new DeclarationNode;
298 newnode->type = new TypeData( TypeData::Array );
299 newnode->type->array.dimension = nullptr;
300 newnode->type->array.isStatic = false;
301 newnode->type->array.isVarLen = true;
302 return newnode->addQualifiers( qualifiers );
303}
304
305DeclarationNode * DeclarationNode::newBitfield( ExpressionNode * size ) {
306 DeclarationNode * newnode = new DeclarationNode;
307 newnode->bitfieldWidth = size;
308 return newnode;
309}
310
311DeclarationNode * DeclarationNode::newTuple( DeclarationNode * members ) {
312 DeclarationNode * newnode = new DeclarationNode;
313 newnode->type = new TypeData( TypeData::Tuple );
314 newnode->type->tuple = members;
315 return newnode;
316}
317
318DeclarationNode * DeclarationNode::newTypeof( ExpressionNode * expr, bool basetypeof ) {
319 DeclarationNode * newnode = new DeclarationNode;
320 newnode->type = new TypeData( basetypeof ? TypeData::Basetypeof : TypeData::Typeof );
321 newnode->type->typeexpr = expr;
322 return newnode;
323}
324
325DeclarationNode * DeclarationNode::newFunction( const string * name, DeclarationNode * ret, DeclarationNode * param, StatementNode * body ) {
326 DeclarationNode * newnode = newName( name );
327 newnode->type = new TypeData( TypeData::Function );
328 newnode->type->function.params = param;
329 newnode->type->function.body = body;
330
331 if ( ret ) {
332 newnode->type->base = ret->type;
333 ret->type = nullptr;
334 delete ret;
335 } // if
336
337 return newnode;
338} // DeclarationNode::newFunction
339
340DeclarationNode * DeclarationNode::newAttribute( const string * name, ExpressionNode * expr ) {
341 DeclarationNode * newnode = new DeclarationNode;
342 newnode->type = nullptr;
343 std::vector<ast::ptr<ast::Expr>> exprs;
344 buildList( expr, exprs );
345 newnode->attributes.push_back( new ast::Attribute( *name, std::move( exprs ) ) );
346 delete name;
347 return newnode;
348}
349
350DeclarationNode * DeclarationNode::newDirectiveStmt( StatementNode * stmt ) {
351 DeclarationNode * newnode = new DeclarationNode;
352 newnode->directiveStmt = stmt;
353 return newnode;
354}
355
356DeclarationNode * DeclarationNode::newAsmStmt( StatementNode * stmt ) {
357 DeclarationNode * newnode = new DeclarationNode;
358 newnode->asmStmt = stmt;
359 return newnode;
360}
361
362DeclarationNode * DeclarationNode::newStaticAssert( ExpressionNode * condition, ast::Expr * message ) {
363 DeclarationNode * newnode = new DeclarationNode;
364 newnode->assert.condition = condition;
365 newnode->assert.message = message;
366 return newnode;
367}
368
369static void appendError( string & dst, const string & src ) {
370 if ( src.empty() ) return;
371 if ( dst.empty() ) { dst = src; return; }
372 dst += ", " + src;
373} // appendError
374
375void DeclarationNode::checkQualifiers( const TypeData * src, const TypeData * dst ) {
376 const ast::CV::Qualifiers qsrc = src->qualifiers, qdst = dst->qualifiers; // optimization
377 const ast::CV::Qualifiers duplicates = qsrc & qdst;
378
379 if ( duplicates.any() ) {
380 std::stringstream str;
381 str << "duplicate ";
382 ast::print( str, duplicates );
383 str << "qualifier(s)";
384 appendError( error, str.str() );
385 } // for
386} // DeclarationNode::checkQualifiers
387
388void DeclarationNode::checkSpecifiers( DeclarationNode * src ) {
389 ast::Function::Specs fsDups = funcSpecs & src->funcSpecs;
390 if ( fsDups.any() ) {
391 std::stringstream str;
392 str << "duplicate ";
393 ast::print( str, fsDups );
394 str << "function specifier(s)";
395 appendError( error, str.str() );
396 } // if
397
398 // Skip if everything is unset.
399 if ( storageClasses.any() && src->storageClasses.any() ) {
400 ast::Storage::Classes dups = storageClasses & src->storageClasses;
401 // Check for duplicates.
402 if ( dups.any() ) {
403 std::stringstream str;
404 str << "duplicate ";
405 ast::print( str, dups );
406 str << "storage class(es)";
407 appendError( error, str.str() );
408 // Check for conflicts.
409 } else if ( !src->storageClasses.is_threadlocal_any() ) {
410 std::stringstream str;
411 str << "conflicting ";
412 ast::print( str, ast::Storage::Classes( 1 << storageClasses.ffs() ) );
413 str << "& ";
414 ast::print( str, ast::Storage::Classes( 1 << src->storageClasses.ffs() ) );
415 str << "storage classes";
416 appendError( error, str.str() );
417 // FIX to preserve invariant of one basic storage specifier
418 src->storageClasses.reset();
419 }
420 } // if
421
422 appendError( error, src->error );
423} // DeclarationNode::checkSpecifiers
424
425DeclarationNode * DeclarationNode::copySpecifiers( DeclarationNode * q, bool copyattr ) {
426 funcSpecs |= q->funcSpecs;
427 storageClasses |= q->storageClasses;
428
429 if ( copyattr ) {
430 std::vector<ast::ptr<ast::Attribute>> tmp;
431 tmp.reserve( q->attributes.size() );
432 for ( auto const & attr : q->attributes ) {
433 tmp.emplace_back( ast::shallowCopy( attr.get() ) );
434 } // for
435 spliceBegin( attributes, tmp );
436 } // if
437
438 return this;
439} // DeclarationNode::copySpecifiers
440
441DeclarationNode * DeclarationNode::addQualifiers( DeclarationNode * q ) {
442 if ( ! q ) { return this; } // empty qualifier
443
444 checkSpecifiers( q );
445 copySpecifiers( q );
446
447 if ( ! q->type ) { delete q; return this; }
448
449 if ( ! type ) {
450 type = q->type; // reuse structure
451 q->type = nullptr;
452 delete q;
453 return this;
454 } // if
455
456 checkQualifiers( type, q->type );
457 TypeData::BuiltinType const builtin = type->builtintype;
458 if ( (builtin == TypeData::Zero || builtin == TypeData::One) && q->type->qualifiers.any() && error.length() == 0 ) {
459 SemanticWarning( yylloc, Warning::BadQualifiersZeroOne, TypeData::builtinTypeNames[builtin] );
460 } // if
461 type = ::addQualifiers( type, q->type );
462 q->type = nullptr;
463
464 delete q;
465 return this;
466} // addQualifiers
467
468DeclarationNode * DeclarationNode::addType( DeclarationNode * o, bool copyattr ) {
469 if ( !o ) return this;
470
471 checkSpecifiers( o );
472 copySpecifiers( o, copyattr );
473 if ( o->type ) {
474 type = ::addType( type, o->type, o->attributes );
475 o->type = nullptr;
476 } // if
477 if ( o->bitfieldWidth ) {
478 bitfieldWidth = o->bitfieldWidth;
479 } // if
480
481 // there may be typedefs chained onto the type
482 if ( o->next ) {
483 set_last( o->next->clone() );
484 } // if
485
486 delete o;
487 return this;
488}
489
490DeclarationNode * DeclarationNode::addEnumBase( DeclarationNode * o ) {
491 if ( o && o->type ) {
492 type->base = o->type;
493 } // if
494 delete o;
495 return this;
496}
497
498// This code handles a special issue with the attribute transparent_union.
499//
500// typedef union U { int i; } typedef_name __attribute__(( aligned(16) )) __attribute__(( transparent_union ))
501//
502// Here the attribute aligned goes with the typedef_name, so variables declared of this type are
503// aligned. However, the attribute transparent_union must be moved from the typedef_name to
504// alias union U. Currently, this is the only know attribute that must be moved from typedef to
505// alias.
506static void moveUnionAttribute( DeclarationNode * decl, DeclarationNode * unionDecl ) {
507 assert( decl->type->kind == TypeData::Symbolic );
508 assert( decl->type->symbolic.isTypedef );
509 assert( unionDecl->type->kind == TypeData::Aggregate );
510
511 if ( unionDecl->type->aggregate.kind != ast::AggregateDecl::Union ) return;
512
513 // Ignore the Aggregate_t::attributes. Why did we add that before the rework?
514 for ( auto attr = decl->attributes.begin() ; attr != decl->attributes.end() ; ) {
515 if ( (*attr)->name == "transparent_union" || (*attr)->name == "__transparent_union__" ) {
516 unionDecl->attributes.emplace_back( attr->release() );
517 attr = decl->attributes.erase( attr );
518 } else {
519 ++attr;
520 }
521 }
522}
523
524// Helper for addTypedef, handles the case where the typedef wraps an
525// aggregate declaration (not a type), returns a chain of nodes.
526static DeclarationNode * addTypedefAggr(
527 DeclarationNode * olddecl, TypeData * newtype ) {
528 TypeData *& oldaggr = olddecl->type->aggInst.aggregate;
529
530 // Handle anonymous aggregates: typedef struct { int i; } foo
531 // Give the typedefed type a consistent name across translation units.
532 if ( oldaggr->aggregate.anon ) {
533 delete oldaggr->aggregate.name;
534 oldaggr->aggregate.name = new string( "__anonymous_" + *olddecl->name );
535 oldaggr->aggregate.anon = false;
536 oldaggr->qualifiers.reset();
537 }
538
539 // Replace the wrapped TypeData with a forward declaration.
540 TypeData * newaggr = new TypeData( TypeData::Aggregate );
541 newaggr->aggregate.kind = oldaggr->aggregate.kind;
542 newaggr->aggregate.name = oldaggr->aggregate.name ? new string( *oldaggr->aggregate.name ) : nullptr;
543 newaggr->aggregate.body = false;
544 newaggr->aggregate.anon = oldaggr->aggregate.anon;
545 newaggr->aggregate.isCfa = oldaggr->aggregate.isCfa;
546 newaggr->aggregate.hiding = oldaggr->aggregate.hiding;
547 swap( newaggr, oldaggr );
548
549 newtype->base = olddecl->type;
550 olddecl->type = newtype;
551 DeclarationNode * newdecl = new DeclarationNode;
552 newdecl->type = newaggr;
553 newdecl->next = olddecl;
554
555 moveUnionAttribute( olddecl, newdecl );
556
557 return newdecl;
558}
559
560// Wrap the declaration in a typedef. It actually does that by modifying the
561// existing declaration, and may split it into two declarations.
562// This only happens if the wrapped type is actually a declaration of a SUE
563// type. If it does, the DeclarationNode for the SUE declaration is the node
564// returned, make sure later transformations are applied to the right node.
565DeclarationNode * DeclarationNode::addTypedef() {
566 TypeData * newtype = new TypeData( TypeData::Symbolic );
567 newtype->symbolic.params = nullptr;
568 newtype->symbolic.isTypedef = true;
569 newtype->symbolic.name = name ? new string( *name ) : nullptr;
570 // If this typedef is wrapping an aggregate, separate them out.
571 if ( TypeData::AggregateInst == type->kind
572 && TypeData::Aggregate == type->aggInst.aggregate->kind
573 && type->aggInst.aggregate->aggregate.body ) {
574 return addTypedefAggr( this, newtype );
575 // There is no internal declaration, just a type.
576 } else {
577 newtype->base = type;
578 type = newtype;
579 return this;
580 }
581}
582
583DeclarationNode * DeclarationNode::addAssertions( DeclarationNode * assertions ) {
584 if ( variable.tyClass != ast::TypeDecl::NUMBER_OF_KINDS ) {
585 extend( variable.assertions, assertions );
586 return this;
587 } // if
588
589 assert( type );
590 assert( TypeData::Symbolic == type->kind );
591 extend( type->symbolic.assertions, assertions );
592
593 return this;
594}
595
596DeclarationNode * DeclarationNode::addName( string * newname ) {
597 assert( ! name );
598 name = newname;
599 return this;
600}
601
602DeclarationNode * DeclarationNode::addAsmName( DeclarationNode * newname ) {
603 assert( ! asmName );
604 asmName = newname ? newname->asmName : nullptr;
605 return this->addQualifiers( newname );
606}
607
608DeclarationNode * DeclarationNode::addBitfield( ExpressionNode * size ) {
609 bitfieldWidth = size;
610 return this;
611}
612
613DeclarationNode * DeclarationNode::addVarArgs() {
614 assert( type );
615 hasEllipsis = true;
616 return this;
617}
618
619DeclarationNode * DeclarationNode::addFunctionBody( StatementNode * body, ExpressionNode * withExprs ) {
620 assert( type );
621 assert( type->kind == TypeData::Function );
622 assert( ! type->function.body );
623 type->function.body = body;
624 type->function.withExprs = withExprs;
625 return this;
626}
627
628DeclarationNode * DeclarationNode::addOldDeclList( DeclarationNode * list ) {
629 assert( type );
630 assert( type->kind == TypeData::Function );
631 assert( ! type->function.oldDeclList );
632 type->function.oldDeclList = list;
633 return this;
634}
635
636DeclarationNode * DeclarationNode::setBase( TypeData * newType ) {
637 if ( type ) {
638 type->setLastBase( newType );
639 } else {
640 type = newType;
641 } // if
642 return this;
643}
644
645DeclarationNode * DeclarationNode::copyAttribute( DeclarationNode * a ) {
646 if ( a ) {
647 spliceBegin( attributes, a->attributes );
648 a->attributes.clear();
649 } // if
650 return this;
651} // copyAttribute
652
653DeclarationNode * DeclarationNode::addPointer( DeclarationNode * p ) {
654 if ( p ) {
655 assert( p->type->kind == TypeData::Pointer || p->type->kind == TypeData::Reference );
656 setBase( p->type );
657 p->type = nullptr;
658 copyAttribute( p );
659 delete p;
660 } // if
661 return this;
662}
663
664DeclarationNode * DeclarationNode::addArray( DeclarationNode * a ) {
665 if ( a ) {
666 assert( a->type->kind == TypeData::Array );
667 setBase( a->type );
668 a->type = nullptr;
669 copyAttribute( a );
670 delete a;
671 } // if
672 return this;
673}
674
675DeclarationNode * DeclarationNode::addNewPointer( DeclarationNode * p ) {
676 if ( !p ) return this;
677 assert( p->type->kind == TypeData::Pointer || p->type->kind == TypeData::Reference );
678 if ( type ) {
679 p->type->base = makeNewBase( type );
680 type = nullptr;
681 } // if
682 delete this;
683 return p;
684}
685
686DeclarationNode * DeclarationNode::addNewArray( DeclarationNode * a ) {
687 if ( !a ) return this;
688 assert( a->type->kind == TypeData::Array );
689 if ( type ) {
690 a->type->setLastBase( makeNewBase( type ) );
691 type = nullptr;
692 } // if
693 delete this;
694 return a;
695}
696
697DeclarationNode * DeclarationNode::addParamList( DeclarationNode * params ) {
698 TypeData * ftype = new TypeData( TypeData::Function );
699 ftype->function.params = params;
700 setBase( ftype );
701 return this;
702}
703
704static TypeData * addIdListToType( TypeData * type, DeclarationNode * ids ) {
705 if ( type ) {
706 if ( type->kind != TypeData::Function ) {
707 type->base = addIdListToType( type->base, ids );
708 } else {
709 type->function.idList = ids;
710 } // if
711 return type;
712 } else {
713 TypeData * newtype = new TypeData( TypeData::Function );
714 newtype->function.idList = ids;
715 return newtype;
716 } // if
717} // addIdListToType
718
719DeclarationNode * DeclarationNode::addIdList( DeclarationNode * ids ) {
720 type = addIdListToType( type, ids );
721 return this;
722}
723
724DeclarationNode * DeclarationNode::addInitializer( InitializerNode * init ) {
725 initializer = init;
726 return this;
727}
728
729DeclarationNode * DeclarationNode::addTypeInitializer( DeclarationNode * init ) {
730 assertf( variable.tyClass != ast::TypeDecl::NUMBER_OF_KINDS, "Called addTypeInitializer on something that isn't a type variable." );
731 variable.initializer = init;
732 return this;
733}
734
735DeclarationNode * DeclarationNode::cloneType( string * name ) {
736 DeclarationNode * newnode = newName( name );
737 newnode->type = maybeCopy( type );
738 newnode->copySpecifiers( this );
739 return newnode;
740}
741
742DeclarationNode * DeclarationNode::cloneBaseType( DeclarationNode * o, bool copyattr ) {
743 if ( ! o ) return nullptr;
744 o->copySpecifiers( this, copyattr );
745 if ( type ) {
746 o->type = ::cloneBaseType( type, o->type );
747 } // if
748 return o;
749}
750
751DeclarationNode * DeclarationNode::extractAggregate() const {
752 if ( type ) {
753 TypeData * ret = typeextractAggregate( type );
754 if ( ret ) {
755 DeclarationNode * newnode = new DeclarationNode;
756 newnode->type = ret;
757 if ( ret->kind == TypeData::Aggregate ) {
758 newnode->attributes.swap( ret->aggregate.attributes );
759 } // if
760 return newnode;
761 } // if
762 } // if
763 return nullptr;
764}
765
766// Get the non-anonymous name of the instance type of the declaration,
767// if one exists.
768static const std::string * getInstTypeOfName( ast::Decl * decl ) {
769 if ( auto dwt = dynamic_cast<ast::DeclWithType *>( decl ) ) {
770 if ( auto aggr = dynamic_cast<ast::BaseInstType const *>( dwt->get_type() ) ) {
771 if ( aggr->name.find("anonymous") == std::string::npos ) {
772 return &aggr->name;
773 }
774 }
775 }
776 return nullptr;
777}
778
779void buildList( DeclarationNode * firstNode, std::vector<ast::ptr<ast::Decl>> & outputList ) {
780 SemanticErrorException errors;
781 std::back_insert_iterator<std::vector<ast::ptr<ast::Decl>>> out( outputList );
782
783 for ( const DeclarationNode * cur = firstNode ; cur ; cur = cur->next ) {
784 try {
785 bool extracted_named = false;
786
787 if ( DeclarationNode * extr = cur->extractAggregate() ) {
788 assert( cur->type );
789
790 if ( ast::Decl * decl = extr->build() ) {
791 *out++ = decl;
792
793 // need to remember the cases where a declaration contains an anonymous aggregate definition
794 assert( extr->type );
795 if ( extr->type->kind == TypeData::Aggregate ) {
796 // typedef struct { int A } B is the only case?
797 extracted_named = ! extr->type->aggregate.anon;
798 } else {
799 extracted_named = true;
800 }
801 } // if
802 delete extr;
803 } // if
804
805 if ( ast::Decl * decl = cur->build() ) {
806 if ( "" == decl->name && !cur->get_inLine() ) {
807 // Don't include anonymous declaration for named aggregates,
808 // but do include them for anonymous aggregates, e.g.:
809 // struct S {
810 // struct T { int x; }; // no anonymous member
811 // struct { int y; }; // anonymous member
812 // struct T; // anonymous member
813 // };
814 if ( extracted_named ) {
815 continue;
816 }
817
818 if ( auto name = getInstTypeOfName( decl ) ) {
819 // Temporary: warn about anonymous member declarations of named types, since
820 // this conflicts with the syntax for the forward declaration of an anonymous type.
821 SemanticWarning( cur->location, Warning::AggrForwardDecl, name->c_str() );
822 }
823 } // if
824 *out++ = decl;
825 } // if
826 } catch ( SemanticErrorException & e ) {
827 errors.append( e );
828 } // try
829 } // for
830
831 errors.throwIfNonEmpty();
832} // buildList
833
834// currently only builds assertions, function parameters, and return values
835void buildList( DeclarationNode * firstNode, std::vector<ast::ptr<ast::DeclWithType>> & outputList ) {
836 SemanticErrorException errors;
837 std::back_insert_iterator<std::vector<ast::ptr<ast::DeclWithType>>> out( outputList );
838
839 for ( const DeclarationNode * cur = firstNode; cur; cur = cur->next ) {
840 try {
841 ast::Decl * decl = cur->build();
842 assertf( decl, "buildList: build for ast::DeclWithType." );
843 if ( ast::DeclWithType * dwt = dynamic_cast<ast::DeclWithType *>( decl ) ) {
844 dwt->location = cur->location;
845 *out++ = dwt;
846 } else if ( ast::StructDecl * agg = dynamic_cast<ast::StructDecl *>( decl ) ) {
847 // e.g., int foo(struct S) {}
848 auto inst = new ast::StructInstType( agg->name );
849 auto obj = new ast::ObjectDecl( cur->location, "", inst );
850 obj->linkage = linkage;
851 *out++ = obj;
852 delete agg;
853 } else if ( ast::UnionDecl * agg = dynamic_cast<ast::UnionDecl *>( decl ) ) {
854 // e.g., int foo(union U) {}
855 auto inst = new ast::UnionInstType( agg->name );
856 auto obj = new ast::ObjectDecl( cur->location,
857 "", inst, nullptr, ast::Storage::Classes(),
858 linkage );
859 *out++ = obj;
860 } else if ( ast::EnumDecl * agg = dynamic_cast<ast::EnumDecl *>( decl ) ) {
861 // e.g., int foo(enum E) {}
862 auto inst = new ast::EnumInstType( agg->name );
863 auto obj = new ast::ObjectDecl( cur->location,
864 "",
865 inst,
866 nullptr,
867 ast::Storage::Classes(),
868 linkage
869 );
870 *out++ = obj;
871 } else {
872 assertf( false, "buildList: Could not convert to ast::DeclWithType." );
873 } // if
874 } catch ( SemanticErrorException & e ) {
875 errors.append( e );
876 } // try
877 } // for
878
879 errors.throwIfNonEmpty();
880} // buildList
881
882void buildTypeList( const DeclarationNode * firstNode,
883 std::vector<ast::ptr<ast::Type>> & outputList ) {
884 SemanticErrorException errors;
885 std::back_insert_iterator<std::vector<ast::ptr<ast::Type>>> out( outputList );
886
887 for ( const DeclarationNode * cur = firstNode ; cur ; cur = cur->next ) {
888 try {
889 * out++ = cur->buildType();
890 } catch ( SemanticErrorException & e ) {
891 errors.append( e );
892 } // try
893 } // for
894
895 errors.throwIfNonEmpty();
896} // buildTypeList
897
898ast::Decl * DeclarationNode::build() const {
899 if ( ! error.empty() ) SemanticError( this, error + " in declaration of " );
900
901 if ( asmStmt ) {
902 auto stmt = strict_dynamic_cast<ast::AsmStmt *>( asmStmt->build() );
903 return new ast::AsmDecl( stmt->location, stmt );
904 } // if
905 if ( directiveStmt ) {
906 auto stmt = strict_dynamic_cast<ast::DirectiveStmt *>( directiveStmt->build() );
907 return new ast::DirectiveDecl( stmt->location, stmt );
908 } // if
909
910 if ( variable.tyClass != ast::TypeDecl::NUMBER_OF_KINDS ) {
911 // otype is internally converted to dtype + otype parameters
912 static const ast::TypeDecl::Kind kindMap[] = { ast::TypeDecl::Dtype, ast::TypeDecl::Dtype, ast::TypeDecl::Dtype, ast::TypeDecl::Ftype, ast::TypeDecl::Ttype, ast::TypeDecl::Dimension };
913 static_assert( sizeof(kindMap) / sizeof(kindMap[0]) == ast::TypeDecl::NUMBER_OF_KINDS, "DeclarationNode::build: kindMap is out of sync." );
914 assertf( variable.tyClass < sizeof(kindMap)/sizeof(kindMap[0]), "Variable's tyClass is out of bounds." );
915 ast::TypeDecl * ret = new ast::TypeDecl( location,
916 *name,
917 ast::Storage::Classes(),
918 (ast::Type *)nullptr,
919 kindMap[ variable.tyClass ],
920 variable.tyClass == ast::TypeDecl::Otype || variable.tyClass == ast::TypeDecl::DStype,
921 variable.initializer ? variable.initializer->buildType() : nullptr
922 );
923 buildList( variable.assertions, ret->assertions );
924 return ret;
925 } // if
926
927 if ( type ) {
928 // Function specifiers can only appear on a function definition/declaration.
929 //
930 // inline _Noreturn int f(); // allowed
931 // inline _Noreturn int g( int i ); // allowed
932 // inline _Noreturn int i; // disallowed
933 if ( type->kind != TypeData::Function && funcSpecs.any() ) {
934 SemanticError( this, "invalid function specifier for " );
935 } // if
936 // Forall qualifier can only appear on a function/aggregate definition/declaration.
937 //
938 // forall int f(); // allowed
939 // forall int g( int i ); // allowed
940 // forall int i; // disallowed
941 if ( type->kind != TypeData::Function && type->forall ) {
942 SemanticError( this, "invalid type qualifier for " );
943 } // if
944 bool isDelete = initializer && initializer->get_isDelete();
945 ast::Decl * decl = buildDecl(
946 type,
947 name ? *name : string( "" ),
948 storageClasses,
949 maybeBuild( bitfieldWidth ),
950 funcSpecs,
951 linkage,
952 asmName,
953 isDelete ? nullptr : maybeBuild( initializer ),
954 copy( attributes )
955 );
956 decl->extension = extension;
957 if ( isDelete ) {
958 auto dwt = strict_dynamic_cast<ast::DeclWithType *>( decl );
959 dwt->isDeleted = true;
960 }
961 return decl;
962 } // if
963
964 if ( assert.condition ) {
965 auto cond = maybeBuild( assert.condition );
966 auto msg = strict_dynamic_cast<ast::ConstantExpr *>( maybeCopy( assert.message ) );
967 return new ast::StaticAssertDecl( location, cond, msg );
968 }
969
970 // SUE's cannot have function specifiers, either
971 //
972 // inline _Noreturn struct S { ... }; // disallowed
973 // inline _Noreturn enum E { ... }; // disallowed
974 if ( funcSpecs.any() ) {
975 SemanticError( this, "invalid function specifier for " );
976 } // if
977 if ( enumInLine ) {
978 return new ast::InlineMemberDecl( location,
979 *name, (ast::Type*)nullptr, storageClasses, linkage );
980 } // if
981 assertf( name, "ObjectDecl must a have name\n" );
982 auto ret = new ast::ObjectDecl( location,
983 *name,
984 (ast::Type*)nullptr,
985 maybeBuild( initializer ),
986 storageClasses,
987 linkage,
988 maybeBuild( bitfieldWidth )
989 );
990 ret->asmName = asmName;
991 ret->extension = extension;
992 return ret;
993}
994
995ast::Type * DeclarationNode::buildType() const {
996 assert( type );
997
998 // Some types are parsed as declarations and, syntactically, can have initializers, which are not support (possibly
999 // meaningless).
1000 if ( initializer && initializer->get_maybeConstructed() ) { // no @=
1001 SemanticError( location, "default initialization for parameter %s is unsupport for a function-pointer declaration.",
1002 (this->name) ? this->name->c_str() : "anonymous" );
1003 }
1004
1005 switch ( type->kind ) {
1006 case TypeData::Aggregate: {
1007 ast::BaseInstType * ret =
1008 buildComAggInst( type, copy( attributes ), linkage );
1009 buildList( type->aggregate.actuals, ret->params );
1010 return ret;
1011 }
1012 case TypeData::Symbolic: {
1013 ast::TypeInstType * ret = new ast::TypeInstType(
1014 *type->symbolic.name,
1015 // This is just a default, the true value is not known yet.
1016 ast::TypeDecl::Dtype,
1017 buildQualifiers( type ),
1018 copy( attributes ) );
1019 buildList( type->symbolic.actuals, ret->params );
1020 return ret;
1021 }
1022 default:
1023 ast::Type * simpletypes = typebuild( type );
1024 // copy because member is const
1025 simpletypes->attributes = attributes;
1026 return simpletypes;
1027 } // switch
1028}
1029
1030// Local Variables: //
1031// tab-width: 4 //
1032// mode: c++ //
1033// compile-command: "make install" //
1034// End: //
Note: See TracBrowser for help on using the repository browser.