Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / sys / boot / common / interp_forth.c
1 /*
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * All rights reserved.
4  *
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.
13  *
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.
25  *
26  * $FreeBSD: src/sys/boot/common/interp_forth.c,v 1.15.2.2 2000/12/28 13:12:34 ps Exp $
27  * $DragonFly: src/sys/boot/common/interp_forth.c,v 1.2 2003/06/17 04:28:16 dillon Exp $
28  */
29
30 #include <sys/param.h>          /* to pick up __FreeBSD_version */
31 #include <string.h>
32 #include <stand.h>
33 #include "bootstrap.h"
34 #include "ficl.h"
35
36 extern char bootprog_rev[];
37
38 /* #define BFORTH_DEBUG */
39
40 #ifdef BFORTH_DEBUG
41 # define DEBUG(fmt, args...)    printf("%s: " fmt "\n" , __FUNCTION__ , ## args)
42 #else
43 # define DEBUG(fmt, args...)
44 #endif
45
46 /*
47  * Eventually, all builtin commands throw codes must be defined
48  * elsewhere, possibly bootstrap.h. For now, just this code, used
49  * just in this file, it is getting defined.
50  */
51 #define BF_PARSE 100
52
53 /*
54  * BootForth   Interface to Ficl Forth interpreter.
55  */
56
57 FICL_VM *bf_vm;
58 FICL_WORD *pInterp;
59
60 /*
61  * Shim for taking commands from BF and passing them out to 'standard'
62  * argv/argc command functions.
63  */
64 static void
65 bf_command(FICL_VM *vm)
66 {
67     char                        *name, *line, *tail, *cp;
68     size_t                      len;
69     struct bootblk_command      **cmdp;
70     bootblk_cmd_t               *cmd;
71     int                         nstrings, i;
72     int                         argc, result;
73     char                        **argv;
74
75     /* Get the name of the current word */
76     name = vm->runningWord->name;
77     
78     /* Find our command structure */
79     cmd = NULL;
80     SET_FOREACH(cmdp, Xcommand_set) {
81         if (((*cmdp)->c_name != NULL) && !strcmp(name, (*cmdp)->c_name))
82             cmd = (*cmdp)->c_fn;
83     }
84     if (cmd == NULL)
85         panic("callout for unknown command '%s'", name);
86    
87     /* Check whether we have been compiled or are being interpreted */
88     if (stackPopINT(vm->pStack)) {
89         /*
90          * Get parameters from stack, in the format:
91          * an un ... a2 u2 a1 u1 n --
92          * Where n is the number of strings, a/u are pairs of
93          * address/size for strings, and they will be concatenated
94          * in LIFO order.
95          */
96         nstrings = stackPopINT(vm->pStack);
97         for (i = 0, len = 0; i < nstrings; i++)
98             len += stackFetch(vm->pStack, i * 2).i + 1;
99         line = malloc(strlen(name) + len + 1);
100         strcpy(line, name);
101
102         if (nstrings)
103             for (i = 0; i < nstrings; i++) {
104                 len = stackPopINT(vm->pStack);
105                 cp = stackPopPtr(vm->pStack);
106                 strcat(line, " ");
107                 strncat(line, cp, len);
108             }
109     } else {
110         /* Get remainder of invocation */
111         tail = vmGetInBuf(vm);
112         for (cp = tail, len = 0; cp != vm->tib.end && *cp != 0 && *cp != '\n'; cp++, len++)
113             ;
114     
115         line = malloc(strlen(name) + len + 2);
116         strcpy(line, name);
117         if (len > 0) {
118             strcat(line, " ");
119             strncat(line, tail, len);
120             vmUpdateTib(vm, tail + len);
121         }
122     }
123     DEBUG("cmd '%s'", line);
124     
125     command_errmsg = command_errbuf;
126     command_errbuf[0] = 0;
127     if (!parse(&argc, &argv, line)) {
128         result = (cmd)(argc, argv);
129         free(argv);
130     } else {
131         result=BF_PARSE;
132     }
133     free(line);
134     /* This is going to be thrown!!! */
135     stackPushINT(vm->pStack,result);
136 }
137
138 /*
139  * Replace a word definition (a builtin command) with another
140  * one that:
141  *
142  *        - Throw error results instead of returning them on the stack
143  *        - Pass a flag indicating whether the word was compiled or is
144  *          being interpreted.
145  *
146  * There is one major problem with builtins that cannot be overcome
147  * in anyway, except by outlawing it. We want builtins to behave
148  * differently depending on whether they have been compiled or they
149  * are being interpreted. Notice that this is *not* the interpreter's
150  * current state. For example:
151  *
152  * : example ls ; immediate
153  * : problem example ;          \ "ls" gets executed while compiling
154  * example                      \ "ls" gets executed while interpreting
155  *
156  * Notice that, though the current state is different in the two
157  * invocations of "example", in both cases "ls" has been
158  * *compiled in*, which is what we really want.
159  *
160  * The problem arises when you tick the builtin. For example:
161  *
162  * : example-1 ['] ls postpone literal ; immediate
163  * : example-2 example-1 execute ; immediate
164  * : problem example-2 ;
165  * example-2
166  *
167  * We have no way, when we get EXECUTEd, of knowing what our behavior
168  * should be. Thus, our only alternative is to "outlaw" this. See RFI
169  * 0007, and ANS Forth Standard's appendix D, item 6.7 for a related
170  * problem, concerning compile semantics.
171  *
172  * The problem is compounded by the fact that "' builtin CATCH" is valid
173  * and desirable. The only solution is to create an intermediary word.
174  * For example:
175  *
176  * : my-ls ls ;
177  * : example ['] my-ls catch ;
178  *
179  * So, with the below implementation, here is a summary of the behavior
180  * of builtins:
181  *
182  * ls -l                                \ "interpret" behavior, ie,
183  *                                      \ takes parameters from TIB
184  * : ex-1 s" -l" 1 ls ;                 \ "compile" behavior, ie,
185  *                                      \ takes parameters from the stack
186  * : ex-2 ['] ls catch ; immediate      \ undefined behavior
187  * : ex-3 ['] ls catch ;                \ undefined behavior
188  * ex-2 ex-3                            \ "interpret" behavior,
189  *                                      \ catch works
190  * : ex-4 ex-2 ;                        \ "compile" behavior,
191  *                                      \ catch does not work
192  * : ex-5 ex-3 ; immediate              \ same as ex-2
193  * : ex-6 ex-3 ;                        \ same as ex-3
194  * : ex-7 ['] ex-1 catch ;              \ "compile" behavior,
195  *                                      \ catch works
196  * : ex-8 postpone ls ; immediate       \ same as ex-2
197  * : ex-9 postpone ls ;                 \ same as ex-3
198  *
199  * As the definition below is particularly tricky, and it's side effects
200  * must be well understood by those playing with it, I'll be heavy on
201  * the comments.
202  *
203  * (if you edit this definition, pay attention to trailing spaces after
204  *  each word -- I warned you! :-) )
205  */
206 #define BUILTIN_CONSTRUCTOR \
207 ": builtin: "           \
208   ">in @ "              /* save the tib index pointer */ \
209   "' "                  /* get next word's xt */ \
210   "swap >in ! "         /* point again to next word */ \
211   "create "             /* create a new definition of the next word */ \
212   ", "                  /* save previous definition's xt */ \
213   "immediate "          /* make the new definition an immediate word */ \
214                         \
215   "does> "              /* Now, the *new* definition will: */ \
216   "state @ if "         /* if in compiling state: */ \
217     "1 postpone literal "       /* pass 1 flag to indicate compile */ \
218     "@ compile, "               /* compile in previous definition */ \
219     "postpone throw "           /* throw stack-returned result */ \
220   "else "               /* if in interpreting state: */ \
221     "0 swap "                   /* pass 0 flag to indicate interpret */ \
222     "@ execute "                /* call previous definition */ \
223     "throw "                    /* throw stack-returned result */ \
224   "then ; "
225
226 /*
227  * Initialise the Forth interpreter, create all our commands as words.
228  */
229 void
230 bf_init(void)
231 {
232     struct bootblk_command      **cmdp;
233     char create_buf[41];        /* 31 characters-long builtins */
234     int fd;
235    
236     ficlInitSystem(10000);      /* Default dictionary ~4000 cells */
237     bf_vm = ficlNewVM();
238
239     /* Put all private definitions in a "builtins" vocabulary */
240     ficlExec(bf_vm, "vocabulary builtins also builtins definitions");
241
242     /* Builtin constructor word  */
243     ficlExec(bf_vm, BUILTIN_CONSTRUCTOR);
244
245     /* make all commands appear as Forth words */
246     SET_FOREACH(cmdp, Xcommand_set) {
247         ficlBuild((*cmdp)->c_name, bf_command, FW_DEFAULT);
248         ficlExec(bf_vm, "forth definitions builtins");
249         sprintf(create_buf, "builtin: %s", (*cmdp)->c_name);
250         ficlExec(bf_vm, create_buf);
251         ficlExec(bf_vm, "builtins definitions");
252     }
253     ficlExec(bf_vm, "only forth definitions");
254
255     /* Export some version numbers so that code can detect the loader/host version */
256     ficlSetEnv("FreeBSD_version", __FreeBSD_version);
257     ficlSetEnv("loader_version", 
258                (bootprog_rev[0] - '0') * 10 + (bootprog_rev[2] - '0'));
259
260     /* try to load and run init file if present */
261     if ((fd = open("/boot/boot.4th", O_RDONLY)) != -1) {
262         (void)ficlExecFD(bf_vm, fd);
263         close(fd);
264     }
265
266     /* Do this last, so /boot/boot.4th can change it */
267     pInterp = ficlLookup("interpret");
268 }
269
270 /*
271  * Feed a line of user input to the Forth interpreter
272  */
273 int
274 bf_run(char *line)
275 {
276     int         result;
277
278     result = ficlExec(bf_vm, line);
279
280     DEBUG("ficlExec '%s' = %d", line, result);
281     switch (result) {
282     case VM_OUTOFTEXT:
283     case VM_ABORTQ:
284     case VM_QUIT:
285     case VM_ERREXIT:
286         break;
287     case VM_USEREXIT:
288         printf("No where to leave to!\n");
289         break;
290     case VM_ABORT:
291         printf("Aborted!\n");
292         break;
293     case BF_PARSE:
294         printf("Parse error!\n");
295         break;
296     default:
297         /* Hopefully, all other codes filled this buffer */
298         printf("%s\n", command_errmsg);
299     }
300     
301     if (result == VM_USEREXIT)
302         panic("interpreter exit");
303     setenv("interpret", bf_vm->state ? "" : "ok", 1);
304
305     return result;
306 }