source: src/Parser/DeclarationNode.cc @ 5b25c49

Last change on this file since 5b25c49 was 057608a, checked in by Andrew Beach <ajbeach@…>, 4 months ago

Parser clean-up: Removed an unused field, added a comment, fixed a memory leak and reformated a function.

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