moka/lib/node.c

72 lines
1.4 KiB
C
Raw Permalink Normal View History

2024-03-26 18:31:33 +00:00
#include "node.h"
MK_ENUM_C(NodeKind, NODE_KIND);
void node_init(struct node* self,
NodeKind kind,
struct token* token,
int line)
{
assert(self);
self->kind = kind;
self->token = token;
vec_init(&self->children);
self->line = line;
}
void node_free(struct node* self)
{
assert(self);
2024-03-26 18:31:33 +00:00
if (self->token)
{
token_free(self->token);
free(self->token);
}
vec_free_elements(&self->children, (void*) node_free);
vec_free(&self->children);
}
void node_str(struct node* self, struct str* str)
{
assert(self);
assert(str);
str_format(str, "%s", NodeKindStr[self->kind] + strlen("NODE_"));
if (self->token && self->token->value)
{
str_format(str, "[%s]", self->token->value);
}
if (self->children.size > 0)
{
str_push(str, '(');
for (size_t i=0; i<self->children.size; i++)
{
if (i > 0)
{
str_push(str, ',');
}
struct str child_str;
str_init(&child_str);
node_str(self->children.data[i], &child_str);
str_extend(str, child_str.value);
str_free(&child_str);
}
str_push(str, ')');
}
}
void node_add_new_child(struct node* self, struct node* child)
{
assert(self);
assert(child);
vec_push(&self->children, child);
}