Steven Pemberton, CWI, Amsterdam
One of the observed difficulties for newcomers to ixml when writing a grammar is dealing with whitespace in the input, since it can often be the source of unintended ambiguity. This article describes a methodology for constructing grammars that minimises the possibilities of creating ambiguities due to whitespace.
One of the challenges when describing free-format input languages in ixml, is describing where whitespace may go. Inexperienced ixml authors, and sometimes even experienced ones, will add spacing that can cause ambiguities in the resultant parse. Here is an example:
bundle: -"bundle", -s, identifier, -s, namespaceDeclarations?, -s, expression**-s, -s, "endBundle", -s.
The problem here is that the author has specified where spaces can happen,
but some of the things that the spaces are separating are optional and
therefore may be absent in an input, and then the parser doesn't know where to
place the spaces. In the above example, both
namespaceDeclarations?, and expression**-s may be
empty, leaving a parse that looks like
-"bundle", -s, identifier, -s, -s, -s, "endBundle", -s.
with three optional sets of spacing next to each other, thus creating an ambiguity. The author could solve this by writing
bundle: -"bundle", -s, identifier, -s, (namespaceDeclarations, -s)?, (expression++-s, -s)?, "endBundle", -s.
but has to be aware of the problem in order to fix it.
The source of the problem may be that authors are used to writing grammars for systems where there is a lexical analysis phase, so that spaces don't appear in the parsing stage, and therefore don't have to be dealt with in the main grammar.
Lexical analysers were historically necessary to enable the use of fast but limited parsers such as LL1; however, using a general parser, ixml not only has no lexical analyser, it has no need for one, and it would actually be disadvantageous to introduce one, since lexical analysers in general do not have any context to help decide what the next token might be. In ixml token recognition is an integral part of the grammar recognition process, adding more context to the process.
This is why it is necessary to include all aspects of the input in an ixml description, including whitespace.
In order to prevent whitespace causing ambiguities, what is needed is a methodical way of writing ixml grammars.
The approach illustrated below is to write the grammar as if there were a lexical analyser, and then have a part of the grammar defining 'tokens'. The definition for any token then also consumes the spaces following it. In this way, at the upper level of the grammar you barely have to worry about spaces at all.
To start off with a very simple example, let us consider the following small grammar for simple arithmetic expressions (which at this point doesn't accept whitespace except newlines between expressions):
input: expression++-#a, -#a?.
-expression: sum; difference; term.
sum: expression, -"+", term.
difference: expression, -"-", term.
-term: product; division; operand.
product: term, -"×", operand.
division: term, -"÷", operand.
-operand: id; number; -"(", expression, -")".
id: [L]+.
number: ["0"-"9"]+.
For instance, with the input
a+(b×2)
this produces
<input>
<sum>
<id>a</id>
<product>
<id>b</id>
<number>2</number>
</product>
</sum>
</input>
The technique for dealing with whitespace is to identify 'tokens' that would be supplied by a lexical analyser, and then define what those are. You can identify potential tokens by the presence of literal strings, hexadecimal representations of characters, and character sets. For visibility, we are going to write such tokens with all capitals:
input: expression++NL, NL?.
-expression: sum; difference; term.
sum: expression, PLUS, term.
difference: expression, MINUS, term.
-term: product; division; operand.
product: term, TIMES, operand.
division: term, DIVIDE, operand.
-operand: id; number; OPEN, expression, CLOSE.
id: ID.
number: NUMBER.
and then define the tokens, with trailing spaces added:
-PLUS: -"+", s.
-MINUS: -"-", s.
-TIMES: -"×", s.
-DIVIDE: -"÷", s.
-OPEN: -"(", s.
-CLOSE: -")", s.
-ID: [L]+, s.
-NUMBER: ["0"-"9"]+, s.
-NL: -#a, s.
-s: -[" "; #9]*.
This guarantees that spaces after every symbol are consumed by the token, and so there is never any doubt about where spaces belong. It also means that all rules begin with non-whitespace characters.
Therefore, the only other thing we have to do is allow leading spaces at the point there hasn't been any token yet: the beginning.
input: s, expression++NL, NL?.
The fact that capitals have been used for the names of tokens is purely a
convention; you could equally choose to use a leading capital
Plus, or some other naming convention such as
plus-symbol, or plus-sym, or not mark them specially
at al.
To summarise the method:
For this example, we will take a grammar for a simplified version of ixml, where rules only contain alternatives, terminal strings, and nonterminals:
subset: rule+.
rule: name, -":", alternatives, -".".
-alternatives: alternative++-";".
alternative: term**-",".
-term: terminal; nonterminal.
nonterminal: name.
terminal: string.
@string: -'"', ~['"']*, -'"'.
@name: [L]+.
Note that we are defining a subset of ixml, but using full ixml to do it; again, in this grammar we haven't yet dealt with spaces.
So we identify tokens from the strings:
subset: rule+.
rule: name, COLON, alternatives, STOP.
-alternatives: alternative++SEMICOLON.
alternative: term**COMMA.
-term: terminal; nonterminal.
nonterminal: name.
terminal: string.
@string: STRING.
@name: NAME.
and then define the tokens, with trailing whitespace added:
-COLON: -":", s.
-STOP: -".", s.
-SEMICOLON: -";", s.
-COMMA: -",", s.
-NAME: [L]+, s.
-STRING: -'"', ~['"']*, -'"', s.
-s: -[" "; #9; #a]*.
Again, the only thing extra we have to do is allow leading spaces before the grammar, since at that point there hasn't been any token yet:
subset: s, rule+.
Following these simple examples, let us now consider the real ixml grammar
itself, which doesn't use this technique, and apply the technique to it. In the
ixml grammar the rule s represents optional whitespace; there is a
complication that spacing covers comments as well, which we will treat shortly.
For the time being assume it is only true whitespace.
Let's start with the definition of a rule as it appears:
rule: naming, -["=:"], s, -alts, -".". -naming: (mark, s)?, name, s, (-">", s, alias, s)?.
Note that this grammar does already deal with spaces, so we will remove the existing spacing from these rules:
rule: naming, IS, -alts, STOP. -naming: mark?, name, (GT, alias)?.
As you can see, the grammar already looks somewhat simpler.
Now for the tokens:
-IS: -["=:"], s.
-STOP: -".". {This is a special case that we will talk about later}
-GT: -">", s.
In the original ixml grammar, a mark looks like:
@mark: ["@^-"].
which we replace with:
@mark: MARK.
and add the corresponding token:
-MARK: ["@^-"], s.
Similarly name, which looks like this:
@name: namestart, namefollower*. -namestart: ["_"; L]. -namefollower: namestart; ["-.·‿⁀"; Nd; Mn].
we replace it with:
@name: NAME.
with the token:
-NAME: namestart, namefollower*, s.
-namestart: ["_"; L]. -namefollower: namestart; ["-.·‿⁀"; Nd; Mn].
An alias is just a NAME:
@alias: NAME.
Now we come to the definition of alternatives; in the original:
alts: alt++(-[";|"], s). alt: term**(-",", s).
This will become:
alts: alt++ALSO. alt: term**COMMA.
with the new tokens:
-ALSO: -[";|"], s. -COMMA: -",", s.
The original rule for term looks like:
-term: factor;
option;
repeat0;
repeat1.
-factor: terminal;
nonterminal;
insertion;
-"(", s, alts, -")", s.
so factor gets replaced with:
-factor: terminal;
nonterminal;
insertion;
OPEN, alts, CLOSE.
with tokens:
-OPEN: -"(", s.
-CLOSE: -")", s.
and the other options for term are:
option: factor, -"?", s. repeat0: factor, (-"*", s; -"**", s, sep). repeat1: factor, (-"+", s; -"++", s, sep).
which are replaced by:
option: factor, QUESTION. repeat0: factor, (STAR; STAR2, sep). repeat1: factor, (PLUS; PLUS2, sep).
with tokens
-QUESTION: -"?", s.
-STAR: -"*", s.
-STAR2: -"**", s.
-PLUS: -"+", s.
-PLUS2: -"++", s.
It was mentioned above that STOP is a special case.
This is because in ixml, rules must be separated by some white space: they may not abut each other. This means you may not write:
@alias:name.alts:alt++ALSO.
but must write something like
@alias:name. alts:alt++ALSO.
or
@alias:name. alts:alt++ALSO.
Consequently, the top-level rule for ixml is:
ixml: s, prolog?, rule++RS, s.
(where RS is 'required spacing'), so that rules are
separated by spacing, and not followed by them, and therefore we have
to include optional spacing at the end of the grammar as well as the beginning.
It also means that the token for STOP must not consume any spaces
(since the very last STOP might not have trailing whitespace).
In ixml, the definition of whitespace also includes comments; the complication is that comments are not deleted, but are required to be kept in the serialisation. While this is a problem that is unlikely to occur often in grammars, it is worth describing how to deal with it.
The definition of space is thus:
-s: (whitespace; comment)*. {Optional spacing}
-whitespace: -[Zs; -#9 {tab}; -#a {lf}; -#d {cr}].
(Zs is any character defined as whitespace in Unicode; this
doesn't include tab or newlines).
This means that if we had an input rule like
subset {top}: {next} rule; rule, subset.
with the rules as we have defined them:
@name: NAME. -NAME: [L]+, s.
we would get output where the comment after a NAME gets included in the attribute:
<rule name='subsettop'>
<comment>next</comment>
<alternative>
<nonterminal name='rule'/>
</alternative>
<alternative>
<nonterminal name='rule'/>
<nonterminal name='subset'/>
</alternative>
</rule>
This is because the trailing non-deleted comment after a NAME
gets included in the attribute. In other words, we have to ensure that comments
don't appear in attribute content.
This involves the rules that define attributes, namely: mark,
tmark, name, alias, string,
hex, from, to, and
code.
One solution is to make all uses of the mark rule into a
token:
-naming: MARK?, name, (GT, alias)?.
and the token split up the meaningful content as an attribute, followed by the whitespace (which may contain comments):
-MARK: mark, s. @mark: ["@^-"].
Similarly for NAME:
-naming: MARK?, NAME, (GT, alias)?.
with the token defined as:
-NAME: name, s. @name: namestart, namefollower*.
and again for alias:
-naming: MARK?, NAME, (GT, ALIAS)?.
with token:
-ALIAS: alias, s. @alias: name.
and so on for the other attributes.
The other option would be to move the s out of the token for
attributes, and in to the main body of the grammar:
-naming: (mark, s)?, name, s, (GT, alias, s)?.
with
@mark: MARK. @name: NAME. @alias: NAME.
and tokens
-MARK: ["^-@"]. {no trailing space}
-NAME: namestart, namefollower*.
So an attribute where the spacing is completely deleted looks like this:
member: code. @code: CODE. -CODE: capital, letter?, s.
and where something is retained in the spacing:
member: CODE. -CODE: code, s. @code: capital, letter?.
Strictly speaking, this second version would also work if the spacing is completely deleted, so the choice is yours.
For completeness, we include the whole ixml grammar in the new style. This has been confirmed to produce the same serialisations as the original ixml grammar.
ixml: s, prolog?, rule++RS, s.
prolog: version, s.
version: -"ixml", RS, -"version", RS, string, -'.' .
rule: naming, IS, -alts, DOT.
-naming: MARK?, NAME, (GT, ALIAS)?.
alts: alt++ALSO.
alt: term**COMMA.
-term: factor;
option;
repeat0;
repeat1.
-factor: terminal;
nonterminal;
insertion;
OPEN, alts, CLOSE.
repeat0: factor, (STAR; STAR2, sep).
repeat1: factor, (PLUS; PLUS2, sep).
option: factor, Q.
sep: factor.
nonterminal: naming.
-terminal: literal;
charset.
literal: quoted;
encoded.
-quoted: TMARK?, STRING.
-encoded: TMARK?, HEX.
-charset: inclusion;
exclusion.
inclusion: TMARK?, set.
exclusion: TMARK?, COMPLEMENT, set.
-set: SUB, member**ALSO, BUS.
member: STRING;
HEX;
range;
class.
-range: FROM, UPTO, TO.
-class: CODE.
insertion: PLUS, (STRING; HEX).
{Lexical}
-DOT: -".". {special case}
-IS: -["=:"], s.
-ALSO: -[";|"], s.
-GT: -">", s.
-COMMA: -",", s.
-OPEN: -"(", s.
-CLOSE: -")", s.
-STAR: -"*", s.
-STAR2: -"**", s.
-PLUS: -"+", s.
-PLUS2: -"++", s.
-Q: -"?", s.
-COMPLEMENT: -"~", s.
-SUB: -"[", s.
-BUS: -"]", s.
-UPTO: -"-", s.
-MARK: mark, s.
@mark: ["@^-"].
-TMARK: tmark, s.
@tmark: ["^-"].
-NAME: name, s.
@name: namestart, namefollower*.
-namestart: ["_"; L].
-namefollower: namestart; ["-.·‿⁀"; Nd; Mn].
-ALIAS: alias, s.
@alias: name.
-STRING: string, s.
@string: -'"', dchar+, -'"';
-"'", schar+, -"'".
-dchar: ~['"'; Cc];
'"', -'"'. {all characters except controls; quotes must be doubled}
-schar: ~["'"; Cc];
"'", -"'". {all characters except controls; quotes must be doubled}
-HEX: hex, s.
@hex: -"#", ["0"-"9"; "a"-"f"; "A"-"F"]+.
-FROM: from, s.
@from: character.
-TO: to, s.
@to: character.
-character: -'"', dchar, -'"';
-"'", schar, -"'";
+"#", hex.
-CODE: code, s.
@code: capital, letter?.
-capital: ["A"-"Z"].
-letter: ["A"-"Z"; "a"-"z"].
-s: (whitespace; comment)*. {Optional spacing}
-RS: (whitespace; comment)+. {Required spacing}
-whitespace: -[Zs; #9 {tab}; #a {lf}; #d {cr}].
comment: -"{", (cchar; comment)*, -"}".
-cchar: ~["{}"].
The methodology we have described above ensures that rules consume all spaces following them, and that all rules start with a non-space character. This is why we have to add an extra term to consume any spaces before the root rule, such as we saw above:
input: s, expression++NL, NL?.
The root rule is thus the only one which can start with spaces.
However, there is a modularisation method planned for ixml in the future, which will allow the composition of ixml grammars from several sub-grammars. Here is one proposal for the syntax of modularisation, using itself as definition:
+uses ixml, name, s, RS from ixml.ixml; iri from iri.ixml
+shares module
module: s, (multiuse; shares)*, ixml.
-multiuse: -"+uses", RS, uses++(-";", s).
shares: -"+shares", RS, entries.
uses: entries, RS, -"from", RS, from.
-entries: share++(-",", s).
share: @name, s.
@from: iri, s.
What this means is that if a grammar is also to be a (future) module, there would be an ambiguity if the root rule can start with spaces.
Therefore, to allow a grammar to serve as both a standalone grammar and a potential module, we have to do something special for the root rule. Here is an example:
+shares input -standalone: s, input. input: expression++NL, NL?.
This creates a new root rule which doesn't appear in the serialisation but accepts leading spaces and uses the old root rule, while the module shares the old root as a rule that doesn't accept leading spaces.
If you want to try it out yourself, here is an example grammar. There is example input, and an example answer.
program: statement*.
-statement: simple; compound.
-simple: assignment; call.
-compound: if; while; block.
assignment: id, -":=", expression.
call: id, -"(", expression**-",", -")".
if: -"IF", comparison, then, else?.
then: -"THEN", statement.
else: -"ELSE", statement.
while: -"WHILE", comparison, -"DO", statement.
block: -"BEGIN", statement*, -"END".
comparison: expression, compare, expression.
@compare: ["<=>≠≤≥"].
expression: sum; term.
sum: term, -"+", term++-"+".
-term: product; operand.
product: operand, -"×", operand++-"×".
-operand: id; number; -"(", -expression, -")".
id: [Ll]+.
number: ["0"-"9"]+.
-s: -[' '; #a; #d]*.