]> ocean-lang.org Git - ocean/blob - csrc/parsergen.mdc
parsergen: pass 'config' in to 'reduce' function.
[ocean] / csrc / parsergen.mdc
1 # LR(1) Parser Generator #
2
3 This parser generator takes a grammar description combined with code
4 fragments, analyses it, and can report details about the analysis and
5 write out C code files which can be compiled to make a parser.
6
7 There are several distinct sections.
8
9 1. `grammar_read` will read a grammar from a literate-code file and
10    store the productions, symbols, and code fragments.
11 2. `grammar_analyse` will take that grammar and build LR parsing
12    states and look-ahead tables.
13 3. `grammar_report` will present the details of the analysis
14    in a readable format and will report any conflicts.
15 4. `parser_generate` will write out C code files with various
16    tables and with the code fragments arranged in useful places.
17 5. `parser_run` is a library function intended to be linked together
18    with the generated parser tables to complete the implementation of
19    a parser.
20 6. Finally `calc` is a test grammar for a simple calculator.  The
21    `parsergen` program built from the C code in this file can extract
22    that grammar directly from this file and process it.
23
24
25 ###### File: parsergen.c
26         #include <unistd.h>
27         #include <stdlib.h>
28         #include <stdio.h>
29         ## includes
30         ## forward declarations
31         ## declarations
32         ## functions
33         ## grammar_read
34         ## grammar_analyse
35         ## grammar_report
36         ## parser_generate
37         ## main
38 ###### File: parser.h
39         ## exported types
40         ## exported functions
41 ###### File: libparser.c
42         #include <unistd.h>
43         #include <stdlib.h>
44         #include <stdio.h>
45         ## parser includes
46         ## parser functions
47         ## parser_run
48 ###### File: parsergen.mk
49         CFLAGS += -Wall -g
50         all :: parsergen calc
51         parsergen.c parsergen.mk libparser.c parser.h : parsergen.mdc
52                 ./md2c parsergen.mdc
53
54 ## Reading the grammar
55
56 The grammar must be stored in a markdown literate code file as parsed
57 by "[mdcode][]".  It must have three top level (i.e. unreferenced)
58 sections: `header`, `code`, and `grammar`.  The first two will be
59 literally copied into the generated `.c` and `.h`. files.  The last
60 contains the grammar.  This is tokenised with "[scanner][]".
61
62 If the `--tag` option is given, then any top level header that doesn't
63 start with the tag is ignored, and the tag is striped from the rest.  So
64 `--tag Foo`
65 means that the three needed sections must be `Foo: header`, `Foo: code`,
66 and `Foo: grammar`.
67
68 [mdcode]: mdcode.html
69 [scanner]: scanner.html
70
71 ###### includes
72         #include "mdcode.h"
73         #include "scanner.h"
74
75 ###### parser includes
76         #include "mdcode.h"
77         #include "scanner.h"
78
79 The grammar contains production sets, precedence/associativity
80 declarations, and data type declarations.  These are all parsed with
81 _ad hoc_ parsing as we don't have a parser generator yet.
82
83 The precedence and associativity can be set for each production, but
84 can be inherited from symbols.  The data type (either structure or a
85 reference to a structure) is potentially defined for each non-terminal
86 and describes what C structure is used to store information about each
87 symbol.
88
89 ###### declarations
90         enum assoc {Left, Right, Non};
91         char *assoc_names[] = {"Left","Right","Non"};
92
93         struct symbol {
94                 struct text struct_name;
95                 int isref;
96                 enum assoc assoc;
97                 unsigned short precedence;
98                 ## symbol fields
99         };
100         struct production {
101                 unsigned short precedence;
102                 enum assoc assoc;
103                 ## production fields
104         };
105         struct grammar {
106                 ## grammar fields
107         };
108
109 The strings reported by `mdcode` and `scanner` are `struct text` which have
110 length rather than being null terminated.  To help with printing and
111 comparing we define `text_is` and `prtxt`, which should possibly go in
112 `mdcode`.  `scanner` does provide `text_dump` which is useful for strings
113 which might contain control characters.
114
115 `strip_tag` is a bit like `strncmp`, but adds a test for a colon,
116 because that is what we need to detect tags.
117
118 ###### functions
119         static int text_is(struct text t, char *s)
120         {
121                 return (strlen(s) == t.len &&
122                         strncmp(s, t.txt, t.len) == 0);
123         }
124         static void prtxt(struct text t)
125         {
126                 printf("%.*s", t.len, t.txt);
127         }
128
129         static int strip_tag(struct text *t, char *tag)
130         {
131                 int skip = strlen(tag) + 1;
132                 if (skip >= t->len ||
133                     strncmp(t->txt, tag, skip-1) != 0 ||
134                     t->txt[skip-1] != ':')
135                         return 0;
136                 while (skip < t->len && t->txt[skip] == ' ')
137                         skip++;
138                 t->len -= skip;
139                 t->txt += skip;
140                 return 1;
141         }
142
143 ### Symbols
144
145 Productions are comprised primarily of symbols - terminal and
146 non-terminal.  We do not make a syntactic distinction between the two,
147 though non-terminals must be identifiers.  Non-terminal symbols are
148 those which appear in the head of a production, terminal symbols are
149 those which don't.  There are also "virtual" symbols used for precedence
150 marking discussed later, and sometimes we won't know what type a symbol
151 is yet.
152
153 ###### forward declarations
154         enum symtype { Unknown, Virtual, Terminal, Nonterminal };
155         char *symtypes = "UVTN";
156 ###### symbol fields
157         enum symtype type;
158
159 Symbols can be either `TK_ident` or `TK_mark`.  They are saved in a
160 table of known symbols and the resulting parser will report them as
161 `TK_reserved + N`.  A small set of identifiers are reserved for the
162 different token types that `scanner` can report.
163
164 ###### declarations
165         static char *reserved_words[] = {
166                 [TK_error]        = "ERROR",
167                 [TK_number]       = "NUMBER",
168                 [TK_ident]        = "IDENTIFIER",
169                 [TK_mark]         = "MARK",
170                 [TK_string]       = "STRING",
171                 [TK_multi_string] = "MULTI_STRING",
172                 [TK_in]           = "IN",
173                 [TK_out]          = "OUT",
174                 [TK_newline]      = "NEWLINE",
175                 [TK_eof]          = "$eof",
176         };
177 ###### symbol fields
178         short num;
179
180 Note that `TK_eof` and the two `TK_*_comment` tokens cannot be
181 recognised.  The former is automatically expected at the end of the text
182 being parsed. The latter are always ignored by the parser.
183
184 All of these symbols are stored in a simple symbol table.  We use the
185 `struct text` from `mdcode` to store the name and link them together
186 into a sorted list using an insertion sort.
187
188 We don't have separate `find` and `insert` functions as any symbol we
189 find needs to be remembered.  We simply expect `find` to always return a
190 symbol, but its type might be `Unknown`.
191
192 ###### includes
193         #include <string.h>
194
195 ###### symbol fields
196         struct text name;
197         struct symbol *next;
198
199 ###### grammar fields
200         struct symbol *syms;
201         int num_syms;
202
203 ###### functions
204         static struct symbol *sym_find(struct grammar *g, struct text s)
205         {
206                 struct symbol **l = &g->syms;
207                 struct symbol *n;
208                 int cmp = 1;
209
210                 while (*l &&
211                         (cmp = text_cmp((*l)->name, s)) < 0)
212                                 l = & (*l)->next;
213                 if (cmp == 0)
214                         return *l;
215                 n = calloc(1, sizeof(*n));
216                 n->name = s;
217                 n->type = Unknown;
218                 n->next = *l;
219                 n->num = -1;
220                 *l = n;
221                 return n;
222         }
223
224         static void symbols_init(struct grammar *g)
225         {
226                 int entries = sizeof(reserved_words)/sizeof(reserved_words[0]);
227                 int i;
228                 for (i = 0; i < entries; i++) {
229                         struct text t;
230                         struct symbol *s;
231                         t.txt = reserved_words[i];
232                         if (!t.txt)
233                                 continue;
234                         t.len = strlen(t.txt);
235                         s = sym_find(g, t);
236                         s->type = Terminal;
237                         s->num = i;
238                 }
239         }
240
241 ### Data types and precedence.
242
243 Data type specification and precedence specification are both
244 introduced by a dollar sign at the start of the line.  If the next
245 word is `LEFT`, `RIGHT` or `NON`, then the line specifies a
246 precedence, otherwise it specifies a data type.
247
248 The data type name is simply stored and applied to the head of all
249 subsequent productions.  It must be the name of a structure optionally
250 preceded by an asterisk which means a reference or "pointer".  So
251 `$expression` maps to `struct expression` and `$*statement` maps to
252 `struct statement *`.
253
254 Any productions given before the first data type declaration will have
255 no data type associated with them and can carry no information.  In
256 order to allow other non-terminals to have no type, the data type
257 `$void` can be given.  This does *not* mean that `struct void` will be
258 used, but rather than no type will be associated with future
259 non-terminals.
260
261 The precedence line must contain a list of symbols - typically
262 terminal symbols, but not necessarily.  It can only contain symbols
263 that have not been seen yet, so precedence declaration must precede
264 the productions that they affect.
265
266 A precedence line may also contain a "virtual" symbol which is an
267 identifier preceded by `$$`.  Virtual terminals carry precedence
268 information but are not included in the grammar.  A production can
269 declare that it inherits the precedence of a given virtual symbol.
270
271 This use for `$$` precludes it from being used as a symbol in the
272 described language.  Two other symbols: `${` and `}$` are also
273 unavailable.
274
275 Each new precedence line introduces a new precedence level and
276 declares how it associates.  This level is stored in each symbol
277 listed and may be inherited by any production which uses the symbol.  A
278 production inherits from the last symbol which has a precedence.
279
280 ###### grammar fields
281         struct text current_type;
282         int type_isref;
283         int prec_levels;
284
285 ###### declarations
286         enum symbols { TK_virtual = TK_reserved, TK_open, TK_close };
287         static const char *known[] = { "$$", "${", "}$" };
288
289 ###### functions
290         static char *dollar_line(struct token_state *ts, struct grammar *g, int isref)
291         {
292                 struct token t = token_next(ts);
293                 char *err;
294                 enum assoc assoc;
295                 int found;
296
297                 if (t.num != TK_ident) {
298                         err = "type or assoc expected after '$'";
299                         goto abort;
300                 }
301                 if (text_is(t.txt, "LEFT"))
302                         assoc = Left;
303                 else if (text_is(t.txt, "RIGHT"))
304                         assoc = Right;
305                 else if (text_is(t.txt, "NON"))
306                         assoc = Non;
307                 else {
308                         g->current_type = t.txt;
309                         g->type_isref = isref;
310                         if (text_is(t.txt, "void"))
311                                 g->current_type.txt = NULL;
312                         t = token_next(ts);
313                         if (t.num != TK_newline) {
314                                 err = "Extra tokens after type name";
315                                 goto abort;
316                         }
317                         return NULL;
318                 }
319
320                 if (isref) {
321                         err = "$* cannot be followed by a precedence";
322                         goto abort;
323                 }
324
325                 // This is a precedence line, need some symbols.
326                 found = 0;
327                 g->prec_levels += 1;
328                 t = token_next(ts);
329                 while (t.num != TK_newline) {
330                         enum symtype type = Terminal;
331                         struct symbol *s;
332                         if (t.num == TK_virtual) {
333                                 type = Virtual;
334                                 t = token_next(ts);
335                                 if (t.num != TK_ident) {
336                                         err = "$$ must be followed by a word";
337                                         goto abort;
338                                 }
339                         } else if (t.num != TK_ident &&
340                                    t.num != TK_mark) {
341                                 err = "Illegal token in precedence line";
342                                 goto abort;
343                         }
344                         s = sym_find(g, t.txt);
345                         if (s->type != Unknown) {
346                                 err = "Symbols in precedence line must not already be known.";
347                                 goto abort;
348                         }
349                         s->type = type;
350                         s->precedence = g->prec_levels;
351                         s->assoc = assoc;
352                         found += 1;
353                 }
354                 if (found == 0)
355                         err = "No symbols given on precedence line";
356                         goto abort;
357                 return NULL;
358         abort:
359                 while (t.num != TK_newline && t.num != TK_eof)
360                         t = token_next(ts);
361                 return err;
362         }
363
364 ### Productions
365
366 A production either starts with an identifier which is the head
367 non-terminal, or a vertical bar (`|`) in which case this production
368 uses the same head as the previous one.  The identifier must be
369 followed by a `->` mark.  All productions for a given non-terminal must
370 be grouped together with the `nonterminal ->` given only once.
371
372 After this a (possibly empty) sequence of identifiers and marks form
373 the body of the production.  A virtual symbol may be given after the
374 body by preceding it with `$$`.  If a virtual symbol is given, the
375 precedence of the production is that for the virtual symbol.  If none
376 is given, the precedence is inherited from the last symbol in the
377 production which has a precedence specified.
378
379 After the optional precedence may come the `${` mark.  This indicates
380 the start of a code fragment.  If present, this must be on the same
381 line as the start of the production.
382
383 All of the text from the `${` through to the matching `}$` is
384 collected and forms the code-fragment for the production.  It must all
385 be in one `code_node` of the literate code.  The `}$` must be
386 at the end of a line.
387
388 Text in the code fragment will undergo substitutions where `$N` or
389 `$<N`,for some numeric `N`, will be replaced with a variable holding
390 the parse information for the particular symbol in the production.
391 `$0` is the head of the production, `$1` is the first symbol of the
392 body, etc.  The type of `$N` for a terminal symbol is `struct token`.
393 For a non-terminal, it is whatever has been declared for that symbol.
394 The `<` may be included for symbols declared as storing a reference
395 (not a structure) and means that the reference is being moved out, so
396 it will not automatically be freed.
397
398 While building productions we will need to add to an array which needs to
399 grow dynamically.
400
401 ###### functions
402         static void array_add(void *varray, int *cnt, void *new)
403         {
404                 void ***array = varray;
405                 int current = 0;
406                 const int step = 8;
407                 current = ((*cnt-1) | (step-1))+1;
408                 if (*cnt == current) {
409                         /* must grow */
410                         current += step;
411                         *array = realloc(*array, current * sizeof(void*));
412                 }
413                 (*array)[*cnt] = new;
414                 (*cnt) += 1;
415         }
416
417 Collecting the code fragment simply involves reading tokens until we
418 hit the end token `}$`, and noting the character position of the start and
419 the end.
420
421 ###### functions
422         static struct text collect_code(struct token_state *state,
423                                         struct token start)
424         {
425                 struct text code;
426                 struct token t;
427                 code.txt = start.txt.txt + start.txt.len;
428                 do
429                         t = token_next(state);
430                 while (t.node == start.node &&
431                        t.num != TK_close && t.num != TK_error &&
432                        t.num != TK_eof);
433                 if (t.num == TK_close && t.node == start.node)
434                         code.len = t.txt.txt - code.txt;
435                 else
436                         code.txt = NULL;
437                 return code;
438         }
439
440 Now we have all the bit we need to parse a full production.
441
442 ###### includes
443         #include <memory.h>
444
445 ###### grammar fields
446         struct production **productions;
447         int production_count;
448
449 ###### production fields
450         struct symbol  *head;
451         struct symbol **body;
452         int             body_size;
453         struct text     code;
454
455 ###### symbol fields
456         int first_production;
457
458 ###### functions
459         static char *parse_production(struct grammar *g,
460                                       struct symbol *head,
461                                       struct token_state *state)
462         {
463                 /* Head has already been parsed. */
464                 struct token tk;
465                 char *err;
466                 struct production p, *pp;
467
468                 memset(&p, 0, sizeof(p));
469                 p.head = head;
470                 tk = token_next(state);
471                 while (tk.num == TK_ident || tk.num == TK_mark) {
472                         struct symbol *bs = sym_find(g, tk.txt);
473                         if (bs->type == Unknown)
474                                 bs->type = Terminal;
475                         if (bs->type == Virtual) {
476                                 err = "Virtual symbol not permitted in production";
477                                 goto abort;
478                         }
479                         if (bs->precedence) {
480                                 p.precedence = bs->precedence;
481                                 p.assoc = bs->assoc;
482                         }
483                         array_add(&p.body, &p.body_size, bs);
484                         tk = token_next(state);
485                 }
486                 if (tk.num == TK_virtual) {
487                         struct symbol *vs;
488                         tk = token_next(state);
489                         if (tk.num != TK_ident) {
490                                 err = "word required after $$";
491                                 goto abort;
492                         }
493                         vs = sym_find(g, tk.txt);
494                         if (vs->type != Virtual) {
495                                 err = "symbol after $$ must be virtual";
496                                 goto abort;
497                         }
498                         p.precedence = vs->precedence;
499                         p.assoc = vs->assoc;
500                         tk = token_next(state);
501                 }
502                 if (tk.num == TK_open) {
503                         p.code = collect_code(state, tk);
504                         if (p.code.txt == NULL) {
505                                 err = "code fragment not closed properly";
506                                 goto abort;
507                         }
508                         tk = token_next(state);
509                 }
510                 if (tk.num != TK_newline && tk.num != TK_eof) {
511                         err = "stray tokens at end of line";
512                         goto abort;
513                 }
514                 pp = malloc(sizeof(*pp));
515                 *pp = p;
516                 array_add(&g->productions, &g->production_count, pp);
517                 return NULL;
518         abort:
519                 while (tk.num != TK_newline && tk.num != TK_eof)
520                         tk = token_next(state);
521                 return err;
522         }
523
524 With the ability to parse production and dollar-lines, we have nearly all
525 that we need to parse a grammar from a `code_node`.
526
527 The head of the first production will effectively be the `start` symbol of
528 the grammar.  However it won't _actually_ be so.  Processing the grammar is
529 greatly simplified if the real start symbol only has a single production,
530 and expects `$eof` as the final terminal.  So when we find the first
531 explicit production we insert an extra production as production zero which
532 looks like
533
534 ###### Example: production 0
535         $start -> START $eof
536
537 where `START` is the first non-terminal given.
538
539 ###### create production zero
540         struct production *p = calloc(1,sizeof(*p));
541         struct text start = {"$start",6};
542         struct text eof = {"$eof",4};
543         p->head = sym_find(g, start);
544         p->head->type = Nonterminal;
545         array_add(&p->body, &p->body_size, head);
546         array_add(&p->body, &p->body_size, sym_find(g, eof));
547         p->head->first_production = g->production_count;
548         array_add(&g->productions, &g->production_count, p);
549
550 Now we are ready to read in the grammar.
551
552 ###### grammar_read
553         static struct grammar *grammar_read(struct code_node *code)
554         {
555                 struct token_config conf = {
556                         .word_start = "",
557                         .word_cont = "",
558                         .words_marks = known,
559                         .known_count = sizeof(known)/sizeof(known[0]),
560                         .number_chars = "",
561                         .ignored = (1 << TK_line_comment)
562                                  | (1 << TK_block_comment)
563                                  | (0 << TK_number)
564                                  | (1 << TK_string)
565                                  | (1 << TK_multi_string)
566                                  | (1 << TK_in)
567                                  | (1 << TK_out),
568                 };
569
570                 struct token_state *state = token_open(code, &conf);
571                 struct token tk;
572                 struct symbol *head = NULL;
573                 struct grammar *g;
574                 char *err = NULL;
575
576                 g = calloc(1, sizeof(*g));
577                 symbols_init(g);
578
579                 for (tk = token_next(state); tk.num != TK_eof;
580                      tk = token_next(state)) {
581                         if (tk.num == TK_newline)
582                                 continue;
583                         if (tk.num == TK_ident) {
584                                 // new non-terminal
585                                 head = sym_find(g, tk.txt);
586                                 if (head->type == Nonterminal)
587                                         err = "This non-terminal has already be used.";
588                                 else if (head->type == Virtual)
589                                         err = "Virtual symbol not permitted in head of production";
590                                 else {
591                                         head->type = Nonterminal;
592                                         head->struct_name = g->current_type;
593                                         head->isref = g->type_isref;
594                                         if (g->production_count == 0) {
595                                                 ## create production zero
596                                         }
597                                         head->first_production = g->production_count;
598                                         tk = token_next(state);
599                                         if (tk.num == TK_mark &&
600                                             text_is(tk.txt, "->"))
601                                                 err = parse_production(g, head, state);
602                                         else
603                                                 err = "'->' missing in production";
604                                 }
605                         } else if (tk.num == TK_mark
606                                    && text_is(tk.txt, "|")) {
607                                 // another production for same non-term
608                                 if (head)
609                                         err = parse_production(g, head, state);
610                                 else
611                                         err = "First production must have a head";
612                         } else if (tk.num == TK_mark
613                                    && text_is(tk.txt, "$")) {
614                                 err = dollar_line(state, g, 0);
615                         } else if (tk.num == TK_mark
616                                    && text_is(tk.txt, "$*")) {
617                                 err = dollar_line(state, g, 1);
618                         } else {
619                                 err = "Unrecognised token at start of line.";
620                         }
621                         if (err)
622                                 goto abort;
623                 }
624                 token_close(state);
625                 return g;
626         abort:
627                 fprintf(stderr, "Error at line %d: %s\n",
628                         tk.line, err);
629                 token_close(state);
630                 free(g);
631                 return NULL;
632         }
633
634 ## Analysing the grammar
635
636 The central task in analysing the grammar is to determine a set of
637 states to drive the parsing process.  This will require finding
638 various sets of symbols and of "items".  Some of these sets will need
639 to attach information to each element in the set, so they are more
640 like maps.
641
642 Each "item" may have a 'look-ahead' or `LA` set associated with
643 it.  Many of these will be the same as each other.  To avoid memory
644 wastage, and to simplify some comparisons of sets, these sets will be
645 stored in a list of unique sets, each assigned a number.
646
647 Once we have the data structures in hand to manage these sets and
648 lists, we can start setting the 'nullable' flag, build the 'FIRST'
649 sets, and then create the item sets which define the various states.
650
651 ### Symbol sets.
652
653 Though we don't only store symbols in these sets, they are the main
654 things we store, so they are called symbol sets or "symsets".
655
656 A symset has a size, an array of shorts, and an optional array of data
657 values, which are also shorts.  If the array of data is not present,
658 we store an impossible pointer, as `NULL` is used to indicate that no
659 memory has been allocated yet;
660
661 ###### declarations
662         struct symset {
663                 short cnt;
664                 unsigned short *syms, *data;
665         };
666         #define NO_DATA ((unsigned short *)1)
667         const struct symset INIT_SYMSET =  { 0, NULL, NO_DATA };
668         const struct symset INIT_DATASET = { 0, NULL, NULL };
669
670 The arrays of shorts are allocated in blocks of 8 and are kept sorted
671 by using an insertion sort.  We don't explicitly record the amount of
672 allocated space as it can be derived directly from the current `cnt` using
673 `((cnt - 1) | 7) + 1`.
674
675 ###### functions
676         static void symset_add(struct symset *s, unsigned short key, unsigned short val)
677         {
678                 int i;
679                 int current = ((s->cnt-1) | 7) + 1;
680                 if (current == s->cnt) {
681                         current += 8;
682                         s->syms = realloc(s->syms, sizeof(*s->syms) * current);
683                         if (s->data != NO_DATA)
684                                 s->data = realloc(s->data, sizeof(*s->data) * current);
685                 }
686                 i = s->cnt;
687                 while (i > 0 && s->syms[i-1] > key) {
688                         s->syms[i] = s->syms[i-1];
689                         if (s->data != NO_DATA)
690                                 s->data[i] = s->data[i-1];
691                         i--;
692                 }
693                 s->syms[i] = key;
694                 if (s->data != NO_DATA)
695                         s->data[i] = val;
696                 s->cnt += 1;
697         }
698
699 Finding a symbol (or item) in a `symset` uses a simple binary search.
700 We return the index where the value was found (so data can be accessed),
701 or `-1` to indicate failure.
702
703         static int symset_find(struct symset *ss, unsigned short key)
704         {
705                 int lo = 0;
706                 int hi = ss->cnt;
707
708                 if (hi == 0)
709                         return -1;
710                 while (lo + 1 < hi) {
711                         int mid = (lo + hi) / 2;
712                         if (ss->syms[mid] <= key)
713                                 lo = mid;
714                         else
715                                 hi = mid;
716                 }
717                 if (ss->syms[lo] == key)
718                         return lo;
719                 return -1;
720         }
721
722 We will often want to form the union of two symsets.  When we do, we
723 will often want to know if anything changed (as they might mean there
724 is more work to do).  So `symset_union` reports whether anything was
725 added to the first set.  We use a slow quadratic approach as these
726 sets don't really get very big.  If profiles shows this to be a problem is
727 can be optimised later.
728
729         static int symset_union(struct symset *a, struct symset *b)
730         {
731                 int i;
732                 int added = 0;
733                 for (i = 0; i < b->cnt; i++)
734                         if (symset_find(a, b->syms[i]) < 0) {
735                                 unsigned short data = 0;
736                                 if (b->data != NO_DATA)
737                                         data = b->data[i];
738                                 symset_add(a, b->syms[i], data);
739                                 added++;
740                         }
741                 return added;
742         }
743
744 And of course we must be able to free a symset.
745
746         static void symset_free(struct symset ss)
747         {
748                 free(ss.syms);
749                 if (ss.data != NO_DATA)
750                         free(ss.data);
751         }
752
753 ### Symset Storage
754
755 Some symsets are simply stored somewhere appropriate in the `grammar`
756 data structure, others needs a bit of indirection.  This applies
757 particularly to "LA" sets.  These will be paired with "items" in an
758 "itemset".  As itemsets will be stored in a symset, the "LA" set needs to be
759 stored in the `data` field, so we need a mapping from a small (short)
760 number to an LA `symset`.
761
762 As mentioned earlier this involves creating a list of unique symsets.
763
764 For now, we just use a linear list sorted by insertion.  A skiplist
765 would be more efficient and may be added later.
766
767 ###### declarations
768
769         struct setlist {
770                 struct symset ss;
771                 int num;
772                 struct setlist *next;
773         };
774
775 ###### grammar fields
776         struct setlist *sets;
777         int nextset;
778
779 ###### functions
780
781         static int ss_cmp(struct symset a, struct symset b)
782         {
783                 int i;
784                 int diff = a.cnt - b.cnt;
785                 if (diff)
786                         return diff;
787                 for (i = 0; i < a.cnt; i++) {
788                         diff = (int)a.syms[i] - (int)b.syms[i];
789                         if (diff)
790                                 return diff;
791                 }
792                 return 0;
793         }
794
795         static int save_set(struct grammar *g, struct symset ss)
796         {
797                 struct setlist **sl = &g->sets;
798                 int cmp = 1;
799                 struct setlist *s;
800
801                 while (*sl && (cmp = ss_cmp((*sl)->ss, ss)) < 0)
802                         sl = & (*sl)->next;
803                 if (cmp == 0) {
804                         symset_free(ss);
805                         return (*sl)->num;
806                 }
807
808                 s = malloc(sizeof(*s));
809                 s->ss = ss;
810                 s->num = g->nextset;
811                 g->nextset += 1;
812                 s->next = *sl;
813                 *sl = s;
814                 return s->num;
815         }
816
817 Finding a set by number is currently performed by a simple linear search.
818 If this turns out to hurt performance, we can store the sets in a dynamic
819 array like the productions.
820
821         static struct symset set_find(struct grammar *g, int num)
822         {
823                 struct setlist *sl = g->sets;
824                 while (sl && sl->num != num)
825                         sl = sl->next;
826                 return sl->ss;
827         }
828
829
830 ### Setting `nullable`
831
832 We set `nullable` on the head symbol for any production for which all
833 the body symbols (if any) are nullable.  As this is a recursive
834 definition, any change in the `nullable` setting means that we need to
835 re-evaluate where it needs to be set.
836
837 We simply loop around performing the same calculations until no more
838 changes happen.
839
840 ###### symbol fields
841         int nullable;
842
843 ###### functions
844         static void set_nullable(struct grammar *g)
845         {
846                 int check_again = 1;
847                 while (check_again) {
848                         int p;
849                         check_again = 0;
850                         for (p = 0; p < g->production_count; p++) {
851                                 struct production *pr = g->productions[p];
852                                 int s;
853
854                                 if (pr->head->nullable)
855                                         continue;
856                                 for (s = 0; s < pr->body_size; s++)
857                                         if (! pr->body[s]->nullable)
858                                                 break;
859                                 if (s == pr->body_size) {
860                                         pr->head->nullable = 1;
861                                         check_again = 1;
862                                 }
863                         }
864                 }
865         }
866
867 ### Setting `can_eol`
868
869 In order to be able to ignore newline tokens when not relevant, but
870 still include them in the parse when needed, we will need to know
871 which states can start a "line-like" section of code.  We ignore
872 newlines when there is an indent since the most recent start of a
873 line-like section.
874
875 To know what is line-like, we first need to know which symbols can end
876 a line-like section, which is precisely those which can end with a
877 newline token.  These symbols don't necessarily alway end with a
878 newline, but they can.  Hence they are not described as "lines" but
879 only "line-like".
880
881 Clearly the `TK_newline` token can end with a newline.  Any symbol
882 which is the head of a production that contains a line-ending symbol
883 followed only by nullable symbols is also a line-ending symbol.  We
884 use a new field `can_eol` to record this attribute of symbols, and
885 compute it in a repetitive manner similar to `set_nullable`.
886
887 ###### symbol fields
888         int can_eol;
889
890 ###### functions
891         static void set_can_eol(struct grammar *g)
892         {
893                 int check_again = 1;
894                 g->symtab[TK_newline]->can_eol = 1;
895                 while (check_again) {
896                         int p;
897                         check_again = 0;
898                         for (p = 0; p < g->production_count; p++) {
899                                 struct production *pr = g->productions[p];
900                                 int s;
901
902                                 if (pr->head->can_eol)
903                                         continue;
904
905                                 for (s = pr->body_size - 1; s >= 0; s--) {
906                                         if (pr->body[s]->can_eol) {
907                                                 pr->head->can_eol = 1;
908                                                 check_again = 1;
909                                                 break;
910                                         }
911                                         if (!pr->body[s]->nullable)
912                                                 break;
913                                 }
914                         }
915                 }
916         }
917
918 ### Building the `first` sets
919
920 When calculating what can follow a particular non-terminal, we will need to
921 know what the "first" terminal in any subsequent non-terminal might be.  So
922 we calculate the `first` set for every non-terminal and store them in an
923 array.  We don't bother recording the "first" set for terminals as they are
924 trivial.
925
926 As the "first" for one symbol might depend on the "first" of another,
927 we repeat the calculations until no changes happen, just like with
928 `set_nullable`.  This makes use of the fact that `symset_union`
929 reports if any change happens.
930
931 The core of this which finds the "first" of part of a production body
932 will be reused for computing the "follow" sets, so we split it out
933 into a separate function.
934
935 ###### grammar fields
936         struct symset *first;
937
938 ###### functions
939
940         static int add_first(struct production *pr, int start,
941                              struct symset *target, struct grammar *g,
942                              int *to_end)
943         {
944                 int s;
945                 int changed = 0;
946                 for (s = start; s < pr->body_size; s++) {
947                         struct symbol *bs = pr->body[s];
948                         if (bs->type == Terminal) {
949                                 if (symset_find(target, bs->num) < 0) {
950                                         symset_add(target, bs->num, 0);
951                                         changed = 1;
952                                 }
953                                 break;
954                         } else if (symset_union(target, &g->first[bs->num]))
955                                 changed = 1;
956                         if (!bs->nullable)
957                                 break;
958                 }
959                 if (to_end)
960                         *to_end = (s == pr->body_size);
961                 return changed;
962         }
963
964         static void build_first(struct grammar *g)
965         {
966                 int check_again = 1;
967                 int s;
968                 g->first = calloc(g->num_syms, sizeof(g->first[0]));
969                 for (s = 0; s < g->num_syms; s++)
970                         g->first[s] = INIT_SYMSET;
971
972                 while (check_again) {
973                         int p;
974                         check_again = 0;
975                         for (p = 0; p < g->production_count; p++) {
976                                 struct production *pr = g->productions[p];
977                                 struct symset *head = &g->first[pr->head->num];
978
979                                 if (add_first(pr, 0, head, g, NULL))
980                                         check_again = 1;
981                         }
982                 }
983         }
984
985 ### Building the `follow` sets.
986
987 There are two different situations when we will want to generate "follow"
988 sets.  If we are doing an SLR analysis, we want to generate a single
989 "follow" set for each non-terminal in the grammar.  That is what is
990 happening here.  If we are doing an LALR or LR analysis we will want
991 to generate a separate "LA" set for each item.  We do that later
992 in state generation.
993
994 There are two parts to generating a "follow" set.  Firstly we look at
995 every place that any non-terminal appears in the body of any
996 production, and we find the set of possible "first" symbols after
997 there.  This is done using `add_first` above and only needs to be done
998 once as the "first" sets are now stable and will not change.
999
1000 ###### follow code
1001
1002         for (p = 0; p < g->production_count; p++) {
1003                 struct production *pr = g->productions[p];
1004                 int b;
1005
1006                 for (b = 0; b < pr->body_size - 1; b++) {
1007                         struct symbol *bs = pr->body[b];
1008                         if (bs->type == Terminal)
1009                                 continue;
1010                         add_first(pr, b+1, &g->follow[bs->num], g, NULL);
1011                 }
1012         }
1013
1014 The second part is to add the "follow" set of the head of a production
1015 to the "follow" sets of the final symbol in the production, and any
1016 other symbol which is followed only by `nullable` symbols.  As this
1017 depends on "follow" itself we need to repeatedly perform the process
1018 until no further changes happen.
1019
1020 ###### follow code
1021
1022         for (again = 0, p = 0;
1023              p < g->production_count;
1024              p < g->production_count-1
1025                 ? p++ : again ? (again = 0, p = 0)
1026                               : p++) {
1027                 struct production *pr = g->productions[p];
1028                 int b;
1029
1030                 for (b = pr->body_size - 1; b >= 0; b--) {
1031                         struct symbol *bs = pr->body[b];
1032                         if (bs->type == Terminal)
1033                                 break;
1034                         if (symset_union(&g->follow[bs->num],
1035                                          &g->follow[pr->head->num]))
1036                                 again = 1;
1037                         if (!bs->nullable)
1038                                 break;
1039                 }
1040         }
1041
1042 We now just need to create and initialise the `follow` list to get a
1043 complete function.
1044
1045 ###### grammar fields
1046         struct symset *follow;
1047
1048 ###### functions
1049         static void build_follow(struct grammar *g)
1050         {
1051                 int s, again, p;
1052                 g->follow = calloc(g->num_syms, sizeof(g->follow[0]));
1053                 for (s = 0; s < g->num_syms; s++)
1054                         g->follow[s] = INIT_SYMSET;
1055                 ## follow code
1056         }
1057
1058 ### Building itemsets and states
1059
1060 There are three different levels of detail that can be chosen for
1061 building the itemsets and states for the LR grammar.  They are:
1062
1063 1. LR(0) or SLR(1), where no look-ahead is considered.
1064 2. LALR(1) where we build look-ahead sets with each item and merge
1065    the LA sets when we find two paths to the same "kernel" set of items.
1066 3. LR(1) where different look-ahead for any item in the set means
1067    a different state must be created.
1068
1069 ###### forward declarations
1070         enum grammar_type { LR0, LR05, SLR, LALR, LR1 };
1071
1072 We need to be able to look through existing states to see if a newly
1073 generated state already exists.  For now we use a simple sorted linked
1074 list.
1075
1076 An item is a pair of numbers: the production number and the position of
1077 "DOT", which is an index into the body of the production.
1078 As the numbers are not enormous we can combine them into a single "short"
1079 and store them in a `symset` - 4 bits for "DOT" and 12 bits for the
1080 production number (so 4000 productions with maximum of 15 symbols in the
1081 body).
1082
1083 Comparing the itemsets will be a little different to comparing symsets
1084 as we want to do the lookup after generating the "kernel" of an
1085 itemset, so we need to ignore the offset=zero items which are added during
1086 completion.
1087
1088 To facilitate this, we modify the "DOT" number so that "0" sorts to
1089 the end of the list in the symset, and then only compare items before
1090 the first "0".
1091
1092 ###### declarations
1093         static inline unsigned short item_num(int production, int index)
1094         {
1095                 return production | ((31-index) << 11);
1096         }
1097         static inline int item_prod(unsigned short item)
1098         {
1099                 return item & 0x7ff;
1100         }
1101         static inline int item_index(unsigned short item)
1102         {
1103                 return (31-(item >> 11)) & 0x1f;
1104         }
1105
1106 For LR(1) analysis we need to compare not just the itemset in a state
1107 but also the LA sets.  As we assign each unique LA set a number, we
1108 can just compare the symset and the data values together.
1109
1110 ###### functions
1111         static int itemset_cmp(struct symset a, struct symset b,
1112                                enum grammar_type type)
1113         {
1114                 int i;
1115                 int av, bv;
1116
1117                 for (i = 0;
1118                      i < a.cnt && i < b.cnt &&
1119                      item_index(a.syms[i]) > 0 &&
1120                      item_index(b.syms[i]) > 0;
1121                      i++) {
1122                         int diff = a.syms[i] - b.syms[i];
1123                         if (diff)
1124                                 return diff;
1125                         if (type == LR1) {
1126                                 diff = a.data[i] - b.data[i];
1127                                 if (diff)
1128                                         return diff;
1129                         }
1130                 }
1131                 if (i == a.cnt || item_index(a.syms[i]) == 0)
1132                         av = -1;
1133                 else
1134                         av = a.syms[i];
1135                 if (i == b.cnt || item_index(b.syms[i]) == 0)
1136                         bv = -1;
1137                 else
1138                         bv = b.syms[i];
1139                 if (av - bv)
1140                         return av - bv;
1141                 if (type < LR1 || av == -1)
1142                         return 0;
1143                 return
1144                         a.data[i] - b.data[i];
1145         }
1146
1147 And now we can build the list of itemsets.  The lookup routine returns
1148 both a success flag and a pointer to where in the list an insert
1149 should happen, so we don't need to search a second time.
1150
1151 ###### declarations
1152         struct itemset {
1153                 struct itemset *next;
1154                 short state;
1155                 struct symset items;
1156                 struct symset go_to;
1157                 char completed;
1158                 char starts_line;
1159         };
1160
1161 ###### grammar fields
1162         struct itemset *items;
1163         int states;
1164
1165 ###### functions
1166         static int itemset_find(struct grammar *g, struct itemset ***where,
1167                                 struct symset kernel, enum grammar_type type)
1168         {
1169                 struct itemset **ip;
1170
1171                 for (ip = &g->items; *ip ; ip = & (*ip)->next) {
1172                         struct itemset *i = *ip;
1173                         int diff;
1174                         diff = itemset_cmp(i->items, kernel, type);
1175                         if (diff < 0)
1176                                 continue;
1177                         if (diff > 0)
1178                                 break;
1179                         /* found */
1180                         *where = ip;
1181                         return 1;
1182                 }
1183                 *where = ip;
1184                 return 0;
1185         }
1186
1187 Adding an itemset may require merging the LA sets if LALR analysis is
1188 happening. If any new LA set adds any symbols that weren't in the old LA set, we
1189 clear the `completed` flag so that the dependants of this itemset will be
1190 recalculated and their LA sets updated.
1191
1192 `add_itemset` must consume the symsets it is passed, either by adding
1193 them to a data structure, of freeing them.
1194
1195         static int add_itemset(struct grammar *g, struct symset ss,
1196                                enum grammar_type type, int starts_line)
1197         {
1198                 struct itemset **where, *is;
1199                 int i;
1200                 int found = itemset_find(g, &where, ss, type);
1201                 if (!found) {
1202                         is = calloc(1, sizeof(*is));
1203                         is->state = g->states;
1204                         g->states += 1;
1205                         is->items = ss;
1206                         is->next = *where;
1207                         is->go_to = INIT_DATASET;
1208                         is->starts_line = starts_line;
1209                         *where = is;
1210                         return is->state;
1211                 }
1212                 is = *where;
1213                 if (type != LALR) {
1214                         symset_free(ss);
1215                         return is->state;
1216                 }
1217                 for (i = 0; i < ss.cnt; i++) {
1218                         struct symset temp = INIT_SYMSET, s;
1219                         if (ss.data[i] == is->items.data[i])
1220                                 continue;
1221                         s = set_find(g, is->items.data[i]);
1222                         symset_union(&temp, &s);
1223                         s = set_find(g, ss.data[i]);
1224                         if (symset_union(&temp, &s)) {
1225                                 is->items.data[i] = save_set(g, temp);
1226                                 is->completed = 0;
1227                         } else
1228                                 symset_free(temp);
1229                 }
1230                 symset_free(ss);
1231                 return is->state;
1232         }
1233
1234 #### The build
1235
1236 To build all the itemsets, we first insert the initial itemset made
1237 from production zero, complete each itemset, and then generate new
1238 itemsets from old until no new ones can be made.
1239
1240 Completing an itemset means finding all the items where "DOT" is followed by
1241 a nonterminal and adding "DOT=0" items for every production from that
1242 non-terminal - providing each item hasn't already been added.
1243
1244 If LA sets are needed, the LA set for each new item is found using
1245 `add_first` which was developed earlier for `FIRST` and `FOLLOW`.  This may
1246 be supplemented by the LA set for the item which produce the new item.
1247
1248 We also collect a set of all symbols which follow "DOT" (in `done`) as this
1249 is used in the next stage.
1250
1251 NOTE: precedence handling should happen here - I haven't written this yet
1252 though.
1253
1254 ###### complete itemset
1255         for (i = 0; i < is->items.cnt; i++) {
1256                 int p = item_prod(is->items.syms[i]);
1257                 int bs = item_index(is->items.syms[i]);
1258                 struct production *pr = g->productions[p];
1259                 int p2;
1260                 struct symbol *s;
1261                 struct symset LA = INIT_SYMSET;
1262                 unsigned short sn = 0;
1263
1264                 if (bs == pr->body_size)
1265                         continue;
1266                 s = pr->body[bs];
1267                 if (symset_find(&done, s->num) < 0)
1268                         symset_add(&done, s->num, 0);
1269                 if (s->type != Nonterminal)
1270                         continue;
1271                 again = 1;
1272                 if (type >= LALR) {
1273                         // Need the LA set.
1274                         int to_end;
1275                         add_first(pr, bs+1, &LA, g, &to_end);
1276                         if (to_end) {
1277                                 struct symset ss = set_find(g, is->items.data[i]);
1278                                 symset_union(&LA, &ss);
1279                         }
1280                         sn = save_set(g, LA);
1281                         LA = set_find(g, sn);
1282                 }
1283
1284                 /* Add productions for this symbol */
1285                 for (p2 = s->first_production;
1286                      p2 < g->production_count &&
1287                       g->productions[p2]->head == s;
1288                      p2++) {
1289                         int itm = item_num(p2, 0);
1290                         int pos = symset_find(&is->items, itm);
1291                         if (pos < 0) {
1292                                 symset_add(&is->items, itm, sn);
1293                                 /* Will have re-ordered, so start
1294                                  * from beginning again */
1295                                 i = -1;
1296                         } else if (type >= LALR) {
1297                                 struct symset ss = set_find(g, is->items.data[pos]);
1298                                 struct symset tmp = INIT_SYMSET;
1299
1300                                 symset_union(&tmp, &ss);
1301                                 if (symset_union(&tmp, &LA)) {
1302                                         is->items.data[pos] = save_set(g, tmp);
1303                                         i = -1;
1304                                 }else
1305                                         symset_free(tmp);
1306                         }
1307                 }
1308         }
1309
1310 For each symbol we found (and placed in `done`) we collect all the items for
1311 which this symbol is next, and create a new itemset with "DOT" advanced over
1312 the symbol.  This is then added to the collection of itemsets (or merged
1313 with a pre-existing itemset).
1314
1315 ###### derive itemsets
1316         // Now we have a completed itemset, so we need to
1317         // compute all the 'next' itemsets and create them
1318         // if they don't exist.
1319         for (i = 0; i < done.cnt; i++) {
1320                 int j;
1321                 unsigned short state;
1322                 int starts_line = 0;
1323                 struct symbol *sym = g->symtab[done.syms[i]];
1324                 struct symset newitemset = INIT_SYMSET;
1325                 if (type >= LALR)
1326                         newitemset = INIT_DATASET;
1327
1328                 if (sym->can_eol ||
1329                     (sym->nullable && is->starts_line))
1330                         starts_line = 1;
1331                 for (j = 0; j < is->items.cnt; j++) {
1332                         int itm = is->items.syms[j];
1333                         int p = item_prod(itm);
1334                         int bp = item_index(itm);
1335                         struct production *pr = g->productions[p];
1336                         unsigned short la = 0;
1337                         int pos;
1338
1339                         if (bp == pr->body_size)
1340                                 continue;
1341                         if (pr->body[bp] != sym)
1342                                 continue;
1343                         if (type >= LALR)
1344                                 la = is->items.data[j];
1345                         pos = symset_find(&newitemset, pr->head->num);
1346                         if (pos < 0)
1347                                 symset_add(&newitemset, item_num(p, bp+1), la);
1348                         else if (type >= LALR) {
1349                                 // Need to merge la set.
1350                                 int la2 = newitemset.data[pos];
1351                                 if (la != la2) {
1352                                         struct symset ss = set_find(g, la2);
1353                                         struct symset LA = INIT_SYMSET;
1354                                         symset_union(&LA, &ss);
1355                                         ss = set_find(g, la);
1356                                         if (symset_union(&LA, &ss))
1357                                                 newitemset.data[pos] = save_set(g, LA);
1358                                         else
1359                                                 symset_free(LA);
1360                                 }
1361                         }
1362                 }
1363                 state = add_itemset(g, newitemset, type, starts_line);
1364                 if (symset_find(&is->go_to, done.syms[i]) < 0)
1365                         symset_add(&is->go_to, done.syms[i], state);
1366         }
1367
1368 All that is left is to crate the initial itemset from production zero, and
1369 with `TK_eof` as the LA set.
1370
1371 ###### functions
1372         static void build_itemsets(struct grammar *g, enum grammar_type type)
1373         {
1374                 struct symset first = INIT_SYMSET;
1375                 struct itemset *is;
1376                 int again;
1377                 unsigned short la = 0;
1378                 if (type >= LALR) {
1379                         // LA set just has eof
1380                         struct symset eof = INIT_SYMSET;
1381                         symset_add(&eof, TK_eof, 0);
1382                         la = save_set(g, eof);
1383                         first = INIT_DATASET;
1384                 }
1385                 // production 0, offset 0 (with no data)
1386                 symset_add(&first, item_num(0, 0), la);
1387                 add_itemset(g, first, type, g->productions[0]->body[0]->can_eol);
1388                 for (again = 0, is = g->items;
1389                      is;
1390                      is = is->next ?: again ? (again = 0, g->items) : NULL) {
1391                         int i;
1392                         struct symset done = INIT_SYMSET;
1393                         if (is->completed)
1394                                 continue;
1395                         is->completed = 1;
1396                         again = 1;
1397                         ## complete itemset
1398                         ## derive itemsets
1399                         symset_free(done);
1400                 }
1401         }
1402
1403 ### Completing the analysis.
1404
1405 The exact process of analysis depends on which level was requested.  For
1406 `LR0` and `LR05` we don't need first and follow sets at all.  For `LALR` and
1407 `LR1` we need first, but not follow.  For `SLR` we need both.
1408
1409 We don't build the "action" tables that you might expect as the parser
1410 doesn't use them.  They will be calculated to some extent if needed for
1411 a report.
1412
1413 Once we have built everything we allocate arrays for the two lists:
1414 symbols and itemsets.  This allows more efficient access during reporting.
1415 The symbols are grouped as terminals and non-terminals and we record the
1416 changeover point in `first_nonterm`.
1417
1418 ###### grammar fields
1419         struct symbol **symtab;
1420         struct itemset **statetab;
1421         int first_nonterm;
1422
1423 ###### grammar_analyse
1424
1425         static void grammar_analyse(struct grammar *g, enum grammar_type type)
1426         {
1427                 struct symbol *s;
1428                 struct itemset *is;
1429                 int snum = TK_reserved;
1430                 for (s = g->syms; s; s = s->next)
1431                         if (s->num < 0 && s->type == Terminal) {
1432                                 s->num = snum;
1433                                 snum++;
1434                         }
1435                 g->first_nonterm = snum;
1436                 for (s = g->syms; s; s = s->next)
1437                         if (s->num < 0) {
1438                                 s->num = snum;
1439                                 snum++;
1440                         }
1441                 g->num_syms = snum;
1442                 g->symtab = calloc(g->num_syms, sizeof(g->symtab[0]));
1443                 for (s = g->syms; s; s = s->next)
1444                         g->symtab[s->num] = s;
1445
1446                 set_nullable(g);
1447                 set_can_eol(g);
1448                 if (type >= SLR)
1449                         build_first(g);
1450
1451                 if (type == SLR)
1452                         build_follow(g);
1453
1454                 build_itemsets(g, type);
1455
1456                 g->statetab = calloc(g->states, sizeof(g->statetab[0]));
1457                 for (is = g->items; is ; is = is->next)
1458                         g->statetab[is->state] = is;
1459         }
1460
1461 ## Reporting on the Grammar
1462
1463 The purpose of the report is to give the grammar developer insight into
1464 how the grammar parser will work.  It is basically a structured dump of
1465 all the tables that have been generated, plus a description of any conflicts.
1466
1467 ###### grammar_report
1468         static int grammar_report(struct grammar *g, enum grammar_type type)
1469         {
1470                 report_symbols(g);
1471                 if (g->follow)
1472                         report_follow(g);
1473                 report_itemsets(g);
1474                 return report_conflicts(g, type);
1475         }
1476
1477 Firstly we have the complete list of symbols, together with the
1478 "FIRST" set if that was generated.  We add a mark to each symbol to
1479 show if it can end in a newline (`>`), or if it is nullable (`.`).
1480
1481 ###### functions
1482
1483         static void report_symbols(struct grammar *g)
1484         {
1485                 int n;
1486                 if (g->first)
1487                         printf("SYMBOLS + FIRST:\n");
1488                 else
1489                         printf("SYMBOLS:\n");
1490
1491                 for (n = 0; n < g->num_syms; n++) {
1492                         struct symbol *s = g->symtab[n];
1493                         if (!s)
1494                                 continue;
1495
1496                         printf(" %c%c%3d%c: ",
1497                                s->nullable ? '.':' ',
1498                                s->can_eol ? '>':' ',
1499                                s->num, symtypes[s->type]);
1500                         prtxt(s->name);
1501                         if (s->precedence)
1502                                 printf(" (%d%s)", s->precedence,
1503                                        assoc_names[s->assoc]);
1504
1505                         if (g->first && s->type == Nonterminal) {
1506                                 int j;
1507                                 char c = ':';
1508                                 for (j = 0; j < g->first[n].cnt; j++) {
1509                                         printf("%c ", c);
1510                                         c = ',';
1511                                         prtxt(g->symtab[g->first[n].syms[j]]->name);
1512                                 }
1513                         }
1514                         printf("\n");
1515                 }
1516         }
1517
1518 Then we have the follow sets if they were computed.
1519
1520         static void report_follow(struct grammar *g)
1521         {
1522                 int n;
1523                 printf("FOLLOW:\n");
1524                 for (n = 0; n < g->num_syms; n++)
1525                         if (g->follow[n].cnt) {
1526                                 int j;
1527                                 char c = ':';
1528                                 printf("  ");
1529                                 prtxt(g->symtab[n]->name);
1530                                 for (j = 0; j < g->follow[n].cnt; j++) {
1531                                         printf("%c ", c);
1532                                         c = ',';
1533                                         prtxt(g->symtab[g->follow[n].syms[j]]->name);
1534                                 }
1535                                 printf("\n");
1536                         }
1537         }
1538
1539 And finally the item sets.  These include the GO TO tables and, for
1540 LALR and LR1, the LA set for each item.  Lots of stuff, so we break
1541 it up a bit.  First the items, with production number and associativity.
1542
1543         static void report_item(struct grammar *g, int itm)
1544         {
1545                 int p = item_prod(itm);
1546                 int dot = item_index(itm);
1547                 struct production *pr = g->productions[p];
1548                 int i;
1549
1550                 printf("    ");
1551                 prtxt(pr->head->name);
1552                 printf(" ->");
1553                 for (i = 0; i < pr->body_size; i++) {
1554                         printf(" %s", (dot == i ? ". ": ""));
1555                         prtxt(pr->body[i]->name);
1556                 }
1557                 if (dot == pr->body_size)
1558                         printf(" .");
1559                 printf(" [%d]", p);
1560                 if (pr->precedence)
1561                         printf(" (%d%s)", pr->precedence,
1562                                assoc_names[pr->assoc]);
1563                 printf("\n");
1564         }
1565
1566 The LA sets which are (possibly) reported with each item:
1567
1568         static void report_la(struct grammar *g, int lanum)
1569         {
1570                 struct symset la = set_find(g, lanum);
1571                 int i;
1572                 char c = ':';
1573
1574                 printf("        LOOK AHEAD(%d)", lanum);
1575                 for (i = 0; i < la.cnt; i++) {
1576                         printf("%c ", c);
1577                         c = ',';
1578                         prtxt(g->symtab[la.syms[i]]->name);
1579                 }
1580                 printf("\n");
1581         }
1582
1583 Then the go to sets:
1584
1585
1586         static void report_goto(struct grammar *g, struct symset gt)
1587         {
1588                 int i;
1589                 printf("    GOTO:\n");
1590
1591                 for (i = 0; i < gt.cnt; i++) {
1592                         printf("      ");
1593                         prtxt(g->symtab[gt.syms[i]]->name);
1594                         printf(" -> %d\n", gt.data[i]);
1595                 }
1596         }
1597
1598 Now we can report all the item sets complete with items, LA sets, and GO TO.
1599
1600         static void report_itemsets(struct grammar *g)
1601         {
1602                 int s;
1603                 printf("ITEM SETS(%d)\n", g->states);
1604                 for (s = 0; s < g->states; s++) {
1605                         int j;
1606                         struct itemset *is = g->statetab[s];
1607                         printf("  Itemset %d:%s\n", s, is->starts_line?" (startsline)":"");
1608                         for (j = 0; j < is->items.cnt; j++) {
1609                                 report_item(g, is->items.syms[j]);
1610                                 if (is->items.data != NO_DATA)
1611                                         report_la(g, is->items.data[j]);
1612                         }
1613                         report_goto(g, is->go_to);
1614                 }
1615         }
1616
1617 ### Reporting conflicts
1618
1619 Conflict detection varies a lot among different analysis levels.  However
1620 LR0 and LR0.5 are quite similar - having no follow sets, and SLR, LALR and
1621 LR1 are also similar as they have FOLLOW or LA sets.
1622
1623 ###### functions
1624
1625         ## conflict functions
1626
1627         static int report_conflicts(struct grammar *g, enum grammar_type type)
1628         {
1629                 int cnt = 0;
1630                 printf("Conflicts:\n");
1631                 if (type < SLR)
1632                         cnt = conflicts_lr0(g, type);
1633                 else
1634                         cnt = conflicts_slr(g, type);
1635                 if (cnt == 0)
1636                         printf(" - no conflicts\n");
1637                 return cnt;
1638         }
1639
1640 LR0 conflicts are any state which have both a reducible item and
1641 a shiftable item, or two reducible items.
1642
1643 LR05 conflicts only occurs if two possibly reductions exist,
1644 as shifts always over-ride reductions.
1645
1646 ###### conflict functions
1647         static int conflicts_lr0(struct grammar *g, enum grammar_type type)
1648         {
1649                 int i;
1650                 int cnt = 0;
1651                 for (i = 0; i < g->states; i++) {
1652                         struct itemset *is = g->statetab[i];
1653                         int last_reduce = -1;
1654                         int prev_reduce = -1;
1655                         int last_shift = -1;
1656                         int j;
1657                         if (!is)
1658                                 continue;
1659                         for (j = 0; j < is->items.cnt; j++) {
1660                                 int itm = is->items.syms[j];
1661                                 int p = item_prod(itm);
1662                                 int bp = item_index(itm);
1663                                 struct production *pr = g->productions[p];
1664
1665                                 if (bp == pr->body_size) {
1666                                         prev_reduce = last_reduce;
1667                                         last_reduce = j;
1668                                         continue;
1669                                 }
1670                                 if (pr->body[bp]->type == Terminal)
1671                                         last_shift = j;
1672                         }
1673                         if (type == LR0 && last_reduce >= 0 && last_shift >= 0) {
1674                                 printf("  State %d has both SHIFT and REDUCE:\n", i);
1675                                 report_item(g, is->items.syms[last_shift]);
1676                                 report_item(g, is->items.syms[last_reduce]);
1677                                 cnt++;
1678                         }
1679                         if (prev_reduce >= 0) {
1680                                 printf("  State %d has 2 (or more) reducible items\n", i);
1681                                 report_item(g, is->items.syms[prev_reduce]);
1682                                 report_item(g, is->items.syms[last_reduce]);
1683                                 cnt++;
1684                         }
1685                 }
1686                 return cnt;
1687         }
1688
1689 SLR, LALR, and LR1 conflicts happen if two reducible items have over-lapping
1690 look ahead, or if a symbol in a look-ahead can be shifted.  They differ only
1691 in the source of the look ahead set.
1692
1693 We build two datasets to reflect the "action" table: one which maps
1694 terminals to items where that terminal could be shifted and another
1695 which maps terminals to items that could be reduced when the terminal
1696 is in look-ahead.  We report when we get conflicts between the two.
1697
1698         static int conflicts_slr(struct grammar *g, enum grammar_type type)
1699         {
1700                 int i;
1701                 int cnt = 0;
1702
1703                 for (i = 0; i < g->states; i++) {
1704                         struct itemset *is = g->statetab[i];
1705                         struct symset shifts = INIT_DATASET;
1706                         struct symset reduce = INIT_DATASET;
1707                         int j;
1708                         if (!is)
1709                                 continue;
1710                         /* First collect the shifts */
1711                         for (j = 0; j < is->items.cnt; j++) {
1712                                 unsigned short itm = is->items.syms[j];
1713                                 int p = item_prod(itm);
1714                                 int bp = item_index(itm);
1715                                 struct production *pr = g->productions[p];
1716
1717                                 if (bp < pr->body_size &&
1718                                     pr->body[bp]->type == Terminal) {
1719                                         /* shiftable */
1720                                         int sym = pr->body[bp]->num;
1721                                         if (symset_find(&shifts, sym) < 0)
1722                                                 symset_add(&shifts, sym, itm);
1723                                 }
1724                         }
1725                         /* Now look for reduction and conflicts */
1726                         for (j = 0; j < is->items.cnt; j++) {
1727                                 unsigned short itm = is->items.syms[j];
1728                                 int p = item_prod(itm);
1729                                 int bp = item_index(itm);
1730                                 struct production *pr = g->productions[p];
1731
1732                                 if (bp < pr->body_size)
1733                                         continue;
1734                                 /* reducible */
1735                                 struct symset la;
1736                                 if (type == SLR)
1737                                         la = g->follow[pr->head->num];
1738                                 else
1739                                         la = set_find(g, is->items.data[j]);
1740                                 int k;
1741                                 for (k = 0; k < la.cnt; k++) {
1742                                         int pos = symset_find(&shifts, la.syms[k]);
1743                                         if (pos >= 0) {
1744                                                 printf("  State %d has SHIFT/REDUCE conflict on ", i);
1745                                                 prtxt(g->symtab[la.syms[k]]->name);
1746                                                 printf(":\n");
1747                                                 report_item(g, shifts.data[pos]);
1748                                                 report_item(g, itm);
1749                                                 cnt++;
1750                                         }
1751                                         pos = symset_find(&reduce, la.syms[k]);
1752                                         if (pos < 0) {
1753                                                 symset_add(&reduce, la.syms[k], itm);
1754                                                 continue;
1755                                         }
1756                                         printf("  State %d has REDUCE/REDUCE conflict on ", i);
1757                                         prtxt(g->symtab[la.syms[k]]->name);
1758                                         printf(":\n");
1759                                         report_item(g, itm);
1760                                         report_item(g, reduce.data[pos]);
1761                                         cnt++;
1762                                 }
1763                         }
1764                         symset_free(shifts);
1765                         symset_free(reduce);
1766                 }
1767                 return cnt;
1768         }
1769
1770
1771 ## Generating the parser
1772
1773 The exported part of the parser is the `parse_XX` function, where the name
1774 `XX` is based on the name of the parser files.
1775
1776 This takes a `code_node`, a partially initialized `token_config`, and an
1777 optional `FILE` to send tracing to.  The `token_config` gets the list of
1778 known words added and then is used with the `code_node` to initialize the
1779 scanner.
1780
1781 `parse_XX` then calls the library function `parser_run` to actually complete
1782 the parse.  This needs the `states` table and function to call the various
1783 pieces of code provided in the grammar file, so they are generated first.
1784
1785 ###### parser_generate
1786
1787         static void gen_parser(FILE *f, struct grammar *g, char *file, char *name)
1788         {
1789                 gen_known(f, g);
1790                 gen_non_term(f, g);
1791                 gen_goto(f, g);
1792                 gen_states(f, g);
1793                 gen_reduce(f, g, file);
1794                 gen_free(f, g);
1795
1796                 fprintf(f, "#line 0 \"gen_parser\"\n");
1797                 fprintf(f, "void *parse_%s(struct code_node *code, struct token_config *config, FILE *trace)\n",
1798                         name);
1799                 fprintf(f, "{\n");
1800                 fprintf(f, "\tstruct token_state *tokens;\n");
1801                 fprintf(f, "\tconfig->words_marks = known;\n");
1802                 fprintf(f, "\tconfig->known_count = sizeof(known)/sizeof(known[0]);\n");
1803                 fprintf(f, "\tconfig->ignored |= (1 << TK_line_comment) | (1 << TK_block_comment);\n");
1804                 fprintf(f, "\ttokens = token_open(code, config);\n");
1805                 fprintf(f, "\tvoid *rv = parser_run(tokens, states, do_reduce, do_free, trace, non_term, config);\n");
1806                 fprintf(f, "\ttoken_close(tokens);\n");
1807                 fprintf(f, "\treturn rv;\n");
1808                 fprintf(f, "}\n\n");
1809         }
1810
1811 ### Known words table
1812
1813 The known words table is simply an array of terminal symbols.
1814 The table of nonterminals used for tracing is a similar array.
1815
1816 ###### functions
1817
1818         static void gen_known(FILE *f, struct grammar *g)
1819         {
1820                 int i;
1821                 fprintf(f, "#line 0 \"gen_known\"\n");
1822                 fprintf(f, "static const char *known[] = {\n");
1823                 for (i = TK_reserved;
1824                      i < g->num_syms && g->symtab[i]->type == Terminal;
1825                      i++)
1826                         fprintf(f, "\t\"%.*s\",\n", g->symtab[i]->name.len,
1827                                 g->symtab[i]->name.txt);
1828                 fprintf(f, "};\n\n");
1829         }
1830
1831         static void gen_non_term(FILE *f, struct grammar *g)
1832         {
1833                 int i;
1834                 fprintf(f, "#line 0 \"gen_non_term\"\n");
1835                 fprintf(f, "static const char *non_term[] = {\n");
1836                 for (i = TK_reserved;
1837                      i < g->num_syms;
1838                      i++)
1839                         if (g->symtab[i]->type == Nonterminal)
1840                                 fprintf(f, "\t\"%.*s\",\n", g->symtab[i]->name.len,
1841                                         g->symtab[i]->name.txt);
1842                 fprintf(f, "};\n\n");
1843         }
1844
1845 ### States and the goto tables.
1846
1847 For each state we record the goto table, the reducible production if
1848 there is one, or a symbol to shift for error recovery.
1849 Some of the details of the reducible production are stored in the
1850 `do_reduce` function to come later.  Here we store the production number,
1851 the body size (useful for stack management) and the resulting symbol (useful
1852 for knowing how to free data later).
1853
1854 The go to table is stored in a simple array of `sym` and corresponding
1855 `state`.
1856
1857 ###### exported types
1858
1859         struct lookup {
1860                 short sym;
1861                 short state;
1862         };
1863         struct state {
1864                 short go_to_cnt;
1865                 const struct lookup * go_to;
1866                 short reduce_prod;
1867                 short reduce_size;
1868                 short reduce_sym;
1869                 short shift_sym;
1870                 short starts_line;
1871         };
1872
1873
1874 ###### functions
1875
1876         static void gen_goto(FILE *f, struct grammar *g)
1877         {
1878                 int i;
1879                 fprintf(f, "#line 0 \"gen_goto\"\n");
1880                 for (i = 0; i < g->states; i++) {
1881                         int j;
1882                         fprintf(f, "static const struct lookup goto_%d[] = {\n",
1883                                 i);
1884                         struct symset gt = g->statetab[i]->go_to;
1885                         for (j = 0; j < gt.cnt; j++)
1886                                 fprintf(f, "\t{ %d, %d },\n",
1887                                         gt.syms[j], gt.data[j]);
1888                         fprintf(f, "};\n");
1889                 }
1890         }
1891
1892 ###### functions
1893
1894         static void gen_states(FILE *f, struct grammar *g)
1895         {
1896                 int i;
1897                 fprintf(f, "#line 0 \"gen_states\"\n");
1898                 fprintf(f, "static const struct state states[] = {\n");
1899                 for (i = 0; i < g->states; i++) {
1900                         struct itemset *is = g->statetab[i];
1901                         int j, prod = -1, prod_len;
1902                         int shift_sym = -1;
1903                         int shift_len = 0, shift_remain = 0;
1904                         for (j = 0; j < is->items.cnt; j++) {
1905                                 int itm = is->items.syms[j];
1906                                 int p = item_prod(itm);
1907                                 int bp = item_index(itm);
1908                                 struct production *pr = g->productions[p];
1909
1910                                 if (bp < pr->body_size) {
1911                                         if (shift_sym < 0 ||
1912                                             (shift_len == bp && shift_remain > pr->body_size - bp)) {
1913                                                 shift_sym = pr->body[bp]->num;
1914                                                 shift_len = bp;
1915                                                 shift_remain = pr->body_size - bp;
1916                                         }
1917                                         continue;
1918                                 }
1919                                 /* This is what we reduce */
1920                                 if (prod < 0 || prod_len < pr->body_size) {
1921                                         prod = p;
1922                                         prod_len = pr->body_size;
1923                                 }
1924                         }
1925
1926                         if (prod >= 0)
1927                                 fprintf(f, "\t[%d] = { %d, goto_%d, %d, %d, %d, 0, %d },\n",
1928                                         i, is->go_to.cnt, i, prod,
1929                                         g->productions[prod]->body_size,
1930                                         g->productions[prod]->head->num,
1931                                         is->starts_line);
1932                         else
1933                                 fprintf(f, "\t[%d] = { %d, goto_%d, -1, -1, -1, %d, %d },\n",
1934                                         i, is->go_to.cnt, i, shift_sym,
1935                                         is->starts_line);
1936                 }
1937                 fprintf(f, "};\n\n");
1938         }
1939
1940 ### The `do_reduce` function and the code
1941
1942 When the parser engine decides to reduce a production, it calls `do_reduce`.
1943 This has two functions.
1944
1945 Firstly, if a non-NULL `trace` file is passed, it prints out details of the
1946 production being reduced.  Secondly it runs the code that was included with
1947 the production if any.
1948
1949 This code needs to be able to store data somewhere.  Rather than requiring
1950 `do_reduce` to `malloc` that "somewhere", we pass in a large buffer and have
1951 `do_reduce` return the size to be saved.
1952
1953 In order for the code to access "global" context, we pass in the
1954 "config" pointer that was passed to parser function.  If the `struct
1955 token_config` is embedded in some larger structure, the reducing code
1956 can access the larger structure using pointer manipulation.
1957
1958 The code fragment requires translation when written out.  Any `$N` needs to
1959 be converted to a reference either to that buffer (if `$0`) or to the
1960 structure returned by a previous reduction.  These pointers need to be cast
1961 to the appropriate type for each access.  All this is handling in
1962 `gen_code`.
1963
1964 `gen_code` also allows symbol references to contain a '`<`' as in '`$<2`'.
1965 This applied only to symbols with references (or pointers), not those with structures.
1966 The `<` implies that the reference it being moved out, so the object will not be
1967 automatically freed.  This is equivalent to assigning `NULL` to the pointer.
1968
1969 ###### functions
1970
1971         static void gen_code(struct production *p, FILE *f, struct grammar *g)
1972         {
1973                 char *c;
1974                 char *used = calloc(1, p->body_size);
1975                 int i;
1976
1977                 fprintf(f, "\t\t\t");
1978                 for (c = p->code.txt; c < p->code.txt + p->code.len; c++) {
1979                         int n;
1980                         int use = 0;
1981                         if (*c != '$') {
1982                                 fputc(*c, f);
1983                                 if (*c == '\n')
1984                                         fputs("\t\t\t", f);
1985                                 continue;
1986                         }
1987                         c++;
1988                         if (*c == '<') {
1989                                 use = 1;
1990                                 c++;
1991                         }
1992                         if (*c < '0' || *c > '9') {
1993                                 if (use)
1994                                         fputc('<', f);
1995                                 fputc(*c, f);
1996                                 continue;
1997                         }
1998                         n = *c - '0';
1999                         while (c[1] >= '0' && c[1] <= '9') {
2000                                 c += 1;
2001                                 n = n * 10 + *c - '0';
2002                         }
2003                         if (n == 0)
2004                                 fprintf(f, "(*(struct %.*s*%s)ret)",
2005                                         p->head->struct_name.len,
2006                                         p->head->struct_name.txt,
2007                                         p->head->isref ? "*":"");
2008                         else if (n > p->body_size)
2009                                 fprintf(f, "$%d", n);
2010                         else if (p->body[n-1]->type == Terminal)
2011                                 fprintf(f, "(*(struct token *)body[%d])",
2012                                         n-1);
2013                         else if (p->body[n-1]->struct_name.txt == NULL)
2014                                 fprintf(f, "$%d", n);
2015                         else {
2016                                 fprintf(f, "(*(struct %.*s*%s)body[%d])",
2017                                         p->body[n-1]->struct_name.len,
2018                                         p->body[n-1]->struct_name.txt,
2019                                         p->body[n-1]->isref ? "*":"", n-1);
2020                                 used[n-1] = use;
2021                         }
2022                 }
2023                 fputs("\n", f);
2024                 for (i = 0; i < p->body_size; i++) {
2025                         if (p->body[i]->struct_name.txt &&
2026                             p->body[i]->isref &&
2027                             used[i])
2028                                 // assume this has been copied out
2029                                 fprintf(f, "\t\t*(void**)body[%d] = NULL;\n", i);
2030                 }
2031                 free(used);
2032         }
2033
2034 ###### functions
2035
2036         static void gen_reduce(FILE *f, struct grammar *g, char *file)
2037         {
2038                 int i;
2039                 fprintf(f, "#line 0 \"gen_reduce\"\n");
2040                 fprintf(f, "static int do_reduce(int prod, void **body, struct token_config *config, void *ret)\n");
2041                 fprintf(f, "{\n");
2042                 fprintf(f, "\tint ret_size = 0;\n");
2043
2044                 fprintf(f, "\tswitch(prod) {\n");
2045                 for (i = 0; i < g->production_count; i++) {
2046                         struct production *p = g->productions[i];
2047                         fprintf(f, "\tcase %d:\n", i);
2048
2049                         if (p->code.txt)
2050                                 gen_code(p, f, g);
2051
2052                         if (p->head->struct_name.txt)
2053                                 fprintf(f, "\t\tret_size = sizeof(struct %.*s%s);\n",
2054                                         p->head->struct_name.len,
2055                                         p->head->struct_name.txt,
2056                                         p->head->isref ? "*":"");
2057
2058                         fprintf(f, "\t\tbreak;\n");
2059                 }
2060                 fprintf(f, "\t}\n\treturn ret_size;\n}\n\n");
2061         }
2062
2063 ### `do_free`
2064
2065 As each non-terminal can potentially cause a different type of data
2066 structure to be allocated and filled in, we need to be able to free it when
2067 done.
2068
2069 It is particularly important to have fine control over freeing during error
2070 recovery where individual stack frames might need to be freed.
2071
2072 For this, the grammar author is required to defined a `free_XX` function for
2073 each structure that is used by a non-terminal.  `do_free` will call whichever
2074 is appropriate given a symbol number, and will call `free` (as is
2075 appropriate for tokens on any terminal symbol.
2076
2077 ###### functions
2078
2079         static void gen_free(FILE *f, struct grammar *g)
2080         {
2081                 int i;
2082
2083                 fprintf(f, "#line 0 \"gen_free\"\n");
2084                 fprintf(f, "static void do_free(short sym, void *asn)\n");
2085                 fprintf(f, "{\n");
2086                 fprintf(f, "\tif (!asn) return;\n");
2087                 fprintf(f, "\tif (sym < %d) {\n", g->first_nonterm);
2088                 fprintf(f, "\t\tfree(asn);\n\t\treturn;\n\t}\n");
2089                 fprintf(f, "\tswitch(sym) {\n");
2090
2091                 for (i = 0; i < g->num_syms; i++) {
2092                         struct symbol *s = g->symtab[i];
2093                         if (!s ||
2094                             s->type != Nonterminal ||
2095                             s->struct_name.txt == NULL)
2096                                 continue;
2097
2098                         fprintf(f, "\tcase %d:\n", s->num);
2099                         if (s->isref) {
2100                                 fprintf(f, "\t\tfree_%.*s(*(void**)asn);\n",
2101                                         s->struct_name.len,
2102                                         s->struct_name.txt);
2103                                 fprintf(f, "\t\tfree(asn);\n");
2104                         } else
2105                                 fprintf(f, "\t\tfree_%.*s(asn);\n",
2106                                         s->struct_name.len,
2107                                         s->struct_name.txt);
2108                         fprintf(f, "\t\tbreak;\n");
2109                 }
2110                 fprintf(f, "\t}\n}\n\n");
2111         }
2112
2113 ## The main routine.
2114
2115 There are three key parts to the "main" function of parsergen: processing
2116 the arguments, loading the grammar file, and dealing with the grammar.
2117
2118 ### Argument processing.
2119
2120 Command line options allow the selection of analysis mode, name of output
2121 file, and whether or not a report should be generated.  By default we create
2122 a report only if no code output was requested.
2123
2124 The `parse_XX` function name uses the basename of the output file which
2125 should not have a suffix (`.c`).  `.c` is added to the given name for the
2126 code, and `.h` is added for the header (if header text is specifed in the
2127 grammar file).
2128
2129 ###### includes
2130         #include <getopt.h>
2131
2132 ###### declarations
2133         static const struct option long_options[] = {
2134                 { "LR0",        0, NULL, '0' },
2135                 { "LR05",       0, NULL, '5' },
2136                 { "SLR",        0, NULL, 'S' },
2137                 { "LALR",       0, NULL, 'L' },
2138                 { "LR1",        0, NULL, '1' },
2139                 { "tag",        1, NULL, 't' },
2140                 { "report",     0, NULL, 'R' },
2141                 { "output",     1, NULL, 'o' },
2142                 { NULL,         0, NULL, 0   }
2143         };
2144         const char *options = "05SL1t:Ro:";
2145
2146 ###### process arguments
2147         int opt;
2148         char *outfile = NULL;
2149         char *infile;
2150         char *name;
2151         char *tag = NULL;
2152         int report = 1;
2153         enum grammar_type type = LR05;
2154         while ((opt = getopt_long(argc, argv, options,
2155                                   long_options, NULL)) != -1) {
2156                 switch(opt) {
2157                 case '0':
2158                         type = LR0; break;
2159                 case '5':
2160                         type = LR05; break;
2161                 case 'S':
2162                         type = SLR; break;
2163                 case 'L':
2164                         type = LALR; break;
2165                 case '1':
2166                         type = LR1; break;
2167                 case 'R':
2168                         report = 2; break;
2169                 case 'o':
2170                         outfile = optarg; break;
2171                 case 't':
2172                         tag = optarg; break;
2173                 default:
2174                         fprintf(stderr, "Usage: parsergen ...\n");
2175                         exit(1);
2176                 }
2177         }
2178         if (optind < argc)
2179                 infile = argv[optind++];
2180         else {
2181                 fprintf(stderr, "No input file given\n");
2182                 exit(1);
2183         }
2184         if (outfile && report == 1)
2185                 report = 0;
2186         name = outfile;
2187         if (name && strchr(name, '/'))
2188                 name = strrchr(name, '/')+1;
2189
2190         if (optind < argc) {
2191                 fprintf(stderr, "Excess command line arguments\n");
2192                 exit(1);
2193         }
2194
2195 ### Loading the grammar file
2196
2197 To be able to run `mdcode` and `scanner` on the grammar we need to memory
2198 map it.
2199
2200 One we have extracted the code (with `mdcode`) we expect to find three
2201 sections: header, code, and grammar.  Anything else that is not
2202 excluded by the `--tag` option is an error.
2203
2204 "header" and "code" are optional, though it is hard to build a working
2205 parser with neither. "grammar" must be provided.
2206
2207 ###### includes
2208         #include <fcntl.h>
2209         #include <sys/mman.h>
2210         #include <errno.h>
2211
2212 ###### functions
2213         static int errs;
2214         static void pr_err(char *msg)
2215         {
2216                 errs++;
2217                 fprintf(stderr, "%s\n", msg);
2218         }
2219
2220 ###### load file
2221         struct section *table;
2222         int fd;
2223         int len;
2224         char *file;
2225         fd = open(infile, O_RDONLY);
2226         if (fd < 0) {
2227                 fprintf(stderr, "parsergen: cannot open %s: %s\n",
2228                         infile, strerror(errno));
2229                 exit(1);
2230         }
2231         len = lseek(fd, 0, 2);
2232         file = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
2233         table = code_extract(file, file+len, pr_err);
2234
2235         struct code_node *hdr = NULL;
2236         struct code_node *code = NULL;
2237         struct code_node *gram = NULL;
2238         for (s = table; s; s = s->next) {
2239                 struct text sec = s->section;
2240                 if (tag && !strip_tag(&sec, tag))
2241                         continue;
2242                 if (text_is(sec, "header"))
2243                         hdr = s->code;
2244                 else if (text_is(sec, "code"))
2245                         code = s->code;
2246                 else if (text_is(sec, "grammar"))
2247                         gram = s->code;
2248                 else {
2249                         fprintf(stderr, "Unknown content section: %.*s\n",
2250                                 s->section.len, s->section.txt);
2251                         rv |= 2;
2252                 }
2253         }
2254
2255 ### Processing the input
2256
2257 As we need to append an extention to a filename and then open it for
2258 writing, and we need to do this twice, it helps to have a separate function.
2259
2260 ###### functions
2261
2262         static FILE *open_ext(char *base, char *ext)
2263         {
2264                 char *fn = malloc(strlen(base) + strlen(ext) + 1);
2265                 FILE *f;
2266                 strcat(strcpy(fn, base), ext);
2267                 f = fopen(fn, "w");
2268                 free(fn);
2269                 return f;
2270         }
2271
2272 If we can read the grammar, then we analyse and optionally report on it.  If
2273 the report finds conflicts we will exit with an error status.
2274
2275 ###### process input
2276         struct grammar *g = NULL;
2277         if (gram == NULL) {
2278                 fprintf(stderr, "No grammar section provided\n");
2279                 rv |= 2;
2280         } else {
2281                 g = grammar_read(gram);
2282                 if (!g) {
2283                         fprintf(stderr, "Failure to parse grammar\n");
2284                         rv |= 2;
2285                 }
2286         }
2287         if (g) {
2288                 grammar_analyse(g, type);
2289                 if (report)
2290                         if (grammar_report(g, type))
2291                                 rv |= 1;
2292         }
2293
2294 If a headers section is defined, we write it out and include a declaration
2295 for the `parse_XX` function so it can be used from separate code.
2296
2297         if (rv == 0 && hdr && outfile) {
2298                 FILE *f = open_ext(outfile, ".h");
2299                 if (f) {
2300                         code_node_print(f, hdr, infile);
2301                         fprintf(f, "void *parse_%s(struct code_node *code, struct token_config *config, FILE *trace);\n",
2302                                 name);
2303                         fclose(f);
2304                 } else {
2305                         fprintf(stderr, "Cannot create %s.h\n",
2306                                 outfile);
2307                         rv |= 4;
2308                 }
2309         }
2310
2311 And if all goes well and an output file was provided, we create the `.c`
2312 file with the code section (if any) and the parser tables and function.
2313
2314         if (rv == 0 && outfile) {
2315                 FILE *f = open_ext(outfile, ".c");
2316                 if (f) {
2317                         if (code)
2318                                 code_node_print(f, code, infile);
2319                         gen_parser(f, g, infile, name);
2320                         fclose(f);
2321                 } else {
2322                         fprintf(stderr, "Cannot create %s.c\n",
2323                                 outfile);
2324                         rv |= 4;
2325                 }
2326         }
2327
2328 And that about wraps it up.  We need to set the locale so that UTF-8 is
2329 recognised properly, and link with `libicuuc` as `libmdcode` requires that.
2330
2331 ###### File: parsergen.mk
2332         parsergen : parsergen.o libscanner.o libmdcode.o
2333                 $(CC) $(CFLAGS) -o parsergen parsergen.o libscanner.o libmdcode.o -licuuc
2334
2335 ###### includes
2336         #include <locale.h>
2337
2338 ###### main
2339
2340         int main(int argc, char *argv[])
2341         {
2342                 struct section *s;
2343                 int rv = 0;
2344
2345                 setlocale(LC_ALL,"");
2346
2347                 ## process arguments
2348                 ## load file
2349                 ## process input
2350
2351                 return rv;
2352         }
2353
2354 ## The SHIFT/REDUCE parser
2355
2356 Having analysed the grammar and generated all the tables, we only need the
2357 shift/reduce engine to bring it all together.
2358
2359 ### Goto table lookup
2360
2361 The parser generator has nicely provided us with goto tables sorted by
2362 symbol number.  We need a binary search function to find a symbol in the
2363 table.
2364
2365 ###### parser functions
2366
2367         static int search(const struct state *l, int sym)
2368         {
2369                 int lo = 0;
2370                 int hi = l->go_to_cnt;
2371
2372                 if (hi == 0)
2373                         return -1;
2374                 while (lo + 1 < hi) {
2375                         int mid = (lo + hi) / 2;
2376                         if (l->go_to[mid].sym <= sym)
2377                                 lo = mid;
2378                         else
2379                                 hi = mid;
2380                 }
2381                 if (l->go_to[lo].sym == sym)
2382                         return l->go_to[lo].state;
2383                 else
2384                         return -1;
2385         }
2386
2387 ### The state stack.
2388
2389 The core data structure for the parser is the stack.  This tracks all the
2390 symbols that have been recognised or partially recognised.
2391
2392 The stack usually won't grow very large - maybe a few tens of entries.  So
2393 we dynamically resize and array as required but never bother to shrink it
2394 down again.
2395
2396 We keep the stack as two separate allocations.  One, `asn_stack` stores the
2397 "abstract syntax nodes" which are created by each reduction.  When we call
2398 `do_reduce` we need to pass an array of the `asn`s of the body of the
2399 production, and by keeping a separate `asn` stack, we can just pass a
2400 pointer into this stack.
2401
2402 The other allocation stores all other stack fields of which there are six.
2403 The `state` is the most important one and guides the parsing process.  The
2404 `sym` is nearly unnecessary.  However when we want to free entries from the
2405 `asn_stack`, it helps to know what type they are so we can call the right
2406 freeing function.  The symbol leads us to the right free function through
2407 `do_free`.
2408
2409 The `indents` count and the `starts_indented` flag track the line
2410 indents in the symbol.  These are used to allow indent information to
2411 guide parsing and error recovery.
2412
2413 `newline_permitted` keeps track of whether newlines should be ignored
2414 or not, and `starts_line` records if this state stated on a newline.
2415
2416 As well as the stack of frames we have a `next` frame which is
2417 assembled from the incoming token and other information prior to
2418 pushing it onto the stack.
2419
2420 ###### parser functions
2421
2422         struct parser {
2423                 struct frame {
2424                         short state;
2425                         short sym;
2426                         short starts_indented;
2427                         short indents;
2428                         short newline_permitted;
2429                 } *stack, next;
2430                 void **asn_stack;
2431                 int stack_size;
2432                 int tos;
2433         };
2434
2435 #### Shift and pop
2436
2437 Two operations are needed on the stack - shift (which is like push) and pop.
2438
2439 Shift applies not only to terminals but also to non-terminals.  When we
2440 reduce a production we will pop off entries corresponding to the body
2441 symbols, then push on an item for the head of the production.  This last is
2442 exactly the same process as shifting in a terminal so we use the same
2443 function for both.
2444
2445 To simplify other code we arrange for `shift` to fail if there is no `goto`
2446 state for the symbol.  This is useful in basic parsing due to our design
2447 that we shift when we can, and reduce when we cannot.  So the `shift`
2448 function reports if it could.
2449
2450 So `shift` finds the next state.  If that succeed it extends the allocations
2451 if needed and pushes all the information onto the stacks.
2452
2453 ###### parser functions
2454
2455         static int shift(struct parser *p,
2456                          void *asn,
2457                          const struct state states[])
2458         {
2459                 // Push an entry onto the stack
2460                 int newstate = search(&states[p->next.state], p->next.sym);
2461                 if (newstate < 0)
2462                         return 0;
2463                 if (p->tos >= p->stack_size) {
2464                         p->stack_size += 10;
2465                         p->stack = realloc(p->stack, p->stack_size
2466                                            * sizeof(p->stack[0]));
2467                         p->asn_stack = realloc(p->asn_stack, p->stack_size
2468                                            * sizeof(p->asn_stack[0]));
2469                 }
2470                 p->stack[p->tos] = p->next;
2471                 p->asn_stack[p->tos] = asn;
2472                 p->tos++;
2473                 p->next.state = newstate;
2474                 p->next.indents = 0;
2475                 p->next.starts_indented = 0;
2476                 // if new state doesn't start a line, we inherit newline_permitted status
2477                 if (states[newstate].starts_line)
2478                         p->next.newline_permitted = 1;
2479                 return 1;
2480         }
2481
2482 `pop` simply moves the top of stack (`tos`) back down the required amount
2483 and frees any `asn` entries that need to be freed.  It is called _after_ we
2484 reduce a production, just before we `shift` the nonterminal in.
2485
2486 ###### parser functions
2487
2488         static void pop(struct parser *p, int num,
2489                         void(*do_free)(short sym, void *asn))
2490         {
2491                 int i;
2492                 p->tos -= num;
2493                 for (i = 0; i < num; i++) {
2494                         p->next.indents += p->stack[p->tos+i].indents;
2495                         do_free(p->stack[p->tos+i].sym,
2496                                 p->asn_stack[p->tos+i]);
2497                 }
2498
2499                 if (num) {
2500                         p->next.state = p->stack[p->tos].state;
2501                         p->next.starts_indented = p->stack[p->tos].starts_indented;
2502                         p->next.newline_permitted = p->stack[p->tos].newline_permitted;
2503                         if (p->next.indents > p->next.starts_indented)
2504                                 p->next.newline_permitted = 0;
2505                 }
2506         }
2507
2508 ### Memory allocation
2509
2510 The `scanner` returns tokens in a local variable - we want them in allocated
2511 memory so they can live in the `asn_stack`.  Similarly the `asn` produced by
2512 a reduce is in a large buffer.  Both of these require some allocation and
2513 copying, hence `memdup` and `tokcopy`.
2514
2515 ###### parser includes
2516         #include <memory.h>
2517
2518 ###### parser functions
2519
2520         void *memdup(void *m, int len)
2521         {
2522                 void *ret;
2523                 if (len == 0)
2524                         return NULL;
2525                 ret = malloc(len);
2526                 memcpy(ret, m, len);
2527                 return ret;
2528         }
2529
2530         static struct token *tok_copy(struct token tk)
2531         {
2532                 struct token *new = malloc(sizeof(*new));
2533                 *new = tk;
2534                 return new;
2535         }
2536
2537 ### The heart of the parser.
2538
2539 Now we have the parser.  If we can shift, we do.  If not and we can reduce
2540 we do.  If the production we reduced was production zero, then we have
2541 accepted the input and can finish.
2542
2543 We return whatever `asn` was returned by reducing production zero.
2544
2545 If we can neither shift nor reduce we have an error to handle.  We pop
2546 single entries off the stack until we can shift the `TK_error` symbol, then
2547 drop input tokens until we find one we can shift into the new error state.
2548
2549 When we find `TK_in` and `TK_out` tokens which report indents we need
2550 to handle them directly as the grammar cannot express what we want to
2551 do with them.
2552
2553 `TK_in` tokens are easy: we simply update the `next` stack frame to
2554 record how many indents there are and that the next token started with
2555 an indent.
2556
2557 `TK_out` tokens must either be counted off against any pending indent,
2558 or must force reductions until there is a pending indent which isn't
2559 at the start of a production.
2560
2561 `TK_newline` tokens are ignored precisely if there has been an indent
2562 since the last state which could have been at the start of a line.
2563
2564 ###### parser includes
2565         #include "parser.h"
2566 ###### parser_run
2567         void *parser_run(struct token_state *tokens,
2568                          const struct state states[],
2569                          int (*do_reduce)(int, void**, struct token_config*, void*),
2570                          void (*do_free)(short, void*),
2571                          FILE *trace, const char *non_term[],
2572                          struct token_config *config)
2573         {
2574                 struct parser p = { 0 };
2575                 struct token *tk = NULL;
2576                 int accepted = 0;
2577                 void *ret;
2578
2579                 p.next.newline_permitted = states[0].starts_line;
2580                 while (!accepted) {
2581                         struct token *err_tk;
2582                         if (!tk)
2583                                 tk = tok_copy(token_next(tokens));
2584                         p.next.sym = tk->num;
2585                         if (trace)
2586                                 parser_trace(trace, &p, tk, states, non_term, config->known_count);
2587
2588                         if (p.next.sym == TK_in) {
2589                                 p.next.starts_indented = 1;
2590                                 p.next.indents = 1;
2591                                 free(tk);
2592                                 tk = NULL;
2593                                 continue;
2594                         }
2595                         if (p.next.sym == TK_out) {
2596                                 if (p.stack[p.tos-1].indents > p.stack[p.tos-1].starts_indented ||
2597                                     (p.stack[p.tos-1].indents == 1 &&
2598                                      states[p.next.state].reduce_size > 1)) {
2599                                         p.stack[p.tos-1].indents -= 1;
2600                                         if (p.stack[p.tos-1].indents == p.stack[p.tos-1].starts_indented) {
2601                                                 // no internal indent any more, reassess 'newline_permitted'
2602                                                 if (states[p.stack[p.tos-1].state].starts_line)
2603                                                         p.stack[p.tos-1].newline_permitted = 1;
2604                                                 else if (p.tos > 1)
2605                                                         p.stack[p.tos-1].newline_permitted = p.stack[p.tos-2].newline_permitted;
2606                                         }
2607                                         free(tk);
2608                                         tk = NULL;
2609                                         continue;
2610                                 }
2611                                 // fall through and force a REDUCE (as 'shift'
2612                                 // will fail).
2613                         }
2614                         if (p.next.sym == TK_newline) {
2615                                 if (!p.tos || ! p.stack[p.tos-1].newline_permitted) {
2616                                         free(tk);
2617                                         tk = NULL;
2618                                         continue;
2619                                 }
2620                         }
2621                         if (shift(&p, tk, states)) {
2622                                 tk = NULL;
2623                                 continue;
2624                         }
2625                         if (states[p.next.state].reduce_prod >= 0) {
2626                                 void **body;
2627                                 int prod = states[p.next.state].reduce_prod;
2628                                 int size = states[p.next.state].reduce_size;
2629                                 int bufsize;
2630                                 static char buf[16*1024];
2631                                 p.next.sym = states[p.next.state].reduce_sym;
2632
2633                                 body = p.asn_stack +
2634                                         (p.tos - states[p.next.state].reduce_size);
2635
2636                                 bufsize = do_reduce(prod, body, config, buf);
2637
2638                                 pop(&p, size, do_free);
2639                                 shift(&p, memdup(buf, bufsize), states);
2640                                 if (prod == 0)
2641                                         accepted = 1;
2642                                 continue;
2643                         }
2644                         if (tk->num == TK_out) {
2645                                 // Indent problem - synthesise tokens to get us
2646                                 // out of here.
2647                                 fprintf(stderr, "Synthesize %d to handle indent problem\n", states[p.next.state].shift_sym);
2648                                 p.next.sym = states[p.next.state].shift_sym;
2649                                 shift(&p, tok_copy(*tk), states);
2650                                 // FIXME need to report this error somehow
2651                                 continue;
2652                         }
2653                         /* Error. We walk up the stack until we
2654                          * find a state which will accept TK_error.
2655                          * We then shift in TK_error and see what state
2656                          * that takes us too.
2657                          * Then we discard input tokens until
2658                          * we find one that is acceptable.
2659                          */
2660
2661                         err_tk = tok_copy(*tk);
2662                         p.next.sym = TK_error;
2663                         while (shift(&p, err_tk, states) == 0
2664                                && p.tos > 0)
2665                                 // discard this state
2666                                 pop(&p, 1, do_free);
2667                         if (p.tos == 0) {
2668                                 free(err_tk);
2669                                 // no state accepted TK_error
2670                                 break;
2671                         }
2672                         while (search(&states[p.next.state], tk->num) < 0 &&
2673                                tk->num != TK_eof) {
2674                                 free(tk);
2675                                 tk = tok_copy(token_next(tokens));
2676                                 if (tk->num == TK_in)
2677                                         p.next.indents += 1;
2678                                 if (tk->num == TK_out) {
2679                                         if (p.next.indents == 0)
2680                                                 break;
2681                                         p.next.indents -= 1;
2682                                 }
2683                         }
2684                         if (p.tos == 0 && tk->num == TK_eof)
2685                                 break;
2686                 }
2687                 free(tk);
2688                 if (accepted)
2689                         ret = p.asn_stack[0];
2690                 else
2691                         pop(&p, p.tos, do_free);
2692                 free(p.asn_stack);
2693                 free(p.stack);
2694                 return ret;
2695         }
2696
2697 ###### exported functions
2698         void *parser_run(struct token_state *tokens,
2699                          const struct state states[],
2700                          int (*do_reduce)(int, void**, struct token_config*, void*),
2701                          void (*do_free)(short, void*),
2702                          FILE *trace, const char *non_term[],
2703                          struct token_config *config);
2704
2705 ### Tracing
2706
2707 Being able to visualize the parser in action can be invaluable when
2708 debugging the parser code, or trying to understand how the parse of a
2709 particular grammar progresses.  The stack contains all the important
2710 state, so just printing out the stack every time around the parse loop
2711 can make it possible to see exactly what is happening.
2712
2713 This doesn't explicitly show each SHIFT and REDUCE action.  However they
2714 are easily deduced from the change between consecutive lines, and the
2715 details of each state can be found by cross referencing the states list
2716 in the stack with the "report" that parsergen can generate.
2717
2718 For terminal symbols, we just dump the token.  For non-terminals we
2719 print the name of the symbol.  The look ahead token is reported at the
2720 end inside square brackets.
2721
2722 ###### parser functions
2723
2724         static char *reserved_words[] = {
2725                 [TK_error]        = "ERROR",
2726                 [TK_in]           = "IN",
2727                 [TK_out]          = "OUT",
2728                 [TK_newline]      = "NEWLINE",
2729                 [TK_eof]          = "$eof",
2730         };
2731         static void parser_trace_state(FILE *trace, struct frame *f, const struct state states[])
2732         {
2733                 fprintf(trace, "(%d", f->state);
2734                 if (f->indents)
2735                         fprintf(trace, "%c%d", f->starts_indented?':':'.',
2736                                 f->indents);
2737                 if (states[f->state].starts_line)
2738                         fprintf(trace, "s");
2739                 if (f->newline_permitted)
2740                         fprintf(trace, "n");
2741                 fprintf(trace, ") ");
2742         }
2743
2744         void parser_trace(FILE *trace, struct parser *p,
2745                           struct token *tk, const struct state states[],
2746                           const char *non_term[], int knowns)
2747         {
2748                 int i;
2749                 for (i = 0; i < p->tos; i++) {
2750                         int sym = p->stack[i].sym;
2751                         parser_trace_state(trace, &p->stack[i], states);
2752                         if (sym < TK_reserved &&
2753                             reserved_words[sym] != NULL)
2754                                 fputs(reserved_words[sym], trace);
2755                         else if (sym < TK_reserved + knowns) {
2756                                 struct token *t = p->asn_stack[i];
2757                                 text_dump(trace, t->txt, 20);
2758                         } else
2759                                 fputs(non_term[sym - TK_reserved - knowns],
2760                                       trace);
2761                         fputs(" ", trace);
2762                 }
2763                 parser_trace_state(trace, &p->next, states);
2764                 fprintf(trace, " [");
2765                 if (tk->num < TK_reserved &&
2766                     reserved_words[tk->num] != NULL)
2767                         fputs(reserved_words[tk->num], trace);
2768                 else
2769                         text_dump(trace, tk->txt, 20);
2770                 fputs("]\n", trace);
2771         }
2772
2773 # A Worked Example
2774
2775 The obvious example for a parser is a calculator.
2776
2777 As `scanner` provides number parsing function using `libgmp` is it not much
2778 work to perform arbitrary rational number calculations.
2779
2780 This calculator takes one expression, or an equality test per line.  The
2781 results are printed and if any equality test fails, the program exits with
2782 an error.
2783
2784 ###### File: parsergen.mk
2785         calc.c calc.h : parsergen parsergen.mdc
2786                 ./parsergen --tag calc -o calc parsergen.mdc
2787         calc : calc.o libparser.o libscanner.o libmdcode.o libnumber.o
2788                 $(CC) $(CFLAGS) -o calc calc.o libparser.o libscanner.o libmdcode.o libnumber.o -licuuc -lgmp
2789
2790 # calc: header
2791
2792         #include "number.h"
2793         // what do we use for a demo-grammar?  A calculator of course.
2794         struct number {
2795                 mpq_t val;
2796                 char tail[2];
2797                 int err;
2798         };
2799
2800 # calc: code
2801
2802         #include <stdlib.h>
2803         #include <unistd.h>
2804         #include <fcntl.h>
2805         #include <sys/mman.h>
2806         #include <stdio.h>
2807         #include <malloc.h>
2808         #include <gmp.h>
2809         #include "mdcode.h"
2810         #include "scanner.h"
2811         #include "number.h"
2812         #include "parser.h"
2813
2814         #include "calc.h"
2815
2816         static void free_number(struct number *n)
2817         {
2818                 mpq_clear(n->val);
2819                 free(n);
2820         }
2821
2822         int main(int argc, char *argv[])
2823         {
2824                 int fd = open(argv[1], O_RDONLY);
2825                 int len = lseek(fd, 0, 2);
2826                 char *file = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
2827                 struct section *s = code_extract(file, file+len, NULL);
2828                 struct token_config config = {
2829                         .ignored = (1 << TK_line_comment)
2830                                  | (1 << TK_block_comment)
2831                                  | (1 << TK_in)
2832                                  | (1 << TK_out),
2833                         .number_chars = ".,_+-",
2834                         .word_start = "",
2835                         .word_cont = "",
2836                 };
2837                 parse_calc(s->code, &config, argc > 2 ? stderr : NULL);
2838                 while (s) {
2839                         struct section *t = s->next;
2840                         code_free(s->code);
2841                         free(s);
2842                         s = t;
2843                 }
2844                 exit(0);
2845         }
2846
2847 # calc: grammar
2848
2849         Session -> Session Line
2850                 | Line
2851
2852         Line -> Expression NEWLINE ${ gmp_printf("Answer = %Qd\n", $1.val);
2853                                         { mpf_t fl; mpf_init2(fl, 20); mpf_set_q(fl, $1.val);
2854                                         gmp_printf("  or as a decimal: %Fg\n", fl);
2855                                         mpf_clear(fl);
2856                                         }
2857                                      }$
2858                 | Expression = Expression NEWLINE ${
2859                         if (mpq_equal($1.val, $3.val))
2860                                 gmp_printf("Both equal %Qd\n", $1.val);
2861                         else {
2862                                 gmp_printf("NOT EQUAL: %Qd\n      != : %Qd\n",
2863                                         $1.val, $3.val);
2864                                 exit(1);
2865                         }
2866                 }$
2867                 | NEWLINE ${ printf("Blank line\n"); }$
2868                 | ERROR NEWLINE ${ printf("Skipped a bad line\n"); }$
2869
2870         $number
2871         Expression -> Expression + Term ${ mpq_init($0.val); mpq_add($0.val, $1.val, $3.val); }$
2872                 | Expression - Term ${ mpq_init($0.val); mpq_sub($0.val, $1.val, $3.val); }$
2873                 | Term ${ mpq_init($0.val); mpq_set($0.val, $1.val); }$
2874
2875         Term -> Term * Factor ${ mpq_init($0.val); mpq_mul($0.val, $1.val, $3.val); }$
2876                 | Term / Factor ${ mpq_init($0.val); mpq_div($0.val, $1.val, $3.val); }$
2877                 | Factor ${ mpq_init($0.val); mpq_set($0.val, $1.val); }$
2878
2879         Factor -> NUMBER ${ if (number_parse($0.val, $0.tail, $1.txt) == 0) mpq_init($0.val); }$
2880                 | ( Expression ) ${ mpq_init($0.val); mpq_set($0.val, $2.val); }$