scanner.cpp 13.5 KB
Newer Older
beder's avatar
beder committed
1
2
#include "scanner.h"
#include "token.h"
beder's avatar
beder committed
3
#include "exceptions.h"
beder's avatar
beder committed
4
5
6
7
8
9
10
11
12
13

namespace YAML
{
	Scanner::Scanner(std::istream& in)
		: INPUT(in), m_startedStream(false), m_simpleKeyAllowed(false), m_flowLevel(0), m_column(0)
	{
	}

	Scanner::~Scanner()
	{
beder's avatar
beder committed
14
15
16
17
18
19
20
21
		while(!m_tokens.empty()) {
			delete m_tokens.front();
			m_tokens.pop();
		}

		// delete limbo tokens (they're here for RAII)
		for(std::set <Token *>::const_iterator it=m_limboTokens.begin();it!=m_limboTokens.end();++it)
			delete *it;
beder's avatar
beder committed
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
	}

	///////////////////////////////////////////////////////////////////////
	// Misc. helpers

	// GetChar
	// . Extracts a character from the stream and updates our position
	char Scanner::GetChar()
	{
		m_column++;
		return INPUT.get();
	}

	// GetLineBreak
	// . Eats with no checking
	void Scanner::EatLineBreak()
	{
		m_column = 0;
		INPUT.get();
	}

	// EatDocumentStart
	// . Eats with no checking
	void Scanner::EatDocumentStart()
	{
		INPUT.get();
		INPUT.get();
		INPUT.get();
	}

	// EatDocumentEnd
	// . Eats with no checking
	void Scanner::EatDocumentEnd()
	{
		INPUT.get();
		INPUT.get();
		INPUT.get();
	}

	// IsWhitespaceToBeEaten
	// . We can eat whitespace if:
	//   1. It's a space
	//   2. It's a tab, and we're either:
	//      a. In the flow context
	//      b. In the block context but not where a simple key could be allowed
	//         (i.e., not at the beginning of a line, or following '-', '?', or ':')
	bool Scanner::IsWhitespaceToBeEaten()
	{
		char ch = INPUT.peek();

		if(ch == ' ')
			return true;

		if(ch == '\t' && (m_flowLevel >= 0 || !m_simpleKeyAllowed))
			return true;

		return false;
	}

	// IsLineBreak
	bool Scanner::IsLineBreak()
	{
		char ch = INPUT.peek();
		return ch == '\n'; // TODO: More types of line breaks
	}

	// IsBlank
	bool Scanner::IsBlank()
	{
		char ch = INPUT.peek();
		return IsLineBreak() || ch == ' ' || ch == '\t' || ch == EOF;
	}

	// IsDocumentStart
	bool Scanner::IsDocumentStart()
	{
		// needs to be at the start of a new line
		if(m_column != 0)
			return false;

		// then needs '---'
		for(int i=0;i<3;i++) {
			if(INPUT.peek() != '-') {
				// first put 'em back
				for(int j=0;j<i;j++)
					INPUT.putback('-');

				// and return
				return false;
			}
			INPUT.get();
		}

		// then needs a blank character (or eof)
		if(!IsBlank()) {
			// put 'em back
			for(int i=0;i<3;i++)
				INPUT.putback('-');

			// and return
			return false;
		}

		// finally, put 'em back and go
		for(int i=0;i<3;i++)
			INPUT.putback('-');

		return true;
	}

	// IsDocumentEnd
	bool Scanner::IsDocumentEnd()
	{
		// needs to be at the start of a new line
		if(m_column != 0)
			return false;

		// then needs '...'
		for(int i=0;i<3;i++) {
			if(INPUT.peek() != '.') {
				// first put 'em back
				for(int j=0;j<i;j++)
					INPUT.putback('.');

				// and return
				return false;
			}
			INPUT.get();
		}

		// then needs a blank character (or eof)
		if(!IsBlank()) {
			// put 'em back
			for(int i=0;i<3;i++)
				INPUT.putback('.');

			// and return
			return false;
		}

		// finally, put 'em back and go
		for(int i=0;i<3;i++)
			INPUT.putback('-');

		return true;
	}

beder's avatar
beder committed
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
	// IsBlockEntry
	bool Scanner::IsBlockEntry()
	{
		if(INPUT.peek() != Keys::BlockEntry)
			return false;

		INPUT.get();

		// then needs a blank character (or eof)
		if(!IsBlank()) {
			INPUT.putback(Keys::BlockEntry);
			return false;
		}

		INPUT.putback(Keys::BlockEntry);
		return true;
	}

	// IsKey
	bool Scanner::IsKey()
	{
		if(INPUT.peek() != Keys::Key)
			return false;

		INPUT.get();

		// then needs a blank character (or eof), if we're in block context
		if(m_flowLevel == 0 && !IsBlank()) {
			INPUT.putback(Keys::BlockEntry);
			return false;
		}

		INPUT.putback(Keys::BlockEntry);
		return true;
	}

	// IsValue
	bool Scanner::IsValue()
	{
		if(INPUT.peek() != Keys::Value)
			return false;

		INPUT.get();

		// then needs a blank character (or eof), if we're in block context
		if(m_flowLevel == 0 && !IsBlank()) {
			INPUT.putback(Keys::BlockEntry);
			return false;
		}

		INPUT.putback(Keys::BlockEntry);
		return true;
	}

	// IsPlainScalar
	// . Rules:
	//   . Cannot start with a blank.
	//   . Can never start with any of , [ ] { } # & * ! | > \' \" % @ `
	//   . In the block context - ? : must be not be followed with a space.
	//   . In the flow context ? : are illegal and - must not be followed with a space.
	bool Scanner::IsPlainScalar()
	{
		if(IsBlank())
			return false;

		// never characters
		std::string never = ",[]{}#&*!|>\'\"%@`";
		for(unsigned i=0;i<never.size();i++)
			if(INPUT.peek() == never[i])
				return false;

		// specific block/flow characters
		if(m_flowLevel == 0) {
			if(INPUT.peek() == '-' || INPUT.peek() == '?' || INPUT.peek() == ':') {
				char ch = INPUT.get();
				if(IsBlank()) {
					INPUT.putback(ch);
					return false;
				}
			}
		} else {
			if(INPUT.peek() == '?' || INPUT.peek() == ':')
				return false;
			if(INPUT.peek() == '-') {
				INPUT.get();
				if(IsBlank()) {
					INPUT.putback('-');
					return false;
				}
			}
		}

		return true;
	}

beder's avatar
beder committed
264
265
266
	///////////////////////////////////////////////////////////////////////
	// Specialization for scanning specific tokens

beder's avatar
beder committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
	// ScanAndEnqueue
	// . Scans the token, then pushes it in the queue.
	// . Note: we also use a set of "limbo tokens", i.e., tokens
	//   that haven't yet been pushed. This way, if ScanToken()
	//   throws an exception, we'll be keeping track of 'pToken'
	//   somewhere, and it will be automatically cleaned up when
	//   the Scanner destructs.
	template <typename T> void Scanner::ScanAndEnqueue(T *pToken)
	{
		m_limboTokens.insert(pToken);
		m_tokens.push(ScanToken(pToken));
		m_limboTokens.erase(pToken);
	}

beder's avatar
beder committed
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
	// StreamStartToken
	template <> StreamStartToken *Scanner::ScanToken(StreamStartToken *pToken)
	{
		m_startedStream = true;
		m_simpleKeyAllowed = true;
		m_indents.push(-1);

		return pToken;
	}

	// StreamEndToken
	template <> StreamEndToken *Scanner::ScanToken(StreamEndToken *pToken)
	{
		// force newline
		if(m_column > 0)
			m_column = 0;

beder's avatar
beder committed
298
		PopIndentTo(-1);
beder's avatar
beder committed
299
300
301
302
303
304
305
306
307
308
		// TODO: "reset simple keys"

		m_simpleKeyAllowed = false;

		return pToken;
	}

	// DocumentStartToken
	template <> DocumentStartToken *Scanner::ScanToken(DocumentStartToken *pToken)
	{
beder's avatar
beder committed
309
310
		PopIndentTo(m_column);
		// TODO: "reset simple keys"
beder's avatar
beder committed
311
312
313
314
315
316
317
318
319
320
321
322

		m_simpleKeyAllowed = false;

		// eat it
		EatDocumentStart();

		return pToken;
	}

	// DocumentEndToken
	template <> DocumentEndToken *Scanner::ScanToken(DocumentEndToken *pToken)
	{
beder's avatar
beder committed
323
324
		PopIndentTo(m_column);
		// TODO: "reset simple keys"
beder's avatar
beder committed
325
326
327
328
329
330
331
332
333

		m_simpleKeyAllowed = false;

		// eat it
		EatDocumentEnd();

		return pToken;
	}

beder's avatar
beder committed
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
	// FlowSeqStartToken
	template <> FlowSeqStartToken *Scanner::ScanToken(FlowSeqStartToken *pToken)
	{
		// TODO: "save simple key"
		// TODO: increase flow level

		m_simpleKeyAllowed = true;

		// eat it
		INPUT.get();

		return pToken;
	}

	// FlowMapStartToken
	template <> FlowMapStartToken *Scanner::ScanToken(FlowMapStartToken *pToken)
	{
		// TODO: "save simple key"
		// TODO: increase flow level

		m_simpleKeyAllowed = true;

		// eat it
		INPUT.get();

		return pToken;
	}

	// FlowSeqEndToken
	template <> FlowSeqEndToken *Scanner::ScanToken(FlowSeqEndToken *pToken)
	{
		// TODO: "remove simple key"
		// TODO: decrease flow level

		m_simpleKeyAllowed = false;

		// eat it
		INPUT.get();

		return pToken;
	}

	// FlowMapEndToken
	template <> FlowMapEndToken *Scanner::ScanToken(FlowMapEndToken *pToken)
	{
		// TODO: "remove simple key"
		// TODO: decrease flow level

		m_simpleKeyAllowed = false;

		// eat it
		INPUT.get();

		return pToken;
	}

	// FlowEntryToken
	template <> FlowEntryToken *Scanner::ScanToken(FlowEntryToken *pToken)
	{
		// TODO: "remove simple key"

		m_simpleKeyAllowed = true;

		// eat it
		INPUT.get();

		return pToken;
	}

	// BlockEntryToken
	template <> BlockEntryToken *Scanner::ScanToken(BlockEntryToken *pToken)
	{
		// we better be in the block context!
		if(m_flowLevel == 0) {
			// can we put it here?
			if(!m_simpleKeyAllowed)
				throw IllegalBlockEntry();

			PushIndentTo(m_column, true);	// , -1
		} else {
			// TODO: throw?
		}

		// TODO: "remove simple key"

		m_simpleKeyAllowed = true;

		// eat
		INPUT.get();
		return pToken;
	}

	// KeyToken
	template <> KeyToken *Scanner::ScanToken(KeyToken *pToken)
	{
		// are we in block context?
		if(m_flowLevel == 0) {
			if(!m_simpleKeyAllowed)
				throw IllegalMapKey();

			PushIndentTo(m_column, false);
		}

		// TODO: "remove simple key"

		// can only put a simple key here if we're in block context
		if(m_flowLevel == 0)
			m_simpleKeyAllowed = true;
		else
			m_simpleKeyAllowed = false;

		// eat
		INPUT.get();
		return pToken;
	}

	// ValueToken
	template <> ValueToken *Scanner::ScanToken(ValueToken *pToken)
	{
		// TODO: Is it a simple key?
		if(false) {
		} else {
			// If not, ...
			// are we in block context?
			if(m_flowLevel == 0) {
				if(!m_simpleKeyAllowed)
					throw IllegalMapValue();

				PushIndentTo(m_column, false);
			}
		}

		// can only put a simple key here if we're in block context
		if(m_flowLevel == 0)
			m_simpleKeyAllowed = true;
		else
			m_simpleKeyAllowed = false;

		// eat
		INPUT.get();
		return pToken;
	}

	// PlainScalarToken
	template <> PlainScalarToken *Scanner::ScanToken(PlainScalarToken *pToken)
	{
		// TODO: "save simple key"

		m_simpleKeyAllowed = false;

		// now eat and store the scalar
		while(1) {
			// doc start/end tokens
			if(IsDocumentStart() || IsDocumentEnd())
				break;

			// comment
			if(INPUT.peek() == Keys::Comment)
				break;

			// first eat non-blanks
			while(!IsBlank()) {
				// illegal colon in flow context
				if(m_flowLevel > 0 && INPUT.peek() == ':') {
					INPUT.get();
					if(!IsBlank()) {
						INPUT.putback(':');
						throw IllegalScalar();
					}
					INPUT.putback(':');
				}

				// characters that might end the scalar
				// TODO: scanner.c line 3434
			}
		}

		return pToken;
	}

beder's avatar
beder committed
514
515
516
	///////////////////////////////////////////////////////////////////////
	// The main scanning function

beder's avatar
beder committed
517
	void Scanner::ScanNextToken()
beder's avatar
beder committed
518
519
	{
		if(!m_startedStream)
beder's avatar
beder committed
520
			return ScanAndEnqueue(new StreamStartToken);
beder's avatar
beder committed
521
522
523

		ScanToNextToken();
		// TODO: remove "obsolete potential simple keys"
beder's avatar
beder committed
524
		PopIndentTo(m_column);
beder's avatar
beder committed
525
526

		if(INPUT.peek() == EOF)
beder's avatar
beder committed
527
			return ScanAndEnqueue(new StreamEndToken);
beder's avatar
beder committed
528

beder's avatar
beder committed
529
		// are we at a document token?
beder's avatar
beder committed
530
		if(IsDocumentStart())
beder's avatar
beder committed
531
			return ScanAndEnqueue(new DocumentStartToken);
beder's avatar
beder committed
532
533

		if(IsDocumentEnd())
beder's avatar
beder committed
534
			return ScanAndEnqueue(new DocumentEndToken);
beder's avatar
beder committed
535

beder's avatar
beder committed
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
		// are we at a flow start/end/entry?
		if(INPUT.peek() == Keys::FlowSeqStart)
			return ScanAndEnqueue(new FlowSeqStartToken);

		if(INPUT.peek() == Keys::FlowSeqEnd)
			return ScanAndEnqueue(new FlowSeqEndToken);
		
		if(INPUT.peek() == Keys::FlowMapStart)
			return ScanAndEnqueue(new FlowMapStartToken);
		
		if(INPUT.peek() == Keys::FlowMapEnd)
			return ScanAndEnqueue(new FlowMapEndToken);

		if(INPUT.peek() == Keys::FlowEntry)
			return ScanAndEnqueue(new FlowEntryToken);

		// block/map stuff?
		if(IsBlockEntry())
			return ScanAndEnqueue(new BlockEntryToken);

		if(IsKey())
			return ScanAndEnqueue(new KeyToken);

		if(IsValue())
			return ScanAndEnqueue(new ValueToken);

		// TODO: alias/anchor/tag

		// TODO: special scalars
		if(INPUT.peek() == Keys::LiteralScalar && m_flowLevel == 0)
			return;

		if(INPUT.peek() == Keys::FoldedScalar && m_flowLevel == 0)
			return;

		if(INPUT.peek() == '\'')
			return;

		if(INPUT.peek() == '\"')
			return;

		// plain scalars
		if(IsPlainScalar())
			return ScanAndEnqueue(new PlainScalarToken);

		// don't know what it is!
		throw UnknownToken();
beder's avatar
beder committed
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
	}

	// ScanToNextToken
	// . Eats input until we reach the next token-like thing.
	void Scanner::ScanToNextToken()
	{
		while(1) {
			// first eat whitespace
			while(IsWhitespaceToBeEaten())
				INPUT.get();

			// then eat a comment
			if(INPUT.peek() == Keys::Comment) {
				// eat until line break
				while(INPUT && !IsLineBreak())
					INPUT.get();
			}

			// if it's NOT a line break, then we're done!
			if(!IsLineBreak())
				break;

			// otherwise, let's eat the line break and keep going
			EatLineBreak();

			// new line - we may be able to accept a simple key now
			if(m_flowLevel == 0)
				m_simpleKeyAllowed = true;
        }
	}

beder's avatar
beder committed
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
	// PushIndentTo
	// . Pushes an indentation onto the stack, and enqueues the
	//   proper token (sequence start or mapping start).
	void Scanner::PushIndentTo(int column, bool sequence)
	{
		// are we in flow?
		if(m_flowLevel > 0)
			return;

		// is this actually an indentation?
		if(column <= m_indents.top())
			return;

		// now push
		m_indents.push(column);
		if(sequence)
			m_tokens.push(new BlockSeqStartToken);
		else
			m_tokens.push(new BlockMapStartToken);
	}

	// PopIndentTo
	// . Pops indentations off the stack until we reach 'column' indentation,
	//   and enqueues the proper token each time.
	void Scanner::PopIndentTo(int column)
	{
		// are we in flow?
		if(m_flowLevel > 0)
			return;

		// now pop away
		while(!m_indents.empty() && m_indents.top() > column) {
			m_indents.pop();
			m_tokens.push(new BlockEndToken);
		}
	}

beder's avatar
beder committed
651
652
653
	// temporary function for testing
	void Scanner::Scan()
	{
beder's avatar
beder committed
654
655
		while(INPUT)
			ScanNextToken();
beder's avatar
beder committed
656
657
	}
}