1 # Ocean Interpreter - Jamison Creek version
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.
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.
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
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
26 Nonetheless, the interpreter should end up being reasonably complete,
27 and any performance bottlenecks which appear and are easily fixed, will
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
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).
44 The "func" clause currently only allows a "main" function to be
45 declared. That will be extended when proper function support is added.
47 An element that is present purely to make a usable language, and
48 without any expectation that they will remain, is the "print" statement
49 which performs simple output.
51 The current scalar types are "number", "Boolean", and "string".
52 Boolean will likely stay in its current form, the other two might, but
53 could just as easily be changed.
57 Versions of the interpreter which obviously do not support a complete
58 language will be named after creeks and streams. This one is Jamison
61 Once we have something reasonably resembling a complete language, the
62 names of rivers will be used.
63 Early versions of the compiler will be named after seas. Major
64 releases of the compiler will be named after oceans. Hopefully I will
65 be finished once I get to the Pacific Ocean release.
69 As well as parsing and executing a program, the interpreter can print
70 out the program from the parsed internal structure. This is useful
71 for validating the parsing.
72 So the main requirements of the interpreter are:
74 - Parse the program, possibly with tracing,
75 - Analyse the parsed program to ensure consistency,
77 - Execute the "main" function in the program, if no parsing or
78 consistency errors were found.
80 This is all performed by a single C program extracted with
83 There will be two formats for printing the program: a default and one
84 that uses bracketing. So a `--bracket` command line option is needed
85 for that. Normally the first code section found is used, however an
86 alternate section can be requested so that a file (such as this one)
87 can contain multiple programs. This is effected with the `--section`
90 This code must be compiled with `-fplan9-extensions` so that anonymous
91 structures can be used.
93 ###### File: oceani.mk
95 myCFLAGS := -Wall -g -fplan9-extensions
96 CFLAGS := $(filter-out $(myCFLAGS),$(CFLAGS)) $(myCFLAGS)
97 myLDLIBS:= libparser.o libscanner.o libmdcode.o -licuuc
98 LDLIBS := $(filter-out $(myLDLIBS),$(LDLIBS)) $(myLDLIBS)
100 all :: $(LDLIBS) oceani
101 oceani.c oceani.h : oceani.mdc parsergen
102 ./parsergen -o oceani --LALR --tag Parser oceani.mdc
103 oceani.mk: oceani.mdc md2c
106 oceani: oceani.o $(LDLIBS)
107 $(CC) $(CFLAGS) -o oceani oceani.o $(LDLIBS)
109 ###### Parser: header
111 struct parse_context;
113 struct parse_context {
114 struct token_config config;
122 #define container_of(ptr, type, member) ({ \
123 const typeof( ((type *)0)->member ) *__mptr = (ptr); \
124 (type *)( (char *)__mptr - offsetof(type,member) );})
126 #define config2context(_conf) container_of(_conf, struct parse_context, \
129 ###### Parser: reduce
130 struct parse_context *c = config2context(config);
138 #include <sys/mman.h>
157 static char Usage[] =
158 "Usage: oceani --trace --print --noexec --brackets --section=SectionName prog.ocn\n";
159 static const struct option long_options[] = {
160 {"trace", 0, NULL, 't'},
161 {"print", 0, NULL, 'p'},
162 {"noexec", 0, NULL, 'n'},
163 {"brackets", 0, NULL, 'b'},
164 {"section", 1, NULL, 's'},
167 const char *options = "tpnbs";
169 static void pr_err(char *msg) // NOTEST
171 fprintf(stderr, "%s\n", msg); // NOTEST
174 int main(int argc, char *argv[])
179 struct section *s = NULL, *ss;
180 char *section = NULL;
181 struct parse_context context = {
183 .ignored = (1 << TK_mark),
184 .number_chars = ".,_+- ",
189 int doprint=0, dotrace=0, doexec=1, brackets=0;
191 while ((opt = getopt_long(argc, argv, options, long_options, NULL))
194 case 't': dotrace=1; break;
195 case 'p': doprint=1; break;
196 case 'n': doexec=0; break;
197 case 'b': brackets=1; break;
198 case 's': section = optarg; break;
199 default: fprintf(stderr, Usage);
203 if (optind >= argc) {
204 fprintf(stderr, "oceani: no input file given\n");
207 fd = open(argv[optind], O_RDONLY);
209 fprintf(stderr, "oceani: cannot open %s\n", argv[optind]);
212 context.file_name = argv[optind];
213 len = lseek(fd, 0, 2);
214 file = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
215 s = code_extract(file, file+len, pr_err);
217 fprintf(stderr, "oceani: could not find any code in %s\n",
222 ## context initialization
225 for (ss = s; ss; ss = ss->next) {
226 struct text sec = ss->section;
227 if (sec.len == strlen(section) &&
228 strncmp(sec.txt, section, sec.len) == 0)
232 fprintf(stderr, "oceani: cannot find section %s\n",
239 fprintf(stderr, "oceani: no code found in requested section\n"); // NOTEST
240 goto cleanup; // NOTEST
243 parse_oceani(ss->code, &context.config, dotrace ? stderr : NULL);
245 resolve_consts(&context);
246 prepare_types(&context);
247 if (!context.parse_error && !analyse_funcs(&context)) {
248 fprintf(stderr, "oceani: type error in program - not running.\n");
249 context.parse_error += 1;
257 if (doexec && !context.parse_error)
258 interp_main(&context, argc - optind, argv + optind);
261 struct section *t = s->next;
266 // FIXME parser should pop scope even on error
267 while (context.scope_depth > 0)
271 ## free context types
272 ## free context storage
273 exit(context.parse_error ? 1 : 0);
278 The four requirements of parse, analyse, print, interpret apply to
279 each language element individually so that is how most of the code
282 Three of the four are fairly self explanatory. The one that requires
283 a little explanation is the analysis step.
285 The current language design does not require the types of variables to
286 be declared, but they must still have a single type. Different
287 operations impose different requirements on the variables, for example
288 addition requires both arguments to be numeric, and assignment
289 requires the variable on the left to have the same type as the
290 expression on the right.
292 Analysis involves propagating these type requirements around and
293 consequently setting the type of each variable. If any requirements
294 are violated (e.g. a string is compared with a number) or if a
295 variable needs to have two different types, then an error is raised
296 and the program will not run.
298 If the same variable is declared in both branchs of an 'if/else', or
299 in all cases of a 'switch' then the multiple instances may be merged
300 into just one variable if the variable is referenced after the
301 conditional statement. When this happens, the types must naturally be
302 consistent across all the branches. When the variable is not used
303 outside the if, the variables in the different branches are distinct
304 and can be of different types.
306 Undeclared names may only appear in "use" statements and "case" expressions.
307 These names are given a type of "label" and a unique value.
308 This allows them to fill the role of a name in an enumerated type, which
309 is useful for testing the `switch` statement.
311 As we will see, the condition part of a `while` statement can return
312 either a Boolean or some other type. This requires that the expected
313 type that gets passed around comprises a type and a flag to indicate
314 that `Tbool` is also permitted.
316 As there are, as yet, no distinct types that are compatible, there
317 isn't much subtlety in the analysis. When we have distinct number
318 types, this will become more interesting.
322 When analysis discovers an inconsistency it needs to report an error;
323 just refusing to run the code ensures that the error doesn't cascade,
324 but by itself it isn't very useful. A clear understanding of the sort
325 of error message that are useful will help guide the process of
328 At a simplistic level, the only sort of error that type analysis can
329 report is that the type of some construct doesn't match a contextual
330 requirement. For example, in `4 + "hello"` the addition provides a
331 contextual requirement for numbers, but `"hello"` is not a number. In
332 this particular example no further information is needed as the types
333 are obvious from local information. When a variable is involved that
334 isn't the case. It may be helpful to explain why the variable has a
335 particular type, by indicating the location where the type was set,
336 whether by declaration or usage.
338 Using a recursive-descent analysis we can easily detect a problem at
339 multiple locations. In "`hello:= "there"; 4 + hello`" the addition
340 will detect that one argument is not a number and the usage of `hello`
341 will detect that a number was wanted, but not provided. In this
342 (early) version of the language, we will generate error reports at
343 multiple locations, so the use of `hello` will report an error and
344 explain were the value was set, and the addition will report an error
345 and say why numbers are needed. To be able to report locations for
346 errors, each language element will need to record a file location
347 (line and column) and each variable will need to record the language
348 element where its type was set. For now we will assume that each line
349 of an error message indicates one location in the file, and up to 2
350 types. So we provide a `printf`-like function which takes a format, a
351 location (a `struct exec` which has not yet been introduced), and 2
352 types. "`%1`" reports the first type, "`%2`" reports the second. We
353 will need a function to print the location, once we know how that is
354 stored. e As will be explained later, there are sometimes extra rules for
355 type matching and they might affect error messages, we need to pass those
358 As well as type errors, we sometimes need to report problems with
359 tokens, which might be unexpected or might name a type that has not
360 been defined. For these we have `tok_err()` which reports an error
361 with a given token. Each of the error functions sets the flag in the
362 context so indicate that parsing failed.
366 static void fput_loc(struct exec *loc, FILE *f);
367 static void type_err(struct parse_context *c,
368 char *fmt, struct exec *loc,
369 struct type *t1, int rules, struct type *t2);
370 static void tok_err(struct parse_context *c, char *fmt, struct token *t);
372 ###### core functions
374 static void type_err(struct parse_context *c,
375 char *fmt, struct exec *loc,
376 struct type *t1, int rules, struct type *t2)
378 fprintf(stderr, "%s:", c->file_name);
379 fput_loc(loc, stderr);
380 for (; *fmt ; fmt++) {
387 case '%': fputc(*fmt, stderr); break; // NOTEST
388 default: fputc('?', stderr); break; // NOTEST
390 type_print(t1, stderr);
393 type_print(t2, stderr);
402 static void tok_err(struct parse_context *c, char *fmt, struct token *t)
404 fprintf(stderr, "%s:%d:%d: %s: %.*s\n", c->file_name, t->line, t->col, fmt,
405 t->txt.len, t->txt.txt);
409 ## Entities: declared and predeclared.
411 There are various "things" that the language and/or the interpreter
412 needs to know about to parse and execute a program. These include
413 types, variables, values, and executable code. These are all lumped
414 together under the term "entities" (calling them "objects" would be
415 confusing) and introduced here. The following section will present the
416 different specific code elements which comprise or manipulate these
421 Executables can be lots of different things. In many cases an
422 executable is just an operation combined with one or two other
423 executables. This allows for expressions and lists etc. Other times an
424 executable is something quite specific like a constant or variable name.
425 So we define a `struct exec` to be a general executable with a type, and
426 a `struct binode` which is a subclass of `exec`, forms a node in a
427 binary tree, and holds an operation. There will be other subclasses,
428 and to access these we need to be able to `cast` the `exec` into the
429 various other types. The first field in any `struct exec` is the type
430 from the `exec_types` enum.
433 #define cast(structname, pointer) ({ \
434 const typeof( ((struct structname *)0)->type) *__mptr = &(pointer)->type; \
435 if (__mptr && *__mptr != X##structname) abort(); \
436 (struct structname *)( (char *)__mptr);})
438 #define new(structname) ({ \
439 struct structname *__ptr = ((struct structname *)calloc(1,sizeof(struct structname))); \
440 __ptr->type = X##structname; \
441 __ptr->line = -1; __ptr->column = -1; \
444 #define new_pos(structname, token) ({ \
445 struct structname *__ptr = ((struct structname *)calloc(1,sizeof(struct structname))); \
446 __ptr->type = X##structname; \
447 __ptr->line = token.line; __ptr->column = token.col; \
456 enum exec_types type;
465 struct exec *left, *right;
470 static int __fput_loc(struct exec *loc, FILE *f)
474 if (loc->line >= 0) {
475 fprintf(f, "%d:%d: ", loc->line, loc->column);
478 if (loc->type == Xbinode)
479 return __fput_loc(cast(binode,loc)->left, f) ||
480 __fput_loc(cast(binode,loc)->right, f); // NOTEST
483 static void fput_loc(struct exec *loc, FILE *f)
485 if (!__fput_loc(loc, f))
486 fprintf(f, "??:??: ");
489 Each different type of `exec` node needs a number of functions defined,
490 a bit like methods. We must be able to free it, print it, analyse it
491 and execute it. Once we have specific `exec` types we will need to
492 parse them too. Let's take this a bit more slowly.
496 The parser generator requires a `free_foo` function for each struct
497 that stores attributes and they will often be `exec`s and subtypes
498 there-of. So we need `free_exec` which can handle all the subtypes,
499 and we need `free_binode`.
503 static void free_binode(struct binode *b)
512 ###### core functions
513 static void free_exec(struct exec *e)
524 static void free_exec(struct exec *e);
526 ###### free exec cases
527 case Xbinode: free_binode(cast(binode, e)); break;
531 Printing an `exec` requires that we know the current indent level for
532 printing line-oriented components. As will become clear later, we
533 also want to know what sort of bracketing to use.
537 static void do_indent(int i, char *str)
544 ###### core functions
545 static void print_binode(struct binode *b, int indent, int bracket)
549 ## print binode cases
553 static void print_exec(struct exec *e, int indent, int bracket)
559 print_binode(cast(binode, e), indent, bracket); break;
564 do_indent(indent, "/* FREE");
565 for (v = e->to_free; v; v = v->next_free) {
566 printf(" %.*s", v->name->name.len, v->name->name.txt);
567 printf("[%d,%d]", v->scope_start, v->scope_end);
568 if (v->frame_pos >= 0)
569 printf("(%d+%d)", v->frame_pos,
570 v->type ? v->type->size:0);
578 static void print_exec(struct exec *e, int indent, int bracket);
582 As discussed, analysis involves propagating type requirements around the
583 program and looking for errors.
585 So `propagate_types` is passed an expected type (being a `struct type`
586 pointer together with some `val_rules` flags) that the `exec` is
587 expected to return, and returns the type that it does return, either of
588 which can be `NULL` signifying "unknown". A `prop_err` flag set is
589 passed by reference. It has `Efail` set when an error is found, and
590 `Eretry` when the type for some element is set via propagation. If
591 any expression cannot be evaluated immediately, `Enoconst` is set.
593 If it remains unchanged at `0`, then no more propagation is needed.
597 enum val_rules {Rnolabel = 1<<0, Rboolok = 1<<1, Rnoconstant = 1<<2};
598 enum prop_err {Efail = 1<<0, Eretry = 1<<1, Enoconst = 1<<2};
602 if (rules & Rnolabel)
603 fputs(" (labels not permitted)", stderr);
607 static struct type *propagate_types(struct exec *prog, struct parse_context *c, enum prop_err *perr,
608 struct type *type, int rules);
609 ###### core functions
611 static struct type *__propagate_types(struct exec *prog, struct parse_context *c, enum prop_err *perr,
612 struct type *type, int rules)
619 switch (prog->type) {
622 struct binode *b = cast(binode, prog);
624 ## propagate binode cases
628 ## propagate exec cases
633 static struct type *propagate_types(struct exec *prog, struct parse_context *c, enum prop_err *perr,
634 struct type *type, int rules)
636 int pre_err = c->parse_error;
637 struct type *ret = __propagate_types(prog, c, perr, type, rules);
639 if (c->parse_error > pre_err)
646 Interpreting an `exec` doesn't require anything but the `exec`. State
647 is stored in variables and each variable will be directly linked from
648 within the `exec` tree. The exception to this is the `main` function
649 which needs to look at command line arguments. This function will be
650 interpreted separately.
652 Each `exec` can return a value combined with a type in `struct lrval`.
653 The type may be `Tnone` but must be non-NULL. Some `exec`s will return
654 the location of a value, which can be updated, in `lval`. Others will
655 set `lval` to NULL indicating that there is a value of appropriate type
659 static struct value interp_exec(struct parse_context *c, struct exec *e,
660 struct type **typeret);
661 ###### core functions
665 struct value rval, *lval;
668 /* If dest is passed, dtype must give the expected type, and
669 * result can go there, in which case type is returned as NULL.
671 static struct lrval _interp_exec(struct parse_context *c, struct exec *e,
672 struct value *dest, struct type *dtype);
674 static struct value interp_exec(struct parse_context *c, struct exec *e,
675 struct type **typeret)
677 struct lrval ret = _interp_exec(c, e, NULL, NULL);
679 if (!ret.type) abort();
683 dup_value(ret.type, ret.lval, &ret.rval);
687 static struct value *linterp_exec(struct parse_context *c, struct exec *e,
688 struct type **typeret)
690 struct lrval ret = _interp_exec(c, e, NULL, NULL);
692 if (!ret.type) abort();
696 free_value(ret.type, &ret.rval);
700 /* dinterp_exec is used when the destination type is certain and
701 * the value has a place to go.
703 static void dinterp_exec(struct parse_context *c, struct exec *e,
704 struct value *dest, struct type *dtype,
707 struct lrval ret = _interp_exec(c, e, dest, dtype);
711 free_value(dtype, dest);
713 dup_value(dtype, ret.lval, dest);
715 memcpy(dest, &ret.rval, dtype->size);
718 static struct lrval _interp_exec(struct parse_context *c, struct exec *e,
719 struct value *dest, struct type *dtype)
721 /* If the result is copied to dest, ret.type is set to NULL */
723 struct value rv = {}, *lrv = NULL;
726 rvtype = ret.type = Tnone;
736 struct binode *b = cast(binode, e);
737 struct value left, right, *lleft;
738 struct type *ltype, *rtype;
739 ltype = rtype = Tnone;
741 ## interp binode cases
743 free_value(ltype, &left);
744 free_value(rtype, &right);
754 ## interp exec cleanup
760 Values come in a wide range of types, with more likely to be added.
761 Each type needs to be able to print its own values (for convenience at
762 least) as well as to compare two values, at least for equality and
763 possibly for order. For now, values might need to be duplicated and
764 freed, though eventually such manipulations will be better integrated
767 Rather than requiring every numeric type to support all numeric
768 operations (add, multiply, etc), we allow types to be able to present
769 as one of a few standard types: integer, float, and fraction. The
770 existence of these conversion functions eventually enable types to
771 determine if they are compatible with other types, though such types
772 have not yet been implemented.
774 Named type are stored in a simple linked list. Objects of each type are
775 "values" which are often passed around by value.
777 There are both explicitly named types, and anonymous types. Anonymous
778 cannot be accessed by name, but are used internally and have a name
779 which might be reported in error messages.
786 ## value union fields
793 struct token first_use;
796 void (*init)(struct type *type, struct value *val);
797 int (*prepare_type)(struct parse_context *c, struct type *type, int parse_time);
798 void (*print)(struct type *type, struct value *val, FILE *f);
799 void (*print_type)(struct type *type, FILE *f);
800 int (*cmp_order)(struct type *t1, struct type *t2,
801 struct value *v1, struct value *v2);
802 int (*cmp_eq)(struct type *t1, struct type *t2,
803 struct value *v1, struct value *v2);
804 void (*dup)(struct type *type, struct value *vold, struct value *vnew);
805 void (*free)(struct type *type, struct value *val);
806 void (*free_type)(struct type *t);
807 long long (*to_int)(struct value *v);
808 double (*to_float)(struct value *v);
809 int (*to_mpq)(mpq_t *q, struct value *v);
818 struct type *typelist;
825 static struct type *find_type(struct parse_context *c, struct text s)
827 struct type *t = c->typelist;
829 while (t && (t->anon ||
830 text_cmp(t->name, s) != 0))
835 static struct type *_add_type(struct parse_context *c, struct text s,
836 struct type *proto, int anon)
840 n = calloc(1, sizeof(*n));
847 n->next = c->typelist;
852 static struct type *add_type(struct parse_context *c, struct text s,
855 return _add_type(c, s, proto, 0);
858 static struct type *add_anon_type(struct parse_context *c,
859 struct type *proto, char *name, ...)
865 vasprintf(&t.txt, name, ap);
867 t.len = strlen(name);
868 return _add_type(c, t, proto, 1);
871 static void free_type(struct type *t)
873 /* The type is always a reference to something in the
874 * context, so we don't need to free anything.
878 static void free_value(struct type *type, struct value *v)
882 memset(v, 0x5a, type->size);
886 static void type_print(struct type *type, FILE *f)
889 fputs("*unknown*type*", f); // NOTEST
890 else if (type->name.len && !type->anon)
891 fprintf(f, "%.*s", type->name.len, type->name.txt);
892 else if (type->print_type)
893 type->print_type(type, f);
895 fputs("*invalid*type*", f);
898 static void val_init(struct type *type, struct value *val)
900 if (type && type->init)
901 type->init(type, val);
904 static void dup_value(struct type *type,
905 struct value *vold, struct value *vnew)
907 if (type && type->dup)
908 type->dup(type, vold, vnew);
911 static int value_cmp(struct type *tl, struct type *tr,
912 struct value *left, struct value *right)
914 if (tl && tl->cmp_order)
915 return tl->cmp_order(tl, tr, left, right);
916 if (tl && tl->cmp_eq) // NOTEST
917 return tl->cmp_eq(tl, tr, left, right); // NOTEST
921 static void print_value(struct type *type, struct value *v, FILE *f)
923 if (type && type->print)
924 type->print(type, v, f);
926 fprintf(f, "*Unknown*"); // NOTEST
929 static void prepare_types(struct parse_context *c)
933 enum { none, some, cannot } progress = none;
938 for (t = c->typelist; t; t = t->next) {
940 tok_err(c, "error: type used but not declared",
942 if (t->size == 0 && t->prepare_type) {
943 if (t->prepare_type(c, t, 1))
945 else if (progress == cannot)
946 tok_err(c, "error: type has recursive definition",
956 progress = cannot; break;
958 progress = none; break;
965 static void free_value(struct type *type, struct value *v);
966 static int type_compat(struct type *require, struct type *have, int rules);
967 static void type_print(struct type *type, FILE *f);
968 static void val_init(struct type *type, struct value *v);
969 static void dup_value(struct type *type,
970 struct value *vold, struct value *vnew);
971 static int value_cmp(struct type *tl, struct type *tr,
972 struct value *left, struct value *right);
973 static void print_value(struct type *type, struct value *v, FILE *f);
975 ###### free context types
977 while (context.typelist) {
978 struct type *t = context.typelist;
980 context.typelist = t->next;
988 Type can be specified for local variables, for fields in a structure,
989 for formal parameters to functions, and possibly elsewhere. Different
990 rules may apply in different contexts. As a minimum, a named type may
991 always be used. Currently the type of a formal parameter can be
992 different from types in other contexts, so we have a separate grammar
998 Type -> IDENTIFIER ${
999 $0 = find_type(c, $ID.txt);
1001 $0 = add_type(c, $ID.txt, NULL);
1002 $0->first_use = $ID;
1007 FormalType -> Type ${ $0 = $<1; }$
1008 ## formal type grammar
1012 Values of the base types can be numbers, which we represent as
1013 multi-precision fractions, strings, Booleans and labels. When
1014 analysing the program we also need to allow for places where no value
1015 is meaningful (type `Tnone`) and where we don't know what type to
1016 expect yet (type is `NULL`).
1018 Values are never shared, they are always copied when used, and freed
1019 when no longer needed.
1021 When propagating type information around the program, we need to
1022 determine if two types are compatible, where type `NULL` is compatible
1023 with anything. There are two special cases with type compatibility,
1024 both related to the Conditional Statement which will be described
1025 later. In some cases a Boolean can be accepted as well as some other
1026 primary type, and in others any type is acceptable except a label (`Vlabel`).
1027 A separate function encoding these cases will simplify some code later.
1029 ###### type functions
1031 int (*compat)(struct type *this, struct type *other);
1033 ###### ast functions
1035 static int type_compat(struct type *require, struct type *have, int rules)
1037 if ((rules & Rboolok) && have == Tbool)
1039 if ((rules & Rnolabel) && have == Tlabel)
1041 if (!require || !have)
1044 if (require->compat)
1045 return require->compat(require, have);
1047 return require == have;
1052 #include "parse_string.h"
1053 #include "parse_number.h"
1056 myLDLIBS := libnumber.o libstring.o -lgmp
1057 LDLIBS := $(filter-out $(myLDLIBS),$(LDLIBS)) $(myLDLIBS)
1059 ###### type union fields
1060 enum vtype {Vnone, Vstr, Vnum, Vbool, Vlabel} vtype;
1062 ###### value union fields
1068 ###### ast functions
1069 static void _free_value(struct type *type, struct value *v)
1073 switch (type->vtype) {
1075 case Vstr: free(v->str.txt); break;
1076 case Vnum: mpq_clear(v->num); break;
1082 ###### value functions
1084 static void _val_init(struct type *type, struct value *val)
1086 switch(type->vtype) {
1087 case Vnone: // NOTEST
1090 mpq_init(val->num); break;
1092 val->str.txt = malloc(1);
1104 static void _dup_value(struct type *type,
1105 struct value *vold, struct value *vnew)
1107 switch (type->vtype) {
1108 case Vnone: // NOTEST
1111 vnew->label = vold->label;
1114 vnew->bool = vold->bool;
1117 mpq_init(vnew->num);
1118 mpq_set(vnew->num, vold->num);
1121 vnew->str.len = vold->str.len;
1122 vnew->str.txt = malloc(vnew->str.len);
1123 memcpy(vnew->str.txt, vold->str.txt, vnew->str.len);
1128 static int _value_cmp(struct type *tl, struct type *tr,
1129 struct value *left, struct value *right)
1133 return tl - tr; // NOTEST
1134 switch (tl->vtype) {
1135 case Vlabel: cmp = left->label == right->label ? 0 : 1; break;
1136 case Vnum: cmp = mpq_cmp(left->num, right->num); break;
1137 case Vstr: cmp = text_cmp(left->str, right->str); break;
1138 case Vbool: cmp = left->bool - right->bool; break;
1139 case Vnone: cmp = 0; // NOTEST
1144 static void _print_value(struct type *type, struct value *v, FILE *f)
1146 switch (type->vtype) {
1147 case Vnone: // NOTEST
1148 fprintf(f, "*no-value*"); break; // NOTEST
1149 case Vlabel: // NOTEST
1150 fprintf(f, "*label-%p*", v->label); break; // NOTEST
1152 fprintf(f, "%.*s", v->str.len, v->str.txt); break;
1154 fprintf(f, "%s", v->bool ? "True":"False"); break;
1159 mpf_set_q(fl, v->num);
1160 gmp_fprintf(f, "%.10Fg", fl);
1167 static void _free_value(struct type *type, struct value *v);
1169 static struct type base_prototype = {
1171 .print = _print_value,
1172 .cmp_order = _value_cmp,
1173 .cmp_eq = _value_cmp,
1175 .free = _free_value,
1178 static struct type *Tbool, *Tstr, *Tnum, *Tnone, *Tlabel;
1180 ###### ast functions
1181 static struct type *add_base_type(struct parse_context *c, char *n,
1182 enum vtype vt, int size)
1184 struct text txt = { n, strlen(n) };
1187 t = add_type(c, txt, &base_prototype);
1190 t->align = size > sizeof(void*) ? sizeof(void*) : size;
1191 if (t->size & (t->align - 1))
1192 t->size = (t->size | (t->align - 1)) + 1; // NOTEST
1196 ###### context initialization
1198 Tbool = add_base_type(&context, "Boolean", Vbool, sizeof(char));
1199 Tstr = add_base_type(&context, "string", Vstr, sizeof(struct text));
1200 Tnum = add_base_type(&context, "number", Vnum, sizeof(mpq_t));
1201 Tnone = add_base_type(&context, "none", Vnone, 0);
1202 Tlabel = add_base_type(&context, "label", Vlabel, sizeof(void*));
1206 We have already met values as separate objects. When manifest constants
1207 appear in the program text, that must result in an executable which has
1208 a constant value. So the `val` structure embeds a value in an
1221 ###### ast functions
1222 struct val *new_val(struct type *T, struct token tk)
1224 struct val *v = new_pos(val, tk);
1235 $0 = new_val(Tbool, $1);
1239 $0 = new_val(Tbool, $1);
1244 $0 = new_val(Tnum, $1);
1245 if (number_parse($0->val.num, tail, $1.txt) == 0)
1246 mpq_init($0->val.num); // UNTESTED
1248 tok_err(c, "error: unsupported number suffix",
1253 $0 = new_val(Tstr, $1);
1254 string_parse(&$1, '\\', &$0->val.str, tail);
1256 tok_err(c, "error: unsupported string suffix",
1261 $0 = new_val(Tstr, $1);
1262 string_parse(&$1, '\\', &$0->val.str, tail);
1264 tok_err(c, "error: unsupported string suffix",
1268 ###### print exec cases
1271 struct val *v = cast(val, e);
1272 if (v->vtype == Tstr)
1274 // FIXME how to ensure numbers have same precision.
1275 print_value(v->vtype, &v->val, stdout);
1276 if (v->vtype == Tstr)
1281 ###### propagate exec cases
1284 struct val *val = cast(val, prog);
1285 if (!type_compat(type, val->vtype, rules))
1286 type_err(c, "error: expected %1%r found %2",
1287 prog, type, rules, val->vtype);
1291 ###### interp exec cases
1293 rvtype = cast(val, e)->vtype;
1294 dup_value(rvtype, &cast(val, e)->val, &rv);
1297 ###### ast functions
1298 static void free_val(struct val *v)
1301 free_value(v->vtype, &v->val);
1305 ###### free exec cases
1306 case Xval: free_val(cast(val, e)); break;
1308 ###### ast functions
1309 // Move all nodes from 'b' to 'rv', reversing their order.
1310 // In 'b' 'left' is a list, and 'right' is the last node.
1311 // In 'rv', left' is the first node and 'right' is a list.
1312 static struct binode *reorder_bilist(struct binode *b)
1314 struct binode *rv = NULL;
1317 struct exec *t = b->right;
1321 b = cast(binode, b->left);
1331 Variables are scoped named values. We store the names in a linked list
1332 of "bindings" sorted in lexical order, and use sequential search and
1339 struct binding *next; // in lexical order
1343 This linked list is stored in the parse context so that "reduce"
1344 functions can find or add variables, and so the analysis phase can
1345 ensure that every variable gets a type.
1347 ###### parse context
1349 struct binding *varlist; // In lexical order
1351 ###### ast functions
1353 static struct binding *find_binding(struct parse_context *c, struct text s)
1355 struct binding **l = &c->varlist;
1360 (cmp = text_cmp((*l)->name, s)) < 0)
1364 n = calloc(1, sizeof(*n));
1371 Each name can be linked to multiple variables defined in different
1372 scopes. Each scope starts where the name is declared and continues
1373 until the end of the containing code block. Scopes of a given name
1374 cannot nest, so a declaration while a name is in-scope is an error.
1376 ###### binding fields
1377 struct variable *var;
1381 struct variable *previous;
1383 struct binding *name;
1384 struct exec *where_decl;// where name was declared
1385 struct exec *where_set; // where type was set
1389 When a scope closes, the values of the variables might need to be freed.
1390 This happens in the context of some `struct exec` and each `exec` will
1391 need to know which variables need to be freed when it completes.
1394 struct variable *to_free;
1396 ####### variable fields
1397 struct exec *cleanup_exec;
1398 struct variable *next_free;
1400 ####### interp exec cleanup
1403 for (v = e->to_free; v; v = v->next_free) {
1404 struct value *val = var_value(c, v);
1405 free_value(v->type, val);
1409 ###### ast functions
1410 static void variable_unlink_exec(struct variable *v)
1412 struct variable **vp;
1413 if (!v->cleanup_exec)
1415 for (vp = &v->cleanup_exec->to_free;
1416 *vp; vp = &(*vp)->next_free) {
1420 v->cleanup_exec = NULL;
1425 While the naming seems strange, we include local constants in the
1426 definition of variables. A name declared `var := value` can
1427 subsequently be changed, but a name declared `var ::= value` cannot -
1430 ###### variable fields
1433 Scopes in parallel branches can be partially merged. More
1434 specifically, if a given name is declared in both branches of an
1435 if/else then its scope is a candidate for merging. Similarly if
1436 every branch of an exhaustive switch (e.g. has an "else" clause)
1437 declares a given name, then the scopes from the branches are
1438 candidates for merging.
1440 Note that names declared inside a loop (which is only parallel to
1441 itself) are never visible after the loop. Similarly names defined in
1442 scopes which are not parallel, such as those started by `for` and
1443 `switch`, are never visible after the scope. Only variables defined in
1444 both `then` and `else` (including the implicit then after an `if`, and
1445 excluding `then` used with `for`) and in all `case`s and `else` of a
1446 `switch` or `while` can be visible beyond the `if`/`switch`/`while`.
1448 Labels, which are a bit like variables, follow different rules.
1449 Labels are not explicitly declared, but if an undeclared name appears
1450 in a context where a label is legal, that effectively declares the
1451 name as a label. The declaration remains in force (or in scope) at
1452 least to the end of the immediately containing block and conditionally
1453 in any larger containing block which does not declare the name in some
1454 other way. Importantly, the conditional scope extension happens even
1455 if the label is only used in one parallel branch of a conditional --
1456 when used in one branch it is treated as having been declared in all
1459 Merge candidates are tentatively visible beyond the end of the
1460 branching statement which creates them. If the name is used, the
1461 merge is affirmed and they become a single variable visible at the
1462 outer layer. If not - if it is redeclared first - the merge lapses.
1464 To track scopes we have an extra stack, implemented as a linked list,
1465 which roughly parallels the parse stack and which is used exclusively
1466 for scoping. When a new scope is opened, a new frame is pushed and
1467 the child-count of the parent frame is incremented. This child-count
1468 is used to distinguish between the first of a set of parallel scopes,
1469 in which declared variables must not be in scope, and subsequent
1470 branches, whether they may already be conditionally scoped.
1472 We need a total ordering of scopes so we can easily compare to variables
1473 to see if they are concurrently in scope. To achieve this we record a
1474 `scope_count` which is actually a count of both beginnings and endings
1475 of scopes. Then each variable has a record of the scope count where it
1476 enters scope, and where it leaves.
1478 To push a new frame *before* any code in the frame is parsed, we need a
1479 grammar reduction. This is most easily achieved with a grammar
1480 element which derives the empty string, and creates the new scope when
1481 it is recognised. This can be placed, for example, between a keyword
1482 like "if" and the code following it.
1486 struct scope *parent;
1490 ###### parse context
1493 struct scope *scope_stack;
1495 ###### variable fields
1496 int scope_start, scope_end;
1498 ###### ast functions
1499 static void scope_pop(struct parse_context *c)
1501 struct scope *s = c->scope_stack;
1503 c->scope_stack = s->parent;
1505 c->scope_depth -= 1;
1506 c->scope_count += 1;
1509 static void scope_push(struct parse_context *c)
1511 struct scope *s = calloc(1, sizeof(*s));
1513 c->scope_stack->child_count += 1;
1514 s->parent = c->scope_stack;
1516 c->scope_depth += 1;
1517 c->scope_count += 1;
1523 OpenScope -> ${ scope_push(c); }$
1525 Each variable records a scope depth and is in one of four states:
1527 - "in scope". This is the case between the declaration of the
1528 variable and the end of the containing block, and also between
1529 the usage with affirms a merge and the end of that block.
1531 The scope depth is not greater than the current parse context scope
1532 nest depth. When the block of that depth closes, the state will
1533 change. To achieve this, all "in scope" variables are linked
1534 together as a stack in nesting order.
1536 - "pending". The "in scope" block has closed, but other parallel
1537 scopes are still being processed. So far, every parallel block at
1538 the same level that has closed has declared the name.
1540 The scope depth is the depth of the last parallel block that
1541 enclosed the declaration, and that has closed.
1543 - "conditionally in scope". The "in scope" block and all parallel
1544 scopes have closed, and no further mention of the name has been seen.
1545 This state includes a secondary nest depth (`min_depth`) which records
1546 the outermost scope seen since the variable became conditionally in
1547 scope. If a use of the name is found, the variable becomes "in scope"
1548 and that secondary depth becomes the recorded scope depth. If the
1549 name is declared as a new variable, the old variable becomes "out of
1550 scope" and the recorded scope depth stays unchanged.
1552 - "out of scope". The variable is neither in scope nor conditionally
1553 in scope. It is permanently out of scope now and can be removed from
1554 the "in scope" stack. When a variable becomes out-of-scope it is
1555 moved to a separate list (`out_scope`) of variables which have fully
1556 known scope. This will be used at the end of each function to assign
1557 each variable a place in the stack frame.
1559 ###### variable fields
1560 int depth, min_depth;
1561 enum { OutScope, PendingScope, CondScope, InScope } scope;
1562 struct variable *in_scope;
1564 ###### parse context
1566 struct variable *in_scope;
1567 struct variable *out_scope;
1569 All variables with the same name are linked together using the
1570 'previous' link. Those variable that have been affirmatively merged all
1571 have a 'merged' pointer that points to one primary variable - the most
1572 recently declared instance. When merging variables, we need to also
1573 adjust the 'merged' pointer on any other variables that had previously
1574 been merged with the one that will no longer be primary.
1576 A variable that is no longer the most recent instance of a name may
1577 still have "pending" scope, if it might still be merged with most
1578 recent instance. These variables don't really belong in the
1579 "in_scope" list, but are not immediately removed when a new instance
1580 is found. Instead, they are detected and ignored when considering the
1581 list of in_scope names.
1583 The storage of the value of a variable will be described later. For now
1584 we just need to know that when a variable goes out of scope, it might
1585 need to be freed. For this we need to be able to find it, so assume that
1586 `var_value()` will provide that.
1588 ###### variable fields
1589 struct variable *merged;
1591 ###### ast functions
1593 static void variable_merge(struct variable *primary, struct variable *secondary)
1597 primary = primary->merged;
1599 for (v = primary->previous; v; v=v->previous)
1600 if (v == secondary || v == secondary->merged ||
1601 v->merged == secondary ||
1602 v->merged == secondary->merged) {
1603 v->scope = OutScope;
1604 v->merged = primary;
1605 if (v->scope_start < primary->scope_start)
1606 primary->scope_start = v->scope_start;
1607 if (v->scope_end > primary->scope_end)
1608 primary->scope_end = v->scope_end; // NOTEST
1609 variable_unlink_exec(v);
1613 ###### forward decls
1614 static struct value *var_value(struct parse_context *c, struct variable *v);
1616 ###### free global vars
1618 while (context.varlist) {
1619 struct binding *b = context.varlist;
1620 struct variable *v = b->var;
1621 context.varlist = b->next;
1624 struct variable *next = v->previous;
1626 if (v->global && v->frame_pos >= 0) {
1627 free_value(v->type, var_value(&context, v));
1628 if (v->depth == 0 && v->type->free == function_free)
1629 // This is a function constant
1630 free_exec(v->where_decl);
1637 #### Manipulating Bindings
1639 When a name is conditionally visible, a new declaration discards the old
1640 binding - the condition lapses. Similarly when we reach the end of a
1641 function (outermost non-global scope) any conditional scope must lapse.
1642 Conversely a usage of the name affirms the visibility and extends it to
1643 the end of the containing block - i.e. the block that contains both the
1644 original declaration and the latest usage. This is determined from
1645 `min_depth`. When a conditionally visible variable gets affirmed like
1646 this, it is also merged with other conditionally visible variables with
1649 When we parse a variable declaration we either report an error if the
1650 name is currently bound, or create a new variable at the current nest
1651 depth if the name is unbound or bound to a conditionally scoped or
1652 pending-scope variable. If the previous variable was conditionally
1653 scoped, it and its homonyms becomes out-of-scope.
1655 When we parse a variable reference (including non-declarative assignment
1656 "foo = bar") we report an error if the name is not bound or is bound to
1657 a pending-scope variable; update the scope if the name is bound to a
1658 conditionally scoped variable; or just proceed normally if the named
1659 variable is in scope.
1661 When we exit a scope, any variables bound at this level are either
1662 marked out of scope or pending-scoped, depending on whether the scope
1663 was sequential or parallel. Here a "parallel" scope means the "then"
1664 or "else" part of a conditional, or any "case" or "else" branch of a
1665 switch. Other scopes are "sequential".
1667 When exiting a parallel scope we check if there are any variables that
1668 were previously pending and are still visible. If there are, then
1669 they weren't redeclared in the most recent scope, so they cannot be
1670 merged and must become out-of-scope. If it is not the first of
1671 parallel scopes (based on `child_count`), we check that there was a
1672 previous binding that is still pending-scope. If there isn't, the new
1673 variable must now be out-of-scope.
1675 When exiting a sequential scope that immediately enclosed parallel
1676 scopes, we need to resolve any pending-scope variables. If there was
1677 no `else` clause, and we cannot determine that the `switch` was exhaustive,
1678 we need to mark all pending-scope variable as out-of-scope. Otherwise
1679 all pending-scope variables become conditionally scoped.
1682 enum closetype { CloseSequential, CloseFunction, CloseParallel, CloseElse };
1684 ###### ast functions
1686 static struct variable *var_decl(struct parse_context *c, struct text s)
1688 struct binding *b = find_binding(c, s);
1689 struct variable *v = b->var;
1691 switch (v ? v->scope : OutScope) {
1693 /* Caller will report the error */
1697 v && v->scope == CondScope;
1699 v->scope = OutScope;
1703 v = calloc(1, sizeof(*v));
1704 v->previous = b->var;
1708 v->min_depth = v->depth = c->scope_depth;
1710 v->in_scope = c->in_scope;
1711 v->scope_start = c->scope_count;
1717 static struct variable *var_ref(struct parse_context *c, struct text s)
1719 struct binding *b = find_binding(c, s);
1720 struct variable *v = b->var;
1721 struct variable *v2;
1723 switch (v ? v->scope : OutScope) {
1726 /* Caller will report the error */
1729 /* All CondScope variables of this name need to be merged
1730 * and become InScope
1732 v->depth = v->min_depth;
1734 for (v2 = v->previous;
1735 v2 && v2->scope == CondScope;
1737 variable_merge(v, v2);
1745 static int var_refile(struct parse_context *c, struct variable *v)
1747 /* Variable just went out of scope. Add it to the out_scope
1748 * list, sorted by ->scope_start
1750 struct variable **vp = &c->out_scope;
1751 while ((*vp) && (*vp)->scope_start < v->scope_start)
1752 vp = &(*vp)->in_scope;
1758 static void var_block_close(struct parse_context *c, enum closetype ct,
1761 /* Close off all variables that are in_scope.
1762 * Some variables in c->scope may already be not-in-scope,
1763 * such as when a PendingScope variable is hidden by a new
1764 * variable with the same name.
1765 * So we check for v->name->var != v and drop them.
1766 * If we choose to make a variable OutScope, we drop it
1769 struct variable *v, **vp, *v2;
1772 for (vp = &c->in_scope;
1773 (v = *vp) && v->min_depth > c->scope_depth;
1774 (v->scope == OutScope || v->name->var != v)
1775 ? (*vp = v->in_scope, var_refile(c, v))
1776 : ( vp = &v->in_scope, 0)) {
1777 v->min_depth = c->scope_depth;
1778 if (v->name->var != v)
1779 /* This is still in scope, but we haven't just
1783 v->min_depth = c->scope_depth;
1784 if (v->scope == InScope)
1785 v->scope_end = c->scope_count;
1786 if (v->scope == InScope && e && !v->global) {
1787 /* This variable gets cleaned up when 'e' finishes */
1788 variable_unlink_exec(v);
1789 v->cleanup_exec = e;
1790 v->next_free = e->to_free;
1795 case CloseParallel: /* handle PendingScope */
1799 if (c->scope_stack->child_count == 1)
1800 /* first among parallel branches */
1801 v->scope = PendingScope;
1802 else if (v->previous &&
1803 v->previous->scope == PendingScope)
1804 /* all previous branches used name */
1805 v->scope = PendingScope;
1806 else if (v->type == Tlabel)
1807 /* Labels remain pending even when not used */
1808 v->scope = PendingScope; // UNTESTED
1810 v->scope = OutScope;
1811 if (ct == CloseElse) {
1812 /* All Pending variables with this name
1813 * are now Conditional */
1815 v2 && v2->scope == PendingScope;
1817 v2->scope = CondScope;
1821 /* Not possible as it would require
1822 * parallel scope to be nested immediately
1823 * in a parallel scope, and that never
1827 /* Not possible as we already tested for
1834 if (v->scope == CondScope)
1835 /* Condition cannot continue past end of function */
1838 case CloseSequential:
1839 if (v->type == Tlabel)
1840 v->scope = PendingScope;
1843 v->scope = OutScope;
1846 /* There was no 'else', so we can only become
1847 * conditional if we know the cases were exhaustive,
1848 * and that doesn't mean anything yet.
1849 * So only labels become conditional..
1852 v2 && v2->scope == PendingScope;
1854 if (v2->type == Tlabel)
1855 v2->scope = CondScope;
1857 v2->scope = OutScope;
1860 case OutScope: break;
1869 The value of a variable is store separately from the variable, on an
1870 analogue of a stack frame. There are (currently) two frames that can be
1871 active. A global frame which currently only stores constants, and a
1872 stacked frame which stores local variables. Each variable knows if it
1873 is global or not, and what its index into the frame is.
1875 Values in the global frame are known immediately they are relevant, so
1876 the frame needs to be reallocated as it grows so it can store those
1877 values. The local frame doesn't get values until the interpreted phase
1878 is started, so there is no need to allocate until the size is known.
1880 We initialize the `frame_pos` to an impossible value, so that we can
1881 tell if it was set or not later.
1883 ###### variable fields
1887 ###### variable init
1890 ###### parse context
1892 short global_size, global_alloc;
1894 void *global, *local;
1896 ###### forward decls
1897 static struct value *global_alloc(struct parse_context *c, struct type *t,
1898 struct variable *v, struct value *init);
1900 ###### ast functions
1902 static struct value *var_value(struct parse_context *c, struct variable *v)
1905 if (!c->local || !v->type)
1906 return NULL; // UNTESTED
1907 if (v->frame_pos + v->type->size > c->local_size) {
1908 printf("INVALID frame_pos\n"); // NOTEST
1911 return c->local + v->frame_pos;
1913 if (c->global_size > c->global_alloc) {
1914 int old = c->global_alloc;
1915 c->global_alloc = (c->global_size | 1023) + 1024;
1916 c->global = realloc(c->global, c->global_alloc);
1917 memset(c->global + old, 0, c->global_alloc - old);
1919 return c->global + v->frame_pos;
1922 static struct value *global_alloc(struct parse_context *c, struct type *t,
1923 struct variable *v, struct value *init)
1926 struct variable scratch;
1928 if (t->prepare_type)
1929 t->prepare_type(c, t, 1); // NOTEST
1931 if (c->global_size & (t->align - 1))
1932 c->global_size = (c->global_size + t->align) & ~(t->align-1); // NOTEST
1937 v->frame_pos = c->global_size;
1939 c->global_size += v->type->size;
1940 ret = var_value(c, v);
1942 memcpy(ret, init, t->size);
1948 As global values are found -- struct field initializers, labels etc --
1949 `global_alloc()` is called to record the value in the global frame.
1951 When the program is fully parsed, each function is analysed, we need to
1952 walk the list of variables local to that function and assign them an
1953 offset in the stack frame. For this we have `scope_finalize()`.
1955 We keep the stack from dense by re-using space for between variables
1956 that are not in scope at the same time. The `out_scope` list is sorted
1957 by `scope_start` and as we process a varible, we move it to an FIFO
1958 stack. For each variable we consider, we first discard any from the
1959 stack anything that went out of scope before the new variable came in.
1960 Then we place the new variable just after the one at the top of the
1963 ###### ast functions
1965 static void scope_finalize(struct parse_context *c, struct type *ft)
1967 int size = ft->function.local_size;
1968 struct variable *next = ft->function.scope;
1969 struct variable *done = NULL;
1972 struct variable *v = next;
1973 struct type *t = v->type;
1980 if (v->frame_pos >= 0)
1982 while (done && done->scope_end < v->scope_start)
1983 done = done->in_scope;
1985 pos = done->frame_pos + done->type->size;
1987 pos = ft->function.local_size;
1988 if (pos & (t->align - 1))
1989 pos = (pos + t->align) & ~(t->align-1);
1991 if (size < pos + v->type->size)
1992 size = pos + v->type->size;
1996 c->out_scope = NULL;
1997 ft->function.local_size = size;
2000 ###### free context storage
2001 free(context.global);
2003 #### Variables as executables
2005 Just as we used a `val` to wrap a value into an `exec`, we similarly
2006 need a `var` to wrap a `variable` into an exec. While each `val`
2007 contained a copy of the value, each `var` holds a link to the variable
2008 because it really is the same variable no matter where it appears.
2009 When a variable is used, we need to remember to follow the `->merged`
2010 link to find the primary instance.
2012 When a variable is declared, it may or may not be given an explicit
2013 type. We need to record which so that we can report the parsed code
2022 struct variable *var;
2025 ###### variable fields
2033 VariableDecl -> IDENTIFIER : ${ {
2034 struct variable *v = var_decl(c, $1.txt);
2035 $0 = new_pos(var, $1);
2040 v = var_ref(c, $1.txt);
2042 type_err(c, "error: variable '%v' redeclared",
2044 type_err(c, "info: this is where '%v' was first declared",
2045 v->where_decl, NULL, 0, NULL);
2048 | IDENTIFIER :: ${ {
2049 struct variable *v = var_decl(c, $1.txt);
2050 $0 = new_pos(var, $1);
2056 v = var_ref(c, $1.txt);
2058 type_err(c, "error: variable '%v' redeclared",
2060 type_err(c, "info: this is where '%v' was first declared",
2061 v->where_decl, NULL, 0, NULL);
2064 | IDENTIFIER : Type ${ {
2065 struct variable *v = var_decl(c, $1.txt);
2066 $0 = new_pos(var, $1);
2072 v->explicit_type = 1;
2074 v = var_ref(c, $1.txt);
2076 type_err(c, "error: variable '%v' redeclared",
2078 type_err(c, "info: this is where '%v' was first declared",
2079 v->where_decl, NULL, 0, NULL);
2082 | IDENTIFIER :: Type ${ {
2083 struct variable *v = var_decl(c, $1.txt);
2084 $0 = new_pos(var, $1);
2091 v->explicit_type = 1;
2093 v = var_ref(c, $1.txt);
2095 type_err(c, "error: variable '%v' redeclared",
2097 type_err(c, "info: this is where '%v' was first declared",
2098 v->where_decl, NULL, 0, NULL);
2103 Variable -> IDENTIFIER ${ {
2104 struct variable *v = var_ref(c, $1.txt);
2105 $0 = new_pos(var, $1);
2107 /* This might be a global const or a label
2108 * Allocate a var with impossible type Tnone,
2109 * which will be adjusted when we find out what it is,
2110 * or will trigger an error.
2112 v = var_decl(c, $1.txt);
2119 cast(var, $0)->var = v;
2122 ###### print exec cases
2125 struct var *v = cast(var, e);
2127 struct binding *b = v->var->name;
2128 printf("%.*s", b->name.len, b->name.txt);
2135 if (loc && loc->type == Xvar) {
2136 struct var *v = cast(var, loc);
2138 struct binding *b = v->var->name;
2139 fprintf(stderr, "%.*s", b->name.len, b->name.txt);
2141 fputs("???", stderr); // NOTEST
2143 fputs("NOTVAR", stderr);
2146 ###### propagate exec cases
2150 struct var *var = cast(var, prog);
2151 struct variable *v = var->var;
2153 type_err(c, "%d:BUG: no variable!!", prog, NULL, 0, NULL); // NOTEST
2154 return Tnone; // NOTEST
2157 if (v->constant && (rules & Rnoconstant)) {
2158 type_err(c, "error: Cannot assign to a constant: %v",
2159 prog, NULL, 0, NULL);
2160 type_err(c, "info: name was defined as a constant here",
2161 v->where_decl, NULL, 0, NULL);
2164 if (v->type == Tnone && v->where_decl == prog)
2165 type_err(c, "error: variable used but not declared: %v",
2166 prog, NULL, 0, NULL);
2167 if (v->type == NULL) {
2168 if (type && !(*perr & Efail)) {
2170 v->where_set = prog;
2173 } else if (!type_compat(type, v->type, rules)) {
2174 type_err(c, "error: expected %1%r but variable '%v' is %2", prog,
2175 type, rules, v->type);
2176 type_err(c, "info: this is where '%v' was set to %1", v->where_set,
2177 v->type, rules, NULL);
2179 if (!v->global || v->frame_pos < 0)
2186 ###### interp exec cases
2189 struct var *var = cast(var, e);
2190 struct variable *v = var->var;
2193 lrv = var_value(c, v);
2198 ###### ast functions
2200 static void free_var(struct var *v)
2205 ###### free exec cases
2206 case Xvar: free_var(cast(var, e)); break;
2211 Now that we have the shape of the interpreter in place we can add some
2212 complex types and connected them in to the data structures and the
2213 different phases of parse, analyse, print, interpret.
2215 Being "complex" the language will naturally have syntax to access
2216 specifics of objects of these types. These will fit into the grammar as
2217 "Terms" which are the things that are combined with various operators to
2218 form "Expression". Where a Term is formed by some operation on another
2219 Term, the subordinate Term will always come first, so for example a
2220 member of an array will be expressed as the Term for the array followed
2221 by an index in square brackets. The strict rule of using postfix
2222 operations makes precedence irrelevant within terms. To provide a place
2223 to put the grammar for each terms of each type, we will start out by
2224 introducing the "Term" grammar production, with contains at least a
2225 simple "Value" (to be explained later).
2229 Term -> Value ${ $0 = $<1; }$
2230 | Variable ${ $0 = $<1; }$
2233 Thus far the complex types we have are arrays and structs.
2237 Arrays can be declared by giving a size and a type, as `[size]type' so
2238 `freq:[26]number` declares `freq` to be an array of 26 numbers. The
2239 size can be either a literal number, or a named constant. Some day an
2240 arbitrary expression will be supported.
2242 As a formal parameter to a function, the array can be declared with a
2243 new variable as the size: `name:[size::number]string`. The `size`
2244 variable is set to the size of the array and must be a constant. As
2245 `number` is the only supported type, it can be left out:
2246 `name:[size::]string`.
2248 Arrays cannot be assigned. When pointers are introduced we will also
2249 introduce array slices which can refer to part or all of an array -
2250 the assignment syntax will create a slice. For now, an array can only
2251 ever be referenced by the name it is declared with. It is likely that
2252 a "`copy`" primitive will eventually be define which can be used to
2253 make a copy of an array with controllable recursive depth.
2255 For now we have two sorts of array, those with fixed size either because
2256 it is given as a literal number or because it is a struct member (which
2257 cannot have a runtime-changing size), and those with a size that is
2258 determined at runtime - local variables with a const size. The former
2259 have their size calculated at parse time, the latter at run time.
2261 For the latter type, the `size` field of the type is the size of a
2262 pointer, and the array is reallocated every time it comes into scope.
2264 We differentiate struct fields with a const size from local variables
2265 with a const size by whether they are prepared at parse time or not.
2267 ###### type union fields
2270 int unspec; // size is unspecified - vsize must be set.
2273 struct variable *vsize;
2274 struct type *member;
2277 ###### value union fields
2278 void *array; // used if not static_size
2280 ###### value functions
2282 static int array_prepare_type(struct parse_context *c, struct type *type,
2285 struct value *vsize;
2287 if (type->array.static_size)
2288 return 1; // UNTESTED
2289 if (type->array.unspec && parse_time)
2290 return 1; // UNTESTED
2291 if (parse_time && type->array.vsize && !type->array.vsize->global)
2292 return 1; // UNTESTED
2294 if (type->array.vsize) {
2295 vsize = var_value(c, type->array.vsize);
2297 return 1; // UNTESTED
2299 mpz_tdiv_q(q, mpq_numref(vsize->num), mpq_denref(vsize->num));
2300 type->array.size = mpz_get_si(q);
2305 if (type->array.member->size <= 0)
2308 type->array.static_size = 1;
2309 type->size = type->array.size * type->array.member->size;
2310 type->align = type->array.member->align;
2315 static void array_init(struct type *type, struct value *val)
2318 void *ptr = val->ptr;
2322 if (!type->array.static_size) {
2323 val->array = calloc(type->array.size,
2324 type->array.member->size);
2327 for (i = 0; i < type->array.size; i++) {
2329 v = (void*)ptr + i * type->array.member->size;
2330 val_init(type->array.member, v);
2334 static void array_free(struct type *type, struct value *val)
2337 void *ptr = val->ptr;
2339 if (!type->array.static_size)
2341 for (i = 0; i < type->array.size; i++) {
2343 v = (void*)ptr + i * type->array.member->size;
2344 free_value(type->array.member, v);
2346 if (!type->array.static_size)
2350 static int array_compat(struct type *require, struct type *have)
2352 if (have->compat != require->compat)
2354 /* Both are arrays, so we can look at details */
2355 if (!type_compat(require->array.member, have->array.member, 0))
2357 if (have->array.unspec && require->array.unspec) {
2358 if (have->array.vsize && require->array.vsize &&
2359 have->array.vsize != require->array.vsize) // UNTESTED
2360 /* sizes might not be the same */
2361 return 0; // UNTESTED
2364 if (have->array.unspec || require->array.unspec)
2365 return 1; // UNTESTED
2366 if (require->array.vsize == NULL && have->array.vsize == NULL)
2367 return require->array.size == have->array.size;
2369 return require->array.vsize == have->array.vsize; // UNTESTED
2372 static void array_print_type(struct type *type, FILE *f)
2375 if (type->array.vsize) {
2376 struct binding *b = type->array.vsize->name;
2377 fprintf(f, "%.*s%s]", b->name.len, b->name.txt,
2378 type->array.unspec ? "::" : "");
2379 } else if (type->array.size)
2380 fprintf(f, "%d]", type->array.size);
2383 type_print(type->array.member, f);
2386 static struct type array_prototype = {
2388 .prepare_type = array_prepare_type,
2389 .print_type = array_print_type,
2390 .compat = array_compat,
2392 .size = sizeof(void*),
2393 .align = sizeof(void*),
2396 ###### declare terminals
2401 | [ NUMBER ] Type ${ {
2407 if (number_parse(num, tail, $2.txt) == 0)
2408 tok_err(c, "error: unrecognised number", &$2);
2410 tok_err(c, "error: unsupported number suffix", &$2);
2413 elements = mpz_get_ui(mpq_numref(num));
2414 if (mpz_cmp_ui(mpq_denref(num), 1) != 0) {
2415 tok_err(c, "error: array size must be an integer",
2417 } else if (mpz_cmp_ui(mpq_numref(num), 1UL << 30) >= 0)
2418 tok_err(c, "error: array size is too large",
2423 $0 = t = add_anon_type(c, &array_prototype, "array[%d]", elements );
2424 t->array.size = elements;
2425 t->array.member = $<4;
2426 t->array.vsize = NULL;
2429 | [ IDENTIFIER ] Type ${ {
2430 struct variable *v = var_ref(c, $2.txt);
2433 tok_err(c, "error: name undeclared", &$2);
2434 else if (!v->constant)
2435 tok_err(c, "error: array size must be a constant", &$2);
2437 $0 = add_anon_type(c, &array_prototype, "array[%.*s]", $2.txt.len, $2.txt.txt);
2438 $0->array.member = $<4;
2440 $0->array.vsize = v;
2445 OptType -> Type ${ $0 = $<1; }$
2448 ###### formal type grammar
2450 | [ IDENTIFIER :: OptType ] Type ${ {
2451 struct variable *v = var_decl(c, $ID.txt);
2457 $0 = add_anon_type(c, &array_prototype, "array[var]");
2458 $0->array.member = $<6;
2460 $0->array.unspec = 1;
2461 $0->array.vsize = v;
2469 | Term [ Expression ] ${ {
2470 struct binode *b = new(binode);
2477 ###### print binode cases
2479 print_exec(b->left, -1, bracket);
2481 print_exec(b->right, -1, bracket);
2485 ###### propagate binode cases
2487 /* left must be an array, right must be a number,
2488 * result is the member type of the array
2490 propagate_types(b->right, c, perr, Tnum, 0);
2491 t = propagate_types(b->left, c, perr, NULL, rules & Rnoconstant);
2492 if (!t || t->compat != array_compat) {
2493 type_err(c, "error: %1 cannot be indexed", prog, t, 0, NULL);
2496 if (!type_compat(type, t->array.member, rules)) {
2497 type_err(c, "error: have %1 but need %2", prog,
2498 t->array.member, rules, type);
2500 return t->array.member;
2504 ###### interp binode cases
2510 lleft = linterp_exec(c, b->left, <ype);
2511 right = interp_exec(c, b->right, &rtype);
2513 mpz_tdiv_q(q, mpq_numref(right.num), mpq_denref(right.num));
2517 if (ltype->array.static_size)
2520 ptr = *(void**)lleft;
2521 rvtype = ltype->array.member;
2522 if (i >= 0 && i < ltype->array.size)
2523 lrv = ptr + i * rvtype->size;
2525 val_init(ltype->array.member, &rv); // UNSAFE
2532 A `struct` is a data-type that contains one or more other data-types.
2533 It differs from an array in that each member can be of a different
2534 type, and they are accessed by name rather than by number. Thus you
2535 cannot choose an element by calculation, you need to know what you
2538 The language makes no promises about how a given structure will be
2539 stored in memory - it is free to rearrange fields to suit whatever
2540 criteria seems important.
2542 Structs are declared separately from program code - they cannot be
2543 declared in-line in a variable declaration like arrays can. A struct
2544 is given a name and this name is used to identify the type - the name
2545 is not prefixed by the word `struct` as it would be in C.
2547 Structs are only treated as the same if they have the same name.
2548 Simply having the same fields in the same order is not enough. This
2549 might change once we can create structure initializers from a list of
2552 Each component datum is identified much like a variable is declared,
2553 with a name, one or two colons, and a type. The type cannot be omitted
2554 as there is no opportunity to deduce the type from usage. An initial
2555 value can be given following an equals sign, so
2557 ##### Example: a struct type
2563 would declare a type called "complex" which has two number fields,
2564 each initialised to zero.
2566 Struct will need to be declared separately from the code that uses
2567 them, so we will need to be able to print out the declaration of a
2568 struct when reprinting the whole program. So a `print_type_decl` type
2569 function will be needed.
2571 ###### type union fields
2580 } *fields; // This is created when field_list is analysed.
2582 struct fieldlist *prev;
2585 } *field_list; // This is created during parsing
2588 ###### type functions
2589 void (*print_type_decl)(struct type *type, FILE *f);
2591 ###### value functions
2593 static void structure_init(struct type *type, struct value *val)
2597 for (i = 0; i < type->structure.nfields; i++) {
2599 v = (void*) val->ptr + type->structure.fields[i].offset;
2600 if (type->structure.fields[i].init)
2601 dup_value(type->structure.fields[i].type,
2602 type->structure.fields[i].init,
2605 val_init(type->structure.fields[i].type, v);
2609 static void structure_free(struct type *type, struct value *val)
2613 for (i = 0; i < type->structure.nfields; i++) {
2615 v = (void*)val->ptr + type->structure.fields[i].offset;
2616 free_value(type->structure.fields[i].type, v);
2620 static void free_fieldlist(struct fieldlist *f)
2624 free_fieldlist(f->prev);
2629 static void structure_free_type(struct type *t)
2632 for (i = 0; i < t->structure.nfields; i++)
2633 if (t->structure.fields[i].init) {
2634 free_value(t->structure.fields[i].type,
2635 t->structure.fields[i].init);
2637 free(t->structure.fields);
2638 free_fieldlist(t->structure.field_list);
2641 static int structure_prepare_type(struct parse_context *c,
2642 struct type *t, int parse_time)
2645 struct fieldlist *f;
2647 if (!parse_time || t->structure.fields)
2650 for (f = t->structure.field_list; f; f=f->prev) {
2654 if (f->f.type->size <= 0)
2656 if (f->f.type->prepare_type)
2657 f->f.type->prepare_type(c, f->f.type, parse_time);
2659 if (f->init == NULL)
2663 propagate_types(f->init, c, &perr, f->f.type, 0);
2664 } while (perr & Eretry);
2666 c->parse_error += 1; // NOTEST
2669 t->structure.nfields = cnt;
2670 t->structure.fields = calloc(cnt, sizeof(struct field));
2671 f = t->structure.field_list;
2673 int a = f->f.type->align;
2675 t->structure.fields[cnt] = f->f;
2676 if (t->size & (a-1))
2677 t->size = (t->size | (a-1)) + 1;
2678 t->structure.fields[cnt].offset = t->size;
2679 t->size += ((f->f.type->size - 1) | (a-1)) + 1;
2683 if (f->init && !c->parse_error) {
2684 struct value vl = interp_exec(c, f->init, NULL);
2685 t->structure.fields[cnt].init =
2686 global_alloc(c, f->f.type, NULL, &vl);
2694 static struct type structure_prototype = {
2695 .init = structure_init,
2696 .free = structure_free,
2697 .free_type = structure_free_type,
2698 .print_type_decl = structure_print_type,
2699 .prepare_type = structure_prepare_type,
2713 ###### free exec cases
2715 free_exec(cast(fieldref, e)->left);
2719 ###### declare terminals
2724 | Term . IDENTIFIER ${ {
2725 struct fieldref *fr = new_pos(fieldref, $2);
2732 ###### print exec cases
2736 struct fieldref *f = cast(fieldref, e);
2737 print_exec(f->left, -1, bracket);
2738 printf(".%.*s", f->name.len, f->name.txt);
2742 ###### ast functions
2743 static int find_struct_index(struct type *type, struct text field)
2746 for (i = 0; i < type->structure.nfields; i++)
2747 if (text_cmp(type->structure.fields[i].name, field) == 0)
2752 ###### propagate exec cases
2756 struct fieldref *f = cast(fieldref, prog);
2757 struct type *st = propagate_types(f->left, c, perr, NULL, 0);
2760 type_err(c, "error: unknown type for field access", f->left, // UNTESTED
2762 else if (st->init != structure_init)
2763 type_err(c, "error: field reference attempted on %1, not a struct",
2764 f->left, st, 0, NULL);
2765 else if (f->index == -2) {
2766 f->index = find_struct_index(st, f->name);
2768 type_err(c, "error: cannot find requested field in %1",
2769 f->left, st, 0, NULL);
2771 if (f->index >= 0) {
2772 struct type *ft = st->structure.fields[f->index].type;
2773 if (!type_compat(type, ft, rules))
2774 type_err(c, "error: have %1 but need %2", prog,
2781 ###### interp exec cases
2784 struct fieldref *f = cast(fieldref, e);
2786 struct value *lleft = linterp_exec(c, f->left, <ype);
2787 lrv = (void*)lleft->ptr + ltype->structure.fields[f->index].offset;
2788 rvtype = ltype->structure.fields[f->index].type;
2792 ###### top level grammar
2793 DeclareStruct -> struct IDENTIFIER FieldBlock Newlines ${ {
2795 t = find_type(c, $ID.txt);
2797 t = add_type(c, $ID.txt, &structure_prototype);
2798 else if (t->size >= 0) {
2799 tok_err(c, "error: type already declared", &$ID);
2800 tok_err(c, "info: this is location of declartion", &t->first_use);
2801 /* Create a new one - duplicate */
2802 t = add_type(c, $ID.txt, &structure_prototype);
2804 struct type tmp = *t;
2805 *t = structure_prototype;
2809 t->structure.field_list = $<FB;
2814 FieldBlock -> { IN OptNL FieldLines OUT OptNL } ${ $0 = $<FL; }$
2815 | { SimpleFieldList } ${ $0 = $<SFL; }$
2816 | IN OptNL FieldLines OUT ${ $0 = $<FL; }$
2817 | SimpleFieldList EOL ${ $0 = $<SFL; }$
2819 FieldLines -> SimpleFieldList Newlines ${ $0 = $<SFL; }$
2820 | FieldLines SimpleFieldList Newlines ${
2825 SimpleFieldList -> Field ${ $0 = $<F; }$
2826 | SimpleFieldList ; Field ${
2830 | SimpleFieldList ; ${
2833 | ERROR ${ tok_err(c, "Syntax error in struct field", &$1); }$
2835 Field -> IDENTIFIER : Type = Expression ${ {
2836 $0 = calloc(1, sizeof(struct fieldlist));
2837 $0->f.name = $ID.txt;
2838 $0->f.type = $<Type;
2842 | IDENTIFIER : Type ${
2843 $0 = calloc(1, sizeof(struct fieldlist));
2844 $0->f.name = $ID.txt;
2845 $0->f.type = $<Type;
2848 ###### forward decls
2849 static void structure_print_type(struct type *t, FILE *f);
2851 ###### value functions
2852 static void structure_print_type(struct type *t, FILE *f)
2856 fprintf(f, "struct %.*s\n", t->name.len, t->name.txt);
2858 for (i = 0; i < t->structure.nfields; i++) {
2859 struct field *fl = t->structure.fields + i;
2860 fprintf(f, " %.*s : ", fl->name.len, fl->name.txt);
2861 type_print(fl->type, f);
2862 if (fl->type->print && fl->init) {
2864 if (fl->type == Tstr)
2865 fprintf(f, "\""); // UNTESTED
2866 print_value(fl->type, fl->init, f);
2867 if (fl->type == Tstr)
2868 fprintf(f, "\""); // UNTESTED
2874 ###### print type decls
2879 while (target != 0) {
2881 for (t = context.typelist; t ; t=t->next)
2882 if (!t->anon && t->print_type_decl &&
2892 t->print_type_decl(t, stdout);
2900 A function is a chunk of code which can be passed parameters and can
2901 return results. Each function has a type which includes the set of
2902 parameters and the return value. As yet these types cannot be declared
2903 separately from the function itself.
2905 The parameters can be specified either in parentheses as a ';' separated
2908 ##### Example: function 1
2910 func main(av:[ac::number]string; env:[envc::number]string)
2913 or as an indented list of one parameter per line (though each line can
2914 be a ';' separated list)
2916 ##### Example: function 2
2919 argv:[argc::number]string
2920 env:[envc::number]string
2924 In the first case a return type can follow the parentheses after a colon,
2925 in the second it is given on a line starting with the word `return`.
2927 ##### Example: functions that return
2929 func add(a:number; b:number): number
2939 Rather than returning a type, the function can specify a set of local
2940 variables to return as a struct. The values of these variables when the
2941 function exits will be provided to the caller. For this the return type
2942 is replaced with a block of result declarations, either in parentheses
2943 or bracketed by `return` and `do`.
2945 ##### Example: functions returning multiple variables
2947 func to_cartesian(rho:number; theta:number):(x:number; y:number)
2960 For constructing the lists we use a `List` binode, which will be
2961 further detailed when Expression Lists are introduced.
2963 ###### type union fields
2966 struct binode *params;
2967 struct type *return_type;
2968 struct variable *scope;
2969 int inline_result; // return value is at start of 'local'
2973 ###### value union fields
2974 struct exec *function;
2976 ###### type functions
2977 void (*check_args)(struct parse_context *c, enum prop_err *perr,
2978 struct type *require, struct exec *args);
2980 ###### value functions
2982 static void function_free(struct type *type, struct value *val)
2984 free_exec(val->function);
2985 val->function = NULL;
2988 static int function_compat(struct type *require, struct type *have)
2990 // FIXME can I do anything here yet?
2994 static void function_check_args(struct parse_context *c, enum prop_err *perr,
2995 struct type *require, struct exec *args)
2997 /* This should be 'compat', but we don't have a 'tuple' type to
2998 * hold the type of 'args'
3000 struct binode *arg = cast(binode, args);
3001 struct binode *param = require->function.params;
3004 struct var *pv = cast(var, param->left);
3006 type_err(c, "error: insufficient arguments to function.",
3007 args, NULL, 0, NULL);
3011 propagate_types(arg->left, c, perr, pv->var->type, 0);
3012 param = cast(binode, param->right);
3013 arg = cast(binode, arg->right);
3016 type_err(c, "error: too many arguments to function.",
3017 args, NULL, 0, NULL);
3020 static void function_print(struct type *type, struct value *val, FILE *f)
3022 print_exec(val->function, 1, 0);
3025 static void function_print_type_decl(struct type *type, FILE *f)
3029 for (b = type->function.params; b; b = cast(binode, b->right)) {
3030 struct variable *v = cast(var, b->left)->var;
3031 fprintf(f, "%.*s%s", v->name->name.len, v->name->name.txt,
3032 v->constant ? "::" : ":");
3033 type_print(v->type, f);
3038 if (type->function.return_type != Tnone) {
3040 if (type->function.inline_result) {
3042 struct type *t = type->function.return_type;
3044 for (i = 0; i < t->structure.nfields; i++) {
3045 struct field *fl = t->structure.fields + i;
3048 fprintf(f, "%.*s:", fl->name.len, fl->name.txt);
3049 type_print(fl->type, f);
3053 type_print(type->function.return_type, f);
3058 static void function_free_type(struct type *t)
3060 free_exec(t->function.params);
3063 static struct type function_prototype = {
3064 .size = sizeof(void*),
3065 .align = sizeof(void*),
3066 .free = function_free,
3067 .compat = function_compat,
3068 .check_args = function_check_args,
3069 .print = function_print,
3070 .print_type_decl = function_print_type_decl,
3071 .free_type = function_free_type,
3074 ###### declare terminals
3084 FuncName -> IDENTIFIER ${ {
3085 struct variable *v = var_decl(c, $1.txt);
3086 struct var *e = new_pos(var, $1);
3092 v = var_ref(c, $1.txt);
3094 type_err(c, "error: function '%v' redeclared",
3096 type_err(c, "info: this is where '%v' was first declared",
3097 v->where_decl, NULL, 0, NULL);
3103 Args -> ArgsLine NEWLINE ${ $0 = $<AL; }$
3104 | Args ArgsLine NEWLINE ${ {
3105 struct binode *b = $<AL;
3106 struct binode **bp = &b;
3108 bp = (struct binode **)&(*bp)->left;
3113 ArgsLine -> ${ $0 = NULL; }$
3114 | Varlist ${ $0 = $<1; }$
3115 | Varlist ; ${ $0 = $<1; }$
3117 Varlist -> Varlist ; ArgDecl ${
3131 ArgDecl -> IDENTIFIER : FormalType ${ {
3132 struct variable *v = var_decl(c, $1.txt);
3138 ##### Function calls
3140 A function call can appear either as an expression or as a statement.
3141 We use a new 'Funcall' binode type to link the function with a list of
3142 arguments, form with the 'List' nodes.
3144 We have already seen the "Term" which is how a function call can appear
3145 in an expression. To parse a function call into a statement we include
3146 it in the "SimpleStatement Grammar" which will be described later.
3152 | Term ( ExpressionList ) ${ {
3153 struct binode *b = new(binode);
3156 b->right = reorder_bilist($<EL);
3160 struct binode *b = new(binode);
3167 ###### SimpleStatement Grammar
3169 | Term ( ExpressionList ) ${ {
3170 struct binode *b = new(binode);
3173 b->right = reorder_bilist($<EL);
3177 ###### print binode cases
3180 do_indent(indent, "");
3181 print_exec(b->left, -1, bracket);
3183 for (b = cast(binode, b->right); b; b = cast(binode, b->right)) {
3186 print_exec(b->left, -1, bracket);
3196 ###### propagate binode cases
3199 /* Every arg must match formal parameter, and result
3200 * is return type of function
3202 struct binode *args = cast(binode, b->right);
3203 struct var *v = cast(var, b->left);
3205 if (!v->var->type || v->var->type->check_args == NULL) {
3206 type_err(c, "error: attempt to call a non-function.",
3207 prog, NULL, 0, NULL);
3211 v->var->type->check_args(c, perr, v->var->type, args);
3212 return v->var->type->function.return_type;
3215 ###### interp binode cases
3218 struct var *v = cast(var, b->left);
3219 struct type *t = v->var->type;
3220 void *oldlocal = c->local;
3221 int old_size = c->local_size;
3222 void *local = calloc(1, t->function.local_size);
3223 struct value *fbody = var_value(c, v->var);
3224 struct binode *arg = cast(binode, b->right);
3225 struct binode *param = t->function.params;
3228 struct var *pv = cast(var, param->left);
3229 struct type *vtype = NULL;
3230 struct value val = interp_exec(c, arg->left, &vtype);
3232 c->local = local; c->local_size = t->function.local_size;
3233 lval = var_value(c, pv->var);
3234 c->local = oldlocal; c->local_size = old_size;
3235 memcpy(lval, &val, vtype->size);
3236 param = cast(binode, param->right);
3237 arg = cast(binode, arg->right);
3239 c->local = local; c->local_size = t->function.local_size;
3240 if (t->function.inline_result && dtype) {
3241 _interp_exec(c, fbody->function, NULL, NULL);
3242 memcpy(dest, local, dtype->size);
3243 rvtype = ret.type = NULL;
3245 rv = interp_exec(c, fbody->function, &rvtype);
3246 c->local = oldlocal; c->local_size = old_size;
3251 ## Complex executables: statements and expressions
3253 Now that we have types and values and variables and most of the basic
3254 Terms which provide access to these, we can explore the more complex
3255 code that combine all of these to get useful work done. Specifically
3256 statements and expressions.
3258 Expressions are various combinations of Terms. We will use operator
3259 precedence to ensure correct parsing. The simplest Expression is just a
3260 Term - others will follow.
3265 Expression -> Term ${ $0 = $<Term; }$
3266 ## expression grammar
3268 ### Expressions: Conditional
3270 Our first user of the `binode` will be conditional expressions, which
3271 is a bit odd as they actually have three components. That will be
3272 handled by having 2 binodes for each expression. The conditional
3273 expression is the lowest precedence operator which is why we define it
3274 first - to start the precedence list.
3276 Conditional expressions are of the form "value `if` condition `else`
3277 other_value". They associate to the right, so everything to the right
3278 of `else` is part of an else value, while only a higher-precedence to
3279 the left of `if` is the if values. Between `if` and `else` there is no
3280 room for ambiguity, so a full conditional expression is allowed in
3286 ###### declare terminals
3290 ###### expression grammar
3292 | Expression if Expression else Expression $$ifelse ${ {
3293 struct binode *b1 = new(binode);
3294 struct binode *b2 = new(binode);
3304 ###### print binode cases
3307 b2 = cast(binode, b->right);
3308 if (bracket) printf("(");
3309 print_exec(b2->left, -1, bracket);
3311 print_exec(b->left, -1, bracket);
3313 print_exec(b2->right, -1, bracket);
3314 if (bracket) printf(")");
3317 ###### propagate binode cases
3320 /* cond must be Tbool, others must match */
3321 struct binode *b2 = cast(binode, b->right);
3324 propagate_types(b->left, c, perr, Tbool, 0);
3325 t = propagate_types(b2->left, c, perr, type, Rnolabel);
3326 t2 = propagate_types(b2->right, c, perr, type ?: t, Rnolabel);
3330 ###### interp binode cases
3333 struct binode *b2 = cast(binode, b->right);
3334 left = interp_exec(c, b->left, <ype);
3336 rv = interp_exec(c, b2->left, &rvtype); // UNTESTED
3338 rv = interp_exec(c, b2->right, &rvtype);
3344 We take a brief detour, now that we have expressions, to describe lists
3345 of expressions. These will be needed for function parameters and
3346 possibly other situations. They seem generic enough to introduce here
3347 to be used elsewhere.
3349 And ExpressionList will use the `List` type of `binode`, building up at
3350 the end. And place where they are used will probably call
3351 `reorder_bilist()` to get a more normal first/next arrangement.
3353 ###### declare terminals
3356 `List` execs have no implicit semantics, so they are never propagated or
3357 interpreted. The can be printed as a comma separate list, which is how
3358 they are parsed. Note they are also used for function formal parameter
3359 lists. In that case a separate function is used to print them.
3361 ###### print binode cases
3365 print_exec(b->left, -1, bracket);
3368 b = cast(binode, b->right);
3372 ###### propagate binode cases
3373 case List: abort(); // NOTEST
3374 ###### interp binode cases
3375 case List: abort(); // NOTEST
3380 ExpressionList -> ExpressionList , Expression ${
3393 ### Expressions: Boolean
3395 The next class of expressions to use the `binode` will be Boolean
3396 expressions. "`and then`" and "`or else`" are similar to `and` and `or`
3397 have same corresponding precendence. The difference is that they don't
3398 evaluate the second expression if not necessary.
3407 ###### declare terminals
3412 ###### expression grammar
3413 | Expression or Expression ${ {
3414 struct binode *b = new(binode);
3420 | Expression or else Expression ${ {
3421 struct binode *b = new(binode);
3428 | Expression and Expression ${ {
3429 struct binode *b = new(binode);
3435 | Expression and then Expression ${ {
3436 struct binode *b = new(binode);
3443 | not Expression ${ {
3444 struct binode *b = new(binode);
3450 ###### print binode cases
3452 if (bracket) printf("(");
3453 print_exec(b->left, -1, bracket);
3455 print_exec(b->right, -1, bracket);
3456 if (bracket) printf(")");
3459 if (bracket) printf("(");
3460 print_exec(b->left, -1, bracket);
3461 printf(" and then ");
3462 print_exec(b->right, -1, bracket);
3463 if (bracket) printf(")");
3466 if (bracket) printf("(");
3467 print_exec(b->left, -1, bracket);
3469 print_exec(b->right, -1, bracket);
3470 if (bracket) printf(")");
3473 if (bracket) printf("(");
3474 print_exec(b->left, -1, bracket);
3475 printf(" or else ");
3476 print_exec(b->right, -1, bracket);
3477 if (bracket) printf(")");
3480 if (bracket) printf("(");
3482 print_exec(b->right, -1, bracket);
3483 if (bracket) printf(")");
3486 ###### propagate binode cases
3492 /* both must be Tbool, result is Tbool */
3493 propagate_types(b->left, c, perr, Tbool, 0);
3494 propagate_types(b->right, c, perr, Tbool, 0);
3495 if (type && type != Tbool)
3496 type_err(c, "error: %1 operation found where %2 expected", prog,
3500 ###### interp binode cases
3502 rv = interp_exec(c, b->left, &rvtype);
3503 right = interp_exec(c, b->right, &rtype);
3504 rv.bool = rv.bool && right.bool;
3507 rv = interp_exec(c, b->left, &rvtype);
3509 rv = interp_exec(c, b->right, NULL);
3512 rv = interp_exec(c, b->left, &rvtype);
3513 right = interp_exec(c, b->right, &rtype);
3514 rv.bool = rv.bool || right.bool;
3517 rv = interp_exec(c, b->left, &rvtype);
3519 rv = interp_exec(c, b->right, NULL);
3522 rv = interp_exec(c, b->right, &rvtype);
3526 ### Expressions: Comparison
3528 Of slightly higher precedence that Boolean expressions are Comparisons.
3529 A comparison takes arguments of any comparable type, but the two types
3532 To simplify the parsing we introduce an `eop` which can record an
3533 expression operator, and the `CMPop` non-terminal will match one of them.
3540 ###### ast functions
3541 static void free_eop(struct eop *e)
3555 ###### declare terminals
3556 $LEFT < > <= >= == != CMPop
3558 ###### expression grammar
3559 | Expression CMPop Expression ${ {
3560 struct binode *b = new(binode);
3570 CMPop -> < ${ $0.op = Less; }$
3571 | > ${ $0.op = Gtr; }$
3572 | <= ${ $0.op = LessEq; }$
3573 | >= ${ $0.op = GtrEq; }$
3574 | == ${ $0.op = Eql; }$
3575 | != ${ $0.op = NEql; }$
3577 ###### print binode cases
3585 if (bracket) printf("(");
3586 print_exec(b->left, -1, bracket);
3588 case Less: printf(" < "); break;
3589 case LessEq: printf(" <= "); break;
3590 case Gtr: printf(" > "); break;
3591 case GtrEq: printf(" >= "); break;
3592 case Eql: printf(" == "); break;
3593 case NEql: printf(" != "); break;
3594 default: abort(); // NOTEST
3596 print_exec(b->right, -1, bracket);
3597 if (bracket) printf(")");
3600 ###### propagate binode cases
3607 /* Both must match but not be labels, result is Tbool */
3608 t = propagate_types(b->left, c, perr, NULL, Rnolabel);
3610 propagate_types(b->right, c, perr, t, 0);
3612 t = propagate_types(b->right, c, perr, NULL, Rnolabel); // UNTESTED
3614 t = propagate_types(b->left, c, perr, t, 0); // UNTESTED
3616 if (!type_compat(type, Tbool, 0))
3617 type_err(c, "error: Comparison returns %1 but %2 expected", prog,
3618 Tbool, rules, type);
3621 ###### interp binode cases
3630 left = interp_exec(c, b->left, <ype);
3631 right = interp_exec(c, b->right, &rtype);
3632 cmp = value_cmp(ltype, rtype, &left, &right);
3635 case Less: rv.bool = cmp < 0; break;
3636 case LessEq: rv.bool = cmp <= 0; break;
3637 case Gtr: rv.bool = cmp > 0; break;
3638 case GtrEq: rv.bool = cmp >= 0; break;
3639 case Eql: rv.bool = cmp == 0; break;
3640 case NEql: rv.bool = cmp != 0; break;
3641 default: rv.bool = 0; break; // NOTEST
3646 ### Expressions: Arithmetic etc.
3648 The remaining expressions with the highest precedence are arithmetic,
3649 string concatenation, and string conversion. String concatenation
3650 (`++`) has the same precedence as multiplication and division, but lower
3653 String conversion is a temporary feature until I get a better type
3654 system. `$` is a prefix operator which expects a string and returns
3657 `+` and `-` are both infix and prefix operations (where they are
3658 absolute value and negation). These have different operator names.
3660 We also have a 'Bracket' operator which records where parentheses were
3661 found. This makes it easy to reproduce these when printing. Possibly I
3662 should only insert brackets were needed for precedence. Putting
3663 parentheses around an expression converts it into a Term,
3673 ###### declare terminals
3679 ###### expression grammar
3680 | Expression Eop Expression ${ {
3681 struct binode *b = new(binode);
3688 | Expression Top Expression ${ {
3689 struct binode *b = new(binode);
3696 | Uop Expression ${ {
3697 struct binode *b = new(binode);
3705 | ( Expression ) ${ {
3706 struct binode *b = new_pos(binode, $1);
3715 Eop -> + ${ $0.op = Plus; }$
3716 | - ${ $0.op = Minus; }$
3718 Uop -> + ${ $0.op = Absolute; }$
3719 | - ${ $0.op = Negate; }$
3720 | $ ${ $0.op = StringConv; }$
3722 Top -> * ${ $0.op = Times; }$
3723 | / ${ $0.op = Divide; }$
3724 | % ${ $0.op = Rem; }$
3725 | ++ ${ $0.op = Concat; }$
3727 ###### print binode cases
3734 if (bracket) printf("(");
3735 print_exec(b->left, indent, bracket);
3737 case Plus: fputs(" + ", stdout); break;
3738 case Minus: fputs(" - ", stdout); break;
3739 case Times: fputs(" * ", stdout); break;
3740 case Divide: fputs(" / ", stdout); break;
3741 case Rem: fputs(" % ", stdout); break;
3742 case Concat: fputs(" ++ ", stdout); break;
3743 default: abort(); // NOTEST
3745 print_exec(b->right, indent, bracket);
3746 if (bracket) printf(")");
3751 if (bracket) printf("(");
3753 case Absolute: fputs("+", stdout); break;
3754 case Negate: fputs("-", stdout); break;
3755 case StringConv: fputs("$", stdout); break;
3756 default: abort(); // NOTEST
3758 print_exec(b->right, indent, bracket);
3759 if (bracket) printf(")");
3763 print_exec(b->right, indent, bracket);
3767 ###### propagate binode cases
3773 /* both must be numbers, result is Tnum */
3776 /* as propagate_types ignores a NULL,
3777 * unary ops fit here too */
3778 propagate_types(b->left, c, perr, Tnum, 0);
3779 propagate_types(b->right, c, perr, Tnum, 0);
3780 if (!type_compat(type, Tnum, 0))
3781 type_err(c, "error: Arithmetic returns %1 but %2 expected", prog,
3786 /* both must be Tstr, result is Tstr */
3787 propagate_types(b->left, c, perr, Tstr, 0);
3788 propagate_types(b->right, c, perr, Tstr, 0);
3789 if (!type_compat(type, Tstr, 0))
3790 type_err(c, "error: Concat returns %1 but %2 expected", prog,
3795 /* op must be string, result is number */
3796 propagate_types(b->left, c, perr, Tstr, 0);
3797 if (!type_compat(type, Tnum, 0))
3798 type_err(c, // UNTESTED
3799 "error: Can only convert string to number, not %1",
3800 prog, type, 0, NULL);
3804 return propagate_types(b->right, c, perr, type, 0);
3806 ###### interp binode cases
3809 rv = interp_exec(c, b->left, &rvtype);
3810 right = interp_exec(c, b->right, &rtype);
3811 mpq_add(rv.num, rv.num, right.num);
3814 rv = interp_exec(c, b->left, &rvtype);
3815 right = interp_exec(c, b->right, &rtype);
3816 mpq_sub(rv.num, rv.num, right.num);
3819 rv = interp_exec(c, b->left, &rvtype);
3820 right = interp_exec(c, b->right, &rtype);
3821 mpq_mul(rv.num, rv.num, right.num);
3824 rv = interp_exec(c, b->left, &rvtype);
3825 right = interp_exec(c, b->right, &rtype);
3826 mpq_div(rv.num, rv.num, right.num);
3831 left = interp_exec(c, b->left, <ype);
3832 right = interp_exec(c, b->right, &rtype);
3833 mpz_init(l); mpz_init(r); mpz_init(rem);
3834 mpz_tdiv_q(l, mpq_numref(left.num), mpq_denref(left.num));
3835 mpz_tdiv_q(r, mpq_numref(right.num), mpq_denref(right.num));
3836 mpz_tdiv_r(rem, l, r);
3837 val_init(Tnum, &rv);
3838 mpq_set_z(rv.num, rem);
3839 mpz_clear(r); mpz_clear(l); mpz_clear(rem);
3844 rv = interp_exec(c, b->right, &rvtype);
3845 mpq_neg(rv.num, rv.num);
3848 rv = interp_exec(c, b->right, &rvtype);
3849 mpq_abs(rv.num, rv.num);
3852 rv = interp_exec(c, b->right, &rvtype);
3855 left = interp_exec(c, b->left, <ype);
3856 right = interp_exec(c, b->right, &rtype);
3858 rv.str = text_join(left.str, right.str);
3861 right = interp_exec(c, b->right, &rvtype);
3865 struct text tx = right.str;
3868 if (tx.txt[0] == '-') {
3869 neg = 1; // UNTESTED
3870 tx.txt++; // UNTESTED
3871 tx.len--; // UNTESTED
3873 if (number_parse(rv.num, tail, tx) == 0)
3874 mpq_init(rv.num); // UNTESTED
3876 mpq_neg(rv.num, rv.num); // UNTESTED
3878 printf("Unsupported suffix: %.*s\n", tx.len, tx.txt); // UNTESTED
3882 ###### value functions
3884 static struct text text_join(struct text a, struct text b)
3887 rv.len = a.len + b.len;
3888 rv.txt = malloc(rv.len);
3889 memcpy(rv.txt, a.txt, a.len);
3890 memcpy(rv.txt+a.len, b.txt, b.len);
3894 ### Blocks, Statements, and Statement lists.
3896 Now that we have expressions out of the way we need to turn to
3897 statements. There are simple statements and more complex statements.
3898 Simple statements do not contain (syntactic) newlines, complex statements do.
3900 Statements often come in sequences and we have corresponding simple
3901 statement lists and complex statement lists.
3902 The former comprise only simple statements separated by semicolons.
3903 The later comprise complex statements and simple statement lists. They are
3904 separated by newlines. Thus the semicolon is only used to separate
3905 simple statements on the one line. This may be overly restrictive,
3906 but I'm not sure I ever want a complex statement to share a line with
3909 Note that a simple statement list can still use multiple lines if
3910 subsequent lines are indented, so
3912 ###### Example: wrapped simple statement list
3917 is a single simple statement list. This might allow room for
3918 confusion, so I'm not set on it yet.
3920 A simple statement list needs no extra syntax. A complex statement
3921 list has two syntactic forms. It can be enclosed in braces (much like
3922 C blocks), or it can be introduced by an indent and continue until an
3923 unindented newline (much like Python blocks). With this extra syntax
3924 it is referred to as a block.
3926 Note that a block does not have to include any newlines if it only
3927 contains simple statements. So both of:
3929 if condition: a=b; d=f
3931 if condition { a=b; print f }
3935 In either case the list is constructed from a `binode` list with
3936 `Block` as the operator. When parsing the list it is most convenient
3937 to append to the end, so a list is a list and a statement. When using
3938 the list it is more convenient to consider a list to be a statement
3939 and a list. So we need a function to re-order a list.
3940 `reorder_bilist` serves this purpose.
3942 The only stand-alone statement we introduce at this stage is `pass`
3943 which does nothing and is represented as a `NULL` pointer in a `Block`
3944 list. Other stand-alone statements will follow once the infrastructure
3947 As many statements will use binodes, we declare a binode pointer 'b' in
3948 the common header for all reductions to use.
3950 ###### Parser: reduce
3961 Block -> { IN OptNL Statementlist OUT OptNL } ${ $0 = $<Sl; }$
3962 | { SimpleStatements } ${ $0 = reorder_bilist($<SS); }$
3963 | SimpleStatements ; ${ $0 = reorder_bilist($<SS); }$
3964 | SimpleStatements EOL ${ $0 = reorder_bilist($<SS); }$
3965 | IN OptNL Statementlist OUT ${ $0 = $<Sl; }$
3967 OpenBlock -> OpenScope { IN OptNL Statementlist OUT OptNL } ${ $0 = $<Sl; }$
3968 | OpenScope { SimpleStatements } ${ $0 = reorder_bilist($<SS); }$
3969 | OpenScope SimpleStatements ; ${ $0 = reorder_bilist($<SS); }$
3970 | OpenScope SimpleStatements EOL ${ $0 = reorder_bilist($<SS); }$
3971 | IN OpenScope OptNL Statementlist OUT ${ $0 = $<Sl; }$
3973 UseBlock -> { OpenScope IN OptNL Statementlist OUT OptNL } ${ $0 = $<Sl; }$
3974 | { OpenScope SimpleStatements } ${ $0 = reorder_bilist($<SS); }$
3975 | IN OpenScope OptNL Statementlist OUT ${ $0 = $<Sl; }$
3977 ColonBlock -> { IN OptNL Statementlist OUT OptNL } ${ $0 = $<Sl; }$
3978 | { SimpleStatements } ${ $0 = reorder_bilist($<SS); }$
3979 | : SimpleStatements ; ${ $0 = reorder_bilist($<SS); }$
3980 | : SimpleStatements EOL ${ $0 = reorder_bilist($<SS); }$
3981 | : IN OptNL Statementlist OUT ${ $0 = $<Sl; }$
3983 Statementlist -> ComplexStatements ${ $0 = reorder_bilist($<CS); }$
3985 ComplexStatements -> ComplexStatements ComplexStatement ${
3995 | ComplexStatement ${
4007 ComplexStatement -> SimpleStatements Newlines ${
4008 $0 = reorder_bilist($<SS);
4010 | SimpleStatements ; Newlines ${
4011 $0 = reorder_bilist($<SS);
4013 ## ComplexStatement Grammar
4016 SimpleStatements -> SimpleStatements ; SimpleStatement ${
4022 | SimpleStatement ${
4031 SimpleStatement -> pass ${ $0 = NULL; }$
4032 | ERROR ${ tok_err(c, "Syntax error in statement", &$1); }$
4033 ## SimpleStatement Grammar
4035 ###### print binode cases
4039 if (b->left == NULL) // UNTESTED
4040 printf("pass"); // UNTESTED
4042 print_exec(b->left, indent, bracket); // UNTESTED
4043 if (b->right) { // UNTESTED
4044 printf("; "); // UNTESTED
4045 print_exec(b->right, indent, bracket); // UNTESTED
4048 // block, one per line
4049 if (b->left == NULL)
4050 do_indent(indent, "pass\n");
4052 print_exec(b->left, indent, bracket);
4054 print_exec(b->right, indent, bracket);
4058 ###### propagate binode cases
4061 /* If any statement returns something other than Tnone
4062 * or Tbool then all such must return same type.
4063 * As each statement may be Tnone or something else,
4064 * we must always pass NULL (unknown) down, otherwise an incorrect
4065 * error might occur. We never return Tnone unless it is
4070 for (e = b; e; e = cast(binode, e->right)) {
4071 t = propagate_types(e->left, c, perr, NULL, rules);
4072 if ((rules & Rboolok) && (t == Tbool || t == Tnone))
4074 if (t == Tnone && e->right)
4075 /* Only the final statement *must* return a value
4083 type_err(c, "error: expected %1%r, found %2",
4084 e->left, type, rules, t);
4090 ###### interp binode cases
4092 while (rvtype == Tnone &&
4095 rv = interp_exec(c, b->left, &rvtype);
4096 b = cast(binode, b->right);
4100 ### The Print statement
4102 `print` is a simple statement that takes a comma-separated list of
4103 expressions and prints the values separated by spaces and terminated
4104 by a newline. No control of formatting is possible.
4106 `print` uses `ExpressionList` to collect the expressions and stores them
4107 on the left side of a `Print` binode unlessthere is a trailing comma
4108 when the list is stored on the `right` side and no trailing newline is
4114 ##### declare terminals
4117 ###### SimpleStatement Grammar
4119 | print ExpressionList ${
4120 $0 = b = new(binode);
4123 b->left = reorder_bilist($<EL);
4125 | print ExpressionList , ${ {
4126 $0 = b = new(binode);
4128 b->right = reorder_bilist($<EL);
4132 $0 = b = new(binode);
4138 ###### print binode cases
4141 do_indent(indent, "print");
4143 print_exec(b->right, -1, bracket);
4146 print_exec(b->left, -1, bracket);
4151 ###### propagate binode cases
4154 /* don't care but all must be consistent */
4156 b = cast(binode, b->left);
4158 b = cast(binode, b->right);
4160 propagate_types(b->left, c, perr, NULL, Rnolabel);
4161 b = cast(binode, b->right);
4165 ###### interp binode cases
4169 struct binode *b2 = cast(binode, b->left);
4171 b2 = cast(binode, b->right);
4172 for (; b2; b2 = cast(binode, b2->right)) {
4173 left = interp_exec(c, b2->left, <ype);
4174 print_value(ltype, &left, stdout);
4175 free_value(ltype, &left);
4179 if (b->right == NULL)
4185 ###### Assignment statement
4187 An assignment will assign a value to a variable, providing it hasn't
4188 been declared as a constant. The analysis phase ensures that the type
4189 will be correct so the interpreter just needs to perform the
4190 calculation. There is a form of assignment which declares a new
4191 variable as well as assigning a value. If a name is assigned before
4192 it is declared, and error will be raised as the name is created as
4193 `Tlabel` and it is illegal to assign to such names.
4199 ###### declare terminals
4202 ###### SimpleStatement Grammar
4203 | Term = Expression ${
4204 $0 = b= new(binode);
4209 | VariableDecl = Expression ${
4210 $0 = b= new(binode);
4217 if ($1->var->where_set == NULL) {
4219 "Variable declared with no type or value: %v",
4223 $0 = b = new(binode);
4230 ###### print binode cases
4233 do_indent(indent, "");
4234 print_exec(b->left, indent, bracket);
4236 print_exec(b->right, indent, bracket);
4243 struct variable *v = cast(var, b->left)->var;
4244 do_indent(indent, "");
4245 print_exec(b->left, indent, bracket);
4246 if (cast(var, b->left)->var->constant) {
4248 if (v->explicit_type) {
4249 type_print(v->type, stdout);
4254 if (v->explicit_type) {
4255 type_print(v->type, stdout);
4261 print_exec(b->right, indent, bracket);
4268 ###### propagate binode cases
4272 /* Both must match and not be labels,
4273 * Type must support 'dup',
4274 * For Assign, left must not be constant.
4277 t = propagate_types(b->left, c, perr, NULL,
4278 Rnolabel | (b->op == Assign ? Rnoconstant : 0));
4283 if (propagate_types(b->right, c, perr, t, 0) != t)
4284 if (b->left->type == Xvar)
4285 type_err(c, "info: variable '%v' was set as %1 here.",
4286 cast(var, b->left)->var->where_set, t, rules, NULL);
4288 t = propagate_types(b->right, c, perr, NULL, Rnolabel);
4290 propagate_types(b->left, c, perr, t,
4291 (b->op == Assign ? Rnoconstant : 0));
4293 if (t && t->dup == NULL && t->name.txt[0] != ' ') // HACK
4294 type_err(c, "error: cannot assign value of type %1", b, t, 0, NULL);
4299 ###### interp binode cases
4302 lleft = linterp_exec(c, b->left, <ype);
4304 dinterp_exec(c, b->right, lleft, ltype, 1);
4310 struct variable *v = cast(var, b->left)->var;
4313 val = var_value(c, v);
4314 if (v->type->prepare_type)
4315 v->type->prepare_type(c, v->type, 0);
4317 dinterp_exec(c, b->right, val, v->type, 0);
4319 val_init(v->type, val);
4323 ### The `use` statement
4325 The `use` statement is the last "simple" statement. It is needed when a
4326 statement block can return a value. This includes the body of a
4327 function which has a return type, and the "condition" code blocks in
4328 `if`, `while`, and `switch` statements.
4333 ###### declare terminals
4336 ###### SimpleStatement Grammar
4338 $0 = b = new_pos(binode, $1);
4341 if (b->right->type == Xvar) {
4342 struct var *v = cast(var, b->right);
4343 if (v->var->type == Tnone) {
4344 /* Convert this to a label */
4347 v->var->type = Tlabel;
4348 val = global_alloc(c, Tlabel, v->var, NULL);
4354 ###### print binode cases
4357 do_indent(indent, "use ");
4358 print_exec(b->right, -1, bracket);
4363 ###### propagate binode cases
4366 /* result matches value */
4367 return propagate_types(b->right, c, perr, type, 0);
4369 ###### interp binode cases
4372 rv = interp_exec(c, b->right, &rvtype);
4375 ### The Conditional Statement
4377 This is the biggy and currently the only complex statement. This
4378 subsumes `if`, `while`, `do/while`, `switch`, and some parts of `for`.
4379 It is comprised of a number of parts, all of which are optional though
4380 set combinations apply. Each part is (usually) a key word (`then` is
4381 sometimes optional) followed by either an expression or a code block,
4382 except the `casepart` which is a "key word and an expression" followed
4383 by a code block. The code-block option is valid for all parts and,
4384 where an expression is also allowed, the code block can use the `use`
4385 statement to report a value. If the code block does not report a value
4386 the effect is similar to reporting `True`.
4388 The `else` and `case` parts, as well as `then` when combined with
4389 `if`, can contain a `use` statement which will apply to some
4390 containing conditional statement. `for` parts, `do` parts and `then`
4391 parts used with `for` can never contain a `use`, except in some
4392 subordinate conditional statement.
4394 If there is a `forpart`, it is executed first, only once.
4395 If there is a `dopart`, then it is executed repeatedly providing
4396 always that the `condpart` or `cond`, if present, does not return a non-True
4397 value. `condpart` can fail to return any value if it simply executes
4398 to completion. This is treated the same as returning `True`.
4400 If there is a `thenpart` it will be executed whenever the `condpart`
4401 or `cond` returns True (or does not return any value), but this will happen
4402 *after* `dopart` (when present).
4404 If `elsepart` is present it will be executed at most once when the
4405 condition returns `False` or some value that isn't `True` and isn't
4406 matched by any `casepart`. If there are any `casepart`s, they will be
4407 executed when the condition returns a matching value.
4409 The particular sorts of values allowed in case parts has not yet been
4410 determined in the language design, so nothing is prohibited.
4412 The various blocks in this complex statement potentially provide scope
4413 for variables as described earlier. Each such block must include the
4414 "OpenScope" nonterminal before parsing the block, and must call
4415 `var_block_close()` when closing the block.
4417 The code following "`if`", "`switch`" and "`for`" does not get its own
4418 scope, but is in a scope covering the whole statement, so names
4419 declared there cannot be redeclared elsewhere. Similarly the
4420 condition following "`while`" is in a scope the covers the body
4421 ("`do`" part) of the loop, and which does not allow conditional scope
4422 extension. Code following "`then`" (both looping and non-looping),
4423 "`else`" and "`case`" each get their own local scope.
4425 The type requirements on the code block in a `whilepart` are quite
4426 unusal. It is allowed to return a value of some identifiable type, in
4427 which case the loop aborts and an appropriate `casepart` is run, or it
4428 can return a Boolean, in which case the loop either continues to the
4429 `dopart` (on `True`) or aborts and runs the `elsepart` (on `False`).
4430 This is different both from the `ifpart` code block which is expected to
4431 return a Boolean, or the `switchpart` code block which is expected to
4432 return the same type as the casepart values. The correct analysis of
4433 the type of the `whilepart` code block is the reason for the
4434 `Rboolok` flag which is passed to `propagate_types()`.
4436 The `cond_statement` cannot fit into a `binode` so a new `exec` is
4437 defined. As there are two scopes which cover multiple parts - one for
4438 the whole statement and one for "while" and "do" - and as we will use
4439 the 'struct exec' to track scopes, we actually need two new types of
4440 exec. One is a `binode` for the looping part, the rest is the
4441 `cond_statement`. The `cond_statement` will use an auxilliary `struct
4442 casepart` to track a list of case parts.
4453 struct exec *action;
4454 struct casepart *next;
4456 struct cond_statement {
4458 struct exec *forpart, *condpart, *thenpart, *elsepart;
4459 struct binode *looppart;
4460 struct casepart *casepart;
4463 ###### ast functions
4465 static void free_casepart(struct casepart *cp)
4469 free_exec(cp->value);
4470 free_exec(cp->action);
4477 static void free_cond_statement(struct cond_statement *s)
4481 free_exec(s->forpart);
4482 free_exec(s->condpart);
4483 free_exec(s->looppart);
4484 free_exec(s->thenpart);
4485 free_exec(s->elsepart);
4486 free_casepart(s->casepart);
4490 ###### free exec cases
4491 case Xcond_statement: free_cond_statement(cast(cond_statement, e)); break;
4493 ###### ComplexStatement Grammar
4494 | CondStatement ${ $0 = $<1; }$
4496 ###### declare terminals
4497 $TERM for then while do
4504 // A CondStatement must end with EOL, as does CondSuffix and
4506 // ForPart, ThenPart, SwitchPart, CasePart are non-empty and
4507 // may or may not end with EOL
4508 // WhilePart and IfPart include an appropriate Suffix
4510 // ForPart, SwitchPart, and IfPart open scopes, o we have to close
4511 // them. WhilePart opens and closes its own scope.
4512 CondStatement -> ForPart OptNL ThenPart OptNL WhilePart CondSuffix ${
4515 $0->thenpart = $<TP;
4516 $0->looppart = $<WP;
4517 var_block_close(c, CloseSequential, $0);
4519 | ForPart OptNL WhilePart CondSuffix ${
4522 $0->looppart = $<WP;
4523 var_block_close(c, CloseSequential, $0);
4525 | WhilePart CondSuffix ${
4527 $0->looppart = $<WP;
4529 | SwitchPart OptNL CasePart CondSuffix ${
4531 $0->condpart = $<SP;
4532 $CP->next = $0->casepart;
4533 $0->casepart = $<CP;
4534 var_block_close(c, CloseSequential, $0);
4536 | SwitchPart : IN OptNL CasePart CondSuffix OUT Newlines ${
4538 $0->condpart = $<SP;
4539 $CP->next = $0->casepart;
4540 $0->casepart = $<CP;
4541 var_block_close(c, CloseSequential, $0);
4543 | IfPart IfSuffix ${
4545 $0->condpart = $IP.condpart; $IP.condpart = NULL;
4546 $0->thenpart = $IP.thenpart; $IP.thenpart = NULL;
4547 // This is where we close an "if" statement
4548 var_block_close(c, CloseSequential, $0);
4551 CondSuffix -> IfSuffix ${
4554 | Newlines CasePart CondSuffix ${
4556 $CP->next = $0->casepart;
4557 $0->casepart = $<CP;
4559 | CasePart CondSuffix ${
4561 $CP->next = $0->casepart;
4562 $0->casepart = $<CP;
4565 IfSuffix -> Newlines ${ $0 = new(cond_statement); }$
4566 | Newlines ElsePart ${ $0 = $<EP; }$
4567 | ElsePart ${$0 = $<EP; }$
4569 ElsePart -> else OpenBlock Newlines ${
4570 $0 = new(cond_statement);
4571 $0->elsepart = $<OB;
4572 var_block_close(c, CloseElse, $0->elsepart);
4574 | else OpenScope CondStatement ${
4575 $0 = new(cond_statement);
4576 $0->elsepart = $<CS;
4577 var_block_close(c, CloseElse, $0->elsepart);
4581 CasePart -> case Expression OpenScope ColonBlock ${
4582 $0 = calloc(1,sizeof(struct casepart));
4585 var_block_close(c, CloseParallel, $0->action);
4589 // These scopes are closed in CondStatement
4590 ForPart -> for OpenBlock ${
4594 ThenPart -> then OpenBlock ${
4596 var_block_close(c, CloseSequential, $0);
4600 // This scope is closed in CondStatement
4601 WhilePart -> while UseBlock OptNL do OpenBlock ${
4606 var_block_close(c, CloseSequential, $0->right);
4607 var_block_close(c, CloseSequential, $0);
4609 | while OpenScope Expression OpenScope ColonBlock ${
4614 var_block_close(c, CloseSequential, $0->right);
4615 var_block_close(c, CloseSequential, $0);
4619 IfPart -> if UseBlock OptNL then OpenBlock ${
4622 var_block_close(c, CloseParallel, $0.thenpart);
4624 | if OpenScope Expression OpenScope ColonBlock ${
4627 var_block_close(c, CloseParallel, $0.thenpart);
4629 | if OpenScope Expression OpenScope OptNL then Block ${
4632 var_block_close(c, CloseParallel, $0.thenpart);
4636 // This scope is closed in CondStatement
4637 SwitchPart -> switch OpenScope Expression ${
4640 | switch UseBlock ${
4644 ###### print binode cases
4646 if (b->left && b->left->type == Xbinode &&
4647 cast(binode, b->left)->op == Block) {
4649 do_indent(indent, "while {\n");
4651 do_indent(indent, "while\n");
4652 print_exec(b->left, indent+1, bracket);
4654 do_indent(indent, "} do {\n");
4656 do_indent(indent, "do\n");
4657 print_exec(b->right, indent+1, bracket);
4659 do_indent(indent, "}\n");
4661 do_indent(indent, "while ");
4662 print_exec(b->left, 0, bracket);
4667 print_exec(b->right, indent+1, bracket);
4669 do_indent(indent, "}\n");
4673 ###### print exec cases
4675 case Xcond_statement:
4677 struct cond_statement *cs = cast(cond_statement, e);
4678 struct casepart *cp;
4680 do_indent(indent, "for");
4681 if (bracket) printf(" {\n"); else printf("\n");
4682 print_exec(cs->forpart, indent+1, bracket);
4685 do_indent(indent, "} then {\n");
4687 do_indent(indent, "then\n");
4688 print_exec(cs->thenpart, indent+1, bracket);
4690 if (bracket) do_indent(indent, "}\n");
4693 print_exec(cs->looppart, indent, bracket);
4697 do_indent(indent, "switch");
4699 do_indent(indent, "if");
4700 if (cs->condpart && cs->condpart->type == Xbinode &&
4701 cast(binode, cs->condpart)->op == Block) {
4706 print_exec(cs->condpart, indent+1, bracket);
4708 do_indent(indent, "}\n");
4710 do_indent(indent, "then\n");
4711 print_exec(cs->thenpart, indent+1, bracket);
4715 print_exec(cs->condpart, 0, bracket);
4721 print_exec(cs->thenpart, indent+1, bracket);
4723 do_indent(indent, "}\n");
4728 for (cp = cs->casepart; cp; cp = cp->next) {
4729 do_indent(indent, "case ");
4730 print_exec(cp->value, -1, 0);
4735 print_exec(cp->action, indent+1, bracket);
4737 do_indent(indent, "}\n");
4740 do_indent(indent, "else");
4745 print_exec(cs->elsepart, indent+1, bracket);
4747 do_indent(indent, "}\n");
4752 ###### propagate binode cases
4754 t = propagate_types(b->right, c, perr, Tnone, 0);
4755 if (!type_compat(Tnone, t, 0))
4756 *perr |= Efail; // UNTESTED
4757 return propagate_types(b->left, c, perr, type, rules);
4759 ###### propagate exec cases
4760 case Xcond_statement:
4762 // forpart and looppart->right must return Tnone
4763 // thenpart must return Tnone if there is a loopart,
4764 // otherwise it is like elsepart.
4766 // be bool if there is no casepart
4767 // match casepart->values if there is a switchpart
4768 // either be bool or match casepart->value if there
4770 // elsepart and casepart->action must match the return type
4771 // expected of this statement.
4772 struct cond_statement *cs = cast(cond_statement, prog);
4773 struct casepart *cp;
4775 t = propagate_types(cs->forpart, c, perr, Tnone, 0);
4776 if (!type_compat(Tnone, t, 0))
4777 *perr |= Efail; // UNTESTED
4780 t = propagate_types(cs->thenpart, c, perr, Tnone, 0);
4781 if (!type_compat(Tnone, t, 0))
4782 *perr |= Efail; // UNTESTED
4784 if (cs->casepart == NULL) {
4785 propagate_types(cs->condpart, c, perr, Tbool, 0);
4786 propagate_types(cs->looppart, c, perr, Tbool, 0);
4788 /* Condpart must match case values, with bool permitted */
4790 for (cp = cs->casepart;
4791 cp && !t; cp = cp->next)
4792 t = propagate_types(cp->value, c, perr, NULL, 0);
4793 if (!t && cs->condpart)
4794 t = propagate_types(cs->condpart, c, perr, NULL, Rboolok); // UNTESTED
4795 if (!t && cs->looppart)
4796 t = propagate_types(cs->looppart, c, perr, NULL, Rboolok); // UNTESTED
4797 // Now we have a type (I hope) push it down
4799 for (cp = cs->casepart; cp; cp = cp->next)
4800 propagate_types(cp->value, c, perr, t, 0);
4801 propagate_types(cs->condpart, c, perr, t, Rboolok);
4802 propagate_types(cs->looppart, c, perr, t, Rboolok);
4805 // (if)then, else, and case parts must return expected type.
4806 if (!cs->looppart && !type)
4807 type = propagate_types(cs->thenpart, c, perr, NULL, rules);
4809 type = propagate_types(cs->elsepart, c, perr, NULL, rules);
4810 for (cp = cs->casepart;
4812 cp = cp->next) // UNTESTED
4813 type = propagate_types(cp->action, c, perr, NULL, rules); // UNTESTED
4816 propagate_types(cs->thenpart, c, perr, type, rules);
4817 propagate_types(cs->elsepart, c, perr, type, rules);
4818 for (cp = cs->casepart; cp ; cp = cp->next)
4819 propagate_types(cp->action, c, perr, type, rules);
4825 ###### interp binode cases
4827 // This just performs one iterration of the loop
4828 rv = interp_exec(c, b->left, &rvtype);
4829 if (rvtype == Tnone ||
4830 (rvtype == Tbool && rv.bool != 0))
4831 // rvtype is Tnone or Tbool, doesn't need to be freed
4832 interp_exec(c, b->right, NULL);
4835 ###### interp exec cases
4836 case Xcond_statement:
4838 struct value v, cnd;
4839 struct type *vtype, *cndtype;
4840 struct casepart *cp;
4841 struct cond_statement *cs = cast(cond_statement, e);
4844 interp_exec(c, cs->forpart, NULL);
4846 while ((cnd = interp_exec(c, cs->looppart, &cndtype)),
4847 cndtype == Tnone || (cndtype == Tbool && cnd.bool != 0))
4848 interp_exec(c, cs->thenpart, NULL);
4850 cnd = interp_exec(c, cs->condpart, &cndtype);
4851 if ((cndtype == Tnone ||
4852 (cndtype == Tbool && cnd.bool != 0))) {
4853 // cnd is Tnone or Tbool, doesn't need to be freed
4854 rv = interp_exec(c, cs->thenpart, &rvtype);
4855 // skip else (and cases)
4859 for (cp = cs->casepart; cp; cp = cp->next) {
4860 v = interp_exec(c, cp->value, &vtype);
4861 if (value_cmp(cndtype, vtype, &v, &cnd) == 0) {
4862 free_value(vtype, &v);
4863 free_value(cndtype, &cnd);
4864 rv = interp_exec(c, cp->action, &rvtype);
4867 free_value(vtype, &v);
4869 free_value(cndtype, &cnd);
4871 rv = interp_exec(c, cs->elsepart, &rvtype);
4878 ### Top level structure
4880 All the language elements so far can be used in various places. Now
4881 it is time to clarify what those places are.
4883 At the top level of a file there will be a number of declarations.
4884 Many of the things that can be declared haven't been described yet,
4885 such as functions, procedures, imports, and probably more.
4886 For now there are two sorts of things that can appear at the top
4887 level. They are predefined constants, `struct` types, and the `main`
4888 function. While the syntax will allow the `main` function to appear
4889 multiple times, that will trigger an error if it is actually attempted.
4891 The various declarations do not return anything. They store the
4892 various declarations in the parse context.
4894 ###### Parser: grammar
4897 Ocean -> OptNL DeclarationList
4899 ## declare terminals
4907 DeclarationList -> Declaration
4908 | DeclarationList Declaration
4910 Declaration -> ERROR Newlines ${
4911 tok_err(c, // UNTESTED
4912 "error: unhandled parse error", &$1);
4918 ## top level grammar
4922 ### The `const` section
4924 As well as being defined in with the code that uses them, constants can
4925 be declared at the top level. These have full-file scope, so they are
4926 always `InScope`, even before(!) they have been declared. The value of
4927 a top level constant can be given as an expression, and this is
4928 evaluated after parsing and before execution.
4930 A function call can be used to evaluate a constant, but it will not have
4931 access to any program state, once such statement becomes meaningful.
4932 e.g. arguments and filesystem will not be visible.
4934 Constants are defined in a section that starts with the reserved word
4935 `const` and then has a block with a list of assignment statements.
4936 For syntactic consistency, these must use the double-colon syntax to
4937 make it clear that they are constants. Type can also be given: if
4938 not, the type will be determined during analysis, as with other
4941 ###### parse context
4942 struct binode *constlist;
4944 ###### top level grammar
4948 DeclareConstant -> const { IN OptNL ConstList OUT OptNL } Newlines
4949 | const { SimpleConstList } Newlines
4950 | const IN OptNL ConstList OUT Newlines
4951 | const SimpleConstList Newlines
4953 ConstList -> ConstList SimpleConstLine
4956 SimpleConstList -> SimpleConstList ; Const
4960 SimpleConstLine -> SimpleConstList Newlines
4961 | ERROR Newlines ${ tok_err(c, "Syntax error in constant", &$1); }$
4964 CType -> Type ${ $0 = $<1; }$
4968 Const -> IDENTIFIER :: CType = Expression ${ {
4970 struct binode *bl, *bv;
4971 struct var *var = new_pos(var, $ID);
4973 v = var_decl(c, $ID.txt);
4975 v->where_decl = var;
4981 v = var_ref(c, $1.txt);
4982 if (v->type == Tnone) {
4983 v->where_decl = var;
4989 tok_err(c, "error: name already declared", &$1);
4990 type_err(c, "info: this is where '%v' was first declared",
4991 v->where_decl, NULL, 0, NULL);
5003 bl->left = c->constlist;
5008 ###### core functions
5009 static void resolve_consts(struct parse_context *c)
5013 enum { none, some, cannot } progress = none;
5015 c->constlist = reorder_bilist(c->constlist);
5018 for (b = cast(binode, c->constlist); b;
5019 b = cast(binode, b->right)) {
5021 struct binode *vb = cast(binode, b->left);
5022 struct var *v = cast(var, vb->left);
5023 if (v->var->frame_pos >= 0)
5027 propagate_types(vb->right, c, &perr,
5029 } while (perr & Eretry);
5031 c->parse_error += 1;
5032 else if (!(perr & Enoconst)) {
5034 struct value res = interp_exec(
5035 c, vb->right, &v->var->type);
5036 global_alloc(c, v->var->type, v->var, &res);
5038 if (progress == cannot)
5039 type_err(c, "error: const %v cannot be resolved.",
5049 progress = cannot; break;
5051 progress = none; break;
5056 ###### print const decls
5061 for (b = cast(binode, context.constlist); b;
5062 b = cast(binode, b->right)) {
5063 struct binode *vb = cast(binode, b->left);
5064 struct var *vr = cast(var, vb->left);
5065 struct variable *v = vr->var;
5071 printf(" %.*s :: ", v->name->name.len, v->name->name.txt);
5072 type_print(v->type, stdout);
5074 print_exec(vb->right, -1, 0);
5079 ###### free const decls
5080 free_binode(context.constlist);
5082 ### Function declarations
5084 The code in an Ocean program is all stored in function declarations.
5085 One of the functions must be named `main` and it must accept an array of
5086 strings as a parameter - the command line arguments.
5088 As this is the top level, several things are handled a bit differently.
5089 The function is not interpreted by `interp_exec` as that isn't passed
5090 the argument list which the program requires. Similarly type analysis
5091 is a bit more interesting at this level.
5093 ###### ast functions
5095 static struct type *handle_results(struct parse_context *c,
5096 struct binode *results)
5098 /* Create a 'struct' type from the results list, which
5099 * is a list for 'struct var'
5101 struct type *t = add_anon_type(c, &structure_prototype,
5102 " function result");
5106 for (b = results; b; b = cast(binode, b->right))
5108 t->structure.nfields = cnt;
5109 t->structure.fields = calloc(cnt, sizeof(struct field));
5111 for (b = results; b; b = cast(binode, b->right)) {
5112 struct var *v = cast(var, b->left);
5113 struct field *f = &t->structure.fields[cnt++];
5114 int a = v->var->type->align;
5115 f->name = v->var->name->name;
5116 f->type = v->var->type;
5118 f->offset = t->size;
5119 v->var->frame_pos = f->offset;
5120 t->size += ((f->type->size - 1) | (a-1)) + 1;
5123 variable_unlink_exec(v->var);
5125 free_binode(results);
5129 static struct variable *declare_function(struct parse_context *c,
5130 struct variable *name,
5131 struct binode *args,
5133 struct binode *results,
5137 struct value fn = {.function = code};
5139 var_block_close(c, CloseFunction, code);
5140 t = add_anon_type(c, &function_prototype,
5141 "func %.*s", name->name->name.len,
5142 name->name->name.txt);
5144 t->function.params = reorder_bilist(args);
5146 ret = handle_results(c, reorder_bilist(results));
5147 t->function.inline_result = 1;
5148 t->function.local_size = ret->size;
5150 t->function.return_type = ret;
5151 global_alloc(c, t, name, &fn);
5152 name->type->function.scope = c->out_scope;
5157 var_block_close(c, CloseFunction, NULL);
5159 c->out_scope = NULL;
5163 ###### declare terminals
5166 ###### top level grammar
5169 DeclareFunction -> func FuncName ( OpenScope ArgsLine ) Block Newlines ${
5170 $0 = declare_function(c, $<FN, $<Ar, Tnone, NULL, $<Bl);
5172 | func FuncName IN OpenScope Args OUT OptNL do Block Newlines ${
5173 $0 = declare_function(c, $<FN, $<Ar, Tnone, NULL, $<Bl);
5175 | func FuncName NEWLINE OpenScope OptNL do Block Newlines ${
5176 $0 = declare_function(c, $<FN, NULL, Tnone, NULL, $<Bl);
5178 | func FuncName ( OpenScope ArgsLine ) : Type Block Newlines ${
5179 $0 = declare_function(c, $<FN, $<Ar, $<Ty, NULL, $<Bl);
5181 | func FuncName ( OpenScope ArgsLine ) : ( ArgsLine ) Block Newlines ${
5182 $0 = declare_function(c, $<FN, $<AL, NULL, $<AL2, $<Bl);
5184 | func FuncName IN OpenScope Args OUT OptNL return Type Newlines do Block Newlines ${
5185 $0 = declare_function(c, $<FN, $<Ar, $<Ty, NULL, $<Bl);
5187 | func FuncName NEWLINE OpenScope return Type Newlines do Block Newlines ${
5188 $0 = declare_function(c, $<FN, NULL, $<Ty, NULL, $<Bl);
5190 | func FuncName IN OpenScope Args OUT OptNL return IN Args OUT OptNL do Block Newlines ${
5191 $0 = declare_function(c, $<FN, $<Ar, NULL, $<Ar2, $<Bl);
5193 | func FuncName NEWLINE OpenScope return IN Args OUT OptNL do Block Newlines ${
5194 $0 = declare_function(c, $<FN, NULL, NULL, $<Ar, $<Bl);
5197 ###### print func decls
5202 while (target != 0) {
5204 for (v = context.in_scope; v; v=v->in_scope)
5205 if (v->depth == 0 && v->type && v->type->check_args) {
5214 struct value *val = var_value(&context, v);
5215 printf("func %.*s", v->name->name.len, v->name->name.txt);
5216 v->type->print_type_decl(v->type, stdout);
5218 print_exec(val->function, 0, brackets);
5220 print_value(v->type, val, stdout);
5221 printf("/* frame size %d */\n", v->type->function.local_size);
5227 ###### core functions
5229 static int analyse_funcs(struct parse_context *c)
5233 for (v = c->in_scope; v; v = v->in_scope) {
5237 if (v->depth != 0 || !v->type || !v->type->check_args)
5239 ret = v->type->function.inline_result ?
5240 Tnone : v->type->function.return_type;
5241 val = var_value(c, v);
5244 propagate_types(val->function, c, &perr, ret, 0);
5245 } while (!(perr & Efail) && (perr & Eretry));
5246 if (!(perr & Efail))
5247 /* Make sure everything is still consistent */
5248 propagate_types(val->function, c, &perr, ret, 0);
5251 if (!v->type->function.inline_result &&
5252 !v->type->function.return_type->dup) {
5253 type_err(c, "error: function cannot return value of type %1",
5254 v->where_decl, v->type->function.return_type, 0, NULL);
5257 scope_finalize(c, v->type);
5262 static int analyse_main(struct type *type, struct parse_context *c)
5264 struct binode *bp = type->function.params;
5268 struct type *argv_type;
5270 argv_type = add_anon_type(c, &array_prototype, "argv");
5271 argv_type->array.member = Tstr;
5272 argv_type->array.unspec = 1;
5274 for (b = bp; b; b = cast(binode, b->right)) {
5278 propagate_types(b->left, c, &perr, argv_type, 0);
5280 default: /* invalid */ // NOTEST
5281 propagate_types(b->left, c, &perr, Tnone, 0); // NOTEST
5284 c->parse_error += 1;
5287 return !c->parse_error;
5290 static void interp_main(struct parse_context *c, int argc, char **argv)
5292 struct value *progp = NULL;
5293 struct text main_name = { "main", 4 };
5294 struct variable *mainv;
5300 mainv = var_ref(c, main_name);
5302 progp = var_value(c, mainv);
5303 if (!progp || !progp->function) {
5304 fprintf(stderr, "oceani: no main function found.\n");
5305 c->parse_error += 1;
5308 if (!analyse_main(mainv->type, c)) {
5309 fprintf(stderr, "oceani: main has wrong type.\n");
5310 c->parse_error += 1;
5313 al = mainv->type->function.params;
5315 c->local_size = mainv->type->function.local_size;
5316 c->local = calloc(1, c->local_size);
5318 struct var *v = cast(var, al->left);
5319 struct value *vl = var_value(c, v->var);
5329 mpq_set_ui(argcq, argc, 1);
5330 memcpy(var_value(c, t->array.vsize), &argcq, sizeof(argcq));
5331 t->prepare_type(c, t, 0);
5332 array_init(v->var->type, vl);
5333 for (i = 0; i < argc; i++) {
5334 struct value *vl2 = vl->array + i * v->var->type->array.member->size;
5336 arg.str.txt = argv[i];
5337 arg.str.len = strlen(argv[i]);
5338 free_value(Tstr, vl2);
5339 dup_value(Tstr, &arg, vl2);
5343 al = cast(binode, al->right);
5345 v = interp_exec(c, progp->function, &vtype);
5346 free_value(vtype, &v);
5351 ###### ast functions
5352 void free_variable(struct variable *v)
5356 ## And now to test it out.
5358 Having a language requires having a "hello world" program. I'll
5359 provide a little more than that: a program that prints "Hello world"
5360 finds the GCD of two numbers, prints the first few elements of
5361 Fibonacci, performs a binary search for a number, and a few other
5362 things which will likely grow as the languages grows.
5364 ###### File: oceani.mk
5367 @echo "===== DEMO ====="
5368 ./oceani --section "demo: hello" oceani.mdc 55 33
5374 four ::= 2 + 2 ; five ::= 10/2
5375 const pie ::= "I like Pie";
5376 cake ::= "The cake is"
5384 func main(argv:[argc::]string)
5385 print "Hello World, what lovely oceans you have!"
5386 print "Are there", five, "?"
5387 print pi, pie, "but", cake
5389 A := $argv[1]; B := $argv[2]
5391 /* When a variable is defined in both branches of an 'if',
5392 * and used afterwards, the variables are merged.
5398 print "Is", A, "bigger than", B,"? ", bigger
5399 /* If a variable is not used after the 'if', no
5400 * merge happens, so types can be different
5403 double:string = "yes"
5404 print A, "is more than twice", B, "?", double
5407 print "double", B, "is", double
5412 if a > 0 and then b > 0:
5418 print "GCD of", A, "and", B,"is", a
5420 print a, "is not positive, cannot calculate GCD"
5422 print b, "is not positive, cannot calculate GCD"
5427 print "Fibonacci:", f1,f2,
5428 then togo = togo - 1
5436 /* Binary search... */
5441 mid := (lo + hi) / 2
5454 print "Yay, I found", target
5456 print "Closest I found was", lo
5461 // "middle square" PRNG. Not particularly good, but one my
5462 // Dad taught me - the first one I ever heard of.
5463 for i:=1; then i = i + 1; while i < size:
5464 n := list[i-1] * list[i-1]
5465 list[i] = (n / 100) % 10 000
5467 print "Before sort:",
5468 for i:=0; then i = i + 1; while i < size:
5472 for i := 1; then i=i+1; while i < size:
5473 for j:=i-1; then j=j-1; while j >= 0:
5474 if list[j] > list[j+1]:
5478 print " After sort:",
5479 for i:=0; then i = i + 1; while i < size:
5483 if 1 == 2 then print "yes"; else print "no"
5487 bob.alive = (bob.name == "Hello")
5488 print "bob", "is" if bob.alive else "isn't", "alive"