source: src/Parser/DeclarationNode.cc @ deda7e6

Last change on this file since deda7e6 was c1e66d9, checked in by JiadaL <j82liang@…>, 12 months ago

Fix designator value in enumerated array and implemented enumerated array with inlined enume declaration

  • Property mode set to 100644
File size: 44.9 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.cc --
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 : Sat Jun 17 14:41:48 2023
13// Update Count     : 1405
14//
15
16#include "DeclarationNode.h"
17
18#include <cassert>                 // for assert, assertf, strict_dynamic_cast
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_ostream
23#include <string>                  // for string, operator+, allocator, char...
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.h"   // for CodeLocation
34#include "Common/Iterate.hpp"      // for reverseIterate
35#include "Common/SemanticError.h"  // for SemanticError
36#include "Common/UniqueName.h"     // for UniqueName
37#include "Common/utility.h"        // for maybeClone
38#include "Parser/ExpressionNode.h" // for ExpressionNode
39#include "Parser/InitializerNode.h"// for InitializerNode
40#include "Parser/StatementNode.h"  // for StatementNode
41#include "TypeData.h"              // for TypeData, TypeData::Aggregate_t
42#include "TypedefTable.h"          // for TypedefTable
43
44class Initializer;
45
46extern TypedefTable typedefTable;
47
48using namespace std;
49
50// These must harmonize with the corresponding DeclarationNode enumerations.
51const char * DeclarationNode::basicTypeNames[] = {
52        "void", "_Bool", "char", "int", "int128",
53        "float", "double", "long double", "float80", "float128",
54        "_float16", "_float32", "_float32x", "_float64", "_float64x", "_float128", "_float128x", "NoBasicTypeNames"
55};
56const char * DeclarationNode::complexTypeNames[] = {
57        "_Complex", "NoComplexTypeNames", "_Imaginary"
58}; // Imaginary unsupported => parse, but make invisible and print error message
59const char * DeclarationNode::signednessNames[] = {
60        "signed", "unsigned", "NoSignednessNames"
61};
62const char * DeclarationNode::lengthNames[] = {
63        "short", "long", "long long", "NoLengthNames"
64};
65const char * DeclarationNode::builtinTypeNames[] = {
66        "__builtin_va_list", "__auto_type", "zero_t", "one_t", "NoBuiltinTypeNames"
67};
68
69UniqueName DeclarationNode::anonymous( "__anonymous" );
70
71extern ast::Linkage::Spec linkage;                                              // defined in parser.yy
72
73DeclarationNode::DeclarationNode() :
74        linkage( ::linkage ) {
75
76//      variable.name = nullptr;
77        variable.tyClass = ast::TypeDecl::NUMBER_OF_KINDS;
78        variable.assertions = nullptr;
79        variable.initializer = nullptr;
80
81        assert.condition = nullptr;
82        assert.message = nullptr;
83}
84
85DeclarationNode::~DeclarationNode() {
86//      delete variable.name;
87        delete variable.assertions;
88        delete variable.initializer;
89
90//      delete type;
91        delete bitfieldWidth;
92
93        delete asmStmt;
94        // asmName, no delete, passed to next stage
95        delete initializer;
96
97        delete assert.condition;
98        delete assert.message;
99}
100
101DeclarationNode * DeclarationNode::clone() const {
102        DeclarationNode * newnode = new DeclarationNode;
103        newnode->set_next( maybeClone( get_next() ) );
104        newnode->name = name ? new string( *name ) : nullptr;
105
106        newnode->builtin = NoBuiltinType;
107        newnode->type = maybeClone( type );
108        newnode->inLine = inLine;
109        newnode->storageClasses = storageClasses;
110        newnode->funcSpecs = funcSpecs;
111        newnode->bitfieldWidth = maybeClone( bitfieldWidth );
112        newnode->enumeratorValue.reset( maybeClone( enumeratorValue.get() ) );
113        newnode->hasEllipsis = hasEllipsis;
114        newnode->linkage = linkage;
115        newnode->asmName = maybeCopy( asmName );
116        newnode->attributes = attributes;
117        newnode->initializer = maybeClone( initializer );
118        newnode->extension = extension;
119        newnode->asmStmt = maybeClone( asmStmt );
120        newnode->error = error;
121
122//      newnode->variable.name = variable.name ? new string( *variable.name ) : nullptr;
123        newnode->variable.tyClass = variable.tyClass;
124        newnode->variable.assertions = maybeClone( variable.assertions );
125        newnode->variable.initializer = maybeClone( variable.initializer );
126
127        newnode->assert.condition = maybeClone( assert.condition );
128        newnode->assert.message = maybeCopy( assert.message );
129        return newnode;
130} // DeclarationNode::clone
131
132void DeclarationNode::print( std::ostream & os, int indent ) const {
133        os << string( indent, ' ' );
134        if ( name ) {
135                os << *name << ": ";
136        } // if
137
138        if ( linkage != ast::Linkage::Cforall ) {
139                os << ast::Linkage::name( linkage ) << " ";
140        } // if
141
142        ast::print( os, storageClasses );
143        ast::print( os, funcSpecs );
144
145        if ( type ) {
146                type->print( os, indent );
147        } else {
148                os << "untyped entity ";
149        } // if
150
151        if ( bitfieldWidth ) {
152                os << endl << string( indent + 2, ' ' ) << "with bitfield width ";
153                bitfieldWidth->printOneLine( os );
154        } // if
155
156        if ( initializer ) {
157                os << endl << string( indent + 2, ' ' ) << "with initializer ";
158                initializer->printOneLine( os );
159                os << " maybe constructed? " << initializer->get_maybeConstructed();
160        } // if
161
162        if ( ! attributes.empty() ) {
163                os << string( indent + 2, ' ' ) << "with attributes " << endl;
164                for ( ast::ptr<ast::Attribute> const & attr : reverseIterate( attributes ) ) {
165                        os << string( indent + 4, ' ' ) << attr->name.c_str() << endl;
166                } // for
167        } // if
168
169        os << endl;
170}
171
172void DeclarationNode::printList( std::ostream & os, int indent ) const {
173        ParseNode::printList( os, indent );
174        if ( hasEllipsis ) {
175                os << string( indent, ' ' )  << "and a variable number of other arguments" << endl;
176        } // if
177}
178
179DeclarationNode * DeclarationNode::newStorageClass( ast::Storage::Classes sc ) {
180        DeclarationNode * newnode = new DeclarationNode;
181        newnode->storageClasses = sc;
182        return newnode;
183} // DeclarationNode::newStorageClass
184
185DeclarationNode * DeclarationNode::newFuncSpecifier( ast::Function::Specs fs ) {
186        DeclarationNode * newnode = new DeclarationNode;
187        newnode->funcSpecs = fs;
188        return newnode;
189} // DeclarationNode::newFuncSpecifier
190
191DeclarationNode * DeclarationNode::newTypeQualifier( ast::CV::Qualifiers tq ) {
192        DeclarationNode * newnode = new DeclarationNode;
193        newnode->type = new TypeData();
194        newnode->type->qualifiers = tq;
195        return newnode;
196} // DeclarationNode::newQualifier
197
198DeclarationNode * DeclarationNode::newBasicType( BasicType bt ) {
199        DeclarationNode * newnode = new DeclarationNode;
200        newnode->type = new TypeData( TypeData::Basic );
201        newnode->type->basictype = bt;
202        return newnode;
203} // DeclarationNode::newBasicType
204
205DeclarationNode * DeclarationNode::newComplexType( ComplexType ct ) {
206        DeclarationNode * newnode = new DeclarationNode;
207        newnode->type = new TypeData( TypeData::Basic );
208        newnode->type->complextype = ct;
209        return newnode;
210} // DeclarationNode::newComplexType
211
212DeclarationNode * DeclarationNode::newSignedNess( Signedness sn ) {
213        DeclarationNode * newnode = new DeclarationNode;
214        newnode->type = new TypeData( TypeData::Basic );
215        newnode->type->signedness = sn;
216        return newnode;
217} // DeclarationNode::newSignedNess
218
219DeclarationNode * DeclarationNode::newLength( Length lnth ) {
220        DeclarationNode * newnode = new DeclarationNode;
221        newnode->type = new TypeData( TypeData::Basic );
222        newnode->type->length = lnth;
223        return newnode;
224} // DeclarationNode::newLength
225
226DeclarationNode * DeclarationNode::newForall( DeclarationNode * forall ) {
227        DeclarationNode * newnode = new DeclarationNode;
228        newnode->type = new TypeData( TypeData::Unknown );
229        newnode->type->forall = forall;
230        return newnode;
231} // DeclarationNode::newForall
232
233DeclarationNode * DeclarationNode::newFromGlobalScope() {
234        DeclarationNode * newnode = new DeclarationNode;
235        newnode->type = new TypeData( TypeData::GlobalScope );
236        return newnode;
237}
238
239DeclarationNode * DeclarationNode::newQualifiedType( DeclarationNode * parent, DeclarationNode * child) {
240        DeclarationNode * newnode = new DeclarationNode;
241        newnode->type = new TypeData( TypeData::Qualified );
242        newnode->type->qualified.parent = parent->type;
243        newnode->type->qualified.child = child->type;
244        parent->type = nullptr;
245        child->type = nullptr;
246        delete parent;
247        delete child;
248        return newnode;
249}
250
251DeclarationNode * DeclarationNode::newAggregate( ast::AggregateDecl::Aggregate kind, const string * name, ExpressionNode * actuals, DeclarationNode * fields, bool body ) {
252        DeclarationNode * newnode = new DeclarationNode;
253        newnode->type = new TypeData( TypeData::Aggregate );
254        newnode->type->aggregate.kind = kind;
255        newnode->type->aggregate.anon = name == nullptr;
256        newnode->type->aggregate.name = newnode->type->aggregate.anon ? new string( DeclarationNode::anonymous.newName() ) : name;
257        newnode->type->aggregate.actuals = actuals;
258        newnode->type->aggregate.fields = fields;
259        newnode->type->aggregate.body = body;
260        newnode->type->aggregate.tagged = false;
261        newnode->type->aggregate.parent = nullptr;
262        return newnode;
263} // DeclarationNode::newAggregate
264
265DeclarationNode * DeclarationNode::newEnum( const string * name, DeclarationNode * constants, bool body, bool typed, DeclarationNode * base, EnumHiding hiding ) {
266        DeclarationNode * newnode = new DeclarationNode;
267        newnode->type = new TypeData( TypeData::Enum );
268        newnode->type->enumeration.anon = name == nullptr;
269        newnode->type->enumeration.name = newnode->type->enumeration.anon ? new string( DeclarationNode::anonymous.newName() ) : name;
270        newnode->type->enumeration.constants = constants;
271        newnode->type->enumeration.body = body;
272        newnode->type->enumeration.typed = typed;
273        newnode->type->enumeration.hiding = hiding;
274        if ( base && base->type )  {
275                newnode->type->base = base->type;
276        } // if
277
278        return newnode;
279} // DeclarationNode::newEnum
280
281DeclarationNode * DeclarationNode::newName( const string * name ) {
282        DeclarationNode * newnode = new DeclarationNode;
283        assert( ! newnode->name );
284        newnode->name = name;
285        return newnode;
286} // DeclarationNode::newName
287
288DeclarationNode * DeclarationNode::newEnumConstant( const string * name, ExpressionNode * constant ) {
289        DeclarationNode * newnode = newName( name );
290        newnode->enumeratorValue.reset( constant );
291        return newnode;
292} // DeclarationNode::newEnumConstant
293
294DeclarationNode * DeclarationNode::newEnumValueGeneric( const string * name, InitializerNode * init ) {
295        if ( init ) {
296                if ( init->get_expression() ) {
297                        return newEnumConstant( name, init->get_expression() );
298                } else {
299                        DeclarationNode * newnode = newName( name );
300                        newnode->initializer = init;
301                        return newnode;
302                } // if
303        } else {
304                return newName( name );
305        } // if
306} // DeclarationNode::newEnumValueGeneric
307
308DeclarationNode * DeclarationNode::newEnumInLine( const string name ) {
309        DeclarationNode * newnode = newName( new std::string(name) );
310        newnode->enumInLine = true;
311        return newnode;
312}
313
314DeclarationNode * DeclarationNode::newFromTypedef( const string * name ) {
315        DeclarationNode * newnode = new DeclarationNode;
316        newnode->type = new TypeData( TypeData::SymbolicInst );
317        newnode->type->symbolic.name = name;
318        newnode->type->symbolic.isTypedef = true;
319        newnode->type->symbolic.params = nullptr;
320        return newnode;
321} // DeclarationNode::newFromTypedef
322
323DeclarationNode * DeclarationNode::newFromTypeGen( const string * name, ExpressionNode * params ) {
324        DeclarationNode * newnode = new DeclarationNode;
325        newnode->type = new TypeData( TypeData::SymbolicInst );
326        newnode->type->symbolic.name = name;
327        newnode->type->symbolic.isTypedef = false;
328        newnode->type->symbolic.actuals = params;
329        return newnode;
330} // DeclarationNode::newFromTypeGen
331
332DeclarationNode * DeclarationNode::newTypeParam( ast::TypeDecl::Kind tc, const string * name ) {
333        DeclarationNode * newnode = newName( name );
334        newnode->type = nullptr;
335        newnode->variable.tyClass = tc;
336        newnode->variable.assertions = nullptr;
337        return newnode;
338} // DeclarationNode::newTypeParam
339
340DeclarationNode * DeclarationNode::newTrait( const string * name, DeclarationNode * params, DeclarationNode * asserts ) {
341        DeclarationNode * newnode = new DeclarationNode;
342        newnode->type = new TypeData( TypeData::Aggregate );
343        newnode->type->aggregate.name = name;
344        newnode->type->aggregate.kind = ast::AggregateDecl::Trait;
345        newnode->type->aggregate.params = params;
346        newnode->type->aggregate.fields = asserts;
347        return newnode;
348} // DeclarationNode::newTrait
349
350DeclarationNode * DeclarationNode::newTraitUse( const string * name, ExpressionNode * params ) {
351        DeclarationNode * newnode = new DeclarationNode;
352        newnode->type = new TypeData( TypeData::AggregateInst );
353        newnode->type->aggInst.aggregate = new TypeData( TypeData::Aggregate );
354        newnode->type->aggInst.aggregate->aggregate.kind = ast::AggregateDecl::Trait;
355        newnode->type->aggInst.aggregate->aggregate.name = name;
356        newnode->type->aggInst.params = params;
357        return newnode;
358} // DeclarationNode::newTraitUse
359
360DeclarationNode * DeclarationNode::newTypeDecl( const string * name, DeclarationNode * typeParams ) {
361        DeclarationNode * newnode = newName( name );
362        newnode->type = new TypeData( TypeData::Symbolic );
363        newnode->type->symbolic.isTypedef = false;
364        newnode->type->symbolic.params = typeParams;
365        return newnode;
366} // DeclarationNode::newTypeDecl
367
368DeclarationNode * DeclarationNode::newPointer( DeclarationNode * qualifiers, OperKinds kind ) {
369        DeclarationNode * newnode = new DeclarationNode;
370        newnode->type = new TypeData( kind == OperKinds::PointTo ? TypeData::Pointer : TypeData::Reference );
371        if ( kind == OperKinds::And ) {
372                // T && is parsed as 'And' operator rather than two references => add a second reference type
373                TypeData * td = new TypeData( TypeData::Reference );
374                td->base = newnode->type;
375                newnode->type = td;
376        }
377        if ( qualifiers ) {
378                return newnode->addQualifiers( qualifiers );
379        } else {
380                return newnode;
381        } // if
382} // DeclarationNode::newPointer
383
384DeclarationNode * DeclarationNode::newArray( ExpressionNode * size, DeclarationNode * qualifiers, bool isStatic ) {
385        DeclarationNode * newnode = new DeclarationNode;
386        newnode->type = new TypeData( TypeData::Array );
387        newnode->type->array.dimension = size;
388        newnode->type->array.isStatic = isStatic;
389        if ( newnode->type->array.dimension == nullptr || newnode->type->array.dimension->isExpressionType<ast::ConstantExpr *>() ) {
390                newnode->type->array.isVarLen = false;
391        } else {
392                newnode->type->array.isVarLen = true;
393        } // if
394        return newnode->addQualifiers( qualifiers );
395} // DeclarationNode::newArray
396
397DeclarationNode * DeclarationNode::newInlineEnumeratedArray( DeclarationNode * enumDecl, DeclarationNode * qualifiers ) {
398        DeclarationNode * newnode = new DeclarationNode;
399        newnode->type = new TypeData( TypeData::Array );
400        newnode->type->array.isStatic = false;
401        newnode->type->array.isVarLen = false;
402
403        if ( enumDecl ) {
404                newnode->type->declType = enumDecl->type;
405                enumDecl->type = nullptr;
406                delete enumDecl;
407        } // if
408       
409        return newnode->addQualifiers( qualifiers );
410}
411
412DeclarationNode * DeclarationNode::newVarArray( DeclarationNode * qualifiers ) {
413        DeclarationNode * newnode = new DeclarationNode;
414        newnode->type = new TypeData( TypeData::Array );
415        newnode->type->array.dimension = nullptr;
416        newnode->type->array.isStatic = false;
417        newnode->type->array.isVarLen = true;
418        return newnode->addQualifiers( qualifiers );
419}
420
421DeclarationNode * DeclarationNode::newBitfield( ExpressionNode * size ) {
422        DeclarationNode * newnode = new DeclarationNode;
423        newnode->bitfieldWidth = size;
424        return newnode;
425}
426
427DeclarationNode * DeclarationNode::newTuple( DeclarationNode * members ) {
428        DeclarationNode * newnode = new DeclarationNode;
429        newnode->type = new TypeData( TypeData::Tuple );
430        newnode->type->tuple = members;
431        return newnode;
432}
433
434DeclarationNode * DeclarationNode::newTypeof( ExpressionNode * expr, bool basetypeof ) {
435        DeclarationNode * newnode = new DeclarationNode;
436        newnode->type = new TypeData( basetypeof ? TypeData::Basetypeof : TypeData::Typeof );
437        newnode->type->typeexpr = expr;
438        return newnode;
439}
440
441DeclarationNode * DeclarationNode::newVtableType( DeclarationNode * decl ) {
442        DeclarationNode * newnode = new DeclarationNode;
443        newnode->type = new TypeData( TypeData::Vtable );
444        newnode->setBase( decl->type );
445        return newnode;
446}
447
448DeclarationNode * DeclarationNode::newBuiltinType( BuiltinType bt ) {
449        DeclarationNode * newnode = new DeclarationNode;
450        newnode->type = new TypeData( TypeData::Builtin );
451        newnode->builtin = bt;
452        newnode->type->builtintype = newnode->builtin;
453        return newnode;
454} // DeclarationNode::newBuiltinType
455
456DeclarationNode * DeclarationNode::newFunction( const string * name, DeclarationNode * ret, DeclarationNode * param, StatementNode * body ) {
457        DeclarationNode * newnode = newName( name );
458        newnode->type = new TypeData( TypeData::Function );
459        newnode->type->function.params = param;
460        newnode->type->function.body = body;
461
462        if ( ret ) {
463                newnode->type->base = ret->type;
464                ret->type = nullptr;
465                delete ret;
466        } // if
467
468        return newnode;
469} // DeclarationNode::newFunction
470
471DeclarationNode * DeclarationNode::newAttribute( const string * name, ExpressionNode * expr ) {
472        DeclarationNode * newnode = new DeclarationNode;
473        newnode->type = nullptr;
474        std::vector<ast::ptr<ast::Expr>> exprs;
475        buildList( expr, exprs );
476        newnode->attributes.push_back( new ast::Attribute( *name, std::move( exprs ) ) );
477        delete name;
478        return newnode;
479}
480
481DeclarationNode * DeclarationNode::newDirectiveStmt( StatementNode * stmt ) {
482        DeclarationNode * newnode = new DeclarationNode;
483        newnode->directiveStmt = stmt;
484        return newnode;
485}
486
487DeclarationNode * DeclarationNode::newAsmStmt( StatementNode * stmt ) {
488        DeclarationNode * newnode = new DeclarationNode;
489        newnode->asmStmt = stmt;
490        return newnode;
491}
492
493DeclarationNode * DeclarationNode::newStaticAssert( ExpressionNode * condition, ast::Expr * message ) {
494        DeclarationNode * newnode = new DeclarationNode;
495        newnode->assert.condition = condition;
496        newnode->assert.message = message;
497        return newnode;
498}
499
500static void appendError( string & dst, const string & src ) {
501        if ( src.empty() ) return;
502        if ( dst.empty() ) { dst = src; return; }
503        dst += ", " + src;
504} // appendError
505
506void DeclarationNode::checkQualifiers( const TypeData * src, const TypeData * dst ) {
507        const ast::CV::Qualifiers qsrc = src->qualifiers, qdst = dst->qualifiers; // optimization
508        const ast::CV::Qualifiers duplicates = qsrc & qdst;
509
510        if ( duplicates.any() ) {
511                std::stringstream str;
512                str << "duplicate ";
513                ast::print( str, duplicates );
514                str << "qualifier(s)";
515                appendError( error, str.str() );
516        } // for
517} // DeclarationNode::checkQualifiers
518
519void DeclarationNode::checkSpecifiers( DeclarationNode * src ) {
520        ast::Function::Specs fsDups = funcSpecs & src->funcSpecs;
521        if ( fsDups.any() ) {
522                std::stringstream str;
523                str << "duplicate ";
524                ast::print( str, fsDups );
525                str << "function specifier(s)";
526                appendError( error, str.str() );
527        } // if
528
529        // Skip if everything is unset.
530        if ( storageClasses.any() && src->storageClasses.any() ) {
531                ast::Storage::Classes dups = storageClasses & src->storageClasses;
532                // Check for duplicates.
533                if ( dups.any() ) {
534                        std::stringstream str;
535                        str << "duplicate ";
536                        ast::print( str, dups );
537                        str << "storage class(es)";
538                        appendError( error, str.str() );
539                // Check for conflicts.
540                } else if ( !src->storageClasses.is_threadlocal_any() ) {
541                        std::stringstream str;
542                        str << "conflicting ";
543                        ast::print( str, ast::Storage::Classes( 1 << storageClasses.ffs() ) );
544                        str << "& ";
545                        ast::print( str, ast::Storage::Classes( 1 << src->storageClasses.ffs() ) );
546                        str << "storage classes";
547                        appendError( error, str.str() );
548                        // FIX to preserve invariant of one basic storage specifier
549                        src->storageClasses.reset();
550                }
551        } // if
552
553        appendError( error, src->error );
554} // DeclarationNode::checkSpecifiers
555
556DeclarationNode * DeclarationNode::copySpecifiers( DeclarationNode * q ) {
557        funcSpecs |= q->funcSpecs;
558        storageClasses |= q->storageClasses;
559
560        std::vector<ast::ptr<ast::Attribute>> tmp;
561        tmp.reserve( q->attributes.size() );
562        for ( auto const & attr : q->attributes ) {
563                tmp.emplace_back( ast::shallowCopy( attr.get() ) );
564        }
565        spliceBegin( attributes, tmp );
566
567        return this;
568} // DeclarationNode::copySpecifiers
569
570static void addQualifiersToType( TypeData *& src, TypeData * dst ) {
571        if ( dst->base ) {
572                addQualifiersToType( src, dst->base );
573        } else if ( dst->kind == TypeData::Function ) {
574                dst->base = src;
575                src = nullptr;
576        } else {
577                dst->qualifiers |= src->qualifiers;
578        } // if
579} // addQualifiersToType
580
581DeclarationNode * DeclarationNode::addQualifiers( DeclarationNode * q ) {
582        if ( ! q ) { return this; }                                                     // empty qualifier
583
584        checkSpecifiers( q );
585        copySpecifiers( q );
586
587        if ( ! q->type ) { delete q; return this; }
588
589        if ( ! type ) {
590                type = q->type;                                                                 // reuse structure
591                q->type = nullptr;
592                delete q;
593                return this;
594        } // if
595
596        if ( q->type->forall ) {                                                        // forall qualifier ?
597                if ( type->forall ) {                                                   // polymorphic routine ?
598                        type->forall->appendList( q->type->forall ); // augment forall qualifier
599                } else {
600                        if ( type->kind == TypeData::Aggregate ) {      // struct/union ?
601                                if ( type->aggregate.params ) {                 // polymorphic ?
602                                        type->aggregate.params->appendList( q->type->forall ); // augment forall qualifier
603                                } else {                                                                // not polymorphic
604                                        type->aggregate.params = q->type->forall; // set forall qualifier
605                                } // if
606                        } else {                                                                        // not polymorphic
607                                type->forall = q->type->forall;                 // make polymorphic routine
608                        } // if
609                } // if
610                q->type->forall = nullptr;                                              // forall qualifier moved
611        } // if
612
613        checkQualifiers( type, q->type );
614        if ( (builtin == Zero || builtin == One) && q->type->qualifiers.any() && error.length() == 0 ) {
615                SemanticWarning( yylloc, Warning::BadQualifiersZeroOne, builtinTypeNames[builtin] );
616        } // if
617        addQualifiersToType( q->type, type );
618
619        delete q;
620        return this;
621} // addQualifiers
622
623static void addTypeToType( TypeData *& src, TypeData *& dst ) {
624        if ( src->forall && dst->kind == TypeData::Function ) {
625                if ( dst->forall ) {
626                        dst->forall->appendList( src->forall );
627                } else {
628                        dst->forall = src->forall;
629                } // if
630                src->forall = nullptr;
631        } // if
632        if ( dst->base ) {
633                addTypeToType( src, dst->base );
634        } else {
635                switch ( dst->kind ) {
636                case TypeData::Unknown:
637                        src->qualifiers |= dst->qualifiers;
638                        dst = src;
639                        src = nullptr;
640                        break;
641                case TypeData::Basic:
642                        dst->qualifiers |= src->qualifiers;
643                        if ( src->kind != TypeData::Unknown ) {
644                                assert( src->kind == TypeData::Basic );
645
646                                if ( dst->basictype == DeclarationNode::NoBasicType ) {
647                                        dst->basictype = src->basictype;
648                                } else if ( src->basictype != DeclarationNode::NoBasicType )
649                                        SemanticError( yylloc, string( "multiple declaration types \"" ) + DeclarationNode::basicTypeNames[ dst->basictype ] +
650                                                                   "\" and \"" + DeclarationNode::basicTypeNames[ src->basictype ] + "\"." );
651
652                                if ( dst->complextype == DeclarationNode::NoComplexType ) {
653                                        dst->complextype = src->complextype;
654                                } else if ( src->complextype != DeclarationNode::NoComplexType )
655                                        SemanticError( yylloc, string( "multiple declaration types \"" ) + DeclarationNode::complexTypeNames[ src->complextype ] +
656                                                                   "\" and \"" + DeclarationNode::complexTypeNames[ src->complextype ] + "\"." );
657
658                                if ( dst->signedness == DeclarationNode::NoSignedness ) {
659                                        dst->signedness = src->signedness;
660                                } else if ( src->signedness != DeclarationNode::NoSignedness )
661                                        SemanticError( yylloc, string( "conflicting type specifier \"" ) + DeclarationNode::signednessNames[ dst->signedness ] +
662                                                                   "\" and \"" + DeclarationNode::signednessNames[ src->signedness ] + "\"." );
663
664                                if ( dst->length == DeclarationNode::NoLength ) {
665                                        dst->length = src->length;
666                                } else if ( dst->length == DeclarationNode::Long && src->length == DeclarationNode::Long ) {
667                                        dst->length = DeclarationNode::LongLong;
668                                } else if ( src->length != DeclarationNode::NoLength )
669                                        SemanticError( yylloc, string( "conflicting type specifier \"" ) + DeclarationNode::lengthNames[ dst->length ] +
670                                                                   "\" and \"" + DeclarationNode::lengthNames[ src->length ] + "\"." );
671                        } // if
672                        break;
673                default:
674                        switch ( src->kind ) {
675                        case TypeData::Aggregate:
676                        case TypeData::Enum:
677                                dst->base = new TypeData( TypeData::AggregateInst );
678                                dst->base->aggInst.aggregate = src;
679                                if ( src->kind == TypeData::Aggregate ) {
680                                        dst->base->aggInst.params = maybeClone( src->aggregate.actuals );
681                                } // if
682                                dst->base->qualifiers |= src->qualifiers;
683                                src = nullptr;
684                                break;
685                        default:
686                                if ( dst->forall ) {
687                                        dst->forall->appendList( src->forall );
688                                } else {
689                                        dst->forall = src->forall;
690                                } // if
691                                src->forall = nullptr;
692                                dst->base = src;
693                                src = nullptr;
694                        } // switch
695                } // switch
696        } // if
697}
698
699DeclarationNode * DeclarationNode::addType( DeclarationNode * o ) {
700        if ( o ) {
701                checkSpecifiers( o );
702                copySpecifiers( o );
703                if ( o->type ) {
704                        if ( ! type ) {
705                                if ( o->type->kind == TypeData::Aggregate || o->type->kind == TypeData::Enum ) {
706                                        type = new TypeData( TypeData::AggregateInst );
707                                        type->aggInst.aggregate = o->type;
708                                        if ( o->type->kind == TypeData::Aggregate ) {
709                                                type->aggInst.hoistType = o->type->aggregate.body;
710                                                type->aggInst.params = maybeClone( o->type->aggregate.actuals );
711                                        } else {
712                                                type->aggInst.hoistType = o->type->enumeration.body;
713                                        } // if
714                                        type->qualifiers |= o->type->qualifiers;
715                                } else {
716                                        type = o->type;
717                                } // if
718                                o->type = nullptr;
719                        } else {
720                                addTypeToType( o->type, type );
721                        } // if
722                } // if
723                if ( o->bitfieldWidth ) {
724                        bitfieldWidth = o->bitfieldWidth;
725                } // if
726
727                // there may be typedefs chained onto the type
728                if ( o->get_next() ) {
729                        set_last( o->get_next()->clone() );
730                } // if
731        } // if
732        delete o;
733
734        return this;
735}
736
737DeclarationNode * DeclarationNode::addEnumBase( DeclarationNode * o ) {
738        if ( o && o->type)  {
739                type->base= o->type;
740        } // if
741        delete o;
742        return this;
743}
744
745DeclarationNode * DeclarationNode::addTypedef() {
746        TypeData * newtype = new TypeData( TypeData::Symbolic );
747        newtype->symbolic.params = nullptr;
748        newtype->symbolic.isTypedef = true;
749        newtype->symbolic.name = name ? new string( *name ) : nullptr;
750        newtype->base = type;
751        type = newtype;
752        return this;
753}
754
755DeclarationNode * DeclarationNode::addAssertions( DeclarationNode * assertions ) {
756        if ( variable.tyClass != ast::TypeDecl::NUMBER_OF_KINDS ) {
757                if ( variable.assertions ) {
758                        variable.assertions->appendList( assertions );
759                } else {
760                        variable.assertions = assertions;
761                } // if
762                return this;
763        } // if
764
765        assert( type );
766        switch ( type->kind ) {
767        case TypeData::Symbolic:
768                if ( type->symbolic.assertions ) {
769                        type->symbolic.assertions->appendList( assertions );
770                } else {
771                        type->symbolic.assertions = assertions;
772                } // if
773                break;
774        default:
775                assert( false );
776        } // switch
777
778        return this;
779}
780
781DeclarationNode * DeclarationNode::addName( string * newname ) {
782        assert( ! name );
783        name = newname;
784        return this;
785}
786
787DeclarationNode * DeclarationNode::addAsmName( DeclarationNode * newname ) {
788        assert( ! asmName );
789        asmName = newname ? newname->asmName : nullptr;
790        return this->addQualifiers( newname );
791}
792
793DeclarationNode * DeclarationNode::addBitfield( ExpressionNode * size ) {
794        bitfieldWidth = size;
795        return this;
796}
797
798DeclarationNode * DeclarationNode::addVarArgs() {
799        assert( type );
800        hasEllipsis = true;
801        return this;
802}
803
804DeclarationNode * DeclarationNode::addFunctionBody( StatementNode * body, ExpressionNode * withExprs ) {
805        assert( type );
806        assert( type->kind == TypeData::Function );
807        assert( ! type->function.body );
808        type->function.body = body;
809        type->function.withExprs = withExprs;
810        return this;
811}
812
813DeclarationNode * DeclarationNode::addOldDeclList( DeclarationNode * list ) {
814        assert( type );
815        assert( type->kind == TypeData::Function );
816        assert( ! type->function.oldDeclList );
817        type->function.oldDeclList = list;
818        return this;
819}
820
821DeclarationNode * DeclarationNode::setBase( TypeData * newType ) {
822        if ( type ) {
823                TypeData * prevBase = type;
824                TypeData * curBase = type->base;
825                while ( curBase != nullptr ) {
826                        prevBase = curBase;
827                        curBase = curBase->base;
828                } // while
829                prevBase->base = newType;
830        } else {
831                type = newType;
832        } // if
833        return this;
834}
835
836DeclarationNode * DeclarationNode::copyAttribute( DeclarationNode * a ) {
837        if ( a ) {
838                spliceBegin( attributes, a->attributes );
839                a->attributes.clear();
840        } // if
841        return this;
842} // copyAttribute
843
844DeclarationNode * DeclarationNode::addPointer( DeclarationNode * p ) {
845        if ( p ) {
846                assert( p->type->kind == TypeData::Pointer || p->type->kind == TypeData::Reference );
847                setBase( p->type );
848                p->type = nullptr;
849                copyAttribute( p );
850                delete p;
851        } // if
852        return this;
853}
854
855DeclarationNode * DeclarationNode::addArray( DeclarationNode * a ) {
856        if ( a ) {
857                assert( a->type->kind == TypeData::Array );
858                setBase( a->type );
859                a->type = nullptr;
860                copyAttribute( a );
861                delete a;
862        } // if
863        return this;
864}
865
866DeclarationNode * DeclarationNode::addNewPointer( DeclarationNode * p ) {
867        if ( p ) {
868                assert( p->type->kind == TypeData::Pointer || p->type->kind == TypeData::Reference );
869                if ( type ) {
870                        switch ( type->kind ) {
871                        case TypeData::Aggregate:
872                        case TypeData::Enum:
873                                p->type->base = new TypeData( TypeData::AggregateInst );
874                                p->type->base->aggInst.aggregate = type;
875                                if ( type->kind == TypeData::Aggregate ) {
876                                        p->type->base->aggInst.params = maybeClone( type->aggregate.actuals );
877                                } // if
878                                p->type->base->qualifiers |= type->qualifiers;
879                                break;
880
881                        default:
882                                p->type->base = type;
883                        } // switch
884                        type = nullptr;
885                } // if
886                delete this;
887                return p;
888        } else {
889                return this;
890        } // if
891}
892
893static TypeData * findLast( TypeData * a ) {
894        assert( a );
895        TypeData * cur = a;
896        while ( cur->base ) {
897                cur = cur->base;
898        } // while
899        return cur;
900}
901
902DeclarationNode * DeclarationNode::addNewArray( DeclarationNode * a ) {
903        if ( ! a ) return this;
904        assert( a->type->kind == TypeData::Array );
905        TypeData * lastArray = findLast( a->type );
906        if ( type ) {
907                switch ( type->kind ) {
908                case TypeData::Aggregate:
909                case TypeData::Enum:
910                        lastArray->base = new TypeData( TypeData::AggregateInst );
911                        lastArray->base->aggInst.aggregate = type;
912                        if ( type->kind == TypeData::Aggregate ) {
913                                lastArray->base->aggInst.params = maybeClone( type->aggregate.actuals );
914                        } // if
915                        lastArray->base->qualifiers |= type->qualifiers;
916                        break;
917                default:
918                        lastArray->base = type;
919                } // switch
920                type = nullptr;
921        } // if
922        delete this;
923        return a;
924}
925
926DeclarationNode * DeclarationNode::addParamList( DeclarationNode * params ) {
927        TypeData * ftype = new TypeData( TypeData::Function );
928        ftype->function.params = params;
929        setBase( ftype );
930        return this;
931}
932
933static TypeData * addIdListToType( TypeData * type, DeclarationNode * ids ) {
934        if ( type ) {
935                if ( type->kind != TypeData::Function ) {
936                        type->base = addIdListToType( type->base, ids );
937                } else {
938                        type->function.idList = ids;
939                } // if
940                return type;
941        } else {
942                TypeData * newtype = new TypeData( TypeData::Function );
943                newtype->function.idList = ids;
944                return newtype;
945        } // if
946} // addIdListToType
947
948DeclarationNode * DeclarationNode::addIdList( DeclarationNode * ids ) {
949        type = addIdListToType( type, ids );
950        return this;
951}
952
953DeclarationNode * DeclarationNode::addInitializer( InitializerNode * init ) {
954        initializer = init;
955        return this;
956}
957
958DeclarationNode * DeclarationNode::addTypeInitializer( DeclarationNode * init ) {
959        assertf( variable.tyClass != ast::TypeDecl::NUMBER_OF_KINDS, "Called addTypeInitializer on something that isn't a type variable." );
960        variable.initializer = init;
961        return this;
962}
963
964DeclarationNode * DeclarationNode::cloneType( string * name ) {
965        DeclarationNode * newnode = newName( name );
966        newnode->type = maybeClone( type );
967        newnode->copySpecifiers( this );
968        return newnode;
969}
970
971DeclarationNode * DeclarationNode::cloneBaseType( DeclarationNode * o ) {
972        if ( ! o ) return nullptr;
973
974        o->copySpecifiers( this );
975        if ( type ) {
976                TypeData * srcType = type;
977
978                // search for the base type by scanning off pointers and array designators
979                while ( srcType->base ) {
980                        srcType = srcType->base;
981                } // while
982
983                TypeData * newType = srcType->clone();
984                if ( newType->kind == TypeData::AggregateInst ) {
985                        // don't duplicate members
986                        if ( newType->aggInst.aggregate->kind == TypeData::Enum ) {
987                                delete newType->aggInst.aggregate->enumeration.constants;
988                                newType->aggInst.aggregate->enumeration.constants = nullptr;
989                                newType->aggInst.aggregate->enumeration.body = false;
990                        } else {
991                                assert( newType->aggInst.aggregate->kind == TypeData::Aggregate );
992                                delete newType->aggInst.aggregate->aggregate.fields;
993                                newType->aggInst.aggregate->aggregate.fields = nullptr;
994                                newType->aggInst.aggregate->aggregate.body = false;
995                        } // if
996                        // don't hoist twice
997                        newType->aggInst.hoistType = false;
998                } // if
999
1000                newType->forall = maybeClone( type->forall );
1001                if ( ! o->type ) {
1002                        o->type = newType;
1003                } else {
1004                        addTypeToType( newType, o->type );
1005                        delete newType;
1006                } // if
1007        } // if
1008        return o;
1009}
1010
1011DeclarationNode * DeclarationNode::extractAggregate() const {
1012        if ( type ) {
1013                TypeData * ret = typeextractAggregate( type );
1014                if ( ret ) {
1015                        DeclarationNode * newnode = new DeclarationNode;
1016                        newnode->type = ret;
1017                        return newnode;
1018                } // if
1019        } // if
1020        return nullptr;
1021}
1022
1023// If a typedef wraps an anonymous declaration, name the inner declaration so it has a consistent name across
1024// translation units.
1025static void nameTypedefedDecl(
1026                DeclarationNode * innerDecl,
1027                const DeclarationNode * outerDecl ) {
1028        TypeData * outer = outerDecl->type;
1029        assert( outer );
1030        // First make sure this is a typedef:
1031        if ( outer->kind != TypeData::Symbolic || !outer->symbolic.isTypedef ) {
1032                return;
1033        }
1034        TypeData * inner = innerDecl->type;
1035        assert( inner );
1036        // Always clear any CVs associated with the aggregate:
1037        inner->qualifiers.reset();
1038        // Handle anonymous aggregates: typedef struct { int i; } foo
1039        if ( inner->kind == TypeData::Aggregate && inner->aggregate.anon ) {
1040                delete inner->aggregate.name;
1041                inner->aggregate.name = new string( "__anonymous_" + *outerDecl->name );
1042                inner->aggregate.anon = false;
1043                assert( outer->base );
1044                delete outer->base->aggInst.aggregate->aggregate.name;
1045                outer->base->aggInst.aggregate->aggregate.name = new string( "__anonymous_" + *outerDecl->name );
1046                outer->base->aggInst.aggregate->aggregate.anon = false;
1047                outer->base->aggInst.aggregate->qualifiers.reset();
1048        // Handle anonymous enumeration: typedef enum { A, B, C } foo
1049        } else if ( inner->kind == TypeData::Enum && inner->enumeration.anon ) {
1050                delete inner->enumeration.name;
1051                inner->enumeration.name = new string( "__anonymous_" + *outerDecl->name );
1052                inner->enumeration.anon = false;
1053                assert( outer->base );
1054                delete outer->base->aggInst.aggregate->enumeration.name;
1055                outer->base->aggInst.aggregate->enumeration.name = new string( "__anonymous_" + *outerDecl->name );
1056                outer->base->aggInst.aggregate->enumeration.anon = false;
1057                // No qualifiers.reset() here.
1058        }
1059}
1060
1061// This code handles a special issue with the attribute transparent_union.
1062//
1063//    typedef union U { int i; } typedef_name __attribute__(( aligned(16) )) __attribute__(( transparent_union ))
1064//
1065// Here the attribute aligned goes with the typedef_name, so variables declared of this type are
1066// aligned.  However, the attribute transparent_union must be moved from the typedef_name to
1067// alias union U.  Currently, this is the only know attribute that must be moved from typedef to
1068// alias.
1069static void moveUnionAttribute( ast::Decl * decl, ast::UnionDecl * unionDecl ) {
1070        if ( auto typedefDecl = dynamic_cast<ast::TypedefDecl *>( decl ) ) {
1071                // Is the typedef alias a union aggregate?
1072                if ( nullptr == unionDecl ) return;
1073
1074                // If typedef is an alias for a union, then its alias type was hoisted above and remembered.
1075                if ( auto unionInstType = typedefDecl->base.as<ast::UnionInstType>() ) {
1076                        auto instType = ast::mutate( unionInstType );
1077                        // Remove all transparent_union attributes from typedef and move to alias union.
1078                        for ( auto attr = instType->attributes.begin() ; attr != instType->attributes.end() ; ) {
1079                                assert( *attr );
1080                                if ( (*attr)->name == "transparent_union" || (*attr)->name == "__transparent_union__" ) {
1081                                        unionDecl->attributes.emplace_back( attr->release() );
1082                                        attr = instType->attributes.erase( attr );
1083                                } else {
1084                                        attr++;
1085                                }
1086                        }
1087                        typedefDecl->base = instType;
1088                }
1089        }
1090}
1091
1092// Get the non-anonymous name of the instance type of the declaration,
1093// if one exists.
1094static const std::string * getInstTypeOfName( ast::Decl * decl ) {
1095        if ( auto dwt = dynamic_cast<ast::DeclWithType *>( decl ) ) {
1096                if ( auto aggr = dynamic_cast<ast::BaseInstType const *>( dwt->get_type() ) ) {
1097                        if ( aggr->name.find("anonymous") == std::string::npos ) {
1098                                return &aggr->name;
1099                        }
1100                }
1101        }
1102        return nullptr;
1103}
1104
1105void buildList( DeclarationNode * firstNode, std::vector<ast::ptr<ast::Decl>> & outputList ) {
1106        SemanticErrorException errors;
1107        std::back_insert_iterator<std::vector<ast::ptr<ast::Decl>>> out( outputList );
1108
1109        for ( const DeclarationNode * cur = firstNode ; cur ; cur = strict_next( cur ) ) {
1110                try {
1111                        bool extracted_named = false;
1112                        ast::UnionDecl * unionDecl = nullptr;
1113
1114                        if ( DeclarationNode * extr = cur->extractAggregate() ) {
1115                                assert( cur->type );
1116                                nameTypedefedDecl( extr, cur );
1117
1118                                if ( ast::Decl * decl = extr->build() ) {
1119                                        // Remember the declaration if it is a union aggregate ?
1120                                        unionDecl = dynamic_cast<ast::UnionDecl *>( decl );
1121
1122                                        *out++ = decl;
1123
1124                                        // need to remember the cases where a declaration contains an anonymous aggregate definition
1125                                        assert( extr->type );
1126                                        if ( extr->type->kind == TypeData::Aggregate ) {
1127                                                // typedef struct { int A } B is the only case?
1128                                                extracted_named = !extr->type->aggregate.anon;
1129                                        } else if ( extr->type->kind == TypeData::Enum ) {
1130                                                // typedef enum { A } B is the only case?
1131                                                extracted_named = !extr->type->enumeration.anon;
1132                                        } else {
1133                                                extracted_named = true;
1134                                        }
1135                                } // if
1136                                delete extr;
1137                        } // if
1138
1139                        if ( ast::Decl * decl = cur->build() ) {
1140                                moveUnionAttribute( decl, unionDecl );
1141
1142                                if ( "" == decl->name && !cur->get_inLine() ) {
1143                                        // Don't include anonymous declaration for named aggregates,
1144                                        // but do include them for anonymous aggregates, e.g.:
1145                                        // struct S {
1146                                        //   struct T { int x; }; // no anonymous member
1147                                        //   struct { int y; };   // anonymous member
1148                                        //   struct T;            // anonymous member
1149                                        // };
1150                                        if ( extracted_named ) {
1151                                                continue;
1152                                        }
1153
1154                                        if ( auto name = getInstTypeOfName( decl ) ) {
1155                                                // Temporary: warn about anonymous member declarations of named types, since
1156                                                // this conflicts with the syntax for the forward declaration of an anonymous type.
1157                                                SemanticWarning( cur->location, Warning::AggrForwardDecl, name->c_str() );
1158                                        }
1159                                } // if
1160                                *out++ = decl;
1161                        } // if
1162                } catch ( SemanticErrorException & e ) {
1163                        errors.append( e );
1164                } // try
1165        } // for
1166
1167        if ( ! errors.isEmpty() ) {
1168                throw errors;
1169        } // if
1170} // buildList
1171
1172// currently only builds assertions, function parameters, and return values
1173void buildList( DeclarationNode * firstNode, std::vector<ast::ptr<ast::DeclWithType>> & outputList ) {
1174        SemanticErrorException errors;
1175        std::back_insert_iterator<std::vector<ast::ptr<ast::DeclWithType>>> out( outputList );
1176
1177        for ( const DeclarationNode * cur = firstNode; cur; cur = strict_next( cur ) ) {
1178                try {
1179                        ast::Decl * decl = cur->build();
1180                        assertf( decl, "buildList: build for ast::DeclWithType." );
1181                        if ( ast::DeclWithType * dwt = dynamic_cast<ast::DeclWithType *>( decl ) ) {
1182                                dwt->location = cur->location;
1183                                *out++ = dwt;
1184                        } else if ( ast::StructDecl * agg = dynamic_cast<ast::StructDecl *>( decl ) ) {
1185                                // e.g., int foo(struct S) {}
1186                                auto inst = new ast::StructInstType( agg->name );
1187                                auto obj = new ast::ObjectDecl( cur->location, "", inst );
1188                                obj->linkage = linkage;
1189                                *out++ = obj;
1190                                delete agg;
1191                        } else if ( ast::UnionDecl * agg = dynamic_cast<ast::UnionDecl *>( decl ) ) {
1192                                // e.g., int foo(union U) {}
1193                                auto inst = new ast::UnionInstType( agg->name );
1194                                auto obj = new ast::ObjectDecl( cur->location,
1195                                        "", inst, nullptr, ast::Storage::Classes(),
1196                                        linkage );
1197                                *out++ = obj;
1198                        } else if ( ast::EnumDecl * agg = dynamic_cast<ast::EnumDecl *>( decl ) ) {
1199                                // e.g., int foo(enum E) {}
1200                                auto inst = new ast::EnumInstType( agg->name );
1201                                auto obj = new ast::ObjectDecl( cur->location,
1202                                        "",
1203                                        inst,
1204                                        nullptr,
1205                                        ast::Storage::Classes(),
1206                                        linkage
1207                                );
1208                                *out++ = obj;
1209                        } else {
1210                                assertf( false, "buildList: Could not convert to ast::DeclWithType." );
1211                        } // if
1212                } catch ( SemanticErrorException & e ) {
1213                        errors.append( e );
1214                } // try
1215        } // for
1216
1217        if ( ! errors.isEmpty() ) {
1218                throw errors;
1219        } // if
1220} // buildList
1221
1222void buildTypeList( const DeclarationNode * firstNode,
1223                std::vector<ast::ptr<ast::Type>> & outputList ) {
1224        SemanticErrorException errors;
1225        std::back_insert_iterator<std::vector<ast::ptr<ast::Type>>> out( outputList );
1226
1227        for ( const DeclarationNode * cur = firstNode ; cur ; cur = strict_next( cur ) ) {
1228                try {
1229                        * out++ = cur->buildType();
1230                } catch ( SemanticErrorException & e ) {
1231                        errors.append( e );
1232                } // try
1233        } // for
1234
1235        if ( ! errors.isEmpty() ) {
1236                throw errors;
1237        } // if
1238} // buildTypeList
1239
1240ast::Decl * DeclarationNode::build() const {
1241        if ( ! error.empty() ) SemanticError( this, error + " in declaration of " );
1242
1243        if ( asmStmt ) {
1244                auto stmt = strict_dynamic_cast<ast::AsmStmt *>( asmStmt->build() );
1245                return new ast::AsmDecl( stmt->location, stmt );
1246        } // if
1247        if ( directiveStmt ) {
1248                auto stmt = strict_dynamic_cast<ast::DirectiveStmt *>( directiveStmt->build() );
1249                return new ast::DirectiveDecl( stmt->location, stmt );
1250        } // if
1251
1252        if ( variable.tyClass != ast::TypeDecl::NUMBER_OF_KINDS ) {
1253                // otype is internally converted to dtype + otype parameters
1254                static const ast::TypeDecl::Kind kindMap[] = { ast::TypeDecl::Dtype, ast::TypeDecl::Dtype, ast::TypeDecl::Dtype, ast::TypeDecl::Ftype, ast::TypeDecl::Ttype, ast::TypeDecl::Dimension };
1255                static_assert( sizeof(kindMap) / sizeof(kindMap[0]) == ast::TypeDecl::NUMBER_OF_KINDS, "DeclarationNode::build: kindMap is out of sync." );
1256                assertf( variable.tyClass < sizeof(kindMap)/sizeof(kindMap[0]), "Variable's tyClass is out of bounds." );
1257                ast::TypeDecl * ret = new ast::TypeDecl( location,
1258                        *name,
1259                        ast::Storage::Classes(),
1260                        (ast::Type *)nullptr,
1261                        kindMap[ variable.tyClass ],
1262                        variable.tyClass == ast::TypeDecl::Otype || variable.tyClass == ast::TypeDecl::DStype,
1263                        variable.initializer ? variable.initializer->buildType() : nullptr
1264                );
1265                buildList( variable.assertions, ret->assertions );
1266                return ret;
1267        } // if
1268
1269        if ( type ) {
1270                // Function specifiers can only appear on a function definition/declaration.
1271                //
1272                //    inline _Noreturn int f();                 // allowed
1273                //    inline _Noreturn int g( int i );  // allowed
1274                //    inline _Noreturn int i;                   // disallowed
1275                if ( type->kind != TypeData::Function && funcSpecs.any() ) {
1276                        SemanticError( this, "invalid function specifier for " );
1277                } // if
1278                // Forall qualifier can only appear on a function/aggregate definition/declaration.
1279                //
1280                //    forall int f();                                   // allowed
1281                //    forall int g( int i );                    // allowed
1282                //    forall int i;                                             // disallowed
1283                if ( type->kind != TypeData::Function && type->forall ) {
1284                        SemanticError( this, "invalid type qualifier for " );
1285                } // if
1286                bool isDelete = initializer && initializer->get_isDelete();
1287                ast::Decl * decl = buildDecl(
1288                        type,
1289                        name ? *name : string( "" ),
1290                        storageClasses,
1291                        maybeBuild( bitfieldWidth ),
1292                        funcSpecs,
1293                        linkage,
1294                        asmName,
1295                        isDelete ? nullptr : maybeBuild( initializer ),
1296                        copy( attributes )
1297                )->set_extension( extension );
1298                if ( isDelete ) {
1299                        auto dwt = strict_dynamic_cast<ast::DeclWithType *>( decl );
1300                        dwt->isDeleted = true;
1301                }
1302                return decl;
1303        } // if
1304
1305        if ( assert.condition ) {
1306                auto cond = maybeBuild( assert.condition );
1307                auto msg = strict_dynamic_cast<ast::ConstantExpr *>( maybeCopy( assert.message ) );
1308                return new ast::StaticAssertDecl( location, cond, msg );
1309        }
1310
1311        // SUE's cannot have function specifiers, either
1312        //
1313        //    inline _Noreturn struct S { ... };                // disallowed
1314        //    inline _Noreturn enum   E { ... };                // disallowed
1315        if ( funcSpecs.any() ) {
1316                SemanticError( this, "invalid function specifier for " );
1317        } // if
1318        if ( enumInLine ) {
1319                return new ast::InlineMemberDecl( location,
1320                        *name, (ast::Type*)nullptr, storageClasses, linkage );
1321        } // if
1322        assertf( name, "ObjectDecl must a have name\n" );
1323        auto ret = new ast::ObjectDecl( location,
1324                *name,
1325                (ast::Type*)nullptr,
1326                maybeBuild( initializer ),
1327                storageClasses,
1328                linkage,
1329                maybeBuild( bitfieldWidth )
1330        );
1331        ret->asmName = asmName;
1332        ret->extension = extension;
1333        return ret;
1334}
1335
1336ast::Type * DeclarationNode::buildType() const {
1337        assert( type );
1338
1339        switch ( type->kind ) {
1340        case TypeData::Enum:
1341        case TypeData::Aggregate: {
1342                ast::BaseInstType * ret =
1343                        buildComAggInst( type, copy( attributes ), linkage );
1344                buildList( type->aggregate.actuals, ret->params );
1345                return ret;
1346        }
1347        case TypeData::Symbolic: {
1348                ast::TypeInstType * ret = new ast::TypeInstType(
1349                        *type->symbolic.name,
1350                        // This is just a default, the true value is not known yet.
1351                        ast::TypeDecl::Dtype,
1352                        buildQualifiers( type ),
1353                        copy( attributes ) );
1354                buildList( type->symbolic.actuals, ret->params );
1355                return ret;
1356        }
1357        default:
1358                ast::Type * simpletypes = typebuild( type );
1359                // copy because member is const
1360                simpletypes->attributes = attributes;
1361                return simpletypes;
1362        } // switch
1363}
1364
1365// Local Variables: //
1366// tab-width: 4 //
1367// mode: c++ //
1368// compile-command: "make install" //
1369// End: //
Note: See TracBrowser for help on using the repository browser.