aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/sdlang/parser.d
blob: c9b8d4f6c65ce22246c7fd221fe73053db8b96ea (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
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
// SDLang-D
// Written in the D programming language.

module sdlang.parser;

import std.file;

import libInputVisitor;
import taggedalgebraic;

import sdlang.ast;
import sdlang.exception;
import sdlang.lexer;
import sdlang.symbol;
import sdlang.token;
import sdlang.util;

/// Returns root tag.
Tag parseFile(string filename)
{
	auto source = cast(string)read(filename);
	return parseSource(source, filename);
}

/// Returns root tag. The optional `filename` parameter can be included
/// so that the SDLang document's filename (if any) can be displayed with
/// any syntax error messages.
Tag parseSource(string source, string filename=null)
{
	auto lexer = new Lexer(source, filename);
	auto parser = DOMParser(lexer);
	return parser.parseRoot();
}

/++
Parses an SDL document using StAX/Pull-style. Returns an InputRange with
element type ParserEvent.

The pullParseFile version reads a file and parses it, while pullParseSource
parses a string passed in. The optional `filename` parameter in pullParseSource
can be included so that the SDLang document's filename (if any) can be displayed
with any syntax error messages.

Note: The old FileStartEvent and FileEndEvent events
$(LINK2 https://github.com/Abscissa/SDLang-D/issues/17, were deemed unnessecary)
and removed as of SDLang-D v0.10.0.

Note: Previously, in SDLang-D v0.9.x, ParserEvent was a
$(LINK2 http://dlang.org/phobos/std_variant.html#.Algebraic, std.variant.Algebraic).
As of SDLang-D v0.10.0, it is now a
$(LINK2 https://github.com/s-ludwig/taggedalgebraic, TaggedAlgebraic),
so usage has changed somewhat.

Example:
------------------
parent 12 attr="q" {
	childA 34
	childB 56
}
lastTag
------------------

The ParserEvent sequence emitted for that SDL document would be as
follows (indented for readability):
------------------
TagStartEvent (parent)
	ValueEvent (12)
	AttributeEvent (attr, "q")
	TagStartEvent (childA)
		ValueEvent (34)
	TagEndEvent
	TagStartEvent (childB)
		ValueEvent (56)
	TagEndEvent
TagEndEvent
TagStartEvent (lastTag)
TagEndEvent
------------------
+/
auto pullParseFile(string filename)
{
	auto source = cast(string)read(filename);
	return parseSource(source, filename);
}

///ditto
auto pullParseSource(string source, string filename=null)
{
	auto lexer = new Lexer(source, filename);
	auto parser = PullParser(lexer);
	return inputVisitor!ParserEvent( parser );
}

///
@("pullParseFile/pullParseSource example")
unittest
{
	// stuff.sdl
	immutable stuffSdl = `
		name "sdlang-d"
		description "An SDL (Simple Declarative Language) library for D."
		homepage "http://github.com/Abscissa/SDLang-D"
		
		configuration "library" {
			targetType "library"
		}
	`;
	
	import std.stdio;

	foreach(event; pullParseSource(stuffSdl))
	final switch(event.kind)
	{
	case ParserEvent.Kind.tagStart:
		auto e = cast(TagStartEvent) event;
		writeln("TagStartEvent: ", e.namespace, ":", e.name, " @ ", e.location);
		break;

	case ParserEvent.Kind.tagEnd:
		auto e = cast(TagEndEvent) event;
		writeln("TagEndEvent");
		break;

	case ParserEvent.Kind.value:
		auto e = cast(ValueEvent) event;
		writeln("ValueEvent: ", e.value);
		break;

	case ParserEvent.Kind.attribute:
		auto e = cast(AttributeEvent) event;
		writeln("AttributeEvent: ", e.namespace, ":", e.name, "=", e.value);
		break;
	}
}

private union ParserEventUnion
{
	TagStartEvent  tagStart;
	TagEndEvent    tagEnd;
	ValueEvent     value;
	AttributeEvent attribute;
}

/++
The element of the InputRange returned by pullParseFile and pullParseSource.

This is a tagged union, built from the following:
-------
alias ParserEvent = TaggedAlgebraic!ParserEventUnion;
private union ParserEventUnion
{
	TagStartEvent  tagStart;
	TagEndEvent    tagEnd;
	ValueEvent     value;
	AttributeEvent attribute;
}
-------

Note: The old FileStartEvent and FileEndEvent events
$(LINK2 https://github.com/Abscissa/SDLang-D/issues/17, were deemed unnessecary)
and removed as of SDLang-D v0.10.0.

Note: Previously, in SDLang-D v0.9.x, ParserEvent was a
$(LINK2 http://dlang.org/phobos/std_variant.html#.Algebraic, std.variant.Algebraic).
As of SDLang-D v0.10.0, it is now a
$(LINK2 https://github.com/s-ludwig/taggedalgebraic, TaggedAlgebraic),
so usage has changed somewhat.
+/
alias ParserEvent = TaggedAlgebraic!ParserEventUnion;

///
@("ParserEvent example")
unittest
{
	// Create
	ParserEvent event1 = TagStartEvent();
	ParserEvent event2 = TagEndEvent();
	ParserEvent event3 = ValueEvent();
	ParserEvent event4 = AttributeEvent();

	// Check type
	assert(event1.kind == ParserEvent.Kind.tagStart);
	assert(event2.kind == ParserEvent.Kind.tagEnd);
	assert(event3.kind == ParserEvent.Kind.value);
	assert(event4.kind == ParserEvent.Kind.attribute);

	// Cast to base type
	auto e1 = cast(TagStartEvent) event1;
	auto e2 = cast(TagEndEvent) event2;
	auto e3 = cast(ValueEvent) event3;
	auto e4 = cast(AttributeEvent) event4;
	//auto noGood = cast(AttributeEvent) event1; // AssertError: event1 is a TagStartEvent, not AttributeEvent.

	// Use as base type.
	// In many cases, no casting is even needed.
	event1.name = "foo";  
	//auto noGood = event3.name; // AssertError: ValueEvent doesn't have a member 'name'.

	// Final switch is supported:
	final switch(event1.kind)
	{
		case ParserEvent.Kind.tagStart:  break;
		case ParserEvent.Kind.tagEnd:    break;
		case ParserEvent.Kind.value:     break;
		case ParserEvent.Kind.attribute: break;
	}
}

/// Event: Start of tag
struct TagStartEvent
{
	Location location;
	string namespace;
	string name;
}

/// Event: End of tag
struct TagEndEvent
{
	//Location location;
}

/// Event: Found a Value in the current tag
struct ValueEvent
{
	Location location;
	Value value;
}

/// Event: Found an Attribute in the current tag
struct AttributeEvent
{
	Location location;
	string namespace;
	string name;
	Value value;
}

// The actual pull parser
private struct PullParser
{
	private Lexer lexer;
	
	private struct IDFull
	{
		string namespace;
		string name;
	}
	
	private void error(string msg)
	{
		error(lexer.front.location, msg);
	}

	private void error(Location loc, string msg)
	{
		throw new ParseException(loc, "Error: "~msg);
	}
	
	private InputVisitor!(PullParser, ParserEvent) v;
	
	void visit(InputVisitor!(PullParser, ParserEvent) v)
	{
		this.v = v;
		parseRoot();
	}
	
	private void emit(Event)(Event event)
	{
		v.yield( ParserEvent(event) );
	}
	
	/// <Root> ::= <Tags> EOF  (Lookaheads: Anything)
	private void parseRoot()
	{
		//trace("Starting parse of file: ", lexer.filename);
		//trace(__FUNCTION__, ": <Root> ::= <Tags> EOF  (Lookaheads: Anything)");

		auto startLocation = Location(lexer.filename, 0, 0, 0);

		parseTags();
		
		auto token = lexer.front;
		if(token.matches!":"())
		{
			lexer.popFront();
			token = lexer.front;
			if(token.matches!"Ident"())
			{
				error("Missing namespace. If you don't wish to use a namespace, then say '"~token.data~"', not ':"~token.data~"'");
				assert(0);
			}
			else
			{
				error("Missing namespace. If you don't wish to use a namespace, then omit the ':'");
				assert(0);
			}
		}
		else if(!token.matches!"EOF"())
			error("Expected a tag or end-of-file, not " ~ token.symbol.name);
	}

	/// <Tags> ::= <Tag> <Tags>  (Lookaheads: Ident Value)
	///        |   EOL   <Tags>  (Lookaheads: EOL)
	///        |   {empty}       (Lookaheads: Anything else, except '{')
	void parseTags()
	{
		//trace("Enter ", __FUNCTION__);
		while(true)
		{
			auto token = lexer.front;
			if(token.matches!"Ident"() || token.matches!"Value"())
			{
				//trace(__FUNCTION__, ": <Tags> ::= <Tag> <Tags>  (Lookaheads: Ident Value)");
				parseTag();
				continue;
			}
			else if(token.matches!"EOL"())
			{
				//trace(__FUNCTION__, ": <Tags> ::= EOL <Tags>  (Lookaheads: EOL)");
				lexer.popFront();
				continue;
			}
			else if(token.matches!"{"())
			{
				error("Found start of child block, but no tag name. If you intended an anonymous "~
				"tag, you must have at least one value before any attributes or child tags.");
			}
			else
			{
				//trace(__FUNCTION__, ": <Tags> ::= {empty}  (Lookaheads: Anything else, except '{')");
				break;
			}
		}
	}

	/// <Tag>
	///     ::= <IDFull> <Values> <Attributes> <OptChild> <TagTerminator>  (Lookaheads: Ident)
	///     |   <Value>  <Values> <Attributes> <OptChild> <TagTerminator>  (Lookaheads: Value)
	void parseTag()
	{
		auto token = lexer.front;
		if(token.matches!"Ident"())
		{
			//trace(__FUNCTION__, ": <Tag> ::= <IDFull> <Values> <Attributes> <OptChild> <TagTerminator>  (Lookaheads: Ident)");
			//trace("Found tag named: ", tag.fullName);
			auto id = parseIDFull();
			emit( TagStartEvent(token.location, id.namespace, id.name) );
		}
		else if(token.matches!"Value"())
		{
			//trace(__FUNCTION__, ": <Tag> ::= <Value>  <Values> <Attributes> <OptChild> <TagTerminator>  (Lookaheads: Value)");
			//trace("Found anonymous tag.");
			emit( TagStartEvent(token.location, null, null) );
		}
		else
			error("Expected tag name or value, not " ~ token.symbol.name);

		if(lexer.front.matches!"="())
			error("Found attribute, but no tag name. If you intended an anonymous "~
			"tag, you must have at least one value before any attributes.");

		parseValues();
		parseAttributes();
		parseOptChild();
		parseTagTerminator();
		
		emit( TagEndEvent() );
	}

	/// <IDFull> ::= Ident <IDSuffix>  (Lookaheads: Ident)
	IDFull parseIDFull()
	{
		auto token = lexer.front;
		if(token.matches!"Ident"())
		{
			//trace(__FUNCTION__, ": <IDFull> ::= Ident <IDSuffix>  (Lookaheads: Ident)");
			lexer.popFront();
			return parseIDSuffix(token.data);
		}
		else
		{
			error("Expected namespace or identifier, not " ~ token.symbol.name);
			assert(0);
		}
	}

	/// <IDSuffix>
	///     ::= ':' Ident  (Lookaheads: ':')
	///     ::= {empty}    (Lookaheads: Anything else)
	IDFull parseIDSuffix(string firstIdent)
	{
		auto token = lexer.front;
		if(token.matches!":"())
		{
			//trace(__FUNCTION__, ": <IDSuffix> ::= ':' Ident  (Lookaheads: ':')");
			lexer.popFront();
			token = lexer.front;
			if(token.matches!"Ident"())
			{
				lexer.popFront();
				return IDFull(firstIdent, token.data);
			}
			else
			{
				error("Expected name, not " ~ token.symbol.name);
				assert(0);
			}
		}
		else
		{
			//trace(__FUNCTION__, ": <IDSuffix> ::= {empty}  (Lookaheads: Anything else)");
			return IDFull("", firstIdent);
		}
	}

	/// <Values>
	///     ::= Value <Values>  (Lookaheads: Value)
	///     |   {empty}         (Lookaheads: Anything else)
	void parseValues()
	{
		while(true)
		{
			auto token = lexer.front;
			if(token.matches!"Value"())
			{
				//trace(__FUNCTION__, ": <Values> ::= Value <Values>  (Lookaheads: Value)");
				parseValue();
				continue;
			}
			else
			{
				//trace(__FUNCTION__, ": <Values> ::= {empty}  (Lookaheads: Anything else)");
				break;
			}
		}
	}

	/// Handle Value terminals that aren't part of an attribute
	void parseValue()
	{
		auto token = lexer.front;
		if(token.matches!"Value"())
		{
			//trace(__FUNCTION__, ": (Handle Value terminals that aren't part of an attribute)");
			auto value = token.value;
			//trace("In tag '", parent.fullName, "', found value: ", value);
			emit( ValueEvent(token.location, value) );
			
			lexer.popFront();
		}
		else
			error("Expected value, not "~token.symbol.name);
	}

	/// <Attributes>
	///     ::= <Attribute> <Attributes>  (Lookaheads: Ident)
	///     |   {empty}                   (Lookaheads: Anything else)
	void parseAttributes()
	{
		while(true)
		{
			auto token = lexer.front;
			if(token.matches!"Ident"())
			{
				//trace(__FUNCTION__, ": <Attributes> ::= <Attribute> <Attributes>  (Lookaheads: Ident)");
				parseAttribute();
				continue;
			}
			else
			{
				//trace(__FUNCTION__, ": <Attributes> ::= {empty}  (Lookaheads: Anything else)");
				break;
			}
		}
	}

	/// <Attribute> ::= <IDFull> '=' Value  (Lookaheads: Ident)
	void parseAttribute()
	{
		//trace(__FUNCTION__, ": <Attribute> ::= <IDFull> '=' Value  (Lookaheads: Ident)");
		auto token = lexer.front;
		if(!token.matches!"Ident"())
			error("Expected attribute name, not "~token.symbol.name);
		
		auto id = parseIDFull();
		
		token = lexer.front;
		if(!token.matches!"="())
			error("Expected '=' after attribute name, not "~token.symbol.name);
		
		lexer.popFront();
		token = lexer.front;
		if(!token.matches!"Value"())
			error("Expected attribute value, not "~token.symbol.name);
		
		//trace("In tag '", parent.fullName, "', found attribute '", attr.fullName, "'");
		emit( AttributeEvent(token.location, id.namespace, id.name, token.value) );
		
		lexer.popFront();
	}

	/// <OptChild>
	///      ::= '{' EOL <Tags> '}'  (Lookaheads: '{')
	///      |   {empty}             (Lookaheads: Anything else)
	void parseOptChild()
	{
		auto token = lexer.front;
		if(token.matches!"{")
		{
			//trace(__FUNCTION__, ": <OptChild> ::= '{' EOL <Tags> '}'  (Lookaheads: '{')");
			lexer.popFront();
			token = lexer.front;
			if(!token.matches!"EOL"())
				error("Expected newline or semicolon after '{', not "~token.symbol.name);
			
			lexer.popFront();
			parseTags();
			
			token = lexer.front;
			if(!token.matches!"}"())
				error("Expected '}' after child tags, not "~token.symbol.name);
			lexer.popFront();
		}
		else
		{
			//trace(__FUNCTION__, ": <OptChild> ::= {empty}  (Lookaheads: Anything else)");
			// Do nothing, no error.
		}
	}
	
	/// <TagTerminator>
	///     ::= EOL      (Lookahead: EOL)
	///     |   {empty}  (Lookahead: EOF)
	void parseTagTerminator()
	{
		auto token = lexer.front;
		if(token.matches!"EOL")
		{
			//trace(__FUNCTION__, ": <TagTerminator> ::= EOL  (Lookahead: EOL)");
			lexer.popFront();
		}
		else if(token.matches!"EOF")
		{
			//trace(__FUNCTION__, ": <TagTerminator> ::= {empty}  (Lookahead: EOF)");
			// Do nothing
		}
		else
			error("Expected end of tag (newline, semicolon or end-of-file), not " ~ token.symbol.name);
	}
}

private struct DOMParser
{
	Lexer lexer;
	
	Tag parseRoot()
	{
		auto currTag = new Tag(null, null, "root");
		currTag.location = Location(lexer.filename, 0, 0, 0);
		
		auto parser = PullParser(lexer);
		auto eventRange = inputVisitor!ParserEvent( parser );
		
		foreach(event; eventRange)
		final switch(event.kind)
		{
		case ParserEvent.Kind.tagStart:
			auto newTag = new Tag(currTag, event.namespace, event.name);
			newTag.location = event.location;
			
			currTag = newTag;
			break;

		case ParserEvent.Kind.tagEnd:
			currTag = currTag.parent;

			if(!currTag)
				parser.error("Internal Error: Received an extra TagEndEvent");
			break;

		case ParserEvent.Kind.value:
			currTag.add((cast(ValueEvent)event).value);
			break;

		case ParserEvent.Kind.attribute:
			auto e = cast(AttributeEvent) event;
			auto attr = new Attribute(e.namespace, e.name, e.value, e.location);
			currTag.add(attr);
			break;
		}
		
		return currTag;
	}
}

// Other parser tests are part of the AST's tests over in the ast module.

// Regression test, issue #13: https://github.com/Abscissa/SDLang-D/issues/13
// "Incorrectly accepts ":tagname" (blank namespace, tagname prefixed with colon)"
@("parser: Regression test issue #13")
unittest
{
	import std.exception;
	assertThrown!ParseException(parseSource(`:test`));
	assertThrown!ParseException(parseSource(`:4`));
}

// Regression test, issue #16: https://github.com/Abscissa/SDLang-D/issues/16
@("parser: Regression test issue #16")
unittest
{
	// Shouldn't crash
	foreach(event; pullParseSource(`tag "data"`))
	{
		if(event.kind == ParserEvent.Kind.tagStart)
			auto e = cast(TagStartEvent) event;
	}
}

// Regression test, issue #31: https://github.com/Abscissa/SDLang-D/issues/31
// "Escape sequence results in range violation error"
@("parser: Regression test issue #31")
unittest
{
	// Shouldn't get a Range violation
	parseSource(`test "\"foo\""`);
}