scanner.cpp 10.3 KB
Newer Older
1
2
3
4
5
#include "scanner.h"
#include "token.h"
#include "exceptions.h"
#include "exp.h"
#include <cassert>
6
#include <memory>
7
8
9
10

namespace YAML
{
	Scanner::Scanner(std::istream& in)
11
		: INPUT(in), m_startedStream(false), m_endedStream(false), m_simpleKeyAllowed(false), m_canBeJSONFlow(false)
12
13
14
15
16
	{
	}

	Scanner::~Scanner()
	{
17
18
19
		for(unsigned i=0;i<m_indentRefs.size();i++)
			delete m_indentRefs[i];
		m_indentRefs.clear();
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
	}

	// empty
	// . Returns true if there are no more tokens to be read
	bool Scanner::empty()
	{
		EnsureTokensInQueue();
		return m_tokens.empty();
	}

	// pop
	// . Simply removes the next token on the queue.
	void Scanner::pop()
	{
		EnsureTokensInQueue();
35
36
		if(!m_tokens.empty()) {
			// Saved anchors shouldn't survive popping the document end marker
37
			if (m_tokens.front().type == Token::DOC_END) {
38
39
				ClearAnchors();
			}
40
			m_tokens.pop();
41
		}
42
43
44
45
46
47
48
49
50
51
	}

	// peek
	// . Returns (but does not remove) the next token on the queue.
	Token& Scanner::peek()
	{
		EnsureTokensInQueue();
		assert(!m_tokens.empty());  // should we be asserting here? I mean, we really just be checking
		                            // if it's empty before peeking.

52
53
54
55
56
57
58
#if 0
		static Token *pLast = 0;
		if(pLast != &m_tokens.front())
			std::cerr << "peek: " << m_tokens.front() << "\n";
		pLast = &m_tokens.front();
#endif

59
60
61
62
63
64
65
66
67
68
69
70
71
		return m_tokens.front();
	}

	// EnsureTokensInQueue
	// . Scan until there's a valid token at the front of the queue,
	//   or we're sure the queue is empty.
	void Scanner::EnsureTokensInQueue()
	{
		while(1) {
			if(!m_tokens.empty()) {
				Token& token = m_tokens.front();

				// if this guy's valid, then we're done
72
				if(token.status == Token::VALID)
73
74
75
					return;

				// here's where we clean up the impossible tokens
76
				if(token.status == Token::INVALID) {
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
					m_tokens.pop();
					continue;
				}

				// note: what's left are the unverified tokens
			}

			// no token? maybe we've actually finished
			if(m_endedStream)
				return;

			// no? then scan...
			ScanNextToken();
		}
	}

	// ScanNextToken
	// . The main scanning function; here we branch out and
	//   scan whatever the next token should be.
	void Scanner::ScanNextToken()
	{
		if(m_endedStream)
			return;

		if(!m_startedStream)
			return StartStream();

		// get rid of whitespace, etc. (in between tokens it should be irrelevent)
		ScanToNextToken();

		// maybe need to end some blocks
108
		PopIndentToHere();
109
110
111
112

		// *****
		// And now branch based on the next few characters!
		// *****
113
		
114
		// end of stream
115
		if(!INPUT)
116
117
			return EndStream();

118
		if(INPUT.column() == 0 && INPUT.peek() == Keys::Directive)
119
120
121
			return ScanDirective();

		// document token
122
		if(INPUT.column() == 0 && Exp::DocStart.Matches(INPUT))
123
124
			return ScanDocStart();

125
		if(INPUT.column() == 0 && Exp::DocEnd.Matches(INPUT))
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
			return ScanDocEnd();

		// flow start/end/entry
		if(INPUT.peek() == Keys::FlowSeqStart || INPUT.peek() == Keys::FlowMapStart)
			return ScanFlowStart();

		if(INPUT.peek() == Keys::FlowSeqEnd || INPUT.peek() == Keys::FlowMapEnd)
			return ScanFlowEnd();
	
		if(INPUT.peek() == Keys::FlowEntry)
			return ScanFlowEntry();

		// block/map stuff
		if(Exp::BlockEntry.Matches(INPUT))
			return ScanBlockEntry();

142
		if((InBlockContext() ? Exp::Key : Exp::KeyInFlow).Matches(INPUT))
143
144
			return ScanKey();

145
		if(GetValueRegex().Matches(INPUT))
146
147
148
149
150
151
152
153
154
155
156
			return ScanValue();

		// alias/anchor
		if(INPUT.peek() == Keys::Alias || INPUT.peek() == Keys::Anchor)
			return ScanAnchorOrAlias();

		// tag
		if(INPUT.peek() == Keys::Tag)
			return ScanTag();

		// special scalars
157
		if(InBlockContext() && (INPUT.peek() == Keys::LiteralScalar || INPUT.peek() == Keys::FoldedScalar))
158
159
160
161
162
163
			return ScanBlockScalar();

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

		// plain scalars
164
		if((InBlockContext() ? Exp::PlainScalar : Exp::PlainScalarInFlow).Matches(INPUT))
165
166
167
			return ScanPlainScalar();

		// don't know what it is!
168
		throw ParserException(INPUT.mark(), ErrorMsg::UNKNOWN_TOKEN);
169
170
171
172
173
174
175
176
	}

	// ScanToNextToken
	// . Eats input until we reach the next token-like thing.
	void Scanner::ScanToNextToken()
	{
		while(1) {
			// first eat whitespace
177
178
179
			while(INPUT && IsWhitespaceToBeEaten(INPUT.peek())) {
				if(InBlockContext() && Exp::Tab.Matches(INPUT))
					m_simpleKeyAllowed = false;
180
				INPUT.eat(1);
181
			}
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198

			// then eat a comment
			if(Exp::Comment.Matches(INPUT)) {
				// eat until line break
				while(INPUT && !Exp::Break.Matches(INPUT))
					INPUT.eat(1);
			}

			// if it's NOT a line break, then we're done!
			if(!Exp::Break.Matches(INPUT))
				break;

			// otherwise, let's eat the line break and keep going
			int n = Exp::Break.Match(INPUT);
			INPUT.eat(n);

			// oh yeah, and let's get rid of that simple key
199
			InvalidateSimpleKey();
200
201

			// new line - we may be able to accept a simple key now
202
			if(InBlockContext())
203
204
205
206
207
208
209
210
				m_simpleKeyAllowed = true;
        }
	}

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

	// IsWhitespaceToBeEaten
211
212
213
214
215
216
217
	// . We can eat whitespace if it's a space or tab
	// . Note: originally tabs in block context couldn't be eaten
	//         "where a simple key could be allowed
	//         (i.e., not at the beginning of a line, or following '-', '?', or ':')"
	//   I think this is wrong, since tabs can be non-content whitespace; it's just
	//   that they can't contribute to indentation, so once you've seen a tab in a
	//   line, you can't start a simple key
218
219
220
221
222
	bool Scanner::IsWhitespaceToBeEaten(char ch)
	{
		if(ch == ' ')
			return true;

223
		if(ch == '\t')
224
225
226
227
228
			return true;

		return false;
	}

229
230
231
232
233
234
235
236
237
238
	// GetValueRegex
	// . Get the appropriate regex to check if it's a value token
	const RegEx& Scanner::GetValueRegex() const
	{
		if(InBlockContext())
			return Exp::Value;
		
		return m_canBeJSONFlow ? Exp::ValueInJSONFlow : Exp::ValueInFlow;
	}

239
240
241
242
243
244
	// StartStream
	// . Set the initial conditions for starting a stream.
	void Scanner::StartStream()
	{
		m_startedStream = true;
		m_simpleKeyAllowed = true;
245
246
247
		IndentMarker *pIndent = new IndentMarker(-1, IndentMarker::NONE);
		m_indentRefs.push_back(pIndent);
		m_indents.push(pIndent);
248
		m_anchors.clear();
249
250
251
252
253
254
255
	}

	// EndStream
	// . Close out the stream, finish up, etc.
	void Scanner::EndStream()
	{
		// force newline
256
257
		if(INPUT.column() > 0)
			INPUT.ResetColumn();
258

259
		PopAllIndents();
260
		PopAllSimpleKeys();
261
262
263
264
265

		m_simpleKeyAllowed = false;
		m_endedStream = true;
	}

266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
	Token *Scanner::PushToken(Token::TYPE type)
	{
		m_tokens.push(Token(type, INPUT.mark()));
		return &m_tokens.back();
	}

	Token::TYPE Scanner::GetStartTokenFor(IndentMarker::INDENT_TYPE type) const
	{
		switch(type) {
			case IndentMarker::SEQ: return Token::BLOCK_SEQ_START;
			case IndentMarker::MAP: return Token::BLOCK_MAP_START;
			case IndentMarker::NONE: assert(false); break;
		}
		assert(false);
	}

282
283
284
	// PushIndentTo
	// . Pushes an indentation onto the stack, and enqueues the
	//   proper token (sequence start or mapping start).
285
286
	// . Returns the indent marker it generates (if any).
	Scanner::IndentMarker *Scanner::PushIndentTo(int column, IndentMarker::INDENT_TYPE type)
287
288
	{
		// are we in flow?
289
		if(InFlowContext())
290
			return 0;
291
		
292
293
294
		std::auto_ptr<IndentMarker> pIndent(new IndentMarker(column, type));
		IndentMarker& indent = *pIndent;
		const IndentMarker& lastIndent = *m_indents.top();
295
296

		// is this actually an indentation?
297
298
299
		if(indent.column < lastIndent.column)
			return 0;
		if(indent.column == lastIndent.column && !(indent.type == IndentMarker::SEQ && lastIndent.type == IndentMarker::MAP))
300
301
			return 0;

302
		// push a start token
303
		indent.pStartToken = PushToken(GetStartTokenFor(type));
304

305
		// and then the indent
306
307
308
		m_indents.push(&indent);
		m_indentRefs.push_back(pIndent.release());
		return m_indentRefs.back();
309
310
	}

311
312
	// PopIndentToHere
	// . Pops indentations off the stack until we reach the current indentation level,
313
	//   and enqueues the proper token each time.
314
	// . Then pops all invalid indentations off.
315
	void Scanner::PopIndentToHere()
316
317
	{
		// are we in flow?
318
		if(InFlowContext())
319
320
321
			return;

		// now pop away
322
		while(!m_indents.empty()) {
323
			const IndentMarker& indent = *m_indents.top();
324
325
326
327
328
329
			if(indent.column < INPUT.column())
				break;
			if(indent.column == INPUT.column() && !(indent.type == IndentMarker::SEQ && !Exp::BlockEntry.Matches(INPUT)))
				break;
				
			PopIndent();
330
		}
331
332
333
		
		while(!m_indents.empty() && m_indents.top()->status == IndentMarker::INVALID)
			PopIndent();
334
	}
335
336
	
	// PopAllIndents
337
	// . Pops all indentations (except for the base empty one) off the stack,
338
339
340
341
	//   and enqueues the proper token each time.
	void Scanner::PopAllIndents()
	{
		// are we in flow?
342
		if(InFlowContext())
343
344
345
			return;

		// now pop away
346
		while(!m_indents.empty()) {
347
			const IndentMarker& indent = *m_indents.top();
348
349
350
			if(indent.type == IndentMarker::NONE)
				break;
			
351
			PopIndent();
352
		}
353
354
355
356
357
358
	}
	
	// PopIndent
	// . Pops a single indent, pushing the proper token
	void Scanner::PopIndent()
	{
359
		const IndentMarker& indent = *m_indents.top();
360
		m_indents.pop();
361
362

		if(indent.status != IndentMarker::VALID) {
363
			InvalidateSimpleKey();
364
			return;
365
		}
366
		
367
		if(indent.type == IndentMarker::SEQ)
368
			m_tokens.push(Token(Token::BLOCK_SEQ_END, INPUT.mark()));
369
		else if(indent.type == IndentMarker::MAP)
370
			m_tokens.push(Token(Token::BLOCK_MAP_END, INPUT.mark()));
371
372
373
374
375
376
377
	}

	// GetTopIndent
	int Scanner::GetTopIndent() const
	{
		if(m_indents.empty())
			return 0;
378
		return m_indents.top()->column;
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

	// Save
	// . Saves a pointer to the Node object referenced by a particular anchor
	//   name.
	void Scanner::Save(const std::string& anchor, Node* value)
	{
		m_anchors[anchor] = value;
	}

	// Retrieve
	// . Retrieves a pointer previously saved for an anchor name.
	// . Throws an exception if the anchor has not been defined.
	const Node *Scanner::Retrieve(const std::string& anchor) const
	{
		typedef std::map<std::string, const Node *> map;

		map::const_iterator itNode = m_anchors.find(anchor);

		if(m_anchors.end() == itNode)
			ThrowParserException(ErrorMsg::UNKNOWN_ANCHOR);

		return itNode->second;
	}

	// ThrowParserException
	// . Throws a ParserException with the current token location
	//   (if available).
	// . Does not parse any more tokens.
	void Scanner::ThrowParserException(const std::string& msg) const
	{
410
		Mark mark = Mark::null();
411
412
		if(!m_tokens.empty()) {
			const Token& token = m_tokens.front();
413
			mark = token.mark;
414
		}
415
		throw ParserException(mark, msg);
416
417
418
419
420
421
	}

	void Scanner::ClearAnchors()
	{
		m_anchors.clear();
	}
422
}
423