~brenns10/funlisp

40fdf0c4c048a860866ce95e8bea0c3edde6a0f0 — Stephen Brennan 2 years ago 0a963d7
Implement user contexts for the lisp_runtime
5 files changed, 42 insertions(+), 0 deletions(-)

M doc/embedding.rst
M inc/funlisp.h
M src/funlisp_internal.h
M src/gc.c
M src/public_util.c
M doc/embedding.rst => doc/embedding.rst +9 -0
@@ 265,6 265,15 @@ This program produces exactly the output you'd expect:
  (double_or_square 11) = 22
  (double_or_square 13) = 26

User Contexts
-------------

Usually, an application will want to have access to some of its own data. To
that end, the embedding application may associate a "user context" with the
:c:type:`lisp_runtime` using :c:func:`lisp_runtime_set_ctx()`. This context may
be some global state, etc. Later (e.g. within a builtin function), the context
may be retrieved with :c:func:`lisp_runtime_get_ctx()`.

Advanced Topics
---------------


M inc/funlisp.h => inc/funlisp.h +21 -0
@@ 19,6 19,13 @@
 * created, and is used for garbage collection as well as holding any other
 * information about your instance of the interpreter. The context can be
 * created with lisp_runtime_new() and destroyed with lisp_runtime_free().
 * The context is passed to nearly every function in the library, and builtin
 * functions receive it as well.
 *
 * The context may contain a "user context" (simply a void pointer) that an
 * embedding application may want its builtin functions to have access to.
 * Context is added with lisp_runtime_set_ctx() and retrieved with
 * lisp_runtime_get_ctx().
 */
typedef struct lisp_runtime lisp_runtime;



@@ 30,6 37,20 @@ typedef struct lisp_runtime lisp_runtime;
lisp_runtime *lisp_runtime_new(void);

/**
 * Set the user context of a ::lisp_runtime.
 * @param rt runtime
 * @param user user context to set
 */
void lisp_runtime_set_ctx(lisp_runtime *rt, void *user);

/**
 * Get the user context from a ::lisp_runtime.
 * @param rt runtime
 * @return the user context object
 */
void *lisp_runtime_get_ctx(lisp_runtime *rt);

/**
 * Clean up all resources and free a runtime object.
 * @warning This will invoke the garbage collector, freeing every language
 * object associated with the runtime. Once calling this, ALL pointers to

M src/funlisp_internal.h => src/funlisp_internal.h +1 -0
@@ 37,6 37,7 @@ struct lisp_value {
struct lisp_runtime {
	lisp_value *head;
	lisp_value *tail;
	void *user;

	/* Some special values we don't want to lose track of */
	lisp_value *nil;

M src/gc.c => src/gc.c +1 -0
@@ 15,6 15,7 @@ void lisp_init(lisp_runtime *rt)
	rt->nil->next = NULL;
	rt->head = rt->nil;
	rt->tail = rt->nil;
	rt->user = NULL;
	rb_init(&rt->rb, sizeof(lisp_value*), 16);
}


M src/public_util.c => src/public_util.c +10 -0
@@ 19,6 19,16 @@ lisp_runtime *lisp_runtime_new(void)
	return rt;
}

void lisp_runtime_set_ctx(lisp_runtime *rt, void *user)
{
	rt->user = user;
}

void *lisp_runtime_get_ctx(lisp_runtime *rt)
{
	return rt->user;
}

void lisp_runtime_free(lisp_runtime *rt)
{
	lisp_destroy(rt);