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