public
Last active

A simple s-expression/lisp-like parser for text-based tree structures

  • Download Gist
miniparse.c
C
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
#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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.