summary refs log tree commit diff
path: root/src/3cl.c
blob: bcadf4d7cd8032d5916f819ebe4d0150d09f2489 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "3cl.h"

#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

#include "instruction.h"


int ccl_init(struct CCL *ccl, const char *code, int (*in)(), void (*out)(int))
{
    *ccl = (struct CCL)
    {
        .code = code,
        .stopped = false,
        .in = in,
        .out = out,
        .rootframe = (struct CCLFrame)
        {
            .prev = NULL, .next = NULL,
            .type = CCL_ROOT,
            .ep = 0,
            .vars = (struct CCLVariable)
            {
                .prev = NULL,
                .next = NULL,
                .name = '_',
                .value = 0
            },
        },
        .stack = (struct CCLStack)
        {
            .length = CCL_STACKSIZE,
            .stack = (CCLNum *)malloc(CCL_STACKSIZE)
        },
    };

    return errno;
}

void ccl_free(struct CCL *ccl)
{
    free(ccl->stack.stack);
    if (ccl->rootframe.next != NULL)
    {
        for (struct CCLFrame *frame = ccl->rootframe.next, *new;;)
        {
            if (frame->vars.next != NULL)
            {
                for (struct CCLVariable *var = frame->vars.next, *new;;)
                {
                    if (var->next == NULL)
                        break;
                    new = var->next;
                    free(var);
                    var = new;
                }
            }

            if (frame->next == NULL)
                break;
            new = frame->next;
            free(frame);
            frame = new;
        }
    }
}

void ccl_exec(struct CCL *ccl)
{
    struct CCLFrame *curframe = &ccl->rootframe;

    for (;;)
    {
        curframe = ccl_instruction(ccl, curframe);
        if (ccl->stopped)
            break;
    }
}