Unleashed v1.4
[unleashed.git] / usr / src / boot / sys / boot / common / interp_forth.c
blobb3eebaede4bf843580bca5bd60daabdfb8f806a1
1 /*
2 * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3 * All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
27 #include <sys/cdefs.h>
29 #include <sys/param.h> /* to pick up __FreeBSD_version */
30 #include <string.h>
31 #include <stand.h>
32 #include "bootstrap.h"
33 #include "ficl.h"
35 extern unsigned bootprog_rev;
37 /* #define BFORTH_DEBUG */
39 #ifdef BFORTH_DEBUG
40 # define DEBUG(fmt, args...) printf("%s: " fmt "\n" , __func__ , ## args)
41 #else
42 # define DEBUG(fmt, args...)
43 #endif
46 * Eventually, all builtin commands throw codes must be defined
47 * elsewhere, possibly bootstrap.h. For now, just this code, used
48 * just in this file, it is getting defined.
50 #define BF_PARSE 100
53 * FreeBSD loader default dictionary cells
55 #ifndef BF_DICTSIZE
56 #define BF_DICTSIZE 30000
57 #endif
60 * BootForth Interface to Ficl Forth interpreter.
63 ficlSystemInformation *fsi;
64 ficlSystem *bf_sys;
65 ficlVm *bf_vm;
68 * Shim for taking commands from BF and passing them out to 'standard'
69 * argv/argc command functions.
71 static void
72 bf_command(ficlVm *vm)
74 char *name, *line, *tail, *cp;
75 size_t len;
76 struct bootblk_command **cmdp;
77 bootblk_cmd_t *cmd;
78 int nstrings, i;
79 int argc, result;
80 char **argv;
82 /* Get the name of the current word */
83 name = vm->runningWord->name;
85 /* Find our command structure */
86 cmd = NULL;
87 SET_FOREACH(cmdp, Xcommand_set) {
88 if (((*cmdp)->c_name != NULL) && !strcmp(name, (*cmdp)->c_name))
89 cmd = (*cmdp)->c_fn;
91 if (cmd == NULL)
92 panic("callout for unknown command '%s'", name);
94 /* Check whether we have been compiled or are being interpreted */
95 if (ficlStackPopInteger(ficlVmGetDataStack(vm))) {
97 * Get parameters from stack, in the format:
98 * an un ... a2 u2 a1 u1 n --
99 * Where n is the number of strings, a/u are pairs of
100 * address/size for strings, and they will be concatenated
101 * in LIFO order.
103 nstrings = ficlStackPopInteger(ficlVmGetDataStack(vm));
104 for (i = 0, len = 0; i < nstrings; i++)
105 len += ficlStackFetch(ficlVmGetDataStack(vm), i * 2).i + 1;
106 line = malloc(strlen(name) + len + 1);
107 strcpy(line, name);
109 if (nstrings)
110 for (i = 0; i < nstrings; i++) {
111 len = ficlStackPopInteger(ficlVmGetDataStack(vm));
112 cp = ficlStackPopPointer(ficlVmGetDataStack(vm));
113 strcat(line, " ");
114 strncat(line, cp, len);
116 } else {
117 /* Get remainder of invocation */
118 tail = ficlVmGetInBuf(vm);
120 len = 0;
121 for (cp = tail; cp != vm->tib.end && *cp != 0 && *cp != '\n'; cp++)
122 len++;
124 line = malloc(strlen(name) + len + 2);
125 strcpy(line, name);
126 if (len > 0) {
127 strcat(line, " ");
128 strncat(line, tail, len);
129 ficlVmUpdateTib(vm, tail + len);
132 DEBUG("cmd '%s'", line);
134 command_errmsg = command_errbuf;
135 command_errbuf[0] = 0;
136 if (!parse(&argc, &argv, line)) {
137 result = (cmd)(argc, argv);
138 free(argv);
139 } else {
140 result = BF_PARSE;
143 switch (result) {
144 case CMD_CRIT:
145 printf("%s\n", command_errmsg);
146 command_errmsg = NULL;
147 break;
148 case CMD_FATAL:
149 panic("%s\n", command_errmsg);
152 free(line);
154 * If there was error during nested ficlExec(), we may no longer have
155 * valid environment to return. Throw all exceptions from here.
157 if (result != CMD_OK)
158 ficlVmThrow(vm, result);
160 /* This is going to be thrown!!! */
161 ficlStackPushInteger(ficlVmGetDataStack(vm),result);
165 * Replace a word definition (a builtin command) with another
166 * one that:
168 * - Throw error results instead of returning them on the stack
169 * - Pass a flag indicating whether the word was compiled or is
170 * being interpreted.
172 * There is one major problem with builtins that cannot be overcome
173 * in anyway, except by outlawing it. We want builtins to behave
174 * differently depending on whether they have been compiled or they
175 * are being interpreted. Notice that this is *not* the interpreter's
176 * current state. For example:
178 * : example ls ; immediate
179 * : problem example ; \ "ls" gets executed while compiling
180 * example \ "ls" gets executed while interpreting
182 * Notice that, though the current state is different in the two
183 * invocations of "example", in both cases "ls" has been
184 * *compiled in*, which is what we really want.
186 * The problem arises when you tick the builtin. For example:
188 * : example-1 ['] ls postpone literal ; immediate
189 * : example-2 example-1 execute ; immediate
190 * : problem example-2 ;
191 * example-2
193 * We have no way, when we get EXECUTEd, of knowing what our behavior
194 * should be. Thus, our only alternative is to "outlaw" this. See RFI
195 * 0007, and ANS Forth Standard's appendix D, item 6.7 for a related
196 * problem, concerning compile semantics.
198 * The problem is compounded by the fact that "' builtin CATCH" is valid
199 * and desirable. The only solution is to create an intermediary word.
200 * For example:
202 * : my-ls ls ;
203 * : example ['] my-ls catch ;
205 * So, with the below implementation, here is a summary of the behavior
206 * of builtins:
208 * ls -l \ "interpret" behavior, ie,
209 * \ takes parameters from TIB
210 * : ex-1 s" -l" 1 ls ; \ "compile" behavior, ie,
211 * \ takes parameters from the stack
212 * : ex-2 ['] ls catch ; immediate \ undefined behavior
213 * : ex-3 ['] ls catch ; \ undefined behavior
214 * ex-2 ex-3 \ "interpret" behavior,
215 * \ catch works
216 * : ex-4 ex-2 ; \ "compile" behavior,
217 * \ catch does not work
218 * : ex-5 ex-3 ; immediate \ same as ex-2
219 * : ex-6 ex-3 ; \ same as ex-3
220 * : ex-7 ['] ex-1 catch ; \ "compile" behavior,
221 * \ catch works
222 * : ex-8 postpone ls ; immediate \ same as ex-2
223 * : ex-9 postpone ls ; \ same as ex-3
225 * As the definition below is particularly tricky, and it's side effects
226 * must be well understood by those playing with it, I'll be heavy on
227 * the comments.
229 * (if you edit this definition, pay attention to trailing spaces after
230 * each word -- I warned you! :-) )
232 #define BUILTIN_CONSTRUCTOR \
233 ": builtin: " \
234 ">in @ " /* save the tib index pointer */ \
235 "' " /* get next word's xt */ \
236 "swap >in ! " /* point again to next word */ \
237 "create " /* create a new definition of the next word */ \
238 ", " /* save previous definition's xt */ \
239 "immediate " /* make the new definition an immediate word */ \
241 "does> " /* Now, the *new* definition will: */ \
242 "state @ if " /* if in compiling state: */ \
243 "1 postpone literal " /* pass 1 flag to indicate compile */ \
244 "@ compile, " /* compile in previous definition */ \
245 "postpone throw " /* throw stack-returned result */ \
246 "else " /* if in interpreting state: */ \
247 "0 swap " /* pass 0 flag to indicate interpret */ \
248 "@ execute " /* call previous definition */ \
249 "throw " /* throw stack-returned result */ \
250 "then ; "
253 * Initialise the Forth interpreter, create all our commands as words.
255 void
256 bf_init(char *rc)
258 struct bootblk_command **cmdp;
259 char create_buf[41]; /* 31 characters-long builtins */
260 int fd, rv;
261 ficlDictionary *dict;
262 ficlDictionary *env;
264 fsi = malloc(sizeof(ficlSystemInformation));
265 ficlSystemInformationInitialize(fsi);
266 fsi->dictionarySize = BF_DICTSIZE;
268 bf_sys = ficlSystemCreate(fsi);
269 bf_vm = ficlSystemCreateVm(bf_sys);
271 /* Put all private definitions in a "builtins" vocabulary */
272 rv = ficlVmEvaluate(bf_vm, "vocabulary builtins also builtins definitions");
273 if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
274 panic("error interpreting forth: %d\n", rv);
277 /* Builtin constructor word */
278 rv = ficlVmEvaluate(bf_vm, BUILTIN_CONSTRUCTOR);
279 if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
280 panic("error interpreting forth: %d\n", rv);
283 /* make all commands appear as Forth words */
284 dict = ficlSystemGetDictionary(bf_sys);
285 SET_FOREACH(cmdp, Xcommand_set) {
286 ficlDictionaryAppendPrimitive(dict, (char *)(*cmdp)->c_name,
287 bf_command, FICL_WORD_DEFAULT);
288 rv = ficlVmEvaluate(bf_vm, "forth definitions builtins");
289 if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
290 panic("error interpreting forth: %d\n", rv);
292 sprintf(create_buf, "builtin: %s", (*cmdp)->c_name);
293 rv = ficlVmEvaluate(bf_vm, create_buf);
294 if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
295 panic("error interpreting forth: %d\n", rv);
297 rv = ficlVmEvaluate(bf_vm, "builtins definitions");
298 if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
299 panic("error interpreting forth: %d\n", rv);
302 rv = ficlVmEvaluate(bf_vm, "only forth definitions");
303 if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
304 panic("error interpreting forth: %d\n", rv);
308 * Export some version numbers so that code can detect the loader/host
309 * version
311 env = ficlSystemGetEnvironment(bf_sys);
312 ficlDictionarySetConstant(env, "loader_version", bootprog_rev);
314 /* try to load and run init file if present */
315 if (rc == NULL)
316 rc = "/boot/forth/boot.4th";
317 if (*rc != '\0') {
318 fd = open(rc, O_RDONLY);
319 if (fd != -1) {
320 (void)ficlExecFD(bf_vm, fd);
321 close(fd);
327 * Feed a line of user input to the Forth interpreter
330 bf_run(char *line)
332 int result;
333 ficlString s;
335 FICL_STRING_SET_FROM_CSTRING(s, line);
336 result = ficlVmExecuteString(bf_vm, s);
338 DEBUG("ficlExec '%s' = %d", line, result);
339 switch (result) {
340 case FICL_VM_STATUS_OUT_OF_TEXT:
341 case FICL_VM_STATUS_ABORTQ:
342 case FICL_VM_STATUS_QUIT:
343 case FICL_VM_STATUS_ERROR_EXIT:
344 break;
345 case FICL_VM_STATUS_USER_EXIT:
346 printf("No where to leave to!\n");
347 break;
348 case FICL_VM_STATUS_ABORT:
349 printf("Aborted!\n");
350 break;
351 case BF_PARSE:
352 printf("Parse error!\n");
353 break;
354 default:
355 if (command_errmsg != NULL) {
356 printf("%s\n", command_errmsg);
357 command_errmsg = NULL;
361 /* bye is same as reboot and will behave depending on platform */
362 if (result == FICL_VM_STATUS_USER_EXIT)
363 bf_run("reboot");
364 setenv("interpret", bf_vm->state ? "" : "ok", 1);
366 return (result);