source: src/Parser/DeclarationNode.cc @ f135b50

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

The compiler is now trying to pass the value of enum const to code gen; but it won't work cause we must be able to evaluate the const_expr in compiler time. It is not currently passed as a Expression but won't be able to evaluate at compile time

  • Property mode set to 100644
File size: 39.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 : 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 typed) {
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 ) { // Marker
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::addEnumBase( DeclarationNode * o ) {
670        if ( o && o -> type)  {
671                type->base= o->type;
672        }
673        delete o;
674        return this;
675}
676
677DeclarationNode * DeclarationNode::addTypedef() {
678        TypeData * newtype = new TypeData( TypeData::Symbolic );
679        newtype->symbolic.params = nullptr;
680        newtype->symbolic.isTypedef = true;
681        newtype->symbolic.name = name ? new string( *name ) : nullptr;
682        newtype->base = type;
683        type = newtype;
684        return this;
685}
686
687DeclarationNode * DeclarationNode::addAssertions( DeclarationNode * assertions ) {
688        if ( variable.tyClass != TypeDecl::NUMBER_OF_KINDS ) {
689                if ( variable.assertions ) {
690                        variable.assertions->appendList( assertions );
691                } else {
692                        variable.assertions = assertions;
693                } // if
694                return this;
695        } // if
696
697        assert( type );
698        switch ( type->kind ) {
699          case TypeData::Symbolic:
700                if ( type->symbolic.assertions ) {
701                        type->symbolic.assertions->appendList( assertions );
702                } else {
703                        type->symbolic.assertions = assertions;
704                } // if
705                break;
706          default:
707                assert( false );
708        } // switch
709
710        return this;
711}
712
713DeclarationNode * DeclarationNode::addName( string * newname ) {
714        assert( ! name );
715        name = newname;
716        return this;
717}
718
719DeclarationNode * DeclarationNode::addAsmName( DeclarationNode * newname ) {
720        assert( ! asmName );
721        asmName = newname ? newname->asmName : nullptr;
722        return this->addQualifiers( newname );
723}
724
725DeclarationNode * DeclarationNode::addBitfield( ExpressionNode * size ) {
726        bitfieldWidth = size;
727        return this;
728}
729
730DeclarationNode * DeclarationNode::addVarArgs() {
731        assert( type );
732        hasEllipsis = true;
733        return this;
734}
735
736DeclarationNode * DeclarationNode::addFunctionBody( StatementNode * body, ExpressionNode * withExprs ) {
737        assert( type );
738        assert( type->kind == TypeData::Function );
739        assert( ! type->function.body );
740        type->function.body = body;
741        type->function.withExprs = withExprs;
742        return this;
743}
744
745DeclarationNode * DeclarationNode::addOldDeclList( DeclarationNode * list ) {
746        assert( type );
747        assert( type->kind == TypeData::Function );
748        assert( ! type->function.oldDeclList );
749        type->function.oldDeclList = list;
750        return this;
751}
752
753DeclarationNode * DeclarationNode::setBase( TypeData * newType ) {
754        if ( type ) {
755                TypeData * prevBase = type;
756                TypeData * curBase = type->base;
757                while ( curBase != nullptr ) {
758                        prevBase = curBase;
759                        curBase = curBase->base;
760                } // while
761                prevBase->base = newType;
762        } else {
763                type = newType;
764        } // if
765        return this;
766}
767
768DeclarationNode * DeclarationNode::copyAttribute( DeclarationNode * a ) {
769        if ( a ) {
770                for ( Attribute *attr: reverseIterate( a->attributes ) ) {
771                        attributes.push_front( attr );
772                } // for
773                a->attributes.clear();
774        } // if
775        return this;
776} // copyAttribute
777
778DeclarationNode * DeclarationNode::addPointer( DeclarationNode * p ) {
779        if ( p ) {
780                assert( p->type->kind == TypeData::Pointer || p->type->kind == TypeData::Reference );
781                setBase( p->type );
782                p->type = nullptr;
783                copyAttribute( p );
784                delete p;
785        } // if
786        return this;
787}
788
789DeclarationNode * DeclarationNode::addArray( DeclarationNode * a ) {
790        if ( a ) {
791                assert( a->type->kind == TypeData::Array );
792                setBase( a->type );
793                a->type = nullptr;
794                copyAttribute( a );
795                delete a;
796        } // if
797        return this;
798}
799
800DeclarationNode * DeclarationNode::addNewPointer( DeclarationNode * p ) {
801        if ( p ) {
802                assert( p->type->kind == TypeData::Pointer || p->type->kind == TypeData::Reference );
803                if ( type ) {
804                        switch ( type->kind ) {
805                          case TypeData::Aggregate:
806                          case TypeData::Enum:
807                                p->type->base = new TypeData( TypeData::AggregateInst );
808                                p->type->base->aggInst.aggregate = type;
809                                if ( type->kind == TypeData::Aggregate ) {
810                                        p->type->base->aggInst.params = maybeClone( type->aggregate.actuals );
811                                } // if
812                                p->type->base->qualifiers |= type->qualifiers;
813                                break;
814
815                          default:
816                                p->type->base = type;
817                        } // switch
818                        type = nullptr;
819                } // if
820                delete this;
821                return p;
822        } else {
823                return this;
824        } // if
825}
826
827static TypeData * findLast( TypeData * a ) {
828        assert( a );
829        TypeData * cur = a;
830        while ( cur->base ) {
831                cur = cur->base;
832        } // while
833        return cur;
834}
835
836DeclarationNode * DeclarationNode::addNewArray( DeclarationNode * a ) {
837  if ( ! a ) return this;
838        assert( a->type->kind == TypeData::Array );
839        TypeData * lastArray = findLast( a->type );
840        if ( type ) {
841                switch ( type->kind ) {
842                  case TypeData::Aggregate:
843                  case TypeData::Enum:
844                        lastArray->base = new TypeData( TypeData::AggregateInst );
845                        lastArray->base->aggInst.aggregate = type;
846                        if ( type->kind == TypeData::Aggregate ) {
847                                lastArray->base->aggInst.params = maybeClone( type->aggregate.actuals );
848                        } // if
849                        lastArray->base->qualifiers |= type->qualifiers;
850                        break;
851                  default:
852                        lastArray->base = type;
853                } // switch
854                type = nullptr;
855        } // if
856        delete this;
857        return a;
858}
859
860DeclarationNode * DeclarationNode::addParamList( DeclarationNode * params ) {
861        TypeData * ftype = new TypeData( TypeData::Function );
862        ftype->function.params = params;
863        setBase( ftype );
864        return this;
865}
866
867static TypeData * addIdListToType( TypeData * type, DeclarationNode * ids ) {
868        if ( type ) {
869                if ( type->kind != TypeData::Function ) {
870                        type->base = addIdListToType( type->base, ids );
871                } else {
872                        type->function.idList = ids;
873                } // if
874                return type;
875        } else {
876                TypeData * newtype = new TypeData( TypeData::Function );
877                newtype->function.idList = ids;
878                return newtype;
879        } // if
880} // addIdListToType
881
882DeclarationNode * DeclarationNode::addIdList( DeclarationNode * ids ) {
883        type = addIdListToType( type, ids );
884        return this;
885}
886
887DeclarationNode * DeclarationNode::addInitializer( InitializerNode * init ) {
888        initializer = init;
889        return this;
890}
891
892DeclarationNode * DeclarationNode::addTypeInitializer( DeclarationNode * init ) {
893        assertf( variable.tyClass != TypeDecl::NUMBER_OF_KINDS, "Called addTypeInitializer on something that isn't a type variable." );
894        variable.initializer = init;
895        return this;
896}
897
898DeclarationNode * DeclarationNode::cloneType( string * name ) {
899        DeclarationNode * newnode = newName( name );
900        newnode->type = maybeClone( type );
901        newnode->copySpecifiers( this );
902        return newnode;
903}
904
905DeclarationNode * DeclarationNode::cloneBaseType( DeclarationNode * o ) {
906        if ( ! o ) return nullptr;
907
908        o->copySpecifiers( this );
909        if ( type ) {
910                TypeData * srcType = type;
911
912                // search for the base type by scanning off pointers and array designators
913                while ( srcType->base ) {
914                        srcType = srcType->base;
915                } // while
916
917                TypeData * newType = srcType->clone();
918                if ( newType->kind == TypeData::AggregateInst ) {
919                        // don't duplicate members
920                        if ( newType->aggInst.aggregate->kind == TypeData::Enum ) {
921                                delete newType->aggInst.aggregate->enumeration.constants;
922                                newType->aggInst.aggregate->enumeration.constants = nullptr;
923                                newType->aggInst.aggregate->enumeration.body = false;
924                        } else {
925                                assert( newType->aggInst.aggregate->kind == TypeData::Aggregate );
926                                delete newType->aggInst.aggregate->aggregate.fields;
927                                newType->aggInst.aggregate->aggregate.fields = nullptr;
928                                newType->aggInst.aggregate->aggregate.body = false;
929                        } // if
930                        // don't hoist twice
931                        newType->aggInst.hoistType = false;
932                } // if
933
934                newType->forall = maybeClone( type->forall );
935                if ( ! o->type ) {
936                        o->type = newType;
937                } else {
938                        addTypeToType( newType, o->type );
939                        delete newType;
940                } // if
941        } // if
942        return o;
943}
944
945DeclarationNode * DeclarationNode::extractAggregate() const {
946        if ( type ) {
947                TypeData * ret = typeextractAggregate( type );
948                if ( ret ) {
949                        DeclarationNode * newnode = new DeclarationNode;
950                        newnode->type = ret;
951                        return newnode;
952                } // if
953        } // if
954        return nullptr;
955}
956
957void buildList( const DeclarationNode * firstNode, std::list< Declaration * > & outputList ) {
958        SemanticErrorException errors;
959        std::back_insert_iterator< std::list< Declaration * > > out( outputList );
960
961        for ( const DeclarationNode * cur = firstNode; cur; cur = dynamic_cast< DeclarationNode * >( cur->get_next() ) ) {
962                try {
963                        bool extracted = false;
964                        bool anon = false;
965                        if ( DeclarationNode * extr = cur->extractAggregate() ) {
966                                // handle the case where a structure declaration is contained within an object or type declaration
967                                Declaration * decl = extr->build();
968                                if ( decl ) {
969                                        // hoist the structure declaration
970                                        decl->location = cur->location;
971                                        * out++ = decl;
972
973                                        // need to remember the cases where a declaration contains an anonymous aggregate definition
974                                        extracted = true;
975                                        assert( extr->type );
976                                        if ( extr->type->kind == TypeData::Aggregate ) {
977                                                anon = extr->type->aggregate.anon;
978                                        } else if ( extr->type->kind == TypeData::Enum ) {
979                                                // xxx - is it useful to have an implicit anonymous enum member?
980                                                anon = extr->type->enumeration.anon;
981                                        }
982                                } // if
983                                delete extr;
984                        } // if
985
986                        Declaration * decl = cur->build();
987                        if ( decl ) {
988                                // don't include anonymous declaration for named aggregates, but do include them for anonymous aggregates, e.g.:
989                                // struct S {
990                                //   struct T { int x; }; // no anonymous member
991                                //   struct { int y; };   // anonymous member
992                                //   struct T;            // anonymous member
993                                // };
994                                if ( ! (extracted && decl->name == "" && ! anon && ! cur->get_inLine()) ) {
995                                        if ( decl->name == "" ) {
996                                                if ( DeclarationWithType * dwt = dynamic_cast<DeclarationWithType *>( decl ) ) {
997                                                        if ( ReferenceToType * aggr = dynamic_cast<ReferenceToType *>( dwt->get_type() ) ) {
998                                                                if ( aggr->name.find("anonymous") == std::string::npos ) {
999                                                                        if ( ! cur->get_inLine() ) {
1000                                                                                // temporary: warn about anonymous member declarations of named types, since
1001                                                                                // this conflicts with the syntax for the forward declaration of an anonymous type
1002                                                                                SemanticWarning( cur->location, Warning::AggrForwardDecl, aggr->name.c_str() );
1003                                                                        } // if
1004                                                                } // if
1005                                                        } // if
1006                                                } // if
1007                                        } // if
1008                                        decl->location = cur->location;
1009                                        *out++ = decl;
1010                                } // if
1011                        } // if
1012                } catch( SemanticErrorException & e ) {
1013                        errors.append( e );
1014                } // try
1015        } // for
1016
1017        if ( ! errors.isEmpty() ) {
1018                throw errors;
1019        } // if
1020} // buildList
1021
1022// currently only builds assertions, function parameters, and return values
1023void buildList( const DeclarationNode * firstNode, std::list< DeclarationWithType * > & outputList ) {
1024        SemanticErrorException errors;
1025        std::back_insert_iterator< std::list< DeclarationWithType * > > out( outputList );
1026
1027        for ( const DeclarationNode * cur = firstNode; cur; cur = dynamic_cast< DeclarationNode * >( cur->get_next() ) ) {
1028                try {
1029                        Declaration * decl = cur->build();
1030                        assert( decl );
1031                        if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
1032                                dwt->location = cur->location;
1033                                *out++ = dwt;
1034                        } else if ( StructDecl * agg = dynamic_cast< StructDecl * >( decl ) ) {
1035                                // e.g., int foo(struct S) {}
1036                                StructInstType * inst = new StructInstType( Type::Qualifiers(), agg->name );
1037                                auto obj = new ObjectDecl( "", Type::StorageClasses(), linkage, nullptr, inst, nullptr );
1038                                obj->location = cur->location;
1039                                *out++ = obj;
1040                                delete agg;
1041                        } else if ( UnionDecl * agg = dynamic_cast< UnionDecl * >( decl ) ) {
1042                                // e.g., int foo(union U) {}
1043                                UnionInstType * inst = new UnionInstType( Type::Qualifiers(), agg->name );
1044                                auto obj = new ObjectDecl( "", Type::StorageClasses(), linkage, nullptr, inst, nullptr );
1045                                obj->location = cur->location;
1046                                *out++ = obj;
1047                        } else if ( EnumDecl * agg = dynamic_cast< EnumDecl * >( decl ) ) {
1048                                // e.g., int foo(enum E) {}
1049                                EnumInstType * inst = new EnumInstType( Type::Qualifiers(), agg->name );
1050                                auto obj = new ObjectDecl( "", Type::StorageClasses(), linkage, nullptr, inst, nullptr );
1051                                obj->location = cur->location;
1052                                *out++ = obj;
1053                        } // if
1054                } catch( SemanticErrorException & e ) {
1055                        errors.append( e );
1056                } // try
1057        } // for
1058
1059        if ( ! errors.isEmpty() ) {
1060                throw errors;
1061        } // if
1062} // buildList
1063
1064void buildTypeList( const DeclarationNode * firstNode, std::list< Type * > & outputList ) {
1065        SemanticErrorException errors;
1066        std::back_insert_iterator< std::list< Type * > > out( outputList );
1067        const DeclarationNode * cur = firstNode;
1068
1069        while ( cur ) {
1070                try {
1071                        * out++ = cur->buildType();
1072                } catch( SemanticErrorException & e ) {
1073                        errors.append( e );
1074                } // try
1075                cur = dynamic_cast< DeclarationNode * >( cur->get_next() );
1076        } // while
1077
1078        if ( ! errors.isEmpty() ) {
1079                throw errors;
1080        } // if
1081} // buildTypeList
1082
1083Declaration * DeclarationNode::build() const {
1084        if ( ! error.empty() ) SemanticError( this, error + " in declaration of " );
1085
1086        if ( asmStmt ) {
1087                return new AsmDecl( strict_dynamic_cast<AsmStmt *>( asmStmt->build() ) );
1088        } // if
1089        if ( directiveStmt ) {
1090                return new DirectiveDecl( strict_dynamic_cast<DirectiveStmt *>( directiveStmt->build() ) );
1091        } // if
1092
1093        if ( variable.tyClass != TypeDecl::NUMBER_OF_KINDS ) {
1094                // otype is internally converted to dtype + otype parameters
1095                static const TypeDecl::Kind kindMap[] = { TypeDecl::Dtype, TypeDecl::Dtype, TypeDecl::Dtype, TypeDecl::Ftype, TypeDecl::Ttype, TypeDecl::Dimension };
1096                static_assert( sizeof(kindMap) / sizeof(kindMap[0]) == TypeDecl::NUMBER_OF_KINDS, "DeclarationNode::build: kindMap is out of sync." );
1097                assertf( variable.tyClass < sizeof(kindMap)/sizeof(kindMap[0]), "Variable's tyClass is out of bounds." );
1098                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 );
1099                buildList( variable.assertions, ret->get_assertions() );
1100                return ret;
1101        } // if
1102
1103        if ( type ) {
1104                // Function specifiers can only appear on a function definition/declaration.
1105                //
1106                //    inline _Noreturn int f();                 // allowed
1107                //    inline _Noreturn int g( int i );  // allowed
1108                //    inline _Noreturn int i;                   // disallowed
1109                if ( type->kind != TypeData::Function && funcSpecs.any() ) {
1110                        SemanticError( this, "invalid function specifier for " );
1111                } // if
1112                // Forall qualifier can only appear on a function/aggregate definition/declaration.
1113                //
1114                //    forall int f();                                   // allowed
1115                //    forall int g( int i );                    // allowed
1116                //    forall int i;                                             // disallowed
1117                if ( type->kind != TypeData::Function && type->forall ) {
1118                        SemanticError( this, "invalid type qualifier for " );
1119                } // if
1120                bool isDelete = initializer && initializer->get_isDelete();
1121                Declaration * decl = buildDecl( type, name ? *name : string( "" ), storageClasses, maybeBuild< Expression >( bitfieldWidth ), funcSpecs, linkage, asmName, isDelete ? nullptr : maybeBuild< Initializer >(initializer), attributes )->set_extension( extension );
1122                if ( isDelete ) {
1123                        DeclarationWithType * dwt = strict_dynamic_cast<DeclarationWithType *>( decl );
1124                        dwt->isDeleted = true;
1125                }
1126                return decl;
1127        } // if
1128
1129        if ( assert.condition ) {
1130                return new StaticAssertDecl( maybeBuild< Expression >( assert.condition ), strict_dynamic_cast< ConstantExpr * >( maybeClone( assert.message ) ) );
1131        }
1132
1133        // SUE's cannot have function specifiers, either
1134        //
1135        //    inline _Noreturn struct S { ... };                // disallowed
1136        //    inline _Noreturn enum   E { ... };                // disallowed
1137        if ( funcSpecs.any() ) {
1138                SemanticError( this, "invalid function specifier for " );
1139        } // if
1140        assertf( name, "ObjectDecl must a have name\n" );
1141        return (new ObjectDecl( *name, storageClasses, linkage, maybeBuild< Expression >( bitfieldWidth ), nullptr, maybeBuild< Initializer >( initializer ) ))->set_asmName( asmName )->set_extension( extension );
1142}
1143
1144Type * DeclarationNode::buildType() const {
1145        assert( type );
1146
1147        if ( attr.expr ) {
1148                return new AttrType( buildQualifiers( type ), *name, attr.expr->build(), attributes );
1149        } else if ( attr.type ) {
1150                return new AttrType( buildQualifiers( type ), *name, attr.type->buildType(), attributes );
1151        } // if
1152
1153        switch ( type->kind ) {
1154          case TypeData::Enum:
1155          case TypeData::Aggregate: {
1156                  ReferenceToType * ret = buildComAggInst( type, attributes, linkage );
1157                  buildList( type->aggregate.actuals, ret->get_parameters() );
1158                  return ret;
1159          }
1160          case TypeData::Symbolic: {
1161                  TypeInstType * ret = new TypeInstType( buildQualifiers( type ), *type->symbolic.name, false, attributes );
1162                  buildList( type->symbolic.actuals, ret->get_parameters() );
1163                  return ret;
1164          }
1165          default:
1166                Type * simpletypes = typebuild( type );
1167                simpletypes->get_attributes() = attributes;             // copy because member is const
1168                return simpletypes;
1169        } // switch
1170}
1171
1172// Local Variables: //
1173// tab-width: 4 //
1174// mode: c++ //
1175// compile-command: "make install" //
1176// End: //
Note: See TracBrowser for help on using the repository browser.