summaryrefslogtreecommitdiff
path: root/src/fwdscript.c
diff options
context:
space:
mode:
authorKimplul <kimi.h.kuparinen@gmail.com>2026-08-13 20:15:01 +0300
committerKimplul <kimi.h.kuparinen@gmail.com>2026-08-13 20:15:01 +0300
commit6fa4569a644090e04ff4dd1ae536c4d2b776668b (patch)
tree2659133f6b822879d9e11398f03045cea876c393 /src/fwdscript.c
parent4580e74f54e22a81f8b5f40639518247ee37d1c5 (diff)
downloadfwdscript-6fa4569a644090e04ff4dd1ae536c4d2b776668b.tar.gz
fwdscript-6fa4569a644090e04ff4dd1ae536c4d2b776668b.zip
allow reading from file
Diffstat (limited to 'src/fwdscript.c')
-rw-r--r--src/fwdscript.c56
1 files changed, 48 insertions, 8 deletions
diff --git a/src/fwdscript.c b/src/fwdscript.c
index 6b47ca0..7b1de26 100644
--- a/src/fwdscript.c
+++ b/src/fwdscript.c
@@ -1,9 +1,11 @@
#include <err.h>
#include <stdio.h>
#include <ctype.h>
+#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
+#include <sys/mman.h>
#define TODO() errx(EXIT_FAILURE, "%s:%d: todo", __FILE__, __LINE__)
@@ -1521,21 +1523,56 @@ static void fwdscript_destroy(struct fwdscript *s)
fwdbuiltins_destroy(&s->builtins);
}
-int main()
+static const char *read_file(const char *fname)
{
+ FILE *f = fopen(fname, "rb");
+ if (!f)
+ err(EXIT_FAILURE, "failed opening %s", fname);
+
+ if (fseek(f, 0, SEEK_END) < 0)
+ err(EXIT_FAILURE, "failed seeking %s", fname);
+
+ long sz = ftell(f);
+ if (sz < 0)
+ err(EXIT_FAILURE, "failed telling %s", fname);
+
+ if (fseek(f, 0, SEEK_SET) < 0)
+ err(EXIT_FAILURE, "failed rewinding %s", fname);
+
+ char *buf = malloc(sz + 1);
+ if (!buf)
+ err(EXIT_FAILURE, "failed allocating buf for %s", fname);
+
+ if ((long)fread(buf, 1, sz, f) != sz)
+ err(EXIT_FAILURE, "failed reading file %s", fname);
+
+ /* trailing zero */
+ buf[sz] = '\0';
+
+ fclose(f);
+ return buf;
+}
+
+int main(int argc, char *argv[])
+{
+ /* a bit silly but good enough for testing */
+ const char *buf =
+ "main /tbl args {\n"
+ " get args 0 => {abort \"impossible\"}\n"
+ " => /str line;\n"
+ " print line\n"
+ "}\n";
+
+ if (argc == 2)
+ buf = read_file(argv[1]);
+
int ret = 0;
struct fwdscript inst = fwdscript_create();
ret = fwdscript_register_builtins(&inst);
assert(ret == 0);
- ret = fwdscript_parse(&inst,
- "main /tbl args {\n"
- " get args 0 => {abort \"impossible\"}\n"
- " => /str line;\n"
- " print line\n"
- "}\n");
-
+ ret = fwdscript_parse(&inst, buf);
assert(ret == 0);
struct fwdvals args = fwdvals_create(1);
@@ -1546,4 +1583,7 @@ int main()
/* string should've been consumed by main so we shouldn't try to free it */
fwdvals_destroy(&args);
fwdscript_destroy(&inst);
+
+ if (argc == 2)
+ free((void *)buf);
}