scanner.cpp 9.55 KB
Newer Older
1
2
#include "scanner.h"
#include "token.h"
3
#include "yaml-cpp/exceptions.h"
4
5
#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
		if(!m_tokens.empty())
36
37
38
39
40
41
42
43
44
45
46
			m_tokens.pop();
	}

	// 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.

47
48
49
50
51
52
53
#if 0
		static Token *pLast = 0;
		if(pLast != &m_tokens.front())
			std::cerr << "peek: " << m_tokens.front() << "\n";
		pLast = &m_tokens.front();
#endif

54
55
56
57
58
59
60
61
62
63
64
65
66
		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
67
				if(token.status == Token::VALID)
68
69
70
					return;

				// here's where we clean up the impossible tokens
71
				if(token.status == Token::INVALID) {
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
					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
103
		PopIndentToHere();
104
105
106
107

		// *****
		// And now branch based on the next few characters!
		// *****
108
		
109
		// end of stream
110
		if(!INPUT)
111
112
			return EndStream();

113
		if(INPUT.column() == 0 && INPUT.peek() == Keys::Directive)
114
115
116
			return ScanDirective();

		// document token
117
		if(INPUT.column() == 0 && Exp::DocStart().Matches(INPUT))
118
119
			return ScanDocStart();

120
		if(INPUT.column() == 0 && Exp::DocEnd().Matches(INPUT))
121
122
123
124
125
126
127
128
129
130
131
132
133
			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
134
		if(Exp::BlockEntry().Matches(INPUT))
135
136
			return ScanBlockEntry();

137
		if((InBlockContext() ? Exp::Key() : Exp::KeyInFlow()).Matches(INPUT))
138
139
			return ScanKey();

140
		if(GetValueRegex().Matches(INPUT))
141
142
143
144
145
146
147
148
149
150
151
			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
152
		if(InBlockContext() && (INPUT.peek() == Keys::LiteralScalar || INPUT.peek() == Keys::FoldedScalar))
153
154
155
156
157
158
			return ScanBlockScalar();

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

		// plain scalars
159
		if((InBlockContext() ? Exp::PlainScalar() : Exp::PlainScalarInFlow()).Matches(INPUT))
160
161
162
			return ScanPlainScalar();

		// don't know what it is!
163
		throw ParserException(INPUT.mark(), ErrorMsg::UNKNOWN_TOKEN);
164
165
166
167
168
169
170
171
	}

	// ScanToNextToken
	// . Eats input until we reach the next token-like thing.
	void Scanner::ScanToNextToken()
	{
		while(1) {
			// first eat whitespace
172
			while(INPUT && IsWhitespaceToBeEaten(INPUT.peek())) {
173
				if(InBlockContext() && Exp::Tab().Matches(INPUT))
174
					m_simpleKeyAllowed = false;
175
				INPUT.eat(1);
176
			}
177
178

			// then eat a comment
179
			if(Exp::Comment().Matches(INPUT)) {
180
				// eat until line break
181
				while(INPUT && !Exp::Break().Matches(INPUT))
182
183
184
185
					INPUT.eat(1);
			}

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

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

			// oh yeah, and let's get rid of that simple key
194
			InvalidateSimpleKey();
195
196

			// new line - we may be able to accept a simple key now
197
			if(InBlockContext())
198
199
200
201
202
203
204
205
				m_simpleKeyAllowed = true;
        }
	}

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

	// IsWhitespaceToBeEaten
206
207
208
209
210
211
212
	// . 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
213
214
215
216
217
	bool Scanner::IsWhitespaceToBeEaten(char ch)
	{
		if(ch == ' ')
			return true;

218
		if(ch == '\t')
219
220
221
222
223
			return true;

		return false;
	}

224
225
226
227
228
	// GetValueRegex
	// . Get the appropriate regex to check if it's a value token
	const RegEx& Scanner::GetValueRegex() const
	{
		if(InBlockContext())
229
			return Exp::Value();
230
		
231
		return m_canBeJSONFlow ? Exp::ValueInJSONFlow() : Exp::ValueInFlow();
232
233
	}

234
235
236
237
238
239
	// StartStream
	// . Set the initial conditions for starting a stream.
	void Scanner::StartStream()
	{
		m_startedStream = true;
		m_simpleKeyAllowed = true;
240
241
242
		IndentMarker *pIndent = new IndentMarker(-1, IndentMarker::NONE);
		m_indentRefs.push_back(pIndent);
		m_indents.push(pIndent);
243
244
245
246
247
248
249
	}

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

253
		PopAllIndents();
254
		PopAllSimpleKeys();
255
256
257
258
259

		m_simpleKeyAllowed = false;
		m_endedStream = true;
	}

260
261
262
263
264
265
266
267
268
269
270
271
272
273
	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);
274
		throw std::runtime_error("yaml-cpp: internal error, invalid indent type");
275
276
	}

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

		// is this actually an indentation?
292
293
294
		if(indent.column < lastIndent.column)
			return 0;
		if(indent.column == lastIndent.column && !(indent.type == IndentMarker::SEQ && lastIndent.type == IndentMarker::MAP))
295
296
			return 0;

297
		// push a start token
298
		indent.pStartToken = PushToken(GetStartTokenFor(type));
299

300
		// and then the indent
301
302
303
		m_indents.push(&indent);
		m_indentRefs.push_back(pIndent.release());
		return m_indentRefs.back();
304
305
	}

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

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

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

		if(indent.status != IndentMarker::VALID) {
358
			InvalidateSimpleKey();
359
			return;
360
		}
361
		
362
		if(indent.type == IndentMarker::SEQ)
363
			m_tokens.push(Token(Token::BLOCK_SEQ_END, INPUT.mark()));
364
		else if(indent.type == IndentMarker::MAP)
365
			m_tokens.push(Token(Token::BLOCK_MAP_END, INPUT.mark()));
366
367
368
369
370
371
372
	}

	// GetTopIndent
	int Scanner::GetTopIndent() const
	{
		if(m_indents.empty())
			return 0;
373
		return m_indents.top()->column;
374
	}
375
376
377
378
379
380
381

	// 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
	{
382
		Mark mark = Mark::null();
383
384
		if(!m_tokens.empty()) {
			const Token& token = m_tokens.front();
385
			mark = token.mark;
386
		}
387
		throw ParserException(mark, msg);
388
	}
389
}
390