summaryrefslogtreecommitdiff
path: root/src/frontend/node.c
blob: 095aecef194f608b971758eae74c633b0bfa9354 (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
#include "node.h"
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

const char* node_types[] = {"prog-ir", "func-ir", "stmt-ir", "expr-ir", "const-ir"};
const char* node_ops[] = {"not-ir", "neg-ir", "plus-ir", "minus-ir", "mult-ir", "div-ir", "mod-ir"};

Node *create_node(enum node_type type) {
  Node *node = malloc(sizeof(Node));
  node->type = type;
  node->children = NULL;
  node->num_children = 0;
  return node;
}

Node *create_function(char *name) {
  Node *node = malloc(sizeof(Node));
  node->type = FUNC;
  node->field.name = name;
  node->children = NULL;
  node->num_children = 0;
  return node;
}

Node *create_expr(enum node_op op) {
  Node *node = malloc(sizeof(Node));
  node->type = EXPR;
  node->field.op = op;
  node->children = NULL;
  node->num_children = 0;
  return node;
}

Node *create_const(int val) {
  Node *node = malloc(sizeof(Node));
  node->type = CONST;
  node->field.val = val;
  node->children = NULL;
  node->num_children = 0;
  return node;
}

void add_child(Node *parent, Node *child) {
  size_t new_size = sizeof(Node*) * (parent->num_children + 1);
  parent->children = realloc(parent->children, new_size);

  parent->children[parent->num_children] = child;
  parent->num_children++;
}

void free_node(Node *node) {
  for (size_t i = 0; i < node->num_children; ++i) {
    free_node(node->children[i]);
  }
  if (node->type == FUNC)
    free(node->field.name);

  free(node->children);
  free(node);
}

void *print_node(Node *node, int indent) {
  if (node == NULL) {
    return;
  }

  for (int i = 0; i < indent; ++i)
    printf(" ");

  printf("type: %s", node_types[node->type]);
  if (node->type == FUNC)
    printf(", name: \"%s\"", node->field.name);
  if (node->type == EXPR)
    printf(", op: %s", node_ops[node->field.op]);
  if (node->type == CONST)
    printf(", val: %d", node->field.val);
  printf("\n");

  for (size_t i = 0; i < node->num_children; ++i) {
    print_node(node->children[i], indent + 1);
  }
}