source: src/Parser/DeclarationNode.cpp @ b0fcd0e

Last change on this file since b0fcd0e was d1fbc56e, checked in by Andrew Beach <ajbeach@…>, 6 weeks ago

Removed two lingering set_extension functions from ast. There was one use each in the parser, which uses get/set functions still.

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