diff options
Diffstat (limited to 'sloth.c')
-rw-r--r-- | sloth.c | 78 |
1 files changed, 76 insertions, 2 deletions
@@ -2,6 +2,23 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <xxhash.h> + +SlothError sloth_init(Sloth *ctx) +{ + SlothError err; + err = sloth_dict_append(ctx, SLOTH_DICT_C("+", sloth_add)); + if (err != NULL) { + sloth_deinit(ctx); + return err; + } + err = sloth_dict_append(ctx, SLOTH_DICT_C(".", sloth_write)); + if (err != NULL) { + sloth_deinit(ctx); + return err; + } + return NULL; +} void sloth_deinit(Sloth *ctx) { @@ -9,14 +26,43 @@ void sloth_deinit(Sloth *ctx) free(ctx->stack); ctx->stack = NULL; } + while (ctx->dict != NULL) { + SlothDict *const next = ctx->dict->next; + free(ctx->dict); + ctx->dict = next; + } } -SlothError sloth_exec(Sloth *ctx, const char *s) +SlothError sloth_dict_append(Sloth *ctx, SlothDict dict) { - printf("exec %s\n", s); + SlothDict **dest; + if (ctx->dict == NULL) + dest = &ctx->dict; + else { + SlothDict *last = ctx->dict; + while (last->next != NULL) + last = last->next; + dest = &last->next; + } + *dest = malloc(sizeof(SlothDict)); + if (*dest == NULL) + return "sloth_dict_append: malloc failed"; + memcpy(*dest, &dict, sizeof(SlothDict)); return NULL; } +SlothError sloth_exec(Sloth *ctx, const char *s) +{ + const SlothHash hash = XXH32(s, strlen(s), 0); + for (SlothDict *dict = ctx->dict; dict != NULL; dict = dict->next) + if (dict->hash == hash) { + const SlothError err = dict->func(ctx); + if (err != NULL) + return err; + } + return "sloth_exec: unrecognized token"; +} + SlothError sloth_exec_line(Sloth *ctx, char *s) { static const char *sep = "\t\n\v\f\r "; @@ -56,6 +102,34 @@ SlothError sloth_push(Sloth *ctx, SlothByte v) return NULL; } +SlothError sloth_add(Sloth *ctx) +{ + SlothError err; + SlothByte a, b; + err = sloth_pop(ctx, &a); + if (err != NULL) + return err; + err = sloth_pop(ctx, &b); + if (err != NULL) + return err; + a += b; + err = sloth_push(ctx, a); + if (err != NULL) + return err; + return NULL; +} + +SlothError sloth_write(Sloth *ctx) +{ + SlothError err; + SlothByte a; + err = sloth_pop(ctx, &a); + if (err != NULL) + return err; + printf("%c", (unsigned char)a); + return NULL; +} + void sloth_inspect_stack(const Sloth *ctx) { printf("<%lu> ", ctx->stack_size); |