source: src/Parser/parser.yy @ 04bdc26

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resnenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since 04bdc26 was 0982a05, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

fix 0 and 1 for new for-control

  • Property mode set to 100644
File size: 132.1 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// parser.yy --
8//
9// Author           : Peter A. Buhr
10// Created On       : Sat Sep  1 20:22:55 2001
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Aug 30 17:02:25 2018
13// Update Count     : 4029
14//
15
16// This grammar is based on the ANSI99/11 C grammar, specifically parts of EXPRESSION and STATEMENTS, and on the C
17// grammar by James A. Roskind, specifically parts of DECLARATIONS and EXTERNAL DEFINITIONS.  While parts have been
18// copied, important changes have been made in all sections; these changes are sufficient to constitute a new grammar.
19// In particular, this grammar attempts to be more syntactically precise, i.e., it parses less incorrect language syntax
20// that must be subsequently rejected by semantic checks.  Nevertheless, there are still several semantic checks
21// required and many are noted in the grammar. Finally, the grammar is extended with GCC and CFA language extensions.
22
23// Acknowledgments to Richard Bilson, Glen Ditchfield, and Rodolfo Gabriel Esteves who all helped when I got stuck with
24// the grammar.
25
26// The root language for this grammar is ANSI99/11 C. All of ANSI99/11 is parsed, except for:
27//
28// 1. designation with '=' (use ':' instead)
29//
30// Most of the syntactic extensions from ANSI90 to ANSI11 C are marked with the comment "C99/C11". This grammar also has
31// two levels of extensions. The first extensions cover most of the GCC C extensions, except for:
32//
33// 1. designation with and without '=' (use ':' instead)
34// 2. attributes not allowed in parenthesis of declarator
35//
36// All of the syntactic extensions for GCC C are marked with the comment "GCC". The second extensions are for Cforall
37// (CFA), which fixes several of C's outstanding problems and extends C with many modern language concepts. All of the
38// syntactic extensions for CFA C are marked with the comment "CFA". As noted above, there is one unreconcileable
39// parsing problem between C99 and CFA with respect to designators; this is discussed in detail before the "designation"
40// grammar rule.
41
42%{
43#define YYDEBUG_LEXER_TEXT (yylval)                                             // lexer loads this up each time
44#define YYDEBUG 1                                                                               // get the pretty debugging code to compile
45#define YYERROR_VERBOSE                                                                 // more information in syntax errors
46
47#undef __GNUC_MINOR__
48
49#include <cstdio>
50#include <stack>
51using namespace std;
52
53#include "ParseNode.h"
54#include "TypedefTable.h"
55#include "TypeData.h"
56#include "LinkageSpec.h"
57#include "Common/SemanticError.h"                                               // error_str
58#include "Common/utility.h"                                                             // for maybeMoveBuild, maybeBuild, CodeLo...
59
60extern DeclarationNode * parseTree;
61extern LinkageSpec::Spec linkage;
62extern TypedefTable typedefTable;
63
64stack< LinkageSpec::Spec > linkageStack;
65
66bool appendStr( string & to, string & from ) {
67        // 1. Multiple strings are concatenated into a single string but not combined internally. The reason is that
68        //    "\x12" "3" is treated as 2 characters versus 1 because "escape sequences are converted into single members of
69        //    the execution character set just prior to adjacent string literal concatenation" (C11, Section 6.4.5-8). It is
70        //    easier to let the C compiler handle this case.
71        //
72        // 2. String encodings are transformed into canonical form (one encoding at start) so the encoding can be found
73        //    without searching the string, e.g.: "abc" L"def" L"ghi" => L"abc" "def" "ghi". Multiple encodings must match,
74        //    i.e., u"a" U"b" L"c" is disallowed.
75
76        if ( from[0] != '"' ) {                                                         // encoding ?
77                if ( to[0] != '"' ) {                                                   // encoding ?
78                        if ( to[0] != from[0] || to[1] != from[1] ) { // different encodings ?
79                                yyerror( "non-matching string encodings for string-literal concatenation" );
80                                return false;                                                   // parse error, must call YYERROR in action
81                        } else if ( from[1] == '8' ) {
82                                from.erase( 0, 1 );                                             // remove 2nd encoding
83                        } // if
84                } else {
85                        if ( from[1] == '8' ) {                                         // move encoding to start
86                                to = "u8" + to;
87                                from.erase( 0, 1 );                                             // remove 2nd encoding
88                        } else {
89                                to = from[0] + to;
90                        } // if
91                } // if
92                from.erase( 0, 1 );                                                             // remove 2nd encoding
93        } // if
94        to += " " + from;                                                                       // concatenated into single string
95        return true;
96} // appendStr
97
98DeclarationNode * distAttr( DeclarationNode * specifier, DeclarationNode * declList ) {
99        // distribute declaration_specifier across all declared variables, e.g., static, const, __attribute__.
100        DeclarationNode * cur = declList, * cl = (new DeclarationNode)->addType( specifier );
101        //cur->addType( specifier );
102        for ( cur = dynamic_cast< DeclarationNode * >( cur->get_next() ); cur != nullptr; cur = dynamic_cast< DeclarationNode * >( cur->get_next() ) ) {
103                cl->cloneBaseType( cur );
104        } // for
105        declList->addType( cl );
106//      delete cl;
107        return declList;
108} // distAttr
109
110void distExt( DeclarationNode * declaration ) {
111        // distribute EXTENSION across all declarations
112        for ( DeclarationNode *iter = declaration; iter != nullptr; iter = (DeclarationNode *)iter->get_next() ) {
113                iter->set_extension( true );
114        } // for
115} // distExt
116
117void distInl( DeclarationNode * declaration ) {
118        // distribute EXTENSION across all declarations
119        for ( DeclarationNode *iter = declaration; iter != nullptr; iter = (DeclarationNode *)iter->get_next() ) {
120                iter->set_inLine( true );
121        } // for
122} // distInl
123
124void distQual( DeclarationNode * declaration, DeclarationNode * qualifiers ) {
125        // distribute qualifiers across all non-variable declarations in a distribution statemement
126        for ( DeclarationNode * iter = declaration; iter != nullptr; iter = (DeclarationNode *)iter->get_next() ) {
127                // SKULLDUGGERY: Distributions are parsed inside out, so qualifiers are added to declarations inside out. Since
128                // addQualifiers appends to the back of the list, the forall clauses are in the wrong order (right to left). To
129                // get the qualifiers in the correct order and still use addQualifiers (otherwise, 90% of addQualifiers has to
130                // be copied to add to front), the appropriate forall pointers are interchanged before calling addQualifiers.
131                DeclarationNode * clone = qualifiers->clone();
132                if ( qualifiers->type ) {                                               // forall clause ? (handles SC)
133                        if ( iter->type->kind == TypeData::Aggregate ) { // struct/union ?
134                                swap( clone->type->forall, iter->type->aggregate.params );
135                                iter->addQualifiers( clone );
136                        } else if ( iter->type->kind == TypeData::AggregateInst && iter->type->aggInst.aggregate->aggregate.body ) { // struct/union ?
137                                // Create temporary node to hold aggregate, call addQualifiers as above, then put nodes back together.
138                                DeclarationNode newnode;
139                                swap( newnode.type, iter->type->aggInst.aggregate );
140                                swap( clone->type->forall, newnode.type->aggregate.params );
141                                newnode.addQualifiers( clone );
142                                swap( newnode.type, iter->type->aggInst.aggregate );
143                        } else if ( iter->type->kind == TypeData::Function ) { // routines ?
144                                swap( clone->type->forall, iter->type->forall );
145                                iter->addQualifiers( clone );
146                        } // if
147                } else {                                                                                // just SC qualifiers
148                        iter->addQualifiers( clone );
149                } // if
150        } // for
151        delete qualifiers;
152} // distQual
153
154// There is an ambiguity for inline generic-routine return-types and generic routines.
155//   forall( otype T ) struct S { int i; } bar( T ) {}
156// Does the forall bind to the struct or the routine, and how would it be possible to explicitly specify the binding.
157//   forall( otype T ) struct S { int T; } forall( otype W ) bar( W ) {}
158// Currently, the forall is associated with the routine, and the generic type has to be separately defined:
159//   forall( otype T ) struct S { int T; };
160//   forall( otype W ) bar( W ) {}
161
162void rebindForall( DeclarationNode * declSpec, DeclarationNode * funcDecl ) {
163        if ( declSpec->type->kind == TypeData::Aggregate ) { // ignore aggregate definition
164                funcDecl->type->forall = declSpec->type->aggregate.params; // move forall from aggregate to function type
165                declSpec->type->aggregate.params = nullptr;
166        } // if
167} // rebindForall
168
169NameExpr * build_postfix_name( const string * name ) {
170        NameExpr * new_name = build_varref( new string( "?`" + *name ) );
171        delete name;
172        return new_name;
173} // build_postfix_name
174
175DeclarationNode * fieldDecl( DeclarationNode * typeSpec, DeclarationNode * fieldList ) {
176        if ( ! fieldList ) {                                                            // field declarator ?
177                if ( ! ( typeSpec->type && typeSpec->type->kind == TypeData::Aggregate ) ) {
178                        stringstream ss;
179                        typeSpec->type->print( ss );
180                        SemanticWarning( yylloc, Warning::SuperfluousDecl, ss.str().c_str() );
181                        return nullptr;
182                } // if
183                fieldList = DeclarationNode::newName( nullptr );
184        } // if
185        return distAttr( typeSpec, fieldList );                         // mark all fields in list
186} // fieldDecl
187
188ExpressionNode *forInc( const OperKinds op ) {
189        return new ExpressionNode( build_constantInteger( *new string( op == OperKinds::LThan || op == OperKinds::LEThan ? "1" : "-1" ) ) );
190} // forInc
191
192ForCtrl * forCtrl( ExpressionNode * type, string * index, ExpressionNode * start, enum OperKinds compop, ExpressionNode * comp, ExpressionNode * inc ) {
193        ConstantExpr *constant = dynamic_cast<ConstantExpr *>(type->get_expr());
194        if ( constant && (constant->get_constant()->get_value() == "0" || constant->get_constant()->get_value() == "1") ) {
195        type = new ExpressionNode( new CastExpr( maybeMoveBuild< Expression >(type), new BasicType( Type::Qualifiers(), BasicType::SignedInt ) ) );
196        } // if
197        return new ForCtrl(
198                distAttr( DeclarationNode::newTypeof( type ), DeclarationNode::newName( index )->addInitializer( new InitializerNode( start ) ) ),
199                new ExpressionNode( build_binary_val( compop, new ExpressionNode( build_varref( new string( *index ) ) ), comp ) ),
200                new ExpressionNode( build_binary_val( OperKinds::PlusAssn, new ExpressionNode( build_varref( new string( *index ) ) ), inc ) ) );
201} // forCtrl
202
203
204bool forall = false, yyy = false;                                               // aggregate have one or more forall qualifiers ?
205
206// https://www.gnu.org/software/bison/manual/bison.html#Location-Type
207#define YYLLOC_DEFAULT(Cur, Rhs, N)                                                                                             \
208if ( N ) {                                                                                                                                              \
209        (Cur).first_line   = YYRHSLOC( Rhs, 1 ).first_line;                                                     \
210        (Cur).first_column = YYRHSLOC( Rhs, 1 ).first_column;                                           \
211        (Cur).last_line    = YYRHSLOC( Rhs, N ).last_line;                                                      \
212        (Cur).last_column  = YYRHSLOC( Rhs, N ).last_column;                                            \
213        (Cur).filename     = YYRHSLOC( Rhs, 1 ).filename;                                                       \
214} else {                                                                                                                                                \
215        (Cur).first_line   = (Cur).last_line = YYRHSLOC( Rhs, 0 ).last_line;            \
216        (Cur).first_column = (Cur).last_column = YYRHSLOC( Rhs, 0 ).last_column;        \
217        (Cur).filename     = YYRHSLOC( Rhs, 0 ).filename;                                                       \
218}
219%}
220
221%define parse.error verbose
222
223// Types declaration for productions
224%union {
225        Token tok;
226        ParseNode * pn;
227        ExpressionNode * en;
228        DeclarationNode * decl;
229        DeclarationNode::Aggregate aggKey;
230        DeclarationNode::TypeClass tclass;
231        StatementNode * sn;
232        WaitForStmt * wfs;
233        Expression * constant;
234        IfCtrl * ifctl;
235        ForCtrl * fctl;
236        enum OperKinds compop;
237        LabelNode * label;
238        InitializerNode * in;
239        OperKinds op;
240        std::string * str;
241        bool flag;
242        CatchStmt::Kind catch_kind;
243        GenericExpr * genexpr;
244}
245
246//************************* TERMINAL TOKENS ********************************
247
248// keywords
249%token TYPEDEF
250%token EXTERN STATIC AUTO REGISTER
251%token THREADLOCAL                                                                              // C11
252%token INLINE FORTRAN                                                                   // C99, extension ISO/IEC 9899:1999 Section J.5.9(1)
253%token NORETURN                                                                                 // C11
254%token CONST VOLATILE
255%token RESTRICT                                                                                 // C99
256%token ATOMIC                                                                                   // C11
257%token FORALL MUTEX VIRTUAL                                                             // CFA
258%token VOID CHAR SHORT INT LONG FLOAT DOUBLE SIGNED UNSIGNED
259%token BOOL COMPLEX IMAGINARY                                                   // C99
260%token INT128 FLOAT80 FLOAT128                                                  // GCC
261%token ZERO_T ONE_T                                                                             // CFA
262%token VALIST                                                                                   // GCC
263%token TYPEOF LABEL                                                                             // GCC
264%token ENUM STRUCT UNION
265%token EXCEPTION                                                                                // CFA
266%token COROUTINE MONITOR THREAD                                                 // CFA
267%token OTYPE FTYPE DTYPE TTYPE TRAIT                                    // CFA
268%token SIZEOF OFFSETOF
269%token ATTRIBUTE EXTENSION                                                              // GCC
270%token IF ELSE SWITCH CASE DEFAULT DO WHILE FOR BREAK CONTINUE GOTO RETURN
271%token CHOOSE DISABLE ENABLE FALLTHRU FALLTHROUGH TRY CATCH CATCHRESUME FINALLY THROW THROWRESUME AT WITH WHEN WAITFOR // CFA
272%token ASM                                                                                              // C99, extension ISO/IEC 9899:1999 Section J.5.10(1)
273%token ALIGNAS ALIGNOF GENERIC STATICASSERT                             // C11
274
275// names and constants: lexer differentiates between identifier and typedef names
276%token<tok> IDENTIFIER                  QUOTED_IDENTIFIER               TYPEDEFname                             TYPEGENname
277%token<tok> TIMEOUT                             WOR
278%token<tok> ATTR_IDENTIFIER             ATTR_TYPEDEFname                ATTR_TYPEGENname
279%token<tok> INTEGERconstant             CHARACTERconstant               STRINGliteral
280%token<tok> DIRECTIVE
281// Floating point constant is broken into three kinds of tokens because of the ambiguity with tuple indexing and
282// overloading constants 0/1, e.g., x.1 is lexed as (x)(.1), where (.1) is a factional constant, but is semantically
283// converted into the tuple index (.)(1). e.g., 3.x
284%token<tok>     FLOATING_DECIMALconstant        FLOATING_FRACTIONconstant       FLOATINGconstant
285
286// multi-character operators
287%token ARROW                                                                                    // ->
288%token ICR DECR                                                                                 // ++   --
289%token LS RS                                                                                    // <<   >>
290%token LE GE EQ NE                                                                              // <=   >=      ==      !=
291%token ANDAND OROR                                                                              // &&   ||
292%token ELLIPSIS                                                                                 // ...
293
294%token EXPassign        MULTassign      DIVassign       MODassign       // \=   *=      /=      %=
295%token PLUSassign       MINUSassign                                                     // +=   -=
296%token LSassign         RSassign                                                        // <<=  >>=
297%token ANDassign        ERassign        ORassign                                // &=   ^=      |=
298
299%token ErangeUpEq       ErangeDown      ErangeDownEq                    // ~=   -~      -~=
300%token ATassign                                                                                 // @=
301
302%type<tok> identifier  no_attr_identifier
303%type<tok> identifier_or_type_name  no_attr_identifier_or_type_name  attr_name
304%type<tok> quasi_keyword
305%type<constant> string_literal
306%type<str> string_literal_list
307
308// expressions
309%type<en> constant
310%type<en> tuple                                                 tuple_expression_list
311%type<op> ptrref_operator                               unary_operator                          assignment_operator
312%type<en> primary_expression                    postfix_expression                      unary_expression
313%type<en> cast_expression                               exponential_expression          multiplicative_expression       additive_expression
314%type<en> shift_expression                              relational_expression           equality_expression
315%type<en> AND_expression                                exclusive_OR_expression         inclusive_OR_expression
316%type<en> logical_AND_expression                logical_OR_expression
317%type<en> conditional_expression                constant_expression                     assignment_expression           assignment_expression_opt
318%type<en> comma_expression                              comma_expression_opt
319%type<en> argument_expression_list              argument_expression                     default_initialize_opt
320%type<ifctl> if_control_expression
321%type<fctl> for_control_expression
322%type<compop> inclexcl
323%type<en> subrange
324%type<decl> asm_name_opt
325%type<en> asm_operands_opt asm_operands_list asm_operand
326%type<label> label_list
327%type<en> asm_clobbers_list_opt
328%type<flag> asm_volatile_opt
329%type<en> handler_predicate_opt
330%type<genexpr> generic_association generic_assoc_list
331
332// statements
333%type<sn> statement                                             labeled_statement                       compound_statement
334%type<sn> statement_decl                                statement_decl_list                     statement_list_nodecl
335%type<sn> selection_statement                   if_statement
336%type<sn> switch_clause_list_opt                switch_clause_list
337%type<en> case_value
338%type<sn> case_clause                                   case_value_list                         case_label                                      case_label_list
339%type<sn> iteration_statement                   jump_statement
340%type<sn> expression_statement                  asm_statement
341%type<sn> with_statement
342%type<en> with_clause_opt
343%type<sn> exception_statement                   handler_clause                          finally_clause
344%type<catch_kind> handler_key
345%type<sn> mutex_statement
346%type<en> when_clause                                   when_clause_opt                         waitfor                                         timeout
347%type<sn> waitfor_statement
348%type<wfs> waitfor_clause
349
350// declarations
351%type<decl> abstract_declarator abstract_ptr abstract_array abstract_function array_dimension multi_array_dimension
352%type<decl> abstract_parameter_declarator abstract_parameter_ptr abstract_parameter_array abstract_parameter_function array_parameter_dimension array_parameter_1st_dimension
353%type<decl> abstract_parameter_declaration
354
355%type<aggKey> aggregate_key
356%type<decl> aggregate_type aggregate_type_nobody
357
358%type<decl> assertion assertion_list assertion_list_opt
359
360%type<en>   bit_subrange_size_opt bit_subrange_size
361
362%type<decl> basic_declaration_specifier basic_type_name basic_type_specifier direct_type indirect_type
363
364%type<decl> trait_declaration trait_declaration_list trait_declaring_list trait_specifier
365
366%type<decl> declaration declaration_list declaration_list_opt declaration_qualifier_list
367%type<decl> declaration_specifier declaration_specifier_nobody declarator declaring_list
368
369%type<decl> elaborated_type elaborated_type_nobody
370
371%type<decl> enumerator_list enum_type enum_type_nobody
372%type<en> enumerator_value_opt
373
374%type<decl> external_definition external_definition_list external_definition_list_opt
375
376%type<decl> exception_declaration
377
378%type<decl> field_declaration_list_opt field_declaration field_declaring_list_opt field_declarator field_abstract_list_opt field_abstract
379%type<en> field field_name_list field_name fraction_constants_opt
380
381%type<decl> external_function_definition function_definition function_array function_declarator function_no_ptr function_ptr
382
383%type<decl> identifier_parameter_declarator identifier_parameter_ptr identifier_parameter_array identifier_parameter_function
384%type<decl> identifier_list
385
386%type<decl> cfa_abstract_array cfa_abstract_declarator_no_tuple cfa_abstract_declarator_tuple
387%type<decl> cfa_abstract_function cfa_abstract_parameter_declaration cfa_abstract_parameter_list
388%type<decl> cfa_abstract_ptr cfa_abstract_tuple
389
390%type<decl> cfa_array_parameter_1st_dimension
391
392%type<decl> cfa_trait_declaring_list cfa_declaration cfa_field_declaring_list cfa_field_abstract_list
393%type<decl> cfa_function_declaration cfa_function_return cfa_function_specifier
394
395%type<decl> cfa_identifier_parameter_array cfa_identifier_parameter_declarator_no_tuple
396%type<decl> cfa_identifier_parameter_declarator_tuple cfa_identifier_parameter_ptr
397
398%type<decl> cfa_parameter_declaration cfa_parameter_list cfa_parameter_ellipsis_list_opt
399
400%type<decl> cfa_typedef_declaration cfa_variable_declaration cfa_variable_specifier
401
402%type<decl> c_declaration static_assert
403%type<decl> KR_function_declarator KR_function_no_ptr KR_function_ptr KR_function_array
404%type<decl> KR_parameter_list KR_parameter_list_opt
405
406%type<decl> parameter_declaration parameter_list parameter_type_list_opt
407
408%type<decl> paren_identifier paren_type
409
410%type<decl> storage_class storage_class_list
411
412%type<decl> sue_declaration_specifier sue_declaration_specifier_nobody sue_type_specifier sue_type_specifier_nobody
413
414%type<tclass> type_class
415%type<decl> type_declarator type_declarator_name type_declaring_list
416
417%type<decl> type_declaration_specifier type_type_specifier type_name typegen_name
418%type<decl> typedef typedef_declaration typedef_expression
419
420%type<decl> variable_type_redeclarator type_ptr type_array type_function
421
422%type<decl> type_parameter_redeclarator type_parameter_ptr type_parameter_array type_parameter_function
423
424%type<decl> type type_no_function
425%type<decl> type_parameter type_parameter_list type_initializer_opt
426
427%type<en> type_parameters_opt type_list
428
429%type<decl> type_qualifier type_qualifier_name forall type_qualifier_list_opt type_qualifier_list
430%type<decl> type_specifier type_specifier_nobody
431
432%type<decl> variable_declarator variable_ptr variable_array variable_function
433%type<decl> variable_abstract_declarator variable_abstract_ptr variable_abstract_array variable_abstract_function
434
435%type<decl> attribute_list_opt attribute_list attribute_name_list attribute attribute_name
436
437// initializers
438%type<in>  initializer initializer_list_opt initializer_opt
439
440// designators
441%type<en>  designator designator_list designation
442
443
444// Handle shift/reduce conflict for dangling else by shifting the ELSE token. For example, this string is ambiguous:
445//   .---------.                                matches IF '(' comma_expression ')' statement . (reduce)
446//   if ( C ) S1 else S2
447//   `-----------------'                matches IF '(' comma_expression ')' statement . (shift) ELSE statement */
448// Similar issues exit with the waitfor statement.
449
450// Order of these lines matters (low-to-high precedence). THEN is left associative over WOR/TIMEOUT/ELSE, WOR is left
451// associative over TIMEOUT/ELSE, and TIMEOUT is left associative over ELSE.
452%precedence THEN        // rule precedence for IF/WAITFOR statement
453%precedence WOR         // token precedence for start of WOR in WAITFOR statement
454%precedence TIMEOUT     // token precedence for start of TIMEOUT in WAITFOR statement
455%precedence ELSE        // token precedence for start of else clause in IF/WAITFOR statement
456
457// Handle shift/reduce conflict for generic type by shifting the '(' token. For example, this string is ambiguous:
458//   forall( otype T ) struct Foo { T v; };
459//       .-----.                                matches pointer to function returning a generic (which is impossible without a type)
460//   Foo ( *fp )( int );
461//   `---'                                              matches start of TYPEGENname '('
462// must be:
463//   Foo( int ) ( *fp )( int );
464// The same problem occurs here:
465//   forall( otype T ) struct Foo { T v; } ( *fp )( int );
466// must be:
467//   forall( otype T ) struct Foo { T v; } ( int ) ( *fp )( int );
468
469// Order of these lines matters (low-to-high precedence).
470%precedence TYPEGENname
471%precedence '}'
472%precedence '('
473
474%locations                                                                                              // support location tracking for error messages
475
476%start translation_unit                                                                 // parse-tree root
477
478%%
479//************************* Namespace Management ********************************
480
481// The C grammar is not context free because it relies on the distinct terminal symbols "identifier" and "TYPEDEFname",
482// which are lexically identical.
483//
484//   typedef int foo; // identifier foo must now be scanned as TYPEDEFname
485//   foo f;           // to allow it to appear in this context
486//
487// While it may be possible to write a purely context-free grammar, such a grammar would obscure the relationship
488// between syntactic and semantic constructs.  Cforall compounds this problem by introducing type names local to the
489// scope of a declaration (for instance, those introduced through "forall" qualifiers), and by introducing "type
490// generators" -- parameterized types.  This latter type name creates a third class of identifiers, "TYPEGENname", which
491// must be distinguished by the lexical scanner.
492//
493// Since the scanner cannot distinguish among the different classes of identifiers without some context information,
494// there is a type table (typedefTable), which holds type names and identifiers that override type names, for each named
495// scope. During parsing, semantic actions update the type table by adding new identifiers in the current scope. For
496// each context that introduces a name scope, a new level is created in the type table and that level is popped on
497// exiting the scope.  Since type names can be local to a particular declaration, each declaration is itself a scope.
498// This requires distinguishing between type names that are local to the current declaration scope and those that
499// persist past the end of the declaration (i.e., names defined in "typedef" or "otype" declarations).
500//
501// The non-terminals "push" and "pop" denote the opening and closing of named scopes. Every push has a matching pop in
502// the production rule. There are multiple lists of declarations, where each declaration is a named scope, so pop/push
503// around the list separator.
504//
505//  int f( forall(T) T (*f1) T , forall( S ) S (*f2)( S ) );
506//      push               pop   push                   pop
507
508push:
509                { typedefTable.enterScope(); }
510        ;
511
512pop:
513                { typedefTable.leaveScope(); }
514        ;
515
516//************************* CONSTANTS ********************************
517
518constant:
519                // ENUMERATIONconstant is not included here; it is treated as a variable with type "enumeration constant".
520        INTEGERconstant                                                         { $$ = new ExpressionNode( build_constantInteger( *$1 ) ); }
521        | FLOATING_DECIMALconstant                                      { $$ = new ExpressionNode( build_constantFloat( *$1 ) ); }
522        | FLOATING_FRACTIONconstant                                     { $$ = new ExpressionNode( build_constantFloat( *$1 ) ); }
523        | FLOATINGconstant                                                      { $$ = new ExpressionNode( build_constantFloat( *$1 ) ); }
524        | CHARACTERconstant                                                     { $$ = new ExpressionNode( build_constantChar( *$1 ) ); }
525        ;
526
527quasi_keyword:                                                                                  // CFA
528        TIMEOUT
529        | WOR
530        ;
531
532no_attr_identifier:
533        IDENTIFIER
534        | quasi_keyword
535        | '@'                                                                                           // CFA
536                { Token tok = { new string( DeclarationNode::anonymous.newName() ), yylval.tok.loc }; $$ = tok; }
537        ;
538
539identifier:
540        no_attr_identifier
541        | ATTR_IDENTIFIER                                                                       // CFA
542        ;
543
544string_literal:
545        string_literal_list                                                     { $$ = build_constantStr( *$1 ); }
546        ;
547
548string_literal_list:                                                                    // juxtaposed strings are concatenated
549        STRINGliteral                                                           { $$ = $1; } // conversion from tok to str
550        | string_literal_list STRINGliteral
551                {
552                        if ( ! appendStr( *$1, *$2 ) ) YYERROR;         // append 2nd juxtaposed string to 1st
553                        delete $2;                                                                      // allocated by lexer
554                        $$ = $1;                                                                        // conversion from tok to str
555                }
556        ;
557
558//************************* EXPRESSIONS ********************************
559
560primary_expression:
561        IDENTIFIER                                                                                      // typedef name cannot be used as a variable name
562                { $$ = new ExpressionNode( build_varref( $1 ) ); }
563        | quasi_keyword
564                { $$ = new ExpressionNode( build_varref( $1 ) ); }
565        | tuple
566        | '(' comma_expression ')'
567                { $$ = $2; }
568        | '(' compound_statement ')'                                            // GCC, lambda expression
569                { $$ = new ExpressionNode( new StmtExpr( dynamic_cast< CompoundStmt * >(maybeMoveBuild< Statement >($2) ) ) ); }
570        | constant '`' IDENTIFIER                                                       // CFA, postfix call
571                { $$ = new ExpressionNode( build_func( new ExpressionNode( build_postfix_name( $3 ) ), $1 ) ); }
572        | string_literal '`' IDENTIFIER                                         // CFA, postfix call
573                { $$ = new ExpressionNode( build_func( new ExpressionNode( build_postfix_name( $3 ) ), new ExpressionNode( $1 ) ) ); }
574        | IDENTIFIER '`' IDENTIFIER                                                     // CFA, postfix call
575                { $$ = new ExpressionNode( build_func( new ExpressionNode( build_postfix_name( $3 ) ), new ExpressionNode( build_varref( $1 ) ) ) ); }
576        | tuple '`' IDENTIFIER                                                          // CFA, postfix call
577                { $$ = new ExpressionNode( build_func( new ExpressionNode( build_postfix_name( $3 ) ), $1 ) ); }
578        | '(' comma_expression ')' '`' IDENTIFIER                       // CFA, postfix call
579                { $$ = new ExpressionNode( build_func( new ExpressionNode( build_postfix_name( $5 ) ), $2 ) ); }
580        | type_name '.' no_attr_identifier                                      // CFA, nested type
581                { SemanticError( yylloc, "Qualified name is currently unimplemented." ); $$ = nullptr; }
582        | type_name '.' '[' field_name_list ']'                         // CFA, nested type / tuple field selector
583                { SemanticError( yylloc, "Qualified name is currently unimplemented." ); $$ = nullptr; }
584        | GENERIC '(' assignment_expression ',' generic_assoc_list ')' // C11
585                {
586                        // add the missing control expression to the GenericExpr and return it
587                        $5->control = maybeMoveBuild<Expression>( $3 );
588                        $$ = new ExpressionNode( $5 );
589                }
590        ;
591
592generic_assoc_list:                                                                             // C11
593        generic_association
594        | generic_assoc_list ',' generic_association
595                {
596                        // steal the association node from the singleton and delete the wrapper
597                        $1->associations.splice($1->associations.end(), $3->associations);
598                        delete $3;
599                        $$ = $1;
600                }
601        ;
602
603generic_association:                                                                    // C11
604        type_no_function ':' assignment_expression
605                {
606                        // create a GenericExpr wrapper with one association pair
607                        $$ = new GenericExpr( nullptr, { { maybeMoveBuildType($1), maybeMoveBuild<Expression>($3) } } );
608                }
609        | DEFAULT ':' assignment_expression
610                { $$ = new GenericExpr( nullptr, { { maybeMoveBuild<Expression>($3) } } ); }
611        ;
612
613postfix_expression:
614        primary_expression
615        | postfix_expression '[' assignment_expression ']'
616                // CFA, comma_expression disallowed in this context because it results in a common user error: subscripting a
617                // matrix with x[i,j] instead of x[i][j]. While this change is not backwards compatible, there seems to be
618                // little advantage to this feature and many disadvantages. It is possible to write x[(i,j)] in CFA, which is
619                // equivalent to the old x[i,j].
620                { $$ = new ExpressionNode( build_binary_val( OperKinds::Index, $1, $3 ) ); }
621        | postfix_expression '{' argument_expression_list '}' // CFA, constructor call
622                {
623                        Token fn;
624                        fn.str = new std::string( "?{}" );                      // location undefined - use location of '{'?
625                        $$ = new ExpressionNode( new ConstructorExpr( build_func( new ExpressionNode( build_varref( fn ) ), (ExpressionNode *)( $1 )->set_last( $3 ) ) ) );
626                }
627        | postfix_expression '(' argument_expression_list ')'
628                { $$ = new ExpressionNode( build_func( $1, $3 ) ); }
629        | postfix_expression '.' no_attr_identifier
630                { $$ = new ExpressionNode( build_fieldSel( $1, build_varref( $3 ) ) ); }
631        | postfix_expression '.' INTEGERconstant                        // CFA, tuple index
632                { $$ = new ExpressionNode( build_fieldSel( $1, build_constantInteger( *$3 ) ) ); }
633        | postfix_expression FLOATING_FRACTIONconstant          // CFA, tuple index
634                { $$ = new ExpressionNode( build_fieldSel( $1, build_field_name_FLOATING_FRACTIONconstant( *$2 ) ) ); }
635        | postfix_expression '.' '[' field_name_list ']'        // CFA, tuple field selector
636                { $$ = new ExpressionNode( build_fieldSel( $1, build_tuple( $4 ) ) ); }
637        | postfix_expression ARROW no_attr_identifier
638                {
639                        $$ = new ExpressionNode( build_pfieldSel( $1, *$3 == "0" || *$3 == "1" ? build_constantInteger( *$3 ) : build_varref( $3 ) ) );
640                }
641        | postfix_expression ARROW INTEGERconstant                      // CFA, tuple index
642                { $$ = new ExpressionNode( build_pfieldSel( $1, build_constantInteger( *$3 ) ) ); }
643        | postfix_expression ARROW '[' field_name_list ']'      // CFA, tuple field selector
644                { $$ = new ExpressionNode( build_pfieldSel( $1, build_tuple( $4 ) ) ); }
645        | postfix_expression ICR
646                { $$ = new ExpressionNode( build_unary_ptr( OperKinds::IncrPost, $1 ) ); }
647        | postfix_expression DECR
648                { $$ = new ExpressionNode( build_unary_ptr( OperKinds::DecrPost, $1 ) ); }
649        | '(' type_no_function ')' '{' initializer_list_opt comma_opt '}' // C99, compound-literal
650                { $$ = new ExpressionNode( build_compoundLiteral( $2, new InitializerNode( $5, true ) ) ); }
651        | '(' type_no_function ')' '@' '{' initializer_list_opt comma_opt '}' // CFA, explicit C compound-literal
652                { $$ = new ExpressionNode( build_compoundLiteral( $2, (new InitializerNode( $6, true ))->set_maybeConstructed( false ) ) ); }
653        | '^' primary_expression '{' argument_expression_list '}' // CFA
654                {
655                        Token fn;
656                        fn.str = new string( "^?{}" );                          // location undefined
657                        $$ = new ExpressionNode( build_func( new ExpressionNode( build_varref( fn ) ), (ExpressionNode *)( $2 )->set_last( $4 ) ) );
658                }
659        ;
660
661argument_expression_list:
662        argument_expression
663        | argument_expression_list ',' argument_expression
664                { $$ = (ExpressionNode *)( $1->set_last( $3 )); }
665        ;
666
667argument_expression:
668        // empty
669                { $$ = nullptr; }
670        | '?'                                                                                           // CFA, default parameter
671                { SemanticError( yylloc, "Default parameter for argument is currently unimplemented." ); $$ = nullptr; }
672                // { $$ = new ExpressionNode( build_constantInteger( *new string( "2" ) ) ); }
673        | assignment_expression
674        ;
675
676field_name_list:                                                                                // CFA, tuple field selector
677        field
678        | field_name_list ',' field                                     { $$ = (ExpressionNode *)$1->set_last( $3 ); }
679        ;
680
681field:                                                                                                  // CFA, tuple field selector
682        field_name
683        | FLOATING_DECIMALconstant field
684                { $$ = new ExpressionNode( build_fieldSel( new ExpressionNode( build_field_name_FLOATING_DECIMALconstant( *$1 ) ), maybeMoveBuild<Expression>( $2 ) ) ); }
685        | FLOATING_DECIMALconstant '[' field_name_list ']'
686                { $$ = new ExpressionNode( build_fieldSel( new ExpressionNode( build_field_name_FLOATING_DECIMALconstant( *$1 ) ), build_tuple( $3 ) ) ); }
687        | field_name '.' field
688                { $$ = new ExpressionNode( build_fieldSel( $1, maybeMoveBuild<Expression>( $3 ) ) ); }
689        | field_name '.' '[' field_name_list ']'
690                { $$ = new ExpressionNode( build_fieldSel( $1, build_tuple( $4 ) ) ); }
691        | field_name ARROW field
692                { $$ = new ExpressionNode( build_pfieldSel( $1, maybeMoveBuild<Expression>( $3 ) ) ); }
693        | field_name ARROW '[' field_name_list ']'
694                { $$ = new ExpressionNode( build_pfieldSel( $1, build_tuple( $4 ) ) ); }
695        ;
696
697field_name:
698        INTEGERconstant fraction_constants_opt
699                { $$ = new ExpressionNode( build_field_name_fraction_constants( build_constantInteger( *$1 ), $2 ) ); }
700        | FLOATINGconstant fraction_constants_opt
701                { $$ = new ExpressionNode( build_field_name_fraction_constants( build_field_name_FLOATINGconstant( *$1 ), $2 ) ); }
702        | no_attr_identifier fraction_constants_opt
703                {
704                        $$ = new ExpressionNode( build_field_name_fraction_constants( build_varref( $1 ), $2 ) );
705                }
706        ;
707
708fraction_constants_opt:
709        // empty
710                { $$ = nullptr; }
711        | fraction_constants_opt FLOATING_FRACTIONconstant
712                {
713                        Expression * constant = build_field_name_FLOATING_FRACTIONconstant( *$2 );
714                        $$ = $1 != nullptr ? new ExpressionNode( build_fieldSel( $1,  constant ) ) : new ExpressionNode( constant );
715                }
716        ;
717
718unary_expression:
719        postfix_expression
720                // first location where constant/string can have operator applied: sizeof 3/sizeof "abc" still requires
721                // semantics checks, e.g., ++3, 3--, *3, &&3
722        | constant
723        | string_literal
724                { $$ = new ExpressionNode( $1 ); }
725        | EXTENSION cast_expression                                                     // GCC
726                { $$ = $2->set_extension( true ); }
727                // '*' ('&') is separated from unary_operator because of shift/reduce conflict in:
728                //              { * X; }         // dereference X
729                //              { * int X; } // CFA declaration of pointer to int
730        | ptrref_operator cast_expression                                       // CFA
731                {
732                        switch ( $1 ) {
733                          case OperKinds::AddressOf:
734                                $$ = new ExpressionNode( new AddressExpr( maybeMoveBuild< Expression >( $2 ) ) );
735                                break;
736                          case OperKinds::PointTo:
737                                $$ = new ExpressionNode( build_unary_val( $1, $2 ) );
738                                break;
739                          case OperKinds::And:
740                                $$ = new ExpressionNode( new AddressExpr( new AddressExpr( maybeMoveBuild< Expression >( $2 ) ) ) );
741                                break;
742                          default:
743                                assert( false );
744                        }
745                }
746        | unary_operator cast_expression
747                { $$ = new ExpressionNode( build_unary_val( $1, $2 ) ); }
748        | ICR unary_expression
749                { $$ = new ExpressionNode( build_unary_ptr( OperKinds::Incr, $2 ) ); }
750        | DECR unary_expression
751                { $$ = new ExpressionNode( build_unary_ptr( OperKinds::Decr, $2 ) ); }
752        | SIZEOF unary_expression
753                { $$ = new ExpressionNode( new SizeofExpr( maybeMoveBuild< Expression >( $2 ) ) ); }
754        | SIZEOF '(' type_no_function ')'
755                { $$ = new ExpressionNode( new SizeofExpr( maybeMoveBuildType( $3 ) ) ); }
756        | ALIGNOF unary_expression                                                      // GCC, variable alignment
757                { $$ = new ExpressionNode( new AlignofExpr( maybeMoveBuild< Expression >( $2 ) ) ); }
758        | ALIGNOF '(' type_no_function ')'                                      // GCC, type alignment
759                { $$ = new ExpressionNode( new AlignofExpr( maybeMoveBuildType( $3 ) ) ); }
760        | OFFSETOF '(' type_no_function ',' no_attr_identifier ')'
761                { $$ = new ExpressionNode( build_offsetOf( $3, build_varref( $5 ) ) ); }
762        | ATTR_IDENTIFIER
763                { $$ = new ExpressionNode( new AttrExpr( build_varref( $1 ), maybeMoveBuild< Expression >( (ExpressionNode *)nullptr ) ) ); }
764        | ATTR_IDENTIFIER '(' argument_expression ')'
765                { $$ = new ExpressionNode( new AttrExpr( build_varref( $1 ), maybeMoveBuild< Expression >( $3 ) ) ); }
766        | ATTR_IDENTIFIER '(' type ')'
767                { $$ = new ExpressionNode( new AttrExpr( build_varref( $1 ), maybeMoveBuildType( $3 ) ) ); }
768        ;
769
770ptrref_operator:
771        '*'                                                                                     { $$ = OperKinds::PointTo; }
772        | '&'                                                                           { $$ = OperKinds::AddressOf; }
773                // GCC, address of label must be handled by semantic check for ref,ref,label
774        | ANDAND                                                                        { $$ = OperKinds::And; }
775        ;
776
777unary_operator:
778        '+'                                                                                     { $$ = OperKinds::UnPlus; }
779        | '-'                                                                           { $$ = OperKinds::UnMinus; }
780        | '!'                                                                           { $$ = OperKinds::Neg; }
781        | '~'                                                                           { $$ = OperKinds::BitNeg; }
782        ;
783
784cast_expression:
785        unary_expression
786        | '(' type_no_function ')' cast_expression
787                { $$ = new ExpressionNode( build_cast( $2, $4 ) ); }
788        | '(' COROUTINE '&' ')' cast_expression                         // CFA
789                { $$ = new ExpressionNode( build_keyword_cast( KeywordCastExpr::Coroutine, $5 ) ); }
790        | '(' THREAD '&' ')' cast_expression                            // CFA
791                { $$ = new ExpressionNode( build_keyword_cast( KeywordCastExpr::Thread, $5 ) ); }
792        | '(' MONITOR '&' ')' cast_expression                           // CFA
793                { $$ = new ExpressionNode( build_keyword_cast( KeywordCastExpr::Monitor, $5 ) ); }
794                // VIRTUAL cannot be opt because of look ahead issues
795        | '(' VIRTUAL ')' cast_expression                                       // CFA
796                { $$ = new ExpressionNode( new VirtualCastExpr( maybeMoveBuild< Expression >( $4 ), maybeMoveBuildType( nullptr ) ) ); }
797        | '(' VIRTUAL type_no_function ')' cast_expression      // CFA
798                { $$ = new ExpressionNode( new VirtualCastExpr( maybeMoveBuild< Expression >( $5 ), maybeMoveBuildType( $3 ) ) ); }
799//      | '(' type_no_function ')' tuple
800//              { $$ = new ExpressionNode( build_cast( $2, $4 ) ); }
801        ;
802
803exponential_expression:
804        cast_expression
805        | exponential_expression '\\' cast_expression
806                { $$ = new ExpressionNode( build_binary_val( OperKinds::Exp, $1, $3 ) ); }
807        ;
808
809multiplicative_expression:
810        exponential_expression
811        | multiplicative_expression '*' exponential_expression
812                { $$ = new ExpressionNode( build_binary_val( OperKinds::Mul, $1, $3 ) ); }
813        | multiplicative_expression '/' exponential_expression
814                { $$ = new ExpressionNode( build_binary_val( OperKinds::Div, $1, $3 ) ); }
815        | multiplicative_expression '%' exponential_expression
816                { $$ = new ExpressionNode( build_binary_val( OperKinds::Mod, $1, $3 ) ); }
817        ;
818
819additive_expression:
820        multiplicative_expression
821        | additive_expression '+' multiplicative_expression
822                { $$ = new ExpressionNode( build_binary_val( OperKinds::Plus, $1, $3 ) ); }
823        | additive_expression '-' multiplicative_expression
824                { $$ = new ExpressionNode( build_binary_val( OperKinds::Minus, $1, $3 ) ); }
825        ;
826
827shift_expression:
828        additive_expression
829        | shift_expression LS additive_expression
830                { $$ = new ExpressionNode( build_binary_val( OperKinds::LShift, $1, $3 ) ); }
831        | shift_expression RS additive_expression
832                { $$ = new ExpressionNode( build_binary_val( OperKinds::RShift, $1, $3 ) ); }
833        ;
834
835relational_expression:
836        shift_expression
837        | relational_expression '<' shift_expression
838                { $$ = new ExpressionNode( build_binary_val( OperKinds::LThan, $1, $3 ) ); }
839        | relational_expression '>' shift_expression
840                { $$ = new ExpressionNode( build_binary_val( OperKinds::GThan, $1, $3 ) ); }
841        | relational_expression LE shift_expression
842                { $$ = new ExpressionNode( build_binary_val( OperKinds::LEThan, $1, $3 ) ); }
843        | relational_expression GE shift_expression
844                { $$ = new ExpressionNode( build_binary_val( OperKinds::GEThan, $1, $3 ) ); }
845        ;
846
847equality_expression:
848        relational_expression
849        | equality_expression EQ relational_expression
850                { $$ = new ExpressionNode( build_binary_val( OperKinds::Eq, $1, $3 ) ); }
851        | equality_expression NE relational_expression
852                { $$ = new ExpressionNode( build_binary_val( OperKinds::Neq, $1, $3 ) ); }
853        ;
854
855AND_expression:
856        equality_expression
857        | AND_expression '&' equality_expression
858                { $$ = new ExpressionNode( build_binary_val( OperKinds::BitAnd, $1, $3 ) ); }
859        ;
860
861exclusive_OR_expression:
862        AND_expression
863        | exclusive_OR_expression '^' AND_expression
864                { $$ = new ExpressionNode( build_binary_val( OperKinds::Xor, $1, $3 ) ); }
865        ;
866
867inclusive_OR_expression:
868        exclusive_OR_expression
869        | inclusive_OR_expression '|' exclusive_OR_expression
870                { $$ = new ExpressionNode( build_binary_val( OperKinds::BitOr, $1, $3 ) ); }
871        ;
872
873logical_AND_expression:
874        inclusive_OR_expression
875        | logical_AND_expression ANDAND inclusive_OR_expression
876                { $$ = new ExpressionNode( build_and_or( $1, $3, true ) ); }
877        ;
878
879logical_OR_expression:
880        logical_AND_expression
881        | logical_OR_expression OROR logical_AND_expression
882                { $$ = new ExpressionNode( build_and_or( $1, $3, false ) ); }
883        ;
884
885conditional_expression:
886        logical_OR_expression
887        | logical_OR_expression '?' comma_expression ':' conditional_expression
888                { $$ = new ExpressionNode( build_cond( $1, $3, $5 ) ); }
889                // FIX ME: computes $1 twice
890        | logical_OR_expression '?' /* empty */ ':' conditional_expression // GCC, omitted first operand
891                { $$ = new ExpressionNode( build_cond( $1, $1, $4 ) ); }
892        ;
893
894constant_expression:
895        conditional_expression
896        ;
897
898assignment_expression:
899                // CFA, assignment is separated from assignment_operator to ensure no assignment operations for tuples
900        conditional_expression
901        | unary_expression assignment_operator assignment_expression
902                { $$ = new ExpressionNode( build_binary_val( $2, $1, $3 ) ); }
903        | unary_expression '=' '{' initializer_list_opt comma_opt '}'
904                { SemanticError( yylloc, "Initializer assignment is currently unimplemented." ); $$ = nullptr; }
905        ;
906
907assignment_expression_opt:
908        // empty
909                { $$ = nullptr; }
910        | assignment_expression
911        ;
912
913assignment_operator:
914        '='                                                                                     { $$ = OperKinds::Assign; }
915        | ATassign                                                                      { $$ = OperKinds::AtAssn; }
916        | EXPassign                                                                     { $$ = OperKinds::ExpAssn; }
917        | MULTassign                                                            { $$ = OperKinds::MulAssn; }
918        | DIVassign                                                                     { $$ = OperKinds::DivAssn; }
919        | MODassign                                                                     { $$ = OperKinds::ModAssn; }
920        | PLUSassign                                                            { $$ = OperKinds::PlusAssn; }
921        | MINUSassign                                                           { $$ = OperKinds::MinusAssn; }
922        | LSassign                                                                      { $$ = OperKinds::LSAssn; }
923        | RSassign                                                                      { $$ = OperKinds::RSAssn; }
924        | ANDassign                                                                     { $$ = OperKinds::AndAssn; }
925        | ERassign                                                                      { $$ = OperKinds::ERAssn; }
926        | ORassign                                                                      { $$ = OperKinds::OrAssn; }
927        ;
928
929tuple:                                                                                                  // CFA, tuple
930                // CFA, one assignment_expression is factored out of comma_expression to eliminate a shift/reduce conflict with
931                // comma_expression in cfa_identifier_parameter_array and cfa_abstract_array
932//      '[' ']'
933//              { $$ = new ExpressionNode( build_tuple() ); }
934//      | '[' push assignment_expression pop ']'
935//              { $$ = new ExpressionNode( build_tuple( $3 ) ); }
936        '[' ',' tuple_expression_list ']'
937                { $$ = new ExpressionNode( build_tuple( (ExpressionNode *)(new ExpressionNode( nullptr ) )->set_last( $3 ) ) ); }
938        | '[' push assignment_expression pop ',' tuple_expression_list ']'
939                { $$ = new ExpressionNode( build_tuple( (ExpressionNode *)$3->set_last( $6 ) ) ); }
940        ;
941
942tuple_expression_list:
943        assignment_expression_opt
944        | tuple_expression_list ',' assignment_expression_opt
945                { $$ = (ExpressionNode *)$1->set_last( $3 ); }
946        ;
947
948comma_expression:
949        assignment_expression
950        | comma_expression ',' assignment_expression
951                { $$ = new ExpressionNode( new CommaExpr( maybeMoveBuild< Expression >( $1 ), maybeMoveBuild< Expression >( $3 ) ) ); }
952        ;
953
954comma_expression_opt:
955        // empty
956                { $$ = nullptr; }
957        | comma_expression
958        ;
959
960//*************************** STATEMENTS *******************************
961
962statement:
963        labeled_statement
964        | compound_statement
965        | expression_statement
966        | selection_statement
967        | iteration_statement
968        | jump_statement
969        | with_statement
970        | mutex_statement
971        | waitfor_statement
972        | exception_statement
973        | enable_disable_statement
974                { SemanticError( yylloc, "enable/disable statement is currently unimplemented." ); $$ = nullptr; }
975        | asm_statement
976        | DIRECTIVE
977                { $$ = new StatementNode( build_directive( $1 ) ); }
978        ;
979
980labeled_statement:
981                // labels cannot be identifiers 0 or 1 or ATTR_IDENTIFIER
982        identifier_or_type_name ':' attribute_list_opt statement
983                {
984                        $$ = $4->add_label( $1, $3 );
985                }
986        ;
987
988compound_statement:
989        '{' '}'
990                { $$ = new StatementNode( build_compound( (StatementNode *)0 ) ); }
991        | '{' push
992          local_label_declaration_opt                                           // GCC, local labels
993          statement_decl_list                                                           // C99, intermix declarations and statements
994          pop '}'
995                { $$ = new StatementNode( build_compound( $4 ) ); }
996        ;
997
998statement_decl_list:                                                                    // C99
999        statement_decl
1000        | statement_decl_list statement_decl
1001                { if ( $1 != 0 ) { $1->set_last( $2 ); $$ = $1; } }
1002        ;
1003
1004statement_decl:
1005        declaration                                                                                     // CFA, new & old style declarations
1006                { $$ = new StatementNode( $1 ); }
1007        | EXTENSION declaration                                                         // GCC
1008                {
1009                        distExt( $2 );
1010                        $$ = new StatementNode( $2 );
1011                }
1012        | function_definition
1013                { $$ = new StatementNode( $1 ); }
1014        | EXTENSION function_definition                                         // GCC
1015                {
1016                        distExt( $2 );
1017                        $$ = new StatementNode( $2 );
1018                }
1019        | statement
1020        ;
1021
1022statement_list_nodecl:
1023        statement
1024        | statement_list_nodecl statement
1025                { if ( $1 != 0 ) { $1->set_last( $2 ); $$ = $1; } }
1026        ;
1027
1028expression_statement:
1029        comma_expression_opt ';'
1030                { $$ = new StatementNode( build_expr( $1 ) ); }
1031        ;
1032
1033selection_statement:
1034                        // pop causes a S/R conflict without separating the IF statement into a non-terminal even after resolving
1035                        // the inherent S/R conflict with THEN/ELSE.
1036        push if_statement pop
1037                { $$ = $2; }
1038        | SWITCH '(' comma_expression ')' case_clause
1039                { $$ = new StatementNode( build_switch( true, $3, $5 ) ); }
1040        | SWITCH '(' comma_expression ')' '{' push declaration_list_opt switch_clause_list_opt pop '}' // CFA
1041                {
1042                        StatementNode *sw = new StatementNode( build_switch( true, $3, $8 ) );
1043                        // The semantics of the declaration list is changed to include associated initialization, which is performed
1044                        // *before* the transfer to the appropriate case clause by hoisting the declarations into a compound
1045                        // statement around the switch.  Statements after the initial declaration list can never be executed, and
1046                        // therefore, are removed from the grammar even though C allows it. The change also applies to choose
1047                        // statement.
1048                        $$ = $7 ? new StatementNode( build_compound( (StatementNode *)((new StatementNode( $7 ))->set_last( sw )) ) ) : sw;
1049                }
1050        | CHOOSE '(' comma_expression ')' case_clause           // CFA
1051                { $$ = new StatementNode( build_switch( false, $3, $5 ) ); }
1052        | CHOOSE '(' comma_expression ')' '{' push declaration_list_opt switch_clause_list_opt pop '}' // CFA
1053                {
1054                        StatementNode *sw = new StatementNode( build_switch( false, $3, $8 ) );
1055                        $$ = $7 ? new StatementNode( build_compound( (StatementNode *)((new StatementNode( $7 ))->set_last( sw )) ) ) : sw;
1056                }
1057        ;
1058
1059if_statement:
1060        IF '(' if_control_expression ')' statement                      %prec THEN
1061                // explicitly deal with the shift/reduce conflict on if/else
1062                { $$ = new StatementNode( build_if( $3, $5, nullptr ) ); }
1063        | IF '(' if_control_expression ')' statement ELSE statement
1064                { $$ = new StatementNode( build_if( $3, $5, $7 ) ); }
1065        ;
1066
1067if_control_expression:
1068        comma_expression
1069                { $$ = new IfCtrl( nullptr, $1 ); }
1070        | c_declaration                                                                         // no semi-colon
1071                { $$ = new IfCtrl( $1, nullptr ); }
1072        | cfa_declaration                                                                       // no semi-colon
1073                { $$ = new IfCtrl( $1, nullptr ); }
1074        | declaration comma_expression                                          // semi-colon separated
1075                { $$ = new IfCtrl( $1, $2 ); }
1076        ;
1077
1078// CASE and DEFAULT clauses are only allowed in the SWITCH statement, precluding Duff's device. In addition, a case
1079// clause allows a list of values and subranges.
1080
1081case_value:                                                                                             // CFA
1082        constant_expression                                                     { $$ = $1; }
1083        | constant_expression ELLIPSIS constant_expression      // GCC, subrange
1084                { $$ = new ExpressionNode( new RangeExpr( maybeMoveBuild< Expression >( $1 ), maybeMoveBuild< Expression >( $3 ) ) ); }
1085        | subrange                                                                                      // CFA, subrange
1086        ;
1087
1088case_value_list:                                                                                // CFA
1089        case_value                                                                      { $$ = new StatementNode( build_case( $1 ) ); }
1090                // convert case list, e.g., "case 1, 3, 5:" into "case 1: case 3: case 5"
1091        | case_value_list ',' case_value                        { $$ = (StatementNode *)($1->set_last( new StatementNode( build_case( $3 ) ) ) ); }
1092        ;
1093
1094case_label:                                                                                             // CFA
1095        CASE case_value_list ':'                                        { $$ = $2; }
1096        | DEFAULT ':'                                                           { $$ = new StatementNode( build_default() ); }
1097                // A semantic check is required to ensure only one default clause per switch/choose statement.
1098        ;
1099
1100//label_list_opt:
1101//      // empty
1102//      | identifier_or_type_name ':'
1103//      | label_list_opt identifier_or_type_name ':'
1104//      ;
1105
1106case_label_list:                                                                                // CFA
1107        case_label
1108        | case_label_list case_label                            { $$ = (StatementNode *)( $1->set_last( $2 )); }
1109        ;
1110
1111case_clause:                                                                                    // CFA
1112        case_label_list statement                                       { $$ = $1->append_last_case( new StatementNode( build_compound( $2 ) ) ); }
1113        ;
1114
1115switch_clause_list_opt:                                                                 // CFA
1116        // empty
1117                { $$ = nullptr; }
1118        | switch_clause_list
1119        ;
1120
1121switch_clause_list:                                                                             // CFA
1122        case_label_list statement_list_nodecl
1123                { $$ = $1->append_last_case( new StatementNode( build_compound( $2 ) ) ); }
1124        | switch_clause_list case_label_list statement_list_nodecl
1125                { $$ = (StatementNode *)( $1->set_last( $2->append_last_case( new StatementNode( build_compound( $3 ) ) ) ) ); }
1126        ;
1127
1128iteration_statement:
1129        WHILE '(' push if_control_expression ')' statement pop
1130                { $$ = new StatementNode( build_while( $4, $6 ) ); }
1131        | WHILE '(' ')' statement                                                       // CFA => while ( 1 )
1132                { $$ = new StatementNode( build_while( new IfCtrl( nullptr, new ExpressionNode( build_constantInteger( *new string( "1" ) ) ) ), $4 ) ); }
1133        | DO statement WHILE '(' comma_expression ')' ';'
1134                { $$ = new StatementNode( build_do_while( $5, $2 ) ); }
1135        | DO statement WHILE '(' ')' ';'                                        // CFA => do while( 1 )
1136                { $$ = new StatementNode( build_do_while( new ExpressionNode( build_constantInteger( *new string( "1" ) ) ), $2 ) ); }
1137        | FOR '(' push for_control_expression ')' statement pop
1138                { $$ = new StatementNode( build_for( $4, $6 ) ); }
1139        ;
1140
1141for_control_expression:
1142        comma_expression_opt                                                            // CFA
1143                {
1144                        if ( ! $1 ) {                                                           // => for ( ;; )
1145                                $$ = new ForCtrl( (ExpressionNode * )nullptr, (ExpressionNode * )nullptr, (ExpressionNode * )nullptr );
1146                        } else {
1147                                $$ = forCtrl( $1, new string( DeclarationNode::anonymous.newName() ), new ExpressionNode( build_constantInteger( *new string( "0" ) ) ),
1148                                                          OperKinds::LThan, $1->clone(), forInc( OperKinds::LThan ) );
1149                        } // if
1150                }
1151        | constant_expression inclexcl constant_expression      // CFA
1152                { $$ = forCtrl( $1, new string( DeclarationNode::anonymous.newName() ), $1->clone(), $2, $3, forInc( $2 ) ); }
1153        | constant_expression inclexcl constant_expression '~' constant_expression // CFA
1154                { $$ = forCtrl( $1, new string( DeclarationNode::anonymous.newName() ), $1->clone(), $2, $3, $5 ); }
1155        | comma_expression_opt ';' comma_expression                     // CFA
1156                {
1157                        if ( ! $1 ) {
1158                                SemanticError( yylloc, "Missing loop index." ); $$ = nullptr;
1159                        } else if ( ! $3 ) {
1160                                SemanticError( yylloc, "Missing loop range." ); $$ = nullptr;
1161                        } else {
1162                                if ( NameExpr *identifier = dynamic_cast<NameExpr *>($1->get_expr()) ) {
1163                                        $$ = forCtrl( $3, new string( identifier->name ), new ExpressionNode( build_constantInteger( *new string( "0" ) ) ),
1164                                                                  OperKinds::LThan, $3->clone(), forInc( OperKinds::LThan ) );
1165                                } else {
1166                                        SemanticError( yylloc, "Expression disallowed. Only loop-index name allowed" ); $$ = nullptr;
1167                                } // if
1168                        } // if
1169                }
1170        | comma_expression_opt ';' constant_expression inclexcl constant_expression // CFA
1171                {
1172                        if ( ! $1 ) {
1173                                SemanticError( yylloc, "Missing loop index." ); $$ = nullptr;
1174                        } else {
1175                                if ( NameExpr *identifier = dynamic_cast<NameExpr *>($1->get_expr()) ) {
1176                                        $$ = forCtrl( $3, new string( identifier->name ), $3->clone(), $4, $5, forInc( $4 ) );
1177                                } else {
1178                                        SemanticError( yylloc, "Expression disallowed. Only loop-index name allowed" ); $$ = nullptr;
1179                                } // if
1180                        } // if
1181                }
1182        | comma_expression_opt ';' constant_expression inclexcl constant_expression '~' constant_expression // CFA
1183                {
1184                        if ( ! $1 ) {
1185                                SemanticError( yylloc, "Missing loop index." ); $$ = nullptr;
1186                        } else {
1187                                if ( NameExpr *identifier = dynamic_cast<NameExpr *>($1->get_expr()) ) {
1188                                        $$ = forCtrl( $3, new string( identifier->name ), $3->clone(), $4, $5, $7 );
1189                                } else {
1190                                        SemanticError( yylloc, "Expression disallowed. Only loop-index name allowed" ); $$ = nullptr;
1191                                } // if
1192                        } // if
1193                }
1194        | comma_expression_opt ';' comma_expression_opt ';' comma_expression_opt
1195                { $$ = new ForCtrl( $1, $3, $5 ); }
1196        | declaration comma_expression_opt ';' comma_expression_opt // C99, declaration has ';'
1197                { $$ = new ForCtrl( $1, $2, $4 ); }
1198        ;
1199
1200inclexcl:
1201        '~'
1202                { $$ = OperKinds::LThan; }
1203        | ErangeUpEq
1204                { $$ = OperKinds::LEThan; }
1205        | ErangeDown
1206                { $$ = OperKinds::GThan; }
1207        | ErangeDownEq
1208                { $$ = OperKinds::GEThan; }
1209        ;
1210
1211jump_statement:
1212        GOTO identifier_or_type_name ';'
1213                { $$ = new StatementNode( build_branch( $2, BranchStmt::Goto ) ); }
1214        | GOTO '*' comma_expression ';'                                         // GCC, computed goto
1215                // The syntax for the GCC computed goto violates normal expression precedence, e.g., goto *i+3; => goto *(i+3);
1216                // whereas normal operator precedence yields goto (*i)+3;
1217                { $$ = new StatementNode( build_computedgoto( $3 ) ); }
1218                // A semantic check is required to ensure fallthru appears only in the body of a choose statement.
1219    | fall_through_name ';'                                                             // CFA
1220                { $$ = new StatementNode( build_branch( BranchStmt::FallThrough ) ); }
1221    | fall_through_name identifier_or_type_name ';'             // CFA
1222                { $$ = new StatementNode( build_branch( $2, BranchStmt::FallThrough ) ); }
1223        | fall_through_name DEFAULT ';'                                         // CFA
1224                { $$ = new StatementNode( build_branch( BranchStmt::FallThroughDefault ) ); }
1225        | CONTINUE ';'
1226                // A semantic check is required to ensure this statement appears only in the body of an iteration statement.
1227                { $$ = new StatementNode( build_branch( BranchStmt::Continue ) ); }
1228        | CONTINUE identifier_or_type_name ';'                          // CFA, multi-level continue
1229                // A semantic check is required to ensure this statement appears only in the body of an iteration statement, and
1230                // the target of the transfer appears only at the start of an iteration statement.
1231                { $$ = new StatementNode( build_branch( $2, BranchStmt::Continue ) ); }
1232        | BREAK ';'
1233                // A semantic check is required to ensure this statement appears only in the body of an iteration statement.
1234                { $$ = new StatementNode( build_branch( BranchStmt::Break ) ); }
1235        | BREAK identifier_or_type_name ';'                                     // CFA, multi-level exit
1236                // A semantic check is required to ensure this statement appears only in the body of an iteration statement, and
1237                // the target of the transfer appears only at the start of an iteration statement.
1238                { $$ = new StatementNode( build_branch( $2, BranchStmt::Break ) ); }
1239        | RETURN comma_expression_opt ';'
1240                { $$ = new StatementNode( build_return( $2 ) ); }
1241        | RETURN '{' initializer_list_opt comma_opt '}'
1242                { SemanticError( yylloc, "Initializer return is currently unimplemented." ); $$ = nullptr; }
1243        | THROW assignment_expression_opt ';'                           // handles rethrow
1244                { $$ = new StatementNode( build_throw( $2 ) ); }
1245        | THROWRESUME assignment_expression_opt ';'                     // handles reresume
1246                { $$ = new StatementNode( build_resume( $2 ) ); }
1247        | THROWRESUME assignment_expression_opt AT assignment_expression ';' // handles reresume
1248                { $$ = new StatementNode( build_resume_at( $2, $4 ) ); }
1249        ;
1250
1251fall_through_name:                                                                              // CFA
1252        FALLTHRU
1253        | FALLTHROUGH
1254        ;
1255
1256with_statement:
1257        WITH '(' tuple_expression_list ')' statement
1258                {
1259                        $$ = new StatementNode( build_with( $3, $5 ) );
1260                }
1261        ;
1262
1263// If MUTEX becomes a general qualifier, there are shift/reduce conflicts, so change syntax to "with mutex".
1264mutex_statement:
1265        MUTEX '(' argument_expression_list ')' statement
1266                { SemanticError( yylloc, "Mutex statement is currently unimplemented." ); $$ = nullptr; }
1267        ;
1268
1269when_clause:
1270        WHEN '(' comma_expression ')'                           { $$ = $3; }
1271        ;
1272
1273when_clause_opt:
1274        // empty
1275                { $$ = nullptr; }
1276        | when_clause
1277        ;
1278
1279waitfor:
1280        WAITFOR '(' cast_expression ')'
1281                { $$ = $3; }
1282        | WAITFOR '(' cast_expression ',' argument_expression_list ')'
1283                { $$ = (ExpressionNode *)$3->set_last( $5 ); }
1284        ;
1285
1286timeout:
1287        TIMEOUT '(' comma_expression ')'                        { $$ = $3; }
1288        ;
1289
1290waitfor_clause:
1291        when_clause_opt waitfor statement                                       %prec THEN
1292                { $$ = build_waitfor( $2, $3, $1 ); }
1293        | when_clause_opt waitfor statement WOR waitfor_clause
1294                { $$ = build_waitfor( $2, $3, $1, $5 ); }
1295        | when_clause_opt timeout statement                                     %prec THEN
1296                { $$ = build_waitfor_timeout( $2, $3, $1 ); }
1297        | when_clause_opt ELSE statement
1298                { $$ = build_waitfor_timeout( nullptr, $3, $1 ); }
1299                // "else" must be conditional after timeout or timeout is never triggered (i.e., it is meaningless)
1300        | when_clause_opt timeout statement WOR ELSE statement
1301                { SemanticError( yylloc, "else clause must be conditional after timeout or timeout never triggered." ); $$ = nullptr; }
1302        | when_clause_opt timeout statement WOR when_clause ELSE statement
1303                { $$ = build_waitfor_timeout( $2, $3, $1, $7, $5 ); }
1304        ;
1305
1306waitfor_statement:
1307        when_clause_opt waitfor statement                                       %prec THEN
1308                { $$ = new StatementNode( build_waitfor( $2, $3, $1 ) ); }
1309        | when_clause_opt waitfor statement WOR waitfor_clause
1310                { $$ = new StatementNode( build_waitfor( $2, $3, $1, $5 ) ); }
1311        ;
1312
1313exception_statement:
1314        TRY compound_statement handler_clause
1315                { $$ = new StatementNode( build_try( $2, $3, 0 ) ); }
1316        | TRY compound_statement finally_clause
1317                { $$ = new StatementNode( build_try( $2, 0, $3 ) ); }
1318        | TRY compound_statement handler_clause finally_clause
1319                { $$ = new StatementNode( build_try( $2, $3, $4 ) ); }
1320        ;
1321
1322handler_clause:
1323        handler_key '(' push exception_declaration pop handler_predicate_opt ')' compound_statement pop
1324                { $$ = new StatementNode( build_catch( $1, $4, $6, $8 ) ); }
1325        | handler_clause handler_key '(' push exception_declaration pop handler_predicate_opt ')' compound_statement pop
1326                { $$ = (StatementNode *)$1->set_last( new StatementNode( build_catch( $2, $5, $7, $9 ) ) ); }
1327        ;
1328
1329handler_predicate_opt:
1330        // empty
1331                { $$ = nullptr; }
1332        | ';' conditional_expression                            { $$ = $2; }
1333        ;
1334
1335handler_key:
1336        CATCH                                                                           { $$ = CatchStmt::Terminate; }
1337        | CATCHRESUME                                                           { $$ = CatchStmt::Resume; }
1338        ;
1339
1340finally_clause:
1341        FINALLY compound_statement                                      { $$ = new StatementNode( build_finally( $2 ) ); }
1342        ;
1343
1344exception_declaration:
1345                // No SUE declaration in parameter list.
1346        type_specifier_nobody
1347        | type_specifier_nobody declarator
1348                { $$ = $2->addType( $1 ); }
1349        | type_specifier_nobody variable_abstract_declarator
1350                { $$ = $2->addType( $1 ); }
1351        | cfa_abstract_declarator_tuple no_attr_identifier      // CFA
1352                { $$ = $1->addName( $2 ); }
1353        | cfa_abstract_declarator_tuple                                         // CFA
1354        ;
1355
1356enable_disable_statement:
1357        enable_disable_key identifier_list compound_statement
1358        ;
1359
1360enable_disable_key:
1361        ENABLE
1362        | DISABLE
1363        ;
1364
1365asm_statement:
1366        ASM asm_volatile_opt '(' string_literal ')' ';'
1367                { $$ = new StatementNode( build_asm( $2, $4, 0 ) ); }
1368        | ASM asm_volatile_opt '(' string_literal ':' asm_operands_opt ')' ';' // remaining GCC
1369                { $$ = new StatementNode( build_asm( $2, $4, $6 ) ); }
1370        | ASM asm_volatile_opt '(' string_literal ':' asm_operands_opt ':' asm_operands_opt ')' ';'
1371                { $$ = new StatementNode( build_asm( $2, $4, $6, $8 ) ); }
1372        | ASM asm_volatile_opt '(' string_literal ':' asm_operands_opt ':' asm_operands_opt ':' asm_clobbers_list_opt ')' ';'
1373                { $$ = new StatementNode( build_asm( $2, $4, $6, $8, $10 ) ); }
1374        | ASM asm_volatile_opt GOTO '(' string_literal ':' ':' asm_operands_opt ':' asm_clobbers_list_opt ':' label_list ')' ';'
1375                { $$ = new StatementNode( build_asm( $2, $5, 0, $8, $10, $12 ) ); }
1376        ;
1377
1378asm_volatile_opt:                                                                               // GCC
1379        // empty
1380                { $$ = false; }
1381        | VOLATILE
1382                { $$ = true; }
1383        ;
1384
1385asm_operands_opt:                                                                               // GCC
1386        // empty
1387                { $$ = nullptr; }                                                               // use default argument
1388        | asm_operands_list
1389        ;
1390
1391asm_operands_list:                                                                              // GCC
1392        asm_operand
1393        | asm_operands_list ',' asm_operand
1394                { $$ = (ExpressionNode *)$1->set_last( $3 ); }
1395        ;
1396
1397asm_operand:                                                                                    // GCC
1398        string_literal '(' constant_expression ')'
1399                { $$ = new ExpressionNode( new AsmExpr( maybeMoveBuild< Expression >( (ExpressionNode *)nullptr ), $1, maybeMoveBuild< Expression >( $3 ) ) ); }
1400        | '[' constant_expression ']' string_literal '(' constant_expression ')'
1401                { $$ = new ExpressionNode( new AsmExpr( maybeMoveBuild< Expression >( $2 ), $4, maybeMoveBuild< Expression >( $6 ) ) ); }
1402        ;
1403
1404asm_clobbers_list_opt:                                                                  // GCC
1405        // empty
1406                { $$ = nullptr; }                                                               // use default argument
1407        | string_literal
1408                { $$ = new ExpressionNode( $1 ); }
1409        | asm_clobbers_list_opt ',' string_literal
1410                // set_last returns ParseNode *
1411                { $$ = (ExpressionNode *)$1->set_last( new ExpressionNode( $3 ) ); }
1412        ;
1413
1414label_list:
1415        no_attr_identifier
1416                {
1417                        $$ = new LabelNode(); $$->labels.push_back( *$1 );
1418                        delete $1;                                                                      // allocated by lexer
1419                }
1420        | label_list ',' no_attr_identifier
1421                {
1422                        $$ = $1; $1->labels.push_back( *$3 );
1423                        delete $3;                                                                      // allocated by lexer
1424                }
1425        ;
1426
1427//******************************* DECLARATIONS *********************************
1428
1429declaration_list_opt:                                                                   // used at beginning of switch statement
1430        // empty
1431                { $$ = nullptr; }
1432        | declaration_list
1433        ;
1434
1435declaration_list:
1436        declaration
1437        | declaration_list declaration
1438                { $$ = $1->appendList( $2 ); }
1439        ;
1440
1441KR_parameter_list_opt:                                                                  // used to declare parameter types in K&R style functions
1442        // empty
1443                { $$ = nullptr; }
1444        | KR_parameter_list
1445        ;
1446
1447KR_parameter_list:
1448        push c_declaration pop ';'
1449                { $$ = $2; }
1450        | KR_parameter_list push c_declaration pop ';'
1451                { $$ = $1->appendList( $3 ); }
1452        ;
1453
1454local_label_declaration_opt:                                                    // GCC, local label
1455        // empty
1456        | local_label_declaration_list
1457        ;
1458
1459local_label_declaration_list:                                                   // GCC, local label
1460        LABEL local_label_list ';'
1461        | local_label_declaration_list LABEL local_label_list ';'
1462        ;
1463
1464local_label_list:                                                                               // GCC, local label
1465        no_attr_identifier_or_type_name
1466        | local_label_list ',' no_attr_identifier_or_type_name
1467        ;
1468
1469declaration:                                                                                    // old & new style declarations
1470        c_declaration ';'
1471        | cfa_declaration ';'                                                           // CFA
1472        | static_assert                                                                         // C11
1473        ;
1474
1475static_assert:
1476        STATICASSERT '(' constant_expression ',' string_literal ')' ';' // C11
1477                { $$ = DeclarationNode::newStaticAssert( $3, $5 ); }
1478        | STATICASSERT '(' constant_expression ')' ';'          // CFA
1479                { $$ = DeclarationNode::newStaticAssert( $3, build_constantStr( *new string( "\"\"" ) ) ); }
1480
1481// C declaration syntax is notoriously confusing and error prone. Cforall provides its own type, variable and function
1482// declarations. CFA declarations use the same declaration tokens as in C; however, CFA places declaration modifiers to
1483// the left of the base type, while C declarations place modifiers to the right of the base type. CFA declaration
1484// modifiers are interpreted from left to right and the entire type specification is distributed across all variables in
1485// the declaration list (as in Pascal).  ANSI C and the new CFA declarations may appear together in the same program
1486// block, but cannot be mixed within a specific declaration.
1487//
1488//                      CFA                                     C
1489//              [10] int x;                     int x[10];              // array of 10 integers
1490//              [10] * char y;          char *y[10];    // array of 10 pointers to char
1491
1492cfa_declaration:                                                                                // CFA
1493        cfa_variable_declaration
1494        | cfa_typedef_declaration
1495        | cfa_function_declaration
1496        | type_declaring_list
1497        | trait_specifier
1498        ;
1499
1500cfa_variable_declaration:                                                               // CFA
1501        cfa_variable_specifier initializer_opt
1502                { $$ = $1->addInitializer( $2 ); }
1503        | declaration_qualifier_list cfa_variable_specifier initializer_opt
1504                // declaration_qualifier_list also includes type_qualifier_list, so a semantic check is necessary to preclude
1505                // them as a type_qualifier cannot appear in that context.
1506                { $$ = $2->addQualifiers( $1 )->addInitializer( $3 ); }
1507        | cfa_variable_declaration pop ',' push identifier_or_type_name initializer_opt
1508                { $$ = $1->appendList( $1->cloneType( $5 )->addInitializer( $6 ) ); }
1509        ;
1510
1511cfa_variable_specifier:                                                                 // CFA
1512                // A semantic check is required to ensure asm_name only appears on declarations with implicit or explicit static
1513                // storage-class
1514        cfa_abstract_declarator_no_tuple identifier_or_type_name asm_name_opt
1515                { $$ = $1->addName( $2 )->addAsmName( $3 ); }
1516        | cfa_abstract_tuple identifier_or_type_name asm_name_opt
1517                { $$ = $1->addName( $2 )->addAsmName( $3 ); }
1518        | type_qualifier_list cfa_abstract_tuple identifier_or_type_name asm_name_opt
1519                { $$ = $2->addQualifiers( $1 )->addName( $3 )->addAsmName( $4 ); }
1520        ;
1521
1522cfa_function_declaration:                                                               // CFA
1523        cfa_function_specifier
1524        | type_qualifier_list cfa_function_specifier
1525                { $$ = $2->addQualifiers( $1 ); }
1526        | declaration_qualifier_list cfa_function_specifier
1527                { $$ = $2->addQualifiers( $1 ); }
1528        | declaration_qualifier_list type_qualifier_list cfa_function_specifier
1529                { $$ = $3->addQualifiers( $1 )->addQualifiers( $2 ); }
1530        | cfa_function_declaration ',' identifier_or_type_name '(' push cfa_parameter_ellipsis_list_opt pop ')'
1531                {
1532                        // Append the return type at the start (left-hand-side) to each identifier in the list.
1533                        DeclarationNode * ret = new DeclarationNode;
1534                        ret->type = maybeClone( $1->type->base );
1535                        $$ = $1->appendList( DeclarationNode::newFunction( $3, ret, $6, nullptr ) );
1536                }
1537        ;
1538
1539cfa_function_specifier:                                                                 // CFA
1540//      '[' ']' identifier_or_type_name '(' push cfa_parameter_ellipsis_list_opt pop ')' // S/R conflict
1541//              {
1542//                      $$ = DeclarationNode::newFunction( $3, DeclarationNode::newTuple( 0 ), $6, 0, true );
1543//              }
1544//      '[' ']' identifier '(' push cfa_parameter_ellipsis_list_opt pop ')'
1545//              {
1546//                      typedefTable.setNextIdentifier( *$5 );
1547//                      $$ = DeclarationNode::newFunction( $5, DeclarationNode::newTuple( 0 ), $8, 0, true );
1548//              }
1549//      | '[' ']' TYPEDEFname '(' push cfa_parameter_ellipsis_list_opt pop ')'
1550//              {
1551//                      typedefTable.setNextIdentifier( *$5 );
1552//                      $$ = DeclarationNode::newFunction( $5, DeclarationNode::newTuple( 0 ), $8, 0, true );
1553//              }
1554//      | '[' ']' typegen_name
1555                // identifier_or_type_name must be broken apart because of the sequence:
1556                //
1557                //   '[' ']' identifier_or_type_name '(' cfa_parameter_ellipsis_list_opt ')'
1558                //   '[' ']' type_specifier
1559                //
1560                // type_specifier can resolve to just TYPEDEFname (e.g., typedef int T; int f( T );). Therefore this must be
1561                // flattened to allow lookahead to the '(' without having to reduce identifier_or_type_name.
1562        cfa_abstract_tuple identifier_or_type_name '(' push cfa_parameter_ellipsis_list_opt pop ')'
1563                // To obtain LR(1 ), this rule must be factored out from function return type (see cfa_abstract_declarator).
1564                { $$ = DeclarationNode::newFunction( $2, $1, $5, 0 ); }
1565        | cfa_function_return identifier_or_type_name '(' push cfa_parameter_ellipsis_list_opt pop ')'
1566                { $$ = DeclarationNode::newFunction( $2, $1, $5, 0 ); }
1567        ;
1568
1569cfa_function_return:                                                                    // CFA
1570        '[' push cfa_parameter_list pop ']'
1571                { $$ = DeclarationNode::newTuple( $3 ); }
1572        | '[' push cfa_parameter_list pop ',' push cfa_abstract_parameter_list pop ']'
1573                // To obtain LR(1 ), the last cfa_abstract_parameter_list is added into this flattened rule to lookahead to the ']'.
1574                { $$ = DeclarationNode::newTuple( $3->appendList( $7 ) ); }
1575        ;
1576
1577cfa_typedef_declaration:                                                                // CFA
1578        TYPEDEF cfa_variable_specifier
1579                {
1580                        typedefTable.addToEnclosingScope( *$2->name, TYPEDEFname, "1" );
1581                        $$ = $2->addTypedef();
1582                }
1583        | TYPEDEF cfa_function_specifier
1584                {
1585                        typedefTable.addToEnclosingScope( *$2->name, TYPEDEFname, "2" );
1586                        $$ = $2->addTypedef();
1587                }
1588        | cfa_typedef_declaration pop ',' push no_attr_identifier
1589                {
1590                        typedefTable.addToEnclosingScope( *$5, TYPEDEFname, "3" );
1591                        $$ = $1->appendList( $1->cloneType( $5 ) );
1592                }
1593        ;
1594
1595// Traditionally typedef is part of storage-class specifier for syntactic convenience only. Here, it is factored out as
1596// a separate form of declaration, which syntactically precludes storage-class specifiers and initialization.
1597
1598typedef_declaration:
1599        TYPEDEF type_specifier declarator
1600                {
1601                        typedefTable.addToEnclosingScope( *$3->name, TYPEDEFname, "4" );
1602                        $$ = $3->addType( $2 )->addTypedef();
1603                }
1604        | typedef_declaration pop ',' push declarator
1605                {
1606                        typedefTable.addToEnclosingScope( *$5->name, TYPEDEFname, "5" );
1607                        $$ = $1->appendList( $1->cloneBaseType( $5 )->addTypedef() );
1608                }
1609        | type_qualifier_list TYPEDEF type_specifier declarator // remaining OBSOLESCENT (see 2 )
1610                {
1611                        typedefTable.addToEnclosingScope( *$4->name, TYPEDEFname, "6" );
1612                        $$ = $4->addType( $3 )->addQualifiers( $1 )->addTypedef();
1613                }
1614        | type_specifier TYPEDEF declarator
1615                {
1616                        typedefTable.addToEnclosingScope( *$3->name, TYPEDEFname, "7" );
1617                        $$ = $3->addType( $1 )->addTypedef();
1618                }
1619        | type_specifier TYPEDEF type_qualifier_list declarator
1620                {
1621                        typedefTable.addToEnclosingScope( *$4->name, TYPEDEFname, "8" );
1622                        $$ = $4->addQualifiers( $1 )->addTypedef()->addType( $1 );
1623                }
1624        ;
1625
1626typedef_expression:
1627                // GCC, naming expression type: typedef name = exp; gives a name to the type of an expression
1628        TYPEDEF no_attr_identifier '=' assignment_expression
1629                {
1630                        // $$ = DeclarationNode::newName( 0 );                  // unimplemented
1631                        SemanticError( yylloc, "Typedef expression is currently unimplemented." ); $$ = nullptr;
1632                }
1633        | typedef_expression pop ',' push no_attr_identifier '=' assignment_expression
1634                {
1635                        // $$ = DeclarationNode::newName( 0 );                  // unimplemented
1636                        SemanticError( yylloc, "Typedef expression is currently unimplemented." ); $$ = nullptr;
1637                }
1638        ;
1639
1640//c_declaration:
1641//      declaring_list pop ';'
1642//      | typedef_declaration pop ';'
1643//      | typedef_expression pop ';'                                            // GCC, naming expression type
1644//      | sue_declaration_specifier pop ';'
1645//      ;
1646//
1647//declaring_list:
1648//              // A semantic check is required to ensure asm_name only appears on declarations with implicit or explicit static
1649//              // storage-class
1650//       declarator asm_name_opt initializer_opt
1651//              {
1652//                      typedefTable.addToEnclosingScope( IDENTIFIER );
1653//                      $$ = ( $2->addType( $1 ))->addAsmName( $3 )->addInitializer( $4 );
1654//              }
1655//      | declaring_list ',' attribute_list_opt declarator asm_name_opt initializer_opt
1656//              {
1657//                      typedefTable.addToEnclosingScope( IDENTIFIER );
1658//                      $$ = $1->appendList( $1->cloneBaseType( $4->addAsmName( $5 )->addInitializer( $6 ) ) );
1659//              }
1660//      ;
1661
1662c_declaration:
1663        declaration_specifier declaring_list
1664                { $$ = distAttr( $1, $2 ); }
1665        | typedef_declaration
1666        | typedef_expression                                                            // GCC, naming expression type
1667        | sue_declaration_specifier
1668        ;
1669
1670declaring_list:
1671                // A semantic check is required to ensure asm_name only appears on declarations with implicit or explicit static
1672                // storage-class
1673        declarator asm_name_opt initializer_opt
1674                { $$ = $1->addAsmName( $2 )->addInitializer( $3 ); }
1675        | declaring_list ',' attribute_list_opt declarator asm_name_opt initializer_opt
1676                { $$ = $1->appendList( $4->addQualifiers( $3 )->addAsmName( $5 )->addInitializer( $6 ) ); }
1677        ;
1678
1679declaration_specifier:                                                                  // type specifier + storage class
1680        basic_declaration_specifier
1681        | sue_declaration_specifier
1682        | type_declaration_specifier
1683        ;
1684
1685declaration_specifier_nobody:                                                   // type specifier + storage class - {...}
1686                // Preclude SUE declarations in restricted scopes:
1687                //
1688                //    int f( struct S { int i; } s1, Struct S s2 ) { struct S s3; ... }
1689                //
1690                // because it is impossible to call f due to name equivalence.
1691        basic_declaration_specifier
1692        | sue_declaration_specifier_nobody
1693        | type_declaration_specifier
1694        ;
1695
1696type_specifier:                                                                                 // type specifier
1697        basic_type_specifier
1698        | sue_type_specifier
1699        | type_type_specifier
1700        ;
1701
1702type_specifier_nobody:                                                                  // type specifier - {...}
1703                // Preclude SUE declarations in restricted scopes:
1704                //
1705                //    int f( struct S { int i; } s1, Struct S s2 ) { struct S s3; ... }
1706                //
1707                // because it is impossible to call f due to name equivalence.
1708        basic_type_specifier
1709        | sue_type_specifier_nobody
1710        | type_type_specifier
1711        ;
1712
1713type_qualifier_list_opt:                                                                // GCC, used in asm_statement
1714        // empty
1715                { $$ = nullptr; }
1716        | type_qualifier_list
1717        ;
1718
1719type_qualifier_list:
1720                // A semantic check is necessary to ensure a type qualifier is appropriate for the kind of declaration.
1721                //
1722                // ISO/IEC 9899:1999 Section 6.7.3(4 ) : If the same qualifier appears more than once in the same
1723                // specifier-qualifier-list, either directly or via one or more typedefs, the behavior is the same as if it
1724                // appeared only once.
1725        type_qualifier
1726        | type_qualifier_list type_qualifier
1727                { $$ = $1->addQualifiers( $2 ); }
1728        ;
1729
1730type_qualifier:
1731        type_qualifier_name
1732        | attribute
1733        ;
1734
1735type_qualifier_name:
1736        CONST
1737                { $$ = DeclarationNode::newTypeQualifier( Type::Const ); }
1738        | RESTRICT
1739                { $$ = DeclarationNode::newTypeQualifier( Type::Restrict ); }
1740        | VOLATILE
1741                { $$ = DeclarationNode::newTypeQualifier( Type::Volatile ); }
1742        | ATOMIC
1743                { $$ = DeclarationNode::newTypeQualifier( Type::Atomic ); }
1744        | forall
1745        ;
1746
1747forall:
1748        FORALL '(' type_parameter_list ')'                                      // CFA
1749                { $$ = DeclarationNode::newForall( $3 ); }
1750        ;
1751
1752declaration_qualifier_list:
1753        storage_class_list
1754        | type_qualifier_list storage_class_list                        // remaining OBSOLESCENT (see 2 )
1755                { $$ = $1->addQualifiers( $2 ); }
1756        | declaration_qualifier_list type_qualifier_list storage_class_list
1757                { $$ = $1->addQualifiers( $2 )->addQualifiers( $3 ); }
1758        ;
1759
1760storage_class_list:
1761                // A semantic check is necessary to ensure a storage class is appropriate for the kind of declaration and that
1762                // only one of each is specified, except for inline, which can appear with the others.
1763                //
1764                // ISO/IEC 9899:1999 Section 6.7.1(2) : At most, one storage-class specifier may be given in the declaration
1765                // specifiers in a declaration.
1766        storage_class
1767        | storage_class_list storage_class
1768                { $$ = $1->addQualifiers( $2 ); }
1769        ;
1770
1771storage_class:
1772        EXTERN
1773                { $$ = DeclarationNode::newStorageClass( Type::Extern ); }
1774        | STATIC
1775                { $$ = DeclarationNode::newStorageClass( Type::Static ); }
1776        | AUTO
1777                { $$ = DeclarationNode::newStorageClass( Type::Auto ); }
1778        | REGISTER
1779                { $$ = DeclarationNode::newStorageClass( Type::Register ); }
1780        | THREADLOCAL                                                                           // C11
1781                { $$ = DeclarationNode::newStorageClass( Type::Threadlocal ); }
1782                // Put function specifiers here to simplify parsing rules, but separate them semantically.
1783        | INLINE                                                                                        // C99
1784                { $$ = DeclarationNode::newFuncSpecifier( Type::Inline ); }
1785        | FORTRAN                                                                                       // C99
1786                { $$ = DeclarationNode::newFuncSpecifier( Type::Fortran ); }
1787        | NORETURN                                                                                      // C11
1788                { $$ = DeclarationNode::newFuncSpecifier( Type::Noreturn ); }
1789        ;
1790
1791basic_type_name:
1792        VOID
1793                { $$ = DeclarationNode::newBasicType( DeclarationNode::Void ); }
1794        | BOOL                                                                                          // C99
1795                { $$ = DeclarationNode::newBasicType( DeclarationNode::Bool ); }
1796        | CHAR
1797                { $$ = DeclarationNode::newBasicType( DeclarationNode::Char ); }
1798        | INT
1799                { $$ = DeclarationNode::newBasicType( DeclarationNode::Int ); }
1800        | INT128
1801                { $$ = DeclarationNode::newBasicType( DeclarationNode::Int128 ); }
1802        | FLOAT
1803                { $$ = DeclarationNode::newBasicType( DeclarationNode::Float ); }
1804        | FLOAT80
1805                { $$ = DeclarationNode::newBasicType( DeclarationNode::Float80 ); }
1806        | FLOAT128
1807                { $$ = DeclarationNode::newBasicType( DeclarationNode::Float128 ); }
1808        | DOUBLE
1809                { $$ = DeclarationNode::newBasicType( DeclarationNode::Double ); }
1810        | COMPLEX                                                                                       // C99
1811                { $$ = DeclarationNode::newComplexType( DeclarationNode::Complex ); }
1812        | IMAGINARY                                                                                     // C99
1813                { $$ = DeclarationNode::newComplexType( DeclarationNode::Imaginary ); }
1814        | SIGNED
1815                { $$ = DeclarationNode::newSignedNess( DeclarationNode::Signed ); }
1816        | UNSIGNED
1817                { $$ = DeclarationNode::newSignedNess( DeclarationNode::Unsigned ); }
1818        | SHORT
1819                { $$ = DeclarationNode::newLength( DeclarationNode::Short ); }
1820        | LONG
1821                { $$ = DeclarationNode::newLength( DeclarationNode::Long ); }
1822        | VALIST                                                                                        // GCC, __builtin_va_list
1823                { $$ = DeclarationNode::newBuiltinType( DeclarationNode::Valist ); }
1824        ;
1825
1826basic_declaration_specifier:
1827                // A semantic check is necessary for conflicting storage classes.
1828        basic_type_specifier
1829        | declaration_qualifier_list basic_type_specifier
1830                { $$ = $2->addQualifiers( $1 ); }
1831        | basic_declaration_specifier storage_class                     // remaining OBSOLESCENT (see 2)
1832                { $$ = $1->addQualifiers( $2 ); }
1833        | basic_declaration_specifier storage_class type_qualifier_list
1834                { $$ = $1->addQualifiers( $2 )->addQualifiers( $3 ); }
1835        | basic_declaration_specifier storage_class basic_type_specifier
1836                { $$ = $3->addQualifiers( $2 )->addType( $1 ); }
1837        ;
1838
1839basic_type_specifier:
1840        direct_type
1841                // Cannot have type modifiers, e.g., short, long, etc.
1842        | type_qualifier_list_opt indirect_type type_qualifier_list_opt
1843                { $$ = $2->addQualifiers( $1 )->addQualifiers( $3 ); }
1844        ;
1845
1846direct_type:
1847        basic_type_name
1848        | type_qualifier_list basic_type_name
1849                { $$ = $2->addQualifiers( $1 ); }
1850        | direct_type type_qualifier
1851                { $$ = $1->addQualifiers( $2 ); }
1852        | direct_type basic_type_name
1853                { $$ = $1->addType( $2 ); }
1854        ;
1855
1856indirect_type:
1857        TYPEOF '(' type ')'                                                                     // GCC: typeof(x) y;
1858                { $$ = $3; }
1859        | TYPEOF '(' comma_expression ')'                                       // GCC: typeof(a+b) y;
1860                { $$ = DeclarationNode::newTypeof( $3 ); }
1861        | ATTR_TYPEGENname '(' type ')'                                         // CFA: e.g., @type(x) y;
1862                { $$ = DeclarationNode::newAttr( $1, $3 ); }
1863        | ATTR_TYPEGENname '(' comma_expression ')'                     // CFA: e.g., @type(a+b) y;
1864                { $$ = DeclarationNode::newAttr( $1, $3 ); }
1865        | ZERO_T                                                                                        // CFA
1866                { $$ = DeclarationNode::newBuiltinType( DeclarationNode::Zero ); }
1867        | ONE_T                                                                                         // CFA
1868                { $$ = DeclarationNode::newBuiltinType( DeclarationNode::One ); }
1869        ;
1870
1871sue_declaration_specifier:                                                              // struct, union, enum + storage class + type specifier
1872        sue_type_specifier
1873        | declaration_qualifier_list sue_type_specifier
1874                { $$ = $2->addQualifiers( $1 ); }
1875        | sue_declaration_specifier storage_class                       // remaining OBSOLESCENT (see 2)
1876                { $$ = $1->addQualifiers( $2 ); }
1877        | sue_declaration_specifier storage_class type_qualifier_list
1878                { $$ = $1->addQualifiers( $2 )->addQualifiers( $3 ); }
1879        ;
1880
1881sue_type_specifier:                                                                             // struct, union, enum + type specifier
1882        elaborated_type
1883        | type_qualifier_list
1884                { if ( $1->type != nullptr && $1->type->forall ) forall = true; } // remember generic type
1885          elaborated_type
1886                { $$ = $3->addQualifiers( $1 ); }
1887        | sue_type_specifier type_qualifier
1888                {
1889                        if ( $2->type != nullptr && $2->type->forall ) forall = true; // remember generic type
1890                        $$ = $1->addQualifiers( $2 );
1891                }
1892        ;
1893
1894sue_declaration_specifier_nobody:                                               // struct, union, enum - {...} + storage class + type specifier
1895        sue_type_specifier_nobody
1896        | declaration_qualifier_list sue_type_specifier_nobody
1897                { $$ = $2->addQualifiers( $1 ); }
1898        | sue_declaration_specifier_nobody storage_class        // remaining OBSOLESCENT (see 2)
1899                { $$ = $1->addQualifiers( $2 ); }
1900        | sue_declaration_specifier_nobody storage_class type_qualifier_list
1901                { $$ = $1->addQualifiers( $2 )->addQualifiers( $3 ); }
1902        ;
1903
1904sue_type_specifier_nobody:                                                              // struct, union, enum - {...} + type specifier
1905        elaborated_type_nobody
1906        | type_qualifier_list elaborated_type_nobody
1907                { $$ = $2->addQualifiers( $1 ); }
1908        | sue_type_specifier_nobody type_qualifier
1909                { $$ = $1->addQualifiers( $2 ); }
1910        ;
1911
1912type_declaration_specifier:
1913        type_type_specifier
1914        | declaration_qualifier_list type_type_specifier
1915                { $$ = $2->addQualifiers( $1 ); }
1916        | type_declaration_specifier storage_class                      // remaining OBSOLESCENT (see 2)
1917                { $$ = $1->addQualifiers( $2 ); }
1918        | type_declaration_specifier storage_class type_qualifier_list
1919                { $$ = $1->addQualifiers( $2 )->addQualifiers( $3 ); }
1920        ;
1921
1922type_type_specifier:                                                                    // typedef types
1923        type_name
1924        | type_qualifier_list type_name
1925                { $$ = $2->addQualifiers( $1 ); }
1926        | type_type_specifier type_qualifier
1927                { $$ = $1->addQualifiers( $2 ); }
1928        ;
1929
1930type_name:
1931        TYPEDEFname
1932                { $$ = DeclarationNode::newFromTypedef( $1 ); }
1933        | '.' TYPEDEFname
1934                { $$ = DeclarationNode::newQualifiedType( DeclarationNode::newFromGlobalScope(), DeclarationNode::newFromTypedef( $2 ) ); }
1935        | type_name '.' TYPEDEFname
1936                { $$ = DeclarationNode::newQualifiedType( $1, DeclarationNode::newFromTypedef( $3 ) ); }
1937        | typegen_name
1938        | '.' typegen_name
1939                { $$ = DeclarationNode::newQualifiedType( DeclarationNode::newFromGlobalScope(), $2 ); }
1940        | type_name '.' typegen_name
1941                { $$ = DeclarationNode::newQualifiedType( $1, $3 ); }
1942        ;
1943
1944typegen_name:                                                                                   // CFA
1945        TYPEGENname
1946                { $$ = DeclarationNode::newFromTypeGen( $1, nullptr ); }
1947        | TYPEGENname '(' ')'
1948                { $$ = DeclarationNode::newFromTypeGen( $1, nullptr ); }
1949        | TYPEGENname '(' type_list ')'
1950                { $$ = DeclarationNode::newFromTypeGen( $1, $3 ); }
1951        ;
1952
1953elaborated_type:                                                                                // struct, union, enum
1954        aggregate_type
1955        | enum_type
1956        ;
1957
1958elaborated_type_nobody:                                                                 // struct, union, enum - {...}
1959        aggregate_type_nobody
1960        | enum_type_nobody
1961        ;
1962
1963fred:
1964        // empty
1965                { yyy = false; }
1966        ;
1967
1968aggregate_type:                                                                                 // struct, union
1969        aggregate_key attribute_list_opt
1970                { forall = false; }                                                             // reset
1971          '{' field_declaration_list_opt '}' type_parameters_opt
1972                { $$ = DeclarationNode::newAggregate( $1, nullptr, $7, $5, true )->addQualifiers( $2 ); }
1973        | aggregate_key attribute_list_opt no_attr_identifier fred
1974                {
1975                        typedefTable.makeTypedef( *$3, forall || typedefTable.getEnclForall() ? TYPEGENname : TYPEDEFname ); // create typedef
1976                        forall = false;                                                         // reset
1977                }
1978          '{' field_declaration_list_opt '}' type_parameters_opt
1979                { $$ = DeclarationNode::newAggregate( $1, $3, $9, $7, true )->addQualifiers( $2 ); }
1980        | aggregate_key attribute_list_opt type_name fred
1981                {
1982                        // for type_name can be a qualified type name S.T, in which case only the last name in the chain needs a typedef (other names in the chain should already have one)
1983                        typedefTable.makeTypedef( *$3->type->leafName(), forall || typedefTable.getEnclForall() ? TYPEGENname : TYPEDEFname ); // create typedef
1984                        forall = false;                                                         // reset
1985                }
1986          '{' field_declaration_list_opt '}' type_parameters_opt
1987                { $$ = DeclarationNode::newAggregate( $1, $3->type->symbolic.name, $9, $7, true )->addQualifiers( $2 ); }
1988        | aggregate_type_nobody
1989        ;
1990
1991type_parameters_opt:
1992        // empty
1993                { $$ = nullptr; }                                                               %prec '}'
1994        | '(' type_list ')'
1995                { $$ = $2; }
1996        ;
1997
1998aggregate_type_nobody:                                                                  // struct, union - {...}
1999        aggregate_key attribute_list_opt no_attr_identifier fred
2000                {
2001                        typedefTable.makeTypedef( *$3, forall || typedefTable.getEnclForall() ? TYPEGENname : TYPEDEFname );
2002                        forall = false;                                                         // reset
2003                        $$ = DeclarationNode::newAggregate( $1, $3, nullptr, nullptr, false )->addQualifiers( $2 );
2004                }
2005        | aggregate_key attribute_list_opt type_name fred
2006                {
2007                        forall = false;                                                         // reset
2008                        // Create new generic declaration with same name as previous forward declaration, where the IDENTIFIER is
2009                        // switched to a TYPEGENname. Link any generic arguments from typegen_name to new generic declaration and
2010                        // delete newFromTypeGen.
2011                        $$ = DeclarationNode::newAggregate( $1, $3->type->symbolic.name, $3->type->symbolic.actuals, nullptr, false )->addQualifiers( $2 );
2012                        $3->type->symbolic.name = nullptr;
2013                        $3->type->symbolic.actuals = nullptr;
2014                        delete $3;
2015                }
2016        ;
2017
2018aggregate_key:
2019        STRUCT
2020                { yyy = true; $$ = DeclarationNode::Struct; }
2021        | UNION
2022                { yyy = true; $$ = DeclarationNode::Union; }
2023        | EXCEPTION
2024                { yyy = true; $$ = DeclarationNode::Exception; }
2025        | COROUTINE
2026                { yyy = true; $$ = DeclarationNode::Coroutine; }
2027        | MONITOR
2028                { yyy = true; $$ = DeclarationNode::Monitor; }
2029        | THREAD
2030                { yyy = true; $$ = DeclarationNode::Thread; }
2031        ;
2032
2033field_declaration_list_opt:
2034        // empty
2035                { $$ = nullptr; }
2036        | field_declaration_list_opt field_declaration
2037                { $$ = $1 ? $1->appendList( $2 ) : $2; }
2038        ;
2039
2040field_declaration:
2041        type_specifier field_declaring_list_opt ';'
2042                { $$ = fieldDecl( $1, $2 ); }
2043        | EXTENSION type_specifier field_declaring_list_opt ';' // GCC
2044                { $$ = fieldDecl( $2, $3 ); distExt( $$ ); }
2045        | INLINE type_specifier field_abstract_list_opt ';'     // CFA
2046                {
2047                        if ( ! $3 ) {                                                           // field declarator ?
2048                                $3 = DeclarationNode::newName( nullptr );
2049                        } // if
2050                        $3->inLine = true;
2051                        $$ = distAttr( $2, $3 );                                        // mark all fields in list
2052                        distInl( $3 );
2053                }
2054        | typedef_declaration ';'                                                       // CFA
2055        | cfa_field_declaring_list ';'                                          // CFA, new style field declaration
2056        | EXTENSION cfa_field_declaring_list ';'                        // GCC
2057                { distExt( $2 ); $$ = $2; }                                             // mark all fields in list
2058        | INLINE cfa_field_abstract_list ';'                            // CFA, new style field declaration
2059                { $$ = $2; }                                                                    // mark all fields in list
2060        | cfa_typedef_declaration ';'                                           // CFA
2061        | static_assert                                                                         // C11
2062        ;
2063
2064field_declaring_list_opt:
2065        // empty
2066                { $$ = nullptr; }
2067        | field_declarator
2068        | field_declaring_list_opt ',' attribute_list_opt field_declarator
2069                { $$ = $1->appendList( $4->addQualifiers( $3 ) ); }
2070        ;
2071
2072field_declarator:
2073        bit_subrange_size                                                                       // C special case, no field name
2074                { $$ = DeclarationNode::newBitfield( $1 ); }
2075        | variable_declarator bit_subrange_size_opt
2076                // A semantic check is required to ensure bit_subrange only appears on integral types.
2077                { $$ = $1->addBitfield( $2 ); }
2078        | variable_type_redeclarator bit_subrange_size_opt
2079                // A semantic check is required to ensure bit_subrange only appears on integral types.
2080                { $$ = $1->addBitfield( $2 ); }
2081        ;
2082
2083field_abstract_list_opt:
2084        // empty
2085                { $$ = nullptr; }
2086        | field_abstract
2087        | field_abstract_list_opt ',' attribute_list_opt field_abstract
2088                { $$ = $1->appendList( $4->addQualifiers( $3 ) ); }
2089        ;
2090
2091field_abstract:
2092                //      no bit fields
2093        variable_abstract_declarator
2094        ;
2095
2096cfa_field_declaring_list:                                                               // CFA, new style field declaration
2097        // bit-fields are handled by C declarations
2098        cfa_abstract_declarator_tuple no_attr_identifier_or_type_name
2099                { $$ = $1->addName( $2 ); }
2100        | cfa_field_declaring_list ',' no_attr_identifier_or_type_name
2101                { $$ = $1->appendList( $1->cloneType( $3 ) ); }
2102        ;
2103
2104cfa_field_abstract_list:                                                                // CFA, new style field declaration
2105        // bit-fields are handled by C declarations
2106        cfa_abstract_declarator_tuple
2107        | cfa_field_abstract_list ','
2108                { $$ = $1->appendList( $1->cloneType( 0 ) ); }
2109        ;
2110
2111bit_subrange_size_opt:
2112        // empty
2113                { $$ = nullptr; }
2114        | bit_subrange_size
2115        ;
2116
2117bit_subrange_size:
2118        ':' constant_expression
2119                { $$ = $2; }
2120        ;
2121
2122enum_type:                                                                                              // enum
2123        ENUM attribute_list_opt '{' enumerator_list comma_opt '}'
2124                { $$ = DeclarationNode::newEnum( nullptr, $4, true )->addQualifiers( $2 ); }
2125        | ENUM attribute_list_opt no_attr_identifier
2126                { typedefTable.makeTypedef( *$3 ); }
2127          '{' enumerator_list comma_opt '}'
2128                { $$ = DeclarationNode::newEnum( $3, $6, true )->addQualifiers( $2 ); }
2129        | ENUM attribute_list_opt type_name
2130          '{' enumerator_list comma_opt '}'
2131                { $$ = DeclarationNode::newEnum( $3->type->symbolic.name, $5, true )->addQualifiers( $2 ); }
2132        | enum_type_nobody
2133        ;
2134
2135enum_type_nobody:                                                                               // enum - {...}
2136        ENUM attribute_list_opt no_attr_identifier
2137                {
2138                        typedefTable.makeTypedef( *$3 );
2139                        $$ = DeclarationNode::newEnum( $3, 0, false )->addQualifiers( $2 );
2140                }
2141        | ENUM attribute_list_opt type_name
2142                {
2143                        typedefTable.makeTypedef( *$3->type->symbolic.name );
2144                        $$ = DeclarationNode::newEnum( $3->type->symbolic.name, 0, false )->addQualifiers( $2 );
2145                }
2146        ;
2147
2148enumerator_list:
2149        no_attr_identifier_or_type_name enumerator_value_opt
2150                { $$ = DeclarationNode::newEnumConstant( $1, $2 ); }
2151        | enumerator_list ',' no_attr_identifier_or_type_name enumerator_value_opt
2152                { $$ = $1->appendList( DeclarationNode::newEnumConstant( $3, $4 ) ); }
2153        ;
2154
2155enumerator_value_opt:
2156        // empty
2157                { $$ = nullptr; }
2158        | '=' constant_expression
2159                { $$ = $2; }
2160        ;
2161
2162cfa_parameter_ellipsis_list_opt:                                                        // CFA, abstract + real
2163        // empty
2164                { $$ = DeclarationNode::newBasicType( DeclarationNode::Void ); }
2165        | ELLIPSIS
2166                { $$ = nullptr; }
2167        | cfa_abstract_parameter_list
2168        | cfa_parameter_list
2169        | cfa_parameter_list pop ',' push cfa_abstract_parameter_list
2170                { $$ = $1->appendList( $5 ); }
2171        | cfa_abstract_parameter_list pop ',' push ELLIPSIS
2172                { $$ = $1->addVarArgs(); }
2173        | cfa_parameter_list pop ',' push ELLIPSIS
2174                { $$ = $1->addVarArgs(); }
2175        ;
2176
2177cfa_parameter_list:                                                                             // CFA
2178                // To obtain LR(1) between cfa_parameter_list and cfa_abstract_tuple, the last cfa_abstract_parameter_list is
2179                // factored out from cfa_parameter_list, flattening the rules to get lookahead to the ']'.
2180        cfa_parameter_declaration
2181        | cfa_abstract_parameter_list pop ',' push cfa_parameter_declaration
2182                { $$ = $1->appendList( $5 ); }
2183        | cfa_parameter_list pop ',' push cfa_parameter_declaration
2184                { $$ = $1->appendList( $5 ); }
2185        | cfa_parameter_list pop ',' push cfa_abstract_parameter_list pop ',' push cfa_parameter_declaration
2186                { $$ = $1->appendList( $5 )->appendList( $9 ); }
2187        ;
2188
2189cfa_abstract_parameter_list:                                                    // CFA, new & old style abstract
2190        cfa_abstract_parameter_declaration
2191        | cfa_abstract_parameter_list pop ',' push cfa_abstract_parameter_declaration
2192                { $$ = $1->appendList( $5 ); }
2193        ;
2194
2195parameter_type_list_opt:
2196        // empty
2197                { $$ = nullptr; }
2198        | ELLIPSIS
2199                { $$ = nullptr; }
2200        | parameter_list
2201        | parameter_list pop ',' push ELLIPSIS
2202                { $$ = $1->addVarArgs(); }
2203        ;
2204
2205parameter_list:                                                                                 // abstract + real
2206        abstract_parameter_declaration
2207        | parameter_declaration
2208        | parameter_list pop ',' push abstract_parameter_declaration
2209                { $$ = $1->appendList( $5 ); }
2210        | parameter_list pop ',' push parameter_declaration
2211                { $$ = $1->appendList( $5 ); }
2212        ;
2213
2214// Provides optional identifier names (abstract_declarator/variable_declarator), no initialization, different semantics
2215// for typedef name by using type_parameter_redeclarator instead of typedef_redeclarator, and function prototypes.
2216
2217cfa_parameter_declaration:                                                              // CFA, new & old style parameter declaration
2218        parameter_declaration
2219        | cfa_identifier_parameter_declarator_no_tuple identifier_or_type_name default_initialize_opt
2220                { $$ = $1->addName( $2 ); }
2221        | cfa_abstract_tuple identifier_or_type_name default_initialize_opt
2222                // To obtain LR(1), these rules must be duplicated here (see cfa_abstract_declarator).
2223                { $$ = $1->addName( $2 ); }
2224        | type_qualifier_list cfa_abstract_tuple identifier_or_type_name default_initialize_opt
2225                { $$ = $2->addName( $3 )->addQualifiers( $1 ); }
2226        | cfa_function_specifier
2227        ;
2228
2229cfa_abstract_parameter_declaration:                                             // CFA, new & old style parameter declaration
2230        abstract_parameter_declaration
2231        | cfa_identifier_parameter_declarator_no_tuple
2232        | cfa_abstract_tuple
2233                // To obtain LR(1), these rules must be duplicated here (see cfa_abstract_declarator).
2234        | type_qualifier_list cfa_abstract_tuple
2235                { $$ = $2->addQualifiers( $1 ); }
2236        | cfa_abstract_function
2237        ;
2238
2239parameter_declaration:
2240                // No SUE declaration in parameter list.
2241        declaration_specifier_nobody identifier_parameter_declarator default_initialize_opt
2242                { $$ = $2->addType( $1 )->addInitializer( $3 ? new InitializerNode( $3 ) : nullptr ); }
2243        | declaration_specifier_nobody type_parameter_redeclarator default_initialize_opt
2244                { $$ = $2->addType( $1 )->addInitializer( $3 ? new InitializerNode( $3 ) : nullptr ); }
2245        ;
2246
2247abstract_parameter_declaration:
2248        declaration_specifier_nobody default_initialize_opt
2249                { $$ = $1->addInitializer( $2 ? new InitializerNode( $2 ) : nullptr ); }
2250        | declaration_specifier_nobody abstract_parameter_declarator default_initialize_opt
2251                { $$ = $2->addType( $1 )->addInitializer( $3 ? new InitializerNode( $3 ) : nullptr ); }
2252        ;
2253
2254// ISO/IEC 9899:1999 Section 6.9.1(6) : "An identifier declared as a typedef name shall not be redeclared as a
2255// parameter." Because the scope of the K&R-style parameter-list sees the typedef first, the following is based only on
2256// identifiers.  The ANSI-style parameter-list can redefine a typedef name.
2257
2258identifier_list:                                                                                // K&R-style parameter list => no types
2259        no_attr_identifier
2260                { $$ = DeclarationNode::newName( $1 ); }
2261        | identifier_list ',' no_attr_identifier
2262                { $$ = $1->appendList( DeclarationNode::newName( $3 ) ); }
2263        ;
2264
2265identifier_or_type_name:
2266        identifier
2267        | TYPEDEFname
2268        | TYPEGENname
2269        ;
2270
2271no_attr_identifier_or_type_name:
2272        no_attr_identifier
2273        | TYPEDEFname
2274        | TYPEGENname
2275        ;
2276
2277type_no_function:                                                                               // sizeof, alignof, cast (constructor)
2278        cfa_abstract_declarator_tuple                                           // CFA
2279        | type_specifier
2280        | type_specifier abstract_declarator
2281                { $$ = $2->addType( $1 ); }
2282        ;
2283
2284type:                                                                                                   // typeof, assertion
2285        type_no_function
2286        | cfa_abstract_function                                                         // CFA
2287        ;
2288
2289initializer_opt:
2290        // empty
2291                { $$ = nullptr; }
2292        | '=' initializer
2293                { $$ = $2; }
2294        | '=' VOID
2295                { $$ = new InitializerNode( true ); }
2296        | ATassign initializer
2297                { $$ = $2->set_maybeConstructed( false ); }
2298        ;
2299
2300initializer:
2301        assignment_expression                                           { $$ = new InitializerNode( $1 ); }
2302        | '{' initializer_list_opt comma_opt '}'        { $$ = new InitializerNode( $2, true ); }
2303        ;
2304
2305initializer_list_opt:
2306        // empty
2307                { $$ = nullptr; }
2308        | initializer
2309        | designation initializer                                       { $$ = $2->set_designators( $1 ); }
2310        | initializer_list_opt ',' initializer          { $$ = (InitializerNode *)( $1->set_last( $3 ) ); }
2311        | initializer_list_opt ',' designation initializer
2312                { $$ = (InitializerNode *)( $1->set_last( $4->set_designators( $3 ) ) ); }
2313        ;
2314
2315// There is an unreconcileable parsing problem between C99 and CFA with respect to designators. The problem is use of
2316// '=' to separator the designator from the initializer value, as in:
2317//
2318//              int x[10] = { [1] = 3 };
2319//
2320// The string "[1] = 3" can be parsed as a designator assignment or a tuple assignment.  To disambiguate this case, CFA
2321// changes the syntax from "=" to ":" as the separator between the designator and initializer. GCC does uses ":" for
2322// field selection. The optional use of the "=" in GCC, or in this case ":", cannot be supported either due to
2323// shift/reduce conflicts
2324
2325designation:
2326        designator_list ':'                                                                     // C99, CFA uses ":" instead of "="
2327        | no_attr_identifier ':'                                                        // GCC, field name
2328                { $$ = new ExpressionNode( build_varref( $1 ) ); }
2329        ;
2330
2331designator_list:                                                                                // C99
2332        designator
2333        | designator_list designator
2334                { $$ = (ExpressionNode *)( $1->set_last( $2 ) ); }
2335        //| designator_list designator                                          { $$ = new ExpressionNode( $1, $2 ); }
2336        ;
2337
2338designator:
2339        '.' no_attr_identifier                                                          // C99, field name
2340                { $$ = new ExpressionNode( build_varref( $2 ) ); }
2341        | '[' push assignment_expression pop ']'                        // C99, single array element
2342                // assignment_expression used instead of constant_expression because of shift/reduce conflicts with tuple.
2343                { $$ = $3; }
2344        | '[' push subrange pop ']'                                                     // CFA, multiple array elements
2345                { $$ = $3; }
2346        | '[' push constant_expression ELLIPSIS constant_expression pop ']' // GCC, multiple array elements
2347                { $$ = new ExpressionNode( new RangeExpr( maybeMoveBuild< Expression >( $3 ), maybeMoveBuild< Expression >( $5 ) ) ); }
2348        | '.' '[' push field_name_list pop ']'                          // CFA, tuple field selector
2349                { $$ = $4; }
2350        ;
2351
2352// The CFA type system is based on parametric polymorphism, the ability to declare functions with type parameters,
2353// rather than an object-oriented type system. This required four groups of extensions:
2354//
2355// Overloading: function, data, and operator identifiers may be overloaded.
2356//
2357// Type declarations: "type" is used to generate new types for declaring objects. Similarly, "dtype" is used for object
2358//     and incomplete types, and "ftype" is used for function types. Type declarations with initializers provide
2359//     definitions of new types. Type declarations with storage class "extern" provide opaque types.
2360//
2361// Polymorphic functions: A forall clause declares a type parameter. The corresponding argument is inferred at the call
2362//     site. A polymorphic function is not a template; it is a function, with an address and a type.
2363//
2364// Specifications and Assertions: Specifications are collections of declarations parameterized by one or more
2365//     types. They serve many of the purposes of abstract classes, and specification hierarchies resemble subclass
2366//     hierarchies. Unlike classes, they can define relationships between types.  Assertions declare that a type or
2367//     types provide the operations declared by a specification.  Assertions are normally used to declare requirements
2368//     on type arguments of polymorphic functions.
2369
2370type_parameter_list:                                                                    // CFA
2371        type_parameter
2372        | type_parameter_list ',' type_parameter
2373                { $$ = $1->appendList( $3 ); }
2374        ;
2375
2376type_initializer_opt:                                                                   // CFA
2377        // empty
2378                { $$ = nullptr; }
2379        | '=' type
2380                { $$ = $2; }
2381        ;
2382
2383type_parameter:                                                                                 // CFA
2384        type_class no_attr_identifier_or_type_name
2385                { typedefTable.addToScope( *$2, TYPEDEFname, "9" ); }
2386          type_initializer_opt assertion_list_opt
2387                { $$ = DeclarationNode::newTypeParam( $1, $2 )->addTypeInitializer( $4 )->addAssertions( $5 ); }
2388        | type_specifier identifier_parameter_declarator
2389        | assertion_list
2390                { $$ = DeclarationNode::newTypeParam( DeclarationNode::Dtype, new string( DeclarationNode::anonymous.newName() ) )->addAssertions( $1 ); }
2391        ;
2392
2393type_class:                                                                                             // CFA
2394        OTYPE
2395                { $$ = DeclarationNode::Otype; }
2396        | DTYPE
2397                { $$ = DeclarationNode::Dtype; }
2398        | FTYPE
2399                { $$ = DeclarationNode::Ftype; }
2400        | TTYPE
2401                { $$ = DeclarationNode::Ttype; }
2402        ;
2403
2404assertion_list_opt:                                                                             // CFA
2405        // empty
2406                { $$ = nullptr; }
2407        | assertion_list
2408        ;
2409
2410assertion_list:                                                                                 // CFA
2411        assertion
2412        | assertion_list assertion
2413                { $$ = $1 ? $1->appendList( $2 ) : $2; }
2414        ;
2415
2416assertion:                                                                                              // CFA
2417        '|' no_attr_identifier_or_type_name '(' type_list ')'
2418                { $$ = DeclarationNode::newTraitUse( $2, $4 ); }
2419        | '|' '{' push trait_declaration_list pop '}'
2420                { $$ = $4; }
2421        // | '|' '(' push type_parameter_list pop ')' '{' push trait_declaration_list pop '}' '(' type_list ')'
2422        //      { SemanticError( yylloc, "Generic data-type assertion is currently unimplemented." ); $$ = nullptr; }
2423        ;
2424
2425type_list:                                                                                              // CFA
2426        type
2427                { $$ = new ExpressionNode( new TypeExpr( maybeMoveBuildType( $1 ) ) ); }
2428        | assignment_expression
2429                { SemanticError( yylloc, toString("Expression generic parameters are currently unimplemented: ", $1->build()) ); $$ = nullptr; }
2430        | type_list ',' type
2431                { $$ = (ExpressionNode *)( $1->set_last( new ExpressionNode( new TypeExpr( maybeMoveBuildType( $3 ) ) ) ) ); }
2432        | type_list ',' assignment_expression
2433                { SemanticError( yylloc, toString("Expression generic parameters are currently unimplemented: ", $3->build()) ); $$ = nullptr; }
2434                // { $$ = (ExpressionNode *)( $1->set_last( $3 )); }
2435        ;
2436
2437type_declaring_list:                                                                    // CFA
2438        OTYPE type_declarator
2439                { $$ = $2; }
2440        | storage_class_list OTYPE type_declarator
2441                { $$ = $3->addQualifiers( $1 ); }
2442        | type_declaring_list ',' type_declarator
2443                { $$ = $1->appendList( $3->copySpecifiers( $1 ) ); }
2444        ;
2445
2446type_declarator:                                                                                // CFA
2447        type_declarator_name assertion_list_opt
2448                { $$ = $1->addAssertions( $2 ); }
2449        | type_declarator_name assertion_list_opt '=' type
2450                { $$ = $1->addAssertions( $2 )->addType( $4 ); }
2451        ;
2452
2453type_declarator_name:                                                                   // CFA
2454        no_attr_identifier_or_type_name
2455                {
2456                        typedefTable.addToEnclosingScope( *$1, TYPEDEFname, "10" );
2457                        $$ = DeclarationNode::newTypeDecl( $1, 0 );
2458                }
2459        | no_attr_identifier_or_type_name '(' type_parameter_list ')'
2460                {
2461                        typedefTable.addToEnclosingScope( *$1, TYPEGENname, "11" );
2462                        $$ = DeclarationNode::newTypeDecl( $1, $3 );
2463                }
2464        ;
2465
2466trait_specifier:                                                                                // CFA
2467        TRAIT no_attr_identifier_or_type_name '(' type_parameter_list ')' '{' '}'
2468                { $$ = DeclarationNode::newTrait( $2, $4, 0 ); }
2469        | TRAIT no_attr_identifier_or_type_name '(' type_parameter_list ')' '{' push trait_declaration_list pop '}'
2470                { $$ = DeclarationNode::newTrait( $2, $4, $8 ); }
2471        ;
2472
2473trait_declaration_list:                                                                 // CFA
2474        trait_declaration
2475        | trait_declaration_list pop push trait_declaration
2476                { $$ = $1->appendList( $4 ); }
2477        ;
2478
2479trait_declaration:                                                                              // CFA
2480        cfa_trait_declaring_list ';'
2481        | trait_declaring_list ';'
2482        ;
2483
2484cfa_trait_declaring_list:                                                               // CFA
2485        cfa_variable_specifier
2486        | cfa_function_specifier
2487        | cfa_trait_declaring_list pop ',' push identifier_or_type_name
2488                { $$ = $1->appendList( $1->cloneType( $5 ) ); }
2489        ;
2490
2491trait_declaring_list:                                                                   // CFA
2492        type_specifier declarator
2493                { $$ = $2->addType( $1 ); }
2494        | trait_declaring_list pop ',' push declarator
2495                { $$ = $1->appendList( $1->cloneBaseType( $5 ) ); }
2496        ;
2497
2498//***************************** EXTERNAL DEFINITIONS *****************************
2499
2500translation_unit:
2501        // empty, input file
2502        | external_definition_list
2503                { parseTree = parseTree ? parseTree->appendList( $1 ) : $1;     }
2504        ;
2505
2506external_definition_list:
2507        push external_definition pop
2508                { $$ = $2; }
2509        | external_definition_list push external_definition pop
2510                { $$ = $1 ? $1->appendList( $3 ) : $3; }
2511        ;
2512
2513external_definition_list_opt:
2514        // empty
2515                { $$ = nullptr; }
2516        | external_definition_list
2517        ;
2518
2519up:
2520                { typedefTable.up( forall ); forall = false; }
2521        ;
2522
2523down:
2524                { typedefTable.down(); }
2525        ;
2526
2527external_definition:
2528        declaration
2529        | external_function_definition
2530        | EXTENSION external_definition                                         // GCC, multiple __extension__ allowed, meaning unknown
2531                {
2532                        distExt( $2 );                                                          // mark all fields in list
2533                        $$ = $2;
2534                }
2535        | ASM '(' string_literal ')' ';'                                        // GCC, global assembler statement
2536                {
2537                        $$ = DeclarationNode::newAsmStmt( new StatementNode( build_asm( false, $3, 0 ) ) );
2538                }
2539        | EXTERN STRINGliteral                                                          // C++-style linkage specifier
2540                {
2541                        linkageStack.push( linkage );                           // handle nested extern "C"/"Cforall"
2542                        linkage = LinkageSpec::linkageUpdate( yylloc, linkage, $2 );
2543                }
2544          '{' up external_definition_list_opt down '}'
2545                {
2546                        linkage = linkageStack.top();
2547                        linkageStack.pop();
2548                        $$ = $6;
2549                }
2550        | type_qualifier_list
2551                {
2552                        if ( $1->type->qualifiers.val ) { SemanticError( yylloc, "CV qualifiers cannot be distributed; only storage-class and forall qualifiers." ); }
2553                        if ( $1->type->forall ) forall = true;          // remember generic type
2554                }
2555          '{' up external_definition_list_opt down '}'          // CFA, namespace
2556                {
2557                        distQual( $5, $1 );
2558                        forall = false;
2559                        $$ = $5;
2560                }
2561        | declaration_qualifier_list
2562                {
2563                        if ( $1->type && $1->type->qualifiers.val ) { SemanticError( yylloc, "CV qualifiers cannot be distributed; only storage-class and forall qualifiers." ); }
2564                        if ( $1->type && $1->type->forall ) forall = true; // remember generic type
2565                }
2566          '{' up external_definition_list_opt down '}'          // CFA, namespace
2567                {
2568                        distQual( $5, $1 );
2569                        forall = false;
2570                        $$ = $5;
2571                }
2572        | declaration_qualifier_list type_qualifier_list
2573                {
2574                        if ( ($1->type && $1->type->qualifiers.val) || $2->type->qualifiers.val ) { SemanticError( yylloc, "CV qualifiers cannot be distributed; only storage-class and forall qualifiers." ); }
2575                        if ( ($1->type && $1->type->forall) || $2->type->forall ) forall = true; // remember generic type
2576                }
2577          '{' up external_definition_list_opt down '}'          // CFA, namespace
2578                {
2579                        distQual( $6, $1->addQualifiers( $2 ) );
2580                        forall = false;
2581                        $$ = $6;
2582                }
2583        ;
2584
2585external_function_definition:
2586        function_definition
2587                // These rules are a concession to the "implicit int" type_specifier because there is a significant amount of
2588                // legacy code with global functions missing the type-specifier for the return type, and assuming "int".
2589                // Parsing is possible because function_definition does not appear in the context of an expression (nested
2590                // functions preclude this concession, i.e., all nested function must have a return type). A function prototype
2591                // declaration must still have a type_specifier.  OBSOLESCENT (see 1)
2592        | function_declarator compound_statement
2593                { $$ = $1->addFunctionBody( $2 ); }
2594        | KR_function_declarator KR_parameter_list_opt compound_statement
2595                { $$ = $1->addOldDeclList( $2 )->addFunctionBody( $3 ); }
2596        ;
2597
2598with_clause_opt:
2599        // empty
2600                { $$ = nullptr; forall = false; }
2601        | WITH '(' tuple_expression_list ')'
2602                { $$ = $3; forall = false; }
2603        ;
2604
2605function_definition:
2606        cfa_function_declaration with_clause_opt compound_statement     // CFA
2607                {
2608                        // Add the function body to the last identifier in the function definition list, i.e., foo3:
2609                        //   [const double] foo1(), foo2( int ), foo3( double ) { return 3.0; }
2610                        $1->get_last()->addFunctionBody( $3, $2 );
2611                        $$ = $1;
2612                }
2613        | declaration_specifier function_declarator with_clause_opt compound_statement
2614                {
2615                        rebindForall( $1, $2 );
2616                        $$ = $2->addFunctionBody( $4, $3 )->addType( $1 );
2617                }
2618        | declaration_specifier variable_type_redeclarator with_clause_opt compound_statement
2619                {
2620                        rebindForall( $1, $2 );
2621                        $$ = $2->addFunctionBody( $4, $3 )->addType( $1 );
2622                }
2623                // handles default int return type, OBSOLESCENT (see 1)
2624        | type_qualifier_list function_declarator with_clause_opt compound_statement
2625                { $$ = $2->addFunctionBody( $4, $3 )->addQualifiers( $1 ); }
2626                // handles default int return type, OBSOLESCENT (see 1)
2627        | declaration_qualifier_list function_declarator with_clause_opt compound_statement
2628                { $$ = $2->addFunctionBody( $4, $3 )->addQualifiers( $1 ); }
2629                // handles default int return type, OBSOLESCENT (see 1)
2630        | declaration_qualifier_list type_qualifier_list function_declarator with_clause_opt compound_statement
2631                { $$ = $3->addFunctionBody( $5, $4 )->addQualifiers( $2 )->addQualifiers( $1 ); }
2632
2633                // Old-style K&R function definition, OBSOLESCENT (see 4)
2634        | declaration_specifier KR_function_declarator KR_parameter_list_opt with_clause_opt compound_statement
2635                {
2636                        rebindForall( $1, $2 );
2637                        $$ = $2->addOldDeclList( $3 )->addFunctionBody( $5, $4 )->addType( $1 );
2638                }
2639                // handles default int return type, OBSOLESCENT (see 1)
2640        | type_qualifier_list KR_function_declarator KR_parameter_list_opt with_clause_opt compound_statement
2641                { $$ = $2->addOldDeclList( $3 )->addFunctionBody( $5, $4 )->addQualifiers( $1 ); }
2642                // handles default int return type, OBSOLESCENT (see 1)
2643        | declaration_qualifier_list KR_function_declarator KR_parameter_list_opt with_clause_opt compound_statement
2644                { $$ = $2->addOldDeclList( $3 )->addFunctionBody( $5, $4 )->addQualifiers( $1 ); }
2645                // handles default int return type, OBSOLESCENT (see 1)
2646        | declaration_qualifier_list type_qualifier_list KR_function_declarator KR_parameter_list_opt with_clause_opt compound_statement
2647                { $$ = $3->addOldDeclList( $4 )->addFunctionBody( $6, $5 )->addQualifiers( $2 )->addQualifiers( $1 ); }
2648        ;
2649
2650declarator:
2651        variable_declarator
2652        | variable_type_redeclarator
2653        | function_declarator
2654        ;
2655
2656subrange:
2657        constant_expression '~' constant_expression                     // CFA, integer subrange
2658                { $$ = new ExpressionNode( new RangeExpr( maybeMoveBuild< Expression >( $1 ), maybeMoveBuild< Expression >( $3 ) ) ); }
2659        ;
2660
2661asm_name_opt:                                                                                   // GCC
2662        // empty
2663                { $$ = nullptr; }
2664        | ASM '(' string_literal ')' attribute_list_opt
2665                {
2666                        DeclarationNode * name = new DeclarationNode();
2667                        name->asmName = $3;
2668                        $$ = name->addQualifiers( $5 );
2669                }
2670        ;
2671
2672attribute_list_opt:                                                                             // GCC
2673        // empty
2674                { $$ = nullptr; }
2675        | attribute_list
2676        ;
2677
2678attribute_list:                                                                                 // GCC
2679        attribute
2680        | attribute_list attribute
2681                { $$ = $2->addQualifiers( $1 ); }
2682        ;
2683
2684attribute:                                                                                              // GCC
2685        ATTRIBUTE '(' '(' attribute_name_list ')' ')'
2686                { $$ = $4; }
2687        ;
2688
2689attribute_name_list:                                                                    // GCC
2690        attribute_name
2691        | attribute_name_list ',' attribute_name
2692                { $$ = $3->addQualifiers( $1 ); }
2693        ;
2694
2695attribute_name:                                                                                 // GCC
2696        // empty
2697                { $$ = nullptr; }
2698        | attr_name
2699                { $$ = DeclarationNode::newAttribute( $1 ); }
2700        | attr_name '(' argument_expression_list ')'
2701                { $$ = DeclarationNode::newAttribute( $1, $3 ); }
2702        ;
2703
2704attr_name:                                                                                              // GCC
2705        IDENTIFIER
2706        | quasi_keyword
2707        | TYPEDEFname
2708        | TYPEGENname
2709        | FALLTHROUGH
2710                { $$ = Token{ new string( "fallthrough" ), { nullptr, -1 } }; }
2711        | CONST
2712                { $$ = Token{ new string( "__const__" ), { nullptr, -1 } }; }
2713        ;
2714
2715// ============================================================================
2716// The following sections are a series of grammar patterns used to parse declarators. Multiple patterns are necessary
2717// because the type of an identifier in wrapped around the identifier in the same form as its usage in an expression, as
2718// in:
2719//
2720//              int (*f())[10] { ... };
2721//              ... (*f())[3] += 1;             // definition mimics usage
2722//
2723// Because these patterns are highly recursive, changes at a lower level in the recursion require copying some or all of
2724// the pattern. Each of these patterns has some subtle variation to ensure correct syntax in a particular context.
2725// ============================================================================
2726
2727// ----------------------------------------------------------------------------
2728// The set of valid declarators before a compound statement for defining a function is less than the set of declarators
2729// to define a variable or function prototype, e.g.:
2730//
2731//              valid declaration               invalid definition
2732//              -----------------               ------------------
2733//              int f;                                  int f {}
2734//              int *f;                                 int *f {}
2735//              int f[10];                              int f[10] {}
2736//              int (*f)(int);                  int (*f)(int) {}
2737//
2738// To preclude this syntactic anomaly requires separating the grammar rules for variable and function declarators, hence
2739// variable_declarator and function_declarator.
2740// ----------------------------------------------------------------------------
2741
2742// This pattern parses a declaration of a variable that is not redefining a typedef name. The pattern precludes
2743// declaring an array of functions versus a pointer to an array of functions.
2744
2745variable_declarator:
2746        paren_identifier attribute_list_opt
2747                { $$ = $1->addQualifiers( $2 ); }
2748        | variable_ptr
2749        | variable_array attribute_list_opt
2750                { $$ = $1->addQualifiers( $2 ); }
2751        | variable_function attribute_list_opt
2752                { $$ = $1->addQualifiers( $2 ); }
2753        ;
2754
2755paren_identifier:
2756        identifier
2757                { $$ = DeclarationNode::newName( $1 ); }
2758        | '(' paren_identifier ')'                                                      // redundant parenthesis
2759                { $$ = $2; }
2760        ;
2761
2762variable_ptr:
2763        ptrref_operator variable_declarator
2764                { $$ = $2->addPointer( DeclarationNode::newPointer( 0, $1 ) ); }
2765        | ptrref_operator type_qualifier_list variable_declarator
2766                { $$ = $3->addPointer( DeclarationNode::newPointer( $2, $1 ) ); }
2767        | '(' variable_ptr ')' attribute_list_opt
2768                { $$ = $2->addQualifiers( $4 ); }                               // redundant parenthesis
2769        ;
2770
2771variable_array:
2772        paren_identifier array_dimension
2773                { $$ = $1->addArray( $2 ); }
2774        | '(' variable_ptr ')' array_dimension
2775                { $$ = $2->addArray( $4 ); }
2776        | '(' variable_array ')' multi_array_dimension          // redundant parenthesis
2777                { $$ = $2->addArray( $4 ); }
2778        | '(' variable_array ')'                                                        // redundant parenthesis
2779                { $$ = $2; }
2780        ;
2781
2782variable_function:
2783        '(' variable_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
2784                { $$ = $2->addParamList( $6 ); }
2785        | '(' variable_function ')'                                                     // redundant parenthesis
2786                { $$ = $2; }
2787        ;
2788
2789// This pattern parses a function declarator that is not redefining a typedef name. For non-nested functions, there is
2790// no context where a function definition can redefine a typedef name, i.e., the typedef and function name cannot exist
2791// is the same scope.  The pattern precludes returning arrays and functions versus pointers to arrays and functions.
2792
2793function_declarator:
2794        function_no_ptr attribute_list_opt
2795                { $$ = $1->addQualifiers( $2 ); }
2796        | function_ptr
2797        | function_array attribute_list_opt
2798                { $$ = $1->addQualifiers( $2 ); }
2799        ;
2800
2801function_no_ptr:
2802        paren_identifier '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
2803                { $$ = $1->addParamList( $4 ); }
2804        | '(' function_ptr ')' '(' push parameter_type_list_opt pop ')'
2805                { $$ = $2->addParamList( $6 ); }
2806        | '(' function_no_ptr ')'                                                       // redundant parenthesis
2807                { $$ = $2; }
2808        ;
2809
2810function_ptr:
2811        ptrref_operator function_declarator
2812                { $$ = $2->addPointer( DeclarationNode::newPointer( 0, $1 ) ); }
2813        | ptrref_operator type_qualifier_list function_declarator
2814                { $$ = $3->addPointer( DeclarationNode::newPointer( $2, $1 ) ); }
2815        | '(' function_ptr ')'
2816                { $$ = $2; }
2817        ;
2818
2819function_array:
2820        '(' function_ptr ')' array_dimension
2821                { $$ = $2->addArray( $4 ); }
2822        | '(' function_array ')' multi_array_dimension          // redundant parenthesis
2823                { $$ = $2->addArray( $4 ); }
2824        | '(' function_array ')'                                                        // redundant parenthesis
2825                { $$ = $2; }
2826        ;
2827
2828// This pattern parses an old-style K&R function declarator (OBSOLESCENT, see 4)
2829//
2830//   f( a, b, c ) int a, *b, c[]; {}
2831//
2832// that is not redefining a typedef name (see function_declarator for additional comments). The pattern precludes
2833// returning arrays and functions versus pointers to arrays and functions.
2834
2835KR_function_declarator:
2836        KR_function_no_ptr
2837        | KR_function_ptr
2838        | KR_function_array
2839        ;
2840
2841KR_function_no_ptr:
2842        paren_identifier '(' identifier_list ')'                        // function_declarator handles empty parameter
2843                { $$ = $1->addIdList( $3 ); }
2844        | '(' KR_function_ptr ')' '(' push parameter_type_list_opt pop ')'
2845                { $$ = $2->addParamList( $6 ); }
2846        | '(' KR_function_no_ptr ')'                                            // redundant parenthesis
2847                { $$ = $2; }
2848        ;
2849
2850KR_function_ptr:
2851        ptrref_operator KR_function_declarator
2852                { $$ = $2->addPointer( DeclarationNode::newPointer( 0, $1 ) ); }
2853        | ptrref_operator type_qualifier_list KR_function_declarator
2854                { $$ = $3->addPointer( DeclarationNode::newPointer( $2, $1 ) ); }
2855        | '(' KR_function_ptr ')'
2856                { $$ = $2; }
2857        ;
2858
2859KR_function_array:
2860        '(' KR_function_ptr ')' array_dimension
2861                { $$ = $2->addArray( $4 ); }
2862        | '(' KR_function_array ')' multi_array_dimension       // redundant parenthesis
2863                { $$ = $2->addArray( $4 ); }
2864        | '(' KR_function_array ')'                                                     // redundant parenthesis
2865                { $$ = $2; }
2866        ;
2867
2868// This pattern parses a declaration for a variable or function prototype that redefines a type name, e.g.:
2869//
2870//              typedef int foo;
2871//              {
2872//                 int foo; // redefine typedef name in new scope
2873//              }
2874//
2875// The pattern precludes declaring an array of functions versus a pointer to an array of functions, and returning arrays
2876// and functions versus pointers to arrays and functions.
2877
2878variable_type_redeclarator:
2879        paren_type attribute_list_opt
2880                { $$ = $1->addQualifiers( $2 ); }
2881        | type_ptr
2882        | type_array attribute_list_opt
2883                { $$ = $1->addQualifiers( $2 ); }
2884        | type_function attribute_list_opt
2885                { $$ = $1->addQualifiers( $2 ); }
2886        ;
2887
2888paren_type:
2889        typedef
2890                // hide type name in enclosing scope by variable name
2891                {
2892                        // if ( ! typedefTable.existsCurr( *$1->name ) ) {
2893                                typedefTable.addToEnclosingScope( *$1->name, IDENTIFIER, "ID" );
2894                        // } else {
2895                        //      SemanticError( yylloc, string("'") + *$1->name + "' redeclared as different kind of symbol." ); $$ = nullptr;
2896                        // } // if
2897                }
2898        | '(' paren_type ')'
2899                { $$ = $2; }
2900        ;
2901
2902type_ptr:
2903        ptrref_operator variable_type_redeclarator
2904                { $$ = $2->addPointer( DeclarationNode::newPointer( 0, $1 ) ); }
2905        | ptrref_operator type_qualifier_list variable_type_redeclarator
2906                { $$ = $3->addPointer( DeclarationNode::newPointer( $2, $1 ) ); }
2907        | '(' type_ptr ')' attribute_list_opt
2908                { $$ = $2->addQualifiers( $4 ); }                               // redundant parenthesis
2909        ;
2910
2911type_array:
2912        paren_type array_dimension
2913                { $$ = $1->addArray( $2 ); }
2914        | '(' type_ptr ')' array_dimension
2915                { $$ = $2->addArray( $4 ); }
2916        | '(' type_array ')' multi_array_dimension                      // redundant parenthesis
2917                { $$ = $2->addArray( $4 ); }
2918        | '(' type_array ')'                                                            // redundant parenthesis
2919                { $$ = $2; }
2920        ;
2921
2922type_function:
2923        paren_type '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
2924                { $$ = $1->addParamList( $4 ); }
2925        | '(' type_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
2926                { $$ = $2->addParamList( $6 ); }
2927        | '(' type_function ')'                                                         // redundant parenthesis
2928                { $$ = $2; }
2929        ;
2930
2931// This pattern parses a declaration for a parameter variable of a function prototype or actual that is not redefining a
2932// typedef name and allows the C99 array options, which can only appear in a parameter list.  The pattern precludes
2933// declaring an array of functions versus a pointer to an array of functions, and returning arrays and functions versus
2934// pointers to arrays and functions.
2935
2936identifier_parameter_declarator:
2937        paren_identifier attribute_list_opt
2938                { $$ = $1->addQualifiers( $2 ); }
2939        | '&' MUTEX paren_identifier attribute_list_opt
2940                { $$ = $3->addPointer( DeclarationNode::newPointer( DeclarationNode::newTypeQualifier( Type::Mutex ), OperKinds::AddressOf ) )->addQualifiers( $4 ); }
2941        | identifier_parameter_ptr
2942        | identifier_parameter_array attribute_list_opt
2943                { $$ = $1->addQualifiers( $2 ); }
2944        | identifier_parameter_function attribute_list_opt
2945                { $$ = $1->addQualifiers( $2 ); }
2946        ;
2947
2948identifier_parameter_ptr:
2949        ptrref_operator identifier_parameter_declarator
2950                { $$ = $2->addPointer( DeclarationNode::newPointer( 0, $1 ) ); }
2951        | ptrref_operator type_qualifier_list identifier_parameter_declarator
2952                { $$ = $3->addPointer( DeclarationNode::newPointer( $2, $1 ) ); }
2953        | '(' identifier_parameter_ptr ')' attribute_list_opt
2954                { $$ = $2->addQualifiers( $4 ); }
2955        ;
2956
2957identifier_parameter_array:
2958        paren_identifier array_parameter_dimension
2959                { $$ = $1->addArray( $2 ); }
2960        | '(' identifier_parameter_ptr ')' array_dimension
2961                { $$ = $2->addArray( $4 ); }
2962        | '(' identifier_parameter_array ')' multi_array_dimension // redundant parenthesis
2963                { $$ = $2->addArray( $4 ); }
2964        | '(' identifier_parameter_array ')'                            // redundant parenthesis
2965                { $$ = $2; }
2966        ;
2967
2968identifier_parameter_function:
2969        paren_identifier '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
2970                { $$ = $1->addParamList( $4 ); }
2971        | '(' identifier_parameter_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
2972                { $$ = $2->addParamList( $6 ); }
2973        | '(' identifier_parameter_function ')'                         // redundant parenthesis
2974                { $$ = $2; }
2975        ;
2976
2977// This pattern parses a declaration for a parameter variable or function prototype that is redefining a typedef name,
2978// e.g.:
2979//
2980//              typedef int foo;
2981//              forall( otype T ) struct foo;
2982//              int f( int foo ); // redefine typedef name in new scope
2983//
2984// and allows the C99 array options, which can only appear in a parameter list.
2985
2986type_parameter_redeclarator:
2987        typedef attribute_list_opt
2988                { $$ = $1->addQualifiers( $2 ); }
2989        | '&' MUTEX typedef attribute_list_opt
2990                { $$ = $3->addPointer( DeclarationNode::newPointer( DeclarationNode::newTypeQualifier( Type::Mutex ), OperKinds::AddressOf ) )->addQualifiers( $4 ); }
2991        | type_parameter_ptr
2992        | type_parameter_array attribute_list_opt
2993                { $$ = $1->addQualifiers( $2 ); }
2994        | type_parameter_function attribute_list_opt
2995                { $$ = $1->addQualifiers( $2 ); }
2996        ;
2997
2998typedef:
2999        TYPEDEFname
3000                { $$ = DeclarationNode::newName( $1 ); }
3001        | TYPEGENname
3002                { $$ = DeclarationNode::newName( $1 ); }
3003        ;
3004
3005type_parameter_ptr:
3006        ptrref_operator type_parameter_redeclarator
3007                { $$ = $2->addPointer( DeclarationNode::newPointer( 0, $1 ) ); }
3008        | ptrref_operator type_qualifier_list type_parameter_redeclarator
3009                { $$ = $3->addPointer( DeclarationNode::newPointer( $2, $1 ) ); }
3010        | '(' type_parameter_ptr ')' attribute_list_opt
3011                { $$ = $2->addQualifiers( $4 ); }
3012        ;
3013
3014type_parameter_array:
3015        typedef array_parameter_dimension
3016                { $$ = $1->addArray( $2 ); }
3017        | '(' type_parameter_ptr ')' array_parameter_dimension
3018                { $$ = $2->addArray( $4 ); }
3019        ;
3020
3021type_parameter_function:
3022        typedef '(' push parameter_type_list_opt pop ')'        // empty parameter list OBSOLESCENT (see 3)
3023                { $$ = $1->addParamList( $4 ); }
3024        | '(' type_parameter_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
3025                { $$ = $2->addParamList( $6 ); }
3026        ;
3027
3028// This pattern parses a declaration of an abstract variable or function prototype, i.e., there is no identifier to
3029// which the type applies, e.g.:
3030//
3031//              sizeof( int );
3032//              sizeof( int * );
3033//              sizeof( int [10] );
3034//              sizeof( int (*)() );
3035//              sizeof( int () );
3036//
3037// The pattern precludes declaring an array of functions versus a pointer to an array of functions, and returning arrays
3038// and functions versus pointers to arrays and functions.
3039
3040abstract_declarator:
3041        abstract_ptr
3042        | abstract_array attribute_list_opt
3043                { $$ = $1->addQualifiers( $2 ); }
3044        | abstract_function attribute_list_opt
3045                { $$ = $1->addQualifiers( $2 ); }
3046        ;
3047
3048abstract_ptr:
3049        ptrref_operator
3050                { $$ = DeclarationNode::newPointer( 0, $1 ); }
3051        | ptrref_operator type_qualifier_list
3052                { $$ = DeclarationNode::newPointer( $2, $1 ); }
3053        | ptrref_operator abstract_declarator
3054                { $$ = $2->addPointer( DeclarationNode::newPointer( 0, $1 ) ); }
3055        | ptrref_operator type_qualifier_list abstract_declarator
3056                { $$ = $3->addPointer( DeclarationNode::newPointer( $2, $1 ) ); }
3057        | '(' abstract_ptr ')' attribute_list_opt
3058                { $$ = $2->addQualifiers( $4 ); }
3059        ;
3060
3061abstract_array:
3062        array_dimension
3063        | '(' abstract_ptr ')' array_dimension
3064                { $$ = $2->addArray( $4 ); }
3065        | '(' abstract_array ')' multi_array_dimension          // redundant parenthesis
3066                { $$ = $2->addArray( $4 ); }
3067        | '(' abstract_array ')'                                                        // redundant parenthesis
3068                { $$ = $2; }
3069        ;
3070
3071abstract_function:
3072        '(' push parameter_type_list_opt pop ')'                        // empty parameter list OBSOLESCENT (see 3)
3073                { $$ = DeclarationNode::newFunction( nullptr, nullptr, $3, nullptr ); }
3074        | '(' abstract_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
3075                { $$ = $2->addParamList( $6 ); }
3076        | '(' abstract_function ')'                                                     // redundant parenthesis
3077                { $$ = $2; }
3078        ;
3079
3080array_dimension:
3081                // Only the first dimension can be empty.
3082        '[' ']'
3083                { $$ = DeclarationNode::newArray( 0, 0, false ); }
3084        | '[' ']' multi_array_dimension
3085                { $$ = DeclarationNode::newArray( 0, 0, false )->addArray( $3 ); }
3086        | multi_array_dimension
3087        ;
3088
3089multi_array_dimension:
3090        '[' push assignment_expression pop ']'
3091                { $$ = DeclarationNode::newArray( $3, 0, false ); }
3092        | '[' push '*' pop ']'                                                          // C99
3093                { $$ = DeclarationNode::newVarArray( 0 ); }
3094        | multi_array_dimension '[' push assignment_expression pop ']'
3095                { $$ = $1->addArray( DeclarationNode::newArray( $4, 0, false ) ); }
3096        | multi_array_dimension '[' push '*' pop ']'            // C99
3097                { $$ = $1->addArray( DeclarationNode::newVarArray( 0 ) ); }
3098        ;
3099
3100// This pattern parses a declaration of a parameter abstract variable or function prototype, i.e., there is no
3101// identifier to which the type applies, e.g.:
3102//
3103//              int f( int );                   // not handled here
3104//              int f( int * );                 // abstract function-prototype parameter; no parameter name specified
3105//              int f( int (*)() );             // abstract function-prototype parameter; no parameter name specified
3106//              int f( int (int) );             // abstract function-prototype parameter; no parameter name specified
3107//
3108// The pattern precludes declaring an array of functions versus a pointer to an array of functions, and returning arrays
3109// and functions versus pointers to arrays and functions. In addition, the pattern handles the
3110// special meaning of parenthesis around a typedef name:
3111//
3112//              ISO/IEC 9899:1999 Section 6.7.5.3(11) : "In a parameter declaration, a single typedef name in
3113//              parentheses is taken to be an abstract declarator that specifies a function with a single parameter,
3114//              not as redundant parentheses around the identifier."
3115//
3116// For example:
3117//
3118//              typedef float T;
3119//              int f( int ( T [5] ) );                                 // see abstract_parameter_declarator
3120//              int g( int ( T ( int ) ) );                             // see abstract_parameter_declarator
3121//              int f( int f1( T a[5] ) );                              // see identifier_parameter_declarator
3122//              int g( int g1( T g2( int p ) ) );               // see identifier_parameter_declarator
3123//
3124// In essence, a '(' immediately to the left of typedef name, T, is interpreted as starting a parameter type list, and
3125// not as redundant parentheses around a redeclaration of T. Finally, the pattern also precludes declaring an array of
3126// functions versus a pointer to an array of functions, and returning arrays and functions versus pointers to arrays and
3127// functions.
3128
3129abstract_parameter_declarator:
3130        abstract_parameter_ptr
3131        | '&' MUTEX attribute_list_opt
3132                { $$ = DeclarationNode::newPointer( DeclarationNode::newTypeQualifier( Type::Mutex ), OperKinds::AddressOf )->addQualifiers( $3 ); }
3133        | abstract_parameter_array attribute_list_opt
3134                { $$ = $1->addQualifiers( $2 ); }
3135        | abstract_parameter_function attribute_list_opt
3136                { $$ = $1->addQualifiers( $2 ); }
3137        ;
3138
3139abstract_parameter_ptr:
3140        ptrref_operator
3141                { $$ = DeclarationNode::newPointer( nullptr, $1 ); }
3142        | ptrref_operator type_qualifier_list
3143                { $$ = DeclarationNode::newPointer( $2, $1 ); }
3144        | ptrref_operator abstract_parameter_declarator
3145                { $$ = $2->addPointer( DeclarationNode::newPointer( nullptr, $1 ) ); }
3146        | ptrref_operator type_qualifier_list abstract_parameter_declarator
3147                { $$ = $3->addPointer( DeclarationNode::newPointer( $2, $1 ) ); }
3148        | '(' abstract_parameter_ptr ')' attribute_list_opt
3149                { $$ = $2->addQualifiers( $4 ); }
3150        ;
3151
3152abstract_parameter_array:
3153        array_parameter_dimension
3154        | '(' abstract_parameter_ptr ')' array_parameter_dimension
3155                { $$ = $2->addArray( $4 ); }
3156        | '(' abstract_parameter_array ')' multi_array_dimension // redundant parenthesis
3157                { $$ = $2->addArray( $4 ); }
3158        | '(' abstract_parameter_array ')'                                      // redundant parenthesis
3159                { $$ = $2; }
3160        ;
3161
3162abstract_parameter_function:
3163        '(' push parameter_type_list_opt pop ')'                        // empty parameter list OBSOLESCENT (see 3)
3164                { $$ = DeclarationNode::newFunction( nullptr, nullptr, $3, nullptr ); }
3165        | '(' abstract_parameter_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
3166                { $$ = $2->addParamList( $6 ); }
3167        | '(' abstract_parameter_function ')'                           // redundant parenthesis
3168                { $$ = $2; }
3169        ;
3170
3171array_parameter_dimension:
3172                // Only the first dimension can be empty or have qualifiers.
3173        array_parameter_1st_dimension
3174        | array_parameter_1st_dimension multi_array_dimension
3175                { $$ = $1->addArray( $2 ); }
3176        | multi_array_dimension
3177        ;
3178
3179// The declaration of an array parameter has additional syntax over arrays in normal variable declarations:
3180//
3181//              ISO/IEC 9899:1999 Section 6.7.5.2(1) : "The optional type qualifiers and the keyword static shall appear only in
3182//              a declaration of a function parameter with an array type, and then only in the outermost array type derivation."
3183
3184array_parameter_1st_dimension:
3185        '[' ']'
3186                { $$ = DeclarationNode::newArray( 0, 0, false ); }
3187                // multi_array_dimension handles the '[' '*' ']' case
3188        | '[' push type_qualifier_list '*' pop ']'                      // remaining C99
3189                { $$ = DeclarationNode::newVarArray( $3 ); }
3190        | '[' push type_qualifier_list pop ']'
3191                { $$ = DeclarationNode::newArray( 0, $3, false ); }
3192                // multi_array_dimension handles the '[' assignment_expression ']' case
3193        | '[' push type_qualifier_list assignment_expression pop ']'
3194                { $$ = DeclarationNode::newArray( $4, $3, false ); }
3195        | '[' push STATIC type_qualifier_list_opt assignment_expression pop ']'
3196                { $$ = DeclarationNode::newArray( $5, $4, true ); }
3197        | '[' push type_qualifier_list STATIC assignment_expression pop ']'
3198                { $$ = DeclarationNode::newArray( $5, $3, true ); }
3199        ;
3200
3201// This pattern parses a declaration of an abstract variable, but does not allow "int ()" for a function pointer.
3202//
3203//              struct S {
3204//          int;
3205//          int *;
3206//          int [10];
3207//          int (*)();
3208//      };
3209
3210variable_abstract_declarator:
3211        variable_abstract_ptr
3212        | variable_abstract_array attribute_list_opt
3213                { $$ = $1->addQualifiers( $2 ); }
3214        | variable_abstract_function attribute_list_opt
3215                { $$ = $1->addQualifiers( $2 ); }
3216        ;
3217
3218variable_abstract_ptr:
3219        ptrref_operator
3220                { $$ = DeclarationNode::newPointer( 0, $1 ); }
3221        | ptrref_operator type_qualifier_list
3222                { $$ = DeclarationNode::newPointer( $2, $1 ); }
3223        | ptrref_operator variable_abstract_declarator
3224                { $$ = $2->addPointer( DeclarationNode::newPointer( 0, $1 ) ); }
3225        | ptrref_operator type_qualifier_list variable_abstract_declarator
3226                { $$ = $3->addPointer( DeclarationNode::newPointer( $2, $1 ) ); }
3227        | '(' variable_abstract_ptr ')' attribute_list_opt
3228                { $$ = $2->addQualifiers( $4 ); }
3229        ;
3230
3231variable_abstract_array:
3232        array_dimension
3233        | '(' variable_abstract_ptr ')' array_dimension
3234                { $$ = $2->addArray( $4 ); }
3235        | '(' variable_abstract_array ')' multi_array_dimension // redundant parenthesis
3236                { $$ = $2->addArray( $4 ); }
3237        | '(' variable_abstract_array ')'                                       // redundant parenthesis
3238                { $$ = $2; }
3239        ;
3240
3241variable_abstract_function:
3242        '(' variable_abstract_ptr ')' '(' push parameter_type_list_opt pop ')' // empty parameter list OBSOLESCENT (see 3)
3243                { $$ = $2->addParamList( $6 ); }
3244        | '(' variable_abstract_function ')'                            // redundant parenthesis
3245                { $$ = $2; }
3246        ;
3247
3248// This pattern parses a new-style declaration for a parameter variable or function prototype that is either an
3249// identifier or typedef name and allows the C99 array options, which can only appear in a parameter list.
3250
3251cfa_identifier_parameter_declarator_tuple:                              // CFA
3252        cfa_identifier_parameter_declarator_no_tuple
3253        | cfa_abstract_tuple
3254        | type_qualifier_list cfa_abstract_tuple
3255                { $$ = $2->addQualifiers( $1 ); }
3256        ;
3257
3258cfa_identifier_parameter_declarator_no_tuple:                   // CFA
3259        cfa_identifier_parameter_ptr
3260        | cfa_identifier_parameter_array
3261        ;
3262
3263cfa_identifier_parameter_ptr:                                                   // CFA
3264                // No SUE declaration in parameter list.
3265        ptrref_operator type_specifier_nobody
3266                { $$ = $2->addNewPointer( DeclarationNode::newPointer( 0, $1 ) ); }
3267        | type_qualifier_list ptrref_operator type_specifier_nobody
3268                { $$ = $3->addNewPointer( DeclarationNode::newPointer( $1, $2 ) ); }
3269        | ptrref_operator cfa_abstract_function
3270                { $$ = $2->addNewPointer( DeclarationNode::newPointer( 0, $1 ) ); }
3271        | type_qualifier_list ptrref_operator cfa_abstract_function
3272                { $$ = $3->addNewPointer( DeclarationNode::newPointer( $1, $2 ) ); }
3273        | ptrref_operator cfa_identifier_parameter_declarator_tuple
3274                { $$ = $2->addNewPointer( DeclarationNode::newPointer( 0, $1 ) ); }
3275        | type_qualifier_list ptrref_operator cfa_identifier_parameter_declarator_tuple
3276                { $$ = $3->addNewPointer( DeclarationNode::newPointer( $1, $2 ) ); }
3277        ;
3278
3279cfa_identifier_parameter_array:                                                 // CFA
3280                // Only the first dimension can be empty or have qualifiers. Empty dimension must be factored out due to
3281                // shift/reduce conflict with new-style empty (void) function return type.
3282        '[' ']' type_specifier_nobody
3283                { $$ = $3->addNewArray( DeclarationNode::newArray( 0, 0, false ) ); }
3284        | cfa_array_parameter_1st_dimension type_specifier_nobody
3285                { $$ = $2->addNewArray( $1 ); }
3286        | '[' ']' multi_array_dimension type_specifier_nobody
3287                { $$ = $4->addNewArray( $3 )->addNewArray( DeclarationNode::newArray( 0, 0, false ) ); }
3288        | cfa_array_parameter_1st_dimension multi_array_dimension type_specifier_nobody
3289                { $$ = $3->addNewArray( $2 )->addNewArray( $1 ); }
3290        | multi_array_dimension type_specifier_nobody
3291                { $$ = $2->addNewArray( $1 ); }
3292
3293        | '[' ']' cfa_identifier_parameter_ptr
3294                { $$ = $3->addNewArray( DeclarationNode::newArray( 0, 0, false ) ); }
3295        | cfa_array_parameter_1st_dimension cfa_identifier_parameter_ptr
3296                { $$ = $2->addNewArray( $1 ); }
3297        | '[' ']' multi_array_dimension cfa_identifier_parameter_ptr
3298                { $$ = $4->addNewArray( $3 )->addNewArray( DeclarationNode::newArray( 0, 0, false ) ); }
3299        | cfa_array_parameter_1st_dimension multi_array_dimension cfa_identifier_parameter_ptr
3300                { $$ = $3->addNewArray( $2 )->addNewArray( $1 ); }
3301        | multi_array_dimension cfa_identifier_parameter_ptr
3302                { $$ = $2->addNewArray( $1 ); }
3303        ;
3304
3305cfa_array_parameter_1st_dimension:
3306        '[' push type_qualifier_list '*' pop ']'                        // remaining C99
3307                { $$ = DeclarationNode::newVarArray( $3 ); }
3308        | '[' push type_qualifier_list assignment_expression pop ']'
3309                { $$ = DeclarationNode::newArray( $4, $3, false ); }
3310        | '[' push declaration_qualifier_list assignment_expression pop ']'
3311                // declaration_qualifier_list must be used because of shift/reduce conflict with
3312                // assignment_expression, so a semantic check is necessary to preclude them as a type_qualifier cannot
3313                // appear in this context.
3314                { $$ = DeclarationNode::newArray( $4, $3, true ); }
3315        | '[' push declaration_qualifier_list type_qualifier_list assignment_expression pop ']'
3316                { $$ = DeclarationNode::newArray( $5, $4->addQualifiers( $3 ), true ); }
3317        ;
3318
3319// This pattern parses a new-style declaration of an abstract variable or function prototype, i.e., there is no
3320// identifier to which the type applies, e.g.:
3321//
3322//              [int] f( int );                         // abstract variable parameter; no parameter name specified
3323//              [int] f( [int] (int) );         // abstract function-prototype parameter; no parameter name specified
3324//
3325// These rules need LR(3):
3326//
3327//              cfa_abstract_tuple identifier_or_type_name
3328//              '[' cfa_parameter_list ']' identifier_or_type_name '(' cfa_parameter_ellipsis_list_opt ')'
3329//
3330// since a function return type can be syntactically identical to a tuple type:
3331//
3332//              [int, int] t;
3333//              [int, int] f( int );
3334//
3335// Therefore, it is necessary to look at the token after identifier_or_type_name to know when to reduce
3336// cfa_abstract_tuple. To make this LR(1), several rules have to be flattened (lengthened) to allow the necessary
3337// lookahead. To accomplish this, cfa_abstract_declarator has an entry point without tuple, and tuple declarations are
3338// duplicated when appearing with cfa_function_specifier.
3339
3340cfa_abstract_declarator_tuple:                                                  // CFA
3341        cfa_abstract_tuple
3342        | type_qualifier_list cfa_abstract_tuple
3343                { $$ = $2->addQualifiers( $1 ); }
3344        | cfa_abstract_declarator_no_tuple
3345        ;
3346
3347cfa_abstract_declarator_no_tuple:                                               // CFA
3348        cfa_abstract_ptr
3349        | cfa_abstract_array
3350        ;
3351
3352cfa_abstract_ptr:                                                                               // CFA
3353        ptrref_operator type_specifier
3354                { $$ = $2->addNewPointer( DeclarationNode::newPointer( 0, $1 ) ); }
3355        | type_qualifier_list ptrref_operator type_specifier
3356                { $$ = $3->addNewPointer( DeclarationNode::newPointer( $1, $2 ) ); }
3357        | ptrref_operator cfa_abstract_function
3358                { $$ = $2->addNewPointer( DeclarationNode::newPointer( 0, $1 ) ); }
3359        | type_qualifier_list ptrref_operator cfa_abstract_function
3360                { $$ = $3->addNewPointer( DeclarationNode::newPointer( $1, $2 ) ); }
3361        | ptrref_operator cfa_abstract_declarator_tuple
3362                { $$ = $2->addNewPointer( DeclarationNode::newPointer( 0, $1 ) ); }
3363        | type_qualifier_list ptrref_operator cfa_abstract_declarator_tuple
3364                { $$ = $3->addNewPointer( DeclarationNode::newPointer( $1, $2 ) ); }
3365        ;
3366
3367cfa_abstract_array:                                                                             // CFA
3368                // Only the first dimension can be empty. Empty dimension must be factored out due to shift/reduce conflict with
3369                // empty (void) function return type.
3370        '[' ']' type_specifier
3371                { $$ = $3->addNewArray( DeclarationNode::newArray( nullptr, nullptr, false ) ); }
3372        | '[' ']' multi_array_dimension type_specifier
3373                { $$ = $4->addNewArray( $3 )->addNewArray( DeclarationNode::newArray( nullptr, nullptr, false ) ); }
3374        | multi_array_dimension type_specifier
3375                { $$ = $2->addNewArray( $1 ); }
3376        | '[' ']' cfa_abstract_ptr
3377                { $$ = $3->addNewArray( DeclarationNode::newArray( nullptr, nullptr, false ) ); }
3378        | '[' ']' multi_array_dimension cfa_abstract_ptr
3379                { $$ = $4->addNewArray( $3 )->addNewArray( DeclarationNode::newArray( nullptr, nullptr, false ) ); }
3380        | multi_array_dimension cfa_abstract_ptr
3381                { $$ = $2->addNewArray( $1 ); }
3382        ;
3383
3384cfa_abstract_tuple:                                                                             // CFA
3385        '[' push cfa_abstract_parameter_list pop ']'
3386                { $$ = DeclarationNode::newTuple( $3 ); }
3387        | '[' push type_specifier_nobody ELLIPSIS pop ']'
3388                { SemanticError( yylloc, "Tuple array currently unimplemented." ); $$ = nullptr; }
3389        | '[' push type_specifier_nobody ELLIPSIS constant_expression pop ']'
3390                { SemanticError( yylloc, "Tuple array currently unimplemented." ); $$ = nullptr; }
3391        ;
3392
3393cfa_abstract_function:                                                                  // CFA
3394//      '[' ']' '(' cfa_parameter_ellipsis_list_opt ')'
3395//              { $$ = DeclarationNode::newFunction( nullptr, DeclarationNode::newTuple( nullptr ), $4, nullptr ); }
3396        cfa_abstract_tuple '(' push cfa_parameter_ellipsis_list_opt pop ')'
3397                { $$ = DeclarationNode::newFunction( nullptr, $1, $4, nullptr ); }
3398        | cfa_function_return '(' push cfa_parameter_ellipsis_list_opt pop ')'
3399                { $$ = DeclarationNode::newFunction( nullptr, $1, $4, nullptr ); }
3400        ;
3401
3402// 1) ISO/IEC 9899:1999 Section 6.7.2(2) : "At least one type specifier shall be given in the declaration specifiers in
3403//    each declaration, and in the specifier-qualifier list in each structure declaration and type name."
3404//
3405// 2) ISO/IEC 9899:1999 Section 6.11.5(1) : "The placement of a storage-class specifier other than at the beginning of
3406//    the declaration specifiers in a declaration is an obsolescent feature."
3407//
3408// 3) ISO/IEC 9899:1999 Section 6.11.6(1) : "The use of function declarators with empty parentheses (not
3409//    prototype-format parameter type declarators) is an obsolescent feature."
3410//
3411// 4) ISO/IEC 9899:1999 Section 6.11.7(1) : "The use of function definitions with separate parameter identifier and
3412//    declaration lists (not prototype-format parameter type and identifier declarators) is an obsolescent feature.
3413
3414//************************* MISCELLANEOUS ********************************
3415
3416comma_opt:                                                                                              // redundant comma
3417        // empty
3418        | ','
3419        ;
3420
3421default_initialize_opt:
3422        // empty
3423                { $$ = nullptr; }
3424        | '=' assignment_expression
3425                { $$ = $2; }
3426        ;
3427
3428%%
3429
3430// ----end of grammar----
3431
3432// Local Variables: //
3433// mode: c++ //
3434// tab-width: 4 //
3435// compile-command: "make install" //
3436// End: //
Note: See TracBrowser for help on using the repository browser.