C++98 lexer

This is an example of a big, real-world re2c program: a C++98 lexer. It conforms to the C++98 standard (except for a couple of hacks that simulate the preprocessor). All nontrivial lexemes (integers, floating-point constants, strings, and character literals) are parsed (not only recognized): numeric literals are converted to numbers, and strings are unescaped. Some additional checks described in the standard (e.g., overflows in integer literals) are also done. In fact, C++ is an easy language to lex: unlike in many other languages, the C++98 lexer can proceed without feedback from the parser.

[cxx98.re]

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#include <float.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>

/*!max:re2c*/
static const size_t SIZE = 64 * 1024;

struct input_t {
    unsigned char buf[SIZE + YYMAXFILL];
    unsigned char *lim;
    unsigned char *cur;
    unsigned char *mar;
    unsigned char *tok;
    bool eof;

    FILE *const file;

    input_t(FILE *f)
        : buf()
        , lim(buf + SIZE)
        , cur(lim)
        , mar(lim)
        , tok(lim)
        , eof(false)
        , file(f)
    {}
    bool fill(size_t need)
    {
        if (eof) {
            return false;
        }
        const size_t free = tok - buf;
        if (free < need) {
            return false;
        }
        memmove(buf, tok, lim - tok);
        lim -= free;
        cur -= free;
        mar -= free;
        tok -= free;
        lim += fread(lim, 1, free, file);
        if (lim < buf + SIZE) {
            eof = true;
            memset(lim, 0, YYMAXFILL);
            lim += YYMAXFILL;
        }
        return true;
    }
};

/*!re2c re2c:define:YYCTYPE = "unsigned char"; */

template<int base>
static bool adddgt(unsigned long &u, unsigned long d)
{
    if (u > (ULONG_MAX - d) / base) {
        return false;
    }
    u = u * base + d;
    return true;
}

static bool lex_oct(const unsigned char *s, const unsigned char *e, unsigned long &u)
{
    for (u = 0, ++s; s < e; ++s) {
        if (!adddgt<8>(u, *s - 0x30u)) {
            return false;
        }
    }
    return true;
}

static bool lex_dec(const unsigned char *s, const unsigned char *e, unsigned long &u)
{
    for (u = 0; s < e; ++s) {
        if (!adddgt<10>(u, *s - 0x30u)) {
            return false;
        }
    }
    return true;
}

static bool lex_hex(const unsigned char *s, const unsigned char *e, unsigned long &u)
{
    for (u = 0, s += 2; s < e;) {
    /*!re2c
        re2c:yyfill:enable = 0;
        re2c:define:YYCURSOR = s;
        *     { if (!adddgt<16>(u, s[-1] - 0x30u))      return false; continue; }
        [a-f] { if (!adddgt<16>(u, s[-1] - 0x61u + 10)) return false; continue; }
        [A-F] { if (!adddgt<16>(u, s[-1] - 0x41u + 10)) return false; continue; }
    */
    }
    return true;
}

static bool lex_str(input_t &in, unsigned char q)
{
    printf("%c", q);
    for (unsigned long u = q;; printf("\\x%lx", u)) {
        in.tok = in.cur;
        /*!re2c
            re2c:define:YYCURSOR = in.cur;
            re2c:define:YYMARKER = in.mar;
            re2c:define:YYLIMIT = in.lim;
            re2c:yyfill:enable = 1;
            re2c:define:YYFILL = "if (!in.fill(@@)) return false;";
            re2c:define:YYFILL:naked = 1;
            *                    { return false; }
            [^\n\\]              { u = in.tok[0]; if (u == q) break; continue; }
            "\\a"                { u = '\a'; continue; }
            "\\b"                { u = '\b'; continue; }
            "\\f"                { u = '\f'; continue; }
            "\\n"                { u = '\n'; continue; }
            "\\r"                { u = '\r'; continue; }
            "\\t"                { u = '\t'; continue; }
            "\\v"                { u = '\v'; continue; }
            "\\\\"               { u = '\\'; continue; }
            "\\'"                { u = '\''; continue; }
            "\\\""               { u = '"';  continue; }
            "\\?"                { u = '?';  continue; }
            "\\" [0-7]{1,3}      { lex_oct(in.tok, in.cur, u); continue; }
            "\\u" [0-9a-fA-F]{4} { lex_hex(in.tok, in.cur, u); continue; }
            "\\U" [0-9a-fA-F]{8} { lex_hex(in.tok, in.cur, u); continue; }
            "\\x" [0-9a-fA-F]+   { if (!lex_hex(in.tok, in.cur, u)) return false; continue; }
        */
    }
    printf("%c", q);
    return true;
}

static bool lex_flt(const unsigned char *s)
{
    double d = 0;
    double x = 1;
    int e = 0;
    /*!re2c
        re2c:yyfill:enable = 0;
        re2c:define:YYCURSOR = s;
    */
mant_int:
    /*!re2c
        "."   { goto mant_frac; }
        [eE]  { goto exp_sign; }
        *     { d = (d * 10) + (s[-1] - '0'); goto mant_int; }
    */
mant_frac:
    /*!re2c
        ""    { goto sfx; }
        [eE]  { goto exp_sign; }
        [0-9] { d += (x /= 10) * (s[-1] - '0'); goto mant_frac; }
    */
exp_sign:
    /*!re2c
        "+"?  { x = 1e+1; goto exp; }
        "-"   { x = 1e-1; goto exp; }
    */
exp:
    /*!re2c
        ""    { for (; e > 0; --e) d *= x;    goto sfx; }
        [0-9] { e = (e * 10) + (s[-1] - '0'); goto exp; }
    */
sfx:
    /*!re2c
        *     { goto end; }
        [fF]  { if (d > FLT_MAX) return false; goto end; }
    */
end:
    printf("%g", d);
    return true;
}

static bool lex(input_t &in)
{
    unsigned long u;
    for (;;) {
        in.tok = in.cur;
        /*!re2c
            re2c:define:YYCURSOR = in.cur;
            re2c:define:YYMARKER = in.mar;
            re2c:define:YYLIMIT = in.lim;
            re2c:yyfill:enable = 1;
            re2c:define:YYFILL = "if (!in.fill(@@)) return false;";
            re2c:define:YYFILL:naked = 1;

            end = "\x00";

            *   { return false; }
            end { return in.lim - in.tok == YYMAXFILL; }

            // macros
            macro = ("#" | "%:") ([^\n] | "\\\n")* "\n";
            macro { continue; }

            // whitespaces
            mcm = "/*" ([^*] | ("*" [^/]))* "*""/";
            scm = "//" [^\n]* "\n";
            wsp = ([ \t\v\n\r] | scm | mcm)+;
            wsp { printf(" "); continue; }

            // character and string literals
            "L"? ['"] { if (!lex_str(in, in.cur[-1])) return false; continue; }
            "L"? "''" { return false; }

            // integer literals
            oct = "0" [0-7]*;
            dec = [1-9][0-9]*;
            hex = '0x' [0-9a-fA-F]+;
            oct { if (!lex_oct(in.tok, in.cur, u)) return false; goto sfx; }
            dec { if (!lex_dec(in.tok, in.cur, u)) return false; goto sfx; }
            hex { if (!lex_hex(in.tok, in.cur, u)) return false; goto sfx; }

            // floating literals
            frc = [0-9]* "." [0-9]+ | [0-9]+ ".";
            exp = 'e' [+-]? [0-9]+;
            flt = (frc exp? | [0-9]+ exp) [fFlL]?;
            flt { if (lex_flt(in.tok)) continue; return false; }

            // boolean literals
            "false" { printf("false"); continue; }
            "true"  { printf("true");  continue; }

            // keywords
            "asm"              { printf("ASM");              continue; }
            "auto"             { printf("AUTO");             continue; }
            "bool"             { printf("BOOL");             continue; }
            "break"            { printf("BREAK");            continue; }
            "case"             { printf("CASE");             continue; }
            "catch"            { printf("CATCH");            continue; }
            "char"             { printf("CHAR");             continue; }
            "class"            { printf("CLASS");            continue; }
            "const"            { printf("CONST");            continue; }
            "const_cast"       { printf("CONST_CAST");       continue; }
            "continue"         { printf("CONTINUE");         continue; }
            "default"          { printf("DEFAULT");          continue; }
            "do"               { printf("DO");               continue; }
            "double"           { printf("DOUBLE");           continue; }
            "dynamic_cast"     { printf("DYNAMIC_CAST");     continue; }
            "else"             { printf("ELSE");             continue; }
            "enum"             { printf("ENUM");             continue; }
            "explicit"         { printf("EXPLICIT");         continue; }
            "export"           { printf("EXPORT");           continue; }
            "extern"           { printf("EXTERN");           continue; }
            "float"            { printf("FLOAT");            continue; }
            "for"              { printf("FOR");              continue; }
            "friend"           { printf("FRIEND");           continue; }
            "goto"             { printf("GOTO");             continue; }
            "if"               { printf("IF");               continue; }
            "inline"           { printf("INLINE");           continue; }
            "int"              { printf("INT");              continue; }
            "long"             { printf("LONG");             continue; }
            "mutable"          { printf("MUTABLE");          continue; }
            "namespace"        { printf("NAMESPACE");        continue; }
            "operator"         { printf("OPERATOR");         continue; }
            "private"          { printf("PRIVATE");          continue; }
            "protected"        { printf("PROTECTED");        continue; }
            "public"           { printf("PUBLIC");           continue; }
            "register"         { printf("REGISTER");         continue; }
            "reinterpret_cast" { printf("REINTERPRET_CAST"); continue; }
            "return"           { printf("RETURN");           continue; }
            "short"            { printf("SHORT");            continue; }
            "signed"           { printf("SIGNED");           continue; }
            "sizeof"           { printf("SIZEOF");           continue; }
            "static"           { printf("STATIC");           continue; }
            "static_cast"      { printf("STATIC_CAST");      continue; }
            "struct"           { printf("STRUCT");           continue; }
            "switch"           { printf("SWITCH");           continue; }
            "template"         { printf("TEMPLATE");         continue; }
            "this"             { printf("THIS");             continue; }
            "throw"            { printf("THROW");            continue; }
            "try"              { printf("TRY");              continue; }
            "typedef"          { printf("TYPEDEF");          continue; }
            "typeid"           { printf("TYPEID");           continue; }
            "typename"         { printf("TYPENAME");         continue; }
            "union"            { printf("UNION");            continue; }
            "unsigned"         { printf("UNSIGNED");         continue; }
            "using"            { printf("USING");            continue; }
            "virtual"          { printf("VIRTUAL");          continue; }
            "void"             { printf("VOID");             continue; }
            "volatile"         { printf("VOLATILE");         continue; }
            "wchar_t"          { printf("WCHAR_T");          continue; }
            "while"            { printf("WHILE");            continue; }

            // operators and punctuation (including preprocessor)
            ("{" | "<%")      { printf("{");      continue; }
            ("}" | "%>")      { printf("}");      continue; }
            ("[" | "<:")      { printf("[");      continue; }
            ("]" | ":>")      { printf("]");      continue; }
            "("               { printf("(");      continue; }
            ")"               { printf(")");      continue; }
            ";"               { printf(";");      continue; }
            ":"               { printf(":");      continue; }
            "..."             { printf("...");    continue; }
            "new"             { printf("new");    continue; }
            "delete"          { printf("delete"); continue; }
            "?"               { printf("?");      continue; }
            "::"              { printf("::");     continue; }
            "."               { printf(".");      continue; }
            ".*"              { printf(".");      continue; }
            "+"               { printf("+");      continue; }
            "-"               { printf("-");      continue; }
            "*"               { printf("*");      continue; }
            "/"               { printf("/");      continue; }
            "%"               { printf("%%");     continue; }
            ("^" | "xor")     { printf("^");      continue; }
            ("&" | "bitand")  { printf("&");      continue; }
            ("|" | "bitor")   { printf("|");      continue; }
            ("~" | "compl")   { printf("~");      continue; }
            ("!" | "not")     { printf("!");      continue; }
            "="               { printf("=");      continue; }
            "<"               { printf("<");      continue; }
            ">"               { printf(">");      continue; }
            "+="              { printf("+=");     continue; }
            "-="              { printf("-=");     continue; }
            "*="              { printf("*=");     continue; }
            "/="              { printf("/=");     continue; }
            "%="              { printf("%%=");    continue; }
            ("^=" | "xor_eq") { printf("^=");     continue; }
            ("&=" | "and_eq") { printf("&=");     continue; }
            ("|=" | "or_eq")  { printf("|=");     continue; }
            "<<"              { printf("<<");     continue; }
            ">>"              { printf(">>");     continue; }
            ">>="             { printf(">>=");    continue; }
            "<<="             { printf("<<=");    continue; }
            "=="              { printf("==");     continue; }
            ("!=" | "not_eq") { printf("!=");     continue; }
            "<="              { printf("<=");     continue; }
            ">="              { printf(">=");     continue; }
            ("&&" | "and")    { printf("&&");     continue; }
            ("||" | "or")     { printf("||");     continue; }
            "++"              { printf("++");     continue; }
            "--"              { printf("--");     continue; }
            ","               { printf(",");      continue; }
            "->*"             { printf("->*");    continue; }
            "->"              { printf("->");     continue; }

            // identifiers
            id = [a-zA-Z_][a-zA-Z_0-9]*;
            id { printf("%.*s", in.cur - in.tok, in.tok); continue; }
        */
sfx:
        /*!re2c
            ""          { if (u > INT_MAX)  return false; printf("%d",  static_cast<int>(u));      continue; }
            'u'         { if (u > UINT_MAX) return false; printf("%u",  static_cast<unsigned>(u)); continue; }
            'l'         { if (u > LONG_MAX) return false; printf("%ld", static_cast<long>(u));     continue; }
            'ul' | 'lu' { printf("%lu", u); continue; }
        */
    }
}

int main(int argc, char **argv)
{
    if (argc != 2) {
        printf ("usage: ./example <filename>\n");
        return 1;
    }

    FILE *file = fopen(argv[1], "rb");
    if (!file) {
        printf("error: cannot open file: %s\n", argv[1]);
        return 1;
    }

    input_t in(file);
    if (!lex(in)) {
        printf("... error\n");
    } else {
        printf("\n");
    }

    fclose(file);
    return 0;
}

Notes:

  • The main lexer is used to lex all trivial lexemes (macros, whitespace, boolean literals, keywords, operators, punctuators, and identifiers), recognize numeric literals (which are further parsed by a bunch of auxiliary lexers), and recognize the start of a string and character literals (which are further recognized and parsed by an auxiliary lexer). Numeric literals are thus lexed twice: this approach may be deemed inefficient, but it takes much more effort to validate and parse them in one go. Besides, a real-world lexer would rather recognize ill-formed lexemes (e.g., overflown integer literals), report them, and resume lexing.
  • We don’t use re2c in cases where a hand-written parser looks simpler: when parsing octal and decimal literals (though a re2c-based parser would do exactly the same, without the slightest overhead). However, hexadecimal literals still require some lexing, which looks better with re2c. Again, it’s only a matter of taste: a re2c-based implementation adds no overhead. Look at the generated code to make sure.
  • The main lexer and string lexer both use re2c:yyfill:enable = 1;, other lexers use re2c:yyfill:enable = 0;. This is very important: both the main lexer and string lexer advance input position to new (yet unseen) input characters, so they must check for the end of input and call YYFILL. In contrast, other lexers only parse lexemes that have already been recognized by the main lexer: these lexemes are guaranteed to be within buffer bounds (they are guarded by in.tok on the left and in.lim on the right).
  • The hardest part is (unsurprisingly) floating-point literals. They are just as hard to lex as they are to use. :)

Generate, compile, and run:

$ re2c -o cxx98.cc cxx98.re
$ g++ -o cxx98 cxx98.cc

Run:

$ ./cxx98 07_cxx98.re | fold
 STATIC CONST size_t SIZE = 64 * 1024; STRUCT input_t { UNSIGNED CHAR buf[SIZE +
 YYMAXFILL]; UNSIGNED CHAR *lim; UNSIGNED CHAR *cur; UNSIGNED CHAR *mar; UNSIGNE
D CHAR *tok; BOOL eof; FILE *CONST file; input_t(FILE *f) : buf() , lim(buf + SI
ZE) , cur(lim) , mar(lim) , tok(lim) , eof(false) , file(f) {} BOOL fill(size_t
need) { IF (eof) { RETURN false; } CONST size_t free = tok - buf; IF (free < nee
d) { RETURN false; } memmove(buf, tok, lim - tok); lim -= free; cur -= free; mar
 -= free; tok -= free; lim += fread(lim, 1, free, file); IF (lim < buf + SIZE) {
 eof = true; memset(lim, 0, YYMAXFILL); lim += YYMAXFILL; } RETURN true; } }; TE
MPLATE<INT base> STATIC BOOL adddgt(UNSIGNED LONG &u, UNSIGNED LONG d) { IF (u >
 (ULONG_MAX - d) / base) { RETURN false; } u = u * base + d; RETURN true; } STAT
IC BOOL lex_oct(CONST UNSIGNED CHAR *s, CONST UNSIGNED CHAR *e, UNSIGNED LONG &u
) { FOR (u = 0, ++s; s < e; ++s) { IF (!adddgt<8>(u, *s - 48)) { RETURN false; }
 } RETURN true; } STATIC BOOL lex_dec(CONST UNSIGNED CHAR *s, CONST UNSIGNED CHA
R *e, UNSIGNED LONG &u) { FOR (u = 0; s < e; ++s) { IF (!adddgt<10>(u, *s - 48))
 { RETURN false; } } RETURN true; } STATIC BOOL lex_hex(CONST UNSIGNED CHAR *s,
CONST UNSIGNED CHAR *e, UNSIGNED LONG &u) { FOR (u = 0, s += 2; s < e;) { } RETU
RN true; } STATIC BOOL lex_str(input_t &in, UNSIGNED CHAR q) { printf("\x25\x63"
, q); FOR (UNSIGNED LONG u = q;; printf("\x5c\x78\x25\x6c\x78", u)) { in.tok = i
n.cur; } printf("\x25\x63", q); RETURN true; } STATIC BOOL lex_flt(CONST UNSIGNE
D CHAR *s) { DOUBLE d = 0; DOUBLE x = 1; INT e = 0; mant_int: mant_frac: exp_sig
n: exp: sfx: end: printf("\x25\x67", d); RETURN true; } STATIC BOOL lex(input_t
&in) { UNSIGNED LONG u; FOR (;;) { in.tok = in.cur; sfx: } } INT main(INT argc,
CHAR **argv) { IF (argc != 2) { printf ("\x75\x73\x61\x67\x65\x3a\x20\x2e\x2f\x6
5\x78\x61\x6d\x70\x6c\x65\x20\x3c\x66\x69\x6c\x65\x6e\x61\x6d\x65\x3e\xa"); RETU
RN 1; } FILE *file = fopen(argv[1], "\x72\x62"); IF (!file) { printf("\x65\x72\x
72\x6f\x72\x3a\x20\x63\x61\x6e\x6e\x6f\x74\x20\x6f\x70\x65\x6e\x20\x66\x69\x6c\x
65\x3a\x20\x25\x73\xa", argv[1]); RETURN 1; } input_t in(file); IF (!lex(in)) {
printf("\x2e\x2e\x2e\x20\x65\x72\x72\x6f\x72\xa"); } ELSE { printf("\xa"); } fcl
ose(file); RETURN 0; }