source: src/Parser/DeclarationNode.cc @ 33807a1e

Last change on this file since 33807a1e was a3525c4, checked in by Andrew Beach <ajbeach@…>, 4 months ago

Some Parser clean-up I did while investigating.

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