1 # Ocean Interpreter - Falls Creek version
3 Ocean is intended to be an compiled language, so this interpreter is
4 not targeted at being the final product. It is very much 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 initial version of the interpreter exists to test out the
33 structured statement providing conditions and iteration. Clearly we
34 need some minimal other functionality so that values can be tested and
35 instructions iterated over. All that functionality is clearly not
36 normative at this stage (not that anything is **really** normative
37 yet) and will change, so early test code will certainly break.
39 Beyond the structured statement and the `use` statement which is
40 intimately related to it we have:
42 - "blocks" of multiple statements.
43 - `pass`: a statement which does nothing.
44 - variables: any identifier is assumed to store a number, string,
46 - expressions: `+`, `-`, `*`, `/` can apply to integers and `++` can
47 catenate strings. `and`, `or`, `not` manipulate Booleans, and
48 normal comparison operators can work on all three types.
49 - assignments: can assign the value of an expression to a variable.
50 - `print`: will print the values in a list of expressions.
51 - `program`: is given a list of identifiers to initialize from
56 Versions of the interpreter which obviously do not support a complete
57 language will be named after creeks and streams. This one is Falls
60 Once we have something reasonably resembling a complete language, the
61 names of rivers will be used.
62 Early versions of the compiler will be named after seas. Major
63 releases of the compiler will be named after oceans. Hopefully I will
64 be finished once I get to the Pacific Ocean release.
68 As well as parsing and executing a program, the interpreter can print
69 out the program from the parsed internal structure. This is useful
70 for validating the parsing.
71 So the main requirements of the interpreter are:
74 - Analyse the parsed program to ensure consistency
78 This is all performed by a single C program extracted with
81 There will be two formats for printing the program a default and one
82 that uses bracketing. So an extra command line option is needed for
85 ###### File: oceani.mk
87 myCFLAGS := -Wall -g -fplan9-extensions
88 CFLAGS := $(filter-out $(myCFLAGS),$(CFLAGS)) $(myCFLAGS)
89 myLDLIBS:= libparser.o libscanner.o libmdcode.o -licuuc
90 LDLIBS := $(filter-out $(myLDLIBS),$(LDLIBS)) $(myLDLIBS)
93 oceani.c oceani.h : oceani.mdc parsergen
94 ./parsergen -o oceani --LALR --tag Parser oceani.mdc
95 oceani.mk: oceani.mdc md2c
100 ###### Parser: header
103 struct parse_context {
104 struct token_config config;
114 #include <sys/mman.h>
133 static char Usage[] = "Usage: oceani --trace --print --noexec prog.ocn\n";
134 static const struct option long_options[] = {
135 {"trace", 0, NULL, 't'},
136 {"print", 0, NULL, 'p'},
137 {"noexec", 0, NULL, 'n'},
138 {"brackets", 0, NULL, 'b'},
141 const char *options = "tpnb";
142 int main(int argc, char *argv[])
148 struct parse_context context = {
150 .ignored = (1 << TK_line_comment)
151 | (1 << TK_block_comment),
152 .number_chars = ".,_+-",
157 int doprint=0, dotrace=0, doexec=1, brackets=0;
160 while ((opt = getopt_long(argc, argv, options, long_options, NULL))
163 case 't': dotrace=1; break;
164 case 'p': doprint=1; break;
165 case 'n': doexec=0; break;
166 case 'b': brackets=1; break;
167 default: fprintf(stderr, Usage);
171 if (optind >= argc) {
172 fprintf(stderr, "oceani: no input file given\n");
175 fd = open(argv[optind], O_RDONLY);
177 fprintf(stderr, "oceani: cannot open %s\n", argv[optind]);
180 len = lseek(fd, 0, 2);
181 file = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
182 s = code_extract(file, file+len, NULL);
184 fprintf(stderr, "oceani: could not find any code in %s\n",
188 prog = parse_oceani(s->code, &context.config,
189 dotrace ? stderr : NULL);
191 print_exec(*prog, 0, brackets);
192 if (prog && doexec) {
193 if (!analyse_prog(*prog, &context)) {
194 fprintf(stderr, "oceani: type error in program\n");
197 interp_prog(*prog, argv+optind+1);
204 struct section *t = s->next;
215 These four requirements of parse, analyse, print, interpret apply to
216 each language element individually so that is how most of the code
219 Three of the four are fairly self explanatory. The one that requires
220 a little explanation is the analysis step.
222 The current language design does not require variables to be declared,
223 but they must have a single type. Different operations impose
224 different requirements on the variables, for example addition requires
225 both arguments to be numeric, and assignment requires the variable on
226 the left to have the same type as the expression on the right.
228 Analysis involves propagating these type requirements around
229 consequently setting the type of each variable. If any requirements
230 are violated (e.g. a string is compared with a number) or if a
231 variable needs to have two different types, then an error is raised
232 and the program will not run.
234 Determining the types of all variables early is important for
235 processing command line arguments. These can be assigned to any type
236 of variable, but we must first know the correct type so any required
237 conversion can happen. If a variable is associated with a command
238 line argument but no type can be interpreted (e.g. the variable is
239 only ever used in a `print` statement), then the type is set to
242 If the type of a variable cannot be determined at all, then it is set
243 to be a number and given a unique value. This allows it to fill the
244 role of a name in an enumerated type, which is useful for testing the
249 One last introductory step before detailing the language elements and
250 providing their four requirements is to establish the data structures
251 to store these elements.
253 There are two key objects that we need to work with: executable
254 elements which comprise the program, and values which the program
255 works with. Between these is the set of variables which hold the
260 Values can be numbers, which we represent as multi-precision
261 fractions, strings and Booleans. When analysing the program we also
262 need to allow for places where no value is meaningful (`Vnone`) and
263 where we don't know what type to expect yet (`Vunknown`).
264 A 2 character 'tail' is included in each value as the scanner wants
265 to parse that from the end of numbers and we need somewhere to put
266 it. It is currently ignored but one day might allow for
267 e.g. "imaginary" numbers.
269 Values are never shared, they are always copied when used, and freed
270 when no longer needed.
278 myLDLIBS := libnumber.o libstring.o -lgmp
279 LDLIBS := $(filter-out $(myLDLIBS),$(LDLIBS)) $(myLDLIBS)
283 enum vtype {Vunknown, Vnone, Vstr, Vnum, Vbool} vtype;
293 void free_value(struct value v)
297 case Vunknown: break;
298 case Vstr: free(v.str.txt); break;
299 case Vnum: mpq_clear(v.num); break;
304 ###### value functions
306 static void val_init(struct value *val, enum vtype type)
311 case Vunknown: break;
313 mpq_init(val->num); break;
315 val->str.txt = malloc(1);
324 static struct value dup_value(struct value v)
330 case Vunknown: break;
336 mpq_set(rv.num, v.num);
339 rv.str.len = v.str.len;
340 rv.str.txt = malloc(rv.str.len);
341 memcpy(rv.str.txt, v.str.txt, v.str.len);
347 static int value_cmp(struct value left, struct value right)
350 if (left.vtype != right.vtype)
351 return left.vtype - right.vtype;
352 switch (left.vtype) {
353 case Vnum: cmp = mpq_cmp(left.num, right.num); break;
354 case Vstr: cmp = text_cmp(left.str, right.str); break;
355 case Vbool: cmp = left.bool - right.bool; break;
357 case Vunknown: cmp = 0;
362 static struct text text_join(struct text a, struct text b)
365 rv.len = a.len + b.len;
366 rv.txt = malloc(rv.len);
367 memcpy(rv.txt, a.txt, a.len);
368 memcpy(rv.txt+a.len, b.txt, b.len);
372 static void print_value(struct value v)
376 printf("*Unknown*"); break;
378 printf("*no-value*"); break;
380 printf("%.*s", v.str.len, v.str.txt); break;
382 printf("%s", v.bool ? "True":"False"); break;
387 mpf_set_q(fl, v.num);
388 gmp_printf("%Fg", fl);
395 static int parse_value(struct value *vl, char *arg)
404 vl->str.len = strlen(arg);
405 vl->str.txt = malloc(vl->str.len);
406 memcpy(vl->str.txt, arg, vl->str.len);
413 tx.txt = arg; tx.len = strlen(tx.txt);
414 if (number_parse(vl->num, vl->tail, tx) == 0)
417 mpq_neg(vl->num, vl->num);
420 if (strcasecmp(arg, "true") == 0 ||
421 strcmp(arg, "1") == 0)
423 else if (strcasecmp(arg, "false") == 0 ||
424 strcmp(arg, "0") == 0)
427 printf("Bad bool: %s\n", arg);
437 Variables are simply named values. We store them in a linked list
438 sorted by name and use sequential search and insertion sort.
440 This linked list is stored in the parse context so that reduce
441 functions can find or add variables, and so the analysis phase can
442 ensure that every variable gets a type.
448 struct variable *next;
454 #define container_of(ptr, type, member) ({ \
455 const typeof( ((type *)0)->member ) *__mptr = (ptr); \
456 (type *)( (char *)__mptr - offsetof(type,member) );})
460 struct variable *varlist;
463 while (context.varlist) {
464 struct variable *v = context.varlist;
465 context.varlist = v->next;
472 static struct variable *find_variable(struct token_config *conf, struct text s)
474 struct variable **l = &container_of(conf, struct parse_context,
480 (cmp = text_cmp((*l)->name, s)) < 0)
484 n = calloc(1, sizeof(*n));
486 n->val.vtype = Vunknown;
494 Executables can be lots of different things. In many cases an
495 executable is just an operation combined with one or two other
496 executables. This allows for expressions and lists etc. Other times
497 an executable is something quite specific like a constant or variable
498 name. So we define a `struct exec` to be a general executable with a
499 type, and a `struct binode` which is a subclass of `exec` and forms a
500 node in a binary tree and holding an operation. There will be other
501 subclasses, and to access these we need to be able to `cast` the
502 `exec` into the various other types.
505 #define cast(structname, pointer) ({ \
506 const typeof( ((struct structname *)0)->type) *__mptr = &(pointer)->type; \
507 if (__mptr && *__mptr != X##structname) abort(); \
508 (struct structname *)( (char *)__mptr);})
510 #define new(structname) ({ \
511 struct structname *__ptr = ((struct structname *)calloc(1,sizeof(struct structname))); \
512 __ptr->type = X##structname; \
521 enum exec_types type;
528 struct exec *left, *right;
531 Each different type of `exec` node needs a number of functions
532 defined, a bit like methods. We must be able to be able to free it,
533 print it, analyse it and execute it. Once we have specific `exec`
534 types we will need to parse them to. Let's take this a bit more
539 The parser generator requires as `free_foo` function for each struct
540 that stores attributes and they will be `exec`s of subtypes there-of.
541 So we need `free_exec` which can handle all the subtypes, and we need
546 static void free_binode(struct binode *b)
555 ###### core functions
556 static void free_exec(struct exec *e)
567 static void free_exec(struct exec *e);
569 ###### free exec cases
570 case Xbinode: free_binode(cast(binode, e)); break;
574 Printing an `exec` requires that we know the current indent level for
575 printing line-oriented components. As will become clear later, we
576 also want to know what sort of bracketing to use.
580 static void do_indent(int i, char *str)
587 ###### core functions
588 static void print_binode(struct binode *b, int indent, int bracket)
592 ## print binode cases
596 static void print_exec(struct exec *e, int indent, int bracket)
600 print_binode(cast(binode, e), indent, bracket); break;
607 static void print_exec(struct exec *e, int indent, int bracket);
611 As discusses, analysis involves propagating type requirements around
612 the program and looking for errors.
614 So propagate_types is passed a type that the `exec` is expected to return,
615 and returns the type that it does return, either of which can be `Vunknown`.
616 An `ok` flag is passed by reference. It is set to `0` when an error is
617 found, and `2` when any change is made. If it remains unchanged at
618 `1`, then no more propagation is needed.
620 ###### core functions
622 static enum vtype propagate_types(struct exec *prog, enum vtype type,
628 if (type != Vunknown && type != Vnone)
633 switch (prog->type) {
636 struct binode *b = cast(binode, prog);
638 ## propagate binode cases
642 ## propagate exec cases
649 Interpreting an `exec` doesn't require anything but the `exec`. State
650 is stored in variables and each variable will be directly linked from
651 within the `exec` tree. The exception to this is the whole `program`
652 which needs to look at command line arguments. The `program` will be
653 interpreted separately.
655 Each `exec` can return a value, which may be `Vnone` but shouldn't be `Vunknown`.
657 ###### core functions
659 static struct value interp_exec(struct exec *e)
669 struct binode *b = cast(binode, e);
670 struct value left, right;
671 left.vtype = right.vtype = Vnone;
673 ## interp binode cases
675 free_value(left); free_value(right);
685 Each language element needs to be parsed, printed, analysed,
686 interpreted, and freed. There are several, so let's just start with
687 the easy ones and work our way up.
691 We have already met values and separate objects. When manifest
692 constants appear in the program text that must result in an executable
693 which has a constant value. So the `val` structure embeds a value in
710 $0->val.vtype = Vbool;
715 $0->val.vtype = Vbool;
720 $0->val.vtype = Vnum;
721 if (number_parse($0->val.num, $0->val.tail, $1.txt) == 0)
722 mpq_init($0->val.num);
726 $0->val.vtype = Vstr;
727 string_parse(&$1, '\\', &$0->val.str, $0->val.tail);
730 ###### print exec cases
733 struct val *v = cast(val, e);
734 if (v->val.vtype == Vstr)
737 if (v->val.vtype == Vstr)
742 ###### propagate exec cases
745 struct val *val = cast(val, prog);
746 if (type != Vunknown &&
747 type != val->val.vtype)
749 return val->val.vtype;
752 ###### interp exec cases
754 return dup_value(cast(val, e)->val);
757 void free_val(struct val *v)
765 ###### free exec cases
766 case Xval: free_val(cast(val, e)); break;
769 // Move all nodes from 'b' to 'rv', reversing the order.
770 // In 'b' 'left' is a list, and 'right' is the last node.
771 // In 'rv', left' is the first node and 'right' is a list.
772 struct binode *reorder_bilist(struct binode *b)
774 struct binode *rv = NULL;
777 struct exec *t = b->right;
781 b = cast(binode, b->left);
791 Just as we used as `val` to wrap a value into an `exec`, we similarly
792 need a `var` to wrap a `variable` into an exec. While each `val`
793 contained a copy of the value, each `var` hold a link to the variable
794 because it really is the same variable no matter where it appears.
802 struct variable *var;
807 Variable -> IDENTIFIER ${
809 $0->var = find_variable(config, $1.txt);
812 ###### print exec cases
815 struct var *v = cast(var, e);
816 printf("%.*s", v->var->name.len, v->var->name.txt);
820 ###### propagate exec cases
824 struct var *var = cast(var, prog);
825 if (var->var->val.vtype == Vunknown) {
826 if (type != Vunknown && *ok != 0) {
827 val_init(&var->var->val, type);
832 if (type == Vunknown)
833 return var->var->val.vtype;
834 if (type != var->var->val.vtype)
839 ###### interp exec cases
841 return dup_value(cast(var, e)->var->val);
845 void free_var(struct var *v)
850 ###### free exec cases
851 case Xvar: free_var(cast(var, e)); break;
853 ### Expressions: Boolean
855 Our first user of the `binode` will be expressions, and particularly
856 Boolean expressions. As I haven't implemented precedence in the
857 parser generator yet, we need different names from each precedence
858 level used by expressions. The outer most or lowest level precedence
859 are Boolean `or` `and`, and `not` which form and `Expression` our of `BTerm`s
870 Expression -> Expression or BTerm ${
876 | BTerm ${ $0 = $<1; }$
878 BTerm -> BTerm and BFact ${
884 | BFact ${ $0 = $<1; }$
886 BFact -> not BFact ${
893 ###### print binode cases
895 print_exec(b->left, -1, 0);
897 print_exec(b->right, -1, 0);
900 print_exec(b->left, -1, 0);
902 print_exec(b->right, -1, 0);
906 print_exec(b->right, -1, 0);
909 ###### propagate binode cases
913 /* both must be Vbool, result is Vbool */
914 propagate_types(b->left, Vbool, ok);
915 propagate_types(b->right, Vbool, ok);
916 if (type != Vbool && type != Vunknown)
920 ###### interp binode cases
922 rv = interp_exec(b->left);
923 right = interp_exec(b->right);
924 rv.bool = rv.bool && right.bool;
927 rv = interp_exec(b->left);
928 right = interp_exec(b->right);
929 rv.bool = rv.bool || right.bool;
932 rv = interp_exec(b->right);
936 ### Expressions: Comparison
938 Of slightly higher precedence that Boolean expressions are
940 A comparison takes arguments of any type, but the two types must be
943 To simplify the parsing we introduce an `eop` which can return an
952 static void free_eop(struct eop *e)
973 | Expr ${ $0 = $<1; }$
978 CMPop -> < ${ $0.op = Less; }$
979 | > ${ $0.op = Gtr; }$
980 | <= ${ $0.op = LessEq; }$
981 | >= ${ $0.op = GtrEq; }$
982 | == ${ $0.op = Eql; }$
983 | != ${ $0.op = NEql; }$
985 ###### print binode cases
993 print_exec(b->left, -1, 0);
995 case Less: printf(" < "); break;
996 case LessEq: printf(" <= "); break;
997 case Gtr: printf(" > "); break;
998 case GtrEq: printf(" >= "); break;
999 case Eql: printf(" == "); break;
1000 case NEql: printf(" != "); break;
1003 print_exec(b->right, -1, 0);
1006 ###### propagate binode cases
1013 /* Both must match, result is Vbool */
1014 t = propagate_types(b->left, Vunknown, ok);
1016 propagate_types(b->right, t, ok);
1018 t = propagate_types(b->right, Vunknown, ok);
1020 t = propagate_types(b->left, t, ok);
1022 if (type != Vbool && type != Vunknown)
1026 ###### interp binode cases
1035 left = interp_exec(b->left);
1036 right = interp_exec(b->right);
1037 cmp = value_cmp(left, right);
1040 case Less: rv.bool = cmp < 0; break;
1041 case LessEq: rv.bool = cmp <= 0; break;
1042 case Gtr: rv.bool = cmp > 0; break;
1043 case GtrEq: rv.bool = cmp >= 0; break;
1044 case Eql: rv.bool = cmp == 0; break;
1045 case NEql: rv.bool = cmp != 0; break;
1046 default: rv.bool = 0; break;
1051 ### Expressions: The rest
1053 The remaining expressions with the highest precedence are arithmetic
1054 and string concatenation. There are `Expr`, `Term`, and `Factor`.
1055 The `Factor` is where the `Value` and `Variable` that we already have
1058 `+` and `-` are both infix and prefix operations (where they are
1059 absolute value and negation). These have different operator names.
1061 We also have a 'Bracket' operator which records where parentheses were
1062 found. This make it easy to reproduce these when printing. Once
1063 precedence is handled better I might be able to discard this.
1075 Expr -> Expr Eop Term ${
1081 | Term ${ $0 = $<1; }$
1083 Term -> Term Top Factor ${
1089 | Factor ${ $0 = $<1; }$
1091 Factor -> ( Expression ) ${
1101 | Value ${ $0 = (struct binode *)$<1; }$
1102 | Variable ${ $0 = (struct binode *)$<1; }$
1105 Eop -> + ${ $0.op = Plus; }$
1106 | - ${ $0.op = Minus; }$
1108 Uop -> + ${ $0.op = Absolute; }$
1109 | - ${ $0.op = Negate; }$
1111 Top -> * ${ $0.op = Times; }$
1112 | / ${ $0.op = Divide; }$
1113 | ++ ${ $0.op = Concat; }$
1115 ###### print binode cases
1121 print_exec(b->left, indent, 0);
1123 case Plus: printf(" + "); break;
1124 case Minus: printf(" - "); break;
1125 case Times: printf(" * "); break;
1126 case Divide: printf(" / "); break;
1127 case Concat: printf(" ++ "); break;
1130 print_exec(b->right, indent, 0);
1134 print_exec(b->right, indent, 0);
1138 print_exec(b->right, indent, 0);
1142 print_exec(b->right, indent, 0);
1146 ###### propagate binode cases
1151 /* both must be numbers, result is Vnum */
1154 /* as propagate_types ignores a NULL,
1155 * unary ops fit here too */
1156 propagate_types(b->left, Vnum, ok);
1157 propagate_types(b->right, Vnum, ok);
1158 if (type != Vnum && type != Vunknown)
1163 /* both must be Vstr, result is Vstr */
1164 propagate_types(b->left, Vstr, ok);
1165 propagate_types(b->right, Vstr, ok);
1166 if (type != Vstr && type != Vunknown)
1171 return propagate_types(b->right, type, ok);
1173 ###### interp binode cases
1176 rv = interp_exec(b->left);
1177 right = interp_exec(b->right);
1178 mpq_add(rv.num, rv.num, right.num);
1181 rv = interp_exec(b->left);
1182 right = interp_exec(b->right);
1183 mpq_sub(rv.num, rv.num, right.num);
1186 rv = interp_exec(b->left);
1187 right = interp_exec(b->right);
1188 mpq_mul(rv.num, rv.num, right.num);
1191 rv = interp_exec(b->left);
1192 right = interp_exec(b->right);
1193 mpq_div(rv.num, rv.num, right.num);
1196 rv = interp_exec(b->right);
1197 mpq_neg(rv.num, rv.num);
1200 rv = interp_exec(b->right);
1201 mpq_abs(rv.num, rv.num);
1204 rv = interp_exec(b->right);
1207 left = interp_exec(b->left);
1208 right = interp_exec(b->right);
1210 rv.str = text_join(left.str, right.str);
1213 ### Blocks, Statements, and Statement lists.
1215 Now that we have expressions out of the way we need to turn to
1216 statements. There are simple statements and more complex statements.
1217 Simple statements do not contain newlines, complex statements do.
1219 Statements often come in sequences and we have corresponding simple
1220 statement lists and complex statement lists.
1221 The former comprise only simple statements separated by semicolons.
1222 The later comprise complex statements and simple statement lists. They are
1223 separated by newlines. Thus the semicolon is only used to separate
1224 simple statements on the one line. This may be overly restrictive,
1225 but I'm not sure I every want a complex statement to share a line with
1228 Note that a simple statement list can still use multiple lines if
1229 subsequent lines are indented, so
1231 ###### Example: wrapped simple statement list
1236 is a single simple statement list. This might allow room for
1237 confusion, so I'm not set on it yet.
1239 A simple statement list needs no extra syntax. A complex statement
1240 list has two syntactic forms. It can be enclosed in braces (much like
1241 C blocks), or it can be introduced by a colon and continue until an
1242 unindented newline (much like Python blocks). With this extra syntax
1243 it is referred to as a block.
1245 Note that a block does not have to include any newlines if it only
1246 contains simple statements. So both of:
1248 if condition: a=b; d=f
1250 if condition { a=b; print f }
1254 In either case the list is constructed from a `binode` list with
1255 `Block` as the operator. When parsing the list it is most convenient
1256 to append to the end, so a list is a list and a statement. When using
1257 the list it is more convenient to consider a list to be a statement
1258 and a list. So we need a function to re-order a list.
1259 `reorder_bilist` serves this purpose.
1261 The only stand-alone statement we introduce at this stage is `pass`
1262 which does nothing and is represented as a `NULL` pointer in a `Block`
1282 Block -> Open Statementlist Close ${ $0 = $<2; }$
1283 | Open SimpleStatements } ${ $0 = reorder_bilist($<2); }$
1284 | : Statementlist ${ $0 = $<2; }$
1285 | : SimpleStatements ${ $0 = reorder_bilist($<2); }$
1287 Statementlist -> ComplexStatements ${ $0 = reorder_bilist($<1); }$
1289 ComplexStatements -> ComplexStatements ComplexStatement ${
1295 | ComplexStatements NEWLINE ${ $0 = $<1; }$
1296 | ComplexStatement ${
1304 ComplexStatement -> SimpleStatements NEWLINE ${
1305 $0 = reorder_bilist($<1);
1307 ## ComplexStatement Grammar
1310 SimpleStatements -> SimpleStatements ; SimpleStatement ${
1316 | SimpleStatement ${
1322 | SimpleStatements ; ${ $0 = $<1; }$
1324 SimpleStatement -> pass ${ $0 = NULL; }$
1325 ## SimpleStatement Grammar
1327 ###### print binode cases
1331 if (b->left == NULL)
1334 print_exec(b->left, indent, 0);
1337 print_exec(b->right, indent, 0);
1340 // block, one per line
1341 if (b->left == NULL)
1342 do_indent(indent, "pass\n");
1344 print_exec(b->left, indent, bracket);
1346 print_exec(b->right, indent, bracket);
1350 ###### propagate binode cases
1353 /* If any statement returns something other then Vnone
1354 * then all such must return same type.
1355 * As each statement may be Vnone or something else,
1356 * we must always pass Vunknown down, otherwise an incorrect
1357 * error might occur.
1361 for (e = b; e; e = cast(binode, e->right)) {
1362 t = propagate_types(e->left, Vunknown, ok);
1363 if (t != Vunknown && t != Vnone) {
1364 if (type == Vunknown)
1373 ###### interp binode cases
1375 while (rv.vtype == Vnone &&
1378 rv = interp_exec(b->left);
1379 b = cast(binode, b->right);
1383 ### The Print statement
1385 `print` is a simple statement that takes a comma-separated list of
1386 expressions and prints the values separated by spaces and terminated
1387 by a newline. No control of formatting is possible.
1389 `print` faces the same list-ordering issue as blocks, and uses the
1395 ###### SimpleStatement Grammar
1397 | print ExpressionList ${
1398 $0 = reorder_bilist($<2);
1400 | print ExpressionList , ${
1405 $0 = reorder_bilist($0);
1416 ExpressionList -> ExpressionList , Expression ${
1429 ###### print binode cases
1432 do_indent(indent, "print");
1436 print_exec(b->left, -1, 0);
1440 b = cast(binode, b->right);
1446 ###### propagate binode cases
1449 /* don't care but all must be consistent */
1450 propagate_types(b->left, Vunknown, ok);
1451 propagate_types(b->right, Vunknown, ok);
1454 ###### interp binode cases
1460 for ( ; b; b = cast(binode, b->right))
1464 left = interp_exec(b->left);
1477 ###### Assignment statement
1479 An assignment will assign a value to a variable. The analysis phase
1480 ensures that the type will be correct so the interpreted just needs to
1481 perform the calculation.
1486 ###### SimpleStatement Grammar
1487 | Variable = Expression ${
1494 ###### print binode cases
1497 do_indent(indent, "");
1498 print_exec(b->left, indent, 0);
1500 print_exec(b->right, indent, 0);
1505 ###### propagate binode cases
1508 /* Both must match, result is Vnone */
1509 t = propagate_types(b->left, Vunknown, ok);
1511 propagate_types(b->right, t, ok);
1513 t = propagate_types(b->right, Vunknown, ok);
1515 t = propagate_types(b->left, t, ok);
1519 ###### interp binode cases
1523 struct variable *v = cast(var, b->left)->var;
1524 right = interp_exec(b->right);
1527 right.vtype = Vunknown;
1531 ### The `use` statement
1533 The `use` statement is the last "simple" statement. It is needed when
1534 the condition in a conditional statement is a block. `use` works much
1535 like `return` in C, but only completes the `condition`, not the whole
1541 ###### SimpleStatement Grammar
1548 ###### print binode cases
1551 do_indent(indent, "use ");
1552 print_exec(b->right, -1, 0);
1557 ###### propagate binode cases
1560 /* result matches value */
1561 return propagate_types(b->right, type, ok);
1563 ###### interp binode cases
1566 rv = interp_exec(b->right);
1569 ### The Conditional Statement
1571 This is the biggy and currently the only complex statement.
1572 This subsumes `if`, `while`, `do/while`, `switch`, and some part of
1573 `for`. It is comprised of a number of parts, all of which are
1574 optional though set combinations apply.
1576 If there is a `forpart`, it is executed first, only once.
1577 If there is a `dopart`, then it is executed repeatedly providing
1578 always that the `condpart` or `cond`, if present, does not return a non-True
1579 value. `condpart` can fail to return any value if it simply executes
1580 to completion. This is treated the same as returning True.
1582 If there is a `thenpart` it will be executed whenever the `condpart`
1583 or `cond` returns True (or does not return), but this will happen
1584 *after* `dopart` (when present).
1586 If `elsepart` is present it will be executed at most once when the
1587 condition returns False. If there are any `casepart`s, they will be
1588 executed when the condition returns a matching value.
1590 The particular sorts of values allowed in case parts has not yet been
1591 determined in the language design.
1593 The cond_statement cannot fit into a `binode` so a new `exec` is
1602 struct exec *action;
1603 struct casepart *next;
1605 struct cond_statement {
1607 struct exec *forpart, *condpart, *dopart, *thenpart, *elsepart;
1608 struct casepart *casepart;
1611 ###### ast functions
1613 static void free_casepart(struct casepart *cp)
1617 free_exec(cp->value);
1618 free_exec(cp->action);
1625 void free_cond_statement(struct cond_statement *s)
1629 free_exec(s->forpart);
1630 free_exec(s->condpart);
1631 free_exec(s->dopart);
1632 free_exec(s->thenpart);
1633 free_exec(s->elsepart);
1634 free_casepart(s->casepart);
1638 ###### free exec cases
1639 case Xcond_statement: free_cond_statement(cast(cond_statement, e)); break;
1641 ###### ComplexStatement Grammar
1642 | CondStatement ${ $0 = $<1; }$
1647 CondStatement -> ForThen WhilePart CondSuffix ${
1649 $0->forpart = $1.forpart; $1.forpart = NULL;
1650 $0->thenpart = $1.thenpart; $1.thenpart = NULL;
1651 $0->condpart = $2.condpart; $2.condpart = NULL;
1652 $0->dopart = $2.dopart; $2.dopart = NULL;
1654 | WhilePart CondSuffix ${
1656 $0->condpart = $1.condpart; $1.condpart = NULL;
1657 $0->dopart = $1.dopart; $1.dopart = NULL;
1659 | SwitchPart CondSuffix ${
1663 | IfPart IfSuffix ${
1665 $0->condpart = $1.condpart; $1.condpart = NULL;
1666 $0->thenpart = $1.thenpart; $1.thenpart = NULL;
1669 CondSuffix -> IfSuffix ${ $0 = $<1; }$
1670 | Newlines case Expression Block CondSuffix ${ {
1671 struct casepart *cp = calloc(1, sizeof(*cp));
1675 cp->next = $0->casepart;
1678 | case Expression Block CondSuffix ${ {
1679 struct casepart *cp = calloc(1, sizeof(*cp));
1683 cp->next = $0->casepart;
1687 IfSuffix -> Newlines ${ $0 = new(cond_statement); }$
1688 | Newlines else Block ${
1689 $0 = new(cond_statement);
1693 $0 = new(cond_statement);
1696 | Newlines else CondStatement ${
1697 $0 = new(cond_statement);
1700 | else CondStatement ${
1701 $0 = new(cond_statement);
1707 ForPart -> for SimpleStatements ${
1708 $0 = reorder_bilist($<2);
1714 ThenPart -> then SimpleStatements ${
1715 $0 = reorder_bilist($<2);
1721 ThenPartNL -> ThenPart OptNL ${
1725 WhileHead -> while Block ${
1730 ForThen -> ForPart OptNL ThenPartNL ${
1738 WhilePart -> while Expression Block ${
1739 $0.type = Xcond_statement;
1743 | WhileHead OptNL do Block ${
1744 $0.type = Xcond_statement;
1749 IfPart -> if Expression Block ${
1750 $0.type = Xcond_statement;
1754 | if Block OptNL then Block ${
1755 $0.type = Xcond_statement;
1761 SwitchPart -> switch Expression ${
1768 ###### print exec cases
1770 case Xcond_statement:
1772 struct cond_statement *cs = cast(cond_statement, e);
1773 struct casepart *cp;
1775 do_indent(indent, "for");
1776 if (bracket) printf(" {\n"); else printf(":\n");
1777 print_exec(cs->forpart, indent+1, bracket);
1780 do_indent(indent, "} then {\n");
1782 do_indent(indent, "then:\n");
1783 print_exec(cs->thenpart, indent+1, bracket);
1785 if (bracket) do_indent(indent, "}\n");
1789 if (cs->condpart && cs->condpart->type == Xbinode &&
1790 cast(binode, cs->condpart)->op == Block) {
1792 do_indent(indent, "while {\n");
1794 do_indent(indent, "while:\n");
1795 print_exec(cs->condpart, indent+1, bracket);
1797 do_indent(indent, "} do {\n");
1799 do_indent(indent, "do:\n");
1800 print_exec(cs->dopart, indent+1, bracket);
1802 do_indent(indent, "}\n");
1804 do_indent(indent, "while ");
1805 print_exec(cs->condpart, 0, bracket);
1810 print_exec(cs->dopart, indent+1, bracket);
1812 do_indent(indent, "}\n");
1817 do_indent(indent, "switch");
1819 do_indent(indent, "if");
1820 if (cs->condpart && cs->condpart->type == Xbinode &&
1821 cast(binode, cs->condpart)->op == Block) {
1823 print_exec(cs->condpart, indent+1, bracket);
1825 do_indent(indent, "then:\n");
1826 print_exec(cs->thenpart, indent+1, bracket);
1830 print_exec(cs->condpart, 0, bracket);
1833 print_exec(cs->thenpart, indent+1, bracket);
1838 for (cp = cs->casepart; cp; cp = cp->next) {
1839 do_indent(indent, "case ");
1840 print_exec(cp->value, -1, 0);
1842 print_exec(cp->action, indent+1, bracket);
1845 do_indent(indent, "else:\n");
1846 print_exec(cs->elsepart, indent+1, bracket);
1851 ###### propagate exec cases
1852 case Xcond_statement:
1854 // forpart and dopart must return Vnone
1855 // condpart must be bool or match casepart->values
1856 // thenpart, elsepart, casepart->action must match
1858 struct cond_statement *cs = cast(cond_statement, prog);
1861 t = propagate_types(cs->forpart, Vnone, ok);
1862 if (t != Vunknown && t != Vnone)
1864 t = propagate_types(cs->dopart, Vnone, ok);
1865 if (t != Vunknown && t != Vnone)
1867 if (cs->casepart == NULL)
1868 propagate_types(cs->condpart, Vbool, ok);
1871 for (c = cs->casepart;
1872 c && (t == Vunknown); c = c->next)
1873 t = propagate_types(c->value, Vunknown, ok);
1874 if (t == Vunknown && cs->condpart)
1875 t = propagate_types(cs->condpart, Vunknown, ok);
1876 // Now we have a type (I hope) push it down
1877 if (t != Vunknown) {
1878 for (c = cs->casepart; c; c = c->next)
1879 propagate_types(c->value, t, ok);
1880 propagate_types(cs->condpart, t, ok);
1883 if (type == Vunknown || type == Vnone)
1884 type = propagate_types(cs->thenpart, Vunknown, ok);
1885 if (type == Vunknown || type == Vnone)
1886 type = propagate_types(cs->elsepart, Vunknown, ok);
1887 for (c = cs->casepart;
1888 c && (type == Vunknown || type == Vnone);
1890 type = propagate_types(c->action, Vunknown, ok);
1891 if (type != Vunknown && type != Vnone) {
1892 propagate_types(cs->thenpart, type, ok);
1893 propagate_types(cs->elsepart, type, ok);
1894 for (c = cs->casepart; c ; c = c->next)
1895 propagate_types(c->action, type, ok);
1901 ###### interp exec cases
1902 case Xcond_statement:
1904 struct value v, cnd;
1905 struct casepart *cp;
1906 struct cond_statement *c = cast(cond_statement, e);
1908 interp_exec(c->forpart);
1911 cnd = interp_exec(c->condpart);
1914 if (!(cnd.vtype == Vnone ||
1915 (cnd.vtype == Vbool && cnd.bool != 0)))
1919 interp_exec(c->dopart);
1922 v = interp_exec(c->thenpart);
1923 if (v.vtype != Vnone || !c->dopart)
1927 } while (c->dopart);
1929 for (cp = c->casepart; cp; cp = cp->next) {
1930 v = interp_exec(cp->value);
1931 if (value_cmp(v, cnd) == 0) {
1934 return interp_exec(cp->action);
1940 return interp_exec(c->elsepart);
1945 ### Finally the whole program.
1947 Somewhat reminiscent of Pascal a (current) Ocean program starts with
1948 the keyword "program" and list of variable names which are assigned
1949 values from command line arguments. Following this is a `block` which
1950 is the code to execute.
1952 As this is the top level, several things are handled a bit
1954 The whole program is not interpreted by `interp_exec` as that isn't
1955 passed the argument list which the program requires. Similarly type
1956 analysis is a bit more interesting at this level.
1961 ###### Parser: grammar
1964 Program -> program Varlist Block OptNL ${
1967 $0->left = reorder_bilist($<2);
1971 Varlist -> Varlist Variable ${
1980 ###### print binode cases
1982 do_indent(indent, "program");
1983 for (b2 = cast(binode, b->left); b2; b2 = cast(binode, b2->right)) {
1985 print_exec(b2->left, 0, 0);
1991 print_exec(b->right, indent+1, bracket);
1993 do_indent(indent, "}\n");
1996 ###### propagate binode cases
1997 case Program: abort();
1999 ###### core functions
2001 static int analyse_prog(struct exec *prog, struct parse_context *c)
2003 struct binode *b = cast(binode, prog);
2009 propagate_types(b->right, Vnone, &ok);
2014 for (b = cast(binode, b->left); b; b = cast(binode, b->right)) {
2015 struct var *v = cast(var, b->left);
2016 if (v->var->val.vtype == Vunknown)
2017 val_init(&v->var->val, Vstr);
2019 b = cast(binode, prog);
2022 propagate_types(b->right, Vnone, &ok);
2027 for (v = c->varlist; v; v = v->next)
2028 if (v->val.vtype == Vunknown) {
2029 v->val.vtype = Vnum;
2030 mpq_init(v->val.num);
2031 mpq_set_ui(v->val.num, uniq, 1);
2034 /* Make sure everything is still consistent */
2035 propagate_types(b->right, Vnone, &ok);
2039 static void interp_prog(struct exec *prog, char **argv)
2041 struct binode *p = cast(binode, prog);
2042 struct binode *al = cast(binode, p->left);
2046 struct var *v = cast(var, al->left);
2047 struct value *vl = &v->var->val;
2049 if (argv[0] == NULL) {
2050 printf("Not enough args\n");
2053 al = cast(binode, al->right);
2055 if (!parse_value(vl, argv[0]))
2059 v = interp_exec(p->right);
2063 ###### interp binode cases
2064 case Program: abort();