summaryrefslogtreecommitdiffstats
path: root/dom.c
blob: 71679bc3415d1df123f794eb6db149da164012e7 (plain)
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
139
140
141
142
143
144
145
146
147
#include <stdio.h>
#include <err.h>

#include "mem.h"
#include "dom.h"
#include "vec.h"
#include "parse.h"

static struct node **nodes;
static size_t count;
static size_t capacity;

static struct vec stack;
static struct node *root;

static inline struct node *node_alloc(void)
{
	struct node *v;

	if (count == capacity) {
		capacity = capacity ? capacity * 2 : 64;
		nodes = REALLOC(nodes, capacity * sizeof(struct node *));
	}

	v = CALLOC(1, sizeof(struct node));
	nodes[count++] = v;
	return v;
}

struct node *dom_init(const char *html)
{
	vec_init(&stack, sizeof(struct node *));
	parse(html);
	return root;
}

void dom_free(void)
{
	size_t i;

	for (i = 0; i < count; i++)
		free(nodes[i]);
	free(nodes);
	nodes = NULL;
	count = 0;
	capacity = 0;

	vec_free(&stack);
}

static inline int is_self_closing(tag_type tag)
{
	switch (tag) {
	case TAG_META:
	case TAG_LINK:
		return 1;
	default:
		return 0;
	}
}

static inline void close_tag(struct node *v)
{
	void *top;
	struct node *parent;

	top = vec_top(&stack);
	if (!top) {
		root = v;
		return;
	}

	parent = *(struct node **)top;
	v->parent = parent;

	if (!parent->first_child) {
		parent->first_child = v;
		parent->last_child = v;
	} else {
		parent->last_child->next_sibling = v;
		parent->last_child = v;
	}
}

extern void on_open(const char *tag, size_t n)
{
	struct node *v;

	v = node_alloc();	
	v->tag = str_to_tag(tag, n);
	vec_push(&stack, &v);
}

extern void on_open_end(void)
{
	struct node *v;

	v = *(struct node **)vec_top(&stack);
	if (is_self_closing(v->tag)) {
		v = *(struct node **)vec_pop(&stack);
		close_tag(v);
	}
}

extern void on_close(const char *tag, size_t n)
{
	tag_type type;
	struct node *top;

	type = str_to_tag(tag, n);
	top = *(struct node **)vec_top(&stack);
	if (top->tag != type)
		errx(1, "Unmatched closing tag: %.*s", (int)n, tag);

	top = *(struct node **)vec_pop(&stack);
	close_tag(top);
}

extern void on_text(const char *text, size_t n)
{
	struct node *v;

	v = node_alloc();	
	v->tag = TAG_TEXT;
	v->text = text;
	v->textlen = n;
	close_tag(v);
}

extern void on_attr(const char *name, size_t nname, 
	const char *val, size_t nval)
{
	struct attr *a;
	struct node *v;

	a = MALLOC(sizeof(struct attr));
	a->key = name;
	a->keylen = nname;
	a->val = val;
	a->vallen = nval;
	a->next = NULL;

	v = *(struct node **)vec_top(&stack);
	a->next = v->attrs;
	v->attrs = a;
}