source: src/Parser/parser.yy @ 5753b33

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

for control now uses basetypeof

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