~sircmpwn/hare-xml

ref: 3292657ccdf1169997838f17cf2d3492a6da7bf4 hare-xml/parser.ha -rw-r--r-- 11.3 KiB
3292657cDrew DeVault all: overhaul switch/match syntax 1 year, 2 months ago
                                                                                
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
// Are you an intrepid programmer seeking to fork this module to create a more
// sophisticated XML parser supporting a broader set of features? Good news: all
// of the features you need to implement are annotated throughout with
// "XXX: Deliberate ommission" comments.
use ascii;
use bufio;
use encoding::utf8;
use io;
use strconv;
use strings;
use strio;

// Returns an XML parser which reads from a stream. The caller must call
// [[parser_free]] when they are finished with it.
//
// Hare's XML parser only supports UTF-8 encoded input files.
//
// This function will attempt to read the XML prologue before returning, and
// will return an error if it is not valid.
export fn parse(in: *io::stream) (*parser | error) = {
	// XXX: The main reason we allocate this instead of returning it on the
	// stack is so that we have a consistent address for the bufio buffer.
	// This is kind of lame, maybe we can avoid that.
	let par = alloc(parser {
		orig = in,
		in = in,
		namebuf = strio::dynamic(),
		entbuf = strio::dynamic(),
		textbuf = strio::dynamic(),
		...
	});
	if (!bufio::isbuffered(in)) {
		par.in = bufio::buffered(par.in, par.buf[..], []);
	};
	prolog(par)?;
	return par;
};

// Frees the resources associated with this parser. Does not close the
// underlying stream.
export fn parser_free(par: *parser) void = {
	if (par.in != par.orig) {
		io::close(par.in);
	};
	io::close(par.namebuf);
	io::close(par.entbuf);
	io::close(par.textbuf);
	for (let i = 0z; i < len(par.tags); i += 1) {
		free(par.tags[i]);
	};
	free(par.tags);
	free(par);
};

// Scans for and returns the next [[token]]. Tokens are borrowed from the parser
// and are not valid on subsequent calls to [[scan]]; use [[token_dup]] to
// extend their lifetime.
export fn scan(par: *parser) (token | void | error) = {
	switch (par.state) {
	case state::ROOT, state::ATTRS => want(par, OPTWS)?;
	case => void;
	};
	let rn: rune = match (bufio::scanrune(par.in)?) {
	case io::EOF =>
		if (par.state == state::ROOT) {
			return syntaxerr;
		} else {
			return;
		};
	case rn: rune =>
		yield rn;
	};
	switch (par.state) {
	case state::ROOT, state::ELEMENT =>
		switch (rn) {
		case '<' =>
			const next = match (bufio::scanrune(par.in)?) {
			case io::EOF =>
				return syntaxerr;
			case rn: rune =>
				bufio::unreadrune(par.in, rn);
				yield rn;
			};
			bufio::unreadrune(par.in, rn);
			switch (next) {
			case '!' =>
				return scan_comment(par);
			case '?' =>
				return scan_pi(par);
			case => void;
			};
			let el = scan_element(par)?;
			par.state = state::ATTRS;
			return el;
		case =>
			if (par.state == state::ROOT) {
				return syntaxerr;
			};
			bufio::unreadrune(par.in, rn);
			return scan_content(par)?;
		};
	case state::ATTRS =>
		if (rn == '/') {
			want(par, '>')?;
			par.state = state::ELEMENT;
			return poptag(par, "")?: elementend;
		} else if (rn == '>') {
			par.state = state::ELEMENT;
			return scan(par)?;
		} else if (!isnamestart(rn)) {
			return syntaxerr;
		};
		bufio::unreadrune(par.in, rn);
		return scan_attr(par)?;
	};
};

fn poptag(par: *parser, expect: str) (str | error) = {
	if (len(par.tags) == 0) {
		return syntaxerr;
	};
	let pop = par.tags[len(par.tags) - 1];
	delete(par.tags[len(par.tags) - 1]);
	defer free(pop);
	if (expect != "" && expect != pop) {
		return syntaxerr;
	};
	strio::reset(par.namebuf);
	strio::concat(par.namebuf, pop)!;
	return strio::string(par.namebuf);
};

fn scan_attr(par: *parser) (token | error) = {
	let name = scan_name(par, par.namebuf)?;
	want(par, OPTWS, '=', OPTWS)?;
	let quot = quote(par)?;
	strio::reset(par.textbuf);
	for (true) match (bufio::scanrune(par.in)?) {
	case io::EOF =>
		return syntaxerr;
	case rn: rune =>
		rn = switch (rn) {
		case '<' =>
			return syntaxerr;
		case '&' =>
			bufio::unreadrune(par.in, rn);
			yield scan_entity(par)?;
		case =>
			yield rn;
		};
		if (rn == quot) break;
		strio::appendrune(par.textbuf, rn)?;
	};
	return (name, strio::string(par.textbuf)): attribute;
};

fn scan_comment(par: *parser) (token | void | error) = {
	want(par, "<!")?;
	match (bufio::scanrune(par.in)?) {
	case io::EOF =>
		return syntaxerr;
	case rn: rune =>
		switch (rn) {
		case '-' => // Comments
			want(par, '-')?;
		case '[' =>
			want(par, "CDATA[")?;
			if (par.state != state::ELEMENT) {
				return syntaxerr;
			};
			return scan_cdata(par)?;
		case =>
			return syntaxerr;
		};
	};
	for (true) {
		const rn = match (bufio::scanrune(par.in)?) {
		case io::EOF =>
			return syntaxerr;
		case rn: rune =>
			yield rn;
		};
		if (rn != '-') continue;
		const rn = match (bufio::scanrune(par.in)?) {
		case io::EOF =>
			return syntaxerr;
		case rn: rune =>
			yield rn;
		};
		if (rn != '-') continue;
		const rn = match (bufio::scanrune(par.in)?) {
		case io::EOF =>
			return syntaxerr;
		case rn: rune =>
			yield rn;
		};
		if (rn == '>') break;
	};
	return scan(par);
};

fn scan_cdata(par: *parser) (text | error) = {
	strio::reset(par.textbuf);
	for (true) {
		const rn = match (bufio::scanrune(par.in)?) {
		case io::EOF =>
			return syntaxerr;
		case rn: rune =>
			yield rn;
		};
		if (rn != ']') {
			strio::appendrune(par.textbuf, rn)!;
			continue;
		};
		const rn = match (bufio::scanrune(par.in)?) {
		case io::EOF =>
			return syntaxerr;
		case rn: rune =>
			yield rn;
		};
		if (rn != ']') {
			strio::appendrune(par.textbuf, rn)!;
			continue;
		};
		const rn = match (bufio::scanrune(par.in)?) {
		case io::EOF =>
			return syntaxerr;
		case rn: rune =>
			yield rn;
		};
		if (rn == '>') break;
		strio::appendrune(par.textbuf, rn)!;
	};
	return strio::string(par.textbuf): text;
};

fn scan_content(par: *parser) (text | error) = {
	strio::reset(par.textbuf);
	for (true) match (bufio::scanrune(par.in)?) {
	case io::EOF =>
		break;
	case rn: rune =>
		rn = switch (rn) {
		case '<' =>
			bufio::unreadrune(par.in, rn);
			break;
		case '&', '%' =>
			bufio::unreadrune(par.in, rn);
			yield scan_entity(par)?;
		case =>
			yield rn;
		};
		strio::appendrune(par.textbuf, rn)?;
	};
	return strio::string(par.textbuf);
};

fn scan_element(par: *parser) (token | error) = {
	want(par, '<')?;
	let close = false;
	match (bufio::scanrune(par.in)?) {
	case io::EOF =>
		return syntaxerr;
	case rn: rune =>
		switch (rn) {
		case '/' =>
			close = true;
		case =>
			bufio::unreadrune(par.in, rn);
		};
	};
	let name = scan_name(par, par.namebuf)?;
	if (close) {
		poptag(par, name)?;
		return name: elementend;
	} else {
		append(par.tags, strings::dup(name));
		return name: elementstart;
	};
};

fn scan_entity(par: *parser) (rune | error) = {
	want(par, '&')?;
	let rn = match (bufio::scanrune(par.in)?) {
	case io::EOF =>
		return syntaxerr;
	case rn: rune =>
		yield rn;
	};
	switch (rn) {
	case '#' =>
		return scan_charref(par);
	case '%' =>
		return syntaxerr; // XXX: Deliberate omission: PEReference
	case =>
		bufio::unreadrune(par.in, rn);
		return scan_namedent(par);
	};
};

fn scan_charref(par: *parser) (rune | error) = {
	let base = strconv::base::DEC;
	match (bufio::scanrune(par.in)?) {
	case io::EOF =>
		return syntaxerr;
	case rn: rune =>
		if (rn == 'x') {
			base = strconv::base::HEX;
		} else {
			bufio::unreadrune(par.in, rn);
		};
	};

	strio::reset(par.entbuf);
	for (true) {
		let rn = match (bufio::scanrune(par.in)?) {
		case io::EOF =>
			return syntaxerr;
		case rn: rune =>
			yield rn;
		};
		if (ascii::isdigit(rn)) {
			strio::appendrune(par.entbuf, rn)?;
		} else if (rn == ';') {
			break;
		} else {
			return syntaxerr;
		};
	};
	if (len(strio::string(par.entbuf)) == 0) {
		return syntaxerr;
	};
	match (strconv::stou32b(strio::string(par.entbuf), base)) {
	case u: u32 =>
		return u: rune;
	case (strconv::invalid | strconv::overflow) =>
		return syntaxerr;
	};
};

fn scan_namedent(par: *parser) (rune | error) = {
	const name = scan_name(par, par.entbuf)?;
	want(par, ';')?;
	const map = [
		("lt", '<'),
		("gt", '>'),
		("amp", '&'),
		("apos", '\''),
		("quot", '"'),
	];
	for (let i = 0z; i < len(map); i += 1) {
		if (map[i].0 == name) {
			return map[i].1;
		};
	};
	// XXX: Deliberate ommission: this only supports the pre-defined
	// entities as defined by XML 1.0 (Fifth Edition) section 4.6.
	return syntaxerr;
};

fn scan_name(par: *parser, buf: *io::stream) (str | error) = {
	strio::reset(buf);

	const rn = match (bufio::scanrune(par.in)?) {
	case io::EOF =>
		return syntaxerr;
	case rn: rune =>
		yield rn;
	};
	if (!isnamestart(rn)) {
		return syntaxerr;
	};
	strio::appendrune(buf, rn)!;

	for (true) match (bufio::scanrune(par.in)?) {
	case io::EOF =>
		return syntaxerr;
	case rn: rune =>
		if (isname(rn)) {
			strio::appendrune(buf, rn)!;
		} else {
			bufio::unreadrune(par.in, rn);
			break;
		};
	};

	return strio::string(buf);
};

fn scan_pi(par: *parser) (void | error) = {
	abort(); // TODO: Processor instructions
};

fn prolog(par: *parser) (void | error) = {
	// XXX: Deliberate omission(s):
	// - UTF-8 BOM detection
	// - UTF-16 support
	want(par, "<?xml", WS)?;

	want(par, "version", OPTWS, '=', OPTWS)?;
	let quot = quote(par)?;
	want(par, OPTWS, "1.")?;
	for (true) match (bufio::scanrune(par.in)?) {
	case io::EOF =>
		break;
	case rn: rune =>
		if (!ascii::isdigit(rn)) {
			bufio::unreadrune(par.in, rn);
			break;
		};
	};
	want(par, quot)?;

	let hadws = want(par, OPTWS)?;
	let encoding = match (bufio::scanrune(par.in)) {
	case io::EOF =>
		yield false;
	case rn: rune =>
		bufio::unreadrune(par.in, rn);
		yield hadws && rn == 'e';
	};
	if (encoding) {
		let attr = scan_attr(par)? as attribute;
		if (attr.0 != "encoding") {
			return syntaxerr;
		};
		// XXX: Deliberate omission: all values other than utf-8
		match (ascii::strcasecmp(attr.1, "utf-8")) {
		case void =>
			return utf8::invalid;
		case n: int =>
			if (n != 0) {
				return utf8::invalid;
			};
		};
	};

	let hadws = want(par, OPTWS)?;
	let standalone = match (bufio::scanrune(par.in)) {
	case io::EOF =>
		yield false;
	case rn: rune =>
		bufio::unreadrune(par.in, rn);
		yield hadws && rn == 's';
	};
	if (standalone) {
		let attr = scan_attr(par)? as attribute;
		if (attr.0 != "standalone") {
			return syntaxerr;
		};
		// XXX: Deliberate omission: non-standalone documents
		match (ascii::strcasecmp(attr.1, "yes")) {
		case void =>
			return syntaxerr;
		case n: int =>
			if (n != 0) {
				return syntaxerr;
			};
		};
	};

	want(par, OPTWS, "?>", OPTWS)?;
	// TODO: Parse doctypedecl & misc
	return;
};

// Mandatory if true
type whitespace = bool;
def WS: whitespace = true;
def OPTWS: whitespace = false;

fn quote(par: *parser) (rune | error) = {
	match (bufio::scanrune(par.in)?) {
	case rn: rune =>
		switch (rn) {
		case '"', '\'' =>
			return rn;
		case =>
			return syntaxerr;
		};
	case =>
		return syntaxerr;
	};
};

fn want(par: *parser, tok: (rune | str | whitespace)...) (bool | error) = {
	let hadws = false;
	for (let i = 0z; i < len(tok); i += 1) match (tok[i]) {
	case x: rune =>
		let have = match (bufio::scanrune(par.in)?) {
		case io::EOF =>
			return syntaxerr;
		case rn: rune =>
			yield rn;
		};
		if (have != x) {
			return syntaxerr;
		};
	case x: str =>
		let iter = strings::iter(x);
		for (true) match (strings::next(&iter)) {
		case rn: rune =>
			want(par, rn)?;
		case void =>
			break;
		};
	case ws: whitespace =>
		let n = 0;
		for (true; n += 1) match (bufio::scanrune(par.in)?) {
		case io::EOF =>
			break;
		case rn: rune =>
			if (!ascii::isspace(rn)) {
				bufio::unreadrune(par.in, rn);
				break;
			};
		};
		if (ws && n < 1) {
			return syntaxerr;
		};
		hadws = n >= 1;
	};
	return hadws;
};