aboutsummaryrefslogtreecommitdiff
path: root/main.cpp
blob: 78515a649f3bf1a1d44c2d16f49f289f7249bfca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "model.h"
#include "builtin.h"
#include "parser.h"
#include "eval.h"
#include "exc.h"

#include <cstdio>
#include <cstdlib>

Tokenizor *tk = new Tokenizor();
ASTGenerator *ast = new ASTGenerator();
Evaluator *eval = new Evaluator();

void load_file(const char *fname) {
    FILE *f = fopen(fname, "r");
    if (!f)
    {
        printf("Can not open file: %s\n", fname);
        exit(0);
    }
    tk->set_stream(f);
    while (1)
    {
        try
        {
            Pair *tree = ast->absorb(tk);
            if (!tree) break;
            eval->run_expr(tree);
        }
        catch (GeneralError &e)
        {
            fprintf(stderr, "An error occured: %s\n", e.get_msg().c_str());
        }
    }
}

void print_help(const char *cmd) {
    fprintf(stderr, 
            "Sonsi: Stupid and Obvious Scheme Interpreter\n"
            "Usage: %s OPTION ...\n"
            "Evaluate Scheme code, interactively or from a script.\n\n"
            "  FILE \t\tload Scheme source code from FILE, and exit\n"
            "The above switches stop argument processing\n\n"
            "  -l FILE \tload Scheme source code from FILE\n"
            "  -h, --help \tdisplay this help and exit\n", cmd);
    exit(0);
}

int main(int argc, char **argv) {

    for (int i = 1; i < argc; i++)
    {
        if (*argv[i] == '-')    // parsing options
        {
            if (strcmp(argv[i], "-l") == 0)
            {
                if (i + 1 < argc)
                    load_file(argv[++i]);
                else 
                {
                    puts("missing argument to `-l` switch");
                    print_help(*argv);
                }
            }
            else if (strcmp(argv[i], "-h") == 0 ||
                     strcmp(argv[i], "--help") == 0)
                print_help(*argv);
            else
            {
                printf("unrecognized switch `%s`\n", argv[i]);
                print_help(*argv);
            }
        }
        else
        {
            load_file(argv[i]); 
            exit(0);
        }
    }

    int rcnt = 0;
    tk->set_stream(stdin);  // interactive mode
    while (1)
    {
        fprintf(stderr, "Sonsi> ");
        try
        {
            Pair *tree = ast->absorb(tk);
            if (!tree) break;
            string output = eval->run_expr(tree)->ext_repr();
            fprintf(stderr, "Ret> $%d = %s\n", rcnt++, output.c_str());
        }
        catch (GeneralError &e)
        {
            fprintf(stderr, "An error occured: %s\n", e.get_msg().c_str());
        }
    }
}