Jacques-Henri Jourdan

François Pottier

A simple, possibly correct LR parser for C11

Keywords: CCS Concepts:, Software and its engineering → Parsers, Compilation, parsing, ambiguity, lexical feedback, C89, C99, C11

The syntax of the C programming language is described in the C11 standard by an ambiguous context-free grammar, accompanied with English prose that describes the concept of "scope" and indicates how certain ambiguous code fragments should be interpreted. Based on these elements, the problem of implementing a compliant C11 parser is not entirely trivial. We review the main sources of difficulty and describe a relatively simple solution to the problem. Our solution employs the well-known technique of combining an LALR(1) parser with a "lexical feedback" mechanism. It draws on folklore knowledge and adds several original aspects, including: a twist on lexical feedback that allows a smooth interaction with lookahead; a simplified and powerful treatment of scopes; and a few amendments in the grammar. Although not formally verified, our parser avoids several pitfalls that other implementations have fallen prey to. We believe that its simplicity, its mostly-declarative nature, and its high similarity with the C11 grammar are strong informal arguments in favor of its correctness. Our parser is accompanied with a small suite of "tricky" C11 programs. We hope that it may serve as a reference or a starting point in the implementation of compilers and analysis tools.

INTRODUCTION

This paper explains how to build a compliant C11 parser by combining: an LALR(1) automaton, produced out of a context-free grammar by an LALR(1) parser generator; a lexical analyzer or "lexer", also generated from a declarative description; and a "lexical feedback" mechanism.

Naturally, this is by no means the only approach to parsing C11. Several other approaches are discussed in Section 4. However, this technique seems quite appealing, for at least two reasons. First, it requires comparatively little effort, as a large part of the code is generated. Second, it makes it comparatively easy to convince oneself that the resulting parser complies with the C11 standard. Indeed, our lexer and parser together are less than a thousand (nonblank, noncomment) lines of code, and are expressed in a mostly declarative style.

Instead of immediately delving into the low-level details of LALR(1) automata, lexical feedback, and so on, we give in Section 2 a high-level overview of the various sources of syntactic ambiguity in the C11 standard. As illustrations, we present a collection of "tricky" yet syntactically valid C11 program fragments. (Unless otherwise indicated, every program fragment in the paper is syntactically valid.) This collection, which we make available online [START_REF] Jourdan | A simple, possibly correct LR parser for C11 -implementation and test suite[END_REF], forms a small benchmark suite.

It can be used to test whether a compiler appears to comply with the C11 standard, especially as concerns the classification of identifiers.

In Section 3, we describe our solution to the problem of parsing C11. It involves a twist on lexical feedback that allows a smooth interaction with lookahead; a simplified and powerful treatment of scopes; and amendments to the C11 grammar. It has been implemented and is available online [START_REF] Jourdan | A simple, possibly correct LR parser for C11 -implementation and test suite[END_REF]. We believe that it complies with the C11 standard. We hope that it may serve as a reference or as a starting point in the implementation of compilers, analysis tools, and so on.

In what sense, if any, is our parser "correct"? In a formal sense, this claim cannot easily be stated (let alone proven), as there is no mathematical specification of the C11 language. The informal prose in the standard does not have unequivocal formal meaning; in fact, we point out two ambiguities in it (see Sections 2.2.1 and 2.4). One might wish to come up with a formal specification of the syntax of the C11 language and prove (either on paper or with machine assistance) that our parser complies with this specification. However, a simple, formal specification of the C11 syntax is elusive: the shortest and simplest specification that we know of is precisely our parser itself. As a result, our parser is not verified, and cannot formally be claimed correct. In an experimental sense, we have evidence that it is working: a slightly extended version of it is used in the CompCert C compiler [START_REF] Leroy | Formal verification of a realistic compiler[END_REF][START_REF] Leroy | The CompCert C verified compiler[END_REF]. Although it might seem desirable to test it more extensively (both against real-world C11-compliant code bases and against examples of invalid code), we have not undertaken this effort.

CHALLENGES IN PARSING C11

To a first approximation, the syntax of the C11 programming language is described by a context-free grammar, which appears in the C11 standard [ISO 2011, A.2]. This grammar is unfortunately ambiguous. The ambiguity is in principle eliminated by a set of rules, expressed in plain English prose, and somewhat scattered through the C11 standard.

In order to implement a correct parser for C11, one must understand why there is ambiguity and how the rules eliminate it, or attempt to eliminate it. As we will see, a few rules are worded in such a way that several interpretations are possible!

In the following, we present the sources of ambiguity, as well as the disambiguation rules and their subtleties, via a series of illustrating examples. It forms a small suite of tricky cases, which can be used as a test suite for a C11 parser.

Ambiguity in the meaning of identifiers

The most problematic source of ambiguity in the C11 grammar lies in the various roles of identifiers. An identifier may belong to one of four name spaces [ISO 2011, 6.2.3], namely "label names", "tags", "members", and "ordinary identifiers". Furthermore, an ordinary identifier can play one of two roles: it can be viewed either as a "variable" or as a "typedef name" [ISO 2011, 6.2.1, §1]. (We use the word "variable" to mean an "object", a "function", or an "enumeration constant" paragraph 6.2.1, §1.) Unfortunately, the distinction between these two roles requires contextual information. For example, consider the following two valid code fragments: In the left-hand fragment, the function f contains a declaration of the local variable b as a pointer to an object of type T (which has been declared as a synonym for int). On the other hand, in the right-hand fragment, the body of f does not contain any declaration: it contains one statement, namely an expression statement, a multiplication of the global variable T by the global variable b.

Thus, the manner in which one should interpret the body of f depends on the context in which this declaration appears. In particular, its interpretation depends on whether the identifier T denotes a variable or a typedef name. Some mechanism is therefore needed in order to classify identifiers.

Before discussing how such a mechanism might be described and implemented (which we do in Section 3), let us recall the rules that this classification process must obey. These rules are relatively simple, but exhibit a few subtleties (such as noncontiguous scopes; see Section 2.1.4) and interactions with other language features (such as the "dangling else" ambiguity; see Section 2.2.2) which further complicate the problem.

2.1.1. Name spaces. As noted above, there are four name spaces of identifiers [ISO 2011, 6.2.3]: label names, tags, members, and ordinary identifiers. An identifier may play independent roles in independent name spaces. For instance, the following code is valid: // namespaces.c typedef int S, T, U; struct S { int T; }; union U { int x; }; void f(void) { // The following uses of S, T, U are correct, and have no // effect on the visibility of S, T, U as typedef names. struct S s = { .T = 1 }; T: s.T = 2; union U u = { 1 }; goto T; // S, T and U are still typedef names: S ss = 1; T tt = 1; U uu = 1; } 2.1.2. Visibility and scopes. A declaration introduces either new variables or new typedef names, depending on whether the typedef keyword appears among the declaration specifiers. A declaration may contain multiple declarators. A declarator declares exactly one entity, and introduces one identifier [ISO 2011, 6.7.6, §2]. It is "visible" within a certain region of the program text [ISO 2011, 6.2.1, §2]. Where the declarator is visible, the declared entity can be referred to via its identifier.

Visibility begins where a declarator is complete. Visibility stops at the end of the scope that the declaration inhabits. The program text is organized in "scopes", that is, regions that begin and end at well-defined points, such as the beginning and end of a block (see Section 2.1.4). Scopes can overlap: more precisely, they can be nested [ISO 2011, 6.2.1, §4]. A declaration of an identifier in an inner scope hides a declaration of the same identifier in the same scope or in an outer scope. Thus, the region where a declaration is visible is not necessarily contiguous: A variable or typedef name becomes visible just after the completion of its declarator [ISO 2011, 6.2.1, §7]. In C terminology, a declarator is a fragment of a declaration that concerns a single identifier. The syntax for declaring pointers, functions, and arrays is part of a declarator, whereas declaration specifiers (such as int and const) and optional initializers are not. Thus, the following code is valid: int T1 = sizeof((int)T1); // In the initializer sizeof((int)T1), the declarator of T1 has // ended (it is constituted solely by the identifier T1), so T1 // denotes a variable. } 2.1.3. Enumeration specifiers modify the current scope. A somewhat counter-intuitive feature of enumeration specifiers is that they declare enumeration constants [ISO 2011, 6.7.2.2, §3], which are ordinary identifiers [ISO 2011, 6.2.3, §1]. This phenomenon takes place regardless of the context in which the enumeration specifier occurs. The newly declared enumeration constants remain visible (except where temporarily hidden) until the end of the current scope, whatever that scope might be.

// local _ scope.c typedef int T; void f(void) { T y = 1; // T is a type if(1) { int T; T = 1; // T is a variable } T x = 1; // T
For instance, mentioning an enumeration specifier as an argument to the sizeof operator, or as part of a cast expression, declares new enumeration constants. Because an expression does not form a scope, these constants remain visible past the end of the expression. In the following example, the typedef name T is hidden by a local declaration of T as an enumeration constant:

// enum _ shadows _ typedef.c typedef int T; void f(void) { int x = (int)(enum {T})1;
// T now denotes an enumeration constant, // and behaves syntactically like a variable: x = (int)T; } An enumeration constant becomes visible in the current scope just after the completion of its enumerator [ISO 2011, 6.2.1, §7]. Thus, the newly declared constant can be referred to in the declaration of further enumeration constants and in the remainder of the current scope:

// enum _ constant _ visibility.c typedef int T; void f(void) { int x; x = (enum {T, U = T+1})1 + T; int y = U -T; } 2.1.4.
Where scopes begin and end. According to the C11 standard [ISO 2011, 6.2.1, §2], there are three kinds of scopes: file, block, and function prototype. (The fourth kind, function scope, does not concern ordinary identifiers. In our case, it can be ignored.) For our purposes, though, it is not necessary to keep track of the various kinds of scopes; it suffices to know where they are opened and closed.

A "file" scope is opened at the beginning of a translation unit, and closed at the end. The C11 standard [ISO 2011, 6.8.2, §2] states that "a compound statement is a block", which means that a new "block" scope must be created at the beginning of a compound statement, and closed at the end: A selection statement forms a block. Furthermore, each of its immediate substatements also forms a block [ISO 2011, 6.8.4, §3]:

// block _ scope.c typedef int T; int x; void f(void) { { T T; T = 1; typedef int x; } x = 1; // x
// if _ scopes.c typedef int T, U; int x; void f(void) { if(sizeof(enum {T}))
// The declaration of T as an enumeration constant is // visible in both branches: x = sizeof(enum {U}) + T; else { // Here, the declaration of U as an enumeration constant // is no longer visible, but that of T still is. U u = (int)T; } switch(sizeof(enum {U})) x = U; // Here, T and U are typedef names again:

T t; U u; }
The same rule applies to iteration statements [ISO 2011, 6.8.5

// no _ local _ scope.c typedef int T, U, V; int x; int f(void) {
x = sizeof(enum {T}); label: x = sizeof(enum {U}); return sizeof(enum {V}); // T, U and V now denote enumeration constants:

x = T + U + V; }
The parameter list of a function prototype gives rise to a new "function prototype" scope, which must be opened at the beginning of the parameter list and closed at the end of the parameter list. Thus, a name introduced somewhere in the parameter list is visible in the remainder of the parameter list and is no longer visible after the parameter list ends. We emphasize that such a name can be either a formal parameter or an enumeration constant that appears in the type of a formal parameter. In the following example, the names introduced by the parameter list of f are The parameter list of a function definition gives rise to a new "block" scope, which must be opened at the beginning of the parameter list and closed at the end of the function body. Indeed, the C11 standard [ISO 2011, 6.2.1, §4] prescribes: "If the declarator or type specifier that declares the identifier appears [...] within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block." Thus, in the following example, which begins like the previous one, the scope of the names T, U, y, x, which are introduced in the parameter list of f, includes the function body:

// function _ parameter _ scope _ extends.c typedef long T, U; enum {V} ( * f(T T, enum {U} y, int x[T+U]))(T t) {
// The last T on the previous line denotes a type! // Here, V, T, U, y, x denote variables: long l = T+U+V+x[0]+y; return 0; } This example is particularly challenging. It shows that a scope need not be contiguous. Indeed, the block scope created at the beginning of the parameter list (T T, enum {U} y, int x[T+U]) encompasses this parameter list as well as the function body, but does not include the rest of the declarator of f. In particular, the identifier T in the parameter list (T t) must be interpreted as a typedef name introduced by the initial typedef declaration.

In an implementation, when reaching the end of a parameter list, one must close the scope that was opened for this parameter list. Yet, one must not discard it entirely, as one may have to re-open it at the beginning of the function body, if this parameter list turns out to be part of a function definition. One cannot "fake" this by opening a new scope at the beginning of the function body and introducing the names of the formal parameters into it, as this new scope would then be missing the enumeration constants that may have been declared in the parameter list.

Ambiguity in if versus if-else

An if statement may or may not have an else branch. This creates an ambiguity, which is well-known as the "dangling else" problem: an else branch that follows two nested if constructs can be attached either to the farthest or to the nearest if construct. For example, according to the C11 grammar, the following code may give rise to two different syntax trees, depending on which if statement the else branch is associated with:

// dangling _ else.c int f(void) { if(0)
if(1) return 1; else return 0; return 1; } 2.2.1. An arguably ambiguous disambiguating sentence. The C11 standard attempts to explicitly eliminate this ambiguity by stating: "An else is associated with the lexically nearest preceding if that is allowed by the syntax" [ISO 2011, 6.8.4.1, §3]. Thus, in the previous example, the else branch must be attached to the second if construct.

However, this disambiguating sentence is itself somewhat unclear, in a subtle way, and could arguably be viewed as ambiguous or misleading. The following invalid code fragment illustrates the problem:

// dangling _ else _ misleading.fail.c typedef int T; void f(void) { if(1) for(int T; ;) if(1) {} else { T x; } }
Here, if the else branch is attached to the second if construct, then the last occurrence of T must denote a variable, which implies that the program is syntactically invalid. One might therefore interpret paragraph 6.8.4.1, §3 as dictating that the else branch be attached to the first if construct. Under this interpretation, the last occurrence of T would denote a typedef name, and the program would be syntactically valid.

Such an interpretation seems exotic: we know of no C compiler that behaves in this manner. Therefore, our informal interpretation of paragraph 6.8.4.1, §3 is that "an else is associated with the lexically nearest preceding if that is allowed by the syntax, considering only what has been read so far". In other words, the text beyond the else keyword must not be taken into account when one commits its association with a certain if keyword.

Nevertheless, we believe it is interesting to point out that the short informal sentence in paragraph 6.8.4.1, §3 does not have clear formal meaning. We point out another such sentence in Section 2.4.

2.2.2. An interaction between the if-else ambiguity and the scoping rules. Another subtle issue caused by the fact that else branches are optional is its interaction with the scoping rules (which we have recalled in Section 2. 1.4). Consider an open-ended if statement, that is, one that does not (yet) have an else branch, such as "if(1);". After such a statement has been read, two cases arise:

-If the token that follows this if statement is the keyword else, then this if statement is in fact not finished. Its scope must extend all the way to the end of the else branch. -If, on the other hand, the token that follows this if statement is not else, then this if statement is finished. Its scope ends immediately before this token.

Although this specification is clear, it may be somewhat tricky to implement correctly in a deterministic parser, such as an LALR(1) parser with lexical feedback. When one reads the first token beyond an open-ended if statement, one does not know yet whether the scope of the if statement has ended. Thus, if this token happens to be an identifier, and if one attempts too early to classify this identifier as a variable or a typedef name, one runs a risk of classifying it incorrectly. The potential danger appears in the following valid example:

// dangling _ else _ lookahead.c typedef int T; void f(void) { for(int T; ;) if(1); // T must be resolved outside of the scope of the // "for" statement, hence denotes a typedef name: T x; x = 0; } This particular example is incorrectly rejected by GCC 5.3 (and older versions). We have reported this bug to the developers of GCC [START_REF] Jourdan | GCC bug #67784: Incorrect parsing when using declarations in for loops and typedefs[END_REF]]. It has been acknowledged and fixed in the development version.

Ambiguity in declarations and struct declarations

The C11 grammar exhibits an ambiguity in the syntax of declarations. This is illustrated by the following code fragment: // declares a variable "T" of type "unsigned" T = 1; }

In the C11 grammar [ISO 2011, 6.7, §1], the syntax of declarations is defined by the production declaration: declaration-specifiers init-declarator-list opt ;. With this in mind, there is only one way of reading the third line above, "unsigned int". Indeed, unsigned and int are type specifiers, hence also declaration specifiers; the initdeclarator-list in this case must be absent. Hence, this declaration declares zero variables of type unsigned int. However, there are two ways of reading each of the two declarations "const T" and "unsigned T". On the one hand, since T is a typedef name, it is also a type specifier, so these declarations could be interpreted, like the previous one, as declarations of zero variables of type const T and unsigned T, respectively. On the other hand, since T is an identifier, it forms a declarator, so these declarations can be interpreted as declarations of a variable T of type const and unsigned, respectively.

This ambiguity also appears in the syntax of parameter declarations, where it is caused by the fact that a parameter may be named or anonymous [ISO 2011, 6.7.6, §1]. An analogous ambiguity appears in the syntax of struct declarations [ISO 2011, 6.7.2.1, §1], where it is caused by the fact that the struct-declarator-list is optional.

Struct declarations exhibit another (similar) ambiguity, which is caused by the fact that a bit-field can be anonymous, as prescribed by the production struct-declarator: declarator opt : constant-expression [ISO 2011, 6.7.2.1, §1]. This is illustrated by the following code fragment: This declares a structure S with two bit-fields. There are, however, two ways of interpreting each of the above two bit-field declarations. Indeed, in each of them, one may consider T either as a type specifier (in which case an anonymous bit-field of type T is being defined) or as a member name (in which case a bit-field named T is being defined).

All of the ambiguities discussed above are eliminated by paragraph 6.7.2, §2, which limits the combinations of type specifiers that may be used in a declaration or struct declaration:

At least one type specifier shall be given in the declaration specifiers in each declaration, and in the specifier-qualifier list in each struct declaration and type name. Each list of type specifiers shall be one of the following multisets [...]:void;char;signed char; [...] In light of this paragraph, the declaration "const T" in declaration _ ambiguity.c must be interpreted as follows. Because every declaration must contain at least one type specifier, T must be interpreted in this declaration as a type specifier. Therefore, this declaration does not declare any variable.

By the same reasoning, the bit-field "const T:3" in the previous example must be interpreted as a constant anonymous bit-field of type T.

The declaration "unsigned T" in declaration _ ambiguity.c must be interpreted as follows. Among the combinations of type specifiers not permitted by paragraph 6.7.2, §2, one finds unsigned T, where T is a typedef name. Thus, this cannot be a declaration of zero variables. Therefore, this must be a declaration of a variable T of type unsigned.

By the same reasoning, the bit-field "unsigned T:3" in the previous example must be interpreted as a bit-field named T whose type is unsigned. (It is worth noting that, therefore, this occurrence of T lies in the name space of "members". Thus, it does not hide the earlier declaration of T as a typedef name. This declaration remains visible on the following line.)

Ambiguity in parameter declarations

In addition to the ambiguity discussed above (Section 2.3), the C11 grammar exhibits a further ambiguity in the syntax of parameter declarations. Consider the following code fragment:

// parameter _ declaration _ ambiguity.c typedef int T; void f(int(x), int(T), int T); // First parameter: named x,

of type int // Second parameter: anonymous, of type int(T) (i.e., T -> int) // Third parameter: named T, of type int

According to the C11 grammar, in this fragment, the parameter declaration int(T) can be interpreted in two ways. One can read it as introducing a parameter whose name is T and whose type is int. One can also read it as introducing an anonymous parameter whose type is int(T), that is, "function of T to int". In the first reading, the name of the parameter is parenthesized, as allowed by the syntax of declarators. The identifier T, which happens to denote a typedef name, is re-declared as a variable. In the second reading, because T denotes a typedef name, (T) forms a valid abstract declarator.

The C11 standard attempts to eliminate this ambiguity as follows [ISO 2011, 6.7.6.3, §11]:

If, in a parameter declaration, an identifier can be treated either as a typedef name or as a parameter name, it shall be taken as a typedef name.

In particular, in the previous example, the second reading must be preferred. The parameter declaration int(T) introduces an anonymous parameter whose type is int(T).

Just like the sentence that pretends to eliminate the "dangling else" ambiguity (Section 2.2.1), this sentence is arguably unclear: it must be carefully interpreted. Indeed, consider the following code fragment, which we consider invalid:

typedef int T; int f(int(T[const * ]));
Here, one might argue that the identifier T "cannot" be treated as a typedef name, because this leads (a little later) to a syntax error: indeed, [const * ] is not allowed by the syntax of abstract declarators1 . Therefore, one might conclude that T must be treated as a parameter name. Under this interpretation, the following two declarations would be considered equivalent:

int f(int(T[const * ])); int f(int T[const * ] );
As in Section 2.2.1, we argue that such an interpretation seems counter-intuitive and difficult or costly to implement. Moreover, in practice, Clang and GCC both accept [const * ] as part of an abstract declarator, and view T as a typedef name in this example. Therefore, we follow Clang and GCC: when one finds an identifier T in this ambiguous position, one should commit to the "typedef name" interpretation before one reads further ahead. In our parser, this is done by appropriately resolving a reduce/reduce conflict (Section 3.5).

Ambiguity in the use of _ Atomic

C11 introduces the keyword _ Atomic. This keyword can be used in two different syntactic fashions:

-It can be used as a type qualifier, like const, restrict, and volatile [ISO 2011, 6.7.3, §1].

-It can be used as part of an atomic type specifier [ISO 2011, 6.7.2.4, §1]. More precisely, if τ is a type name, then _ Atomic(τ ) is a type specifier.

At first sight, this overloading of the _ Atomic keyword appears as if it might create an ambiguity. When _ Atomic is followed by an opening parenthesis, one does not know whether _ Atomic is used as a type qualifier (in which case the declaration specifier list is finished, and this parenthesis is the beginning of a parenthesized declarator) or whether this is the beginning of an atomic type specifier. In order to eliminate this potential ambiguity, the C11 standard states [ISO 2011, 6.7.2.4, §4]:

If the _ Atomic keyword is immediately followed by a left parenthesis, it is interpreted as a type specifier (with a type name), not as a type qualifier.

However, this restriction is not really necessary, as paragraph 6.7.2, §2 (quoted and discussed in Section 2.3) already removes this ambiguity. Indeed, upon encountering an _ Atomic keyword followed by an opening parenthesis, one may reason as follows:

-If a type specifier has been read already as part of the current declaration, then this _ Atomic keyword cannot be viewed as the beginning of another type specifier. Indeed, according to the list of permitted combinations of type specifiers [ISO 2011, 6.7.2, §2], an atomic type specifier cannot be accompanied by another type specifier. Thus, in this case, _ Atomic must be viewed as a type qualifier. (In this case, paragraph 6.7.2.4, §4 would impose rejecting the code.) -If no type specifier has been read yet, then this _ Atomic keyword cannot be viewed as a type qualifier. Indeed, that would imply that the parenthesis is the beginning of a parenthesized declarator, so that the declaration specifier list is finished and contains no type specifier. This is forbidden: a declaration specifier list must contain at least one type specifier. Thus, in this case, _ Atomic must be viewed as the beginning of a type specifier.

This may seem a somewhat complicated and informal proof of unambiguity. Fortunately, the absence of ambiguity is automatically proved by LR parser generators (see Section 3.5).

AN LALR(1) PARSER FOR C11

Our C11 parser [START_REF] Jourdan | A simple, possibly correct LR parser for C11 -implementation and test suite[END_REF]] is produced by an LALR(1) parser generator out of a grammar which we strive to keep as close as possible to the C11 grammar and as simple as possible. We assume that its input is preprocessed source code.

In search of a suitable grammar

What grammar should be provided as an input to an LALR(1) parser generator? It seems natural to first examine the C11 grammar [ISO 2011, A.2]. Let us refer to it as G 0 . As explained earlier (Section 2.1), it is an ambiguous context-free grammar, whose most problematic source of ambiguity has to do with the various roles of identifiers. An identifier may belong to one of four name spaces [ISO 2011, 6.2.3], namely "label names", "tags", "members", and "ordinary identifiers". Furthermore, an ordinary identifier can play one of two roles: it can be viewed either as a "variable" or as a "typedef name" [ISO 2011, 6.2.1, §1]. In G 0 , identifier is a terminal symbol, whereas typedefname is a nonterminal symbol, defined by the production typedef-name: identifier [ISO 2011, 6.7.8, §1]. This creates an ambiguity: G 0 does not indicate when this production should be used, that is, when an identifier should be viewed as a typedef name and when (on the contrary) it should be viewed as a variable (or a label name, or a tag, or a member). This is done in the most part by a set of informal "scoping rules" [ISO 2011, 6.2.1] and in a lesser part by informal restrictions enunciated in other places, such as paragraph 6.7.2, §2, paragraph 6.7.6.3, §11, and paragraph 6.9.1, §6.

In order to eliminate this source of ambiguity, it is customary2 to remove from G 0 the production typedef-name: identifier and view identifier and typedef-name as two distinct terminal symbols. By doing so, one ostensibly assumes that ordinary identifiers are somehow classified prior to parsing as variables or typedef names. Let us refer to this new grammar as G 1 [Degener 2012].

The grammar G 1 seems remarkably well-behaved. It is "almost" LALR(1). More precisely, the automaton built for G 1 by an LALR(1) parser generator exhibits only two conflicts: a shift/reduce conflict caused by the "dangling else" ambiguity (Section 2.2) and a shift/reduce conflict caused by the " _ Atomic(" ambiguity (Section 2.5). In both cases, the desired behavior can be obtained by instructing the parser generator to always prefer shifting.

Unfortunately, the grammar G 1 is too restrictive: there are valid C11 programs that it rejects. Indeed, whereas in G 0 the terminal symbol identifier means "an arbitrary identifier", in G 1 it has more restricted conventional meaning: it represents "an identifier that has been classified as a variable" (as opposed to a typedef name). In two places, namely primary-expression [ISO 2011, 6.5.1, §2] and identifier-list [ISO 2011, 6.9.1, §6], this restricted meaning is in fact desired. Therefore, in these two places, it is fine to use identifier. Everywhere else, the unrestricted meaning of "an arbitrary identifier" is desired. In those places, G 1 is too restrictive and must be amended by replacing identifier with a choice between identifier and typedef-name. This yields a new grammar, which we refer to as G 2 .

The grammar G 2 is slightly less well-behaved than G 1 . In addition to the two shift/reduce conflicts mentioned above, it exhibits a reduce/reduce conflict caused by the "parameter declaration" ambiguity (Section 2.4) and a shift/reduce conflict caused by the "declaration" ambiguity (Section 2.3). The former conflict can be solved by instructing the parser generator to always prefer a certain production (Section 3.5). Unfortunately, the latter conflict cannot be statically solved: neither "always shift" nor "always reduce" is the correct behavior (Section 3.4).

In summary, the grammar G 2 is our starting point. At least two problems remain to be solved. First, one must implement a mechanism by which ordinary identifiers are (correctly) classified as variables or typedef names. Although it is well-known that such a classification must be performed on the fly via a form of "lexical feedback", the problem is trickier than it may at first seem, as we have argued earlier (Section 2).

Our solution, which requires several changes in the grammar, is described in Section 3.3. Second, one must further modify the grammar so as to eliminate the problematic shift/reduce conflict described above. Our solution is described in Section 3.4.

Tools

We build our lexer and parser with the programming language OCaml, the lexer generator ocamllex, and the parser generator Menhir [START_REF] Pottier | The Menhir parser generator[END_REF]. The latter two can be described as the OCaml analogues of lex and yacc. Minsky et al. [Minsky et al. 2013, Chapter 16] give a good tutorial introduction to these tools.

The implementation of the lexer does not present any significant difficulty, except in its interaction with the parser, which is described in detail in the following.

Menhir supports several parser construction methods, including LALR(1), Pager's method [START_REF] Pager | A Practical General Method for Constructing LR(k) Parsers[END_REF]] and Knuth's canonical method [START_REF] Knuth | On the translation of languages from left to right[END_REF]]. For our purposes, LALR(1) is sufficient. We exploit two specific features of Menhir that improve conciseness and readability, namely parameterized nonterminal symbols [Pottier and Régis-Gianas 2016, §5.2] and inlined nonterminal symbols [Pottier and Régis-Gianas 2016, §5.3]. Both features can be expanded away (by Menhir itself), producing a version of the grammar that does not exploit these features.

This expanded grammar, with empty semantic actions, forms a valid .y file, which yacc and Bison [START_REF] Donnelly | Bison[END_REF] can read and process, and which we distribute [START_REF] Jourdan | A simple, possibly correct LR parser for C11 -implementation and test suite[END_REF]. The LALR(1) automata produced by Bison and Menhir appear to be identical. (We have checked that they have the same number of states.)

Lexical feedback

As explained in Section 3.1, we follow an approach where variables and typedef names must give rise to distinct tokens (or, in our case, distinct sequences of tokens). In an ideal world, this distinction would be made prior to parsing, in a logically separate phase. It would take the form of extra logic inserted into the lexer (or between the lexer and parser). Unfortunately, in reality, this is impossible. Indeed, as explained in Section 2, in order to tell whether an identifier is a variable or a typedef name, one must know which declarations are visible in the current scope. This in turn requires being aware of where scopes are opened and closed and where declarations take effect. To obtain this information requires parsing. Thus, a form of feedback is required: the parser must provide information to the lexer. To this end, some form of global state, which the lexer reads and the parser updates, is required. This is known elegantly as "lexical feedback", or, rather more prosaically, as "the lexer hack".

In all implementations of lexical feedback known to us, including ours, the lexer has read access to some global state, which the parser is in charge of updating. The updates take place in the semantic actions associated with certain productions. They are executed when these productions are reduced.

In all previous implementations of lexical feedback known to us, upon encountering an identifier in the source code, the lexer immediately consults the global state so as to determine whether (in the current scope) this identifier represents a variable or a typedef name, and, depending on the outcome of this test, emits distinct tokens: say, VARIABLE versus TYPE. In our approach, in contrast, upon encountering an identifier in the source code, the lexer immediately produces the token NAME, followed with either VARIABLE or TYPE. This delays the access by the lexer to the global state, thus eliminating the risk of incorrect classification that was illustrated in Section 2.2.2.

In the following, we first describe what global state is shared between our lexer and parser, and through which API this global state is updated and read (Section 3.3.1). Then, we explain when this global state is updated by the parser. This involves sav-ing and restoring contexts (Section 3.3.2) and declaring new identifiers in the current context (Section 3.3.3). Finally, we explain when the lexer accesses the global state (Section 3.3.4).

3.3.1. Context API. Let us use the word "context", in a precise technical sense, to mean a "set of identifiers". A context represents a set of identifiers that should be viewed as typedef names (whereas all other identifiers should be viewed as variables). It is an immutable set.

In Our OCaml implementation, the management of contexts is encapsulated in a single module, baptized Context. This module is extremely simple: it is implemented in 8 lines of code. It contains one mutable global variable, namely current, which holds a pointer to an immutable set of identifiers. The set !current is "the current context"3 .

This module is used by the lexer (which consults the global state) and by the parser (which updates the global state), thus allowing information to flow from the parser to the lexer. It offers the following API:

val declare _ typedefname : string -> unit val declare _ varname : string -> unit val is _ typedefname : string -> bool type context val save _ context : unit -> context val restore _ context : context -> unit
The functions declare _ typedefname and declare _ varname are invoked by the parser when a new variable or typedef name is introduced: they change the current context. More precisely, the call declare _ typedefname id adds the identifier id to the current context, whereas declare _ varname id removes id from the current context. The function is _ typedefname is invoked by the lexer when it needs to decide whether to emit VARIABLE or TYPE; it consults the current context. These three functions have logarithmic time complexity: OCaml's persistent set library exploits balanced binary search trees.

The function save _ context is invoked by the parser when opening a new scope. This function returns !current, an immutable set of identifiers: in other words, a snapshot of the current context. This snapshot can be later re-installed (if and when desired) by invoking restore _ context. This function simply writes its argument into current. These two functions have constant time complexity.

The module Context does not internally maintain a stack. Nor does its API impose a stack discipline: calls to save _ context and restore _ context need not be balanced. Thus, the API is very simple and powerful.

3.3.2. Where contexts are saved and restored. For convenience, we define a nonterminal symbol, save _ context, which generates the empty sentence, as follows:

save _ context: ( * empty * ) { save _ context() }
When this production is reduced, its semantic action is executed and returns a snapshot of the current context. We use this nonterminal symbol at any point in the grammar where we need to save the current context in order to prepare for a possible later re-installation. We may do so quite freely, for the following reasons:

-Because save _ context generates the empty sentence, its use has no effect on the language that is accepted by the parser. -As noted earlier, the runtime cost of saving the context is very low.

-Since calls to save _ context and restore _ context need not be balanced, we may use save _ context wherever we please, without worrying about matching calls to restore _ context.

One possible adverse effect of inserting occurrences of save _ context in the grammar is that this can create new shift/reduce conflicts. Such a conflict is typically between reducing the production save _ context: ( * empty * ) (which means: take a snapshot now!) and shifting (which means: make progress in some other productions p 1 , p 2 , . . .). We avoid all such conflicts by adding redundant occurrences of save _ context in the productions p 1 , p 2 , . . . By doing so, we instruct the parser to always take a snapshot now, even in situations where it is not known yet whether this snapshot will be useful in the future.

Most calls to save _ context and restore _ context come in matching pairs. In that case, for documentation and for conciseness, it is desirable to phrase the grammar in terms of a high-level notion of "scope", instead of low-level function calls. To this end, we define a parameterized nonterminal symbol, scoped(X):

scoped(X): ctx = save _ context x = X { restore _ context ctx; x }
The parameter X stands for a (terminal or nonterminal) symbol. By definition, scoped(X) generates the same language as save _ context X, which itself generates the same language as X. The difference between scoped(X) and X is in the semantic actions: when one uses scoped(X), the current context is saved initially and restored at the end4 . More precisely, when the production scoped(X): save _ context X is reduced, the top two cells of the parser's stack respectively contain a saved context ctx and an abstract syntax tree x for the symbol X. The semantic action restore _ context ctx; x re-installs the context ctx and returns x. This explains why we do not need to explicitly maintain a stack of contexts: saved contexts are naturally stored in the parser's stack. An analogous idea appears in Bison's manual [Donnelly and Stallman 2015, 3.4.8.1]. It is unfortunately expressed in a much lower-level style that makes it more difficult to understand and notationally heavier.

We use this construction, among other places, in the syntax of statements:

statement: labeled _ statement | scoped(compound _ statement) | expression _ statement | scoped(selection _ statement) | scoped(iteration _ statement) | jump _ statement {}
This elegantly reflects the fact that compound statements, selection statements, and iteration statements form a "block" (Section 2.1.4) and therefore require opening and closing a new scope. Function definitions are more difficult to deal with, in part because one cannot distinguish a declaration and a function definition until one reaches a function body, and in part because in a function definition the scope where the parameters are visible is noncontiguous. (Both phenomena have been illustrated in Section 2.1.4.)

To deal with these difficulties, we build (simplified) abstract syntax trees for declarators. An abstract syntax tree of OCaml type declarator stores the identifier that is declared and (if this is a function declarator) a snapshot of the context at the end of the parameter list. The API offered by these abstract syntax trees is as follows: The accessor function identifier retrieves the identifier that is declared by a declarator. It is used in the definition of the nonterminal symbols declarator _ varname and declarator _ typedefname, which recognize the same language as declarator and have the added side effect of declaring this identifier (as a variable or as a typedef name, respectively) in the current scope: The accessor function reinstall _ function _ context expects its argument d to be a function declarator. It retrieves the context that was saved at the end of the parameter list and re-installs it (by invoking restore _ context). On top of that, it declares the function's name as a variable, by calling declare _ varname (identifier d).

Putting the pieces together, a function definition is described as follows:

function _ definition1: declaration _ specifiers d = declarator _ varname { let ctx = save _ context () in reinstall _ function _ context d; ctx } function _ definition: ctx = function _ definition1 declaration _ list? compound _ statement { restore _ context ctx }
Assume, for the sake of simplicity, that the parser is reading a function definition whose declaration _ list? is empty. Then, the nonterminal symbol function _ definition1 is reduced when the parser looks ahead at the opening brace that forms the beginning of the coumpound _ statement. At this point, the current context is saved under the name ctx.

(This context includes the function's name, declared as a variable, because we have used declarator _ varname.) Then, the call reinstall _ function _ context d restores the context that existed at the end of the parameter list (which has been saved as part of the abstract syntax tree d) and, on top of it, declares the function's name. The function body is parsed in this scope. Upon completion, this scope is closed by restoring the context ctx.

3.3.3. Where declarations take effect. In the C11 grammar, "variable" declarations and "type" declarations are described by a single nonterminal symbol, declaration [ISO 2011, 6.7]. In our parser, however, we must know, at the end of each declarator, whether this declarator introduces a new variable or a new typedef name. Indeed, we must make the lexer aware of this new name, by updating the current context.

For this reason, we distinguish between two kinds of declarations: those that contain one occurrence of the typedef keyword, and those that do not. (The C11 standard forbids multiple occurrences of typedef.) A list of declaration specifiers that does not contain typedef is described by the nonterminal symbol declaration _ specifiers, whereas a list that contains one occurrence of typedef is described by the nonterminal symbol declaration _ specifiers _ typedef. (The definitions of these symbols are given and explained in Section 3.4.)

This allows us to distinguish between "variable" declarations and "type" declarations, as follows: The symbols init _ declarator _ list and init _ declarator are defined as in the C11 grammar, except they are parameterized over declarator. This parameter can be instantiated, as desired, with declarator _ varname or declarator _ typedefname (whose definitions have been shown in Section 3.3.2). Thus, we obtain the desired effect: the absence or presence of typedef among the declaration specifiers influences the manner in which the declarators update the current context.

3.3.4. Token sequences for identifiers. The lexer uses the current context in order to classify identifiers and emit appropriate tokens. However, an LALR(1) parser may request one token from the lexer, known as a "lookahead" token, before it decides whether a production should be reduced and which production should be reduced. As noted earlier (Section 2.2.2), this introduces a danger of mis-classification of an identifier by the lexer. Indeed, the lexer classifies this identifier in the current scope, whereas perhaps the parser is just about to perform a reduction that affects the current scope (by declaring a new identifier in this scope, or by closing this scope). This is not just a theoretical possibility: it is the root of the bug that we have identified in GCC [START_REF] Jourdan | GCC bug #67784: Incorrect parsing when using declarations in for loops and typedefs[END_REF]].

Some parser generators, such as Bison, guarantee that, in a "defaulted state", the parser will not request a lookahead token from the lexer 5 . By relying on this feature, one might hope to cleverly avoid the danger. We have no such luck, though: in the example of Section 2.2.2, the problem arises in a state where the parser will either shift the token ELSE or reduce the production selection _ statement: IF LPAREN expression RPAREN scoped(statement). (This is the very state where the "dangling else" shift-reduce conflict arises.) This is not a defaulted state: hence, the guarantee offered by Bison does not help. Furthermore, Menhir does not at present offer this guarantee, so we would rather not rely on it.

To work around this danger, we introduce an original idea. Upon encountering an identifier, our lexer emits a sequence of two tokens. The first token is always NAME. It is produced by the lexer without consulting the global state. The second token is either VARIABLE or TYPE, depending on the current status of this identifier. Because the distinction is delayed until the second token is demanded by the parser, the danger of mis-classification disappears. By the time the second token is demanded, the global state must have been updated already (if necessary) and cannot be outdated. Indeed, one can check 6 that no production with a side effect can be reduced when the lookahead token is "fragile", that is, when it is VARIABLE or TYPE.

Our grammar has three nonterminal symbols that correspond to an identifier 7 :

typedef _ name: i = NAME TYPE { i } var _ name: i = NAME VARIABLE { i } general _ identifier: i = typedef _ name | i = var _ name { i }
Where the C11 grammar uses typedef-name, we use typedef _ name. Where the C11 grammar uses identifier, we use var _ name or general _ identifier. More precisely, var _ name is used when referring to a variable in an expression (primary _ expression: var _ name [ISO 2011, 6.5.1, §2]) or in the identifier list of a K&R function declarator 8 (identifier _ list: var _ name | identifier _ list COMMA var _ name), whereas general _ identifier is used everywhere else.

Controlling type specifiers in declarations and struct declarations

As explained in Section 2.3, the C11 grammar exhibits an ambiguity in the syntax of declarations. This ambiguity gives rise in the grammar G 2 to a shift/reduce conflict (Section 3.1). In short, this conflict can be explained as follows: when the parser has read a list of declaration specifiers and finds that the next input symbol is a typedef name, it must choose between shifting (which means that the list of declaration specifiers is not finished, and this typedef name is a type specifier) and reducing (which means that the list of declaration specifiers is finished, and this typedef name is the beginning of a declarator). This conflict cannot be solved via a precedence declaration. Indeed, neither "always shift" nor "always reduce" is the correct behavior.

As explained in Section 2.3, in order to eliminate the ambiguity, the C11 standard imposes a well-formedness constraint on lists of declaration specifiers [ISO 2011, ple, the semantic actions might pop a scope stack that yylex uses to determine what token to return. Thus, the delay might be necessary to ensure that yylex does not look up the next token in a scope that should already be considered closed." 6 In our grammar, VARIABLE and TYPE always follow NAME. In other words, they never follow a nonterminal symbol, and they are never the first symbol in a right-hand side. Therefore, no reduction can possibly take place when VARIABLE or TYPE is the lookahead symbol. This reasoning holds even in the presence of default reductions. 7 In Menhir, the syntax "i =" introduces an OCaml variable i and binds it to the semantic value of the symbol that follows. (An analogous feature in Bison is known as a "named reference" [Donnelly and Stallman 2015, §3.6].) Here, one could also remove all occurrences of "i =" and write "$1" instead of "i" in the semantic actions.

8 The C11 standard [ISO 2011, 6.9.1, §6] does not allow a typedef name to occur in the identifier list of a K&R function declarator. Indeed, it prescribes: "An identifier declared as a typedef name shall not be redeclared as a parameter".

6.7.2, §2

]. Similarly, in order to eliminate the shift/reduce conflict, we must encode this constraint into our grammar. Fortunately, we need not enforce this constraint exactly. We may enforce a weaker constraint, provided it is still strong enough to eliminate the conflict. Checking that the C11 standard is respected is deferred to a later semantic analysis. Our aim is to keep our grammar as simple as possible.

We split type specifiers in two disjoint categories:

-"Unique" type specifiers cannot occur together with any other type specifiers in a declaration. They are void, _ Bool, atomic type specifiers, struct or union specifiers, enumeration specifiers, and typedef names. -"Nonunique" type specifiers can occur together with other (nonunique) type specifiers in a declaration. They are char, short, int, long, float, double, signed, unsigned and _ Complex.

It follows from paragraph 6.7.2, §2 that a list of declaration specifiers either contains exactly one unique type specifier or contains one or more nonunique type specifiers. Fortunately, lists restricted by simple numeric constraints can be described in the formalism of LR(1) grammars. For instance, the parameterized nonterminal symbol list _ eq1(A, B) describes a list whose elements are A's or B's and which contains exactly one element of type A:

list _ eq1(A, B): A B * | B list _ eq1(A, B) {}
This definition states that such a list either begins with A, in which case the remainder of the list must match B * , or begins with B, in which case the remainder of the list must match list _ eq1(A, B) again. Similarly, we define list _ ge1(A, B), which describes a list whose elements are A's or B's and which contains at least one element of type A:

list _ ge1(A, B): A B * | A list _ ge1(A, B) | B list _ ge1(A, B) {}
Equipped with these tools, we can easily require every list of declaration specifiers to either contain exactly one unique type specifier or contain at least one nonunique type specifier: declaration _ specifiers: list _ eq1(type _ specifier _ unique, declaration _ specifier) | list _ ge1(type _ specifier _ nonunique, declaration _ specifier) {}

The nonterminal symbols type _ specifier _ unique and type _ specifier _ nonunique are as described above. The nonterminal symbol declaration _ specifier corresponds to a declaration specifier that is neither a type specifier nor the typedef keyword. (Our handling of typedef is discussed below.) This grammar fragment is amenable to LR(1) parsing. As long as it finds declaration _ specifiers, the LR automaton accumulates them on its stack, exploring in parallel the possibility that this could be a list _ eq1(type _ specifier _ unique, ...) and the possibility that this could be a list _ ge1(type _ specifier _ nonunique, ...). As soon as it finds a type specifier (which must be either unique or nonunique, but cannot be both), one of these possibilities is discarded.

The nonterminal symbol declaration _ specifiers _ typedef, which was mentioned earlier (Section 3.3.3), is defined in an analogous manner. Like declaration _ specifiers, it requires the list to either contain exactly one unique type specifier or contain at least one nonunique type specifier. In addition, it requires the list to exhibit exactly one occurrence of typedef. declaration _ specifiers _ typedef: list _ eq1 _ eq1(TYPEDEF, type _ specifier _ unique, declaration _ specifier) | list _ eq1 _ ge1(TYPEDEF, type _ specifier _ nonunique, declaration _ specifier) {}

The parameterized nonterminal symbol list _ eq1 _ eq1(A, B, C) describes a list of A's, B's, and C's that contains exactly one A and exactly one B. Similarly, list _ eq1 _ ge1(A, B, C) describes a list of A's, B's, and C's that contains exactly one A and at least one B. Their definitions are omitted.

Wrapping up

We have presented the main two ingredients of our approach, namely the original manner in which we set up lexical feedback (Section 3.3) and the manner in which we avoid the conflict caused by the "declaration" ambiguity (Section 3.4). There remain two conflicts in the grammar. They are statically solved, as follows.

The "dangling else" ambiguity (Section 2.2) gives rise to a well-known shift-reduce conflict. This conflict is solved via a suitable precedence declaration [Aho et al. 1986, Chapter 4], which causes shifting to be preferred to reduction when the lookahead symbol is ELSE:

selection _ statement: IF LPAREN expression RPAREN scoped(statement) ELSE scoped(statement) | IF LPAREN expression RPAREN scoped(statement) %prec below _ ELSE | SWITCH LPAREN expression RPAREN scoped(statement)
The "parameter declaration" ambiguity (Section 2.4) gives rise in our grammar to a reduce/reduce conflict. Initially, this conflict is between the productions general _ identifier: typedef _ name (Section 3.3.4) and type _ specifier _ unique: typedef _ name (Section 3.4). It appears in only one state of the automaton, and only when the lookahead symbol is '(', ')', or '['. By studying how one may reach this situation, one finds that it is reachable only via a parameter declaration. Thus, paragraph 6.7.6.3, §11 applies, and prescribes that the typedef name on top of the parser's stack should be viewed as a type specifier. Thus, the parser generator must be instructed to always reduce the second of the above two productions. Menhir, like Bison [Donnelly and Stallman 2015, §5.6], always favors the production that appears first in the grammar. In our grammar, the production general _ identifier: typedef _ name happens to come first, and we do not wish to change that, as we want to keep the rules in the same order as they appear in the C11 grammar [ISO 2011, A.2]. So, we replace type _ specifier _ unique: typedef _ name with type _ specifier _ unique: typedef _ name _ spec and add the production typedef _ name _ spec: typedef _ name at the beginning of the grammar. This has the desired effect.

The " _ Atomic(" ambiguity (Section 2.5) gives rise to a shift/reduce conflict in the grammars G 1 and G 2 (Section 3.1). Fortunately, in our grammar, this conflict is gone. As explained in Section 2.5, the restriction imposed by paragraph 6.7.2, §2 eliminates the ambiguity; and we are fortunate enough that our implementation of this restriction (Section 3.4) eliminates the conflict.

Because the restriction of paragraph 6.7.2.4, §4 is not necessary, our parser does not, by default, implement it. Therefore, it accepts a slightly larger language than prescribed by the C11 standard. For instance, it accepts the following noncompliant code:

// atomic _ parenthesis.c int _ Atomic (x);
In case strict compliance is needed, our parser can be configured to enforce the restriction of paragraph 6.7.2.4, §4 and reject the above code. To do this, we let the lexer emit the special token ATOMIC _ LPAREN, instead of LPAREN, when it encounters an opening parenthesis that immediately follows an _ Atomic keyword. Furthermore, we add the production atomic _ type _ specifier: ATOMIC ATOMIC _ LPAREN type _ name RPAREN. Thus, a parenthesis that follows _ Atomic must be part of an atomic type specifier; it cannot be interpreted in any other way.

RELATED WORK

Our approach to parsing C11 combines a deterministic parser (produced by an LALR(1) parser generator, based on a slightly modified version of the C11 grammar) and a deterministic "lexical feedback" mechanism, which distinguishes between variables and typedef names. This approach follows a well-established tradition, which we discuss in Section 4.1. However, there are other approaches to parsing C (and, more generally, C++), which we discuss in Section 4.2.

LR parsers and lexical feedback

Lexical feedback in an LR parser is a well-known technique, and has been in use for a long time. Mason, Brown, and Levine's book [Brown et al. 1992, Chapter 7] offers a brief description of it. It is however a rather subtle and fragile technique, due in particular to a possible adverse interaction between lexical feedback and lookahead. There is a danger that the lexer reads one token ahead, before the parser has updated the global state that informs the lexer. This would cause the lexer to deliver an incorrect token. The issue is complicated by the fact that, in the presence of default reductions, it can be hard to understand exactly when the parser requests a new token from the lexer.

This issue, as well as the problem of classifying identifiers in a C parser, is discussed at length in a very interesting thread on the newsgroup comp.compilers [lex 1992].

Deep in this thread, Jim Roskind explains how to prove the absence of adverse interaction between lexical feedback and lookahead: "[one] must show that [no] reductions involved with annotation of [the] symbol table take place while [a fragile token] is waiting in the lookahead buffer". We have used this argument in Section 3.3.4, where (in our case) no reduction at all can take place when the lookahead token is a fragile token (that is, VARIABLE or TYPE). Roskind also asserts that "the typedef-ness of an identifier can change only after a declarator is complete". Technically, this is false: it can change also when a scope is closed and when defining a new enumeration constant. In ANSI C, at the end of a scope, the lookahead token must be '}' or ')', neither of which is fragile, so all is well. In C99, however, a selection statement forms a block, so a scope is closed at the end of such a statement. Due to the "if-else" ambiguity, determining whether an if statement is finished requires looking ahead at the next token, which could be fragile. Therefore, there is a danger of misclassification, which we have discussed in Section 2.2.2, identifying a bug in GCC [START_REF] Jourdan | GCC bug #67784: Incorrect parsing when using declarations in for loops and typedefs[END_REF]].

In the same thread, Dale R. Worley puts forth the idea that, in order to eliminate the ambiguity in declarations, "the grammar must keep track of whether a type-specifier has been seen in the declaration-specifiers". His changes to the grammar are analogous in spirit to those we present in Section 3.4. We keep track of more information (namely, the distinction between unique and nonunique type specifiers, and the absence or presence of typedef) and we use parameterized nonterminal symbols to preserve readability.

Roskind is the author of an LALR(1) grammar for ANSI C and for C++. These grammars are available online [START_REF] Roskind | A grammar for ANSI C[END_REF]], together with detailed explanations, which unfortunately seem to concern mostly C++. Roskind goes to great lengths to eliminate ambiguity: his ANSI C grammar exhibits only one shift/reduce conflict, namely the benign "dangling else" conflict, and no reduce/reduce conflict. The subgrammars of declarations, parameter declarations, and declarators appear to have been quite deeply re-worked. Unfortunately, Roskind's published grammar does not contain semantic actions; it would take some work to reconstruct the lexical feedback mechanism.

Up until version 3.4.4, GCC used an LALR(1) parser [The GNU project 2004]. Like Roskind's [START_REF] Roskind | A grammar for ANSI C[END_REF]] and Worley's (cited above), this parser has (deeply) re-worked subgrammars of declarations, declarators, declaration specifiers, etc. It uses explicit auxiliary stacks to keep track of which scopes have been opened and (in a declaration) which declaration specifiers have been seen. It also stores information on the parser's stack, in the same way as we store saved contexts on the parser's stack (Section 3.3.2). We are perhaps the first to point out that no auxiliary stack is needed. Since version 4.0.0, GCC uses a hand-written recursive descent parser, which today is about 16Kloc. This parser accepts a much larger language than C11: it accepts Objective C as well as many GNU extensions.

Clang, too, uses a hand-written recursive descent parser. Even though the recursive descent parsers in GCC and Clang are hand-written, they use a lexical feedback mechanism, or "lexer hack". Some claim that Clang's approach does not use a "hack" [Bendersky 2012]. In our eyes, whether the global state resides in the lexer itself, or in a separate "symbol table" module (such as our Context module, presented in Section 3.3.1) makes relatively little difference: the on-the-fly classification of identifiers remains difficult to get right, as evidenced by the bug that we found in GCC [START_REF] Jourdan | GCC bug #67784: Incorrect parsing when using declarations in for loops and typedefs[END_REF]].

The CompCert C compiler [START_REF] Leroy | Formal verification of a realistic compiler[END_REF][START_REF] Leroy | The CompCert C verified compiler[END_REF]] contains two parsers. The Com-pCert "pre-parser" (in cparser/pre _ parser.mly) is an LALR(1) parser equipped with a lexical feedback mechanism. The C11 parser presented in this paper is based on it. The pre-parser is in charge of detecting and reporting syntax errors, following a technique proposed by Jeffery [START_REF] Jeffery | Generating LR syntax error messages from examples[END_REF]] and implemented in Menhir by the second author [START_REF] Pottier | Reachability and error diagnosis in LR(1) parsers[END_REF]]. The CompCert "parser" (in cparser/Parser.vy) is also an LALR(1) parser, but does not need lexical feedback: it parses the input again, exploiting the classification of identifiers that has been performed already by the pre-parser. As a result, it is very simple. Its grammar is very close to the C11 grammar. It is LALR(1): it has no conflicts whatsoever. In particular, the "dangling else" conflict is resolved by distinguishing "open-ended" and "non-open-ended" if statements (Section 2.2.2). This is done without actually duplicating the subgrammar of statements, thanks to parameterized terminal symbols. Out of this grammar, Menhir produces an executable parser, written in the Coq programming language, whose correctness can be verified by the Coq proof assistant [START_REF] Jourdan | Validating LR(1) Parsers[END_REF]. [START_REF] Van Wyk | Context-aware Scanning for Parsing Extensible Languages[END_REF] propose a "contextaware" variant of the LR algorithm where the parser passes to the lexer a "valid lookahead set", that is, a set of valid symbols that the lexer is permitted to return at this point. However, this does not solve the "typedef name" ambiguity, so, when parsing C, lexical feedback is still required [Van Wyk and Schwerdfeger 2007, §6.1]. Furthermore, because the computation of the lookahead symbol depends on the current control state of the parser, the lookahead symbol must be re-computed after each reduction [Van Wyk and Schwerdfeger 2007, §6.2.1]. Van Wyk and Schwerdfeger use this technique to develop an extensible variant of ANSI C.

A short paper by Scarpazza [START_REF] Paolo | Practical Parsing for ANSI C[END_REF]] presents an approach to parsing ANSI C using flex, Bison, and lexical feedback. When parsing a declaration, Scarpazza insists that the identifier that is being declared should be classified by the lexer as a variable. (In contrast, we let the lexer randomly classify this identifier, and compensate by accepting general _ identifier in our grammar.) This leads Scarpazza to set up an elaborate form of lexical feedback, whereby the parser keeps track of "type stacks" and uses them to inform the lexer.

Other approaches

Nondeterministic parsing algorithms support general (possibly ambiguous) contextfree grammars. Examples of such algorithms include various forms of backtracking LR, as implemented for instance in BtYacc [START_REF] Dodd | BtYacc[END_REF]; GLR [Grune and Jacobs 2008, §11.1]; Earley's algorithm [Grune and Jacobs 2008, §7.2]; and many more. These algorithms explore several potential parses (either one after the other or in parallel), discarding those that lead to a syntax error.

Because they support ambiguous grammars, nondeterministic parsing algorithms can be applied, without lexical feedback, to the C11 grammar, as it appears in the C11 standard. In the newsgroup thread cited earlier [lex 1992], Jan Rekers argues in favor of using GLR, without lexical feedback, for parsing C. Baxter et al. [START_REF] Baxter | DMS R : Program Transformations for Practical Scalable Software Evolution[END_REF]] also report using GLR to parse many languages, including C and C++.

McPeak and Necula present a hybrid GLR/LR parsing algorithm, and use it in a C++ parser [START_REF] Mcpeak | Elkhound: a Fast, Practical GLR Parser Generator[END_REF]. However, this approach does not magically eliminate the difficulty of parsing C11. Because the C11 grammar is ambiguous, a nondeterministic parsing algorithm produces an exponential number of potential parse trees. Well-formedness filters (applied either a posteriori or on the fly) are necessary so as to discard those trees that do not respect the informal prose in the C11 standard. These filters must implement the scoping rules as well as several paragraphs of the standard that have been cited in Section 2. They could be just as difficult to implement correctly as lexical feedback.

A nondeterministic parsing algorithm can also be used with lexical feedback. In that case, the side effects of the semantic actions must be undone when backtracking. For instance, Thurston and Cordy develop a backtracking LR algorithm and apply it to C++ [START_REF] Thurston | A Backtracking LR Algorithm for Parsing Ambiguous Context-dependent Languages[END_REF]. Their paper contains a good survey of the related work in this area.

A way of avoiding lexical feedback, which may be used in a deterministic or nondeterministic parser, is to modify the grammar so that it does not require a distinction between variables and typedef names, yet is not ambiguous. This may require unifying several syntactic categories that are considered distinct in the official grammar. For instance, a parser might recognize "T * b" as a "declaration-or-expression", letting a later semantic analysis determine whether (in the context where it occurs) it should be interpreted as a declaration or as an expression. Willink [Willink 2001, Chapter 5] adopts this approach, which he calls the "superset grammar" approach, in a nondeterministic parser for C++. This approach may well be applicable to C11. Unfortunately, it imposes pervasive changes on the grammar and requires implementing an ad hoc semantic analysis. It may be difficult to argue that the modified grammar, in conjunction with the semantic analysis, complies exactly with the C11 standard.

Grimm [START_REF] Grimm | Better extensibility through modular syntax[END_REF]] describes Rats!, a parser generator based on parsing expression grammars (PEGs), as opposed to context-free grammars. Instead of symmetric choice, PEGs offer an ordered choice operator, therefore eliminating all ambiguity by construction. They also support syntactic predicates, which match the input without consuming it. PEG parsers are backtracking parsers. They achieve linear time and space complexity via memoization. Grimm discusses the use of Rats! to parse C [Grimm 2006, §5]. He notes that the added power of PEGs makes it easier to deal with certain aspects of C. For instance, there is no need to alter the grammar so as to track the presence of type specifiers in a sequence of declaration specifiers, as we did in Section 3.4. To classify identifiers, Grimm uses a standard lexical feedback mechanism. In the presence of backtracking, the side effects required by this mechanism must be performed within (nested) transactions.

Semantic predicates makes it possible to invalidate a production based on an arbitrary predicate evaluated at parse time. They are available in several parser generators, including Rats!, ANTLR and in the GLR mode of Bison. They could, in principle, lift the need for a lexical feedback mechanism by disabling the reductions containing an identifier token when this identifier does not have the right status in the current environment. However, to the best of our knowledge, we are not aware of any C11 parser that would use semantic predicates.

We have assumed that the C source code has been preprocessed and therefore contains no preprocessor directives. In contrast, some authors attempt to parse without expanding macros, without reading #included files, and/or without resolving static conditionals.

Padioleau [START_REF] Padioleau | Parsing C/C++ Code Without Pre-processing[END_REF]], for instance, performs neither of these three tasks. He extends the grammar of C with new terminal symbols, including #include, #ifdef, etc., as well as several classes of identifiers. Indeed, in addition to typedef names and variables, he wishes to recognize identifiers that denote macros. Furthermore, he wishes to distinguish between several typical families of macros, such as macros that expand to statements, macros that expand to loop headers, and so on. This classification involves heuristic aspects (for instance, it exploits indentation). It takes the form of a transformation of the token stream, which is inserted between the lexer and the parser. Padioleau's work is used in Coccinelle [START_REF] Padioleau | Documenting and automating collateral evolutions in Linux device drivers[END_REF], a tool that helps analyze and evolve C code.

Gazzillo and Grimm [START_REF] Gazzillo | SuperC: Parsing All of C by Taming the Preprocessor[END_REF] expand macros and read #included files, but do not resolve static conditionals, as they wish to parse all possible "configurations" of the software simultaneously. They introduce a new LR engine, Fork-Merge-LR, which relies on standard LALR(1) parse tables. Like GLR, it is a nondeterministic parsing algorithm. However, the need for nondeterminism does not stem from ambiguity in the grammar; it stems from the desire to parse all possible configurations simultaneously. Gazzillo and Grimm's use Roskind's grammar, extended with support for common gcc extensions. Their parser uses a form of lexical feedback [Gazzillo and Grimm 2012, §5.2]. When it encounters an identifier that denotes a typedef name in one configuration and a variable in another configuration, it forks two subparsers.

CONCLUSION

In this paper, we have reviewed several of the difficulties that arise in writing a C11 parser, and we have presented such a parser. It is a slightly simplified version of the "pre-parser" found in the CompCert C compiler.

It is very concise: the grammar, including (just) the semantic actions necessary to perform lexical feedback, is under 500 (nonblank, noncomment) lines of code; the lexer and the support code are less than 400 lines.

To the best of our knowledge, this parser complies with the C11 standard. However, it has not been extensively tested. (Running it on large existing code bases would require extending it with support for the most commonly used extensions of C, such as the GNU extensions.) We offer only a small suite of "tricky" C11 programs that can be used as a "torture test".

There exist many commercial and academic tools that can parse C. Some of them have been discussed in Section 4. Unfortunately, these parsers are often either designed for an older version of the language (such as C89) or plain incorrect. The C11 parsers found in popular compilers, such as GCC and Clang, are very likely correct, but their size is in the tens of thousands of lines. Therefore, we believe that there is a need for a simple reference implementation that is easy to adopt and extend. We hope that our parser can play this role.

Although we discuss only C11 in this paper, our parser can also parse C99, which is a subset of C11. C89, on the other hand, is not a subset of C11. There are differences concerning the scoping rules and, more importantly, the "implicit int" rule, which allows declarations without a type specifier, in which case the default type int is used [ANSI 1989, 3.5.2]. This makes C89 more difficult to parse. Our distribution [START_REF] Jourdan | A simple, possibly correct LR parser for C11 -implementation and test suite[END_REF]] includes a C89 parser, which is separate from our C11 parser. (It is based on a different grammar.) It supports the "implicit int" rule, handles all C11 constructs, and supports either set of scoping rules, depending on its configuration. Therefore, when configured to use the C89 scoping rules, this parser accepts every C89 program; and, when configured to use the C99/C11 scoping rules, it accepts every C99 or C11 program. For the sake of brevity, it is not discussed in the paper. [ioption(X)] is the same thing, but is inlined at its use site, which in some cases is necessary in order to avoid a conflict. The first field is a named t, while the second is unnamed of type t.

/

  / bitfield _ declaration _ ambiguity.c typedef signed int T; struct S { unsigned T:3; // bit-field named T with type unsigned const T:3; // anonymous bit-field with type const T };

  . * ) val identifier _ declarator: string -> declarator val function _ declarator: declarator -> context -> declarator val other _ declarator: declarator -> declarator ( * Accessors. * ) val identifier: declarator -> string val reinstall _ function _ context: declarator -> unit The three constructors above are used in the semantic actions associated with the nonterminal symbols declarator and direct _ declarator. For instance, the following production recognizes a function declarator and builds an abstract syntax tree for it: direct _ declarator: ... | d = direct _ declarator LPAREN ctx = scoped(parameter _ type _ list) RPAREN { function _ declarator d ctx } | ... The variable ctx above represents a snapshot of the context at the end of the parameter list. This stems from the following definition: parameter _ type _ list: parameter _ list option(COMMA ELLIPSIS {}) ctx = save _ context { ctx }

  { declare _ typedefname (identifier d); d }

  init _ declarator _ list(declarator _ varname)? SEMICOLON | declaration _ specifiers _ typedef init _ declarator _ list(declarator _ typedefname)? SEMICOLON | static _ assert _ declaration {}

  %token CONSTANT STRING _ LITERAL %token ALIGNAS ALIGNOF ATOMIC BOOL COMPLEX IMAGINARY GENERIC NORETURN STATIC _ ASSERT THREAD _ LOCAL AUTO BREAK CASE CHAR CONST CONTINUE DEFAULT DO DOUBLE ELSE ENUM EXTERN FLOAT FOR GOTO IF INLINE INT LONG REGISTER RESTRICT RETURN SHORT SIGNED SIZEOF STATIC STRUCT SWITCH TYPEDEF UNION UNSIGNED VOID VOLATILE WHILE %token PTR INC DEC LEFT RIGHT LEQ GEQ EQEQ EQ NEQ LT GT ANDAND BARBAR PLUS MINUS STAR TILDE BANG SLASH PERCENT HAT BAR QUESTION COLON AND MUL _ ASSIGN DIV _ ASSIGN MOD _ ASSIGN ADD _ ASSIGN SUB _ ASSIGN LEFT _ ASSIGN RIGHT _ ASSIGN AND _ ASSIGN XOR _ ASSIGN OR _ ASSIGN LPAREN ATOMIC _ LPAREN RPAREN LBRACK RBRACK LBRACE RBRACE DOT COMMA SEMICOLON ELLIPSIS %token EOF %type<context> save _ context parameter _ type _ list function _ definition1 %type<string> typedef _ name var _ name general _ identifier enumeration _ constant %type<declarator> declarator direct _ declarator ( * There is a reduce/reduce conflict in the grammar. It corresponds to the conflict in the second declaration in the following snippet: typedef int T; int f(int(T)); It is specified by 6.7.6.3 11: 'T' should be taken as the type of the parameter of the anonymous function taken as a parameter by f (thus, f has type (T -> int) -> int). The reduce/reduce conflict is solved by letting menhir reduce the production appearing first in this file. This is the reason why we have the [typedef _ name _ spec] proxy: it is here just to make sure the conflicting production appears before the other (which concerns [general _ identifier]). * ) ( * These precedence declarations solve the dangling else conflict. * ) %nonassoc below _ ELSE %nonassoc ELSE %start<unit> translation _ unit _ file %% ( * Helpers * ) ( * [option(X)] represents a choice between nothing and [X].

[

  declaration _ specifiers] forbids the [TYPEDEF] keyword. * ) declaration _ specifiers: | list _ eq1(type _ specifier _ unique, declaration _ specifier) | list _ ge1(type _ specifier _ nonunique, declaration _ specifier) {} ( * [declaration _ specifiers _ typedef] is analogous to [declaration _ specifiers], but requires the [TYPEDEF] keyword to be present (exactly once). * ) declaration _ specifiers _ typedef: | list _ eq1 _ eq1(TYPEDEF, type _ specifier _ unique, declaration _ specifier) | list _ eq1 _ ge1(TYPEDEF, type _ specifier _ nonunique, declaration _ specifier) {} ( * The parameter [declarator] in [init _ declarator _ list] and [init _ declarator] is instantiated with [declarator _ varname] or [declarator _ typedefname]. * ) init _ declarator _ list(declarator): | init _ declarator(declarator) | init _ declarator _ list(declarator) COMMA init _ declarator(declarator) {}

  is a type again } Both variable declarations and type declarations may appear in an inner scope. A variable declaration can hide a type declaration, and vice-versa:

	// local _ typedef.c
	typedef int T1;	// Declaration of type T1 as int
	void f(void) {
	typedef int * T2;	// Declaration of type T2 as pointer to int
	T1 x1;	// Declaration of x1 of type T1
	T2 x2;	// Declaration of x2 of type T2
	x1 = 0;
	x2 = 0;
	}

  , §5]:On the other hand, expression statements, return statements, and labelled statements do not give rise to new scopes:

	// loop _ scopes.c
	typedef int T, U;
	int x;
	void f(void) {
	for(int T = 0; sizeof(enum {U}); ) x = U+T;
	for(sizeof(enum {U}); ; ) x = U + sizeof(enum {T});
	while(sizeof(enum {U})) x = U;
	// A declaration in the body of a do ... while loop
	// is not visible in the loop condition.
	do x = sizeof(enum {U}) + U;
	while((U)1 + sizeof(enum {U}));
	// The above declarations of T and U took place in inner scopes
	// and are no longer visible.
	T u3; U u4;
	}

  By convention, [X?] is syntactic sugar for [option(X)]. * ) We separate type declarations, which contain an occurrence of [TYPEDEF], and normal declarations, which do not. This makes it possible to distinguish /in the grammar/ whether a declaration introduces typedef names or variables in the context. * ) declaration _ specifiers] requires that at least one type specifier be present, and, if a unique type specifier is present, then no other type specifier be present. In other words, one should have either at least one nonunique type specifier, or exactly one unique type specifier. This is a weaker condition than 6.7.2 2. Encoding this condition in the grammar is necessary to disambiguate the example in 6.7.7 6:

	constant _ expression:
	| conditional _ expression
	{}
	( * declaration:
	| declaration _ specifiers	init _ declarator _ list(declarator _ varname)?	SEMICOLON
	| declaration _ specifiers _ typedef init _ declarator _ list(declarator _ typedefname)? SEMICOLON
	| static _ assert _ declaration
	{}
	( * [declaration _ specifier] corresponds to one declaration specifier in the C11
	standard, deprived of TYPEDEF and of type specifiers. * )
	declaration _ specifier:
	| storage _ class _ specifier ( * deprived of TYPEDEF * )
	| type _ qualifier
	| function _ specifier
	| alignment _ specifier
	{}
	( * [typedef signed int t;
	struct tag {
	unsigned t:4;
	const t:5;
	};
	%inline ioption(X):
	| / * nothing * /
	| X
	{}

ACM Transactions on Programming Languages and Systems, Vol. 39, No. 4, Article 14, Publication date: August 2017.

The production direct-abstract-declarator: direct-abstract-declarator opt [ * ] [ISO

2011, 6.7.7, §1] does not allow const to appear here. This is an asymmetry with the production direct-declarator: direct-declarator [ type-qualifier-list opt * ], which allows it. We do not have an explanation for this asymmetry. It would be possible to relax the syntax of abstract declarators without introducing a conflict.ACM Transactions on Programming Languages and Systems, Vol. 39, No. 4, Article 14, Publication date: August 2017.

This idea probably goes back to the early days of the B and C programming languages, circa 1969-70[START_REF] Ritchie | The Development of the C Language[END_REF]]. In any case, it explicitly appears in[START_REF] Kernighan | The C Programming Language, Second Edition[END_REF] Ritchie's 1988 book [Kernighan and Ritchie 1988, §A.13], which describes "K&R C". They write: "With one further change, namely deleting the production typedef-name: identifier and making typedef-name a terminal symbol, this grammar is acceptable to the YACC parser-generator. It has only one conflict, generated by the if-else ambiguity." ACM Transactions on Programming Languages and Systems, Vol.

39, No. 4, Article 14, Publication date: August 2017.

In OCaml, ! dereferences a mutable variable. ACM Transactions on Programming Languages and Systems, Vol. 39, No.

4, Article 14, Publication date: August 2017.

Again, ctx and x are OCaml variables: they are bound to the semantic values returned by save _ context and X, respectively. One could replace them in the semantic action with $1 and $2.ACM Transactions on Programming Languages and Systems, Vol. 39, No. 4, Article 14, Publication date: August 2017.

The Bison manual[Donnelly and Stallman 2015, §5.8.2] notes: "The presence of defaulted states is an important consideration[...]. That is, if the behavior of yylex can influence or be influenced by the semantic actions [...], then the delay of the next yylex invocation until after those reductions is significant. For exam-ACM Transactions on Programming Languages and Systems, Vol. 39, No. 4, Article 14, Publication date: August 2017.

grant ANR-11-INSE-003. Permission to make digital or hard copies of all or part of this work for personal or classroom

( * Upon finding an identifier, the lexer emits two tokens. The first token, [NAME], indicates that a name has been found; the second token, either [TYPE] or [VARIABLE], tells what kind of name this is. The classification is performed only when the second token is demanded by the parser. * ) typedef _ name: