source: src/Parser/parser.yy @ ba01b14

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

update constant parsing add _FloatNN

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