view src/bin/ylisp.c @ 169:cdf06bdd9592

bin/ylisp: Support reading scripts
author Lewin Bormann <lbo@spheniscida.de>
date Tue, 03 Sep 2019 20:18:05 +0200
parents 5697df53fe81
children 37b01b114b50
line wrap: on
line source

#include <stdio.h>
#include <err.h>

#include <src/parse.h>
#include <src/preprocess.h>
#include <src/eval.h>

yexpr_t run(FILE* input, yeval_state_t* state, yvec_t** root) {
    yexpr_t file = yexpr_new();
    yexpr_t result = yexpr_new();
    ystr_t error = ystr_new(NULL);
    bool ok = yparse(input, &file, &error);
    if (!ok) {
        fprintf(stderr, "Parse error: %s\n", ystr_str(&error));
        goto clean_all;
    }
    ypreprocess_resolve_builtins(&file);
    ypreprocess_refs_repl(&file, root);
    result = yeval_list_return_last(state, &file.value.list, 0);
clean_all:
    yexpr_destroy(&file);
    ystr_destroy(&error);
    return result;
}

int main(int argc, char** argv) {
    yvec_t* root = NULL;
    yeval_state_t state;
    state.call_stack = YVEC_NEW(NULL, 16, yexpr_t);
    yexpr_t result = yexpr_new();

    if (argc == 1) {
        result = run(stdin, &state, &root);
    } else {
        for (int i = 1; i < argc; i++) {
            FILE* source = fopen(argv[i], "r");
            if (source == NULL) {
                err(1, "couldn't open file %s", argv[i]);
            }
            yexpr_t result = run(source, &state, &root);
            yexpr_destroy(&result);
            fclose(source);
        }
    }

    yvec_destroy(YVEC_AT(root, 0, yvec_t));
    free(*YVEC_AT(root, 0, void*));
    yvec_destroy(root);
    free(root);
    yvec_destroy(&state.call_stack);
    yexpr_destroy(&result);

    yvalue_free_all();
    yatom_free_all();
    return 0;
}