aboutsummaryrefslogtreecommitdiff
path: root/sem3/osc/miniproject/cnasm/ast.c
blob: cc53e24e5ed2566f8f3873b9c42937470e7ba2f1 (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "ast.h"

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

static ast_node_t *create_empty_node()
{
    ast_node_t *n = malloc(sizeof(ast_node_t));
    memset(n, 0, sizeof(ast_node_t));
}

ast_node_t *insert_ctrl(enum ntype t, cond_t *c, ast_node_t *iftrue,
                        ast_node_t *iffalse)
{
    ast_node_t *n = create_empty_node();

    n->t = t;
    n->flowctrl.condition = c;
    n->flowctrl.iftrue = iftrue;
    n->flowctrl.iffalse = iffalse;

    return n;
}

ast_node_t *insert_for(char *pre, cond_t *c, char *inc, ast_node_t *stuff)
{
    ast_node_t *n = create_empty_node();

    n->t = TFOR;
    n->forloop.condition = c;
    n->forloop.pre = pre;
    n->forloop.inc = inc;
    n->forloop.stuff = stuff;

    return n;
}

ast_node_t *insert_stm(ast_node_t *stm, ast_node_t *stm_list)
{
    ast_node_t *n = create_empty_node();

    n->t = TSTM_LIST;
    n->list.children[0] = stm_list;
    n->list.children[1] = stm;

    return n;
}
ast_node_t *insert_ident(char *ident)
{
    ast_node_t *n = create_empty_node();

    n->t = TIDENT;
    n->ident = ident;

    return n;
}

cond_t *insert_cond(uint8_t cmp, char *a, char *b)
{
    cond_t *c = malloc(sizeof(cond_t));

    c->cmp = cmp;
    c->a = a;
    c->b = b;
}

void node_print(ast_node_t *node)
{
    if (!node) {
        printf("Nil");
        return;
    }
    switch (node->t) {
    case TSTM_LIST:
        printf("Stm_list(");
        node_print(node->list.children[0]);
        printf(",");
        node_print(node->list.children[1]);
        printf(")");
        break;
    case TIF:
        printf("If");
        printf("(%s %c %s) {", node->flowctrl.condition->a,
               node->flowctrl.condition->cmp, node->flowctrl.condition->b);
        node_print(node->flowctrl.iftrue);
        printf("}{");
        node_print(node->flowctrl.iffalse);
        printf("}");
        break;
    case TIDENT:
        printf("%s", node->ident);
        break;
    case TWHILE:
        printf("while");
        printf("(%s %c %s) {", node->flowctrl.condition->a,
               node->flowctrl.condition->cmp, node->flowctrl.condition->b);
        node_print(node->flowctrl.iftrue);
        printf("}");
        break;
    default:
        printf("invalid");
    }
}