Threaded code in C - Forth

grt at twitch.UUCP grt at twitch.UUCP
Tue Jul 15 00:47:08 AEST 1986


> > which are not exactly "threaded".  [...]  An extreme case is to have the
> > whole Forth as a huge 'case' statement in C.  (Yes, I have seen something
> > like that :-) ).
> 
> How else can you implement threading if C is used as the implementation
> language?  (Or is that what the smiley is for?)  In other languages the

You do not need to use a switch.  The threaded code is a list of pointers
to words in the vocabulary.  Each word includes a pointer to a function to
be executed.  The virtual machine fetches those pointers and dereferences
to execute the functions.  The dictionary area ought to be defined as
an array of pointers to dictionary word headers, though I have cheated on the
pointer types and used casts.  The function for executing a definition is

xqdef(pwd)
struct w_list *pwd;	/* location in dictionary where we are called */
{
	struct w_list *func;	/* working d.p. for this function */
	save_pc_on_a_stack;	/* pc is dictionary pointer */
	pc = (long*)wargs(pwd);	/* get to first pointer in definition */
	/* note that pc was called pointer to long (yeah, gross) */
	do	func = (struct w_list*)(*pc++);
	while ((*func->w_func)(func) != END);
	pop_pc_from_stack;
	return(DEF);
}

Here w_list is the dictionary header, pc is the dictionary pointer,
and so func is a pointer to a header.  In the header, w_func is a pointer
to a function.  Note that the function is passed the pointer to the place
in the dictionary where it was called.  This allows access to inline
literal constants, nesting, and so on.  The functions return int values.
This function returns DEF.  The last pointer in the compiled definition points
to a function that returns END, which terminates the loop.  I wrote a different
dialect, but in standard Forth, ':' would cause the word to point to this
function, while ';' would generate the pointer to the function returning END.
All primitives are C functions in the instruction space, while the vocabulary
is headers, pointers, literals, etc in the data space.  I think it is
impossible to do a Forth-like assembler because of the I/D separation; words
must have a pointer to a function rather than being executed directly.
-- 
	George Tomasevich, ihnp4!twitch!grt
	AT&T Bell Laboratories, Holmdel, NJ



More information about the Comp.lang.c mailing list