ccm/lib/node.c

79 lines
1.5 KiB
C
Raw Permalink Normal View History

#include "node.h"
2024-03-18 17:20:40 +00:00
CCM_ENUM_C(NodeKind, NODE_KIND);
void node_init(node_t* self,
NodeKind kind,
char const* value,
int line)
{
assert(self);
self->line = line;
self->kind = kind;
vec_init(&self->children);
if (value)
{
self->value = strdup(value);
}
}
void node_free(node_t* self)
{
assert(self);
vec_free_elements(&self->children, (void*) node_free);
vec_free(&self->children);
if (self->value)
{
free(self->value);
self->value = NULL;
}
}
void node_push_new_child(node_t* self, node_t* child)
{
assert(self);
assert(child);
vec_push(&self->children, child);
}
size_t node_str(node_t* self, char* buffer, size_t size)
{
assert(self);
size_t sz = 0;
sz += snprintf(
buffer + sz, size - sz, "%s",
NodeKindStr[self->kind] + strlen("NODE_")
);
if (strlen(self->value) > 0)
{
sz += snprintf(buffer + sz, size - sz, "[%s]", self->value);
}
if (self->children.size > 0)
{
sz += snprintf(buffer + sz, size - sz, "(");
for (size_t i=0; i<self->children.size; i++)
{
if (i > 0)
{
sz += snprintf(buffer + sz, size - sz, ",");
}
sz += node_str(
self->children.data[i],
buffer + sz, size - sz
);
}
sz += snprintf(buffer + sz, size - sz, ")");
}
return sz;
}