tisp

tiny lisp
git clone git://edryd.org/tisp
Log | Files | Refs | LICENSE

commit 39bfce81a3ad58a63c9db89bdb08e61347737f28
parent 4d6cacaaaa9d7dc645bb9ec2b0c574290feac177
Author: Ed van Bruggen <edvb@uw.edu>
Date:   Thu,  7 Feb 2019 17:08:08 -0800

Add tisp_read_file to return string of given file

Diffstat:
tisp.c | 38++++++++++++++++++++++++++++++++++++++
tisp.h | 2++
2 files changed, 40 insertions(+), 0 deletions(-)

diff --git a/tisp.c b/tisp.c @@ -20,12 +20,14 @@ */ #include <ctype.h> #include <dlfcn.h> +#include <fcntl.h> #include <limits.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <unistd.h> #include "tisp.h" @@ -124,6 +126,18 @@ skip_ws(Str str) str->d += strcspn(str->d, "\n"); } +static int +count_parens(char *s, int len) +{ + int count = 0; + for (int i = 0; i < len && s[i]; i++) + if (s[i] == '(') + count++; + else if (s[i] == ')') + count--; + return count; +} + int list_len(Val v) { @@ -534,6 +548,30 @@ tisp_read(Env env, Str str) tsp_warn("could not read given input"); } +char * +tisp_read_file(char *fname) +{ + char buf[BUFSIZ], *file = NULL; + int len = 0, n, fd, parens = 0; + if (!fname) + fd = 0; + else if ((fd = open(fname, O_RDONLY)) < 0) + tsp_warnf("could not load file '%s'", fname); + while ((n = read(fd, buf, sizeof(buf))) > 0) { + file = erealloc(file, len + n + 1); + memcpy(file + len, buf, n); + len += n; + file[len] = '\0'; + if (fd == 0 && !(parens += count_parens(buf, n))) + break; + } + if (fd) + close(fd); + if (n < 0) + die("read:"); + return file; +} + Val tisp_eval_list(Env env, Val v) { diff --git a/tisp.h b/tisp.h @@ -141,6 +141,8 @@ Val tisp_eval_list(Env env, Val v); Val tisp_eval(Env env, Val v); void tisp_print(FILE *f, Val v); +char *tisp_read_file(char *fname); + void tisp_env_add(Env e, char *key, Val v); Env tisp_env_init(size_t cap); void tisp_env_free(Env env);