source: src/Parser/DeclarationNode.cc @ d734fa1

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

Removed unused field from TypeData?.

  • 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        return newnode;
188} // DeclarationNode::newAggregate
189
190DeclarationNode * DeclarationNode::newEnum( const string * name, DeclarationNode * constants, bool body, bool typed, DeclarationNode * base, EnumHiding hiding ) {
191        DeclarationNode * newnode = new DeclarationNode;
192        newnode->type = new TypeData( TypeData::Enum );
193        newnode->type->enumeration.anon = name == nullptr;
194        newnode->type->enumeration.name = newnode->type->enumeration.anon ? new string( DeclarationNode::anonymous.newName() ) : name;
195        newnode->type->enumeration.constants = constants;
196        newnode->type->enumeration.body = body;
197        newnode->type->enumeration.typed = typed;
198        newnode->type->enumeration.hiding = hiding;
199        if ( base ) {
200                assert( typed );
201                assert( base->type );
202                newnode->type->base = base->type;
203                base->type = nullptr;
204                delete base;
205        } // if
206
207        return newnode;
208} // DeclarationNode::newEnum
209
210DeclarationNode * DeclarationNode::newName( const string * name ) {
211        DeclarationNode * newnode = new DeclarationNode;
212        assert( ! newnode->name );
213        newnode->name = name;
214        return newnode;
215} // DeclarationNode::newName
216
217DeclarationNode * DeclarationNode::newEnumConstant( const string * name, ExpressionNode * constant ) {
218        DeclarationNode * newnode = newName( name );
219        newnode->enumeratorValue.reset( constant );
220        return newnode;
221} // DeclarationNode::newEnumConstant
222
223DeclarationNode * DeclarationNode::newEnumValueGeneric( const string * name, InitializerNode * init ) {
224        if ( nullptr == init ) {
225                return newName( name );
226        } else if ( init->get_expression() ) {
227                return newEnumConstant( name, init->get_expression() );
228        } else {
229                DeclarationNode * newnode = newName( name );
230                newnode->initializer = init;
231                return newnode;
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
504// This code handles a special issue with the attribute transparent_union.
505//
506//    typedef union U { int i; } typedef_name __attribute__(( aligned(16) )) __attribute__(( transparent_union ))
507//
508// Here the attribute aligned goes with the typedef_name, so variables declared of this type are
509// aligned.  However, the attribute transparent_union must be moved from the typedef_name to
510// alias union U.  Currently, this is the only know attribute that must be moved from typedef to
511// alias.
512static void moveUnionAttribute( DeclarationNode * decl, DeclarationNode * unionDecl ) {
513        assert( decl->type->kind == TypeData::Symbolic );
514        assert( decl->type->symbolic.isTypedef );
515        assert( unionDecl->type->kind == TypeData::Aggregate );
516
517        if ( unionDecl->type->aggregate.kind != ast::AggregateDecl::Union ) return;
518
519        // Ignore the Aggregate_t::attributes. Why did we add that before the rework?
520        for ( auto attr = decl->attributes.begin() ; attr != decl->attributes.end() ; ) {
521                if ( (*attr)->name == "transparent_union" || (*attr)->name == "__transparent_union__" ) {
522                        unionDecl->attributes.emplace_back( attr->release() );
523                        attr = decl->attributes.erase( attr );
524                } else {
525                        ++attr;
526                }
527        }
528}
529
530// Helper for addTypedef, handles the case where the typedef wraps an
531// aggregate declaration (not a type), returns a chain of nodes.
532static DeclarationNode * addTypedefAggr(
533                DeclarationNode * olddecl, TypeData * newtype ) {
534        TypeData *& oldaggr = olddecl->type->aggInst.aggregate;
535
536        // Handle anonymous aggregates: typedef struct { int i; } foo
537        // Give the typedefed type a consistent name across translation units.
538        if ( oldaggr->aggregate.anon ) {
539                delete oldaggr->aggregate.name;
540                oldaggr->aggregate.name = new string( "__anonymous_" + *olddecl->name );
541                oldaggr->aggregate.anon = false;
542                oldaggr->qualifiers.reset();
543        }
544
545        // Replace the wrapped TypeData with a forward declaration.
546        TypeData * newaggr = new TypeData( TypeData::Aggregate );
547        newaggr->aggregate.kind = oldaggr->aggregate.kind;
548        newaggr->aggregate.name = oldaggr->aggregate.name ? new string( *oldaggr->aggregate.name ) : nullptr;
549        newaggr->aggregate.body = false;
550        newaggr->aggregate.anon = oldaggr->aggregate.anon;
551        swap( newaggr, oldaggr );
552
553        newtype->base = olddecl->type;
554        olddecl->type = newtype;
555        DeclarationNode * newdecl = new DeclarationNode;
556        newdecl->type = newaggr;
557        newdecl->next = olddecl;
558
559        moveUnionAttribute( olddecl, newdecl );
560
561        return newdecl;
562}
563
564// Helper for addTypedef, handles the case where the typedef wraps an
565// enumeration declaration (not a type), returns a chain of nodes.
566static DeclarationNode * addTypedefEnum(
567                DeclarationNode * olddecl, TypeData * newtype ) {
568        TypeData *& oldenum = olddecl->type->aggInst.aggregate;
569
570        // Handle anonymous enumeration: typedef enum { A, B, C } foo
571        // Give the typedefed type a consistent name across translation units.
572        if ( oldenum->enumeration.anon ) {
573                delete oldenum->enumeration.name;
574                oldenum->enumeration.name = new string( "__anonymous_" + *olddecl->name );
575                oldenum->enumeration.anon = false;
576                oldenum->qualifiers.reset();
577        }
578
579        // Replace the wrapped TypeData with a forward declaration.
580        TypeData * newenum = new TypeData( TypeData::Enum );
581        newenum->enumeration.name = oldenum->enumeration.name ? new string( *oldenum->enumeration.name ) : nullptr;
582        newenum->enumeration.body = false;
583        newenum->enumeration.anon = oldenum->enumeration.anon;
584        newenum->enumeration.typed = oldenum->enumeration.typed;
585        newenum->enumeration.hiding = oldenum->enumeration.hiding;
586        swap( newenum, oldenum );
587
588        newtype->base = olddecl->type;
589        olddecl->type = newtype;
590        DeclarationNode * newdecl = new DeclarationNode;
591        newdecl->type = newenum;
592        newdecl->next = olddecl;
593
594        return newdecl;
595}
596
597// Wrap the declaration in a typedef. It actually does that by modifying the
598// existing declaration, and may split it into two declarations.
599// This only happens if the wrapped type is actually a declaration of a SUE
600// type. If it does, the DeclarationNode for the SUE declaration is the node
601// returned, make sure later transformations are applied to the right node.
602DeclarationNode * DeclarationNode::addTypedef() {
603        TypeData * newtype = new TypeData( TypeData::Symbolic );
604        newtype->symbolic.params = nullptr;
605        newtype->symbolic.isTypedef = true;
606        newtype->symbolic.name = name ? new string( *name ) : nullptr;
607        // If this typedef is wrapping an aggregate, separate them out.
608        if ( TypeData::AggregateInst == type->kind
609                        && TypeData::Aggregate == type->aggInst.aggregate->kind
610                        && type->aggInst.aggregate->aggregate.body ) {
611                return addTypedefAggr( this, newtype );
612        // If this typedef is wrapping an enumeration, separate them out.
613        } else if ( TypeData::AggregateInst == type->kind
614                        && TypeData::Enum == type->aggInst.aggregate->kind
615                        && type->aggInst.aggregate->enumeration.body ) {
616                return addTypedefEnum( this, newtype );
617        // There is no internal declaration, just a type.
618        } else {
619                newtype->base = type;
620                type = newtype;
621                return this;
622        }
623}
624
625DeclarationNode * DeclarationNode::addAssertions( DeclarationNode * assertions ) {
626        if ( variable.tyClass != ast::TypeDecl::NUMBER_OF_KINDS ) {
627                if ( variable.assertions ) {
628                        variable.assertions->set_last( assertions );
629                } else {
630                        variable.assertions = assertions;
631                } // if
632                return this;
633        } // if
634
635        assert( type );
636        switch ( type->kind ) {
637        case TypeData::Symbolic:
638                if ( type->symbolic.assertions ) {
639                        type->symbolic.assertions->set_last( assertions );
640                } else {
641                        type->symbolic.assertions = assertions;
642                } // if
643                break;
644        default:
645                assert( false );
646        } // switch
647
648        return this;
649}
650
651DeclarationNode * DeclarationNode::addName( string * newname ) {
652        assert( ! name );
653        name = newname;
654        return this;
655}
656
657DeclarationNode * DeclarationNode::addAsmName( DeclarationNode * newname ) {
658        assert( ! asmName );
659        asmName = newname ? newname->asmName : nullptr;
660        return this->addQualifiers( newname );
661}
662
663DeclarationNode * DeclarationNode::addBitfield( ExpressionNode * size ) {
664        bitfieldWidth = size;
665        return this;
666}
667
668DeclarationNode * DeclarationNode::addVarArgs() {
669        assert( type );
670        hasEllipsis = true;
671        return this;
672}
673
674DeclarationNode * DeclarationNode::addFunctionBody( StatementNode * body, ExpressionNode * withExprs ) {
675        assert( type );
676        assert( type->kind == TypeData::Function );
677        assert( ! type->function.body );
678        type->function.body = body;
679        type->function.withExprs = withExprs;
680        return this;
681}
682
683DeclarationNode * DeclarationNode::addOldDeclList( DeclarationNode * list ) {
684        assert( type );
685        assert( type->kind == TypeData::Function );
686        assert( ! type->function.oldDeclList );
687        type->function.oldDeclList = list;
688        return this;
689}
690
691DeclarationNode * DeclarationNode::setBase( TypeData * newType ) {
692        if ( type ) {
693                type->setLastBase( newType );
694        } else {
695                type = newType;
696        } // if
697        return this;
698}
699
700DeclarationNode * DeclarationNode::copyAttribute( DeclarationNode * a ) {
701        if ( a ) {
702                spliceBegin( attributes, a->attributes );
703                a->attributes.clear();
704        } // if
705        return this;
706} // copyAttribute
707
708DeclarationNode * DeclarationNode::addPointer( DeclarationNode * p ) {
709        if ( p ) {
710                assert( p->type->kind == TypeData::Pointer || p->type->kind == TypeData::Reference );
711                setBase( p->type );
712                p->type = nullptr;
713                copyAttribute( p );
714                delete p;
715        } // if
716        return this;
717}
718
719DeclarationNode * DeclarationNode::addArray( DeclarationNode * a ) {
720        if ( a ) {
721                assert( a->type->kind == TypeData::Array );
722                setBase( a->type );
723                a->type = nullptr;
724                copyAttribute( a );
725                delete a;
726        } // if
727        return this;
728}
729
730DeclarationNode * DeclarationNode::addNewPointer( DeclarationNode * p ) {
731        if ( p ) {
732                assert( p->type->kind == TypeData::Pointer || p->type->kind == TypeData::Reference );
733                if ( type ) {
734                        p->type->base = makeNewBase( type );
735                        type = nullptr;
736                } // if
737                delete this;
738                return p;
739        } else {
740                return this;
741        } // if
742}
743
744DeclarationNode * DeclarationNode::addNewArray( DeclarationNode * a ) {
745        if ( ! a ) return this;
746        assert( a->type->kind == TypeData::Array );
747        if ( type ) {
748                a->type->setLastBase( makeNewBase( type ) );
749                type = nullptr;
750        } // if
751        delete this;
752        return a;
753}
754
755DeclarationNode * DeclarationNode::addParamList( DeclarationNode * params ) {
756        TypeData * ftype = new TypeData( TypeData::Function );
757        ftype->function.params = params;
758        setBase( ftype );
759        return this;
760}
761
762static TypeData * addIdListToType( TypeData * type, DeclarationNode * ids ) {
763        if ( type ) {
764                if ( type->kind != TypeData::Function ) {
765                        type->base = addIdListToType( type->base, ids );
766                } else {
767                        type->function.idList = ids;
768                } // if
769                return type;
770        } else {
771                TypeData * newtype = new TypeData( TypeData::Function );
772                newtype->function.idList = ids;
773                return newtype;
774        } // if
775} // addIdListToType
776
777DeclarationNode * DeclarationNode::addIdList( DeclarationNode * ids ) {
778        type = addIdListToType( type, ids );
779        return this;
780}
781
782DeclarationNode * DeclarationNode::addInitializer( InitializerNode * init ) {
783        initializer = init;
784        return this;
785}
786
787DeclarationNode * DeclarationNode::addTypeInitializer( DeclarationNode * init ) {
788        assertf( variable.tyClass != ast::TypeDecl::NUMBER_OF_KINDS, "Called addTypeInitializer on something that isn't a type variable." );
789        variable.initializer = init;
790        return this;
791}
792
793DeclarationNode * DeclarationNode::cloneType( string * name ) {
794        DeclarationNode * newnode = newName( name );
795        newnode->type = maybeCopy( type );
796        newnode->copySpecifiers( this );
797        return newnode;
798}
799
800DeclarationNode * DeclarationNode::cloneBaseType( DeclarationNode * o, bool copyattr ) {
801        if ( ! o ) return nullptr;
802        o->copySpecifiers( this, copyattr );
803        if ( type ) {
804                o->type = ::cloneBaseType( type, o->type );
805        } // if
806        return o;
807}
808
809DeclarationNode * DeclarationNode::extractAggregate() const {
810        if ( type ) {
811                TypeData * ret = typeextractAggregate( type );
812                if ( ret ) {
813                        DeclarationNode * newnode = new DeclarationNode;
814                        newnode->type = ret;
815                        if ( ret->kind == TypeData::Aggregate ) {
816                                newnode->attributes.swap( ret->aggregate.attributes );
817                        } // if
818                        return newnode;
819                } // if
820        } // if
821        return nullptr;
822}
823
824// Get the non-anonymous name of the instance type of the declaration,
825// if one exists.
826static const std::string * getInstTypeOfName( ast::Decl * decl ) {
827        if ( auto dwt = dynamic_cast<ast::DeclWithType *>( decl ) ) {
828                if ( auto aggr = dynamic_cast<ast::BaseInstType const *>( dwt->get_type() ) ) {
829                        if ( aggr->name.find("anonymous") == std::string::npos ) {
830                                return &aggr->name;
831                        }
832                }
833        }
834        return nullptr;
835}
836
837void buildList( DeclarationNode * firstNode, std::vector<ast::ptr<ast::Decl>> & outputList ) {
838        SemanticErrorException errors;
839        std::back_insert_iterator<std::vector<ast::ptr<ast::Decl>>> out( outputList );
840
841        for ( const DeclarationNode * cur = firstNode ; cur ; cur = cur->next ) {
842                try {
843                        bool extracted_named = false;
844
845                        if ( DeclarationNode * extr = cur->extractAggregate() ) {
846                                assert( cur->type );
847
848                                if ( ast::Decl * decl = extr->build() ) {
849                                        *out++ = decl;
850
851                                        // need to remember the cases where a declaration contains an anonymous aggregate definition
852                                        assert( extr->type );
853                                        if ( extr->type->kind == TypeData::Aggregate ) {
854                                                // typedef struct { int A } B is the only case?
855                                                extracted_named = ! extr->type->aggregate.anon;
856                                        } else if ( extr->type->kind == TypeData::Enum ) {
857                                                // typedef enum { A } B is the only case?
858                                                extracted_named = ! extr->type->enumeration.anon;
859                                        } else {
860                                                extracted_named = true;
861                                        }
862                                } // if
863                                delete extr;
864                        } // if
865
866                        if ( ast::Decl * decl = cur->build() ) {
867                                if ( "" == decl->name && !cur->get_inLine() ) {
868                                        // Don't include anonymous declaration for named aggregates,
869                                        // but do include them for anonymous aggregates, e.g.:
870                                        // struct S {
871                                        //   struct T { int x; }; // no anonymous member
872                                        //   struct { int y; };   // anonymous member
873                                        //   struct T;            // anonymous member
874                                        // };
875                                        if ( extracted_named ) {
876                                                continue;
877                                        }
878
879                                        if ( auto name = getInstTypeOfName( decl ) ) {
880                                                // Temporary: warn about anonymous member declarations of named types, since
881                                                // this conflicts with the syntax for the forward declaration of an anonymous type.
882                                                SemanticWarning( cur->location, Warning::AggrForwardDecl, name->c_str() );
883                                        }
884                                } // if
885                                *out++ = decl;
886                        } // if
887                } catch ( SemanticErrorException & e ) {
888                        errors.append( e );
889                } // try
890        } // for
891
892        if ( ! errors.isEmpty() ) {
893                throw errors;
894        } // if
895} // buildList
896
897// currently only builds assertions, function parameters, and return values
898void buildList( DeclarationNode * firstNode, std::vector<ast::ptr<ast::DeclWithType>> & outputList ) {
899        SemanticErrorException errors;
900        std::back_insert_iterator<std::vector<ast::ptr<ast::DeclWithType>>> out( outputList );
901
902        for ( const DeclarationNode * cur = firstNode; cur; cur = cur->next ) {
903                try {
904                        ast::Decl * decl = cur->build();
905                        assertf( decl, "buildList: build for ast::DeclWithType." );
906                        if ( ast::DeclWithType * dwt = dynamic_cast<ast::DeclWithType *>( decl ) ) {
907                                dwt->location = cur->location;
908                                *out++ = dwt;
909                        } else if ( ast::StructDecl * agg = dynamic_cast<ast::StructDecl *>( decl ) ) {
910                                // e.g., int foo(struct S) {}
911                                auto inst = new ast::StructInstType( agg->name );
912                                auto obj = new ast::ObjectDecl( cur->location, "", inst );
913                                obj->linkage = linkage;
914                                *out++ = obj;
915                                delete agg;
916                        } else if ( ast::UnionDecl * agg = dynamic_cast<ast::UnionDecl *>( decl ) ) {
917                                // e.g., int foo(union U) {}
918                                auto inst = new ast::UnionInstType( agg->name );
919                                auto obj = new ast::ObjectDecl( cur->location,
920                                        "", inst, nullptr, ast::Storage::Classes(),
921                                        linkage );
922                                *out++ = obj;
923                        } else if ( ast::EnumDecl * agg = dynamic_cast<ast::EnumDecl *>( decl ) ) {
924                                // e.g., int foo(enum E) {}
925                                auto inst = new ast::EnumInstType( agg->name );
926                                auto obj = new ast::ObjectDecl( cur->location,
927                                        "",
928                                        inst,
929                                        nullptr,
930                                        ast::Storage::Classes(),
931                                        linkage
932                                );
933                                *out++ = obj;
934                        } else {
935                                assertf( false, "buildList: Could not convert to ast::DeclWithType." );
936                        } // if
937                } catch ( SemanticErrorException & e ) {
938                        errors.append( e );
939                } // try
940        } // for
941
942        if ( ! errors.isEmpty() ) {
943                throw errors;
944        } // if
945} // buildList
946
947void buildTypeList( const DeclarationNode * firstNode,
948                std::vector<ast::ptr<ast::Type>> & outputList ) {
949        SemanticErrorException errors;
950        std::back_insert_iterator<std::vector<ast::ptr<ast::Type>>> out( outputList );
951
952        for ( const DeclarationNode * cur = firstNode ; cur ; cur = cur->next ) {
953                try {
954                        * out++ = cur->buildType();
955                } catch ( SemanticErrorException & e ) {
956                        errors.append( e );
957                } // try
958        } // for
959
960        if ( ! errors.isEmpty() ) {
961                throw errors;
962        } // if
963} // buildTypeList
964
965ast::Decl * DeclarationNode::build() const {
966        if ( ! error.empty() ) SemanticError( this, error + " in declaration of " );
967
968        if ( asmStmt ) {
969                auto stmt = strict_dynamic_cast<ast::AsmStmt *>( asmStmt->build() );
970                return new ast::AsmDecl( stmt->location, stmt );
971        } // if
972        if ( directiveStmt ) {
973                auto stmt = strict_dynamic_cast<ast::DirectiveStmt *>( directiveStmt->build() );
974                return new ast::DirectiveDecl( stmt->location, stmt );
975        } // if
976
977        if ( variable.tyClass != ast::TypeDecl::NUMBER_OF_KINDS ) {
978                // otype is internally converted to dtype + otype parameters
979                static const ast::TypeDecl::Kind kindMap[] = { ast::TypeDecl::Dtype, ast::TypeDecl::Dtype, ast::TypeDecl::Dtype, ast::TypeDecl::Ftype, ast::TypeDecl::Ttype, ast::TypeDecl::Dimension };
980                static_assert( sizeof(kindMap) / sizeof(kindMap[0]) == ast::TypeDecl::NUMBER_OF_KINDS, "DeclarationNode::build: kindMap is out of sync." );
981                assertf( variable.tyClass < sizeof(kindMap)/sizeof(kindMap[0]), "Variable's tyClass is out of bounds." );
982                ast::TypeDecl * ret = new ast::TypeDecl( location,
983                        *name,
984                        ast::Storage::Classes(),
985                        (ast::Type *)nullptr,
986                        kindMap[ variable.tyClass ],
987                        variable.tyClass == ast::TypeDecl::Otype || variable.tyClass == ast::TypeDecl::DStype,
988                        variable.initializer ? variable.initializer->buildType() : nullptr
989                );
990                buildList( variable.assertions, ret->assertions );
991                return ret;
992        } // if
993
994        if ( type ) {
995                // Function specifiers can only appear on a function definition/declaration.
996                //
997                //    inline _Noreturn int f();                 // allowed
998                //    inline _Noreturn int g( int i );  // allowed
999                //    inline _Noreturn int i;                   // disallowed
1000                if ( type->kind != TypeData::Function && funcSpecs.any() ) {
1001                        SemanticError( this, "invalid function specifier for " );
1002                } // if
1003                // Forall qualifier can only appear on a function/aggregate definition/declaration.
1004                //
1005                //    forall int f();                                   // allowed
1006                //    forall int g( int i );                    // allowed
1007                //    forall int i;                                             // disallowed
1008                if ( type->kind != TypeData::Function && type->forall ) {
1009                        SemanticError( this, "invalid type qualifier for " );
1010                } // if
1011                bool isDelete = initializer && initializer->get_isDelete();
1012                ast::Decl * decl = buildDecl(
1013                        type,
1014                        name ? *name : string( "" ),
1015                        storageClasses,
1016                        maybeBuild( bitfieldWidth ),
1017                        funcSpecs,
1018                        linkage,
1019                        asmName,
1020                        isDelete ? nullptr : maybeBuild( initializer ),
1021                        copy( attributes )
1022                )->set_extension( extension );
1023                if ( isDelete ) {
1024                        auto dwt = strict_dynamic_cast<ast::DeclWithType *>( decl );
1025                        dwt->isDeleted = true;
1026                }
1027                return decl;
1028        } // if
1029
1030        if ( assert.condition ) {
1031                auto cond = maybeBuild( assert.condition );
1032                auto msg = strict_dynamic_cast<ast::ConstantExpr *>( maybeCopy( assert.message ) );
1033                return new ast::StaticAssertDecl( location, cond, msg );
1034        }
1035
1036        // SUE's cannot have function specifiers, either
1037        //
1038        //    inline _Noreturn struct S { ... };                // disallowed
1039        //    inline _Noreturn enum   E { ... };                // disallowed
1040        if ( funcSpecs.any() ) {
1041                SemanticError( this, "invalid function specifier for " );
1042        } // if
1043        if ( enumInLine ) {
1044                return new ast::InlineMemberDecl( location,
1045                        *name, (ast::Type*)nullptr, storageClasses, linkage );
1046        } // if
1047        assertf( name, "ObjectDecl must a have name\n" );
1048        auto ret = new ast::ObjectDecl( location,
1049                *name,
1050                (ast::Type*)nullptr,
1051                maybeBuild( initializer ),
1052                storageClasses,
1053                linkage,
1054                maybeBuild( bitfieldWidth )
1055        );
1056        ret->asmName = asmName;
1057        ret->extension = extension;
1058        return ret;
1059}
1060
1061ast::Type * DeclarationNode::buildType() const {
1062        assert( type );
1063
1064        switch ( type->kind ) {
1065        case TypeData::Enum:
1066        case TypeData::Aggregate: {
1067                ast::BaseInstType * ret =
1068                        buildComAggInst( type, copy( attributes ), linkage );
1069                buildList( type->aggregate.actuals, ret->params );
1070                return ret;
1071        }
1072        case TypeData::Symbolic: {
1073                ast::TypeInstType * ret = new ast::TypeInstType(
1074                        *type->symbolic.name,
1075                        // This is just a default, the true value is not known yet.
1076                        ast::TypeDecl::Dtype,
1077                        buildQualifiers( type ),
1078                        copy( attributes ) );
1079                buildList( type->symbolic.actuals, ret->params );
1080                return ret;
1081        }
1082        default:
1083                ast::Type * simpletypes = typebuild( type );
1084                // copy because member is const
1085                simpletypes->attributes = attributes;
1086                return simpletypes;
1087        } // switch
1088}
1089
1090// Local Variables: //
1091// tab-width: 4 //
1092// mode: c++ //
1093// compile-command: "make install" //
1094// End: //
Note: See TracBrowser for help on using the repository browser.