aboutsummaryrefslogtreecommitdiff
path: root/src/parser.c
blob: a274cd87a0b2d5066ae1d28d3af181edd90b98fa (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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include "all.h"
#include <stdlib.h>

static inline char peek(const char **p) { return **p; }

static inline char advance(const char **p) { return *(*p)++; }

static ast_node_t *new_node(ast_type_e type, int val) {
  ast_node_t *n = malloc(sizeof(ast_node_t));
  n->type = type;
  n->val = val;
  n->next = NULL;
  n->children = (node_vec){0};
  return n;
}

static ast_node_t *parse_block(const char **p);

static ast_node_t *parse_single(const char **p) {
  char c = peek(p);

  switch (c) {

  case '+': {
    int count = 0;
    while (peek(p) == '+') {
      advance(p);
      count++;
    }
    return new_node(AST_INC, count);
  }

  case '-': {
    int count = 0;
    while (peek(p) == '-') {
      advance(p);
      count++;
    }
    return new_node(AST_DEC, count);
  }

  case '>': {
    int count = 0;
    while (peek(p) == '>') {
      advance(p);
      count++;
    }
    return new_node(AST_PTR_INC, count);
  }

  case '<': {
    int count = 0;
    while (peek(p) == '<') {
      advance(p);
      count++;
    }
    return new_node(AST_PTR_DEC, count);
  }

  case '.':
    advance(p);
    return new_node(AST_OUT, 1);

  case ',':
    advance(p);
    return new_node(AST_IN, 1);

  case '[':
    advance(p);
    return parse_block(p);

  case ']':
  case '\0':
    return NULL;

  default:
    advance(p); // ignore garbage
    return NULL;
  }
}

static ast_node_t *parse_block(const char **p) {
  ast_node_t *loop = new_node(AST_LOOP, 1);

  while (**p) {

    if (**p == ']') {
      advance(p);
      break;
    }

    ast_node_t *child = parse_single(p);

    if (child)
      node_vec_push(&loop->children, child);
  }

  return loop;
}

ast_node_t *parse(const char *src) {
  const char *p = src;

  ast_node_t *head = NULL;
  ast_node_t *tail = NULL;

  while (*p) {

    ast_node_t *node = parse_single(&p);
    if (!node)
      continue;

    if (!head) {
      head = tail = node;
    } else {
      tail->next = node;
      tail = node;
    }
  }

  return head;
}

void ast_free(ast_node_t *node) {
  if (!node)
    return;

  if (node->next)
    ast_free(node->next);

  for (size_t i = 0; i < node->children.len; i++) {
    ast_free(node->children._data[i]);
  }

  node_vec_free(&node->children);

  free(node);
}