source: src/Parser/DeclarationNode.cc @ 2d019af

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 2d019af was 2d019af, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

parser global pragmas, fixes #241

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