blob: 5db7df07e66227c2760b1c88c476268fffcf56ff (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
#include "sloth.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sloth_deinit(Sloth *ctx)
{
if (ctx->stack != NULL) {
free(ctx->stack);
ctx->stack = NULL;
}
}
SlothError sloth_exec(Sloth *ctx, const char *s)
{
printf("exec %s\n", s);
return NULL;
}
SlothError sloth_exec_line(Sloth *ctx, char *s)
{
static const char *sep = "\t\n\v\f\r ";
for (char *tok = strtok(s, sep); tok != NULL; tok = strtok(NULL, sep)) {
const SlothError err = sloth_exec(ctx, tok);
if (err != NULL)
return err;
}
return NULL;
}
SlothError sloth_pop(Sloth *ctx, SlothByte *v)
{
if (ctx->stack_size == 0)
return "sloth_pull: stack is empty";
*v = ctx->stack[ctx->stack_size - 1];
ctx->stack_size -= 1;
return NULL;
}
SlothError sloth_push(Sloth *ctx, SlothByte v)
{
if (ctx->stack == NULL) {
ctx->stack = malloc(sizeof(SlothByte) * 16);
if (ctx->stack == NULL)
return "sloth_push: calloc failed";
ctx->stack_capacity = 16;
} else if (ctx->stack_size == ctx->stack_capacity) {
SlothByte *const new_stack =
realloc(ctx->stack, ctx->stack_capacity * 2);
if (new_stack == NULL)
return "sloth_push: realloc failed";
ctx->stack_capacity *= 2;
}
ctx->stack[ctx->stack_size] = v;
ctx->stack_size += 1;
return NULL;
}
void sloth_inspect_stack(const Sloth *ctx)
{
printf("<%lu> ", ctx->stack_size);
for (size_t i = 0; i < ctx->stack_size; i++)
printf("%d ", ctx->stack[i]);
}
|