Brad Merrill Microsoft
Version 1.0, 20-Sep-1999
Manual revision 24-Sep-1999
A lexical analyzer breaks an input stream of characters into tokens. Writing lexical analyzers by hand can be a tedious process, so software tools have been developed to ease this task.
Perhaps the best known such utility is the original C-based Lex. Lex is a lexical analyzer generator for the UNIX operating system, targeted to the C programming language.
Lex takes a specially-formatted specification file containing the details of a lexical analyzer. This tool then creates a C source file for the associated table-driven lexer.
The CsLex utility is based upon the Lex lexical analyzer generator model. CsLex takes a specification file similar to that accepted by Lex, then creates a C# source file for the corresponding lexical analyzer.
CsLex is loosely based on the JLex tool, which was based on the Lex tool. This was a significant rewrite, so consequently any errors are solely the responsibility of the most recent author. See the credits section for more info.
A CsLex input file is organized into three sections, separated by
double-percent directives (``%%''). A proper CsLex specification has the
following format.
user code
%%
CsLex directives
%%
regular expression rules
The ``%%'' directives distinguish sections of the input file and
must be placed at the beginning of
their line. The remainder of the line containing the ``%%'' directives may be
discarded and should not be used to house additional declarations or code.
The user code section - the first section of the specification file - is copied directly into the resulting output file. This area of the specification provides space for the implementation of utility classes or return types.
The CsLex directives section is the second part of the input file. Here, macros definitions are given and state names are declared.
The third section contains the rules of lexical analysis, each of which consists of three parts: an optional state list, a regular expression, and an action.
User code precedes the first double-percent directive (``%%'). This code is copied verbatim into the lexical analyzer source file that CsLex outputs, at the top of the file. Therefore, if the lexer source file needs to begin with a package declaration or with the importation of an external class, the user code section should begin with the corresponding declaration. This declaration will then be copied onto the top of the generated source file.
The %{...%} directive allows the user to write C# code to be copied
into the lexical analyzer class. This directive is used as follows.
%{
<code>
%}
To be properly recognized, the %{ and %} should
each be situated at the beginning of a line. The specified C#
code in <code> will be then copied into the lexical
analyzer class created by CsLex.
class Yylex {
... <code> ...
}
This permits the declaration of variables and functions
internal to the generated lexical analyzer class. Variable names
beginning with yy should be avoided, as these are
reserved for use by the generated lexical analyzer class.
Macro names should be valid identifiers, e.g. sequences of letters, digits, and underscores beginning with a letter or underscore.
Macro definitions should be valid regular expressions, the details of which are described in another section below.
Macro definitions can contain other macro expansions, in the standard
{<name>} format for macros within regular
expressions. However, the user should note that these
expressions are macros - not functions or nonterminals - so
mutually recursive constructs using macros are
illegal. Therefore, cycles in macro definitions will have
unpredictable results.
State names should be valid identifiers, e.g. sequences of letters, digits, and underscores beginning with a letter or underscore.
A single lexical state is implicitly declared by CsLex. This state is called YYINITIAL, and the generated lexer begins lexical analysis in this state.
Rules of lexical analysis begin with an optional state list. If a state list is given, the lexical rule is matched only when the lexical analyzer is in one of the specified states. If a state list is not given, the lexical rule is matched when the lexical analyzer is in any state.
If a CsLex specification does not make use of states, by neither declaring states nor preceding lexical rules with state lists, the resulting lexer will remain in state YYINITIAL throughout execution. Since lexical rules are not prefaced by state lists, these rules are matched in all existing states, including the implicitly declared state YYINITIAL. Therefore, everything works as expected if states are not used at all.
States are declared as constant integers within the generated lexical analyzer class. The constant integer declared for a declared state has the same name as that state. The user should be careful to avoid name conflict between state names and variables declared in the action portion of rules or elsewhere within the lexical analyzer class. A convenient convention would be to declare state names in all capitals, as a reminder that these identifiers effectively become constants.
To change the name of the lexical analyzers namespace
from YyNameSpace,
use the %namespace directive.
%namespace <name>
To change the name of the lexical
analyzer class from Yylex, use the %class
directive.
%class <name>
To change the name of the tokenizing function from yylex,
use the %function directive.
%function <name>
To change the name of the return type from the tokenizing
function from Yytoken, use the %type
directive.
%type <name>
If the default names are not altering using these directives, the tokenizing function is envoked with a call to Yylex.yylex(), which returns the Ytoken type.
To avoid scoping conflicts, names beginning with yy are normally reserved for lexical analyzer internal functions and variables.
Notice that the effect of %intwrap directive can be
equivalently accomplished using the %type directive, as
follows.
%type object
This manually changes the name of the return type from
Yylex.yylex() to
object.
The %yyeof directive causes the constant integer
Yylex.YYEOF to be declared and returned upon
end-of-file.
%yyeof
This constant integer is discussed in more detail in a previous
section. Note also that Yylex.YYEOF is a int, so
the user should make sure that this return value is compatible
with the return type of Yylex.yylex().
The %full directive can be used to extend this alphabet
to include all 8-bit values.
%full
If the %full directive is given, CsLex will generate a
lexical analyzer that supports an alphabet of character codes
between 0 and 255 inclusive.
An example of usage is given below. Suppose the return value
desired on end-of-file is (new token(sym.EOF)) rather
than the default value null. The user adds the following
declaration to the specification file.
%eofval{
return (new token(sym.EOF));
%eofval}
The code is then copied into Yylex.yylex() into the
appropriate place.
public Yytoken yylex () { ...
return (new token(sym.EOF));
... }
The value returned by Yylex.yylex() upon end-of-file and
from that point onward is now (new token(sym.EOF)).
The rules have three distinct parts: the optional state list,
the regular expression, and the associated action. This format
is represented as follows.
[<states>] <expression> { <action> }
Each part of the rule is discussed in a section below.
If more than one rule matches strings from its input, the generated lexer resolves conflicts between rules by greedily choosing the rule that matches the longest string. If more than one rule matches strings of the same length, the lexer will choose the rule that is given first in the CsLex specification. Therefore, rules appearing earlier in the specification are given a higher priority by the generated lexer.
The rules given in a CsLex specification should match all possible input. If the generated lexical analyzer receives input that does not match any of its rules, an error will be raised.
Therefore, all input should be matched by at least one
rule. This can be guaranteed by placing the following rule at
the bottom of a CsLex specification:
. { Console.WriteLine("Unmatched input: " + yytext()); }
The dot (.), as described below, will match any input except for
the newline.
For instance, if yylex() is called with the lexer at state A, the lexer will attempt to match the input only against those rules that have A in their state list.
If no state list is specified for a given rule, the rule is matched against in all lexical states.
The alphabet for CsLex is the Ascii character set, meaning character codes between 0 and 127 inclusive.
The following characters are metacharacters, with special
meanings in CsLex regular expressions.
? * + | ( ) ^ $ / ; . = < > [ ] { } " \
ef Consecutive regular expressions represents their concatenation.
e|f The vertical bar (|) represents an option between the regular expressions that surround it, so matches either expression e or f.
The following escape sequences are recognized and expanded:
\b | Backspace |
\n | newline |
\t | Tab |
\f | Formfeed |
\r | Carriage return |
\ddd | The character code corresponding to the number formed by three octal digits ddd |
\xdd | The character code corresponding to the number formed by two hexadecimal digits dd |
\udddd | The Unicode character code corresponding to the number formed by four hexidecimal digits dddd. The support of Unicode escape sequences of this type is unimplemented. |
\^C | Control character |
\c | A backslash followed by any other character c matches itself |
Symbol | Meaning | ||||||||
---|---|---|---|---|---|---|---|---|---|
$ | The dollar sign ($) denotes the end of a line. If the dollar sign ends a regular expression, the expression is matched only at the end of a line. | ||||||||
. | The dot (.) matches any character except the newline, so this expression is equivalent to [^\n]. | ||||||||
"..." | Metacharacters lose their meaning within double quotes
and represent themselves. The sequence \"
(which represents the single character " )
is the only exception. |
||||||||
{name} | Curly braces denote a macro expansion, with name the declared name of the associated macro. | ||||||||
* | The star (*) represents Kleene closure and matches zero or more repetitions of the preceding regular expression. | ||||||||
+ | The plus (+) matches one or more repetitions of the preceding regular expression, so e+ is equivalent to ee*. | ||||||||
? | The question mark (?) matches zero or one repetitions of the preceding regular expression. | ||||||||
(...) | Parentheses are used for grouping within regular expressions. | ||||||||
[...] | Square backets denote a class of characters and match
any one character enclosed in the backets. If the first
character following the left bracket ([) is the up arrow
(^), the set is negated and the expression matches any
character except those enclosed in the
backets. Different metacharacter rules hold inside the
backets, with the following expressions having special
meanings:
|
All curly braces contained in action not part of strings or comments should be balanced.
The lexical analyzer can be made to recur explicitly with a call
to yylex(), as in the following code fragment.
{ ...
return yylex();
... }
This code fragment causes the lexical analyzer to recur,
searching for the next match in the input and returning the
value associated with that match. The same effect can be had,
however, by simply returning null from a given action. This
results in the lexer searching for the next match, without the
additional overhead of recursion.
The preceding code fragment is an example of tail recursion,
since the recursive call comes at the end of the calling
function's execution. The following code fragment is an example
of a recursive call that is not tail recursive.
{ ...
next = yylex();
return null;
... }
Recursive actions that are not tail-recursive work in the
expected way, except that variables such as yyline and
yychar may be changed during recursion.
The state state must be declared within the CsLex directives section, or this call will result in a compiler error in the generated source file. The one exception to this declaration requirement is state YYINITIAL, the lexical state implicitly declared by CsLex. The generated lexer begins lexical analysis in state YYINITIAL and remains in this state until a transition is made.
Variable or Method | ActivationDirective | Description |
---|---|---|
System.String yytext(); | Always active. | Matched portion of the character input stream. |
int yychar; | %char | Zero-based character index of the first character in the matched portion of the input stream |
int yyline; | %line | Zero-based line number of the start of the matched portion of the input stream |
The generated lexical analayzer resides in the class Yylex. There are two constructors to this class, both requiring a single argument: the input stream to be tokenized. The input stream may either be of type System.IO.StreamReader or System.IO.FileReader.
The access function to the lexer is Yylex.yylex(), which
returns the next token from the input stream. The return type is
Yytoken and the function is declared as follows.
class Yylex { ...
public Yytoken yylex () {
... }
The user must declare the type of Yytoken and can
accomplish this conveniently in the first section of the CsLex
specification, the user code section. For instance, to make
Yylex.yylex() return the boxed (Int32.Box) integer
wrapper type, the user would enter the following code somewhere
preceding the first ``%%''.
class Yytoken { }
Then, in the lexical actions, wrapped integers would be
returned, in something like this way.
{ ...
return ((object) i);
... }
Likewise, in the user code section, a class could be defined declaring
constants that correspond to each of the token types.
class TokenCodes { ...
public static final STRING = 0;
public static final INTEGER = 1;
... }
Then, in the lexical actions, these token codes could be
returned.
{ ...
return ((object) STRING);
... }
These are simplified examples; in actual use, one would probably
define a token class containing more information than an integer
code.
These examples begin to illustrate the object-oriented
techniques a user could employ to define an arbitrarily complex
token type to be returned by Yylex.yylex(). In
particular, inheritance permits the user to return more than one
token type. If a distinct token type was needed for strings and
integers, the user could make the following declarations.
class Yytoken { ... }
class IntegerToken extends Yytoken { ... }
class StringToken extends Yytoken { ... }
Then the user could return both IntegerToken and
StringToken types from the lexical actions.
The names of the lexical analyzer class, the tokening function, and its return type each may be altered using the CsLex directives.
The design and architecture of CsLex, written in C#, is based on a melding of the JLex implementation and the Lex functional specification. JLex was written for the Java language, and it's direct antecedent Lex, designed and written for the C language.
CsLex distinguishes itself by incorporating a number of C# language constructs and services; refer to the design notes for CsLex for more details on C# specific features incorporated into the CsLex design.
Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the authors or their employers not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.
The authors and their employers disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the authors or their employers be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software.
C# is a trademark of Microsoft Corp. References to the C# programming language in relation to CsLex are not meant to imply that Microsoft endorses this product.
Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the authors or their employers not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.
The authors and their employers disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the authors or their employers be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software.
Java is a trademark of Sun Microsystems, Inc. References to the Java programming language in relation to JLex are not meant to imply that Sun endorses this product.