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