Download Language development case study (Pdf, 133 pages)

Transcript
A grammar for a superset of ANSI-C 107
9.4 A grammar for a superset of ANSI-C
Our aim with the grammar for pretty_c is to accept all valid ANSI-C programs,
but we are not limited to accepting only valid ANSI-C. The outline form of the
grammar is:
program ::=
f any valid ANSI-C lexeme g.
This will be a string of zero or more ANSI-C lexemes in whatever order,
including sequences that are not syntactically correct ANSI-C, so for instance
pretty_c would accept a `program' of the form
int main(void)
{
else 3 do case 16:
}
which should certainly be rejected by any real C compiler.
The full pretty_c grammar specication is shown in Figures 9.1 and 9.2.
The top level rule program accepts zero or more matches against one of 16
subrules that between them generate the complete ANSI-C lexicon. Each of
the 16 subrules denes a particular kind of token, and each kind has dierent
spacing conventions | all of the diadic operators, for instance, are dened in
rule diadic. Rule program receives (in the synthesized attribute lexeme) the
string of characters matched by the scanner, and a local attribute kind is assigned one member of the kind enumeration which is dened in the auxiliary
le pr_c_aux.h shown in Figure 9.3. Rule program also includes calls to the
auxiliary functions pretty_open() and pretty_close() that control the le
handling.
There are two cases where the string returned in lexeme is not necessarily
the actual string matched by the scanner. In the case of both character and
string literals (dened in lines 82 and 84) the scanner will process embedded
escape sequences to produce a string which may contain binary characters.
This is the source of the restriction noted in section 9.3.5 in which octal escape
sequences will be rewritten as hexadecimal escape sequences on output: the
scanner does not preserve information on whether a particular escape sequence
was octal or hexadecimal so we have arbitrarily decided to output them all as
hexadecimal.
Comments in rdp generated parsers are usually dened using one of the
`invisible' comment scanner primitives and quietly suppressed by the scanner. In this application, of course, we wish to pass comments from the parser
into the pretty printer (otherwise the comments would be removed from the
formatted output!) As a result, comments are dened in line 56 using the
COMMENT_VISIBLE primitive.
Preprocessor directives in ANSI-C present the pretty printer with particular
problems. Unusually for a high level language, spacing is critical in preprocessor
denitions. These two commands have quite dierent meanings:
#define a(b) b=3;
#define a (b) b=3;