New type instances creation

Creation of a new instance of the extended type necessitates the definition of a constructor function. This constructor obeys always the same framework. First you have to create a new cell with the NEWCELL macro. This macro has two parameters, a SCM object which will point the new cell and the type of the cell to create. The second argument is generally equal to the value returned by STk_add_new_type. Once the cell is created, we have generally to (dynamically) allocate a C structure which contains the informations which are necessary to implement the new type. Dynamic allocation can be done with the function STk_must_malloc. The area returned by STk_must_malloc must be stored in the data field of the new cell. This field can be accessed with the EXTDATA macro.

Let's go back to the stack example. We can now define a new primitive function to make a new stack. Provided that the global variable tc_stack already contains the value returned by STk_add_new_type, we can write


\begin{Code}
\begin{listing}[200]{2}
...

\begin{Code}
\begin{listing}[200]{2}
static PRIMITIVE make_stack(void)
{
SCM z;...
...STACK(z)->len = 0;
STACK(z)->values = NIL;
return z;
}
\end{listing}\end{Code}

Here, the Stack structure is used to represent a stack. This structure contains two fields: len and values. Since the latter field is a SCM object, it must be recursively marked when a stack is marked. We can now define the utility function necessary for the GC:
\begin{Code}
\begin{listing}[200]{2}
static void mark_stack(SCM p)
{
STk_gc_mar...
...par
static void free_stack(SCM p)
{
free(EXTDATA(p));
}
\end{listing}\end{Code}

To terminate with this example, we give below the code of the primitive stack_push!. Other primitive are built in the same fashion and will not be described here. A complete listing of the stack implementation is given in appendix.
\begin{Code}
\begin{listing}[200]{2}
static PRIMITIVE stack_push(SCM s, SCM val)...
...values = Cons(val, sp->values);
\par
return UNDEFINED;
}
\end{listing}\end{Code}