aboutsummaryrefslogtreecommitdiffstats
path: root/forthmachine.c
blob: 91c77ff8527a01281e4916573ec8d6870f72f30e (plain)
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
#include "forthmachine.h"
#include <string.h>
#include "drhstrings.h"
/****/

forthmachine* forthmachine_new() {
    forthmachine* fm = (forthmachine*)malloc(sizeof(forthmachine));
    fm->ot = optable_new();
    fm->s = stack_new();
    fm->outputbuffer = (char*)malloc(sizeof(char) * MAX_OUTPUT_BUFFER_SIZE);
    strcpy(fm->outputbuffer, "");
    return fm;
}

static void op_exec(wordop* op, forthmachine* fm, char *word, int len, char* line, int* i) {
    switch (op->optype) {
        case script:
            forthmachine_eval(fm, op->scriptlen, op->script);
            break;
        case builtin:
            op->op(fm);
            break;
        case directive:
            op->directive(fm, len, line, i);
            break;
        case compiled:
            for (int j = 0; j < op->oplistlen; j++) {
                if (op->oplist[j].isliteral) {
                    stack_push(fm->s, op->oplist[j].literal);
                } else {
                    op_exec(op->oplist[j].wordop, fm, word, len, line, i);
                }
            }
            break;
    }
}

static void forthmachine_exec(forthmachine* fm, char *word, int len, char* line, int* i) {
    wordop* op = optable_getop(fm->ot, word);
    if (op) {
        op_exec(op, fm, word, len, line, i);
    } else if (isnumber(word)) {
        stack_push(fm->s, atoi(word));
    }
}

void forthmachine_eval(forthmachine* fm, int len, char* line) {
    char word[WORD_LEN_LIMIT];
    int wordi = 0;
    for (int i = 0; i < len; i++) {
        if (notdelim(line[i]) && wordi < WORD_LEN_LIMIT - 1) {
            word[wordi++] = line[i];
        } else { // end of word
            if (wordi > 0) { // don't exec an empty string
                word[wordi] = '\0';
                forthmachine_exec(fm, word, len, line, &i);
            }
            // start new word
            wordi = 0;
        }
        // end of input string
        if (line[i] == '\0') {
            return;
        }
    }
}