

































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


































Coco/R is a compiler generator, which takes an attributed grammar of a source language and generates a scanner and a recursive descent parser for this language. The user has to supply a main class that calls the parser as well as semantic classes (e.g. a symbol table handler or a code generator) that are used by semantic actions in the parser. This is shown in Figure 1.
compiler description
Main
Parser
Scanner semantic classes
Coco/R
Figure 1 Input and output of Coco/R
In order to give you an idea of how attributed grammars look like in Coco/R, let us look at a sample production for variable declarations in a Pascal-like language:
The core of this specification is the EBNF production
VarDeclaration = Ident {',' Ident} ':' Type ';'.
It is augmented with attributes and semantic actions. The attributes (e.g.
Parser
The parser is specified by a set of EBNF productions with attributes and semantic actions. The productions allow for alternatives, repetition and optional parts. Coco/R translates the productions into an efficient recursive descent parser. The parser is reentrant, so multiple instances of it can be active at the same time. Nonterminal symbols can have any number of input and output attributes (the Java version allows just one output attribute, which may, however, be an object of a suitable composite class). Terminal symbols do not have explicit attributes, but the tokens returned by the scanner contain information that can be viewed as attributes. All attributes are evaluated during parsing (i.e. the grammar is processed as an L- attributed grammar). Semantic actions can be placed anywhere in the grammar (not just at the end of productions). They may contain arbitrary statements or declarations written in the language of the generated parser (e.g. C#, Java or C++). The special symbol ANY can be used to denote a set of complementary tokens. In principle, the grammar must be LL(1). However, Coco/R can also handle non- LL(1) grammars by using so-called resolvers that make a parsing decision based on a multi-symbol lookahead or on semantic information. Every production can have its own local variables. In addition to these, one can declare global variables or methods, which are translated into fields and methods of the parser. Semantic actions can also access other objects or methods from user- written classes or from library classes. Coco/R checks the grammar for completeness, consistency and non-redundancy. It also reports LL(1) conflicts. The error messages printed by the generated parser can be configured to conform to a user-specific format. The generated parser and scanner can be specified to belong to a certain namespace (or package).
This section specifies the compiler description language Cocol/R that is used as the input language for Coco/R. A compiler description consists of a set of grammar rules that describe the lexical and syntactical structure of a language as well as its translation to a target language.
The basic elements of Cocol/R are identifiers, numbers, strings and character constants, which are defined as follows:
ident = letter {letter | digit}. number = digit {digit}. string = '"' {anyButQuote} '"'. char = ''' anyButApostrophe '''.
Upper case letters are distinct from lower case letters. Strings must not extend across multiple lines. Both strings and character constants may contain the following escape sequences:
\ backslash \r carriage return \f form feed ' apostrophe \n new line \a bell " quote \t horizontal tab \b backspace \0 null character \v vertical tab \uxxxx hex char value
The following identifiers are reserved keywords (in the C# version of Cocol/R the identifier using is also a keyword, in the Java version the identifier import):
ANY CONTEXT IGNORE PRAGMAS TOKENS CHARACTERS END IGNORECASE PRODUCTIONS WEAK COMMENTS FROM NESTED SYNC COMPILER IF out TO
Comments are enclosed in /* and */ and may be nested. Alternatively they can start with // and go to the end of the line.
EBNF
All syntax descriptions in Cocol/R are written in Extended Backus-Naur Form (EBNF) [Wirth77]. By convention, identifiers starting with a lower case letter denote terminal symbols, identifiers starting with an upper case letter denote nonterminal symbols. Strings denote themselves. The following meta-characters are used:
symbol meaning example = separates the sides of a production A = a b c.
. terminates a production A = a b c. | separates alternatives a b | c | d e means a b or c or d e ( ) groups alternatives (a | b) c means a c or b c [ ] option [a] b means a b or b { } iteration (0 or more times) {a} b means b or a b or a a b or ...
Attributes are written between < and >. Semantic actions are enclosed in (. and .). The operators + and - are used to form character sets.
A Cocol/R compiler description has the following structure:
Cocol = [ Imports ] "COMPILER" ident [ GlobalFieldsAndMethods ] ScannerSpecification ParserSpecification "END" ident '.' .
The name after the keyword COMPILER is the grammar name and must match the name after the keyword END. The grammar name also denotes the topmost nonterminal symbol (the start symbol ). The parser specification must contain a production for this symbol.
Imports. In front of the keyword COMPILER one can import namespaces (in C#) or packages (in Java) or include header files (in C++), for example:
using System; using System.Collections;
This is the main section of the scanner specification, in which the tokens (or terminal symbols) of the language are declared. Tokens may be divided into literals and token classes.
Literals (such as while or >=) have a fixed representation in the source language. In the grammar they are written as strings (e.g. "while" or ">=") and denote themselves. They don't have to be declared in the tokens section but are implicitly declared at their first use in the productions of the grammar.
Token classes (such as identifiers or numbers) have a certain structure that must be explicitly declared by a regular expression in EBNF. There are usually many instances of a token class (e.g. many different identifiers), which have the same token code, but different lexeme values.
The syntax of token declarations is as follows:
TokenDecl = Symbol ['=' TokenExpr '.']. TokenExpr = TokenTerm {'|' TokenTerm}. TokenTerm = TokenFactor {TokenFactor} ["CONTEXT" '(' TokenExpr ')']. TokenFactor = Symbol | '(' TokenExpr ')' | '[' TokenExpr ']' | '{' TokenExpr '}'. Symbol = ident | string | char.
A token declaration defines the syntax of a terminal symbol by a regular EBNF ex- pression. This expression may contain strings or character constants denoting themselves (e.g. ">=" or ';') as well as names of character sets (e.g. letter) denoting an arbitrary character from this set. It must not contain other token names, which implies that EBNF expressions in token declarations cannot be recursive.
Examples
ident = letter {letter | digit | '_'}. number = digit {digit} | "0x" hexDigit hexDigit hexDigit hexDigit. float = digit {digit} '.' {digit} ['E' ['+'|'-'] digit {digit}].
The token declarations need not be LL(1) as can be seen in the declaration of number, where both alternatives can start with a '0'. Coco/R automatically resolves any ambiguities and generates a deterministic finite scanner automaton.
Tokens may be declared in any order. However, if a token is declared as a literal that matches an instance of a more general token, the literal has to be declared after the more general token.
Example
ident = letter {letter | digit}. while = "while".
Since the string "while" matches both the tokens while and ident, the declaration of while must come after the declaration of ident. In principle, literal tokens don't have to be declared in the token declarations at all, but can simply be introduced directly in the productions of the grammar. In some situations, however, it makes sense to declare them explicitly, for example, in order to get a token name for them that can be used in resolver methods (see Section 2.4.6).
Context-dependent tokens. The CONTEXT phrase in a TokenTerm means that the term is only recognized if its context (i.e. the characters that follow the term in the input stream) matches the TokenExpr specified in brackets. Note that the TokenExpr is not part of the token.
Example
number = digit {digit} | digit {digit} CONTEXT (".."). float = digit {digit} '.' {digit} ['E' ['+'|'-'] digit {digit}].
The CONTEXT phrase in this example allows the scanner to distinguish between float tokens (e.g. 1.23) and integer ranges (e.g. 1..2) that could otherwise not be scanned with a single character lookahead. This works as follows: after having read "1." the scanner still works on both tokens. If the next character is a '.' the characters ".." are pushed back to the input stream and a number token with the value 1 is returned to the parser. If the next character is not a '.' the scanner continues with the recognition of a float token.
Hand-written scanners. If the right-hand sides of the token declarations are missing no scanner is generated. This gives the user the chance to provide a hand-written scanner, which must conform to the interface described in Section 3.4.1.
Example
TOKENS ident number "if" "while" ...
Tokens are assigned numbers in the order of their declaration. The first token gets the number 1 , the second the number 2 , and so on. The number 0 is reserved for the end- of-file token. The hand-written scanner must return the token numbers according to these conventions. In particular, it must return an end-of-file token if no more input is available.
It is hardly ever necessary to supply a hand-written scanner, because the scanner generated by Coco/R is highly optimized. A user-supplied scanner would be needed, for example, if the scanner were required to process include directives.
Pragmas are tokens that may occur anywhere in the input stream (for example, end- of-line symbols or compiler directives). It would be too tedious to handle all their possible occurrences in the grammar. Therefore they are excluded from the token stream that is passed to the parser. Pragmas are declared like tokens, but they may have a semantic action associated with them that is executed whenever they are recognized by the scanner.
PragmaDecl = TokenDecl [SemAction]. SemAction = "(." ArbitraryStatements ".)".
Some languages such as Pascal are case insensitive. In Pascal, for example, one can write the keyword while also as While or WHILE. By default, Coco/R generates scanners that are case sensitive. If this is not desired, one has to write IGNORECASE at the beginning of the scanner specification.
The effect of IGNORECASE is that all input to the scanner is treated in a case-insensitive way. The production
WhileStatement = "while" '(' Expr ')' Statement.
will therefore also recognize while statements that start with While or WHILE. Similarly, the declaration:
TOKENS float = digit {digit} '.' ['E' ('+'|'-') digit {digit}].
will cause the scanner to recognize not only 1.2E2 but also 1.2e2 as a float token. However, the original casing of tokens is preserved in the val field of every token (see Section 3.4.2) so that the lexical value of tokens such as identifiers and strings is delivered exactly as it was written in the input text.
The parser specification is the main part of a compiler description. It contains the productions of an attributed grammar, which specify the syntax of the language to be parsed as well as its translation.
ParserSpecification = "PRODUCTIONS" {Production}. Production = ident [FormalAttributes] [LocalDecl] '=' Expression '.'. Expression = Term {'|' Term}. Term = [[Resolver] Factor {Factor}]. Factor = ["WEAK"] Symbol [ActualAttributes] | '(' Expression ')' | '[' Expression ']' | '{' Expression '}' | "ANY" | "SYNC" | SemAction. Symbol = ident | string | char. SemAction = "(." ArbitraryStatements ".)". LocalDecl = SemAction. FormalAttributes = '<' ArbitraryText '>'. ActualAttributes = '<' ArbitraryText '>'. Resolver = "IF" '(' {ANY} ')'.
A production specifies the syntactical structure of a nonterminal symbol. It consists of a left-hand side and a right-hand side which are separated by an equal sign. The left- hand side specifies the name of the nonterminal together with its formal attributes and the local variables of the production. The right-hand side consists of an EBNF expression that specifies the structure of the nonterminal as well as its translation in form of attributes and semantic actions.
The productions may be given in any order. References to as yet undeclared nonterminals are allowed. For every nonterminal there must be exactly one production. In particular, there must be a production for the grammar name, which is the start symbol of the grammar.
A semantic action is a piece of code written in the target language of Coco/R (i.e. in C#, Java or C++). It is executed by the generated parser at the position where it has been specified in the grammar. Semantic actions are simply copied to the generated parser without being checked by Coco/R.
A semantic action can also contain the declarations of local variables. Every production has its own set of local variables, which are retained in recursive productions. The optional semantic action on the left-hand side of a production (LocalDecl) is intended for such declarations, but variables can also be declared in any other semantic action.
Here is an example that counts the number of identifiers in an identifier list:
IdentList = ident (. int n = 1; .) {',' ident (. n++; .) } (. Console.WriteLine("n = " + n); .) .
As a matter of style, it is good practice to write all syntax parts on the left side and all semantic actions on the right side of a page. This makes a production better readable because the syntax is separated from its processing.
Semantic actions cannot only access local variables but also fields and methods declared at the beginning of the attributed grammar (see Section 2.2) as well as fields and methods of imported classes.
Productions are considered as (and are actually translated to) parsing methods. The occurrence of a nonterminal on the right-hand side of a production can be viewed as a call of that nonterminal's parsing method.
Nonterminals may have attributes, which correspond to parameters of the nontermi- nal's parsing method. There are input attributes , which are used to pass values to the production of a nonterminal, and output attributes , which are used to return values from the production of a nonterminal to its caller (i.e. to the place where this nonterminal occurs in some other production).
As with parameters, we distinguish between formal attributes , which are specified at the nonterminal's declaration on the left-hand side of a production, and actual attributes , which are specified at the nonterminal's occurrence on the right-hand side of a production.
Attributes are enclosed in angle brackets (e.g., < ... >). If attributes contain the operators '<' or '>' or generic types like List
Coco/R checks that nonterminals with attributes are always used with attributes and that nonterminals without attributes are always used without attributes. However, it does not check the correspondence between formal and actual attributes, which is left to the compiler of the target language.
Ident
The variable t is the most recently recognized token. Its field t.val holds the textual representation of the token (see Section 3.4.4).
In the productions of the grammar the symbol ANY denotes any token that is not an alternative to that ANY symbol in the current production. It can be used to conveniently parse structures that contain arbitrary text. The following production, for example, processes an attribute list in Cocol/R and returns the number of characters between the angle brackets:
Attributes < out int len> = '<' (. int beg = t.pos + 1; .) {ANY} '>' (. len = t.pos - beg; .).
In this example the token '>' is an implicit alternative of the ANY symbol in curly braces. The meaning is that this ANY matches any token except '>'. t.pos is the source text position of the most recently recognized token (see Section 3.4.4).
Here is another example that counts the number of statements in a block:
Block
In this example the ANY matches any token except ';', '{' and '}' which are alternatives of it ('{' is a terminal start symbol of Block).
Recursive descent parsing requires that the grammar of the parsed language is LL(1) (i.e. parsable from L eft to right with L eft-canonical derivations and 1 lookahead symbol). This means that at any point in the grammar the parser must be able to decide on the basis of a single lookahead symbol which of several possible alternatives have to be selected. The following production, for example, is not LL(1):
Statement = ident '=' Expression ';' | ident '(' [ActualParameters] ')' ';' | ....
Both alternatives start with the symbol ident. When the parser comes to the beginning of a Statement and ident is the next input token, it cannot distinguish between the two alternatives. However, this production can easily be transformed to
Statement = ident ( '=' Expression ';' | '(' [ActualParameters] ')' ';' ) | ....
where all alternatives start with distinct symbols and the LL(1) conflict has dis- appeared.
LL(1) conflicts can arise not only from explicit alternatives like those in the example above but also from implicit alternatives that are hidden in optional or iterative EBNF expressions. The following list shows how to check for LL(1) conflicts in these situations (Greek symbols denote arbitrary EBNF expressions such as a[b]C; first (α) denotes the set of terminal start symbols of the EBNF expression α; follow (A) denotes the set of terminal symbols that can follow the nonterminal A in any other production):
Explicit alternatives A = α|β|γ. check that first (α) ∩ first (β) = {} ∧ first (α) ∩ first (γ) = {} ∧ first (β) ∩ first (γ) = {}. A =(α|)β. check that first(α) ∩ first(β) = {} A =(α|). check that first(α) ∩ follow(A) = {}
Options A = [α] β. check that first (α) ∩ first (β) = {} A = [α]. check that first (α) ∩ follow(A) = {}
Iterations A = {α} β. check that first (α) ∩ first (β) = {} A = {α}. check that first (α) ∩ follow (A) = {}
It would be very tedious and error-prone to check all these conditions manually for a grammar of a realistic size. Fortunately, Coco/R does that automatically. For example, the grammar
A = (a | B C d). B = [b] a. C = c {d}.
will result in the following LL(1) warnings:
LL1 warning in A: a is start of several alternatives LL1 warning in C: d is start & successor of deletable structure
The first conflict arises because B can start with an a. The second conflict comes from the fact that C may be followed by a d, and so the parser does not know whether it should do another iteration of {d} in C or terminate C and continue with the d outside.
Another situation that leads to a conflict is when an expression in curly or square brackets is deletable, e.g.:
A = [B] a. B = {b}.
If the parser tries to recognize A and sees an a it cannot decide whether to enter the deletable symbol B or to skip [B]. Therefore Coco/R prints the warning:
LL1 warning in A: contents of [...] or {...} must not be deletable
Note that Coco/R reports LL(1) conflicts as warnings, not as errors. Whenever the parser sees two or more alternatives that can start with the same token it always chooses the first one. If this is what the user intends then everything is fine, like in the well-known example of the dangling else that occurs in many programming languages:
Statement = "if" '(' Expression ')' Statement ["else" Statement] | ....
Input for this grammar like
if (a > b) if (a > c) max = a; else max = b;
Semantic issues. Finally, factorization is sometimes inhibited by the fact that the se- mantic processing of conflicting alternatives differs, e.g.:
A = ident (. x = 1; .) {',' ident (. x++; .) } ':' | ident (. Foo(); .) {',' ident (. Bar(); .) } ';'.
The common parts of these two alternatives cannot be factored out, because each alternative has its own way to be processed semantically. Again this problem can be solved with the technique explained in Section 2.4.6.
A conflict resolver is a boolean expression that is inserted into the grammar at the beginning of the first of two conflicting alternatives and decides, using a multi- symbol lookahead or a semantic check, whether this alternative matches the actual input. If the resolver yields true, the alternative prefixed by the resolver is selected, otherwise the next alternative will be checked. A conflict resolver is written as
Resolver = "IF" '(' ... any expression ... ')'.
where any boolean expression can be written between the parentheses. In most cases this will be a function call that returns true or false.
Thus we can resolve the LL(1) conflict from Section 2.4.5 in the following way:
UsingClause = "using" [ IF(IsAlias()) ident '='] Qualident ';'.
IsAlias is a user-defined method that reads two tokens ahead. It returns true, if ident is followed by '=', otherwise it returns false.
Conflict resolution by a multi-symbol lookahead
The generated parser remembers the most recently recognized token as well as the current lookahead token in two global variables (see also Section 3.4.4):
Token t; // most recently recognized token Token la; // lookahead token
The generated scanner offers a method Peek() that can be used to read ahead beyond the lookahead token without removing any tokens from the input stream. When normal parsing resumes the scanner will return these tokens again.
With Peek() we can implement IsAlias() in the following way:
bool IsAlias() { Token next = scanner.Peek(); return la.kind == _ident && next.kind == _eql; }
The conflict mentioned at the end of Section 2.4.5 can be resolved by the production
A = IF(FollowedByColon()) ident (. x = 1; .) {',' ident (. x++; .) } ':' | ident (. Foo(); .) {',' ident (. Bar(); .) } ';'.
and the following implementation of the function FollowedByColon():
bool FollowedByColon() { Token x = la; while (x.kind == _comma || x.kind == _ident) x = scanner.Peek(); return x.kind == _colon; }
Token names. For peeking it is convenient to be able to refer to the token numbers by names such as _ident or _comma. Coco/R generates such names for all tokens declared in the TOKENS section of the scanner specification. For example, if the tokens are declared like this:
TOKENS ident = letter {letter | digit}. number = digit {digit}. eql = '='; comma = ','. colon = ':'.
Coco/R will generate the following constant declarations in the parser:
const int _EOF = 0; const int _ident = 1; const int _number = 2; const int _eql = 3; const int _comma = 4; const int _colon = 5;
The token names are preceded by an underscore in order to avoid conflicts with reserved keywords and other identifiers.
Normally the TOKENS section will only contain declarations for token classes like ident or number. However, if the name of a literal token is needed for peeking, it has to be declared there as well. In the productions of the grammar this token can then be referred to either by its name (e.g. _comma) or by its literal value (e.g. ',').
Resetting the peek position. The scanner makes sure that a sequence of Peek() calls will return the tokens following the lookahead token la. In rare situations, however, the user has to reset the peek position manually. Consider the following grammar:
A = ( IF (IsFirstAlternative()) ... | IF (IsSecondAlternative()) ... | ... ).
Assume that the function IsFirstAlternative() starts peeking and finds out that the input does not match the first alternative. So it returns false and the parser checks the second alternative. The function IsSecondAlternative() starts peeking again, but before that, it should reset the peek position to the first symbol after the lookahead token la. This can be done by calling scanner.ResetPeek().
bool IsSecondAlternative() { scanner.ResetPeek(); Token x = scanner.Peek(); // returns the first token after the ... // lookahead token again }
The peek position is reset automatically every time a regular token is recognized by scanner.Scan() (see Section 3.4.1).
Translation of conflict resolvers. Coco/R treats resolvers like semantic actions and simply copies them into the generated parser at the position where they appear in the grammar. For example, the production
UsingClause = "using" [ IF(IsAlias()) ident '='] Qualident ';'.
is translated into the following parsing method:
Here is how the resolvers should have been placed in this example:
A = ( IF (...) a b // resolves conflict betw. the first two alternatives | a c | b ).
The following example is also interesting:
A = { a | IF (...) b c // resolver placed incorrectly. } b.
Although the b in the second alternative constitutes an LL(1) conflict with the b after the iteration, the resolver is placed incorrectly. It should rather be placed at the beginning of the iteration like this:
A = { IF (AnotherIteration()) ( a | b c ) } b.
The function AnotherIteration() could then be implemented as follows:
bool AnotherIteration() { Token next = scanner.Peek(); return la.kind == _a || la.kind == _b && next.kind == _c; }
The reason why this resolver is placed incorrectly is that it should be called only once in the parser (namely in the header of the while loop):
void A() { while (AnotherIteration()) { if (la.kind == _a) Expect(_a); else if (la.kind == _b) { Expect(_b); Expect(_c); } } Expect(_b); }
and not both in the while header and at the beginning of the second alternative. Remember, that the resolver must be placed at the earliest possible point where the LL(1) conflict arises.
If a syntax error is detected during parsing the generated parser reports the error and tries to recover by synchronizing the erroneous input with the grammar. While error messages are generated automatically, the user has to give certain hints in the grammar in order to enable the parser to recover from errors.
Invalid terminal symbols. If a certain terminal symbol was expected but not found in the input the parser just reports that this symbol was expected. For example, if we had a production
A = a b c.
for which the input was
a x c
the parser reports
-- line ... col ...: b expected
Invalid alternative lists. If the lookahead symbol does not match any alternative from a list of expected alternatives in a nonterminal A the parser just reports that A was invalid. For example, if we had a production
A = a (b|c|d) e.
for which the input was
a x e
the parser reports
-- line ... col ...: invalid A
Obviously, this error message can be improved if we turn the alternative list into a separate nonterminal symbol, i.e.:
A = a B e. B = b|c|d.
In this case the error message would be
-- line ... col ...: invalid B
which is more precise.
Synchronization. After an error was reported the parser continues until it gets to a so- called synchronization point where it tries to synchronize the input with the grammar again. Synchronization points have to be specified by the keyword SYNC. They are points in the grammar where particularly safe tokens are expected, i.e. tokens that hardly occur anywhere else and are unlikely to be mistyped. When the parser reaches a synchronization point it skips all input until a token occurs that is expected at this point.
In many languages good candidates for synchronization points are the beginning of a statement (where keywords like if, while or for are expected) or the beginning of a declaration sequence (where keywords like public, private or void are expected). A semicolon is also a good synchronization point in a statement sequence.
The following production, for example, specifies the beginning of a statement as well as the semicolon after an assignment as synchronization points:
State SYNC
ment = ( Designator '=' Expression SYNC ';' | "if" '(' Expression ')' Statement ["else" Statement] | "while" '(' Expression ')' Statement | '{' {Statement} '}' | ... ).
In the generated parser, these synchronization points look as follows (written in pseudo code here):