scanner.cpp 9.47 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
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
	{
	}

	Scanner::~Scanner()
	{
	}

	// 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();
32
		if(!m_tokens.empty())
33
34
35
36
37
38
39
40
41
42
43
			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.

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

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

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

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

110
		if(INPUT.column() == 0 && INPUT.peek() == Keys::Directive)
111
112
113
			return ScanDirective();

		// document token
114
		if(INPUT.column() == 0 && Exp::DocStart().Matches(INPUT))
115
116
			return ScanDocStart();

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

134
		if((InBlockContext() ? Exp::Key() : Exp::KeyInFlow()).Matches(INPUT))
135
136
			return ScanKey();

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

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

		// plain scalars
156
		if((InBlockContext() ? Exp::PlainScalar() : Exp::PlainScalarInFlow()).Matches(INPUT))
157
158
159
			return ScanPlainScalar();

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

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

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

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

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

			// oh yeah, and let's get rid of that simple key
191
			InvalidateSimpleKey();
192
193

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

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

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

215
		if(ch == '\t')
216
217
218
219
220
			return true;

		return false;
	}

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

231
232
233
234
235
236
	// StartStream
	// . Set the initial conditions for starting a stream.
	void Scanner::StartStream()
	{
		m_startedStream = true;
		m_simpleKeyAllowed = true;
237
		std::auto_ptr<IndentMarker> pIndent(new IndentMarker(-1, IndentMarker::NONE));
238
		m_indentRefs.push_back(pIndent);
239
		m_indents.push(&m_indentRefs.back());
240
241
242
243
244
245
246
	}

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

250
		PopAllIndents();
251
		PopAllSimpleKeys();
252
253
254
255
256

		m_simpleKeyAllowed = false;
		m_endedStream = true;
	}

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

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

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

294
		// push a start token
295
		indent.pStartToken = PushToken(GetStartTokenFor(type));
296

297
		// and then the indent
298
		m_indents.push(&indent);
299
300
		m_indentRefs.push_back(pIndent);
		return &m_indentRefs.back();
301
302
	}

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

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

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

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

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

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