commit 774465336717a6dd001a5fcab4fbea9f56225575
parent 3ffd4c857dc602a97b159a4ca0e8127d33248886
Author: prenev <an2qzavok@gmail.com>
Date: Sat, 30 Jul 2022 13:36:51 +0300
fix error in celldup, add simple stack to repl
Diffstat:
M | Makefile | | | 2 | +- |
M | cell.c | | | 2 | +- |
M | repl.c | | | 60 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- |
3 files changed, 60 insertions(+), 4 deletions(-)
diff --git a/Makefile b/Makefile
@@ -24,7 +24,7 @@ main: ${OBJS} main.o
cc -o $@ ${OBJS} main.o
repl: ${OBJS} repl.o
- cc -o repl repl.o util.o
+ cc -o $@ ${OBJS} repl.o
.c.o:
cc -o $@ -c $<
diff --git a/cell.c b/cell.c
@@ -19,7 +19,7 @@ celldup(Cell *cell)
dup->n = cell->n;
dup->p = malloc(cell->n);
memcpy(dup->p, cell->p, cell->n);
- return cell;
+ return dup;
}
void
diff --git a/repl.c b/repl.c
@@ -3,15 +3,23 @@
#include <unistd.h>
#include <string.h>
+#include "cell.h"
#include "util.h"
-char buf[1024];
-int n;
+#define StackSize 256
+struct {
+ Cell mem[StackSize];
+ unsigned int n;
+} stack;
+
+void push(Cell *);
+Cell * pop(void);
#define CMD(x) void x(void)
CMD(str);
CMD(hex);
CMD(stk);
+CMD(drp);
CMD(hlp);
struct {
@@ -21,12 +29,15 @@ struct {
{"str", str},
{"hex", hex},
{"stk", stk},
+ {"drp", drp},
{"hlp", hlp},
};
void
repl(void)
{
+ long n;
+ char buf[1024];
int i;
printf("> ");
fflush(stdout);
@@ -53,18 +64,28 @@ main(void)
void
str(void)
{
+ long n;
+ char buf[1024];
printf("` ");
fflush(stdout);
n = read(0, buf, 1024);
+ buf[n-1] = '\0';
+ Cell *c = createcell(n, NULL);
+ c->p = malloc(n);
+ memcpy(c->p, buf, n);
+ push(c);
}
void
hex(void)
{
+ long n;
+ char buf[1024];
long long x;
printf("0x");
fflush(stdout);
n = read(0, buf, 1024);
+ buf[n-1] = '\0';
x = strtoll(buf, 0, 16);
}
@@ -81,5 +102,40 @@ hlp(void)
void
stk(void)
{
+ unsigned int n;
+ n = stack.n - 1;
+ if (n >= StackSize) n = StackSize - 1;
+ Cell *c = &stack.mem[n];
+ printf("[%02d] ", n);
+ hexdump(c->n, c->p);
+ printf("\n");
+}
+
+void
+drp(void)
+{
+ Cell *c = pop();
+ freecell(c);
+}
+
+void
+push(Cell *new)
+{
+ stack.mem[stack.n] = *new;
+ free(new);
+ stack.n++;
+ if (stack.n >= StackSize) stack.n = 0;
+}
+
+Cell *
+pop(void)
+{
+ stack.n--;
+ if (stack.n >= StackSize) stack.n = StackSize - 1;
+ Cell *c = celldup(&stack.mem[stack.n]);
+ free(stack.mem[stack.n].p);
+ stack.mem[stack.n].p = NULL;
+ stack.mem[stack.n].n = 0;
+ return c;
}