source: src/Parser/DeclarationNode.cc @ a8ef59e

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since a8ef59e was a77713b, checked in by JiadaL <j82liang@…>, 3 years ago

Enable typed enum

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