]> ocean-lang.org Git - ocean/blob - csrc/oceani.mdc
oceani: move ->prepare_type call (back) into val_alloc()
[ocean] / csrc / oceani.mdc
1 # Ocean Interpreter - Jamison Creek version
2
3 Ocean is intended to be a compiled language, so this interpreter is
4 not targeted at being the final product.  It is, rather, an intermediate
5 stage and fills that role in two distinct ways.
6
7 Firstly, it exists as a platform to experiment with the early language
8 design.  An interpreter is easy to write and easy to get working, so
9 the barrier for entry is lower if I aim to start with an interpreter.
10
11 Secondly, the plan for the Ocean compiler is to write it in the
12 [Ocean language](http://ocean-lang.org).  To achieve this we naturally
13 need some sort of boot-strap process and this interpreter - written in
14 portable C - will fill that role.  It will be used to bootstrap the
15 Ocean compiler.
16
17 Two features that are not needed to fill either of these roles are
18 performance and completeness.  The interpreter only needs to be fast
19 enough to run small test programs and occasionally to run the compiler
20 on itself.  It only needs to be complete enough to test aspects of the
21 design which are developed before the compiler is working, and to run
22 the compiler on itself.  Any features not used by the compiler when
23 compiling itself are superfluous.  They may be included anyway, but
24 they may not.
25
26 Nonetheless, the interpreter should end up being reasonably complete,
27 and any performance bottlenecks which appear and are easily fixed, will
28 be.
29
30 ## Current version
31
32 This third version of the interpreter exists to test out some initial
33 ideas relating to types.  Particularly it adds arrays (indexed from
34 zero) and simple structures.  Basic control flow and variable scoping
35 are already fairly well established, as are basic numerical and
36 boolean operators.
37
38 Some operators that have only recently been added, and so have not
39 generated all that much experience yet are "and then" and "or else" as
40 short-circuit Boolean operators, and the "if ... else" trinary
41 operator which can select between two expressions based on a third
42 (which appears syntactically in the middle).
43
44 Elements that are present purely to make a usable language, and
45 without any expectation that they will remain, are the "program'
46 clause, which provides a list of variables to received command-line
47 arguments, and the "print" statement which performs simple output.
48
49 The current scalar types are "number", "Boolean", and "string".
50 Boolean will likely stay in its current form, the other two might, but
51 could just as easily be changed.
52
53 ## Naming
54
55 Versions of the interpreter which obviously do not support a complete
56 language will be named after creeks and streams.  This one is Jamison
57 Creek.
58
59 Once we have something reasonably resembling a complete language, the
60 names of rivers will be used.
61 Early versions of the compiler will be named after seas.  Major
62 releases of the compiler will be named after oceans.  Hopefully I will
63 be finished once I get to the Pacific Ocean release.
64
65 ## Outline
66
67 As well as parsing and executing a program, the interpreter can print
68 out the program from the parsed internal structure.  This is useful
69 for validating the parsing.
70 So the main requirements of the interpreter are:
71
72 - Parse the program, possibly with tracing,
73 - Analyse the parsed program to ensure consistency,
74 - Print the program,
75 - Execute the program, if no parsing or consistency errors were found.
76
77 This is all performed by a single C program extracted with
78 `parsergen`.
79
80 There will be two formats for printing the program: a default and one
81 that uses bracketing.  So a `--bracket` command line option is needed
82 for that.  Normally the first code section found is used, however an
83 alternate section can be requested so that a file (such as this one)
84 can contain multiple programs.  This is effected with the `--section`
85 option.
86
87 This code must be compiled with `-fplan9-extensions` so that anonymous
88 structures can be used.
89
90 ###### File: oceani.mk
91
92         myCFLAGS := -Wall -g -fplan9-extensions
93         CFLAGS := $(filter-out $(myCFLAGS),$(CFLAGS)) $(myCFLAGS)
94         myLDLIBS:= libparser.o libscanner.o libmdcode.o -licuuc
95         LDLIBS := $(filter-out $(myLDLIBS),$(LDLIBS)) $(myLDLIBS)
96         ## libs
97         all :: $(LDLIBS) oceani
98         oceani.c oceani.h : oceani.mdc parsergen
99                 ./parsergen -o oceani --LALR --tag Parser oceani.mdc
100         oceani.mk: oceani.mdc md2c
101                 ./md2c oceani.mdc
102
103         oceani: oceani.o $(LDLIBS)
104                 $(CC) $(CFLAGS) -o oceani oceani.o $(LDLIBS)
105
106 ###### Parser: header
107         ## macros
108         ## ast
109         struct parse_context {
110                 struct token_config config;
111                 char *file_name;
112                 int parse_error;
113                 struct exec *prog;
114                 ## parse context
115         };
116
117 ###### macros
118
119         #define container_of(ptr, type, member) ({                      \
120                 const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
121                 (type *)( (char *)__mptr - offsetof(type,member) );})
122
123         #define config2context(_conf) container_of(_conf, struct parse_context, \
124                 config)
125
126 ###### Parser: reduce
127         struct parse_context *c = config2context(config);
128
129 ###### Parser: code
130
131         #include <unistd.h>
132         #include <stdlib.h>
133         #include <fcntl.h>
134         #include <errno.h>
135         #include <sys/mman.h>
136         #include <string.h>
137         #include <stdio.h>
138         #include <locale.h>
139         #include <malloc.h>
140         #include "mdcode.h"
141         #include "scanner.h"
142         #include "parser.h"
143
144         ## includes
145
146         #include "oceani.h"
147
148         ## forward decls
149         ## value functions
150         ## ast functions
151         ## core functions
152
153         #include <getopt.h>
154         static char Usage[] =
155                 "Usage: oceani --trace --print --noexec --brackets --section=SectionName prog.ocn\n";
156         static const struct option long_options[] = {
157                 {"trace",     0, NULL, 't'},
158                 {"print",     0, NULL, 'p'},
159                 {"noexec",    0, NULL, 'n'},
160                 {"brackets",  0, NULL, 'b'},
161                 {"section",   1, NULL, 's'},
162                 {NULL,        0, NULL, 0},
163         };
164         const char *options = "tpnbs";
165         int main(int argc, char *argv[])
166         {
167                 int fd;
168                 int len;
169                 char *file;
170                 struct section *s, *ss;
171                 char *section = NULL;
172                 struct parse_context context = {
173                         .config = {
174                                 .ignored = (1 << TK_mark),
175                                 .number_chars = ".,_+- ",
176                                 .word_start = "_",
177                                 .word_cont = "_",
178                         },
179                 };
180                 int doprint=0, dotrace=0, doexec=1, brackets=0;
181                 int opt;
182                 while ((opt = getopt_long(argc, argv, options, long_options, NULL))
183                        != -1) {
184                         switch(opt) {
185                         case 't': dotrace=1; break;
186                         case 'p': doprint=1; break;
187                         case 'n': doexec=0; break;
188                         case 'b': brackets=1; break;
189                         case 's': section = optarg; break;
190                         default: fprintf(stderr, Usage);
191                                 exit(1);
192                         }
193                 }
194                 if (optind >= argc) {
195                         fprintf(stderr, "oceani: no input file given\n");
196                         exit(1);
197                 }
198                 fd = open(argv[optind], O_RDONLY);
199                 if (fd < 0) {
200                         fprintf(stderr, "oceani: cannot open %s\n", argv[optind]);
201                         exit(1);
202                 }
203                 context.file_name = argv[optind];
204                 len = lseek(fd, 0, 2);
205                 file = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
206                 s = code_extract(file, file+len, NULL);
207                 if (!s) {
208                         fprintf(stderr, "oceani: could not find any code in %s\n",
209                                 argv[optind]);
210                         exit(1);
211                 }
212
213                 ## context initialization
214
215                 if (section) {
216                         for (ss = s; ss; ss = ss->next) {
217                                 struct text sec = ss->section;
218                                 if (sec.len == strlen(section) &&
219                                     strncmp(sec.txt, section, sec.len) == 0)
220                                         break;
221                         }
222                         if (!ss) {
223                                 fprintf(stderr, "oceani: cannot find section %s\n",
224                                         section);
225                                 exit(1);
226                         }
227                 } else
228                         ss = s;
229                 parse_oceani(ss->code, &context.config, dotrace ? stderr : NULL);
230
231                 if (!context.prog) {
232                         fprintf(stderr, "oceani: no program found.\n");
233                         context.parse_error = 1;
234                 }
235                 if (context.prog && doprint) {
236                         ## print const decls
237                         ## print type decls
238                         print_exec(context.prog, 0, brackets);
239                 }
240                 if (context.prog && doexec && !context.parse_error) {
241                         if (!analyse_prog(context.prog, &context)) {
242                                 fprintf(stderr, "oceani: type error in program - not running.\n");
243                                 exit(1);
244                         }
245                         interp_prog(context.prog, argv+optind+1);
246                 }
247                 free_exec(context.prog);
248
249                 while (s) {
250                         struct section *t = s->next;
251                         code_free(s->code);
252                         free(s);
253                         s = t;
254                 }
255                 ## free context vars
256                 ## free context types
257                 exit(context.parse_error ? 1 : 0);
258         }
259
260 ### Analysis
261
262 The four requirements of parse, analyse, print, interpret apply to
263 each language element individually so that is how most of the code
264 will be structured.
265
266 Three of the four are fairly self explanatory.  The one that requires
267 a little explanation is the analysis step.
268
269 The current language design does not require the types of variables to
270 be declared, but they must still have a single type.  Different
271 operations impose different requirements on the variables, for example
272 addition requires both arguments to be numeric, and assignment
273 requires the variable on the left to have the same type as the
274 expression on the right.
275
276 Analysis involves propagating these type requirements around and
277 consequently setting the type of each variable.  If any requirements
278 are violated (e.g. a string is compared with a number) or if a
279 variable needs to have two different types, then an error is raised
280 and the program will not run.
281
282 If the same variable is declared in both branchs of an 'if/else', or
283 in all cases of a 'switch' then the multiple instances may be merged
284 into just one variable if the variable is referenced after the
285 conditional statement.  When this happens, the types must naturally be
286 consistent across all the branches.  When the variable is not used
287 outside the if, the variables in the different branches are distinct
288 and can be of different types.
289
290 Undeclared names may only appear in "use" statements and "case" expressions.
291 These names are given a type of "label" and a unique value.
292 This allows them to fill the role of a name in an enumerated type, which
293 is useful for testing the `switch` statement.
294
295 As we will see, the condition part of a `while` statement can return
296 either a Boolean or some other type.  This requires that the expected
297 type that gets passed around comprises a type and a flag to indicate
298 that `Tbool` is also permitted.
299
300 As there are, as yet, no distinct types that are compatible, there
301 isn't much subtlety in the analysis.  When we have distinct number
302 types, this will become more interesting.
303
304 #### Error reporting
305
306 When analysis discovers an inconsistency it needs to report an error;
307 just refusing to run the code ensures that the error doesn't cascade,
308 but by itself it isn't very useful.  A clear understanding of the sort
309 of error message that are useful will help guide the process of
310 analysis.
311
312 At a simplistic level, the only sort of error that type analysis can
313 report is that the type of some construct doesn't match a contextual
314 requirement.  For example, in `4 + "hello"` the addition provides a
315 contextual requirement for numbers, but `"hello"` is not a number.  In
316 this particular example no further information is needed as the types
317 are obvious from local information.  When a variable is involved that
318 isn't the case.  It may be helpful to explain why the variable has a
319 particular type, by indicating the location where the type was set,
320 whether by declaration or usage.
321
322 Using a recursive-descent analysis we can easily detect a problem at
323 multiple locations. In "`hello:= "there"; 4 + hello`" the addition
324 will detect that one argument is not a number and the usage of `hello`
325 will detect that a number was wanted, but not provided.  In this
326 (early) version of the language, we will generate error reports at
327 multiple locations, so the use of `hello` will report an error and
328 explain were the value was set, and the addition will report an error
329 and say why numbers are needed.  To be able to report locations for
330 errors, each language element will need to record a file location
331 (line and column) and each variable will need to record the language
332 element where its type was set.  For now we will assume that each line
333 of an error message indicates one location in the file, and up to 2
334 types.  So we provide a `printf`-like function which takes a format, a
335 location (a `struct exec` which has not yet been introduced), and 2
336 types. "`%1`" reports the first type, "`%2`" reports the second.  We
337 will need a function to print the location, once we know how that is
338 stored. e As will be explained later, there are sometimes extra rules for
339 type matching and they might affect error messages, we need to pass those
340 in too.
341
342 As well as type errors, we sometimes need to report problems with
343 tokens, which might be unexpected or might name a type that has not
344 been defined.  For these we have `tok_err()` which reports an error
345 with a given token.  Each of the error functions sets the flag in the
346 context so indicate that parsing failed.
347
348 ###### forward decls
349
350         static void fput_loc(struct exec *loc, FILE *f);
351
352 ###### core functions
353
354         static void type_err(struct parse_context *c,
355                              char *fmt, struct exec *loc,
356                              struct type *t1, int rules, struct type *t2)
357         {
358                 fprintf(stderr, "%s:", c->file_name);
359                 fput_loc(loc, stderr);
360                 for (; *fmt ; fmt++) {
361                         if (*fmt != '%') {
362                                 fputc(*fmt, stderr);
363                                 continue;
364                         }
365                         fmt++;
366                         switch (*fmt) {
367                         case '%': fputc(*fmt, stderr); break;   // NOTEST
368                         default: fputc('?', stderr); break;     // NOTEST
369                         case '1':
370                                 type_print(t1, stderr);
371                                 break;
372                         case '2':
373                                 type_print(t2, stderr);
374                                 break;
375                         ## format cases
376                         }
377                 }
378                 fputs("\n", stderr);
379                 c->parse_error = 1;
380         }
381
382         static void tok_err(struct parse_context *c, char *fmt, struct token *t)
383         {
384                 fprintf(stderr, "%s:%d:%d: %s: %.*s\n", c->file_name, t->line, t->col, fmt,
385                         t->txt.len, t->txt.txt);
386                 c->parse_error = 1;
387         }
388
389 ## Entities: declared and predeclared.
390
391 There are various "things" that the language and/or the interpreter
392 needs to know about to parse and execute a program.  These include
393 types, variables, values, and executable code.  These are all lumped
394 together under the term "entities" (calling them "objects" would be
395 confusing) and introduced here.  The following section will present the
396 different specific code elements which comprise or manipulate these
397 various entities.
398
399 ### Types
400
401 Values come in a wide range of types, with more likely to be added.
402 Each type needs to be able to print its own values (for convenience at
403 least) as well as to compare two values, at least for equality and
404 possibly for order.  For now, values might need to be duplicated and
405 freed, though eventually such manipulations will be better integrated
406 into the language.
407
408 Rather than requiring every numeric type to support all numeric
409 operations (add, multiple, etc), we allow types to be able to present
410 as one of a few standard types: integer, float, and fraction.  The
411 existence of these conversion functions eventually enable types to
412 determine if they are compatible with other types, though such types
413 have not yet been implemented.
414
415 Named type are stored in a simple linked list.  Objects of each type are
416 "values" which are often passed around by value.
417
418 ###### ast
419
420         struct value {
421                 union {
422                         char ptr[1];
423                         ## value union fields
424                 };
425         };
426
427         struct type {
428                 struct text name;
429                 struct type *next;
430                 int size, align;
431                 void (*init)(struct type *type, struct value *val);
432                 void (*prepare_type)(struct type *type);
433                 void (*print)(struct type *type, struct value *val);
434                 void (*print_type)(struct type *type, FILE *f);
435                 int (*cmp_order)(struct type *t1, struct type *t2,
436                                  struct value *v1, struct value *v2);
437                 int (*cmp_eq)(struct type *t1, struct type *t2,
438                               struct value *v1, struct value *v2);
439                 void (*dup)(struct type *type, struct value *vold, struct value *vnew);
440                 void (*free)(struct type *type, struct value *val);
441                 void (*free_type)(struct type *t);
442                 long long (*to_int)(struct value *v);
443                 double (*to_float)(struct value *v);
444                 int (*to_mpq)(mpq_t *q, struct value *v);
445                 ## type functions
446                 union {
447                         ## type union fields
448                 };
449         };
450
451 ###### parse context
452
453         struct type *typelist;
454
455 ###### ast functions
456
457         static struct type *find_type(struct parse_context *c, struct text s)
458         {
459                 struct type *l = c->typelist;
460
461                 while (l &&
462                        text_cmp(l->name, s) != 0)
463                                 l = l->next;
464                 return l;
465         }
466
467         static struct type *add_type(struct parse_context *c, struct text s,
468                                      struct type *proto)
469         {
470                 struct type *n;
471
472                 n = calloc(1, sizeof(*n));
473                 *n = *proto;
474                 n->name = s;
475                 n->next = c->typelist;
476                 c->typelist = n;
477                 return n;
478         }
479
480         static void free_type(struct type *t)
481         {
482                 /* The type is always a reference to something in the
483                  * context, so we don't need to free anything.
484                  */
485         }
486
487         static void free_value(struct type *type, struct value *v)
488         {
489                 if (type && v)
490                         type->free(type, v);
491         }
492
493         static void type_print(struct type *type, FILE *f)
494         {
495                 if (!type)
496                         fputs("*unknown*type*", f);
497                 else if (type->name.len)
498                         fprintf(f, "%.*s", type->name.len, type->name.txt);
499                 else if (type->print_type)
500                         type->print_type(type, f);
501                 else
502                         fputs("*invalid*type*", f);     // NOTEST
503         }
504
505         static void val_init(struct type *type, struct value *val)
506         {
507                 if (type && type->init)
508                         type->init(type, val);
509         }
510
511         static void dup_value(struct type *type, 
512                               struct value *vold, struct value *vnew)
513         {
514                 if (type && type->dup)
515                         type->dup(type, vold, vnew);
516         }
517
518         static int value_cmp(struct type *tl, struct type *tr,
519                              struct value *left, struct value *right)
520         {
521                 if (tl && tl->cmp_order)
522                         return tl->cmp_order(tl, tr, left, right);
523                 if (tl && tl->cmp_eq)
524                         return tl->cmp_eq(tl, tr, left, right);
525                 return -1;
526         }
527
528         static void print_value(struct type *type, struct value *v)
529         {
530                 if (type && type->print)
531                         type->print(type, v);
532                 else
533                         printf("*Unknown*");            // NOTEST
534         }
535
536         static struct value *val_alloc(struct type *t, struct value *init)
537         {
538                 struct value *ret;
539
540                 if (t->prepare_type)
541                         t->prepare_type(t);
542
543                 ret = calloc(1, t->size);
544                 if (init)
545                         memcpy(ret, init, t->size);
546                 else
547                         val_init(t, ret);
548                 return ret;
549         }
550
551 ###### forward decls
552
553         static void free_value(struct type *type, struct value *v);
554         static int type_compat(struct type *require, struct type *have, int rules);
555         static void type_print(struct type *type, FILE *f);
556         static void val_init(struct type *type, struct value *v);
557         static void dup_value(struct type *type,
558                               struct value *vold, struct value *vnew);
559         static int value_cmp(struct type *tl, struct type *tr,
560                              struct value *left, struct value *right);
561         static void print_value(struct type *type, struct value *v);
562
563 ###### free context types
564
565         while (context.typelist) {
566                 struct type *t = context.typelist;
567
568                 context.typelist = t->next;
569                 if (t->free_type)
570                         t->free_type(t);
571                 free(t);
572         }
573
574 #### Base Types
575
576 Values of the base types can be numbers, which we represent as
577 multi-precision fractions, strings, Booleans and labels.  When
578 analysing the program we also need to allow for places where no value
579 is meaningful (type `Tnone`) and where we don't know what type to
580 expect yet (type is `NULL`).
581
582 Values are never shared, they are always copied when used, and freed
583 when no longer needed.
584
585 When propagating type information around the program, we need to
586 determine if two types are compatible, where type `NULL` is compatible
587 with anything.  There are two special cases with type compatibility,
588 both related to the Conditional Statement which will be described
589 later.  In some cases a Boolean can be accepted as well as some other
590 primary type, and in others any type is acceptable except a label (`Vlabel`).
591 A separate function encoding these cases will simplify some code later.
592
593 ## type functions
594
595         int (*compat)(struct type *this, struct type *other);
596
597 ## ast functions
598
599         static int type_compat(struct type *require, struct type *have, int rules)
600         {
601                 if ((rules & Rboolok) && have == Tbool)
602                         return 1;
603                 if ((rules & Rnolabel) && have == Tlabel)
604                         return 0;
605                 if (!require || !have)
606                         return 1;
607
608                 if (require->compat)
609                         return require->compat(require, have);
610
611                 return require == have;
612         }
613
614 ###### includes
615         #include <gmp.h>
616         #include "parse_string.h"
617         #include "parse_number.h"
618
619 ###### libs
620         myLDLIBS := libnumber.o libstring.o -lgmp
621         LDLIBS := $(filter-out $(myLDLIBS),$(LDLIBS)) $(myLDLIBS)
622
623 ###### type union fields
624         enum vtype {Vnone, Vstr, Vnum, Vbool, Vlabel} vtype;
625
626 ###### value union fields
627         struct text str;
628         mpq_t num;
629         unsigned char bool;
630         void *label;
631
632 ###### ast functions
633         static void _free_value(struct type *type, struct value *v)
634         {
635                 if (!v)
636                         return;
637                 switch (type->vtype) {
638                 case Vnone: break;
639                 case Vstr: free(v->str.txt); break;
640                 case Vnum: mpq_clear(v->num); break;
641                 case Vlabel:
642                 case Vbool: break;
643                 }
644         }
645
646 ###### value functions
647
648         static void _val_init(struct type *type, struct value *val)
649         {
650                 switch(type->vtype) {
651                 case Vnone:             // NOTEST
652                         break;          // NOTEST
653                 case Vnum:
654                         mpq_init(val->num); break;
655                 case Vstr:
656                         val->str.txt = malloc(1);
657                         val->str.len = 0;
658                         break;
659                 case Vbool:
660                         val->bool = 0;
661                         break;
662                 case Vlabel:                    // NOTEST
663                         val->label = NULL;      // NOTEST
664                         break;                  // NOTEST
665                 }
666         }
667
668         static void _dup_value(struct type *type, 
669                                struct value *vold, struct value *vnew)
670         {
671                 switch (type->vtype) {
672                 case Vnone:             // NOTEST
673                         break;          // NOTEST
674                 case Vlabel:
675                         vnew->label = vold->label;
676                         break;
677                 case Vbool:
678                         vnew->bool = vold->bool;
679                         break;
680                 case Vnum:
681                         mpq_init(vnew->num);
682                         mpq_set(vnew->num, vold->num);
683                         break;
684                 case Vstr:
685                         vnew->str.len = vold->str.len;
686                         vnew->str.txt = malloc(vnew->str.len);
687                         memcpy(vnew->str.txt, vold->str.txt, vnew->str.len);
688                         break;
689                 }
690         }
691
692         static int _value_cmp(struct type *tl, struct type *tr,
693                               struct value *left, struct value *right)
694         {
695                 int cmp;
696                 if (tl != tr)
697                         return tl - tr; // NOTEST
698                 switch (tl->vtype) {
699                 case Vlabel: cmp = left->label == right->label ? 0 : 1; break;
700                 case Vnum: cmp = mpq_cmp(left->num, right->num); break;
701                 case Vstr: cmp = text_cmp(left->str, right->str); break;
702                 case Vbool: cmp = left->bool - right->bool; break;
703                 case Vnone: cmp = 0;                    // NOTEST
704                 }
705                 return cmp;
706         }
707
708         static void _print_value(struct type *type, struct value *v)
709         {
710                 switch (type->vtype) {
711                 case Vnone:                             // NOTEST
712                         printf("*no-value*"); break;    // NOTEST
713                 case Vlabel:                            // NOTEST
714                         printf("*label-%p*", v->label); break; // NOTEST
715                 case Vstr:
716                         printf("%.*s", v->str.len, v->str.txt); break;
717                 case Vbool:
718                         printf("%s", v->bool ? "True":"False"); break;
719                 case Vnum:
720                         {
721                         mpf_t fl;
722                         mpf_init2(fl, 20);
723                         mpf_set_q(fl, v->num);
724                         gmp_printf("%Fg", fl);
725                         mpf_clear(fl);
726                         break;
727                         }
728                 }
729         }
730
731         static void _free_value(struct type *type, struct value *v);
732
733         static struct type base_prototype = {
734                 .init = _val_init,
735                 .print = _print_value,
736                 .cmp_order = _value_cmp,
737                 .cmp_eq = _value_cmp,
738                 .dup = _dup_value,
739                 .free = _free_value,
740         };
741
742         static struct type *Tbool, *Tstr, *Tnum, *Tnone, *Tlabel;
743
744 ###### ast functions
745         static struct type *add_base_type(struct parse_context *c, char *n,
746                                           enum vtype vt, int size)
747         {
748                 struct text txt = { n, strlen(n) };
749                 struct type *t;
750
751                 t = add_type(c, txt, &base_prototype);
752                 t->vtype = vt;
753                 t->size = size;
754                 t->align = size > sizeof(void*) ? sizeof(void*) : size;
755                 if (t->size & (t->align - 1))
756                         t->size = (t->size | (t->align - 1)) + 1;
757                 return t;
758         }
759
760 ###### context initialization
761
762         Tbool  = add_base_type(&context, "Boolean", Vbool, sizeof(char));
763         Tstr   = add_base_type(&context, "string", Vstr, sizeof(struct text));
764         Tnum   = add_base_type(&context, "number", Vnum, sizeof(mpq_t));
765         Tnone  = add_base_type(&context, "none", Vnone, 0);
766         Tlabel = add_base_type(&context, "label", Vlabel, sizeof(void*));
767
768 ### Variables
769
770 Variables are scoped named values.  We store the names in a linked list
771 of "bindings" sorted in lexical order, and use sequential search and
772 insertion sort.
773
774 ###### ast
775
776         struct binding {
777                 struct text name;
778                 struct binding *next;   // in lexical order
779                 ## binding fields
780         };
781
782 This linked list is stored in the parse context so that "reduce"
783 functions can find or add variables, and so the analysis phase can
784 ensure that every variable gets a type.
785
786 ###### parse context
787
788         struct binding *varlist;  // In lexical order
789
790 ###### ast functions
791
792         static struct binding *find_binding(struct parse_context *c, struct text s)
793         {
794                 struct binding **l = &c->varlist;
795                 struct binding *n;
796                 int cmp = 1;
797
798                 while (*l &&
799                         (cmp = text_cmp((*l)->name, s)) < 0)
800                                 l = & (*l)->next;
801                 if (cmp == 0)
802                         return *l;
803                 n = calloc(1, sizeof(*n));
804                 n->name = s;
805                 n->next = *l;
806                 *l = n;
807                 return n;
808         }
809
810 Each name can be linked to multiple variables defined in different
811 scopes.  Each scope starts where the name is declared and continues
812 until the end of the containing code block.  Scopes of a given name
813 cannot nest, so a declaration while a name is in-scope is an error.
814
815 ###### binding fields
816         struct variable *var;
817
818 ###### ast
819         struct variable {
820                 struct variable *previous;
821                 struct type *type;
822                 struct value *val;
823                 struct binding *name;
824                 struct exec *where_decl;// where name was declared
825                 struct exec *where_set; // where type was set
826                 ## variable fields
827         };
828
829 While the naming seems strange, we include local constants in the
830 definition of variables.  A name declared `var := value` can
831 subsequently be changed, but a name declared `var ::= value` cannot -
832 it is constant
833
834 ###### variable fields
835         int constant;
836
837 Scopes in parallel branches can be partially merged.  More
838 specifically, if a given name is declared in both branches of an
839 if/else then its scope is a candidate for merging.  Similarly if
840 every branch of an exhaustive switch (e.g. has an "else" clause)
841 declares a given name, then the scopes from the branches are
842 candidates for merging.
843
844 Note that names declared inside a loop (which is only parallel to
845 itself) are never visible after the loop.  Similarly names defined in
846 scopes which are not parallel, such as those started by `for` and
847 `switch`, are never visible after the scope.  Only variables defined in
848 both `then` and `else` (including the implicit then after an `if`, and
849 excluding `then` used with `for`) and in all `case`s and `else` of a
850 `switch` or `while` can be visible beyond the `if`/`switch`/`while`.
851
852 Labels, which are a bit like variables, follow different rules.
853 Labels are not explicitly declared, but if an undeclared name appears
854 in a context where a label is legal, that effectively declares the
855 name as a label.  The declaration remains in force (or in scope) at
856 least to the end of the immediately containing block and conditionally
857 in any larger containing block which does not declare the name in some
858 other way.  Importantly, the conditional scope extension happens even
859 if the label is only used in one parallel branch of a conditional --
860 when used in one branch it is treated as having been declared in all
861 branches.
862
863 Merge candidates are tentatively visible beyond the end of the
864 branching statement which creates them.  If the name is used, the
865 merge is affirmed and they become a single variable visible at the
866 outer layer.  If not - if it is redeclared first - the merge lapses.
867
868 To track scopes we have an extra stack, implemented as a linked list,
869 which roughly parallels the parse stack and which is used exclusively
870 for scoping.  When a new scope is opened, a new frame is pushed and
871 the child-count of the parent frame is incremented.  This child-count
872 is used to distinguish between the first of a set of parallel scopes,
873 in which declared variables must not be in scope, and subsequent
874 branches, whether they may already be conditionally scoped.
875
876 To push a new frame *before* any code in the frame is parsed, we need a
877 grammar reduction.  This is most easily achieved with a grammar
878 element which derives the empty string, and creates the new scope when
879 it is recognised.  This can be placed, for example, between a keyword
880 like "if" and the code following it.
881
882 ###### ast
883         struct scope {
884                 struct scope *parent;
885                 int child_count;
886         };
887
888 ###### parse context
889         int scope_depth;
890         struct scope *scope_stack;
891
892 ###### ast functions
893         static void scope_pop(struct parse_context *c)
894         {
895                 struct scope *s = c->scope_stack;
896
897                 c->scope_stack = s->parent;
898                 free(s);
899                 c->scope_depth -= 1;
900         }
901
902         static void scope_push(struct parse_context *c)
903         {
904                 struct scope *s = calloc(1, sizeof(*s));
905                 if (c->scope_stack)
906                         c->scope_stack->child_count += 1;
907                 s->parent = c->scope_stack;
908                 c->scope_stack = s;
909                 c->scope_depth += 1;
910         }
911
912 ###### Grammar
913
914         $void
915         OpenScope -> ${ scope_push(c); }$
916         ClosePara -> ${ var_block_close(c, CloseParallel); }$
917
918 Each variable records a scope depth and is in one of four states:
919
920 - "in scope".  This is the case between the declaration of the
921   variable and the end of the containing block, and also between
922   the usage with affirms a merge and the end of that block.
923
924   The scope depth is not greater than the current parse context scope
925   nest depth.  When the block of that depth closes, the state will
926   change.  To achieve this, all "in scope" variables are linked
927   together as a stack in nesting order.
928
929 - "pending".  The "in scope" block has closed, but other parallel
930   scopes are still being processed.  So far, every parallel block at
931   the same level that has closed has declared the name.
932
933   The scope depth is the depth of the last parallel block that
934   enclosed the declaration, and that has closed.
935
936 - "conditionally in scope".  The "in scope" block and all parallel
937   scopes have closed, and no further mention of the name has been
938   seen.  This state includes a secondary nest depth which records the
939   outermost scope seen since the variable became conditionally in
940   scope.  If a use of the name is found, the variable becomes "in
941   scope" and that secondary depth becomes the recorded scope depth.
942   If the name is declared as a new variable, the old variable becomes
943   "out of scope" and the recorded scope depth stays unchanged.
944
945 - "out of scope".  The variable is neither in scope nor conditionally
946   in scope.  It is permanently out of scope now and can be removed from
947   the "in scope" stack.
948
949 ###### variable fields
950         int depth, min_depth;
951         enum { OutScope, PendingScope, CondScope, InScope } scope;
952         struct variable *in_scope;
953
954 ###### parse context
955
956         struct variable *in_scope;
957
958 All variables with the same name are linked together using the
959 'previous' link.  Those variable that have been affirmatively merged all
960 have a 'merged' pointer that points to one primary variable - the most
961 recently declared instance.  When merging variables, we need to also
962 adjust the 'merged' pointer on any other variables that had previously
963 been merged with the one that will no longer be primary.
964
965 A variable that is no longer the most recent instance of a name may
966 still have "pending" scope, if it might still be merged with most
967 recent instance.  These variables don't really belong in the
968 "in_scope" list, but are not immediately removed when a new instance
969 is found.  Instead, they are detected and ignored when considering the
970 list of in_scope names.
971
972 ###### variable fields
973         struct variable *merged;
974
975 ###### ast functions
976
977         static void variable_merge(struct variable *primary, struct variable *secondary)
978         {
979                 struct variable *v;
980
981                 if (primary->merged)
982                         // shouldn't happen
983                         primary = primary->merged;
984
985                 for (v = primary->previous; v; v=v->previous)
986                         if (v == secondary || v == secondary->merged ||
987                             v->merged == secondary ||
988                             (v->merged && v->merged == secondary->merged)) {
989                                 v->scope = OutScope;
990                                 v->merged = primary;
991                         }
992         }
993
994 ###### free context vars
995
996         while (context.varlist) {
997                 struct binding *b = context.varlist;
998                 struct variable *v = b->var;
999                 context.varlist = b->next;
1000                 free(b);
1001                 while (v) {
1002                         struct variable *t = v;
1003
1004                         v = t->previous;
1005                         free_value(t->type, t->val);
1006                         free(t->val);
1007                         if (t->depth == 0)
1008                                 // This is a global constant
1009                                 free_exec(t->where_decl);
1010                         free(t);
1011                 }
1012         }
1013
1014 #### Manipulating Bindings
1015
1016 When a name is conditionally visible, a new declaration discards the
1017 old binding - the condition lapses.  Conversely a usage of the name
1018 affirms the visibility and extends it to the end of the containing
1019 block - i.e. the block that contains both the original declaration and
1020 the latest usage.  This is determined from `min_depth`.  When a
1021 conditionally visible variable gets affirmed like this, it is also
1022 merged with other conditionally visible variables with the same name.
1023
1024 When we parse a variable declaration we either report an error if the
1025 name is currently bound, or create a new variable at the current nest
1026 depth if the name is unbound or bound to a conditionally scoped or
1027 pending-scope variable.  If the previous variable was conditionally
1028 scoped, it and its homonyms becomes out-of-scope.
1029
1030 When we parse a variable reference (including non-declarative assignment
1031 "foo = bar") we report an error if the name is not bound or is bound to
1032 a pending-scope variable; update the scope if the name is bound to a
1033 conditionally scoped variable; or just proceed normally if the named
1034 variable is in scope.
1035
1036 When we exit a scope, any variables bound at this level are either
1037 marked out of scope or pending-scoped, depending on whether the scope
1038 was sequential or parallel.  Here a "parallel" scope means the "then"
1039 or "else" part of a conditional, or any "case" or "else" branch of a
1040 switch.  Other scopes are "sequential".
1041
1042 When exiting a parallel scope we check if there are any variables that
1043 were previously pending and are still visible. If there are, then
1044 there weren't redeclared in the most recent scope, so they cannot be
1045 merged and must become out-of-scope.  If it is not the first of
1046 parallel scopes (based on `child_count`), we check that there was a
1047 previous binding that is still pending-scope.  If there isn't, the new
1048 variable must now be out-of-scope.
1049
1050 When exiting a sequential scope that immediately enclosed parallel
1051 scopes, we need to resolve any pending-scope variables.  If there was
1052 no `else` clause, and we cannot determine that the `switch` was exhaustive,
1053 we need to mark all pending-scope variable as out-of-scope.  Otherwise
1054 all pending-scope variables become conditionally scoped.
1055
1056 ###### ast
1057         enum closetype { CloseSequential, CloseParallel, CloseElse };
1058
1059 ###### ast functions
1060
1061         static struct variable *var_decl(struct parse_context *c, struct text s)
1062         {
1063                 struct binding *b = find_binding(c, s);
1064                 struct variable *v = b->var;
1065
1066                 switch (v ? v->scope : OutScope) {
1067                 case InScope:
1068                         /* Caller will report the error */
1069                         return NULL;
1070                 case CondScope:
1071                         for (;
1072                              v && v->scope == CondScope;
1073                              v = v->previous)
1074                                 v->scope = OutScope;
1075                         break;
1076                 default: break;
1077                 }
1078                 v = calloc(1, sizeof(*v));
1079                 v->previous = b->var;
1080                 b->var = v;
1081                 v->name = b;
1082                 v->min_depth = v->depth = c->scope_depth;
1083                 v->scope = InScope;
1084                 v->in_scope = c->in_scope;
1085                 c->in_scope = v;
1086                 v->val = NULL;
1087                 return v;
1088         }
1089
1090         static struct variable *var_ref(struct parse_context *c, struct text s)
1091         {
1092                 struct binding *b = find_binding(c, s);
1093                 struct variable *v = b->var;
1094                 struct variable *v2;
1095
1096                 switch (v ? v->scope : OutScope) {
1097                 case OutScope:
1098                 case PendingScope:
1099                         /* Caller will report the error */
1100                         return NULL;
1101                 case CondScope:
1102                         /* All CondScope variables of this name need to be merged
1103                          * and become InScope
1104                          */
1105                         v->depth = v->min_depth;
1106                         v->scope = InScope;
1107                         for (v2 = v->previous;
1108                              v2 && v2->scope == CondScope;
1109                              v2 = v2->previous)
1110                                 variable_merge(v, v2);
1111                         break;
1112                 case InScope:
1113                         break;
1114                 }
1115                 return v;
1116         }
1117
1118         static void var_block_close(struct parse_context *c, enum closetype ct)
1119         {
1120                 /* Close off all variables that are in_scope */
1121                 struct variable *v, **vp, *v2;
1122
1123                 scope_pop(c);
1124                 for (vp = &c->in_scope;
1125                      v = *vp, v && v->depth > c->scope_depth && v->min_depth > c->scope_depth;
1126                      ) {
1127                         if (v->name->var == v) switch (ct) {
1128                         case CloseElse:
1129                         case CloseParallel: /* handle PendingScope */
1130                                 switch(v->scope) {
1131                                 case InScope:
1132                                 case CondScope:
1133                                         if (c->scope_stack->child_count == 1)
1134                                                 v->scope = PendingScope;
1135                                         else if (v->previous &&
1136                                                  v->previous->scope == PendingScope)
1137                                                 v->scope = PendingScope;
1138                                         else if (v->type == Tlabel)
1139                                                 v->scope = PendingScope;
1140                                         else if (v->name->var == v)
1141                                                 v->scope = OutScope;
1142                                         if (ct == CloseElse) {
1143                                                 /* All Pending variables with this name
1144                                                  * are now Conditional */
1145                                                 for (v2 = v;
1146                                                      v2 && v2->scope == PendingScope;
1147                                                      v2 = v2->previous)
1148                                                         v2->scope = CondScope;
1149                                         }
1150                                         break;
1151                                 case PendingScope:
1152                                         for (v2 = v;
1153                                              v2 && v2->scope == PendingScope;
1154                                              v2 = v2->previous)
1155                                                 if (v2->type != Tlabel)
1156                                                         v2->scope = OutScope;
1157                                         break;
1158                                 case OutScope: break;
1159                                 }
1160                                 break;
1161                         case CloseSequential:
1162                                 if (v->type == Tlabel)
1163                                         v->scope = PendingScope;
1164                                 switch (v->scope) {
1165                                 case InScope:
1166                                         v->scope = OutScope;
1167                                         break;
1168                                 case PendingScope:
1169                                         /* There was no 'else', so we can only become
1170                                          * conditional if we know the cases were exhaustive,
1171                                          * and that doesn't mean anything yet.
1172                                          * So only labels become conditional..
1173                                          */
1174                                         for (v2 = v;
1175                                              v2 && v2->scope == PendingScope;
1176                                              v2 = v2->previous)
1177                                                 if (v2->type == Tlabel) {
1178                                                         v2->scope = CondScope;
1179                                                         v2->min_depth = c->scope_depth;
1180                                                 } else
1181                                                         v2->scope = OutScope;
1182                                         break;
1183                                 case CondScope:
1184                                 case OutScope: break;
1185                                 }
1186                                 break;
1187                         }
1188                         if (v->scope == OutScope || v->name->var != v)
1189                                 *vp = v->in_scope;
1190                         else
1191                                 vp = &v->in_scope;
1192                 }
1193         }
1194
1195 ### Executables
1196
1197 Executables can be lots of different things.  In many cases an
1198 executable is just an operation combined with one or two other
1199 executables.  This allows for expressions and lists etc.  Other times an
1200 executable is something quite specific like a constant or variable name.
1201 So we define a `struct exec` to be a general executable with a type, and
1202 a `struct binode` which is a subclass of `exec`, forms a node in a
1203 binary tree, and holds an operation.  There will be other subclasses,
1204 and to access these we need to be able to `cast` the `exec` into the
1205 various other types.  The first field in any `struct exec` is the type
1206 from the `exec_types` enum.
1207
1208 ###### macros
1209         #define cast(structname, pointer) ({            \
1210                 const typeof( ((struct structname *)0)->type) *__mptr = &(pointer)->type; \
1211                 if (__mptr && *__mptr != X##structname) abort();                \
1212                 (struct structname *)( (char *)__mptr);})
1213
1214         #define new(structname) ({                                              \
1215                 struct structname *__ptr = ((struct structname *)calloc(1,sizeof(struct structname))); \
1216                 __ptr->type = X##structname;                                            \
1217                 __ptr->line = -1; __ptr->column = -1;                                   \
1218                 __ptr;})
1219
1220         #define new_pos(structname, token) ({                                           \
1221                 struct structname *__ptr = ((struct structname *)calloc(1,sizeof(struct structname))); \
1222                 __ptr->type = X##structname;                                            \
1223                 __ptr->line = token.line; __ptr->column = token.col;                    \
1224                 __ptr;})
1225
1226 ###### ast
1227         enum exec_types {
1228                 Xbinode,
1229                 ## exec type
1230         };
1231         struct exec {
1232                 enum exec_types type;
1233                 int line, column;
1234         };
1235         struct binode {
1236                 struct exec;
1237                 enum Btype {
1238                         ## Binode types
1239                 } op;
1240                 struct exec *left, *right;
1241         };
1242
1243 ###### ast functions
1244
1245         static int __fput_loc(struct exec *loc, FILE *f)
1246         {
1247                 if (!loc)
1248                         return 0;               // NOTEST
1249                 if (loc->line >= 0) {
1250                         fprintf(f, "%d:%d: ", loc->line, loc->column);
1251                         return 1;
1252                 }
1253                 if (loc->type == Xbinode)
1254                         return __fput_loc(cast(binode,loc)->left, f) ||
1255                                __fput_loc(cast(binode,loc)->right, f);
1256                 return 0;
1257         }
1258         static void fput_loc(struct exec *loc, FILE *f)
1259         {
1260                 if (!__fput_loc(loc, f))
1261                         fprintf(f, "??:??: ");  // NOTEST
1262         }
1263
1264 Each different type of `exec` node needs a number of functions defined,
1265 a bit like methods.  We must be able to free it, print it, analyse it
1266 and execute it.  Once we have specific `exec` types we will need to
1267 parse them too.  Let's take this a bit more slowly.
1268
1269 #### Freeing
1270
1271 The parser generator requires a `free_foo` function for each struct
1272 that stores attributes and they will often be `exec`s and subtypes
1273 there-of.  So we need `free_exec` which can handle all the subtypes,
1274 and we need `free_binode`.
1275
1276 ###### ast functions
1277
1278         static void free_binode(struct binode *b)
1279         {
1280                 if (!b)
1281                         return;
1282                 free_exec(b->left);
1283                 free_exec(b->right);
1284                 free(b);
1285         }
1286
1287 ###### core functions
1288         static void free_exec(struct exec *e)
1289         {
1290                 if (!e)
1291                         return;
1292                 switch(e->type) {
1293                         ## free exec cases
1294                 }
1295         }
1296
1297 ###### forward decls
1298
1299         static void free_exec(struct exec *e);
1300
1301 ###### free exec cases
1302         case Xbinode: free_binode(cast(binode, e)); break;
1303
1304 #### Printing
1305
1306 Printing an `exec` requires that we know the current indent level for
1307 printing line-oriented components.  As will become clear later, we
1308 also want to know what sort of bracketing to use.
1309
1310 ###### ast functions
1311
1312         static void do_indent(int i, char *str)
1313         {
1314                 while (i--)
1315                         printf("    ");
1316                 printf("%s", str);
1317         }
1318
1319 ###### core functions
1320         static void print_binode(struct binode *b, int indent, int bracket)
1321         {
1322                 struct binode *b2;
1323                 switch(b->op) {
1324                 ## print binode cases
1325                 }
1326         }
1327
1328         static void print_exec(struct exec *e, int indent, int bracket)
1329         {
1330                 if (!e)
1331                         return;         // NOTEST
1332                 switch (e->type) {
1333                 case Xbinode:
1334                         print_binode(cast(binode, e), indent, bracket); break;
1335                 ## print exec cases
1336                 }
1337         }
1338
1339 ###### forward decls
1340
1341         static void print_exec(struct exec *e, int indent, int bracket);
1342
1343 #### Analysing
1344
1345 As discussed, analysis involves propagating type requirements around the
1346 program and looking for errors.
1347
1348 So `propagate_types` is passed an expected type (being a `struct type`
1349 pointer together with some `val_rules` flags) that the `exec` is
1350 expected to return, and returns the type that it does return, either
1351 of which can be `NULL` signifying "unknown".  An `ok` flag is passed
1352 by reference. It is set to `0` when an error is found, and `2` when
1353 any change is made.  If it remains unchanged at `1`, then no more
1354 propagation is needed.
1355
1356 ###### ast
1357
1358         enum val_rules {Rnolabel = 1<<0, Rboolok = 1<<1, Rnoconstant = 2<<1};
1359
1360 ###### format cases
1361         case 'r':
1362                 if (rules & Rnolabel)
1363                         fputs(" (labels not permitted)", stderr);
1364                 break;
1365
1366 ###### core functions
1367
1368         static struct type *propagate_types(struct exec *prog, struct parse_context *c, int *ok,
1369                                             struct type *type, int rules);
1370         static struct type *__propagate_types(struct exec *prog, struct parse_context *c, int *ok,
1371                                               struct type *type, int rules)
1372         {
1373                 struct type *t;
1374
1375                 if (!prog)
1376                         return Tnone;
1377
1378                 switch (prog->type) {
1379                 case Xbinode:
1380                 {
1381                         struct binode *b = cast(binode, prog);
1382                         switch (b->op) {
1383                         ## propagate binode cases
1384                         }
1385                         break;
1386                 }
1387                 ## propagate exec cases
1388                 }
1389                 return Tnone;
1390         }
1391
1392         static struct type *propagate_types(struct exec *prog, struct parse_context *c, int *ok,
1393                                             struct type *type, int rules)
1394         {
1395                 struct type *ret = __propagate_types(prog, c, ok, type, rules);
1396
1397                 if (c->parse_error)
1398                         *ok = 0;
1399                 return ret;
1400         }
1401
1402 #### Interpreting
1403
1404 Interpreting an `exec` doesn't require anything but the `exec`.  State
1405 is stored in variables and each variable will be directly linked from
1406 within the `exec` tree.  The exception to this is the whole `program`
1407 which needs to look at command line arguments.  The `program` will be
1408 interpreted separately.
1409
1410 Each `exec` can return a value combined with a type in `struct lrval`.
1411 The type may be `Tnone` but must be non-NULL.  Some `exec`s will return
1412 the location of a value, which can be updated, in `lval`.  Others will
1413 set `lval` to NULL indicating that there is a value of appropriate type
1414 in `rval`.
1415
1416
1417 ###### core functions
1418
1419         struct lrval {
1420                 struct type *type;
1421                 struct value rval, *lval;
1422         };
1423
1424         static struct lrval _interp_exec(struct exec *e);
1425
1426         static struct value interp_exec(struct exec *e, struct type **typeret)
1427         {
1428                 struct lrval ret = _interp_exec(e);
1429
1430                 if (!ret.type) abort();
1431                 if (typeret)
1432                         *typeret = ret.type;
1433                 if (ret.lval)
1434                         dup_value(ret.type, ret.lval, &ret.rval);
1435                 return ret.rval;
1436         }
1437
1438         static struct value *linterp_exec(struct exec *e, struct type **typeret)
1439         {
1440                 struct lrval ret = _interp_exec(e);
1441
1442                 if (ret.lval)
1443                         *typeret = ret.type;
1444                 else
1445                         free_value(ret.type, &ret.rval);
1446                 return ret.lval;
1447         }
1448
1449         static struct lrval _interp_exec(struct exec *e)
1450         {
1451                 struct lrval ret;
1452                 struct value rv = {}, *lrv = NULL;
1453                 struct type *rvtype;
1454
1455                 rvtype = ret.type = Tnone;
1456                 if (!e) {
1457                         ret.lval = lrv;
1458                         ret.rval = rv;
1459                         return ret;
1460                 }
1461
1462                 switch(e->type) {
1463                 case Xbinode:
1464                 {
1465                         struct binode *b = cast(binode, e);
1466                         struct value left, right, *lleft;
1467                         struct type *ltype, *rtype;
1468                         ltype = rtype = Tnone;
1469                         switch (b->op) {
1470                         ## interp binode cases
1471                         }
1472                         free_value(ltype, &left);
1473                         free_value(rtype, &right);
1474                         break;
1475                 }
1476                 ## interp exec cases
1477                 }
1478                 ret.lval = lrv;
1479                 ret.rval = rv;
1480                 ret.type = rvtype;
1481                 return ret;
1482         }
1483
1484 ### Complex types
1485
1486 Now that we have the shape of the interpreter in place we can add some
1487 complex types and connected them in to the data structures and the
1488 different phases of parse, analyse, print, interpret.
1489
1490 Thus far we have arrays and structs.
1491
1492 #### Arrays
1493
1494 Arrays can be declared by giving a size and a type, as `[size]type' so
1495 `freq:[26]number` declares `freq` to be an array of 26 numbers.  The
1496 size can be either a literal number, or a named constant.  Some day an
1497 arbitrary expression will be supported.
1498
1499 Arrays cannot be assigned.  When pointers are introduced we will also
1500 introduce array slices which can refer to part or all of an array -
1501 the assignment syntax will create a slice.  For now, an array can only
1502 ever be referenced by the name it is declared with.  It is likely that
1503 a "`copy`" primitive will eventually be define which can be used to
1504 make a copy of an array with controllable recursive depth.
1505
1506 ###### type union fields
1507
1508         struct {
1509                 int size;
1510                 struct variable *vsize;
1511                 struct type *member;
1512         } array;
1513
1514 ###### value functions
1515
1516         static void array_prepare_type(struct type *type)
1517         {
1518                 mpz_t q;
1519                 if (!type->array.vsize)
1520                         return;
1521
1522                 mpz_init(q);
1523                 mpz_tdiv_q(q, mpq_numref(type->array.vsize->val->num),
1524                            mpq_denref(type->array.vsize->val->num));
1525                 type->array.size = mpz_get_si(q);
1526                 mpz_clear(q);
1527
1528                 type->size = type->array.size * type->array.member->size;
1529                 type->align = type->array.member->align;
1530         }
1531
1532         static void array_init(struct type *type, struct value *val)
1533         {
1534                 int i;
1535
1536                 if (!val)
1537                         return;         
1538                 for (i = 0; i < type->array.size; i++) {
1539                         struct value *v;
1540                         v = (void*)val->ptr + i * type->array.member->size;
1541                         val_init(type->array.member, v);
1542                 }
1543         }
1544
1545         static void array_free(struct type *type, struct value *val)
1546         {
1547                 int i;
1548
1549                 for (i = 0; i < type->array.size; i++) {
1550                         struct value *v;
1551                         v = (void*)val->ptr + i * type->array.member->size;
1552                         free_value(type->array.member, v);
1553                 }
1554         }
1555
1556         static int array_compat(struct type *require, struct type *have)
1557         {
1558                 if (have->compat != require->compat)
1559                         return 0;
1560                 /* Both are arrays, so we can look at details */
1561                 if (!type_compat(require->array.member, have->array.member, 0))
1562                         return 0;
1563                 if (require->array.vsize == NULL && have->array.vsize == NULL)
1564                         return require->array.size == have->array.size;
1565
1566                 return require->array.vsize == have->array.vsize;
1567         }
1568
1569         static void array_print_type(struct type *type, FILE *f)
1570         {
1571                 fputs("[", f);
1572                 if (type->array.vsize) {
1573                         struct binding *b = type->array.vsize->name;
1574                         fprintf(f, "%.*s]", b->name.len, b->name.txt);
1575                 } else
1576                         fprintf(f, "%d]", type->array.size);
1577                 type_print(type->array.member, f);
1578         }
1579
1580         static struct type array_prototype = {
1581                 .init = array_init,
1582                 .prepare_type = array_prepare_type,
1583                 .print_type = array_print_type,
1584                 .compat = array_compat,
1585                 .free = array_free,
1586         };
1587
1588 ###### declare terminals
1589         $TERM [ ]
1590
1591 ###### type grammar
1592
1593         | [ NUMBER ] Type ${ {
1594                 char tail[3];
1595                 mpq_t num;
1596                 struct text noname = { "", 0 };
1597                 struct type *t;
1598
1599                 $0 = t = add_type(c, noname, &array_prototype);
1600                 t->array.member = $<4;
1601                 t->array.vsize = NULL;
1602                 if (number_parse(num, tail, $2.txt) == 0)
1603                         tok_err(c, "error: unrecognised number", &$2);
1604                 else if (tail[0])
1605                         tok_err(c, "error: unsupported number suffix", &$2);
1606                 else {
1607                         t->array.size = mpz_get_ui(mpq_numref(num));
1608                         if (mpz_cmp_ui(mpq_denref(num), 1) != 0) {
1609                                 tok_err(c, "error: array size must be an integer",
1610                                         &$2);
1611                         } else if (mpz_cmp_ui(mpq_numref(num), 1UL << 30) >= 0)
1612                                 tok_err(c, "error: array size is too large",
1613                                         &$2);
1614                         mpq_clear(num);
1615                 }
1616                 t->size = t->array.size * t->array.member->size;
1617                 t->align = t->array.member->align;
1618         } }$
1619
1620         | [ IDENTIFIER ] Type ${ {
1621                 struct variable *v = var_ref(c, $2.txt);
1622                 struct text noname = { "", 0 };
1623
1624                 if (!v)
1625                         tok_err(c, "error: name undeclared", &$2);
1626                 else if (!v->constant)
1627                         tok_err(c, "error: array size must be a constant", &$2);
1628
1629                 $0 = add_type(c, noname, &array_prototype);
1630                 $0->array.member = $<4;
1631                 $0->array.size = 0;
1632                 $0->array.vsize = v;
1633         } }$
1634
1635 ###### Binode types
1636         Index,
1637
1638 ###### variable grammar
1639
1640         | Variable [ Expression ] ${ {
1641                 struct binode *b = new(binode);
1642                 b->op = Index;
1643                 b->left = $<1;
1644                 b->right = $<3;
1645                 $0 = b;
1646         } }$
1647
1648 ###### print binode cases
1649         case Index:
1650                 print_exec(b->left, -1, bracket);
1651                 printf("[");
1652                 print_exec(b->right, -1, bracket);
1653                 printf("]");
1654                 break;
1655
1656 ###### propagate binode cases
1657         case Index:
1658                 /* left must be an array, right must be a number,
1659                  * result is the member type of the array
1660                  */
1661                 propagate_types(b->right, c, ok, Tnum, 0);
1662                 t = propagate_types(b->left, c, ok, NULL, rules & Rnoconstant);
1663                 if (!t || t->compat != array_compat) {
1664                         type_err(c, "error: %1 cannot be indexed", prog, t, 0, NULL);
1665                         return NULL;
1666                 } else {
1667                         if (!type_compat(type, t->array.member, rules)) {
1668                                 type_err(c, "error: have %1 but need %2", prog,
1669                                          t->array.member, rules, type);
1670                         }
1671                         return t->array.member;
1672                 }
1673                 break;
1674
1675 ###### interp binode cases
1676         case Index: {
1677                 mpz_t q;
1678                 long i;
1679
1680                 lleft = linterp_exec(b->left, &ltype);
1681                 right = interp_exec(b->right, &rtype);
1682                 mpz_init(q);
1683                 mpz_tdiv_q(q, mpq_numref(right.num), mpq_denref(right.num));
1684                 i = mpz_get_si(q);
1685                 mpz_clear(q);
1686
1687                 rvtype = ltype->array.member;
1688                 if (i >= 0 && i < ltype->array.size)
1689                         lrv = (void*)lleft + i * rvtype->size;
1690                 else
1691                         val_init(ltype->array.member, &rv);
1692                 ltype = NULL;
1693                 break;
1694         }
1695
1696 #### Structs
1697
1698 A `struct` is a data-type that contains one or more other data-types.
1699 It differs from an array in that each member can be of a different
1700 type, and they are accessed by name rather than by number.  Thus you
1701 cannot choose an element by calculation, you need to know what you
1702 want up-front.
1703
1704 The language makes no promises about how a given structure will be
1705 stored in memory - it is free to rearrange fields to suit whatever
1706 criteria seems important.
1707
1708 Structs are declared separately from program code - they cannot be
1709 declared in-line in a variable declaration like arrays can.  A struct
1710 is given a name and this name is used to identify the type - the name
1711 is not prefixed by the word `struct` as it would be in C.
1712
1713 Structs are only treated as the same if they have the same name.
1714 Simply having the same fields in the same order is not enough.  This
1715 might change once we can create structure initializers from a list of
1716 values.
1717
1718 Each component datum is identified much like a variable is declared,
1719 with a name, one or two colons, and a type.  The type cannot be omitted
1720 as there is no opportunity to deduce the type from usage.  An initial
1721 value can be given following an equals sign, so
1722
1723 ##### Example: a struct type
1724
1725         struct complex:
1726                 x:number = 0
1727                 y:number = 0
1728
1729 would declare a type called "complex" which has two number fields,
1730 each initialised to zero.
1731
1732 Struct will need to be declared separately from the code that uses
1733 them, so we will need to be able to print out the declaration of a
1734 struct when reprinting the whole program.  So a `print_type_decl` type
1735 function will be needed.
1736
1737 ###### type union fields
1738
1739         struct {
1740                 int nfields;
1741                 struct field {
1742                         struct text name;
1743                         struct type *type;
1744                         struct value *init;
1745                         int offset;
1746                 } *fields;
1747         } structure;
1748
1749 ###### type functions
1750         void (*print_type_decl)(struct type *type, FILE *f);
1751
1752 ###### value functions
1753
1754         static void structure_init(struct type *type, struct value *val)
1755         {
1756                 int i;
1757
1758                 for (i = 0; i < type->structure.nfields; i++) {
1759                         struct value *v;
1760                         v = (void*) val->ptr + type->structure.fields[i].offset;
1761                         val_init(type->structure.fields[i].type, v);
1762                 }
1763         }
1764
1765         static void structure_free(struct type *type, struct value *val)
1766         {
1767                 int i;
1768
1769                 for (i = 0; i < type->structure.nfields; i++) {
1770                         struct value *v;
1771                         v = (void*)val->ptr + type->structure.fields[i].offset;
1772                         free_value(type->structure.fields[i].type, v);
1773                 }
1774         }
1775
1776         static void structure_free_type(struct type *t)
1777         {
1778                 int i;
1779                 for (i = 0; i < t->structure.nfields; i++)
1780                         if (t->structure.fields[i].init) {
1781                                 free_value(t->structure.fields[i].type,
1782                                            t->structure.fields[i].init);
1783                                 free(t->structure.fields[i].init);
1784                         }
1785                 free(t->structure.fields);
1786         }
1787
1788         static struct type structure_prototype = {
1789                 .init = structure_init,
1790                 .free = structure_free,
1791                 .free_type = structure_free_type,
1792                 .print_type_decl = structure_print_type,
1793         };
1794
1795 ###### exec type
1796         Xfieldref,
1797
1798 ###### ast
1799         struct fieldref {
1800                 struct exec;
1801                 struct exec *left;
1802                 int index;
1803                 struct text name;
1804         };
1805
1806 ###### free exec cases
1807         case Xfieldref:
1808                 free_exec(cast(fieldref, e)->left);
1809                 free(e);
1810                 break;
1811
1812 ###### declare terminals
1813         $TERM struct .
1814
1815 ###### variable grammar
1816
1817         | Variable . IDENTIFIER ${ {
1818                 struct fieldref *fr = new_pos(fieldref, $2);
1819                 fr->left = $<1;
1820                 fr->name = $3.txt;
1821                 fr->index = -2;
1822                 $0 = fr;
1823         } }$
1824
1825 ###### print exec cases
1826
1827         case Xfieldref:
1828         {
1829                 struct fieldref *f = cast(fieldref, e);
1830                 print_exec(f->left, -1, bracket);
1831                 printf(".%.*s", f->name.len, f->name.txt);
1832                 break;
1833         }
1834
1835 ###### ast functions
1836         static int find_struct_index(struct type *type, struct text field)
1837         {
1838                 int i;
1839                 for (i = 0; i < type->structure.nfields; i++)
1840                         if (text_cmp(type->structure.fields[i].name, field) == 0)
1841                                 return i;
1842                 return -1;
1843         }
1844
1845 ###### propagate exec cases
1846
1847         case Xfieldref:
1848         {
1849                 struct fieldref *f = cast(fieldref, prog);
1850                 struct type *st = propagate_types(f->left, c, ok, NULL, 0);
1851
1852                 if (!st)
1853                         type_err(c, "error: unknown type for field access", f->left,
1854                                  NULL, 0, NULL);
1855                 else if (st->init != structure_init)
1856                         type_err(c, "error: field reference attempted on %1, not a struct",
1857                                  f->left, st, 0, NULL);
1858                 else if (f->index == -2) {
1859                         f->index = find_struct_index(st, f->name);
1860                         if (f->index < 0)
1861                                 type_err(c, "error: cannot find requested field in %1",
1862                                          f->left, st, 0, NULL);
1863                 }
1864                 if (f->index >= 0) {
1865                         struct type *ft = st->structure.fields[f->index].type;
1866                         if (!type_compat(type, ft, rules))
1867                                 type_err(c, "error: have %1 but need %2", prog,
1868                                          ft, rules, type);
1869                         return ft;
1870                 }
1871                 break;
1872         }
1873
1874 ###### interp exec cases
1875         case Xfieldref:
1876         {
1877                 struct fieldref *f = cast(fieldref, e);
1878                 struct type *ltype;
1879                 struct value *lleft = linterp_exec(f->left, &ltype);
1880                 lrv = (void*)lleft->ptr + ltype->structure.fields[f->index].offset;
1881                 rvtype = ltype->structure.fields[f->index].type;
1882                 break;
1883         }
1884
1885 ###### ast
1886         struct fieldlist {
1887                 struct fieldlist *prev;
1888                 struct field f;
1889         };
1890
1891 ###### ast functions
1892         static void free_fieldlist(struct fieldlist *f)
1893         {
1894                 if (!f)
1895                         return;
1896                 free_fieldlist(f->prev);
1897                 if (f->f.init) {
1898                         free_value(f->f.type, f->f.init);
1899                         free(f->f.init);
1900                 }
1901                 free(f);
1902         }
1903
1904 ###### top level grammar
1905         DeclareStruct -> struct IDENTIFIER FieldBlock Newlines ${ {
1906                         struct type *t =
1907                                 add_type(c, $2.txt, &structure_prototype);
1908                         int cnt = 0;
1909                         struct fieldlist *f;
1910
1911                         for (f = $3; f; f=f->prev)
1912                                 cnt += 1;
1913
1914                         t->structure.nfields = cnt;
1915                         t->structure.fields = calloc(cnt, sizeof(struct field));
1916                         f = $3;
1917                         while (cnt > 0) {
1918                                 int a = f->f.type->align;
1919                                 cnt -= 1;
1920                                 t->structure.fields[cnt] = f->f;
1921                                 if (t->size & (a-1))
1922                                         t->size = (t->size | (a-1)) + 1;
1923                                 t->structure.fields[cnt].offset = t->size;
1924                                 t->size += ((f->f.type->size - 1) | (a-1)) + 1;
1925                                 if (a > t->align)
1926                                         t->align = a;
1927                                 f->f.init = NULL;
1928                                 f = f->prev;
1929                         }
1930                 } }$
1931
1932         $*fieldlist
1933         FieldBlock -> { IN OptNL FieldLines OUT OptNL } ${ $0 = $<FL; }$
1934                 | { SimpleFieldList } ${ $0 = $<SFL; }$
1935                 | IN OptNL FieldLines OUT ${ $0 = $<FL; }$
1936                 | SimpleFieldList EOL ${ $0 = $<SFL; }$
1937
1938         FieldLines -> SimpleFieldList Newlines ${ $0 = $<SFL; }$
1939                 | FieldLines SimpleFieldList Newlines ${
1940                         $SFL->prev = $<FL;
1941                         $0 = $<SFL;
1942                 }$
1943
1944         SimpleFieldList -> Field ${ $0 = $<F; }$
1945                 | SimpleFieldList ; Field ${
1946                         $F->prev = $<SFL;
1947                         $0 = $<F;
1948                 }$
1949                 | SimpleFieldList ; ${
1950                         $0 = $<SFL;
1951                 }$
1952                 | ERROR ${ tok_err(c, "Syntax error in struct field", &$1); }$
1953
1954         Field -> IDENTIFIER : Type = Expression ${ {
1955                         int ok;
1956
1957                         $0 = calloc(1, sizeof(struct fieldlist));
1958                         $0->f.name = $1.txt;
1959                         $0->f.type = $<3;
1960                         $0->f.init = NULL;
1961                         do {
1962                                 ok = 1;
1963                                 propagate_types($<5, c, &ok, $3, 0);
1964                         } while (ok == 2);
1965                         if (!ok)
1966                                 c->parse_error = 1;
1967                         else {
1968                                 struct value vl = interp_exec($5, NULL);
1969                                 $0->f.init = val_alloc($0->f.type, &vl);
1970                         }
1971                 } }$
1972                 | IDENTIFIER : Type ${
1973                         $0 = calloc(1, sizeof(struct fieldlist));
1974                         $0->f.name = $1.txt;
1975                         $0->f.type = $<3;
1976                         $0->f.init = val_alloc($0->f.type, NULL);
1977                 }$
1978
1979 ###### forward decls
1980         static void structure_print_type(struct type *t, FILE *f);
1981
1982 ###### value functions
1983         static void structure_print_type(struct type *t, FILE *f)
1984         {
1985                 int i;
1986
1987                 fprintf(f, "struct %.*s\n", t->name.len, t->name.txt);
1988
1989                 for (i = 0; i < t->structure.nfields; i++) {
1990                         struct field *fl = t->structure.fields + i;
1991                         fprintf(f, "    %.*s : ", fl->name.len, fl->name.txt);
1992                         type_print(fl->type, f);
1993                         if (fl->type->print && fl->init) {
1994                                 fprintf(f, " = ");
1995                                 if (fl->type == Tstr)
1996                                         fprintf(f, "\"");
1997                                 print_value(fl->type, fl->init);
1998                                 if (fl->type == Tstr)
1999                                         fprintf(f, "\"");
2000                         }
2001                         printf("\n");
2002                 }
2003         }
2004
2005 ###### print type decls
2006         {
2007                 struct type *t;
2008                 int target = -1;
2009
2010                 while (target != 0) {
2011                         int i = 0;
2012                         for (t = context.typelist; t ; t=t->next)
2013                                 if (t->print_type_decl) {
2014                                         i += 1;
2015                                         if (i == target)
2016                                                 break;
2017                                 }
2018
2019                         if (target == -1) {
2020                                 target = i;
2021                         } else {
2022                                 t->print_type_decl(t, stdout);
2023                                 target -= 1;
2024                         }
2025                 }
2026         }
2027
2028 ## Executables: the elements of code
2029
2030 Each code element needs to be parsed, printed, analysed,
2031 interpreted, and freed.  There are several, so let's just start with
2032 the easy ones and work our way up.
2033
2034 ### Values
2035
2036 We have already met values as separate objects.  When manifest
2037 constants appear in the program text, that must result in an executable
2038 which has a constant value.  So the `val` structure embeds a value in
2039 an executable.
2040
2041 ###### exec type
2042         Xval,
2043
2044 ###### ast
2045         struct val {
2046                 struct exec;
2047                 struct type *vtype;
2048                 struct value val;
2049         };
2050
2051 ###### ast functions
2052         struct val *new_val(struct type *T, struct token tk)
2053         {
2054                 struct val *v = new_pos(val, tk);
2055                 v->vtype = T;
2056                 return v;
2057         }
2058
2059 ###### Grammar
2060
2061         $TERM True False
2062
2063         $*val
2064         Value ->  True ${
2065                         $0 = new_val(Tbool, $1);
2066                         $0->val.bool = 1;
2067                         }$
2068                 | False ${
2069                         $0 = new_val(Tbool, $1);
2070                         $0->val.bool = 0;
2071                         }$
2072                 | NUMBER ${
2073                         $0 = new_val(Tnum, $1);
2074                         {
2075                         char tail[3];
2076                         if (number_parse($0->val.num, tail, $1.txt) == 0)
2077                                 mpq_init($0->val.num);
2078                                 if (tail[0])
2079                                         tok_err(c, "error: unsupported number suffix",
2080                                                 &$1);
2081                         }
2082                         }$
2083                 | STRING ${
2084                         $0 = new_val(Tstr, $1);
2085                         {
2086                         char tail[3];
2087                         string_parse(&$1, '\\', &$0->val.str, tail);
2088                         if (tail[0])
2089                                 tok_err(c, "error: unsupported string suffix",
2090                                         &$1);
2091                         }
2092                         }$
2093                 | MULTI_STRING ${
2094                         $0 = new_val(Tstr, $1);
2095                         {
2096                         char tail[3];
2097                         string_parse(&$1, '\\', &$0->val.str, tail);
2098                         if (tail[0])
2099                                 tok_err(c, "error: unsupported string suffix",
2100                                         &$1);
2101                         }
2102                         }$
2103
2104 ###### print exec cases
2105         case Xval:
2106         {
2107                 struct val *v = cast(val, e);
2108                 if (v->vtype == Tstr)
2109                         printf("\"");
2110                 print_value(v->vtype, &v->val);
2111                 if (v->vtype == Tstr)
2112                         printf("\"");
2113                 break;
2114         }
2115
2116 ###### propagate exec cases
2117         case Xval:
2118         {
2119                 struct val *val = cast(val, prog);
2120                 if (!type_compat(type, val->vtype, rules))
2121                         type_err(c, "error: expected %1%r found %2",
2122                                    prog, type, rules, val->vtype);
2123                 return val->vtype;
2124         }
2125
2126 ###### interp exec cases
2127         case Xval:
2128                 rvtype = cast(val, e)->vtype;
2129                 dup_value(rvtype, &cast(val, e)->val, &rv);
2130                 break;
2131
2132 ###### ast functions
2133         static void free_val(struct val *v)
2134         {
2135                 if (v)
2136                         free_value(v->vtype, &v->val);
2137                 free(v);
2138         }
2139
2140 ###### free exec cases
2141         case Xval: free_val(cast(val, e)); break;
2142
2143 ###### ast functions
2144         // Move all nodes from 'b' to 'rv', reversing their order.
2145         // In 'b' 'left' is a list, and 'right' is the last node.
2146         // In 'rv', left' is the first node and 'right' is a list.
2147         static struct binode *reorder_bilist(struct binode *b)
2148         {
2149                 struct binode *rv = NULL;
2150
2151                 while (b) {
2152                         struct exec *t = b->right;
2153                         b->right = rv;
2154                         rv = b;
2155                         if (b->left)
2156                                 b = cast(binode, b->left);
2157                         else
2158                                 b = NULL;
2159                         rv->left = t;
2160                 }
2161                 return rv;
2162         }
2163
2164 ### Variables
2165
2166 Just as we used a `val` to wrap a value into an `exec`, we similarly
2167 need a `var` to wrap a `variable` into an exec.  While each `val`
2168 contained a copy of the value, each `var` holds a link to the variable
2169 because it really is the same variable no matter where it appears.
2170 When a variable is used, we need to remember to follow the `->merged`
2171 link to find the primary instance.
2172
2173 ###### exec type
2174         Xvar,
2175
2176 ###### ast
2177         struct var {
2178                 struct exec;
2179                 struct variable *var;
2180         };
2181
2182 ###### Grammar
2183
2184         $TERM : ::
2185
2186         $*var
2187         VariableDecl -> IDENTIFIER : ${ {
2188                 struct variable *v = var_decl(c, $1.txt);
2189                 $0 = new_pos(var, $1);
2190                 $0->var = v;
2191                 if (v)
2192                         v->where_decl = $0;
2193                 else {
2194                         v = var_ref(c, $1.txt);
2195                         $0->var = v;
2196                         type_err(c, "error: variable '%v' redeclared",
2197                                  $0, NULL, 0, NULL);
2198                         type_err(c, "info: this is where '%v' was first declared",
2199                                  v->where_decl, NULL, 0, NULL);
2200                 }
2201         } }$
2202             | IDENTIFIER :: ${ {
2203                 struct variable *v = var_decl(c, $1.txt);
2204                 $0 = new_pos(var, $1);
2205                 $0->var = v;
2206                 if (v) {
2207                         v->where_decl = $0;
2208                         v->constant = 1;
2209                 } else {
2210                         v = var_ref(c, $1.txt);
2211                         $0->var = v;
2212                         type_err(c, "error: variable '%v' redeclared",
2213                                  $0, NULL, 0, NULL);
2214                         type_err(c, "info: this is where '%v' was first declared",
2215                                  v->where_decl, NULL, 0, NULL);
2216                 }
2217         } }$
2218             | IDENTIFIER : Type ${ {
2219                 struct variable *v = var_decl(c, $1.txt);
2220                 $0 = new_pos(var, $1);
2221                 $0->var = v;
2222                 if (v) {
2223                         v->where_decl = $0;
2224                         v->where_set = $0;
2225                         v->type = $<Type;
2226                         v->val = NULL;
2227                 } else {
2228                         v = var_ref(c, $1.txt);
2229                         $0->var = v;
2230                         type_err(c, "error: variable '%v' redeclared",
2231                                  $0, NULL, 0, NULL);
2232                         type_err(c, "info: this is where '%v' was first declared",
2233                                  v->where_decl, NULL, 0, NULL);
2234                 }
2235         } }$
2236             | IDENTIFIER :: Type ${ {
2237                 struct variable *v = var_decl(c, $1.txt);
2238                 $0 = new_pos(var, $1);
2239                 $0->var = v;
2240                 if (v) {
2241                         v->where_decl = $0;
2242                         v->where_set = $0;
2243                         v->type = $<Type;
2244                         v->val = NULL;
2245                         v->constant = 1;
2246                 } else {
2247                         v = var_ref(c, $1.txt);
2248                         $0->var = v;
2249                         type_err(c, "error: variable '%v' redeclared",
2250                                  $0, NULL, 0, NULL);
2251                         type_err(c, "info: this is where '%v' was first declared",
2252                                  v->where_decl, NULL, 0, NULL);
2253                 }
2254         } }$
2255
2256         $*exec
2257         Variable -> IDENTIFIER ${ {
2258                 struct variable *v = var_ref(c, $1.txt);
2259                 $0 = new_pos(var, $1);
2260                 if (v == NULL) {
2261                         /* This might be a label - allocate a var just in case */
2262                         v = var_decl(c, $1.txt);
2263                         if (v) {
2264                                 v->val = NULL;
2265                                 v->type = Tnone;
2266                                 v->where_decl = $0;
2267                                 v->where_set = $0;
2268                         }
2269                 }
2270                 cast(var, $0)->var = v;
2271         } }$
2272         ## variable grammar
2273
2274         $*type
2275         Type -> IDENTIFIER ${
2276                 $0 = find_type(c, $1.txt);
2277                 if (!$0) {
2278                         tok_err(c,
2279                                 "error: undefined type", &$1);
2280
2281                         $0 = Tnone;
2282                 }
2283         }$
2284         ## type grammar
2285
2286 ###### print exec cases
2287         case Xvar:
2288         {
2289                 struct var *v = cast(var, e);
2290                 if (v->var) {
2291                         struct binding *b = v->var->name;
2292                         printf("%.*s", b->name.len, b->name.txt);
2293                 }
2294                 break;
2295         }
2296
2297 ###### format cases
2298         case 'v':
2299                 if (loc->type == Xvar) {
2300                         struct var *v = cast(var, loc);
2301                         if (v->var) {
2302                                 struct binding *b = v->var->name;
2303                                 fprintf(stderr, "%.*s", b->name.len, b->name.txt);
2304                         } else
2305                                 fputs("???", stderr);   // NOTEST
2306                 } else
2307                         fputs("NOTVAR", stderr);        // NOTEST
2308                 break;
2309
2310 ###### propagate exec cases
2311
2312         case Xvar:
2313         {
2314                 struct var *var = cast(var, prog);
2315                 struct variable *v = var->var;
2316                 if (!v) {
2317                         type_err(c, "%d:BUG: no variable!!", prog, NULL, 0, NULL); // NOTEST
2318                         return Tnone;                                   // NOTEST
2319                 }
2320                 if (v->merged)
2321                         v = v->merged;
2322                 if (v->constant && (rules & Rnoconstant)) {
2323                         type_err(c, "error: Cannot assign to a constant: %v",
2324                                  prog, NULL, 0, NULL);
2325                         type_err(c, "info: name was defined as a constant here",
2326                                  v->where_decl, NULL, 0, NULL);
2327                         return v->type;
2328                 }
2329                 if (v->type == Tnone && v->where_decl == prog)
2330                         type_err(c, "error: variable used but not declared: %v",
2331                                  prog, NULL, 0, NULL);
2332                 if (v->type == NULL) {
2333                         if (type && *ok != 0) {
2334                                 v->type = type;
2335                                 v->val = NULL;
2336                                 v->where_set = prog;
2337                                 *ok = 2;
2338                         }
2339                         return type;
2340                 }
2341                 if (!type_compat(type, v->type, rules)) {
2342                         type_err(c, "error: expected %1%r but variable '%v' is %2", prog,
2343                                  type, rules, v->type);
2344                         type_err(c, "info: this is where '%v' was set to %1", v->where_set,
2345                                  v->type, rules, NULL);
2346                 }
2347                 if (!type)
2348                         return v->type;
2349                 return type;
2350         }
2351
2352 ###### interp exec cases
2353         case Xvar:
2354         {
2355                 struct var *var = cast(var, e);
2356                 struct variable *v = var->var;
2357
2358                 if (v->merged)
2359                         v = v->merged;
2360                 lrv = v->val;
2361                 rvtype = v->type;
2362                 break;
2363         }
2364
2365 ###### ast functions
2366
2367         static void free_var(struct var *v)
2368         {
2369                 free(v);
2370         }
2371
2372 ###### free exec cases
2373         case Xvar: free_var(cast(var, e)); break;
2374
2375 ### Expressions: Conditional
2376
2377 Our first user of the `binode` will be conditional expressions, which
2378 is a bit odd as they actually have three components.  That will be
2379 handled by having 2 binodes for each expression.  The conditional
2380 expression is the lowest precedence operator which is why we define it
2381 first - to start the precedence list.
2382
2383 Conditional expressions are of the form "value `if` condition `else`
2384 other_value".  They associate to the right, so everything to the right
2385 of `else` is part of an else value, while only a higher-precedence to
2386 the left of `if` is the if values.  Between `if` and `else` there is no
2387 room for ambiguity, so a full conditional expression is allowed in
2388 there.
2389
2390 ###### Binode types
2391         CondExpr,
2392
2393 ###### Grammar
2394
2395         $LEFT if $$ifelse
2396         ## expr precedence
2397
2398         $*exec
2399         Expression -> Expression if Expression else Expression $$ifelse ${ {
2400                         struct binode *b1 = new(binode);
2401                         struct binode *b2 = new(binode);
2402                         b1->op = CondExpr;
2403                         b1->left = $<3;
2404                         b1->right = b2;
2405                         b2->op = CondExpr;
2406                         b2->left = $<1;
2407                         b2->right = $<5;
2408                         $0 = b1;
2409                 } }$
2410                 ## expression grammar
2411
2412 ###### print binode cases
2413
2414         case CondExpr:
2415                 b2 = cast(binode, b->right);
2416                 if (bracket) printf("(");
2417                 print_exec(b2->left, -1, bracket);
2418                 printf(" if ");
2419                 print_exec(b->left, -1, bracket);
2420                 printf(" else ");
2421                 print_exec(b2->right, -1, bracket);
2422                 if (bracket) printf(")");
2423                 break;
2424
2425 ###### propagate binode cases
2426
2427         case CondExpr: {
2428                 /* cond must be Tbool, others must match */
2429                 struct binode *b2 = cast(binode, b->right);
2430                 struct type *t2;
2431
2432                 propagate_types(b->left, c, ok, Tbool, 0);
2433                 t = propagate_types(b2->left, c, ok, type, Rnolabel);
2434                 t2 = propagate_types(b2->right, c, ok, type ?: t, Rnolabel);
2435                 return t ?: t2;
2436         }
2437
2438 ###### interp binode cases
2439
2440         case CondExpr: {
2441                 struct binode *b2 = cast(binode, b->right);
2442                 left = interp_exec(b->left, &ltype);
2443                 if (left.bool)
2444                         rv = interp_exec(b2->left, &rvtype);
2445                 else
2446                         rv = interp_exec(b2->right, &rvtype);
2447                 }
2448                 break;
2449
2450 ### Expressions: Boolean
2451
2452 The next class of expressions to use the `binode` will be Boolean
2453 expressions.  "`and then`" and "`or else`" are similar to `and` and `or`
2454 have same corresponding precendence.  The difference is that they don't
2455 evaluate the second expression if not necessary.
2456
2457 ###### Binode types
2458         And,
2459         AndThen,
2460         Or,
2461         OrElse,
2462         Not,
2463
2464 ###### expr precedence
2465         $LEFT or
2466         $LEFT and
2467         $LEFT not
2468
2469 ###### expression grammar
2470                 | Expression or Expression ${ {
2471                         struct binode *b = new(binode);
2472                         b->op = Or;
2473                         b->left = $<1;
2474                         b->right = $<3;
2475                         $0 = b;
2476                 } }$
2477                 | Expression or else Expression ${ {
2478                         struct binode *b = new(binode);
2479                         b->op = OrElse;
2480                         b->left = $<1;
2481                         b->right = $<4;
2482                         $0 = b;
2483                 } }$
2484
2485                 | Expression and Expression ${ {
2486                         struct binode *b = new(binode);
2487                         b->op = And;
2488                         b->left = $<1;
2489                         b->right = $<3;
2490                         $0 = b;
2491                 } }$
2492                 | Expression and then Expression ${ {
2493                         struct binode *b = new(binode);
2494                         b->op = AndThen;
2495                         b->left = $<1;
2496                         b->right = $<4;
2497                         $0 = b;
2498                 } }$
2499
2500                 | not Expression ${ {
2501                         struct binode *b = new(binode);
2502                         b->op = Not;
2503                         b->right = $<2;
2504                         $0 = b;
2505                 } }$
2506
2507 ###### print binode cases
2508         case And:
2509                 if (bracket) printf("(");
2510                 print_exec(b->left, -1, bracket);
2511                 printf(" and ");
2512                 print_exec(b->right, -1, bracket);
2513                 if (bracket) printf(")");
2514                 break;
2515         case AndThen:
2516                 if (bracket) printf("(");
2517                 print_exec(b->left, -1, bracket);
2518                 printf(" and then ");
2519                 print_exec(b->right, -1, bracket);
2520                 if (bracket) printf(")");
2521                 break;
2522         case Or:
2523                 if (bracket) printf("(");
2524                 print_exec(b->left, -1, bracket);
2525                 printf(" or ");
2526                 print_exec(b->right, -1, bracket);
2527                 if (bracket) printf(")");
2528                 break;
2529         case OrElse:
2530                 if (bracket) printf("(");
2531                 print_exec(b->left, -1, bracket);
2532                 printf(" or else ");
2533                 print_exec(b->right, -1, bracket);
2534                 if (bracket) printf(")");
2535                 break;
2536         case Not:
2537                 if (bracket) printf("(");
2538                 printf("not ");
2539                 print_exec(b->right, -1, bracket);
2540                 if (bracket) printf(")");
2541                 break;
2542
2543 ###### propagate binode cases
2544         case And:
2545         case AndThen:
2546         case Or:
2547         case OrElse:
2548         case Not:
2549                 /* both must be Tbool, result is Tbool */
2550                 propagate_types(b->left, c, ok, Tbool, 0);
2551                 propagate_types(b->right, c, ok, Tbool, 0);
2552                 if (type && type != Tbool)
2553                         type_err(c, "error: %1 operation found where %2 expected", prog,
2554                                    Tbool, 0, type);
2555                 return Tbool;
2556
2557 ###### interp binode cases
2558         case And:
2559                 rv = interp_exec(b->left, &rvtype);
2560                 right = interp_exec(b->right, &rtype);
2561                 rv.bool = rv.bool && right.bool;
2562                 break;
2563         case AndThen:
2564                 rv = interp_exec(b->left, &rvtype);
2565                 if (rv.bool)
2566                         rv = interp_exec(b->right, NULL);
2567                 break;
2568         case Or:
2569                 rv = interp_exec(b->left, &rvtype);
2570                 right = interp_exec(b->right, &rtype);
2571                 rv.bool = rv.bool || right.bool;
2572                 break;
2573         case OrElse:
2574                 rv = interp_exec(b->left, &rvtype);
2575                 if (!rv.bool)
2576                         rv = interp_exec(b->right, NULL);
2577                 break;
2578         case Not:
2579                 rv = interp_exec(b->right, &rvtype);
2580                 rv.bool = !rv.bool;
2581                 break;
2582
2583 ### Expressions: Comparison
2584
2585 Of slightly higher precedence that Boolean expressions are Comparisons.
2586 A comparison takes arguments of any comparable type, but the two types
2587 must be the same.
2588
2589 To simplify the parsing we introduce an `eop` which can record an
2590 expression operator, and the `CMPop` non-terminal will match one of them.
2591
2592 ###### ast
2593         struct eop {
2594                 enum Btype op;
2595         };
2596
2597 ###### ast functions
2598         static void free_eop(struct eop *e)
2599         {
2600                 if (e)
2601                         free(e);
2602         }
2603
2604 ###### Binode types
2605         Less,
2606         Gtr,
2607         LessEq,
2608         GtrEq,
2609         Eql,
2610         NEql,
2611
2612 ###### expr precedence
2613         $LEFT < > <= >= == != CMPop
2614
2615 ###### expression grammar
2616         | Expression CMPop Expression ${ {
2617                 struct binode *b = new(binode);
2618                 b->op = $2.op;
2619                 b->left = $<1;
2620                 b->right = $<3;
2621                 $0 = b;
2622         } }$
2623
2624 ###### Grammar
2625
2626         $eop
2627         CMPop ->   < ${ $0.op = Less; }$
2628                 |  > ${ $0.op = Gtr; }$
2629                 |  <= ${ $0.op = LessEq; }$
2630                 |  >= ${ $0.op = GtrEq; }$
2631                 |  == ${ $0.op = Eql; }$
2632                 |  != ${ $0.op = NEql; }$
2633
2634 ###### print binode cases
2635
2636         case Less:
2637         case LessEq:
2638         case Gtr:
2639         case GtrEq:
2640         case Eql:
2641         case NEql:
2642                 if (bracket) printf("(");
2643                 print_exec(b->left, -1, bracket);
2644                 switch(b->op) {
2645                 case Less:   printf(" < "); break;
2646                 case LessEq: printf(" <= "); break;
2647                 case Gtr:    printf(" > "); break;
2648                 case GtrEq:  printf(" >= "); break;
2649                 case Eql:    printf(" == "); break;
2650                 case NEql:   printf(" != "); break;
2651                 default: abort();               // NOTEST
2652                 }
2653                 print_exec(b->right, -1, bracket);
2654                 if (bracket) printf(")");
2655                 break;
2656
2657 ###### propagate binode cases
2658         case Less:
2659         case LessEq:
2660         case Gtr:
2661         case GtrEq:
2662         case Eql:
2663         case NEql:
2664                 /* Both must match but not be labels, result is Tbool */
2665                 t = propagate_types(b->left, c, ok, NULL, Rnolabel);
2666                 if (t)
2667                         propagate_types(b->right, c, ok, t, 0);
2668                 else {
2669                         t = propagate_types(b->right, c, ok, NULL, Rnolabel);
2670                         if (t)
2671                                 t = propagate_types(b->left, c, ok, t, 0);
2672                 }
2673                 if (!type_compat(type, Tbool, 0))
2674                         type_err(c, "error: Comparison returns %1 but %2 expected", prog,
2675                                     Tbool, rules, type);
2676                 return Tbool;
2677
2678 ###### interp binode cases
2679         case Less:
2680         case LessEq:
2681         case Gtr:
2682         case GtrEq:
2683         case Eql:
2684         case NEql:
2685         {
2686                 int cmp;
2687                 left = interp_exec(b->left, &ltype);
2688                 right = interp_exec(b->right, &rtype);
2689                 cmp = value_cmp(ltype, rtype, &left, &right);
2690                 rvtype = Tbool;
2691                 switch (b->op) {
2692                 case Less:      rv.bool = cmp <  0; break;
2693                 case LessEq:    rv.bool = cmp <= 0; break;
2694                 case Gtr:       rv.bool = cmp >  0; break;
2695                 case GtrEq:     rv.bool = cmp >= 0; break;
2696                 case Eql:       rv.bool = cmp == 0; break;
2697                 case NEql:      rv.bool = cmp != 0; break;
2698                 default:        rv.bool = 0; break;     // NOTEST
2699                 }
2700                 break;
2701         }
2702
2703 ### Expressions: The rest
2704
2705 The remaining expressions with the highest precedence are arithmetic,
2706 string concatenation, and string conversion.  String concatenation
2707 (`++`) has the same precedence as multiplication and division, but lower
2708 than the uniary.
2709
2710 String conversion is a temporary feature until I get a better type
2711 system.  `$` is a prefix operator which expects a string and returns
2712 a number.
2713
2714 `+` and `-` are both infix and prefix operations (where they are
2715 absolute value and negation).  These have different operator names.
2716
2717 We also have a 'Bracket' operator which records where parentheses were
2718 found.  This makes it easy to reproduce these when printing.  Possibly I
2719 should only insert brackets were needed for precedence.
2720
2721 ###### Binode types
2722         Plus, Minus,
2723         Times, Divide, Rem,
2724         Concat,
2725         Absolute, Negate,
2726         StringConv,
2727         Bracket,
2728
2729 ###### expr precedence
2730         $LEFT + - Eop
2731         $LEFT * / % ++ Top
2732         $LEFT Uop $
2733         $TERM ( )
2734
2735 ###### expression grammar
2736                 | Expression Eop Expression ${ {
2737                         struct binode *b = new(binode);
2738                         b->op = $2.op;
2739                         b->left = $<1;
2740                         b->right = $<3;
2741                         $0 = b;
2742                 } }$
2743
2744                 | Expression Top Expression ${ {
2745                         struct binode *b = new(binode);
2746                         b->op = $2.op;
2747                         b->left = $<1;
2748                         b->right = $<3;
2749                         $0 = b;
2750                 } }$
2751
2752                 | ( Expression ) ${ {
2753                         struct binode *b = new_pos(binode, $1);
2754                         b->op = Bracket;
2755                         b->right = $<2;
2756                         $0 = b;
2757                 } }$
2758                 | Uop Expression ${ {
2759                         struct binode *b = new(binode);
2760                         b->op = $1.op;
2761                         b->right = $<2;
2762                         $0 = b;
2763                 } }$
2764                 | Value ${ $0 = $<1; }$
2765                 | Variable ${ $0 = $<1; }$
2766
2767         $eop
2768         Eop ->    + ${ $0.op = Plus; }$
2769                 | - ${ $0.op = Minus; }$
2770
2771         Uop ->    + ${ $0.op = Absolute; }$
2772                 | - ${ $0.op = Negate; }$
2773                 | $ ${ $0.op = StringConv; }$
2774
2775         Top ->    * ${ $0.op = Times; }$
2776                 | / ${ $0.op = Divide; }$
2777                 | % ${ $0.op = Rem; }$
2778                 | ++ ${ $0.op = Concat; }$
2779
2780 ###### print binode cases
2781         case Plus:
2782         case Minus:
2783         case Times:
2784         case Divide:
2785         case Concat:
2786         case Rem:
2787                 if (bracket) printf("(");
2788                 print_exec(b->left, indent, bracket);
2789                 switch(b->op) {
2790                 case Plus:   fputs(" + ", stdout); break;
2791                 case Minus:  fputs(" - ", stdout); break;
2792                 case Times:  fputs(" * ", stdout); break;
2793                 case Divide: fputs(" / ", stdout); break;
2794                 case Rem:    fputs(" % ", stdout); break;
2795                 case Concat: fputs(" ++ ", stdout); break;
2796                 default: abort();       // NOTEST
2797                 }                       // NOTEST
2798                 print_exec(b->right, indent, bracket);
2799                 if (bracket) printf(")");
2800                 break;
2801         case Absolute:
2802         case Negate:
2803         case StringConv:
2804                 if (bracket) printf("(");
2805                 switch (b->op) {
2806                 case Absolute:   fputs("+", stdout); break;
2807                 case Negate:     fputs("-", stdout); break;
2808                 case StringConv: fputs("$", stdout); break;
2809                 default: abort();       // NOTEST
2810                 }                       // NOTEST
2811                 print_exec(b->right, indent, bracket);
2812                 if (bracket) printf(")");
2813                 break;
2814         case Bracket:
2815                 printf("(");
2816                 print_exec(b->right, indent, bracket);
2817                 printf(")");
2818                 break;
2819
2820 ###### propagate binode cases
2821         case Plus:
2822         case Minus:
2823         case Times:
2824         case Rem:
2825         case Divide:
2826                 /* both must be numbers, result is Tnum */
2827         case Absolute:
2828         case Negate:
2829                 /* as propagate_types ignores a NULL,
2830                  * unary ops fit here too */
2831                 propagate_types(b->left, c, ok, Tnum, 0);
2832                 propagate_types(b->right, c, ok, Tnum, 0);
2833                 if (!type_compat(type, Tnum, 0))
2834                         type_err(c, "error: Arithmetic returns %1 but %2 expected", prog,
2835                                    Tnum, rules, type);
2836                 return Tnum;
2837
2838         case Concat:
2839                 /* both must be Tstr, result is Tstr */
2840                 propagate_types(b->left, c, ok, Tstr, 0);
2841                 propagate_types(b->right, c, ok, Tstr, 0);
2842                 if (!type_compat(type, Tstr, 0))
2843                         type_err(c, "error: Concat returns %1 but %2 expected", prog,
2844                                    Tstr, rules, type);
2845                 return Tstr;
2846
2847         case StringConv:
2848                 /* op must be string, result is number */
2849                 propagate_types(b->left, c, ok, Tstr, 0);
2850                 if (!type_compat(type, Tnum, 0))
2851                         type_err(c,
2852                           "error: Can only convert string to number, not %1",
2853                                 prog, type, 0, NULL);
2854                 return Tnum;
2855
2856         case Bracket:
2857                 return propagate_types(b->right, c, ok, type, 0);
2858
2859 ###### interp binode cases
2860
2861         case Plus:
2862                 rv = interp_exec(b->left, &rvtype);
2863                 right = interp_exec(b->right, &rtype);
2864                 mpq_add(rv.num, rv.num, right.num);
2865                 break;
2866         case Minus:
2867                 rv = interp_exec(b->left, &rvtype);
2868                 right = interp_exec(b->right, &rtype);
2869                 mpq_sub(rv.num, rv.num, right.num);
2870                 break;
2871         case Times:
2872                 rv = interp_exec(b->left, &rvtype);
2873                 right = interp_exec(b->right, &rtype);
2874                 mpq_mul(rv.num, rv.num, right.num);
2875                 break;
2876         case Divide:
2877                 rv = interp_exec(b->left, &rvtype);
2878                 right = interp_exec(b->right, &rtype);
2879                 mpq_div(rv.num, rv.num, right.num);
2880                 break;
2881         case Rem: {
2882                 mpz_t l, r, rem;
2883
2884                 left = interp_exec(b->left, &ltype);
2885                 right = interp_exec(b->right, &rtype);
2886                 mpz_init(l); mpz_init(r); mpz_init(rem);
2887                 mpz_tdiv_q(l, mpq_numref(left.num), mpq_denref(left.num));
2888                 mpz_tdiv_q(r, mpq_numref(right.num), mpq_denref(right.num));
2889                 mpz_tdiv_r(rem, l, r);
2890                 val_init(Tnum, &rv);
2891                 mpq_set_z(rv.num, rem);
2892                 mpz_clear(r); mpz_clear(l); mpz_clear(rem);
2893                 rvtype = ltype;
2894                 break;
2895         }
2896         case Negate:
2897                 rv = interp_exec(b->right, &rvtype);
2898                 mpq_neg(rv.num, rv.num);
2899                 break;
2900         case Absolute:
2901                 rv = interp_exec(b->right, &rvtype);
2902                 mpq_abs(rv.num, rv.num);
2903                 break;
2904         case Bracket:
2905                 rv = interp_exec(b->right, &rvtype);
2906                 break;
2907         case Concat:
2908                 left = interp_exec(b->left, &ltype);
2909                 right = interp_exec(b->right, &rtype);
2910                 rvtype = Tstr;
2911                 rv.str = text_join(left.str, right.str);
2912                 break;
2913         case StringConv:
2914                 right = interp_exec(b->right, &rvtype);
2915                 rtype = Tstr;
2916                 rvtype = Tnum;
2917
2918                 struct text tx = right.str;
2919                 char tail[3];
2920                 int neg = 0;
2921                 if (tx.txt[0] == '-') {
2922                         neg = 1;
2923                         tx.txt++;
2924                         tx.len--;
2925                 }
2926                 if (number_parse(rv.num, tail, tx) == 0)
2927                         mpq_init(rv.num);
2928                 else if (neg)
2929                         mpq_neg(rv.num, rv.num);
2930                 if (tail[0])
2931                         printf("Unsupported suffix: %.*s\n", tx.len, tx.txt);
2932
2933                 break;
2934
2935 ###### value functions
2936
2937         static struct text text_join(struct text a, struct text b)
2938         {
2939                 struct text rv;
2940                 rv.len = a.len + b.len;
2941                 rv.txt = malloc(rv.len);
2942                 memcpy(rv.txt, a.txt, a.len);
2943                 memcpy(rv.txt+a.len, b.txt, b.len);
2944                 return rv;
2945         }
2946
2947 ### Blocks, Statements, and Statement lists.
2948
2949 Now that we have expressions out of the way we need to turn to
2950 statements.  There are simple statements and more complex statements.
2951 Simple statements do not contain (syntactic) newlines, complex statements do.
2952
2953 Statements often come in sequences and we have corresponding simple
2954 statement lists and complex statement lists.
2955 The former comprise only simple statements separated by semicolons.
2956 The later comprise complex statements and simple statement lists.  They are
2957 separated by newlines.  Thus the semicolon is only used to separate
2958 simple statements on the one line.  This may be overly restrictive,
2959 but I'm not sure I ever want a complex statement to share a line with
2960 anything else.
2961
2962 Note that a simple statement list can still use multiple lines if
2963 subsequent lines are indented, so
2964
2965 ###### Example: wrapped simple statement list
2966
2967         a = b; c = d;
2968            e = f; print g
2969
2970 is a single simple statement list.  This might allow room for
2971 confusion, so I'm not set on it yet.
2972
2973 A simple statement list needs no extra syntax.  A complex statement
2974 list has two syntactic forms.  It can be enclosed in braces (much like
2975 C blocks), or it can be introduced by an indent and continue until an
2976 unindented newline (much like Python blocks).  With this extra syntax
2977 it is referred to as a block.
2978
2979 Note that a block does not have to include any newlines if it only
2980 contains simple statements.  So both of:
2981
2982         if condition: a=b; d=f
2983
2984         if condition { a=b; print f }
2985
2986 are valid.
2987
2988 In either case the list is constructed from a `binode` list with
2989 `Block` as the operator.  When parsing the list it is most convenient
2990 to append to the end, so a list is a list and a statement.  When using
2991 the list it is more convenient to consider a list to be a statement
2992 and a list.  So we need a function to re-order a list.
2993 `reorder_bilist` serves this purpose.
2994
2995 The only stand-alone statement we introduce at this stage is `pass`
2996 which does nothing and is represented as a `NULL` pointer in a `Block`
2997 list.  Other stand-alone statements will follow once the infrastructure
2998 is in-place.
2999
3000 ###### Binode types
3001         Block,
3002
3003 ###### Grammar
3004
3005         $TERM { } ;
3006
3007         $*binode
3008         Block -> { IN OptNL Statementlist OUT OptNL } ${ $0 = $<Sl; }$
3009                 | { SimpleStatements } ${ $0 = reorder_bilist($<SS); }$
3010                 | SimpleStatements ; ${ $0 = reorder_bilist($<SS); }$
3011                 | SimpleStatements EOL ${ $0 = reorder_bilist($<SS); }$
3012                 | IN OptNL Statementlist OUT ${ $0 = $<Sl; }$
3013
3014         OpenBlock -> OpenScope { IN OptNL Statementlist OUT OptNL } ${ $0 = $<Sl; }$
3015                 | OpenScope { SimpleStatements } ${ $0 = reorder_bilist($<SS); }$
3016                 | OpenScope SimpleStatements ; ${ $0 = reorder_bilist($<SS); }$
3017                 | OpenScope SimpleStatements EOL ${ $0 = reorder_bilist($<SS); }$
3018                 | IN OpenScope OptNL Statementlist OUT ${ $0 = $<Sl; }$
3019
3020         UseBlock -> { OpenScope IN OptNL Statementlist OUT OptNL } ${ $0 = $<Sl; }$
3021                 | { OpenScope SimpleStatements } ${ $0 = reorder_bilist($<SS); }$
3022                 | IN OpenScope OptNL Statementlist OUT ${ $0 = $<Sl; }$
3023
3024         ColonBlock -> { IN OptNL Statementlist OUT OptNL } ${ $0 = $<Sl; }$
3025                 | { SimpleStatements } ${ $0 = reorder_bilist($<SS); }$
3026                 | : SimpleStatements ; ${ $0 = reorder_bilist($<SS); }$
3027                 | : SimpleStatements EOL ${ $0 = reorder_bilist($<SS); }$
3028                 | : IN OptNL Statementlist OUT ${ $0 = $<Sl; }$
3029
3030         Statementlist -> ComplexStatements ${ $0 = reorder_bilist($<CS); }$
3031
3032         ComplexStatements -> ComplexStatements ComplexStatement ${
3033                         if ($2 == NULL) {
3034                                 $0 = $<1;
3035                         } else {
3036                                 $0 = new(binode);
3037                                 $0->op = Block;
3038                                 $0->left = $<1;
3039                                 $0->right = $<2;
3040                         }
3041                 }$
3042                 | ComplexStatement ${
3043                         if ($1 == NULL) {
3044                                 $0 = NULL;
3045                         } else {
3046                                 $0 = new(binode);
3047                                 $0->op = Block;
3048                                 $0->left = NULL;
3049                                 $0->right = $<1;
3050                         }
3051                 }$
3052
3053         $*exec
3054         ComplexStatement -> SimpleStatements Newlines ${
3055                         $0 = reorder_bilist($<SS);
3056                         }$
3057                 |  SimpleStatements ; Newlines ${
3058                         $0 = reorder_bilist($<SS);
3059                         }$
3060                 ## ComplexStatement Grammar
3061
3062         $*binode
3063         SimpleStatements -> SimpleStatements ; SimpleStatement ${
3064                         $0 = new(binode);
3065                         $0->op = Block;
3066                         $0->left = $<1;
3067                         $0->right = $<3;
3068                         }$
3069                 | SimpleStatement ${
3070                         $0 = new(binode);
3071                         $0->op = Block;
3072                         $0->left = NULL;
3073                         $0->right = $<1;
3074                         }$
3075
3076         $TERM pass
3077         SimpleStatement -> pass ${ $0 = NULL; }$
3078                 | ERROR ${ tok_err(c, "Syntax error in statement", &$1); }$
3079                 ## SimpleStatement Grammar
3080
3081 ###### print binode cases
3082         case Block:
3083                 if (indent < 0) {
3084                         // simple statement
3085                         if (b->left == NULL)
3086                                 printf("pass");
3087                         else
3088                                 print_exec(b->left, indent, bracket);
3089                         if (b->right) {
3090                                 printf("; ");
3091                                 print_exec(b->right, indent, bracket);
3092                         }
3093                 } else {
3094                         // block, one per line
3095                         if (b->left == NULL)
3096                                 do_indent(indent, "pass\n");
3097                         else
3098                                 print_exec(b->left, indent, bracket);
3099                         if (b->right)
3100                                 print_exec(b->right, indent, bracket);
3101                 }
3102                 break;
3103
3104 ###### propagate binode cases
3105         case Block:
3106         {
3107                 /* If any statement returns something other than Tnone
3108                  * or Tbool then all such must return same type.
3109                  * As each statement may be Tnone or something else,
3110                  * we must always pass NULL (unknown) down, otherwise an incorrect
3111                  * error might occur.  We never return Tnone unless it is
3112                  * passed in.
3113                  */
3114                 struct binode *e;
3115
3116                 for (e = b; e; e = cast(binode, e->right)) {
3117                         t = propagate_types(e->left, c, ok, NULL, rules);
3118                         if ((rules & Rboolok) && t == Tbool)
3119                                 t = NULL;
3120                         if (t && t != Tnone && t != Tbool) {
3121                                 if (!type)
3122                                         type = t;
3123                                 else if (t != type)
3124                                         type_err(c, "error: expected %1%r, found %2",
3125                                                  e->left, type, rules, t);
3126                         }
3127                 }
3128                 return type;
3129         }
3130
3131 ###### interp binode cases
3132         case Block:
3133                 while (rvtype == Tnone &&
3134                        b) {
3135                         if (b->left)
3136                                 rv = interp_exec(b->left, &rvtype);
3137                         b = cast(binode, b->right);
3138                 }
3139                 break;
3140
3141 ### The Print statement
3142
3143 `print` is a simple statement that takes a comma-separated list of
3144 expressions and prints the values separated by spaces and terminated
3145 by a newline.  No control of formatting is possible.
3146
3147 `print` faces the same list-ordering issue as blocks, and uses the
3148 same solution.
3149
3150 ###### Binode types
3151         Print,
3152
3153 ##### expr precedence
3154         $TERM print ,
3155
3156 ###### SimpleStatement Grammar
3157
3158         | print ExpressionList ${
3159                 $0 = reorder_bilist($<2);
3160         }$
3161         | print ExpressionList , ${
3162                 $0 = new(binode);
3163                 $0->op = Print;
3164                 $0->right = NULL;
3165                 $0->left = $<2;
3166                 $0 = reorder_bilist($0);
3167         }$
3168         | print ${
3169                 $0 = new(binode);
3170                 $0->op = Print;
3171                 $0->right = NULL;
3172         }$
3173
3174 ###### Grammar
3175
3176         $*binode
3177         ExpressionList -> ExpressionList , Expression ${
3178                 $0 = new(binode);
3179                 $0->op = Print;
3180                 $0->left = $<1;
3181                 $0->right = $<3;
3182                 }$
3183                 | Expression ${
3184                         $0 = new(binode);
3185                         $0->op = Print;
3186                         $0->left = NULL;
3187                         $0->right = $<1;
3188                 }$
3189
3190 ###### print binode cases
3191
3192         case Print:
3193                 do_indent(indent, "print");
3194                 while (b) {
3195                         if (b->left) {
3196                                 printf(" ");
3197                                 print_exec(b->left, -1, bracket);
3198                                 if (b->right)
3199                                         printf(",");
3200                         }
3201                         b = cast(binode, b->right);
3202                 }
3203                 if (indent >= 0)
3204                         printf("\n");
3205                 break;
3206
3207 ###### propagate binode cases
3208
3209         case Print:
3210                 /* don't care but all must be consistent */
3211                 propagate_types(b->left, c, ok, NULL, Rnolabel);
3212                 propagate_types(b->right, c, ok, NULL, Rnolabel);
3213                 break;
3214
3215 ###### interp binode cases
3216
3217         case Print:
3218         {
3219                 char sep = 0;
3220                 int eol = 1;
3221                 for ( ; b; b = cast(binode, b->right))
3222                         if (b->left) {
3223                                 if (sep)
3224                                         putchar(sep);
3225                                 left = interp_exec(b->left, &ltype);
3226                                 print_value(ltype, &left);
3227                                 free_value(ltype, &left);
3228                                 if (b->right)
3229                                         sep = ' ';
3230                         } else if (sep)
3231                                 eol = 0;
3232                 ltype = Tnone;
3233                 if (eol)
3234                         printf("\n");
3235                 break;
3236         }
3237
3238 ###### Assignment statement
3239
3240 An assignment will assign a value to a variable, providing it hasn't
3241 been declared as a constant.  The analysis phase ensures that the type
3242 will be correct so the interpreter just needs to perform the
3243 calculation.  There is a form of assignment which declares a new
3244 variable as well as assigning a value.  If a name is assigned before
3245 it is declared, and error will be raised as the name is created as
3246 `Tlabel` and it is illegal to assign to such names.
3247
3248 ###### Binode types
3249         Assign,
3250         Declare,
3251
3252 ###### declare terminals
3253         $TERM =
3254
3255 ###### SimpleStatement Grammar
3256         | Variable = Expression ${
3257                         $0 = new(binode);
3258                         $0->op = Assign;
3259                         $0->left = $<1;
3260                         $0->right = $<3;
3261                 }$
3262         | VariableDecl = Expression ${
3263                         $0 = new(binode);
3264                         $0->op = Declare;
3265                         $0->left = $<1;
3266                         $0->right =$<3;
3267                 }$
3268
3269         | VariableDecl ${
3270                         if ($1->var->where_set == NULL) {
3271                                 type_err(c,
3272                                          "Variable declared with no type or value: %v",
3273                                          $1, NULL, 0, NULL);
3274                         } else {
3275                                 $0 = new(binode);
3276                                 $0->op = Declare;
3277                                 $0->left = $<1;
3278                                 $0->right = NULL;
3279                         }
3280                 }$
3281
3282 ###### print binode cases
3283
3284         case Assign:
3285                 do_indent(indent, "");
3286                 print_exec(b->left, indent, bracket);
3287                 printf(" = ");
3288                 print_exec(b->right, indent, bracket);
3289                 if (indent >= 0)
3290                         printf("\n");
3291                 break;
3292
3293         case Declare:
3294                 {
3295                 struct variable *v = cast(var, b->left)->var;
3296                 do_indent(indent, "");
3297                 print_exec(b->left, indent, bracket);
3298                 if (cast(var, b->left)->var->constant) {
3299                         if (v->where_decl == v->where_set) {
3300                                 printf("::");
3301                                 type_print(v->type, stdout);
3302                                 printf(" ");
3303                         } else
3304                                 printf(" ::");
3305                 } else {
3306                         if (v->where_decl == v->where_set) {
3307                                 printf(":");
3308                                 type_print(v->type, stdout);
3309                                 printf(" ");
3310                         } else
3311                                 printf(" :");
3312                 }
3313                 if (b->right) {
3314                         printf("= ");
3315                         print_exec(b->right, indent, bracket);
3316                 }
3317                 if (indent >= 0)
3318                         printf("\n");
3319                 }
3320                 break;
3321
3322 ###### propagate binode cases
3323
3324         case Assign:
3325         case Declare:
3326                 /* Both must match and not be labels,
3327                  * Type must support 'dup',
3328                  * For Assign, left must not be constant.
3329                  * result is Tnone
3330                  */
3331                 t = propagate_types(b->left, c, ok, NULL,
3332                                     Rnolabel | (b->op == Assign ? Rnoconstant : 0));
3333                 if (!b->right)
3334                         return Tnone;
3335
3336                 if (t) {
3337                         if (propagate_types(b->right, c, ok, t, 0) != t)
3338                                 if (b->left->type == Xvar)
3339                                         type_err(c, "info: variable '%v' was set as %1 here.",
3340                                                  cast(var, b->left)->var->where_set, t, rules, NULL);
3341                 } else {
3342                         t = propagate_types(b->right, c, ok, NULL, Rnolabel);
3343                         if (t)
3344                                 propagate_types(b->left, c, ok, t,
3345                                                 (b->op == Assign ? Rnoconstant : 0));
3346                 }
3347                 if (t && t->dup == NULL)
3348                         type_err(c, "error: cannot assign value of type %1", b, t, 0, NULL);
3349                 return Tnone;
3350
3351                 break;
3352
3353 ###### interp binode cases
3354
3355         case Assign:
3356                 lleft = linterp_exec(b->left, &ltype);
3357                 right = interp_exec(b->right, &rtype);
3358                 if (lleft) {
3359                         free_value(ltype, lleft);
3360                         dup_value(ltype, &right, lleft);
3361                         ltype = NULL;
3362                 }
3363                 break;
3364
3365         case Declare:
3366         {
3367                 struct variable *v = cast(var, b->left)->var;
3368                 if (v->merged)
3369                         v = v->merged;
3370                 free_value(v->type, v->val);
3371                 free(v->val);
3372                 if (b->right) {
3373                         right = interp_exec(b->right, &rtype);
3374                         v->val = val_alloc(v->type, &right);
3375                         rtype = Tnone;
3376                 } else {
3377                         v->val = val_alloc(v->type, NULL);
3378                 }
3379                 break;
3380         }
3381
3382 ### The `use` statement
3383
3384 The `use` statement is the last "simple" statement.  It is needed when
3385 the condition in a conditional statement is a block.  `use` works much
3386 like `return` in C, but only completes the `condition`, not the whole
3387 function.
3388
3389 ###### Binode types
3390         Use,
3391
3392 ###### expr precedence
3393         $TERM use       
3394
3395 ###### SimpleStatement Grammar
3396         | use Expression ${
3397                 $0 = new_pos(binode, $1);
3398                 $0->op = Use;
3399                 $0->right = $<2;
3400                 if ($0->right->type == Xvar) {
3401                         struct var *v = cast(var, $0->right);
3402                         if (v->var->type == Tnone) {
3403                                 /* Convert this to a label */
3404                                 v->var->type = Tlabel;
3405                                 v->var->val = val_alloc(Tlabel, NULL);
3406                                 v->var->val->label = v->var->val;
3407                         }
3408                 }
3409         }$
3410
3411 ###### print binode cases
3412
3413         case Use:
3414                 do_indent(indent, "use ");
3415                 print_exec(b->right, -1, bracket);
3416                 if (indent >= 0)
3417                         printf("\n");
3418                 break;
3419
3420 ###### propagate binode cases
3421
3422         case Use:
3423                 /* result matches value */
3424                 return propagate_types(b->right, c, ok, type, 0);
3425
3426 ###### interp binode cases
3427
3428         case Use:
3429                 rv = interp_exec(b->right, &rvtype);
3430                 break;
3431
3432 ### The Conditional Statement
3433
3434 This is the biggy and currently the only complex statement.  This
3435 subsumes `if`, `while`, `do/while`, `switch`, and some parts of `for`.
3436 It is comprised of a number of parts, all of which are optional though
3437 set combinations apply.  Each part is (usually) a key word (`then` is
3438 sometimes optional) followed by either an expression or a code block,
3439 except the `casepart` which is a "key word and an expression" followed
3440 by a code block.  The code-block option is valid for all parts and,
3441 where an expression is also allowed, the code block can use the `use`
3442 statement to report a value.  If the code block does not report a value
3443 the effect is similar to reporting `True`.
3444
3445 The `else` and `case` parts, as well as `then` when combined with
3446 `if`, can contain a `use` statement which will apply to some
3447 containing conditional statement. `for` parts, `do` parts and `then`
3448 parts used with `for` can never contain a `use`, except in some
3449 subordinate conditional statement.
3450
3451 If there is a `forpart`, it is executed first, only once.
3452 If there is a `dopart`, then it is executed repeatedly providing
3453 always that the `condpart` or `cond`, if present, does not return a non-True
3454 value.  `condpart` can fail to return any value if it simply executes
3455 to completion.  This is treated the same as returning `True`.
3456
3457 If there is a `thenpart` it will be executed whenever the `condpart`
3458 or `cond` returns True (or does not return any value), but this will happen
3459 *after* `dopart` (when present).
3460
3461 If `elsepart` is present it will be executed at most once when the
3462 condition returns `False` or some value that isn't `True` and isn't
3463 matched by any `casepart`.  If there are any `casepart`s, they will be
3464 executed when the condition returns a matching value.
3465
3466 The particular sorts of values allowed in case parts has not yet been
3467 determined in the language design, so nothing is prohibited.
3468
3469 The various blocks in this complex statement potentially provide scope
3470 for variables as described earlier.  Each such block must include the
3471 "OpenScope" nonterminal before parsing the block, and must call
3472 `var_block_close()` when closing the block.
3473
3474 The code following "`if`", "`switch`" and "`for`" does not get its own
3475 scope, but is in a scope covering the whole statement, so names
3476 declared there cannot be redeclared elsewhere.  Similarly the
3477 condition following "`while`" is in a scope the covers the body
3478 ("`do`" part) of the loop, and which does not allow conditional scope
3479 extension.  Code following "`then`" (both looping and non-looping),
3480 "`else`" and "`case`" each get their own local scope.
3481
3482 The type requirements on the code block in a `whilepart` are quite
3483 unusal.  It is allowed to return a value of some identifiable type, in
3484 which case the loop aborts and an appropriate `casepart` is run, or it
3485 can return a Boolean, in which case the loop either continues to the
3486 `dopart` (on `True`) or aborts and runs the `elsepart` (on `False`).
3487 This is different both from the `ifpart` code block which is expected to
3488 return a Boolean, or the `switchpart` code block which is expected to
3489 return the same type as the casepart values.  The correct analysis of
3490 the type of the `whilepart` code block is the reason for the
3491 `Rboolok` flag which is passed to `propagate_types()`.
3492
3493 The `cond_statement` cannot fit into a `binode` so a new `exec` is
3494 defined.
3495
3496 ###### exec type
3497         Xcond_statement,
3498
3499 ###### ast
3500         struct casepart {
3501                 struct exec *value;
3502                 struct exec *action;
3503                 struct casepart *next;
3504         };
3505         struct cond_statement {
3506                 struct exec;
3507                 struct exec *forpart, *condpart, *dopart, *thenpart, *elsepart;
3508                 struct casepart *casepart;
3509         };
3510
3511 ###### ast functions
3512
3513         static void free_casepart(struct casepart *cp)
3514         {
3515                 while (cp) {
3516                         struct casepart *t;
3517                         free_exec(cp->value);
3518                         free_exec(cp->action);
3519                         t = cp->next;
3520                         free(cp);
3521                         cp = t;
3522                 }
3523         }
3524
3525         static void free_cond_statement(struct cond_statement *s)
3526         {
3527                 if (!s)
3528                         return;
3529                 free_exec(s->forpart);
3530                 free_exec(s->condpart);
3531                 free_exec(s->dopart);
3532                 free_exec(s->thenpart);
3533                 free_exec(s->elsepart);
3534                 free_casepart(s->casepart);
3535                 free(s);
3536         }
3537
3538 ###### free exec cases
3539         case Xcond_statement: free_cond_statement(cast(cond_statement, e)); break;
3540
3541 ###### ComplexStatement Grammar
3542         | CondStatement ${ $0 = $<1; }$
3543
3544 ###### expr precedence
3545         $TERM for then while do
3546         $TERM else
3547         $TERM switch case
3548
3549 ###### Grammar
3550
3551         $*cond_statement
3552         // A CondStatement must end with EOL, as does CondSuffix and
3553         // IfSuffix.
3554         // ForPart, ThenPart, SwitchPart, CasePart are non-empty and
3555         // may or may not end with EOL
3556         // WhilePart and IfPart include an appropriate Suffix
3557
3558
3559         // Both ForPart and Whilepart open scopes, and CondSuffix only
3560         // closes one - so in the first branch here we have another to close.
3561         CondStatement -> ForPart OptNL ThenPart OptNL WhilePart CondSuffix ${
3562                         $0 = $<CS;
3563                         $0->forpart = $<FP;
3564                         $0->thenpart = $<TP;
3565                         $0->condpart = $WP.condpart; $WP.condpart = NULL;
3566                         $0->dopart = $WP.dopart; $WP.dopart = NULL;
3567                         var_block_close(c, CloseSequential);
3568                         }$
3569                 | ForPart OptNL WhilePart CondSuffix ${
3570                         $0 = $<CS;
3571                         $0->forpart = $<FP;
3572                         $0->condpart = $WP.condpart; $WP.condpart = NULL;
3573                         $0->dopart = $WP.dopart; $WP.dopart = NULL;
3574                         var_block_close(c, CloseSequential);
3575                         }$
3576                 | WhilePart CondSuffix ${
3577                         $0 = $<CS;
3578                         $0->condpart = $WP.condpart; $WP.condpart = NULL;
3579                         $0->dopart = $WP.dopart; $WP.dopart = NULL;
3580                         }$
3581                 | SwitchPart OptNL CasePart CondSuffix ${
3582                         $0 = $<CS;
3583                         $0->condpart = $<SP;
3584                         $CP->next = $0->casepart;
3585                         $0->casepart = $<CP;
3586                         }$
3587                 | SwitchPart : IN OptNL CasePart CondSuffix OUT Newlines ${
3588                         $0 = $<CS;
3589                         $0->condpart = $<SP;
3590                         $CP->next = $0->casepart;
3591                         $0->casepart = $<CP;
3592                         }$
3593                 | IfPart IfSuffix ${
3594                         $0 = $<IS;
3595                         $0->condpart = $IP.condpart; $IP.condpart = NULL;
3596                         $0->thenpart = $IP.thenpart; $IP.thenpart = NULL;
3597                         // This is where we close an "if" statement
3598                         var_block_close(c, CloseSequential);
3599                         }$
3600
3601         CondSuffix -> IfSuffix ${
3602                         $0 = $<1;
3603                         // This is where we close scope of the whole
3604                         // "for" or "while" statement
3605                         var_block_close(c, CloseSequential);
3606                 }$
3607                 | Newlines CasePart CondSuffix ${
3608                         $0 = $<CS;
3609                         $CP->next = $0->casepart;
3610                         $0->casepart = $<CP;
3611                 }$
3612                 | CasePart CondSuffix ${
3613                         $0 = $<CS;
3614                         $CP->next = $0->casepart;
3615                         $0->casepart = $<CP;
3616                 }$
3617
3618         IfSuffix -> Newlines ${ $0 = new(cond_statement); }$
3619                 | Newlines ElsePart ${ $0 = $<EP; }$
3620                 | ElsePart ${$0 = $<EP; }$
3621
3622         ElsePart -> else OpenBlock Newlines ${
3623                         $0 = new(cond_statement);
3624                         $0->elsepart = $<OB;
3625                         var_block_close(c, CloseElse);
3626                 }$
3627                 | else OpenScope CondStatement ${
3628                         $0 = new(cond_statement);
3629                         $0->elsepart = $<CS;
3630                         var_block_close(c, CloseElse);
3631                 }$
3632
3633         $*casepart
3634         CasePart -> case Expression OpenScope ColonBlock ${
3635                         $0 = calloc(1,sizeof(struct casepart));
3636                         $0->value = $<Ex;
3637                         $0->action = $<Bl;
3638                         var_block_close(c, CloseParallel);
3639                 }$
3640
3641         $*exec
3642         // These scopes are closed in CondSuffix
3643         ForPart -> for OpenBlock ${
3644                         $0 = $<Bl;
3645                 }$
3646
3647         ThenPart -> then OpenBlock ${
3648                         $0 = $<OB;
3649                         var_block_close(c, CloseSequential);
3650                 }$
3651
3652         $cond_statement
3653         // This scope is closed in CondSuffix
3654         WhilePart -> while UseBlock OptNL do Block ${
3655                         $0.condpart = $<UB;
3656                         $0.dopart = $<Bl;
3657                 }$
3658                 | while OpenScope Expression ColonBlock ${
3659                         $0.condpart = $<Exp;
3660                         $0.dopart = $<Bl;
3661                 }$
3662
3663         IfPart -> if UseBlock OptNL then OpenBlock ClosePara ${
3664                         $0.condpart = $<UB;
3665                         $0.thenpart = $<Bl;
3666                 }$
3667                 | if OpenScope Expression OpenScope ColonBlock ClosePara ${
3668                         $0.condpart = $<Ex;
3669                         $0.thenpart = $<Bl;
3670                 }$
3671                 | if OpenScope Expression OpenScope OptNL then Block ClosePara ${
3672                         $0.condpart = $<Ex;
3673                         $0.thenpart = $<Bl;
3674                 }$
3675
3676         $*exec
3677         // This scope is closed in CondSuffix
3678         SwitchPart -> switch OpenScope Expression ${
3679                         $0 = $<Ex;
3680                 }$
3681                 | switch UseBlock ${
3682                         $0 = $<Bl;
3683                 }$
3684
3685 ###### print exec cases
3686
3687         case Xcond_statement:
3688         {
3689                 struct cond_statement *cs = cast(cond_statement, e);
3690                 struct casepart *cp;
3691                 if (cs->forpart) {
3692                         do_indent(indent, "for");
3693                         if (bracket) printf(" {\n"); else printf("\n");
3694                         print_exec(cs->forpart, indent+1, bracket);
3695                         if (cs->thenpart) {
3696                                 if (bracket)
3697                                         do_indent(indent, "} then {\n");
3698                                 else
3699                                         do_indent(indent, "then\n");
3700                                 print_exec(cs->thenpart, indent+1, bracket);
3701                         }
3702                         if (bracket) do_indent(indent, "}\n");
3703                 }
3704                 if (cs->dopart) {
3705                         // a loop
3706                         if (cs->condpart && cs->condpart->type == Xbinode &&
3707                             cast(binode, cs->condpart)->op == Block) {
3708                                 if (bracket)
3709                                         do_indent(indent, "while {\n");
3710                                 else
3711                                         do_indent(indent, "while\n");
3712                                 print_exec(cs->condpart, indent+1, bracket);
3713                                 if (bracket)
3714                                         do_indent(indent, "} do {\n");
3715                                 else
3716                                         do_indent(indent, "do\n");
3717                                 print_exec(cs->dopart, indent+1, bracket);
3718                                 if (bracket)
3719                                         do_indent(indent, "}\n");
3720                         } else {
3721                                 do_indent(indent, "while ");
3722                                 print_exec(cs->condpart, 0, bracket);
3723                                 if (bracket)
3724                                         printf(" {\n");
3725                                 else
3726                                         printf(":\n");
3727                                 print_exec(cs->dopart, indent+1, bracket);
3728                                 if (bracket)
3729                                         do_indent(indent, "}\n");
3730                         }
3731                 } else {
3732                         // a condition
3733                         if (cs->casepart)
3734                                 do_indent(indent, "switch");
3735                         else
3736                                 do_indent(indent, "if");
3737                         if (cs->condpart && cs->condpart->type == Xbinode &&
3738                             cast(binode, cs->condpart)->op == Block) {
3739                                 if (bracket)
3740                                         printf(" {\n");
3741                                 else
3742                                         printf(":\n");
3743                                 print_exec(cs->condpart, indent+1, bracket);
3744                                 if (bracket)
3745                                         do_indent(indent, "}\n");
3746                                 if (cs->thenpart) {
3747                                         do_indent(indent, "then:\n");
3748                                         print_exec(cs->thenpart, indent+1, bracket);
3749                                 }
3750                         } else {
3751                                 printf(" ");
3752                                 print_exec(cs->condpart, 0, bracket);
3753                                 if (cs->thenpart) {
3754                                         if (bracket)
3755                                                 printf(" {\n");
3756                                         else
3757                                                 printf(":\n");
3758                                         print_exec(cs->thenpart, indent+1, bracket);
3759                                         if (bracket)
3760                                                 do_indent(indent, "}\n");
3761                                 } else
3762                                         printf("\n");
3763                         }
3764                 }
3765                 for (cp = cs->casepart; cp; cp = cp->next) {
3766                         do_indent(indent, "case ");
3767                         print_exec(cp->value, -1, 0);
3768                         if (bracket)
3769                                 printf(" {\n");
3770                         else
3771                                 printf(":\n");
3772                         print_exec(cp->action, indent+1, bracket);
3773                         if (bracket)
3774                                 do_indent(indent, "}\n");
3775                 }
3776                 if (cs->elsepart) {
3777                         do_indent(indent, "else");
3778                         if (bracket)
3779                                 printf(" {\n");
3780                         else
3781                                 printf("\n");
3782                         print_exec(cs->elsepart, indent+1, bracket);
3783                         if (bracket)
3784                                 do_indent(indent, "}\n");
3785                 }
3786                 break;
3787         }
3788
3789 ###### propagate exec cases
3790         case Xcond_statement:
3791         {
3792                 // forpart and dopart must return Tnone
3793                 // thenpart must return Tnone if there is a dopart,
3794                 // otherwise it is like elsepart.
3795                 // condpart must:
3796                 //    be bool if there is no casepart
3797                 //    match casepart->values if there is a switchpart
3798                 //    either be bool or match casepart->value if there
3799                 //             is a whilepart
3800                 // elsepart and casepart->action must match the return type
3801                 //   expected of this statement.
3802                 struct cond_statement *cs = cast(cond_statement, prog);
3803                 struct casepart *cp;
3804
3805                 t = propagate_types(cs->forpart, c, ok, Tnone, 0);
3806                 if (!type_compat(Tnone, t, 0))
3807                         *ok = 0;
3808                 t = propagate_types(cs->dopart, c, ok, Tnone, 0);
3809                 if (!type_compat(Tnone, t, 0))
3810                         *ok = 0;
3811                 if (cs->dopart) {
3812                         t = propagate_types(cs->thenpart, c, ok, Tnone, 0);
3813                         if (!type_compat(Tnone, t, 0))
3814                                 *ok = 0;
3815                 }
3816                 if (cs->casepart == NULL)
3817                         propagate_types(cs->condpart, c, ok, Tbool, 0);
3818                 else {
3819                         /* Condpart must match case values, with bool permitted */
3820                         t = NULL;
3821                         for (cp = cs->casepart;
3822                              cp && !t; cp = cp->next)
3823                                 t = propagate_types(cp->value, c, ok, NULL, 0);
3824                         if (!t && cs->condpart)
3825                                 t = propagate_types(cs->condpart, c, ok, NULL, Rboolok);
3826                         // Now we have a type (I hope) push it down
3827                         if (t) {
3828                                 for (cp = cs->casepart; cp; cp = cp->next)
3829                                         propagate_types(cp->value, c, ok, t, 0);
3830                                 propagate_types(cs->condpart, c, ok, t, Rboolok);
3831                         }
3832                 }
3833                 // (if)then, else, and case parts must return expected type.
3834                 if (!cs->dopart && !type)
3835                         type = propagate_types(cs->thenpart, c, ok, NULL, rules);
3836                 if (!type)
3837                         type = propagate_types(cs->elsepart, c, ok, NULL, rules);
3838                 for (cp = cs->casepart;
3839                      cp && !type;
3840                      cp = cp->next)
3841                         type = propagate_types(cp->action, c, ok, NULL, rules);
3842                 if (type) {
3843                         if (!cs->dopart)
3844                                 propagate_types(cs->thenpart, c, ok, type, rules);
3845                         propagate_types(cs->elsepart, c, ok, type, rules);
3846                         for (cp = cs->casepart; cp ; cp = cp->next)
3847                                 propagate_types(cp->action, c, ok, type, rules);
3848                         return type;
3849                 } else
3850                         return NULL;
3851         }
3852
3853 ###### interp exec cases
3854         case Xcond_statement:
3855         {
3856                 struct value v, cnd;
3857                 struct type *vtype, *cndtype;
3858                 struct casepart *cp;
3859                 struct cond_statement *c = cast(cond_statement, e);
3860
3861                 if (c->forpart)
3862                         interp_exec(c->forpart, NULL);
3863                 do {
3864                         if (c->condpart)
3865                                 cnd = interp_exec(c->condpart, &cndtype);
3866                         else
3867                                 cndtype = Tnone;
3868                         if (!(cndtype == Tnone ||
3869                               (cndtype == Tbool && cnd.bool != 0)))
3870                                 break;
3871                         // cnd is Tnone or Tbool, doesn't need to be freed
3872                         if (c->dopart)
3873                                 interp_exec(c->dopart, NULL);
3874
3875                         if (c->thenpart) {
3876                                 rv = interp_exec(c->thenpart, &rvtype);
3877                                 if (rvtype != Tnone || !c->dopart)
3878                                         goto Xcond_done;
3879                                 free_value(rvtype, &rv);
3880                                 rvtype = Tnone;
3881                         }
3882                 } while (c->dopart);
3883
3884                 for (cp = c->casepart; cp; cp = cp->next) {
3885                         v = interp_exec(cp->value, &vtype);
3886                         if (value_cmp(cndtype, vtype, &v, &cnd) == 0) {
3887                                 free_value(vtype, &v);
3888                                 free_value(cndtype, &cnd);
3889                                 rv = interp_exec(cp->action, &rvtype);
3890                                 goto Xcond_done;
3891                         }
3892                         free_value(vtype, &v);
3893                 }
3894                 free_value(cndtype, &cnd);
3895                 if (c->elsepart)
3896                         rv = interp_exec(c->elsepart, &rvtype);
3897                 else
3898                         rvtype = Tnone;
3899         Xcond_done:
3900                 break;
3901         }
3902
3903 ### Top level structure
3904
3905 All the language elements so far can be used in various places.  Now
3906 it is time to clarify what those places are.
3907
3908 At the top level of a file there will be a number of declarations.
3909 Many of the things that can be declared haven't been described yet,
3910 such as functions, procedures, imports, and probably more.
3911 For now there are two sorts of things that can appear at the top
3912 level.  They are predefined constants, `struct` types, and the main
3913 program.  While the syntax will allow the main program to appear
3914 multiple times, that will trigger an error if it is actually attempted.
3915
3916 The various declarations do not return anything.  They store the
3917 various declarations in the parse context.
3918
3919 ###### Parser: grammar
3920
3921         $void
3922         Ocean -> OptNL DeclarationList
3923
3924         ## declare terminals
3925
3926         OptNL ->
3927                 | OptNL NEWLINE
3928         Newlines -> NEWLINE
3929                 | Newlines NEWLINE
3930
3931         DeclarationList -> Declaration
3932                 | DeclarationList Declaration
3933
3934         Declaration -> ERROR Newlines ${
3935                         tok_err(c,
3936                                 "error: unhandled parse error", &$1);
3937                 }$
3938                 | DeclareConstant
3939                 | DeclareProgram
3940                 | DeclareStruct
3941
3942         ## top level grammar
3943
3944 ### The `const` section
3945
3946 As well as being defined in with the code that uses them, constants
3947 can be declared at the top level.  These have full-file scope, so they
3948 are always `InScope`.  The value of a top level constant can be given
3949 as an expression, and this is evaluated immediately rather than in the
3950 later interpretation stage.  Once we add functions to the language, we
3951 will need rules concern which, if any, can be used to define a top
3952 level constant.
3953
3954 Constants are defined in a section that starts with the reserved word
3955 `const` and then has a block with a list of assignment statements.
3956 For syntactic consistency, these must use the double-colon syntax to
3957 make it clear that they are constants.  Type can also be given: if
3958 not, the type will be determined during analysis, as with other
3959 constants.
3960
3961 As the types constants are inserted at the head of a list, printing
3962 them in the same order that they were read is not straight forward.
3963 We take a quadratic approach here and count the number of constants
3964 (variables of depth 0), then count down from there, each time
3965 searching through for the Nth constant for decreasing N.
3966
3967 ###### top level grammar
3968
3969         $TERM const
3970
3971         DeclareConstant -> const { IN OptNL ConstList OUT OptNL } Newlines
3972                 | const { SimpleConstList } Newlines
3973                 | const IN OptNL ConstList OUT Newlines
3974                 | const SimpleConstList Newlines
3975
3976         ConstList -> ConstList SimpleConstLine
3977                 | SimpleConstLine
3978         SimpleConstList -> SimpleConstList ; Const
3979                 | Const
3980                 | SimpleConstList ;
3981         SimpleConstLine -> SimpleConstList Newlines
3982                 | ERROR Newlines ${ tok_err(c, "Syntax error in constant", &$1); }$
3983
3984         $*type
3985         CType -> Type   ${ $0 = $<1; }$
3986                 |       ${ $0 = NULL; }$
3987         $void
3988         Const -> IDENTIFIER :: CType = Expression ${ {
3989                 int ok;
3990                 struct variable *v;
3991
3992                 v = var_decl(c, $1.txt);
3993                 if (v) {
3994                         struct var *var = new_pos(var, $1);
3995                         v->where_decl = var;
3996                         v->where_set = var;
3997                         var->var = v;
3998                         v->constant = 1;
3999                 } else {
4000                         v = var_ref(c, $1.txt);
4001                         tok_err(c, "error: name already declared", &$1);
4002                         type_err(c, "info: this is where '%v' was first declared",
4003                                  v->where_decl, NULL, 0, NULL);
4004                 }
4005                 do {
4006                         ok = 1;
4007                         propagate_types($5, c, &ok, $3, 0);
4008                 } while (ok == 2);
4009                 if (!ok)
4010                         c->parse_error = 1;
4011                 else if (v) {
4012                         struct value res = interp_exec($5, &v->type);
4013                         v->val = val_alloc(v->type, &res);
4014                 }
4015         } }$
4016
4017 ###### print const decls
4018         {
4019                 struct variable *v;
4020                 int target = -1;
4021
4022                 while (target != 0) {
4023                         int i = 0;
4024                         for (v = context.in_scope; v; v=v->in_scope)
4025                                 if (v->depth == 0) {
4026                                         i += 1;
4027                                         if (i == target)
4028                                                 break;
4029                                 }
4030
4031                         if (target == -1) {
4032                                 if (i)
4033                                         printf("const\n");
4034                                 target = i;
4035                         } else {
4036                                 printf("    %.*s :: ", v->name->name.len, v->name->name.txt);
4037                                 type_print(v->type, stdout);
4038                                 printf(" = ");
4039                                 if (v->type == Tstr)
4040                                         printf("\"");
4041                                 print_value(v->type, v->val);
4042                                 if (v->type == Tstr)
4043                                         printf("\"");
4044                                 printf("\n");
4045                                 target -= 1;
4046                         }
4047                 }
4048         }
4049
4050 ### Finally the whole program.
4051
4052 Somewhat reminiscent of Pascal a (current) Ocean program starts with
4053 the keyword "program" and a list of variable names which are assigned
4054 values from command line arguments.  Following this is a `block` which
4055 is the code to execute.  Unlike Pascal, constants and other
4056 declarations come *before* the program.
4057
4058 As this is the top level, several things are handled a bit
4059 differently.
4060 The whole program is not interpreted by `interp_exec` as that isn't
4061 passed the argument list which the program requires.  Similarly type
4062 analysis is a bit more interesting at this level.
4063
4064 ###### Binode types
4065         Program,
4066
4067 ###### top level grammar
4068
4069         DeclareProgram -> Program ${ {
4070                 if (c->prog)
4071                         type_err(c, "Program defined a second time",
4072                                  $1, NULL, 0, NULL);
4073                 else
4074                         c->prog = $<1;
4075         } }$
4076
4077         $TERM program
4078
4079         $*binode
4080         Program -> program OpenScope Varlist ColonBlock Newlines ${
4081                 $0 = new(binode);
4082                 $0->op = Program;
4083                 $0->left = reorder_bilist($<Vl);
4084                 $0->right = $<Bl;
4085                 var_block_close(c, CloseSequential);
4086                 if (c->scope_stack && !c->parse_error) abort();
4087                 }$
4088
4089         Varlist -> Varlist ArgDecl ${
4090                         $0 = new(binode);
4091                         $0->op = Program;
4092                         $0->left = $<1;
4093                         $0->right = $<2;
4094                 }$
4095                 | ${ $0 = NULL; }$
4096
4097         $*var
4098         ArgDecl -> IDENTIFIER ${ {
4099                 struct variable *v = var_decl(c, $1.txt);
4100                 $0 = new(var);
4101                 $0->var = v;
4102         } }$
4103
4104         ## Grammar
4105
4106 ###### print binode cases
4107         case Program:
4108                 do_indent(indent, "program");
4109                 for (b2 = cast(binode, b->left); b2; b2 = cast(binode, b2->right)) {
4110                         printf(" ");
4111                         print_exec(b2->left, 0, 0);
4112                 }
4113                 if (bracket)
4114                         printf(" {\n");
4115                 else
4116                         printf(":\n");
4117                 print_exec(b->right, indent+1, bracket);
4118                 if (bracket)
4119                         do_indent(indent, "}\n");
4120                 break;
4121
4122 ###### propagate binode cases
4123         case Program: abort();          // NOTEST
4124
4125 ###### core functions
4126
4127         static int analyse_prog(struct exec *prog, struct parse_context *c)
4128         {
4129                 struct binode *b = cast(binode, prog);
4130                 int ok = 1;
4131
4132                 if (!b)
4133                         return 0;       // NOTEST
4134                 do {
4135                         ok = 1;
4136                         propagate_types(b->right, c, &ok, Tnone, 0);
4137                 } while (ok == 2);
4138                 if (!ok)
4139                         return 0;
4140
4141                 for (b = cast(binode, b->left); b; b = cast(binode, b->right)) {
4142                         struct var *v = cast(var, b->left);
4143                         if (!v->var->type) {
4144                                 v->var->where_set = b;
4145                                 v->var->type = Tstr;
4146                                 v->var->val = NULL;
4147                         }
4148                 }
4149                 b = cast(binode, prog);
4150                 do {
4151                         ok = 1;
4152                         propagate_types(b->right, c, &ok, Tnone, 0);
4153                 } while (ok == 2);
4154                 if (!ok)
4155                         return 0;
4156
4157                 /* Make sure everything is still consistent */
4158                 propagate_types(b->right, c, &ok, Tnone, 0);
4159                 return !!ok;
4160         }
4161
4162         static void interp_prog(struct exec *prog, char **argv)
4163         {
4164                 struct binode *p = cast(binode, prog);
4165                 struct binode *al;
4166                 struct value v;
4167                 struct type *vtype;
4168
4169                 if (!prog)
4170                         return;         // NOTEST
4171                 al = cast(binode, p->left);
4172                 while (al) {
4173                         struct var *v = cast(var, al->left);
4174                         struct value *vl = v->var->val;
4175
4176                         if (argv[0] == NULL) {
4177                                 printf("Not enough args\n");
4178                                 exit(1);
4179                         }
4180                         al = cast(binode, al->right);
4181                         if (vl)
4182                                 free_value(v->var->type, vl);
4183                         if (!vl) {
4184                                 vl = val_alloc(v->var->type, NULL);
4185                                 v->var->val = vl;
4186                         }
4187                         free_value(v->var->type, vl);
4188                         vl->str.len = strlen(argv[0]);
4189                         vl->str.txt = malloc(vl->str.len);
4190                         memcpy(vl->str.txt, argv[0], vl->str.len);
4191                         argv++;
4192                 }
4193                 v = interp_exec(p->right, &vtype);
4194                 free_value(vtype, &v);
4195         }
4196
4197 ###### interp binode cases
4198         case Program: abort();  // NOTEST
4199
4200 ## And now to test it out.
4201
4202 Having a language requires having a "hello world" program.  I'll
4203 provide a little more than that: a program that prints "Hello world"
4204 finds the GCD of two numbers, prints the first few elements of
4205 Fibonacci, performs a binary search for a number, and a few other
4206 things which will likely grow as the languages grows.
4207
4208 ###### File: oceani.mk
4209         demos :: sayhello
4210         sayhello : oceani
4211                 @echo "===== DEMO ====="
4212                 ./oceani --section "demo: hello" oceani.mdc 55 33
4213
4214 ###### demo: hello
4215
4216         const
4217                 pi ::= 3.141_592_6
4218                 four ::= 2 + 2 ; five ::= 10/2
4219         const pie ::= "I like Pie";
4220                 cake ::= "The cake is"
4221                   ++ " a lie"
4222
4223         struct fred
4224                 size:[four]number
4225                 name:string
4226                 alive:Boolean
4227
4228         program Astr Bstr:
4229                 print "Hello World, what lovely oceans you have!"
4230                 print "Are there", five, "?"
4231                 print pi, pie, "but", cake
4232
4233                 A := $Astr; B := $Bstr
4234
4235                 /* When a variable is defined in both branches of an 'if',
4236                  * and used afterwards, the variables are merged.
4237                  */
4238                 if A > B:
4239                         bigger := "yes"
4240                 else
4241                         bigger := "no"
4242                 print "Is", A, "bigger than", B,"? ", bigger
4243                 /* If a variable is not used after the 'if', no
4244                  * merge happens, so types can be different
4245                  */
4246                 if A > B * 2:
4247                         double:string = "yes"
4248                         print A, "is more than twice", B, "?", double
4249                 else
4250                         double := B*2
4251                         print "double", B, "is", double
4252
4253                 a : number
4254                 a = A;
4255                 b:number = B
4256                 if a > 0 and then b > 0:
4257                         while a != b:
4258                                 if a < b:
4259                                         b = b - a
4260                                 else
4261                                         a = a - b
4262                         print "GCD of", A, "and", B,"is", a
4263                 else if a <= 0:
4264                         print a, "is not positive, cannot calculate GCD"
4265                 else
4266                         print b, "is not positive, cannot calculate GCD"
4267
4268                 for
4269                         togo := 10
4270                         f1 := 1; f2 := 1
4271                         print "Fibonacci:", f1,f2,
4272                 then togo = togo - 1
4273                 while togo > 0:
4274                         f3 := f1 + f2
4275                         print "", f3,
4276                         f1 = f2
4277                         f2 = f3
4278                 print ""
4279
4280                 /* Binary search... */
4281                 for
4282                         lo:= 0; hi := 100
4283                         target := 77
4284                 while
4285                         mid := (lo + hi) / 2
4286                         if mid == target:
4287                                 use Found
4288                         if mid < target:
4289                                 lo = mid
4290                         else
4291                                 hi = mid
4292                         if hi - lo < 1:
4293                                 use GiveUp
4294                         use True
4295                 do pass
4296                 case Found:
4297                         print "Yay, I found", target
4298                 case GiveUp:
4299                         print "Closest I found was", mid
4300
4301                 size::= 10
4302                 list:[size]number
4303                 list[0] = 1234
4304                 // "middle square" PRNG.  Not particularly good, but one my
4305                 // Dad taught me - the first one I ever heard of.
4306                 for i:=1; then i = i + 1; while i < size:
4307                         n := list[i-1] * list[i-1]
4308                         list[i] = (n / 100) % 10 000
4309
4310                 print "Before sort:",
4311                 for i:=0; then i = i + 1; while i < size:
4312                         print "", list[i],
4313                 print
4314
4315                 for i := 1; then i=i+1; while i < size:
4316                         for j:=i-1; then j=j-1; while j >= 0:
4317                                 if list[j] > list[j+1]:
4318                                         t:= list[j]
4319                                         list[j] = list[j+1]
4320                                         list[j+1] = t
4321                 print " After sort:",
4322                 for i:=0; then i = i + 1; while i < size:
4323                         print "", list[i],
4324                 print
4325
4326                 if 1 == 2 then print "yes"; else print "no"
4327
4328                 bob:fred
4329                 bob.name = "Hello"
4330                 bob.alive = (bob.name == "Hello")
4331                 print "bob", "is" if  bob.alive else "isn't", "alive"