xref: /freebsd/stand/common/interp_forth.c (revision 25b86f88e32f50afd03341c6558a288ec45a0d33)
1 /*-
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * Copyright (c) 2011 Wojciech A. Koszek <wkoszek@FreeBSD.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include <sys/param.h>		/* to pick up __FreeBSD_version */
32 #include <string.h>
33 #include <stand.h>
34 #include "bootstrap.h"
35 #include "ficl.h"
36 #include "interp.h"
37 
38 extern unsigned bootprog_rev;
39 
40 /* #define BFORTH_DEBUG */
41 
42 #ifdef BFORTH_DEBUG
43 #define	DEBUG(fmt, args...)	printf("%s: " fmt "\n" , __func__ , ## args)
44 #else
45 #define	DEBUG(fmt, args...)
46 #endif
47 
48 /*
49  * Eventually, all builtin commands throw codes must be defined
50  * elsewhere, possibly bootstrap.h. For now, just this code, used
51  * just in this file, it is getting defined.
52  */
53 #define BF_PARSE 100
54 
55 /*
56  * FreeBSD loader default dictionary cells
57  */
58 #ifndef	BF_DICTSIZE
59 #define	BF_DICTSIZE	10000
60 #endif
61 
62 /*
63  * BootForth   Interface to Ficl Forth interpreter.
64  */
65 struct interp_forth_softc {
66 	FICL_SYSTEM *bf_sys;
67 	FICL_VM	*bf_vm;
68 	FICL_WORD *pInterp;
69 };
70 struct interp_forth_softc	forth_softc = { NULL, NULL, NULL };
71 
72 #define	RETURN(x)	stackPushINT(bf_vm->pStack,!x); return(x)
73 
74 /*
75  * Shim for taking commands from BF and passing them out to 'standard'
76  * argv/argc command functions.
77  */
78 static void
79 bf_command(FICL_VM *vm)
80 {
81 	char			*name, *line, *tail, *cp;
82 	size_t			len;
83 	struct bootblk_command	**cmdp;
84 	bootblk_cmd_t		*cmd;
85 	int			nstrings, i;
86 	int			argc, result;
87 	char			**argv;
88 
89 	/* Get the name of the current word */
90 	name = vm->runningWord->name;
91 
92 	/* Find our command structure */
93 	cmd = NULL;
94 	SET_FOREACH(cmdp, Xcommand_set) {
95 		if (((*cmdp)->c_name != NULL) && !strcmp(name, (*cmdp)->c_name))
96 			cmd = (*cmdp)->c_fn;
97 	}
98 	if (cmd == NULL)
99 		panic("callout for unknown command '%s'", name);
100 
101 	/* Check whether we have been compiled or are being interpreted */
102 	if (stackPopINT(vm->pStack)) {
103 		/*
104 		* Get parameters from stack, in the format:
105 		* an un ... a2 u2 a1 u1 n --
106 		* Where n is the number of strings, a/u are pairs of
107 		* address/size for strings, and they will be concatenated
108 		* in LIFO order.
109 		*/
110 		nstrings = stackPopINT(vm->pStack);
111 		for (i = 0, len = 0; i < nstrings; i++)
112 			len += stackFetch(vm->pStack, i * 2).i + 1;
113 		line = malloc(strlen(name) + len + 1);
114 		strcpy(line, name);
115 
116 		if (nstrings)
117 			for (i = 0; i < nstrings; i++) {
118 				len = stackPopINT(vm->pStack);
119 				cp = stackPopPtr(vm->pStack);
120 				strcat(line, " ");
121 				strncat(line, cp, len);
122 			}
123 	} else {
124 		/* Get remainder of invocation */
125 		tail = vmGetInBuf(vm);
126 		for (cp = tail, len = 0; cp != vm->tib.end && *cp != 0 && *cp != '\n'; cp++, len++)
127 			;
128 
129 		line = malloc(strlen(name) + len + 2);
130 		strcpy(line, name);
131 		if (len > 0) {
132 			strcat(line, " ");
133 			strncat(line, tail, len);
134 			vmUpdateTib(vm, tail + len);
135 		}
136 	}
137 	DEBUG("cmd '%s'", line);
138 
139 	command_errmsg = command_errbuf;
140 	command_errbuf[0] = 0;
141 	if (!parse(&argc, &argv, line)) {
142 		result = (cmd)(argc, argv);
143 		free(argv);
144 	} else {
145 		result=BF_PARSE;
146 	}
147 
148 	/* XXX Not sure about the rest of this -- imp */
149 
150 	switch (result) {
151 	case CMD_CRIT:
152 		printf("%s\n", command_errmsg);
153 		break;
154 	case CMD_FATAL:
155 		panic("%s\n", command_errmsg);
156 	}
157 
158 	free(line);
159 	/*
160 	 * If there was error during nested ficlExec(), we may no longer have
161 	 * valid environment to return.  Throw all exceptions from here.
162 	 */
163 	if (result != CMD_OK)
164 		vmThrow(vm, result);
165 
166 	/* This is going to be thrown!!! */
167 	stackPushINT(vm->pStack,result);
168 }
169 
170 /*
171  * Replace a word definition (a builtin command) with another
172  * one that:
173  *
174  *        - Throw error results instead of returning them on the stack
175  *        - Pass a flag indicating whether the word was compiled or is
176  *          being interpreted.
177  *
178  * There is one major problem with builtins that cannot be overcome
179  * in anyway, except by outlawing it. We want builtins to behave
180  * differently depending on whether they have been compiled or they
181  * are being interpreted. Notice that this is *not* the interpreter's
182  * current state. For example:
183  *
184  * : example ls ; immediate
185  * : problem example ;		\ "ls" gets executed while compiling
186  * example			\ "ls" gets executed while interpreting
187  *
188  * Notice that, though the current state is different in the two
189  * invocations of "example", in both cases "ls" has been
190  * *compiled in*, which is what we really want.
191  *
192  * The problem arises when you tick the builtin. For example:
193  *
194  * : example-1 ['] ls postpone literal ; immediate
195  * : example-2 example-1 execute ; immediate
196  * : problem example-2 ;
197  * example-2
198  *
199  * We have no way, when we get EXECUTEd, of knowing what our behavior
200  * should be. Thus, our only alternative is to "outlaw" this. See RFI
201  * 0007, and ANS Forth Standard's appendix D, item 6.7 for a related
202  * problem, concerning compile semantics.
203  *
204  * The problem is compounded by the fact that "' builtin CATCH" is valid
205  * and desirable. The only solution is to create an intermediary word.
206  * For example:
207  *
208  * : my-ls ls ;
209  * : example ['] my-ls catch ;
210  *
211  * So, with the below implementation, here is a summary of the behavior
212  * of builtins:
213  *
214  * ls -l				\ "interpret" behavior, ie,
215  *					\ takes parameters from TIB
216  * : ex-1 s" -l" 1 ls ;			\ "compile" behavior, ie,
217  *					\ takes parameters from the stack
218  * : ex-2 ['] ls catch ; immediate	\ undefined behavior
219  * : ex-3 ['] ls catch ;		\ undefined behavior
220  * ex-2 ex-3				\ "interpret" behavior,
221  *					\ catch works
222  * : ex-4 ex-2 ;			\ "compile" behavior,
223  *					\ catch does not work
224  * : ex-5 ex-3 ; immediate		\ same as ex-2
225  * : ex-6 ex-3 ;			\ same as ex-3
226  * : ex-7 ['] ex-1 catch ;		\ "compile" behavior,
227  *					\ catch works
228  * : ex-8 postpone ls ;	immediate	\ same as ex-2
229  * : ex-9 postpone ls ;			\ same as ex-3
230  *
231  * As the definition below is particularly tricky, and it's side effects
232  * must be well understood by those playing with it, I'll be heavy on
233  * the comments.
234  *
235  * (if you edit this definition, pay attention to trailing spaces after
236  *  each word -- I warned you! :-) )
237  */
238 #define BUILTIN_CONSTRUCTOR \
239 ": builtin: "		\
240   ">in @ "		/* save the tib index pointer */ \
241   "' "			/* get next word's xt */ \
242   "swap >in ! "		/* point again to next word */ \
243   "create "		/* create a new definition of the next word */ \
244   ", "			/* save previous definition's xt */ \
245   "immediate "		/* make the new definition an immediate word */ \
246 			\
247   "does> "		/* Now, the *new* definition will: */ \
248   "state @ if "		/* if in compiling state: */ \
249     "1 postpone literal "	/* pass 1 flag to indicate compile */ \
250     "@ compile, "		/* compile in previous definition */ \
251     "postpone throw "		/* throw stack-returned result */ \
252   "else "		/* if in interpreting state: */ \
253     "0 swap "			/* pass 0 flag to indicate interpret */ \
254     "@ execute "		/* call previous definition */ \
255     "throw "			/* throw stack-returned result */ \
256   "then ; "
257 
258 /*
259  * Initialise the Forth interpreter, create all our commands as words.
260  */
261 static void
262 interp_forth_init(void *ctx)
263 {
264     struct interp_forth_softc   *softc;
265     struct bootblk_command	**cmdp;
266     char create_buf[41];	/* 31 characters-long builtins */
267     FICL_SYSTEM *bf_sys;
268     FICL_VM	*bf_vm;
269 
270     softc = ctx;
271 
272     assert((softc->bf_sys == NULL) && (softc->bf_vm == NULL) &&
273 	(softc->pInterp == NULL));	/* No Forth context at this stage */
274 
275     bf_sys = softc->bf_sys = ficlInitSystem(BF_DICTSIZE);
276     bf_vm = softc->bf_vm = ficlNewVM(bf_sys);
277 
278     /* Put all private definitions in a "builtins" vocabulary */
279     ficlExec(bf_vm, "vocabulary builtins also builtins definitions");
280 
281     /* Builtin constructor word  */
282     ficlExec(bf_vm, BUILTIN_CONSTRUCTOR);
283 
284     /* make all commands appear as Forth words */
285     SET_FOREACH(cmdp, Xcommand_set) {
286 	ficlBuild(bf_sys, (char *)(*cmdp)->c_name, bf_command, FW_DEFAULT);
287 	ficlExec(bf_vm, "forth definitions builtins");
288 	sprintf(create_buf, "builtin: %s", (*cmdp)->c_name);
289 	ficlExec(bf_vm, create_buf);
290 	ficlExec(bf_vm, "builtins definitions");
291     }
292     ficlExec(bf_vm, "only forth definitions");
293 
294     /* Export some version numbers so that code can detect the loader/host version */
295     ficlSetEnv(bf_sys, "FreeBSD_version", __FreeBSD_version);
296     ficlSetEnv(bf_sys, "loader_version", bootprog_rev);
297 }
298 
299 /*
300  * Feed a line of user input to the Forth interpreter
301  */
302 static int
303 interp_forth_run(void *ctx, const char *line)
304 {
305     struct interp_forth_softc *softc;
306     int		result;
307 
308     softc = ctx;
309 
310     result = ficlExec(softc->bf_vm, (char *)line);
311 
312     DEBUG("ficlExec '%s' = %d", line, result);
313     switch (result) {
314     case VM_OUTOFTEXT:
315     case VM_ABORTQ:
316     case VM_QUIT:
317     case VM_ERREXIT:
318 	break;
319     case VM_USEREXIT:
320 	printf("No where to leave to!\n");
321 	break;
322     case VM_ABORT:
323 	printf("Aborted!\n");
324 	break;
325     case BF_PARSE:
326 	printf("Parse error!\n");
327 	break;
328     default:
329 	if (command_errmsg != NULL) {
330 	    printf("%s\n", command_errmsg);
331 	    command_errmsg = NULL;
332 	}
333     }
334 
335     if (result == VM_USEREXIT)
336 	panic("interpreter exit");
337     setenv("interpret", softc->bf_vm->state ? "" : "OK", 1);
338 
339     return (result);
340 }
341 
342 static int
343 interp_forth_incl(void *ctx, const char *filename)
344 {
345 	struct interp_forth_softc *softc;
346 	int	fd;
347 
348 	softc = ctx;
349 
350 	fd = open(filename, O_RDONLY);
351 	if (fd == -1) {
352 		/* Hihger layers print the error message */
353 		snprintf(command_errbuf, sizeof(command_errbuf),
354 		    "can't open %s\n", filename);
355 		return (CMD_ERROR);
356 	}
357 	return (ficlExecFD(softc->bf_vm, fd));
358 }
359 
360 
361 struct interp boot_interp_forth = {
362 	.init = interp_forth_init,
363 	.run = interp_forth_run,
364 	.incl = interp_forth_incl,
365 	.load_configs = default_load_config,
366 	.context = &forth_softc
367 };
368