Source

arana-main / arana / main.c

/*
 * main.c
 *
 * (c) Copyright 2009 by Georg Brandl.
 */

#include "arana.h"

static char
usage[] = "Usage: %s [-c code|filename|-v]\n";


int
main(int argc, char *argv[])
{
    int opt;
    char *code = NULL;

    /* the root is here */
    AR_ROOT_SCOPE;

    /* create the interpreter in the root scope */
    AR_INTERPRETER();

    /* parse options */
    while ((opt = getopt(argc, argv, "c:v")) != -1) {
        switch (opt) {
        case 'c':
            code = optarg;
            break;
        case 'v':
            printf("Arana version %d:%s [%s]\n",
                   ARANA_REVISION,
                   ARANA_HG_CHANGESET,
                   ARANA_DATE);
            return 0;
        default:
            fprintf(stderr, usage, argv[0]);
            exit(EXIT_FAILURE);
        }
    }

    if (!code && optind >= argc) {
        /* no argument given */
        arana_repl_loop(AR_ISIG);
        return 0;
    }

    ArAstNode *ast;
    char *fn;
    if (code) {
        fn = "<command>";
        ast = (ArAstNode *)arana_parse_string(AR_ISIG, code, AR_STRING(fn));
    } else {
        fn = argv[optind];
        FILE *f = fopen(fn, "r");
        if (f == NULL) {
            fprintf(stderr, "Error opening %s: %s\n", fn, strerror(errno));
            exit(EXIT_FAILURE);
        }
        ast = (ArAstNode *)arana_parse_file(AR_ISIG, f, AR_STRING(fn));
    }
    /* execute code -- XXX factor that out */
    arana_ast_optimize(AR_ISIG, ast);
    arana_ast_dump(AR_ISIG, ast, stdout);
    ArCode *codeobj = AR_COMPILE(ast, fn);
    AR_DEBUG_CODE(codeobj);
    ArFrame *frame = AR_FRAME(codeobj);
    AR_EVALUATE(frame);
    return 0;
}