Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
A simple s-expression/lisp-like parser for text-based tree structures
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct node {
char* name;
struct node* parent;
struct node* child;
struct node* next;
};
struct node* parse(const char* code)
{
struct node* root = calloc(1, sizeof(struct node));
struct node* result = root;
int head, len = 0;
for (head=0; code[head]; head++)
if (code[head] == '(') {
result->child = calloc(1, sizeof(struct node));
result->child->parent = result;
result = result->child;
} else if (code[head] == ')') {
if (result->parent) {
result = result->parent;
len = result->name ? strlen(result->name) : 0;
}
} else if (code[head] == ' ') {
while (code[head + 1] == ' ') head++;
result->next = calloc(1, sizeof(struct node));
result->next->parent = result->parent;
result = result->next;
len = 0;
} else {
result->name = realloc(result->name, len + 2);
result->name[len++] = code[head];
result->name[len] = 0;
}
return root;
}
void free_node(struct node* node)
{
free(node->name);
if (node->child) free_node(node->child);
if (node->next) free_node(node->next);
free(node);
}
void dump(struct node* node)
{
struct node* child;
if (node->name)
printf("%s ", node->name);
if (node->child) {
printf("(");
for (child=node->child; child; child=child->next)
dump(child);
printf(")\n");
}
}
int main(void)
{
struct node* node = parse("(hello world (this is) (indeed (very good)))");
dump(node);
free_node(node);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.