blob: b9bbdc33a4333d63c0798a26f85daa5bb2220b97 [file] [log] [blame]
Eugene Zelenko72208a82017-06-21 23:19:47 +00001//===- YAMLParser.cpp - Simple YAML parser --------------------------------===//
Michael J. Spencer22120c42012-04-03 23:09:22 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Michael J. Spencer22120c42012-04-03 23:09:22 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements a YAML parser.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Support/YAMLParser.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000014#include "llvm/ADT/AllocatorList.h"
Eugene Zelenko72208a82017-06-21 23:19:47 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/None.h"
David Majnemer0d955d02016-08-11 22:21:41 +000017#include "llvm/ADT/STLExtras.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000018#include "llvm/ADT/SmallString.h"
Michael J. Spencer22120c42012-04-03 23:09:22 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringExtras.h"
Eugene Zelenko72208a82017-06-21 23:19:47 +000021#include "llvm/ADT/StringRef.h"
Michael J. Spencer22120c42012-04-03 23:09:22 +000022#include "llvm/ADT/Twine.h"
Eugene Zelenko72208a82017-06-21 23:19:47 +000023#include "llvm/Support/Compiler.h"
Michael J. Spencer22120c42012-04-03 23:09:22 +000024#include "llvm/Support/ErrorHandling.h"
25#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko72208a82017-06-21 23:19:47 +000026#include "llvm/Support/SMLoc.h"
Michael J. Spencer22120c42012-04-03 23:09:22 +000027#include "llvm/Support/SourceMgr.h"
Graydon Hoare926cd9b2018-03-27 19:52:45 +000028#include "llvm/Support/Unicode.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Support/raw_ostream.h"
Eugene Zelenko72208a82017-06-21 23:19:47 +000030#include <algorithm>
31#include <cassert>
32#include <cstddef>
33#include <cstdint>
34#include <map>
35#include <memory>
36#include <string>
37#include <system_error>
38#include <utility>
Michael J. Spencer22120c42012-04-03 23:09:22 +000039
40using namespace llvm;
41using namespace yaml;
42
43enum UnicodeEncodingForm {
Dmitri Gribenkodbeafa72012-06-09 00:01:45 +000044 UEF_UTF32_LE, ///< UTF-32 Little Endian
45 UEF_UTF32_BE, ///< UTF-32 Big Endian
46 UEF_UTF16_LE, ///< UTF-16 Little Endian
47 UEF_UTF16_BE, ///< UTF-16 Big Endian
48 UEF_UTF8, ///< UTF-8 or ascii.
49 UEF_Unknown ///< Not a valid Unicode encoding.
Michael J. Spencer22120c42012-04-03 23:09:22 +000050};
51
52/// EncodingInfo - Holds the encoding type and length of the byte order mark if
53/// it exists. Length is in {0, 2, 3, 4}.
Eugene Zelenko72208a82017-06-21 23:19:47 +000054using EncodingInfo = std::pair<UnicodeEncodingForm, unsigned>;
Michael J. Spencer22120c42012-04-03 23:09:22 +000055
56/// getUnicodeEncoding - Reads up to the first 4 bytes to determine the Unicode
57/// encoding form of \a Input.
58///
59/// @param Input A string of length 0 or more.
60/// @returns An EncodingInfo indicating the Unicode encoding form of the input
61/// and how long the byte order mark is if one exists.
62static EncodingInfo getUnicodeEncoding(StringRef Input) {
Eugene Zelenko72208a82017-06-21 23:19:47 +000063 if (Input.empty())
Michael J. Spencer22120c42012-04-03 23:09:22 +000064 return std::make_pair(UEF_Unknown, 0);
65
66 switch (uint8_t(Input[0])) {
67 case 0x00:
68 if (Input.size() >= 4) {
69 if ( Input[1] == 0
70 && uint8_t(Input[2]) == 0xFE
71 && uint8_t(Input[3]) == 0xFF)
72 return std::make_pair(UEF_UTF32_BE, 4);
73 if (Input[1] == 0 && Input[2] == 0 && Input[3] != 0)
74 return std::make_pair(UEF_UTF32_BE, 0);
75 }
76
77 if (Input.size() >= 2 && Input[1] != 0)
78 return std::make_pair(UEF_UTF16_BE, 0);
79 return std::make_pair(UEF_Unknown, 0);
80 case 0xFF:
81 if ( Input.size() >= 4
82 && uint8_t(Input[1]) == 0xFE
83 && Input[2] == 0
84 && Input[3] == 0)
85 return std::make_pair(UEF_UTF32_LE, 4);
86
87 if (Input.size() >= 2 && uint8_t(Input[1]) == 0xFE)
88 return std::make_pair(UEF_UTF16_LE, 2);
89 return std::make_pair(UEF_Unknown, 0);
90 case 0xFE:
91 if (Input.size() >= 2 && uint8_t(Input[1]) == 0xFF)
92 return std::make_pair(UEF_UTF16_BE, 2);
93 return std::make_pair(UEF_Unknown, 0);
94 case 0xEF:
95 if ( Input.size() >= 3
96 && uint8_t(Input[1]) == 0xBB
97 && uint8_t(Input[2]) == 0xBF)
98 return std::make_pair(UEF_UTF8, 3);
99 return std::make_pair(UEF_Unknown, 0);
100 }
101
102 // It could still be utf-32 or utf-16.
103 if (Input.size() >= 4 && Input[1] == 0 && Input[2] == 0 && Input[3] == 0)
104 return std::make_pair(UEF_UTF32_LE, 0);
105
106 if (Input.size() >= 2 && Input[1] == 0)
107 return std::make_pair(UEF_UTF16_LE, 0);
108
109 return std::make_pair(UEF_UTF8, 0);
110}
111
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000112/// Pin the vtables to this file.
113void Node::anchor() {}
114void NullNode::anchor() {}
115void ScalarNode::anchor() {}
Alex Lorenza22b250c2015-05-13 23:10:51 +0000116void BlockScalarNode::anchor() {}
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000117void KeyValueNode::anchor() {}
118void MappingNode::anchor() {}
119void SequenceNode::anchor() {}
120void AliasNode::anchor() {}
121
Eugene Zelenko72208a82017-06-21 23:19:47 +0000122namespace llvm {
123namespace yaml {
124
Michael J. Spencer22120c42012-04-03 23:09:22 +0000125/// Token - A single YAML token.
Duncan P. N. Exon Smith23d83062016-09-11 22:40:40 +0000126struct Token {
Michael J. Spencer22120c42012-04-03 23:09:22 +0000127 enum TokenKind {
128 TK_Error, // Uninitialized token.
129 TK_StreamStart,
130 TK_StreamEnd,
131 TK_VersionDirective,
132 TK_TagDirective,
133 TK_DocumentStart,
134 TK_DocumentEnd,
135 TK_BlockEntry,
136 TK_BlockEnd,
137 TK_BlockSequenceStart,
138 TK_BlockMappingStart,
139 TK_FlowEntry,
140 TK_FlowSequenceStart,
141 TK_FlowSequenceEnd,
142 TK_FlowMappingStart,
143 TK_FlowMappingEnd,
144 TK_Key,
145 TK_Value,
146 TK_Scalar,
Alex Lorenza22b250c2015-05-13 23:10:51 +0000147 TK_BlockScalar,
Michael J. Spencer22120c42012-04-03 23:09:22 +0000148 TK_Alias,
149 TK_Anchor,
150 TK_Tag
Eugene Zelenko72208a82017-06-21 23:19:47 +0000151 } Kind = TK_Error;
Michael J. Spencer22120c42012-04-03 23:09:22 +0000152
153 /// A string of length 0 or more whose begin() points to the logical location
154 /// of the token in the input.
155 StringRef Range;
156
Alex Lorenza22b250c2015-05-13 23:10:51 +0000157 /// The value of a block scalar node.
158 std::string Value;
159
Eugene Zelenko72208a82017-06-21 23:19:47 +0000160 Token() = default;
Michael J. Spencer22120c42012-04-03 23:09:22 +0000161};
Michael J. Spencer22120c42012-04-03 23:09:22 +0000162
Eugene Zelenko72208a82017-06-21 23:19:47 +0000163} // end namespace yaml
164} // end namespace llvm
165
166using TokenQueueT = BumpPtrList<Token>;
Michael J. Spencer22120c42012-04-03 23:09:22 +0000167
168namespace {
Eugene Zelenko72208a82017-06-21 23:19:47 +0000169
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000170/// This struct is used to track simple keys.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000171///
172/// Simple keys are handled by creating an entry in SimpleKeys for each Token
173/// which could legally be the start of a simple key. When peekNext is called,
174/// if the Token To be returned is referenced by a SimpleKey, we continue
175/// tokenizing until that potential simple key has either been found to not be
176/// a simple key (we moved on to the next line or went further than 1024 chars).
177/// Or when we run into a Value, and then insert a Key token (and possibly
178/// others) before the SimpleKey's Tok.
179struct SimpleKey {
180 TokenQueueT::iterator Tok;
Simon Pilgrimb0d09282019-11-09 22:11:50 +0000181 unsigned Column = 0;
182 unsigned Line = 0;
183 unsigned FlowLevel = 0;
184 bool IsRequired = false;
Michael J. Spencer22120c42012-04-03 23:09:22 +0000185
186 bool operator ==(const SimpleKey &Other) {
187 return Tok == Other.Tok;
188 }
189};
Eugene Zelenko72208a82017-06-21 23:19:47 +0000190
191} // end anonymous namespace
Michael J. Spencer22120c42012-04-03 23:09:22 +0000192
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000193/// The Unicode scalar value of a UTF-8 minimal well-formed code unit
Michael J. Spencer22120c42012-04-03 23:09:22 +0000194/// subsequence and the subsequence's length in code units (uint8_t).
195/// A length of 0 represents an error.
Eugene Zelenko72208a82017-06-21 23:19:47 +0000196using UTF8Decoded = std::pair<uint32_t, unsigned>;
Michael J. Spencer22120c42012-04-03 23:09:22 +0000197
198static UTF8Decoded decodeUTF8(StringRef Range) {
199 StringRef::iterator Position= Range.begin();
200 StringRef::iterator End = Range.end();
201 // 1 byte: [0x00, 0x7f]
202 // Bit pattern: 0xxxxxxx
203 if ((*Position & 0x80) == 0) {
204 return std::make_pair(*Position, 1);
205 }
206 // 2 bytes: [0x80, 0x7ff]
207 // Bit pattern: 110xxxxx 10xxxxxx
208 if (Position + 1 != End &&
209 ((*Position & 0xE0) == 0xC0) &&
210 ((*(Position + 1) & 0xC0) == 0x80)) {
211 uint32_t codepoint = ((*Position & 0x1F) << 6) |
212 (*(Position + 1) & 0x3F);
213 if (codepoint >= 0x80)
214 return std::make_pair(codepoint, 2);
215 }
216 // 3 bytes: [0x8000, 0xffff]
217 // Bit pattern: 1110xxxx 10xxxxxx 10xxxxxx
218 if (Position + 2 != End &&
219 ((*Position & 0xF0) == 0xE0) &&
220 ((*(Position + 1) & 0xC0) == 0x80) &&
221 ((*(Position + 2) & 0xC0) == 0x80)) {
222 uint32_t codepoint = ((*Position & 0x0F) << 12) |
223 ((*(Position + 1) & 0x3F) << 6) |
224 (*(Position + 2) & 0x3F);
225 // Codepoints between 0xD800 and 0xDFFF are invalid, as
226 // they are high / low surrogate halves used by UTF-16.
227 if (codepoint >= 0x800 &&
228 (codepoint < 0xD800 || codepoint > 0xDFFF))
229 return std::make_pair(codepoint, 3);
230 }
231 // 4 bytes: [0x10000, 0x10FFFF]
232 // Bit pattern: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
233 if (Position + 3 != End &&
234 ((*Position & 0xF8) == 0xF0) &&
235 ((*(Position + 1) & 0xC0) == 0x80) &&
236 ((*(Position + 2) & 0xC0) == 0x80) &&
237 ((*(Position + 3) & 0xC0) == 0x80)) {
238 uint32_t codepoint = ((*Position & 0x07) << 18) |
239 ((*(Position + 1) & 0x3F) << 12) |
240 ((*(Position + 2) & 0x3F) << 6) |
241 (*(Position + 3) & 0x3F);
242 if (codepoint >= 0x10000 && codepoint <= 0x10FFFF)
243 return std::make_pair(codepoint, 4);
244 }
245 return std::make_pair(0, 0);
246}
247
248namespace llvm {
249namespace yaml {
Eugene Zelenko72208a82017-06-21 23:19:47 +0000250
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000251/// Scans YAML tokens from a MemoryBuffer.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000252class Scanner {
253public:
Mehdi Amini3ab3fef2016-11-28 21:38:52 +0000254 Scanner(StringRef Input, SourceMgr &SM, bool ShowColors = true,
255 std::error_code *EC = nullptr);
256 Scanner(MemoryBufferRef Buffer, SourceMgr &SM_, bool ShowColors = true,
257 std::error_code *EC = nullptr);
Michael J. Spencer22120c42012-04-03 23:09:22 +0000258
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000259 /// Parse the next token and return it without popping it.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000260 Token &peekNext();
261
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000262 /// Parse the next token and pop it from the queue.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000263 Token getNext();
264
265 void printError(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Message,
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000266 ArrayRef<SMRange> Ranges = None) {
Alex Lorenze4bcfbf2015-05-07 18:08:46 +0000267 SM.PrintMessage(Loc, Kind, Message, Ranges, /* FixIts= */ None, ShowColors);
Michael J. Spencer22120c42012-04-03 23:09:22 +0000268 }
269
270 void setError(const Twine &Message, StringRef::iterator Position) {
Simon Pilgrim22257972020-04-03 18:53:38 +0100271 if (Position >= End)
272 Position = End - 1;
Michael J. Spencer22120c42012-04-03 23:09:22 +0000273
Mehdi Amini3ab3fef2016-11-28 21:38:52 +0000274 // propagate the error if possible
275 if (EC)
276 *EC = make_error_code(std::errc::invalid_argument);
277
Michael J. Spencer22120c42012-04-03 23:09:22 +0000278 // Don't print out more errors after the first one we encounter. The rest
279 // are just the result of the first, and have no meaning.
280 if (!Failed)
Simon Pilgrim22257972020-04-03 18:53:38 +0100281 printError(SMLoc::getFromPointer(Position), SourceMgr::DK_Error, Message);
Michael J. Spencer22120c42012-04-03 23:09:22 +0000282 Failed = true;
283 }
284
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000285 /// Returns true if an error occurred while parsing.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000286 bool failed() {
287 return Failed;
288 }
289
290private:
Rafael Espindola68669e32014-08-27 19:03:22 +0000291 void init(MemoryBufferRef Buffer);
292
Michael J. Spencer22120c42012-04-03 23:09:22 +0000293 StringRef currentInput() {
294 return StringRef(Current, End - Current);
295 }
296
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000297 /// Decode a UTF-8 minimal well-formed code unit subsequence starting
Michael J. Spencer22120c42012-04-03 23:09:22 +0000298 /// at \a Position.
299 ///
300 /// If the UTF-8 code units starting at Position do not form a well-formed
301 /// code unit subsequence, then the Unicode scalar value is 0, and the length
302 /// is 0.
303 UTF8Decoded decodeUTF8(StringRef::iterator Position) {
304 return ::decodeUTF8(StringRef(Position, End - Position));
305 }
306
307 // The following functions are based on the gramar rules in the YAML spec. The
308 // style of the function names it meant to closely match how they are written
309 // in the spec. The number within the [] is the number of the grammar rule in
310 // the spec.
311 //
312 // See 4.2 [Production Naming Conventions] for the meaning of the prefixes.
313 //
314 // c-
315 // A production starting and ending with a special character.
316 // b-
317 // A production matching a single line break.
318 // nb-
319 // A production starting and ending with a non-break character.
320 // s-
321 // A production starting and ending with a white space character.
322 // ns-
323 // A production starting and ending with a non-space character.
324 // l-
325 // A production matching complete line(s).
326
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000327 /// Skip a single nb-char[27] starting at Position.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000328 ///
329 /// A nb-char is 0x9 | [0x20-0x7E] | 0x85 | [0xA0-0xD7FF] | [0xE000-0xFEFE]
330 /// | [0xFF00-0xFFFD] | [0x10000-0x10FFFF]
331 ///
332 /// @returns The code unit after the nb-char, or Position if it's not an
333 /// nb-char.
334 StringRef::iterator skip_nb_char(StringRef::iterator Position);
335
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000336 /// Skip a single b-break[28] starting at Position.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000337 ///
338 /// A b-break is 0xD 0xA | 0xD | 0xA
339 ///
340 /// @returns The code unit after the b-break, or Position if it's not a
341 /// b-break.
342 StringRef::iterator skip_b_break(StringRef::iterator Position);
343
Alex Lorenza22b250c2015-05-13 23:10:51 +0000344 /// Skip a single s-space[31] starting at Position.
345 ///
346 /// An s-space is 0x20
347 ///
348 /// @returns The code unit after the s-space, or Position if it's not a
349 /// s-space.
350 StringRef::iterator skip_s_space(StringRef::iterator Position);
351
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000352 /// Skip a single s-white[33] starting at Position.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000353 ///
354 /// A s-white is 0x20 | 0x9
355 ///
356 /// @returns The code unit after the s-white, or Position if it's not a
357 /// s-white.
358 StringRef::iterator skip_s_white(StringRef::iterator Position);
359
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000360 /// Skip a single ns-char[34] starting at Position.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000361 ///
362 /// A ns-char is nb-char - s-white
363 ///
364 /// @returns The code unit after the ns-char, or Position if it's not a
365 /// ns-char.
366 StringRef::iterator skip_ns_char(StringRef::iterator Position);
367
Eugene Zelenko72208a82017-06-21 23:19:47 +0000368 using SkipWhileFunc = StringRef::iterator (Scanner::*)(StringRef::iterator);
369
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000370 /// Skip minimal well-formed code unit subsequences until Func
Michael J. Spencer22120c42012-04-03 23:09:22 +0000371 /// returns its input.
372 ///
373 /// @returns The code unit after the last minimal well-formed code unit
374 /// subsequence that Func accepted.
375 StringRef::iterator skip_while( SkipWhileFunc Func
376 , StringRef::iterator Position);
377
Alex Lorenza22b250c2015-05-13 23:10:51 +0000378 /// Skip minimal well-formed code unit subsequences until Func returns its
379 /// input.
380 void advanceWhile(SkipWhileFunc Func);
381
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000382 /// Scan ns-uri-char[39]s starting at Cur.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000383 ///
384 /// This updates Cur and Column while scanning.
Justin Bogner16742612016-10-16 22:01:22 +0000385 void scan_ns_uri_char();
Michael J. Spencer22120c42012-04-03 23:09:22 +0000386
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000387 /// Consume a minimal well-formed code unit subsequence starting at
Michael J. Spencer22120c42012-04-03 23:09:22 +0000388 /// \a Cur. Return false if it is not the same Unicode scalar value as
389 /// \a Expected. This updates \a Column.
390 bool consume(uint32_t Expected);
391
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000392 /// Skip \a Distance UTF-8 code units. Updates \a Cur and \a Column.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000393 void skip(uint32_t Distance);
394
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000395 /// Return true if the minimal well-formed code unit subsequence at
Michael J. Spencer22120c42012-04-03 23:09:22 +0000396 /// Pos is whitespace or a new line
397 bool isBlankOrBreak(StringRef::iterator Position);
398
Alex Lorenza22b250c2015-05-13 23:10:51 +0000399 /// Consume a single b-break[28] if it's present at the current position.
400 ///
401 /// Return false if the code unit at the current position isn't a line break.
402 bool consumeLineBreakIfPresent();
403
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000404 /// If IsSimpleKeyAllowed, create and push_back a new SimpleKey.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000405 void saveSimpleKeyCandidate( TokenQueueT::iterator Tok
406 , unsigned AtColumn
407 , bool IsRequired);
408
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000409 /// Remove simple keys that can no longer be valid simple keys.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000410 ///
411 /// Invalid simple keys are not on the current line or are further than 1024
412 /// columns back.
413 void removeStaleSimpleKeyCandidates();
414
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000415 /// Remove all simple keys on FlowLevel \a Level.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000416 void removeSimpleKeyCandidatesOnFlowLevel(unsigned Level);
417
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000418 /// Unroll indentation in \a Indents back to \a Col. Creates BlockEnd
Michael J. Spencer22120c42012-04-03 23:09:22 +0000419 /// tokens if needed.
420 bool unrollIndent(int ToColumn);
421
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000422 /// Increase indent to \a Col. Creates \a Kind token at \a InsertPoint
Michael J. Spencer22120c42012-04-03 23:09:22 +0000423 /// if needed.
424 bool rollIndent( int ToColumn
425 , Token::TokenKind Kind
426 , TokenQueueT::iterator InsertPoint);
427
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000428 /// Skip a single-line comment when the comment starts at the current
Alex Lorenzfe6f1862015-05-06 23:00:45 +0000429 /// position of the scanner.
430 void skipComment();
431
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000432 /// Skip whitespace and comments until the start of the next token.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000433 void scanToNextToken();
434
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000435 /// Must be the first token generated.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000436 bool scanStreamStart();
437
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000438 /// Generate tokens needed to close out the stream.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000439 bool scanStreamEnd();
440
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000441 /// Scan a %BLAH directive.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000442 bool scanDirective();
443
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000444 /// Scan a ... or ---.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000445 bool scanDocumentIndicator(bool IsStart);
446
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000447 /// Scan a [ or { and generate the proper flow collection start token.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000448 bool scanFlowCollectionStart(bool IsSequence);
449
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000450 /// Scan a ] or } and generate the proper flow collection end token.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000451 bool scanFlowCollectionEnd(bool IsSequence);
452
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000453 /// Scan the , that separates entries in a flow collection.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000454 bool scanFlowEntry();
455
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000456 /// Scan the - that starts block sequence entries.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000457 bool scanBlockEntry();
458
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000459 /// Scan an explicit ? indicating a key.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000460 bool scanKey();
461
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000462 /// Scan an explicit : indicating a value.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000463 bool scanValue();
464
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000465 /// Scan a quoted scalar.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000466 bool scanFlowScalar(bool IsDoubleQuoted);
467
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000468 /// Scan an unquoted scalar.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000469 bool scanPlainScalar();
470
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000471 /// Scan an Alias or Anchor starting with * or &.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000472 bool scanAliasOrAnchor(bool IsAlias);
473
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000474 /// Scan a block scalar starting with | or >.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000475 bool scanBlockScalar(bool IsLiteral);
476
Alex Lorenza22b250c2015-05-13 23:10:51 +0000477 /// Scan a chomping indicator in a block scalar header.
478 char scanBlockChompingIndicator();
479
480 /// Scan an indentation indicator in a block scalar header.
481 unsigned scanBlockIndentationIndicator();
482
483 /// Scan a block scalar header.
484 ///
485 /// Return false if an error occurred.
486 bool scanBlockScalarHeader(char &ChompingIndicator, unsigned &IndentIndicator,
487 bool &IsDone);
488
489 /// Look for the indentation level of a block scalar.
490 ///
491 /// Return false if an error occurred.
492 bool findBlockScalarIndent(unsigned &BlockIndent, unsigned BlockExitIndent,
493 unsigned &LineBreaks, bool &IsDone);
494
495 /// Scan the indentation of a text line in a block scalar.
496 ///
497 /// Return false if an error occurred.
498 bool scanBlockScalarIndent(unsigned BlockIndent, unsigned BlockExitIndent,
499 bool &IsDone);
500
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000501 /// Scan a tag of the form !stuff.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000502 bool scanTag();
503
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000504 /// Dispatch to the next scanning function based on \a *Cur.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000505 bool fetchMoreTokens();
506
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000507 /// The SourceMgr used for diagnostics and buffer management.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000508 SourceMgr &SM;
509
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000510 /// The original input.
Rafael Espindola68669e32014-08-27 19:03:22 +0000511 MemoryBufferRef InputBuffer;
Michael J. Spencer22120c42012-04-03 23:09:22 +0000512
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000513 /// The current position of the scanner.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000514 StringRef::iterator Current;
515
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000516 /// The end of the input (one past the last character).
Michael J. Spencer22120c42012-04-03 23:09:22 +0000517 StringRef::iterator End;
518
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000519 /// Current YAML indentation level in spaces.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000520 int Indent;
521
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000522 /// Current column number in Unicode code points.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000523 unsigned Column;
524
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000525 /// Current line number.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000526 unsigned Line;
527
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000528 /// How deep we are in flow style containers. 0 Means at block level.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000529 unsigned FlowLevel;
530
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000531 /// Are we at the start of the stream?
Michael J. Spencer22120c42012-04-03 23:09:22 +0000532 bool IsStartOfStream;
533
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000534 /// Can the next token be the start of a simple key?
Michael J. Spencer22120c42012-04-03 23:09:22 +0000535 bool IsSimpleKeyAllowed;
536
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000537 /// True if an error has occurred.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000538 bool Failed;
539
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000540 /// Should colors be used when printing out the diagnostic messages?
Alex Lorenze4bcfbf2015-05-07 18:08:46 +0000541 bool ShowColors;
542
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000543 /// Queue of tokens. This is required to queue up tokens while looking
Michael J. Spencer22120c42012-04-03 23:09:22 +0000544 /// for the end of a simple key. And for cases where a single character
545 /// can produce multiple tokens (e.g. BlockEnd).
546 TokenQueueT TokenQueue;
547
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000548 /// Indentation levels.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000549 SmallVector<int, 4> Indents;
550
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000551 /// Potential simple keys.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000552 SmallVector<SimpleKey, 4> SimpleKeys;
Mehdi Amini3ab3fef2016-11-28 21:38:52 +0000553
554 std::error_code *EC;
Michael J. Spencer22120c42012-04-03 23:09:22 +0000555};
556
557} // end namespace yaml
558} // end namespace llvm
559
560/// encodeUTF8 - Encode \a UnicodeScalarValue in UTF-8 and append it to result.
561static void encodeUTF8( uint32_t UnicodeScalarValue
562 , SmallVectorImpl<char> &Result) {
563 if (UnicodeScalarValue <= 0x7F) {
564 Result.push_back(UnicodeScalarValue & 0x7F);
565 } else if (UnicodeScalarValue <= 0x7FF) {
566 uint8_t FirstByte = 0xC0 | ((UnicodeScalarValue & 0x7C0) >> 6);
567 uint8_t SecondByte = 0x80 | (UnicodeScalarValue & 0x3F);
568 Result.push_back(FirstByte);
569 Result.push_back(SecondByte);
570 } else if (UnicodeScalarValue <= 0xFFFF) {
571 uint8_t FirstByte = 0xE0 | ((UnicodeScalarValue & 0xF000) >> 12);
572 uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
573 uint8_t ThirdByte = 0x80 | (UnicodeScalarValue & 0x3F);
574 Result.push_back(FirstByte);
575 Result.push_back(SecondByte);
576 Result.push_back(ThirdByte);
577 } else if (UnicodeScalarValue <= 0x10FFFF) {
578 uint8_t FirstByte = 0xF0 | ((UnicodeScalarValue & 0x1F0000) >> 18);
579 uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0x3F000) >> 12);
580 uint8_t ThirdByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
581 uint8_t FourthByte = 0x80 | (UnicodeScalarValue & 0x3F);
582 Result.push_back(FirstByte);
583 Result.push_back(SecondByte);
584 Result.push_back(ThirdByte);
585 Result.push_back(FourthByte);
586 }
587}
588
589bool yaml::dumpTokens(StringRef Input, raw_ostream &OS) {
590 SourceMgr SM;
591 Scanner scanner(Input, SM);
592 while (true) {
593 Token T = scanner.getNext();
594 switch (T.Kind) {
595 case Token::TK_StreamStart:
596 OS << "Stream-Start: ";
597 break;
598 case Token::TK_StreamEnd:
599 OS << "Stream-End: ";
600 break;
601 case Token::TK_VersionDirective:
602 OS << "Version-Directive: ";
603 break;
604 case Token::TK_TagDirective:
605 OS << "Tag-Directive: ";
606 break;
607 case Token::TK_DocumentStart:
608 OS << "Document-Start: ";
609 break;
610 case Token::TK_DocumentEnd:
611 OS << "Document-End: ";
612 break;
613 case Token::TK_BlockEntry:
614 OS << "Block-Entry: ";
615 break;
616 case Token::TK_BlockEnd:
617 OS << "Block-End: ";
618 break;
619 case Token::TK_BlockSequenceStart:
620 OS << "Block-Sequence-Start: ";
621 break;
622 case Token::TK_BlockMappingStart:
623 OS << "Block-Mapping-Start: ";
624 break;
625 case Token::TK_FlowEntry:
626 OS << "Flow-Entry: ";
627 break;
628 case Token::TK_FlowSequenceStart:
629 OS << "Flow-Sequence-Start: ";
630 break;
631 case Token::TK_FlowSequenceEnd:
632 OS << "Flow-Sequence-End: ";
633 break;
634 case Token::TK_FlowMappingStart:
635 OS << "Flow-Mapping-Start: ";
636 break;
637 case Token::TK_FlowMappingEnd:
638 OS << "Flow-Mapping-End: ";
639 break;
640 case Token::TK_Key:
641 OS << "Key: ";
642 break;
643 case Token::TK_Value:
644 OS << "Value: ";
645 break;
646 case Token::TK_Scalar:
647 OS << "Scalar: ";
648 break;
Alex Lorenza22b250c2015-05-13 23:10:51 +0000649 case Token::TK_BlockScalar:
650 OS << "Block Scalar: ";
651 break;
Michael J. Spencer22120c42012-04-03 23:09:22 +0000652 case Token::TK_Alias:
653 OS << "Alias: ";
654 break;
655 case Token::TK_Anchor:
656 OS << "Anchor: ";
657 break;
658 case Token::TK_Tag:
659 OS << "Tag: ";
660 break;
661 case Token::TK_Error:
662 break;
663 }
664 OS << T.Range << "\n";
665 if (T.Kind == Token::TK_StreamEnd)
666 break;
667 else if (T.Kind == Token::TK_Error)
668 return false;
669 }
670 return true;
671}
672
673bool yaml::scanTokens(StringRef Input) {
Eugene Zelenko72208a82017-06-21 23:19:47 +0000674 SourceMgr SM;
675 Scanner scanner(Input, SM);
676 while (true) {
677 Token T = scanner.getNext();
Michael J. Spencer22120c42012-04-03 23:09:22 +0000678 if (T.Kind == Token::TK_StreamEnd)
679 break;
680 else if (T.Kind == Token::TK_Error)
681 return false;
682 }
683 return true;
684}
685
Graydon Hoare926cd9b2018-03-27 19:52:45 +0000686std::string yaml::escape(StringRef Input, bool EscapePrintable) {
Michael J. Spencer22120c42012-04-03 23:09:22 +0000687 std::string EscapedInput;
688 for (StringRef::iterator i = Input.begin(), e = Input.end(); i != e; ++i) {
689 if (*i == '\\')
690 EscapedInput += "\\\\";
691 else if (*i == '"')
692 EscapedInput += "\\\"";
693 else if (*i == 0)
694 EscapedInput += "\\0";
695 else if (*i == 0x07)
696 EscapedInput += "\\a";
697 else if (*i == 0x08)
698 EscapedInput += "\\b";
699 else if (*i == 0x09)
700 EscapedInput += "\\t";
701 else if (*i == 0x0A)
702 EscapedInput += "\\n";
703 else if (*i == 0x0B)
704 EscapedInput += "\\v";
705 else if (*i == 0x0C)
706 EscapedInput += "\\f";
707 else if (*i == 0x0D)
708 EscapedInput += "\\r";
709 else if (*i == 0x1B)
710 EscapedInput += "\\e";
Benjamin Kramer0aa0d3d2012-04-21 10:51:42 +0000711 else if ((unsigned char)*i < 0x20) { // Control characters not handled above.
Michael J. Spencer22120c42012-04-03 23:09:22 +0000712 std::string HexStr = utohexstr(*i);
713 EscapedInput += "\\x" + std::string(2 - HexStr.size(), '0') + HexStr;
714 } else if (*i & 0x80) { // UTF-8 multiple code unit subsequence.
715 UTF8Decoded UnicodeScalarValue
716 = decodeUTF8(StringRef(i, Input.end() - i));
717 if (UnicodeScalarValue.second == 0) {
718 // Found invalid char.
719 SmallString<4> Val;
720 encodeUTF8(0xFFFD, Val);
721 EscapedInput.insert(EscapedInput.end(), Val.begin(), Val.end());
722 // FIXME: Error reporting.
723 return EscapedInput;
724 }
725 if (UnicodeScalarValue.first == 0x85)
726 EscapedInput += "\\N";
727 else if (UnicodeScalarValue.first == 0xA0)
728 EscapedInput += "\\_";
729 else if (UnicodeScalarValue.first == 0x2028)
730 EscapedInput += "\\L";
731 else if (UnicodeScalarValue.first == 0x2029)
732 EscapedInput += "\\P";
Graydon Hoare926cd9b2018-03-27 19:52:45 +0000733 else if (!EscapePrintable &&
734 sys::unicode::isPrintable(UnicodeScalarValue.first))
735 EscapedInput += StringRef(i, UnicodeScalarValue.second);
Michael J. Spencer22120c42012-04-03 23:09:22 +0000736 else {
737 std::string HexStr = utohexstr(UnicodeScalarValue.first);
738 if (HexStr.size() <= 2)
739 EscapedInput += "\\x" + std::string(2 - HexStr.size(), '0') + HexStr;
740 else if (HexStr.size() <= 4)
741 EscapedInput += "\\u" + std::string(4 - HexStr.size(), '0') + HexStr;
742 else if (HexStr.size() <= 8)
743 EscapedInput += "\\U" + std::string(8 - HexStr.size(), '0') + HexStr;
744 }
745 i += UnicodeScalarValue.second - 1;
746 } else
747 EscapedInput.push_back(*i);
748 }
749 return EscapedInput;
750}
751
Mehdi Amini3ab3fef2016-11-28 21:38:52 +0000752Scanner::Scanner(StringRef Input, SourceMgr &sm, bool ShowColors,
753 std::error_code *EC)
754 : SM(sm), ShowColors(ShowColors), EC(EC) {
Rafael Espindola68669e32014-08-27 19:03:22 +0000755 init(MemoryBufferRef(Input, "YAML"));
Michael J. Spencer22120c42012-04-03 23:09:22 +0000756}
757
Mehdi Amini3ab3fef2016-11-28 21:38:52 +0000758Scanner::Scanner(MemoryBufferRef Buffer, SourceMgr &SM_, bool ShowColors,
759 std::error_code *EC)
760 : SM(SM_), ShowColors(ShowColors), EC(EC) {
Rafael Espindola68669e32014-08-27 19:03:22 +0000761 init(Buffer);
762}
763
764void Scanner::init(MemoryBufferRef Buffer) {
765 InputBuffer = Buffer;
766 Current = InputBuffer.getBufferStart();
767 End = InputBuffer.getBufferEnd();
768 Indent = -1;
769 Column = 0;
770 Line = 0;
771 FlowLevel = 0;
772 IsStartOfStream = true;
773 IsSimpleKeyAllowed = true;
774 Failed = false;
775 std::unique_ptr<MemoryBuffer> InputBufferOwner =
776 MemoryBuffer::getMemBuffer(Buffer);
777 SM.AddNewSourceBuffer(std::move(InputBufferOwner), SMLoc());
Sean Silvaaba82702012-11-19 23:21:47 +0000778}
779
Michael J. Spencer22120c42012-04-03 23:09:22 +0000780Token &Scanner::peekNext() {
781 // If the current token is a possible simple key, keep parsing until we
782 // can confirm.
783 bool NeedMore = false;
784 while (true) {
785 if (TokenQueue.empty() || NeedMore) {
786 if (!fetchMoreTokens()) {
787 TokenQueue.clear();
Thomas Finch092452d2019-11-05 21:51:04 -0800788 SimpleKeys.clear();
Michael J. Spencer22120c42012-04-03 23:09:22 +0000789 TokenQueue.push_back(Token());
790 return TokenQueue.front();
791 }
792 }
793 assert(!TokenQueue.empty() &&
794 "fetchMoreTokens lied about getting tokens!");
795
796 removeStaleSimpleKeyCandidates();
797 SimpleKey SK;
Duncan P. N. Exon Smith6eeaff12015-10-08 22:47:55 +0000798 SK.Tok = TokenQueue.begin();
David Majnemer0d955d02016-08-11 22:21:41 +0000799 if (!is_contained(SimpleKeys, SK))
Michael J. Spencer22120c42012-04-03 23:09:22 +0000800 break;
801 else
802 NeedMore = true;
803 }
804 return TokenQueue.front();
805}
806
807Token Scanner::getNext() {
808 Token Ret = peekNext();
809 // TokenQueue can be empty if there was an error getting the next token.
810 if (!TokenQueue.empty())
811 TokenQueue.pop_front();
812
813 // There cannot be any referenced Token's if the TokenQueue is empty. So do a
814 // quick deallocation of them all.
Duncan P. N. Exon Smith23d83062016-09-11 22:40:40 +0000815 if (TokenQueue.empty())
816 TokenQueue.resetAlloc();
Michael J. Spencer22120c42012-04-03 23:09:22 +0000817
818 return Ret;
819}
820
821StringRef::iterator Scanner::skip_nb_char(StringRef::iterator Position) {
Michael J. Spencer60331132012-04-27 21:12:20 +0000822 if (Position == End)
823 return Position;
Michael J. Spencer22120c42012-04-03 23:09:22 +0000824 // Check 7 bit c-printable - b-char.
825 if ( *Position == 0x09
826 || (*Position >= 0x20 && *Position <= 0x7E))
827 return Position + 1;
828
829 // Check for valid UTF-8.
830 if (uint8_t(*Position) & 0x80) {
831 UTF8Decoded u8d = decodeUTF8(Position);
832 if ( u8d.second != 0
833 && u8d.first != 0xFEFF
834 && ( u8d.first == 0x85
835 || ( u8d.first >= 0xA0
836 && u8d.first <= 0xD7FF)
837 || ( u8d.first >= 0xE000
838 && u8d.first <= 0xFFFD)
839 || ( u8d.first >= 0x10000
840 && u8d.first <= 0x10FFFF)))
841 return Position + u8d.second;
842 }
843 return Position;
844}
845
846StringRef::iterator Scanner::skip_b_break(StringRef::iterator Position) {
Michael J. Spencer60331132012-04-27 21:12:20 +0000847 if (Position == End)
848 return Position;
Michael J. Spencer22120c42012-04-03 23:09:22 +0000849 if (*Position == 0x0D) {
850 if (Position + 1 != End && *(Position + 1) == 0x0A)
851 return Position + 2;
852 return Position + 1;
853 }
854
855 if (*Position == 0x0A)
856 return Position + 1;
857 return Position;
858}
859
Alex Lorenza22b250c2015-05-13 23:10:51 +0000860StringRef::iterator Scanner::skip_s_space(StringRef::iterator Position) {
861 if (Position == End)
862 return Position;
863 if (*Position == ' ')
864 return Position + 1;
865 return Position;
866}
Michael J. Spencer22120c42012-04-03 23:09:22 +0000867
868StringRef::iterator Scanner::skip_s_white(StringRef::iterator Position) {
869 if (Position == End)
870 return Position;
871 if (*Position == ' ' || *Position == '\t')
872 return Position + 1;
873 return Position;
874}
875
876StringRef::iterator Scanner::skip_ns_char(StringRef::iterator Position) {
877 if (Position == End)
878 return Position;
879 if (*Position == ' ' || *Position == '\t')
880 return Position;
881 return skip_nb_char(Position);
882}
883
884StringRef::iterator Scanner::skip_while( SkipWhileFunc Func
885 , StringRef::iterator Position) {
886 while (true) {
887 StringRef::iterator i = (this->*Func)(Position);
888 if (i == Position)
889 break;
890 Position = i;
891 }
892 return Position;
893}
894
Alex Lorenza22b250c2015-05-13 23:10:51 +0000895void Scanner::advanceWhile(SkipWhileFunc Func) {
896 auto Final = skip_while(Func, Current);
897 Column += Final - Current;
898 Current = Final;
899}
900
Michael J. Spencer22120c42012-04-03 23:09:22 +0000901static bool is_ns_hex_digit(const char C) {
902 return (C >= '0' && C <= '9')
903 || (C >= 'a' && C <= 'z')
904 || (C >= 'A' && C <= 'Z');
905}
906
907static bool is_ns_word_char(const char C) {
908 return C == '-'
909 || (C >= 'a' && C <= 'z')
910 || (C >= 'A' && C <= 'Z');
911}
912
Justin Bogner16742612016-10-16 22:01:22 +0000913void Scanner::scan_ns_uri_char() {
Michael J. Spencer22120c42012-04-03 23:09:22 +0000914 while (true) {
915 if (Current == End)
916 break;
917 if (( *Current == '%'
918 && Current + 2 < End
919 && is_ns_hex_digit(*(Current + 1))
920 && is_ns_hex_digit(*(Current + 2)))
921 || is_ns_word_char(*Current)
922 || StringRef(Current, 1).find_first_of("#;/?:@&=+$,_.!~*'()[]")
923 != StringRef::npos) {
924 ++Current;
925 ++Column;
926 } else
927 break;
928 }
Michael J. Spencer22120c42012-04-03 23:09:22 +0000929}
930
Michael J. Spencer22120c42012-04-03 23:09:22 +0000931bool Scanner::consume(uint32_t Expected) {
Thomas Finch092452d2019-11-05 21:51:04 -0800932 if (Expected >= 0x80) {
Simon Pilgrim22257972020-04-03 18:53:38 +0100933 setError("Cannot consume non-ascii characters", Current);
Thomas Finch092452d2019-11-05 21:51:04 -0800934 return false;
935 }
Michael J. Spencer22120c42012-04-03 23:09:22 +0000936 if (Current == End)
937 return false;
Thomas Finch092452d2019-11-05 21:51:04 -0800938 if (uint8_t(*Current) >= 0x80) {
Simon Pilgrim22257972020-04-03 18:53:38 +0100939 setError("Cannot consume non-ascii characters", Current);
Thomas Finch092452d2019-11-05 21:51:04 -0800940 return false;
941 }
Michael J. Spencer22120c42012-04-03 23:09:22 +0000942 if (uint8_t(*Current) == Expected) {
943 ++Current;
944 ++Column;
945 return true;
946 }
947 return false;
948}
949
950void Scanner::skip(uint32_t Distance) {
951 Current += Distance;
952 Column += Distance;
Benjamin Kramer8fb58f62012-09-26 15:52:15 +0000953 assert(Current <= End && "Skipped past the end");
Michael J. Spencer22120c42012-04-03 23:09:22 +0000954}
955
956bool Scanner::isBlankOrBreak(StringRef::iterator Position) {
957 if (Position == End)
958 return false;
Alexander Kornienko66da20a2015-12-28 15:46:15 +0000959 return *Position == ' ' || *Position == '\t' || *Position == '\r' ||
960 *Position == '\n';
Michael J. Spencer22120c42012-04-03 23:09:22 +0000961}
962
Alex Lorenza22b250c2015-05-13 23:10:51 +0000963bool Scanner::consumeLineBreakIfPresent() {
964 auto Next = skip_b_break(Current);
965 if (Next == Current)
966 return false;
967 Column = 0;
968 ++Line;
969 Current = Next;
970 return true;
971}
972
Michael J. Spencer22120c42012-04-03 23:09:22 +0000973void Scanner::saveSimpleKeyCandidate( TokenQueueT::iterator Tok
974 , unsigned AtColumn
975 , bool IsRequired) {
976 if (IsSimpleKeyAllowed) {
977 SimpleKey SK;
978 SK.Tok = Tok;
979 SK.Line = Line;
980 SK.Column = AtColumn;
981 SK.IsRequired = IsRequired;
982 SK.FlowLevel = FlowLevel;
983 SimpleKeys.push_back(SK);
984 }
985}
986
987void Scanner::removeStaleSimpleKeyCandidates() {
988 for (SmallVectorImpl<SimpleKey>::iterator i = SimpleKeys.begin();
989 i != SimpleKeys.end();) {
990 if (i->Line != Line || i->Column + 1024 < Column) {
991 if (i->IsRequired)
992 setError( "Could not find expected : for simple key"
993 , i->Tok->Range.begin());
994 i = SimpleKeys.erase(i);
995 } else
996 ++i;
997 }
998}
999
1000void Scanner::removeSimpleKeyCandidatesOnFlowLevel(unsigned Level) {
1001 if (!SimpleKeys.empty() && (SimpleKeys.end() - 1)->FlowLevel == Level)
1002 SimpleKeys.pop_back();
1003}
1004
1005bool Scanner::unrollIndent(int ToColumn) {
1006 Token T;
1007 // Indentation is ignored in flow.
1008 if (FlowLevel != 0)
1009 return true;
1010
1011 while (Indent > ToColumn) {
1012 T.Kind = Token::TK_BlockEnd;
1013 T.Range = StringRef(Current, 1);
1014 TokenQueue.push_back(T);
1015 Indent = Indents.pop_back_val();
1016 }
1017
1018 return true;
1019}
1020
1021bool Scanner::rollIndent( int ToColumn
1022 , Token::TokenKind Kind
1023 , TokenQueueT::iterator InsertPoint) {
1024 if (FlowLevel)
1025 return true;
1026 if (Indent < ToColumn) {
1027 Indents.push_back(Indent);
1028 Indent = ToColumn;
1029
1030 Token T;
1031 T.Kind = Kind;
1032 T.Range = StringRef(Current, 0);
1033 TokenQueue.insert(InsertPoint, T);
1034 }
1035 return true;
1036}
1037
Alex Lorenzfe6f1862015-05-06 23:00:45 +00001038void Scanner::skipComment() {
1039 if (*Current != '#')
1040 return;
1041 while (true) {
1042 // This may skip more than one byte, thus Column is only incremented
1043 // for code points.
1044 StringRef::iterator I = skip_nb_char(Current);
1045 if (I == Current)
1046 break;
1047 Current = I;
1048 ++Column;
1049 }
1050}
1051
Michael J. Spencer22120c42012-04-03 23:09:22 +00001052void Scanner::scanToNextToken() {
1053 while (true) {
1054 while (*Current == ' ' || *Current == '\t') {
1055 skip(1);
1056 }
1057
Alex Lorenzfe6f1862015-05-06 23:00:45 +00001058 skipComment();
Michael J. Spencer22120c42012-04-03 23:09:22 +00001059
1060 // Skip EOL.
1061 StringRef::iterator i = skip_b_break(Current);
1062 if (i == Current)
1063 break;
1064 Current = i;
1065 ++Line;
1066 Column = 0;
1067 // New lines may start a simple key.
1068 if (!FlowLevel)
1069 IsSimpleKeyAllowed = true;
1070 }
1071}
1072
1073bool Scanner::scanStreamStart() {
1074 IsStartOfStream = false;
1075
1076 EncodingInfo EI = getUnicodeEncoding(currentInput());
1077
1078 Token T;
1079 T.Kind = Token::TK_StreamStart;
1080 T.Range = StringRef(Current, EI.second);
1081 TokenQueue.push_back(T);
1082 Current += EI.second;
1083 return true;
1084}
1085
1086bool Scanner::scanStreamEnd() {
1087 // Force an ending new line if one isn't present.
1088 if (Column != 0) {
1089 Column = 0;
1090 ++Line;
1091 }
1092
1093 unrollIndent(-1);
1094 SimpleKeys.clear();
1095 IsSimpleKeyAllowed = false;
1096
1097 Token T;
1098 T.Kind = Token::TK_StreamEnd;
1099 T.Range = StringRef(Current, 0);
1100 TokenQueue.push_back(T);
1101 return true;
1102}
1103
1104bool Scanner::scanDirective() {
1105 // Reset the indentation level.
1106 unrollIndent(-1);
1107 SimpleKeys.clear();
1108 IsSimpleKeyAllowed = false;
1109
1110 StringRef::iterator Start = Current;
1111 consume('%');
1112 StringRef::iterator NameStart = Current;
1113 Current = skip_while(&Scanner::skip_ns_char, Current);
1114 StringRef Name(NameStart, Current - NameStart);
1115 Current = skip_while(&Scanner::skip_s_white, Current);
Fangrui Songf78650a2018-07-30 19:41:25 +00001116
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00001117 Token T;
Michael J. Spencer22120c42012-04-03 23:09:22 +00001118 if (Name == "YAML") {
1119 Current = skip_while(&Scanner::skip_ns_char, Current);
Michael J. Spencer22120c42012-04-03 23:09:22 +00001120 T.Kind = Token::TK_VersionDirective;
1121 T.Range = StringRef(Start, Current - Start);
1122 TokenQueue.push_back(T);
1123 return true;
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00001124 } else if(Name == "TAG") {
1125 Current = skip_while(&Scanner::skip_ns_char, Current);
1126 Current = skip_while(&Scanner::skip_s_white, Current);
1127 Current = skip_while(&Scanner::skip_ns_char, Current);
1128 T.Kind = Token::TK_TagDirective;
1129 T.Range = StringRef(Start, Current - Start);
1130 TokenQueue.push_back(T);
1131 return true;
Michael J. Spencer22120c42012-04-03 23:09:22 +00001132 }
1133 return false;
1134}
1135
1136bool Scanner::scanDocumentIndicator(bool IsStart) {
1137 unrollIndent(-1);
1138 SimpleKeys.clear();
1139 IsSimpleKeyAllowed = false;
1140
1141 Token T;
1142 T.Kind = IsStart ? Token::TK_DocumentStart : Token::TK_DocumentEnd;
1143 T.Range = StringRef(Current, 3);
1144 skip(3);
1145 TokenQueue.push_back(T);
1146 return true;
1147}
1148
1149bool Scanner::scanFlowCollectionStart(bool IsSequence) {
1150 Token T;
1151 T.Kind = IsSequence ? Token::TK_FlowSequenceStart
1152 : Token::TK_FlowMappingStart;
1153 T.Range = StringRef(Current, 1);
1154 skip(1);
1155 TokenQueue.push_back(T);
1156
1157 // [ and { may begin a simple key.
Duncan P. N. Exon Smith6eeaff12015-10-08 22:47:55 +00001158 saveSimpleKeyCandidate(--TokenQueue.end(), Column - 1, false);
Michael J. Spencer22120c42012-04-03 23:09:22 +00001159
1160 // And may also be followed by a simple key.
1161 IsSimpleKeyAllowed = true;
1162 ++FlowLevel;
1163 return true;
1164}
1165
1166bool Scanner::scanFlowCollectionEnd(bool IsSequence) {
1167 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1168 IsSimpleKeyAllowed = false;
1169 Token T;
1170 T.Kind = IsSequence ? Token::TK_FlowSequenceEnd
1171 : Token::TK_FlowMappingEnd;
1172 T.Range = StringRef(Current, 1);
1173 skip(1);
1174 TokenQueue.push_back(T);
1175 if (FlowLevel)
1176 --FlowLevel;
1177 return true;
1178}
1179
1180bool Scanner::scanFlowEntry() {
1181 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1182 IsSimpleKeyAllowed = true;
1183 Token T;
1184 T.Kind = Token::TK_FlowEntry;
1185 T.Range = StringRef(Current, 1);
1186 skip(1);
1187 TokenQueue.push_back(T);
1188 return true;
1189}
1190
1191bool Scanner::scanBlockEntry() {
1192 rollIndent(Column, Token::TK_BlockSequenceStart, TokenQueue.end());
1193 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1194 IsSimpleKeyAllowed = true;
1195 Token T;
1196 T.Kind = Token::TK_BlockEntry;
1197 T.Range = StringRef(Current, 1);
1198 skip(1);
1199 TokenQueue.push_back(T);
1200 return true;
1201}
1202
1203bool Scanner::scanKey() {
1204 if (!FlowLevel)
1205 rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
1206
1207 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1208 IsSimpleKeyAllowed = !FlowLevel;
1209
1210 Token T;
1211 T.Kind = Token::TK_Key;
1212 T.Range = StringRef(Current, 1);
1213 skip(1);
1214 TokenQueue.push_back(T);
1215 return true;
1216}
1217
1218bool Scanner::scanValue() {
1219 // If the previous token could have been a simple key, insert the key token
1220 // into the token queue.
1221 if (!SimpleKeys.empty()) {
1222 SimpleKey SK = SimpleKeys.pop_back_val();
1223 Token T;
1224 T.Kind = Token::TK_Key;
1225 T.Range = SK.Tok->Range;
1226 TokenQueueT::iterator i, e;
1227 for (i = TokenQueue.begin(), e = TokenQueue.end(); i != e; ++i) {
1228 if (i == SK.Tok)
1229 break;
1230 }
Thomas Finch092452d2019-11-05 21:51:04 -08001231 if (i == e) {
1232 Failed = true;
1233 return false;
1234 }
Michael J. Spencer22120c42012-04-03 23:09:22 +00001235 i = TokenQueue.insert(i, T);
1236
1237 // We may also need to add a Block-Mapping-Start token.
1238 rollIndent(SK.Column, Token::TK_BlockMappingStart, i);
1239
1240 IsSimpleKeyAllowed = false;
1241 } else {
1242 if (!FlowLevel)
1243 rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
1244 IsSimpleKeyAllowed = !FlowLevel;
1245 }
1246
1247 Token T;
1248 T.Kind = Token::TK_Value;
1249 T.Range = StringRef(Current, 1);
1250 skip(1);
1251 TokenQueue.push_back(T);
1252 return true;
1253}
1254
1255// Forbidding inlining improves performance by roughly 20%.
1256// FIXME: Remove once llvm optimizes this to the faster version without hints.
1257LLVM_ATTRIBUTE_NOINLINE static bool
1258wasEscaped(StringRef::iterator First, StringRef::iterator Position);
1259
1260// Returns whether a character at 'Position' was escaped with a leading '\'.
1261// 'First' specifies the position of the first character in the string.
1262static bool wasEscaped(StringRef::iterator First,
1263 StringRef::iterator Position) {
1264 assert(Position - 1 >= First);
1265 StringRef::iterator I = Position - 1;
1266 // We calculate the number of consecutive '\'s before the current position
1267 // by iterating backwards through our string.
1268 while (I >= First && *I == '\\') --I;
1269 // (Position - 1 - I) now contains the number of '\'s before the current
1270 // position. If it is odd, the character at 'Position' was escaped.
1271 return (Position - 1 - I) % 2 == 1;
1272}
1273
1274bool Scanner::scanFlowScalar(bool IsDoubleQuoted) {
1275 StringRef::iterator Start = Current;
1276 unsigned ColStart = Column;
1277 if (IsDoubleQuoted) {
1278 do {
1279 ++Current;
1280 while (Current != End && *Current != '"')
1281 ++Current;
1282 // Repeat until the previous character was not a '\' or was an escaped
1283 // backslash.
Michael J. Spencer60331132012-04-27 21:12:20 +00001284 } while ( Current != End
1285 && *(Current - 1) == '\\'
1286 && wasEscaped(Start + 1, Current));
Michael J. Spencer22120c42012-04-03 23:09:22 +00001287 } else {
1288 skip(1);
1289 while (true) {
1290 // Skip a ' followed by another '.
1291 if (Current + 1 < End && *Current == '\'' && *(Current + 1) == '\'') {
1292 skip(2);
1293 continue;
1294 } else if (*Current == '\'')
1295 break;
1296 StringRef::iterator i = skip_nb_char(Current);
1297 if (i == Current) {
1298 i = skip_b_break(Current);
1299 if (i == Current)
1300 break;
1301 Current = i;
1302 Column = 0;
1303 ++Line;
1304 } else {
1305 if (i == End)
1306 break;
1307 Current = i;
1308 ++Column;
1309 }
1310 }
1311 }
Benjamin Kramer8fb58f62012-09-26 15:52:15 +00001312
1313 if (Current == End) {
1314 setError("Expected quote at end of scalar", Current);
1315 return false;
1316 }
1317
Michael J. Spencer22120c42012-04-03 23:09:22 +00001318 skip(1); // Skip ending quote.
1319 Token T;
1320 T.Kind = Token::TK_Scalar;
1321 T.Range = StringRef(Start, Current - Start);
1322 TokenQueue.push_back(T);
1323
Duncan P. N. Exon Smith6eeaff12015-10-08 22:47:55 +00001324 saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
Michael J. Spencer22120c42012-04-03 23:09:22 +00001325
1326 IsSimpleKeyAllowed = false;
1327
1328 return true;
1329}
1330
1331bool Scanner::scanPlainScalar() {
1332 StringRef::iterator Start = Current;
1333 unsigned ColStart = Column;
1334 unsigned LeadingBlanks = 0;
1335 assert(Indent >= -1 && "Indent must be >= -1 !");
1336 unsigned indent = static_cast<unsigned>(Indent + 1);
1337 while (true) {
1338 if (*Current == '#')
1339 break;
1340
1341 while (!isBlankOrBreak(Current)) {
1342 if ( FlowLevel && *Current == ':'
1343 && !(isBlankOrBreak(Current + 1) || *(Current + 1) == ',')) {
1344 setError("Found unexpected ':' while scanning a plain scalar", Current);
1345 return false;
1346 }
1347
1348 // Check for the end of the plain scalar.
1349 if ( (*Current == ':' && isBlankOrBreak(Current + 1))
1350 || ( FlowLevel
1351 && (StringRef(Current, 1).find_first_of(",:?[]{}")
1352 != StringRef::npos)))
1353 break;
1354
1355 StringRef::iterator i = skip_nb_char(Current);
1356 if (i == Current)
1357 break;
1358 Current = i;
1359 ++Column;
1360 }
1361
1362 // Are we at the end?
1363 if (!isBlankOrBreak(Current))
1364 break;
1365
1366 // Eat blanks.
1367 StringRef::iterator Tmp = Current;
1368 while (isBlankOrBreak(Tmp)) {
1369 StringRef::iterator i = skip_s_white(Tmp);
1370 if (i != Tmp) {
1371 if (LeadingBlanks && (Column < indent) && *Tmp == '\t') {
1372 setError("Found invalid tab character in indentation", Tmp);
1373 return false;
1374 }
1375 Tmp = i;
1376 ++Column;
1377 } else {
1378 i = skip_b_break(Tmp);
1379 if (!LeadingBlanks)
1380 LeadingBlanks = 1;
1381 Tmp = i;
1382 Column = 0;
1383 ++Line;
1384 }
1385 }
1386
1387 if (!FlowLevel && Column < indent)
1388 break;
1389
1390 Current = Tmp;
1391 }
1392 if (Start == Current) {
1393 setError("Got empty plain scalar", Start);
1394 return false;
1395 }
1396 Token T;
1397 T.Kind = Token::TK_Scalar;
1398 T.Range = StringRef(Start, Current - Start);
1399 TokenQueue.push_back(T);
1400
1401 // Plain scalars can be simple keys.
Duncan P. N. Exon Smith6eeaff12015-10-08 22:47:55 +00001402 saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
Michael J. Spencer22120c42012-04-03 23:09:22 +00001403
1404 IsSimpleKeyAllowed = false;
1405
1406 return true;
1407}
1408
1409bool Scanner::scanAliasOrAnchor(bool IsAlias) {
1410 StringRef::iterator Start = Current;
1411 unsigned ColStart = Column;
1412 skip(1);
1413 while(true) {
1414 if ( *Current == '[' || *Current == ']'
1415 || *Current == '{' || *Current == '}'
1416 || *Current == ','
1417 || *Current == ':')
1418 break;
1419 StringRef::iterator i = skip_ns_char(Current);
1420 if (i == Current)
1421 break;
1422 Current = i;
1423 ++Column;
1424 }
1425
1426 if (Start == Current) {
1427 setError("Got empty alias or anchor", Start);
1428 return false;
1429 }
1430
1431 Token T;
1432 T.Kind = IsAlias ? Token::TK_Alias : Token::TK_Anchor;
1433 T.Range = StringRef(Start, Current - Start);
1434 TokenQueue.push_back(T);
1435
1436 // Alias and anchors can be simple keys.
Duncan P. N. Exon Smith6eeaff12015-10-08 22:47:55 +00001437 saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
Michael J. Spencer22120c42012-04-03 23:09:22 +00001438
1439 IsSimpleKeyAllowed = false;
1440
1441 return true;
1442}
1443
Alex Lorenza22b250c2015-05-13 23:10:51 +00001444char Scanner::scanBlockChompingIndicator() {
1445 char Indicator = ' ';
1446 if (Current != End && (*Current == '+' || *Current == '-')) {
1447 Indicator = *Current;
1448 skip(1);
1449 }
1450 return Indicator;
1451}
1452
1453/// Get the number of line breaks after chomping.
1454///
1455/// Return the number of trailing line breaks to emit, depending on
1456/// \p ChompingIndicator.
1457static unsigned getChompedLineBreaks(char ChompingIndicator,
1458 unsigned LineBreaks, StringRef Str) {
1459 if (ChompingIndicator == '-') // Strip all line breaks.
1460 return 0;
1461 if (ChompingIndicator == '+') // Keep all line breaks.
1462 return LineBreaks;
1463 // Clip trailing lines.
1464 return Str.empty() ? 0 : 1;
1465}
1466
1467unsigned Scanner::scanBlockIndentationIndicator() {
1468 unsigned Indent = 0;
1469 if (Current != End && (*Current >= '1' && *Current <= '9')) {
1470 Indent = unsigned(*Current - '0');
1471 skip(1);
1472 }
1473 return Indent;
1474}
1475
1476bool Scanner::scanBlockScalarHeader(char &ChompingIndicator,
1477 unsigned &IndentIndicator, bool &IsDone) {
1478 auto Start = Current;
1479
1480 ChompingIndicator = scanBlockChompingIndicator();
1481 IndentIndicator = scanBlockIndentationIndicator();
1482 // Check for the chomping indicator once again.
1483 if (ChompingIndicator == ' ')
1484 ChompingIndicator = scanBlockChompingIndicator();
1485 Current = skip_while(&Scanner::skip_s_white, Current);
1486 skipComment();
1487
1488 if (Current == End) { // EOF, we have an empty scalar.
1489 Token T;
1490 T.Kind = Token::TK_BlockScalar;
1491 T.Range = StringRef(Start, Current - Start);
1492 TokenQueue.push_back(T);
1493 IsDone = true;
1494 return true;
1495 }
1496
1497 if (!consumeLineBreakIfPresent()) {
1498 setError("Expected a line break after block scalar header", Current);
1499 return false;
1500 }
1501 return true;
1502}
1503
1504bool Scanner::findBlockScalarIndent(unsigned &BlockIndent,
1505 unsigned BlockExitIndent,
1506 unsigned &LineBreaks, bool &IsDone) {
1507 unsigned MaxAllSpaceLineCharacters = 0;
1508 StringRef::iterator LongestAllSpaceLine;
1509
1510 while (true) {
1511 advanceWhile(&Scanner::skip_s_space);
1512 if (skip_nb_char(Current) != Current) {
1513 // This line isn't empty, so try and find the indentation.
1514 if (Column <= BlockExitIndent) { // End of the block literal.
1515 IsDone = true;
1516 return true;
1517 }
1518 // We found the block's indentation.
1519 BlockIndent = Column;
1520 if (MaxAllSpaceLineCharacters > BlockIndent) {
1521 setError(
1522 "Leading all-spaces line must be smaller than the block indent",
1523 LongestAllSpaceLine);
Michael J. Spencer22120c42012-04-03 23:09:22 +00001524 return false;
1525 }
Alex Lorenza22b250c2015-05-13 23:10:51 +00001526 return true;
Michael J. Spencer22120c42012-04-03 23:09:22 +00001527 }
Alex Lorenza22b250c2015-05-13 23:10:51 +00001528 if (skip_b_break(Current) != Current &&
1529 Column > MaxAllSpaceLineCharacters) {
1530 // Record the longest all-space line in case it's longer than the
1531 // discovered block indent.
1532 MaxAllSpaceLineCharacters = Column;
1533 LongestAllSpaceLine = Current;
1534 }
1535
1536 // Check for EOF.
1537 if (Current == End) {
1538 IsDone = true;
1539 return true;
1540 }
1541
1542 if (!consumeLineBreakIfPresent()) {
1543 IsDone = true;
1544 return true;
1545 }
1546 ++LineBreaks;
1547 }
1548 return true;
1549}
1550
1551bool Scanner::scanBlockScalarIndent(unsigned BlockIndent,
1552 unsigned BlockExitIndent, bool &IsDone) {
1553 // Skip the indentation.
1554 while (Column < BlockIndent) {
1555 auto I = skip_s_space(Current);
1556 if (I == Current)
1557 break;
1558 Current = I;
Michael J. Spencer22120c42012-04-03 23:09:22 +00001559 ++Column;
1560 }
1561
Alex Lorenza22b250c2015-05-13 23:10:51 +00001562 if (skip_nb_char(Current) == Current)
1563 return true;
1564
1565 if (Column <= BlockExitIndent) { // End of the block literal.
1566 IsDone = true;
1567 return true;
Michael J. Spencer22120c42012-04-03 23:09:22 +00001568 }
1569
Alex Lorenza22b250c2015-05-13 23:10:51 +00001570 if (Column < BlockIndent) {
1571 if (Current != End && *Current == '#') { // Trailing comment.
1572 IsDone = true;
1573 return true;
1574 }
1575 setError("A text line is less indented than the block scalar", Current);
1576 return false;
1577 }
1578 return true; // A normal text line.
1579}
1580
1581bool Scanner::scanBlockScalar(bool IsLiteral) {
1582 // Eat '|' or '>'
1583 assert(*Current == '|' || *Current == '>');
1584 skip(1);
1585
1586 char ChompingIndicator;
1587 unsigned BlockIndent;
1588 bool IsDone = false;
1589 if (!scanBlockScalarHeader(ChompingIndicator, BlockIndent, IsDone))
1590 return false;
1591 if (IsDone)
1592 return true;
1593
1594 auto Start = Current;
1595 unsigned BlockExitIndent = Indent < 0 ? 0 : (unsigned)Indent;
1596 unsigned LineBreaks = 0;
1597 if (BlockIndent == 0) {
1598 if (!findBlockScalarIndent(BlockIndent, BlockExitIndent, LineBreaks,
1599 IsDone))
1600 return false;
1601 }
1602
1603 // Scan the block's scalars body.
1604 SmallString<256> Str;
1605 while (!IsDone) {
1606 if (!scanBlockScalarIndent(BlockIndent, BlockExitIndent, IsDone))
1607 return false;
1608 if (IsDone)
1609 break;
1610
1611 // Parse the current line.
1612 auto LineStart = Current;
1613 advanceWhile(&Scanner::skip_nb_char);
1614 if (LineStart != Current) {
1615 Str.append(LineBreaks, '\n');
1616 Str.append(StringRef(LineStart, Current - LineStart));
1617 LineBreaks = 0;
1618 }
1619
1620 // Check for EOF.
1621 if (Current == End)
1622 break;
1623
1624 if (!consumeLineBreakIfPresent())
1625 break;
1626 ++LineBreaks;
1627 }
1628
1629 if (Current == End && !LineBreaks)
1630 // Ensure that there is at least one line break before the end of file.
1631 LineBreaks = 1;
1632 Str.append(getChompedLineBreaks(ChompingIndicator, LineBreaks, Str), '\n');
1633
1634 // New lines may start a simple key.
1635 if (!FlowLevel)
1636 IsSimpleKeyAllowed = true;
1637
Michael J. Spencer22120c42012-04-03 23:09:22 +00001638 Token T;
Alex Lorenza22b250c2015-05-13 23:10:51 +00001639 T.Kind = Token::TK_BlockScalar;
Michael J. Spencer22120c42012-04-03 23:09:22 +00001640 T.Range = StringRef(Start, Current - Start);
Jonas Devlieghereb2924d92020-01-29 21:14:15 -08001641 T.Value = std::string(Str);
Michael J. Spencer22120c42012-04-03 23:09:22 +00001642 TokenQueue.push_back(T);
1643 return true;
1644}
1645
1646bool Scanner::scanTag() {
1647 StringRef::iterator Start = Current;
1648 unsigned ColStart = Column;
1649 skip(1); // Eat !.
1650 if (Current == End || isBlankOrBreak(Current)); // An empty tag.
1651 else if (*Current == '<') {
1652 skip(1);
1653 scan_ns_uri_char();
1654 if (!consume('>'))
1655 return false;
1656 } else {
1657 // FIXME: Actually parse the c-ns-shorthand-tag rule.
1658 Current = skip_while(&Scanner::skip_ns_char, Current);
1659 }
1660
1661 Token T;
1662 T.Kind = Token::TK_Tag;
1663 T.Range = StringRef(Start, Current - Start);
1664 TokenQueue.push_back(T);
1665
1666 // Tags can be simple keys.
Duncan P. N. Exon Smith6eeaff12015-10-08 22:47:55 +00001667 saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
Michael J. Spencer22120c42012-04-03 23:09:22 +00001668
1669 IsSimpleKeyAllowed = false;
1670
1671 return true;
1672}
1673
1674bool Scanner::fetchMoreTokens() {
1675 if (IsStartOfStream)
1676 return scanStreamStart();
1677
1678 scanToNextToken();
1679
1680 if (Current == End)
1681 return scanStreamEnd();
1682
1683 removeStaleSimpleKeyCandidates();
1684
1685 unrollIndent(Column);
1686
1687 if (Column == 0 && *Current == '%')
1688 return scanDirective();
1689
1690 if (Column == 0 && Current + 4 <= End
1691 && *Current == '-'
1692 && *(Current + 1) == '-'
1693 && *(Current + 2) == '-'
1694 && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1695 return scanDocumentIndicator(true);
1696
1697 if (Column == 0 && Current + 4 <= End
1698 && *Current == '.'
1699 && *(Current + 1) == '.'
1700 && *(Current + 2) == '.'
1701 && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1702 return scanDocumentIndicator(false);
1703
1704 if (*Current == '[')
1705 return scanFlowCollectionStart(true);
1706
1707 if (*Current == '{')
1708 return scanFlowCollectionStart(false);
1709
1710 if (*Current == ']')
1711 return scanFlowCollectionEnd(true);
1712
1713 if (*Current == '}')
1714 return scanFlowCollectionEnd(false);
1715
1716 if (*Current == ',')
1717 return scanFlowEntry();
1718
1719 if (*Current == '-' && isBlankOrBreak(Current + 1))
1720 return scanBlockEntry();
1721
1722 if (*Current == '?' && (FlowLevel || isBlankOrBreak(Current + 1)))
1723 return scanKey();
1724
1725 if (*Current == ':' && (FlowLevel || isBlankOrBreak(Current + 1)))
1726 return scanValue();
1727
1728 if (*Current == '*')
1729 return scanAliasOrAnchor(true);
1730
1731 if (*Current == '&')
1732 return scanAliasOrAnchor(false);
1733
1734 if (*Current == '!')
1735 return scanTag();
1736
1737 if (*Current == '|' && !FlowLevel)
1738 return scanBlockScalar(true);
1739
1740 if (*Current == '>' && !FlowLevel)
1741 return scanBlockScalar(false);
1742
1743 if (*Current == '\'')
1744 return scanFlowScalar(false);
1745
1746 if (*Current == '"')
1747 return scanFlowScalar(true);
1748
1749 // Get a plain scalar.
1750 StringRef FirstChar(Current, 1);
1751 if (!(isBlankOrBreak(Current)
1752 || FirstChar.find_first_of("-?:,[]{}#&*!|>'\"%@`") != StringRef::npos)
1753 || (*Current == '-' && !isBlankOrBreak(Current + 1))
1754 || (!FlowLevel && (*Current == '?' || *Current == ':')
1755 && isBlankOrBreak(Current + 1))
1756 || (!FlowLevel && *Current == ':'
1757 && Current + 2 < End
1758 && *(Current + 1) == ':'
1759 && !isBlankOrBreak(Current + 2)))
1760 return scanPlainScalar();
1761
Simon Pilgrim22257972020-04-03 18:53:38 +01001762 setError("Unrecognized character while tokenizing.", Current);
Michael J. Spencer22120c42012-04-03 23:09:22 +00001763 return false;
1764}
1765
Mehdi Amini3ab3fef2016-11-28 21:38:52 +00001766Stream::Stream(StringRef Input, SourceMgr &SM, bool ShowColors,
1767 std::error_code *EC)
1768 : scanner(new Scanner(Input, SM, ShowColors, EC)), CurrentDoc() {}
Michael J. Spencer22120c42012-04-03 23:09:22 +00001769
Mehdi Amini3ab3fef2016-11-28 21:38:52 +00001770Stream::Stream(MemoryBufferRef InputBuffer, SourceMgr &SM, bool ShowColors,
1771 std::error_code *EC)
1772 : scanner(new Scanner(InputBuffer, SM, ShowColors, EC)), CurrentDoc() {}
Sean Silvaaba82702012-11-19 23:21:47 +00001773
Eugene Zelenko72208a82017-06-21 23:19:47 +00001774Stream::~Stream() = default;
Benjamin Kramera1355d12012-04-04 08:53:34 +00001775
Michael J. Spencer22120c42012-04-03 23:09:22 +00001776bool Stream::failed() { return scanner->failed(); }
1777
Joachim Meyerf64903f2020-08-18 14:33:34 +02001778void Stream::printError(Node *N, const Twine &Msg, SourceMgr::DiagKind Kind) {
Thomas Finch092452d2019-11-05 21:51:04 -08001779 SMRange Range = N ? N->getSourceRange() : SMRange();
Joachim Meyerf64903f2020-08-18 14:33:34 +02001780 scanner->printError(Range.Start, Kind, Msg, Range);
Michael J. Spencer22120c42012-04-03 23:09:22 +00001781}
1782
Michael J. Spencer22120c42012-04-03 23:09:22 +00001783document_iterator Stream::begin() {
1784 if (CurrentDoc)
1785 report_fatal_error("Can only iterate over the stream once");
1786
1787 // Skip Stream-Start.
1788 scanner->getNext();
1789
1790 CurrentDoc.reset(new Document(*this));
1791 return document_iterator(CurrentDoc);
1792}
1793
1794document_iterator Stream::end() {
1795 return document_iterator();
1796}
1797
1798void Stream::skip() {
1799 for (document_iterator i = begin(), e = end(); i != e; ++i)
1800 i->skip();
1801}
1802
Ahmed Charles56440fd2014-03-06 05:51:42 +00001803Node::Node(unsigned int Type, std::unique_ptr<Document> &D, StringRef A,
1804 StringRef T)
1805 : Doc(D), TypeID(Type), Anchor(A), Tag(T) {
Michael J. Spencer22120c42012-04-03 23:09:22 +00001806 SMLoc Start = SMLoc::getFromPointer(peekNext().Range.begin());
1807 SourceRange = SMRange(Start, Start);
1808}
1809
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00001810std::string Node::getVerbatimTag() const {
1811 StringRef Raw = getRawTag();
1812 if (!Raw.empty() && Raw != "!") {
1813 std::string Ret;
1814 if (Raw.find_last_of('!') == 0) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01001815 Ret = std::string(Doc->getTagMap().find("!")->second);
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00001816 Ret += Raw.substr(1);
Richard Trieu73d06522015-01-17 00:46:44 +00001817 return Ret;
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00001818 } else if (Raw.startswith("!!")) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01001819 Ret = std::string(Doc->getTagMap().find("!!")->second);
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00001820 Ret += Raw.substr(2);
Richard Trieu73d06522015-01-17 00:46:44 +00001821 return Ret;
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00001822 } else {
1823 StringRef TagHandle = Raw.substr(0, Raw.find_last_of('!') + 1);
1824 std::map<StringRef, StringRef>::const_iterator It =
1825 Doc->getTagMap().find(TagHandle);
1826 if (It != Doc->getTagMap().end())
Benjamin Krameradcd0262020-01-28 20:23:46 +01001827 Ret = std::string(It->second);
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00001828 else {
1829 Token T;
1830 T.Kind = Token::TK_Tag;
1831 T.Range = TagHandle;
1832 setError(Twine("Unknown tag handle ") + TagHandle, T);
1833 }
1834 Ret += Raw.substr(Raw.find_last_of('!') + 1);
Richard Trieu73d06522015-01-17 00:46:44 +00001835 return Ret;
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00001836 }
1837 }
1838
1839 switch (getType()) {
1840 case NK_Null:
1841 return "tag:yaml.org,2002:null";
1842 case NK_Scalar:
Alex Lorenza22b250c2015-05-13 23:10:51 +00001843 case NK_BlockScalar:
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00001844 // TODO: Tag resolution.
1845 return "tag:yaml.org,2002:str";
1846 case NK_Mapping:
1847 return "tag:yaml.org,2002:map";
1848 case NK_Sequence:
1849 return "tag:yaml.org,2002:seq";
1850 }
1851
1852 return "";
1853}
1854
Michael J. Spencer22120c42012-04-03 23:09:22 +00001855Token &Node::peekNext() {
1856 return Doc->peekNext();
1857}
1858
1859Token Node::getNext() {
1860 return Doc->getNext();
1861}
1862
1863Node *Node::parseBlockNode() {
1864 return Doc->parseBlockNode();
1865}
1866
1867BumpPtrAllocator &Node::getAllocator() {
1868 return Doc->NodeAllocator;
1869}
1870
1871void Node::setError(const Twine &Msg, Token &Tok) const {
1872 Doc->setError(Msg, Tok);
1873}
1874
1875bool Node::failed() const {
1876 return Doc->failed();
1877}
1878
Michael J. Spencer22120c42012-04-03 23:09:22 +00001879StringRef ScalarNode::getValue(SmallVectorImpl<char> &Storage) const {
1880 // TODO: Handle newlines properly. We need to remove leading whitespace.
1881 if (Value[0] == '"') { // Double quoted.
1882 // Pull off the leading and trailing "s.
1883 StringRef UnquotedValue = Value.substr(1, Value.size() - 2);
1884 // Search for characters that would require unescaping the value.
1885 StringRef::size_type i = UnquotedValue.find_first_of("\\\r\n");
1886 if (i != StringRef::npos)
1887 return unescapeDoubleQuoted(UnquotedValue, i, Storage);
1888 return UnquotedValue;
1889 } else if (Value[0] == '\'') { // Single quoted.
1890 // Pull off the leading and trailing 's.
1891 StringRef UnquotedValue = Value.substr(1, Value.size() - 2);
1892 StringRef::size_type i = UnquotedValue.find('\'');
1893 if (i != StringRef::npos) {
1894 // We're going to need Storage.
1895 Storage.clear();
1896 Storage.reserve(UnquotedValue.size());
1897 for (; i != StringRef::npos; i = UnquotedValue.find('\'')) {
1898 StringRef Valid(UnquotedValue.begin(), i);
1899 Storage.insert(Storage.end(), Valid.begin(), Valid.end());
1900 Storage.push_back('\'');
1901 UnquotedValue = UnquotedValue.substr(i + 2);
1902 }
1903 Storage.insert(Storage.end(), UnquotedValue.begin(), UnquotedValue.end());
1904 return StringRef(Storage.begin(), Storage.size());
1905 }
1906 return UnquotedValue;
1907 }
1908 // Plain or block.
Vedant Kumar98372e32016-02-16 02:06:01 +00001909 return Value.rtrim(' ');
Michael J. Spencer22120c42012-04-03 23:09:22 +00001910}
1911
1912StringRef ScalarNode::unescapeDoubleQuoted( StringRef UnquotedValue
1913 , StringRef::size_type i
1914 , SmallVectorImpl<char> &Storage)
1915 const {
1916 // Use Storage to build proper value.
1917 Storage.clear();
1918 Storage.reserve(UnquotedValue.size());
1919 for (; i != StringRef::npos; i = UnquotedValue.find_first_of("\\\r\n")) {
1920 // Insert all previous chars into Storage.
1921 StringRef Valid(UnquotedValue.begin(), i);
1922 Storage.insert(Storage.end(), Valid.begin(), Valid.end());
1923 // Chop off inserted chars.
1924 UnquotedValue = UnquotedValue.substr(i);
1925
1926 assert(!UnquotedValue.empty() && "Can't be empty!");
1927
1928 // Parse escape or line break.
1929 switch (UnquotedValue[0]) {
1930 case '\r':
1931 case '\n':
1932 Storage.push_back('\n');
1933 if ( UnquotedValue.size() > 1
1934 && (UnquotedValue[1] == '\r' || UnquotedValue[1] == '\n'))
1935 UnquotedValue = UnquotedValue.substr(1);
1936 UnquotedValue = UnquotedValue.substr(1);
1937 break;
1938 default:
Thomas Finch092452d2019-11-05 21:51:04 -08001939 if (UnquotedValue.size() == 1) {
1940 Token T;
1941 T.Range = StringRef(UnquotedValue.begin(), 1);
1942 setError("Unrecognized escape code", T);
1943 return "";
1944 }
Michael J. Spencer22120c42012-04-03 23:09:22 +00001945 UnquotedValue = UnquotedValue.substr(1);
1946 switch (UnquotedValue[0]) {
1947 default: {
1948 Token T;
1949 T.Range = StringRef(UnquotedValue.begin(), 1);
Thomas Finch092452d2019-11-05 21:51:04 -08001950 setError("Unrecognized escape code", T);
Michael J. Spencer22120c42012-04-03 23:09:22 +00001951 return "";
1952 }
1953 case '\r':
1954 case '\n':
1955 // Remove the new line.
1956 if ( UnquotedValue.size() > 1
1957 && (UnquotedValue[1] == '\r' || UnquotedValue[1] == '\n'))
1958 UnquotedValue = UnquotedValue.substr(1);
1959 // If this was just a single byte newline, it will get skipped
1960 // below.
1961 break;
1962 case '0':
1963 Storage.push_back(0x00);
1964 break;
1965 case 'a':
1966 Storage.push_back(0x07);
1967 break;
1968 case 'b':
1969 Storage.push_back(0x08);
1970 break;
1971 case 't':
1972 case 0x09:
1973 Storage.push_back(0x09);
1974 break;
1975 case 'n':
1976 Storage.push_back(0x0A);
1977 break;
1978 case 'v':
1979 Storage.push_back(0x0B);
1980 break;
1981 case 'f':
1982 Storage.push_back(0x0C);
1983 break;
1984 case 'r':
1985 Storage.push_back(0x0D);
1986 break;
1987 case 'e':
1988 Storage.push_back(0x1B);
1989 break;
1990 case ' ':
1991 Storage.push_back(0x20);
1992 break;
1993 case '"':
1994 Storage.push_back(0x22);
1995 break;
1996 case '/':
1997 Storage.push_back(0x2F);
1998 break;
1999 case '\\':
2000 Storage.push_back(0x5C);
2001 break;
2002 case 'N':
2003 encodeUTF8(0x85, Storage);
2004 break;
2005 case '_':
2006 encodeUTF8(0xA0, Storage);
2007 break;
2008 case 'L':
2009 encodeUTF8(0x2028, Storage);
2010 break;
2011 case 'P':
2012 encodeUTF8(0x2029, Storage);
2013 break;
2014 case 'x': {
2015 if (UnquotedValue.size() < 3)
2016 // TODO: Report error.
2017 break;
Michael J. Spencera6c2c292012-04-26 19:27:11 +00002018 unsigned int UnicodeScalarValue;
2019 if (UnquotedValue.substr(1, 2).getAsInteger(16, UnicodeScalarValue))
2020 // TODO: Report error.
2021 UnicodeScalarValue = 0xFFFD;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002022 encodeUTF8(UnicodeScalarValue, Storage);
2023 UnquotedValue = UnquotedValue.substr(2);
2024 break;
2025 }
2026 case 'u': {
2027 if (UnquotedValue.size() < 5)
2028 // TODO: Report error.
2029 break;
Michael J. Spencera6c2c292012-04-26 19:27:11 +00002030 unsigned int UnicodeScalarValue;
2031 if (UnquotedValue.substr(1, 4).getAsInteger(16, UnicodeScalarValue))
2032 // TODO: Report error.
2033 UnicodeScalarValue = 0xFFFD;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002034 encodeUTF8(UnicodeScalarValue, Storage);
2035 UnquotedValue = UnquotedValue.substr(4);
2036 break;
2037 }
2038 case 'U': {
2039 if (UnquotedValue.size() < 9)
2040 // TODO: Report error.
2041 break;
Michael J. Spencera6c2c292012-04-26 19:27:11 +00002042 unsigned int UnicodeScalarValue;
2043 if (UnquotedValue.substr(1, 8).getAsInteger(16, UnicodeScalarValue))
2044 // TODO: Report error.
2045 UnicodeScalarValue = 0xFFFD;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002046 encodeUTF8(UnicodeScalarValue, Storage);
2047 UnquotedValue = UnquotedValue.substr(8);
2048 break;
2049 }
2050 }
2051 UnquotedValue = UnquotedValue.substr(1);
2052 }
2053 }
2054 Storage.insert(Storage.end(), UnquotedValue.begin(), UnquotedValue.end());
2055 return StringRef(Storage.begin(), Storage.size());
2056}
2057
2058Node *KeyValueNode::getKey() {
2059 if (Key)
2060 return Key;
2061 // Handle implicit null keys.
2062 {
2063 Token &t = peekNext();
2064 if ( t.Kind == Token::TK_BlockEnd
2065 || t.Kind == Token::TK_Value
2066 || t.Kind == Token::TK_Error) {
2067 return Key = new (getAllocator()) NullNode(Doc);
2068 }
2069 if (t.Kind == Token::TK_Key)
2070 getNext(); // skip TK_Key.
2071 }
2072
2073 // Handle explicit null keys.
2074 Token &t = peekNext();
2075 if (t.Kind == Token::TK_BlockEnd || t.Kind == Token::TK_Value) {
2076 return Key = new (getAllocator()) NullNode(Doc);
2077 }
2078
2079 // We've got a normal key.
2080 return Key = parseBlockNode();
2081}
2082
2083Node *KeyValueNode::getValue() {
2084 if (Value)
2085 return Value;
Thomas Finch092452d2019-11-05 21:51:04 -08002086
2087 if (Node* Key = getKey())
2088 Key->skip();
2089 else {
2090 setError("Null key in Key Value.", peekNext());
2091 return Value = new (getAllocator()) NullNode(Doc);
2092 }
2093
Michael J. Spencer22120c42012-04-03 23:09:22 +00002094 if (failed())
2095 return Value = new (getAllocator()) NullNode(Doc);
2096
2097 // Handle implicit null values.
2098 {
2099 Token &t = peekNext();
2100 if ( t.Kind == Token::TK_BlockEnd
2101 || t.Kind == Token::TK_FlowMappingEnd
2102 || t.Kind == Token::TK_Key
2103 || t.Kind == Token::TK_FlowEntry
2104 || t.Kind == Token::TK_Error) {
2105 return Value = new (getAllocator()) NullNode(Doc);
2106 }
2107
2108 if (t.Kind != Token::TK_Value) {
2109 setError("Unexpected token in Key Value.", t);
2110 return Value = new (getAllocator()) NullNode(Doc);
2111 }
2112 getNext(); // skip TK_Value.
2113 }
2114
2115 // Handle explicit null values.
2116 Token &t = peekNext();
2117 if (t.Kind == Token::TK_BlockEnd || t.Kind == Token::TK_Key) {
2118 return Value = new (getAllocator()) NullNode(Doc);
2119 }
2120
2121 // We got a normal value.
2122 return Value = parseBlockNode();
2123}
2124
2125void MappingNode::increment() {
2126 if (failed()) {
2127 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002128 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002129 return;
2130 }
2131 if (CurrentEntry) {
2132 CurrentEntry->skip();
2133 if (Type == MT_Inline) {
2134 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002135 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002136 return;
2137 }
2138 }
2139 Token T = peekNext();
2140 if (T.Kind == Token::TK_Key || T.Kind == Token::TK_Scalar) {
2141 // KeyValueNode eats the TK_Key. That way it can detect null keys.
2142 CurrentEntry = new (getAllocator()) KeyValueNode(Doc);
2143 } else if (Type == MT_Block) {
2144 switch (T.Kind) {
2145 case Token::TK_BlockEnd:
2146 getNext();
2147 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002148 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002149 break;
2150 default:
2151 setError("Unexpected token. Expected Key or Block End", T);
Galina Kistanova5e6c5422017-05-23 01:20:52 +00002152 LLVM_FALLTHROUGH;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002153 case Token::TK_Error:
2154 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002155 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002156 }
2157 } else {
2158 switch (T.Kind) {
2159 case Token::TK_FlowEntry:
2160 // Eat the flow entry and recurse.
2161 getNext();
2162 return increment();
2163 case Token::TK_FlowMappingEnd:
2164 getNext();
Galina Kistanova5e6c5422017-05-23 01:20:52 +00002165 LLVM_FALLTHROUGH;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002166 case Token::TK_Error:
2167 // Set this to end iterator.
2168 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002169 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002170 break;
2171 default:
2172 setError( "Unexpected token. Expected Key, Flow Entry, or Flow "
2173 "Mapping End."
2174 , T);
2175 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002176 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002177 }
2178 }
2179}
2180
2181void SequenceNode::increment() {
2182 if (failed()) {
2183 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002184 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002185 return;
2186 }
2187 if (CurrentEntry)
2188 CurrentEntry->skip();
2189 Token T = peekNext();
2190 if (SeqType == ST_Block) {
2191 switch (T.Kind) {
2192 case Token::TK_BlockEntry:
2193 getNext();
2194 CurrentEntry = parseBlockNode();
Craig Topper8d399f82014-04-09 04:20:00 +00002195 if (!CurrentEntry) { // An error occurred.
Michael J. Spencer22120c42012-04-03 23:09:22 +00002196 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002197 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002198 }
2199 break;
2200 case Token::TK_BlockEnd:
2201 getNext();
2202 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002203 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002204 break;
2205 default:
2206 setError( "Unexpected token. Expected Block Entry or Block End."
2207 , T);
Galina Kistanova5e6c5422017-05-23 01:20:52 +00002208 LLVM_FALLTHROUGH;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002209 case Token::TK_Error:
2210 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002211 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002212 }
2213 } else if (SeqType == ST_Indentless) {
2214 switch (T.Kind) {
2215 case Token::TK_BlockEntry:
2216 getNext();
2217 CurrentEntry = parseBlockNode();
Craig Topper8d399f82014-04-09 04:20:00 +00002218 if (!CurrentEntry) { // An error occurred.
Michael J. Spencer22120c42012-04-03 23:09:22 +00002219 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002220 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002221 }
2222 break;
2223 default:
2224 case Token::TK_Error:
2225 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002226 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002227 }
2228 } else if (SeqType == ST_Flow) {
2229 switch (T.Kind) {
2230 case Token::TK_FlowEntry:
2231 // Eat the flow entry and recurse.
2232 getNext();
2233 WasPreviousTokenFlowEntry = true;
2234 return increment();
2235 case Token::TK_FlowSequenceEnd:
2236 getNext();
Galina Kistanova5e6c5422017-05-23 01:20:52 +00002237 LLVM_FALLTHROUGH;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002238 case Token::TK_Error:
2239 // Set this to end iterator.
2240 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002241 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002242 break;
2243 case Token::TK_StreamEnd:
2244 case Token::TK_DocumentEnd:
2245 case Token::TK_DocumentStart:
2246 setError("Could not find closing ]!", T);
2247 // Set this to end iterator.
2248 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002249 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002250 break;
2251 default:
2252 if (!WasPreviousTokenFlowEntry) {
2253 setError("Expected , between entries!", T);
2254 IsAtEnd = true;
Craig Topperc10719f2014-04-07 04:17:22 +00002255 CurrentEntry = nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002256 break;
2257 }
2258 // Otherwise it must be a flow entry.
2259 CurrentEntry = parseBlockNode();
2260 if (!CurrentEntry) {
2261 IsAtEnd = true;
2262 }
2263 WasPreviousTokenFlowEntry = false;
2264 break;
2265 }
2266 }
2267}
2268
Craig Topperc10719f2014-04-07 04:17:22 +00002269Document::Document(Stream &S) : stream(S), Root(nullptr) {
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002270 // Tag maps starts with two default mappings.
2271 TagMap["!"] = "!";
2272 TagMap["!!"] = "tag:yaml.org,2002:";
2273
Michael J. Spencer22120c42012-04-03 23:09:22 +00002274 if (parseDirectives())
2275 expectToken(Token::TK_DocumentStart);
2276 Token &T = peekNext();
2277 if (T.Kind == Token::TK_DocumentStart)
2278 getNext();
2279}
2280
2281bool Document::skip() {
2282 if (stream.scanner->failed())
2283 return false;
Thomas Finchac385ca2019-11-11 20:48:28 -08002284 if (!Root && !getRoot())
2285 return false;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002286 Root->skip();
2287 Token &T = peekNext();
2288 if (T.Kind == Token::TK_StreamEnd)
2289 return false;
2290 if (T.Kind == Token::TK_DocumentEnd) {
2291 getNext();
2292 return skip();
2293 }
2294 return true;
2295}
2296
2297Token &Document::peekNext() {
2298 return stream.scanner->peekNext();
2299}
2300
2301Token Document::getNext() {
2302 return stream.scanner->getNext();
2303}
2304
2305void Document::setError(const Twine &Message, Token &Location) const {
2306 stream.scanner->setError(Message, Location.Range.begin());
2307}
2308
2309bool Document::failed() const {
2310 return stream.scanner->failed();
2311}
2312
2313Node *Document::parseBlockNode() {
2314 Token T = peekNext();
2315 // Handle properties.
2316 Token AnchorInfo;
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002317 Token TagInfo;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002318parse_property:
2319 switch (T.Kind) {
2320 case Token::TK_Alias:
2321 getNext();
2322 return new (NodeAllocator) AliasNode(stream.CurrentDoc, T.Range.substr(1));
2323 case Token::TK_Anchor:
2324 if (AnchorInfo.Kind == Token::TK_Anchor) {
2325 setError("Already encountered an anchor for this node!", T);
Craig Topperc10719f2014-04-07 04:17:22 +00002326 return nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002327 }
2328 AnchorInfo = getNext(); // Consume TK_Anchor.
2329 T = peekNext();
2330 goto parse_property;
2331 case Token::TK_Tag:
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002332 if (TagInfo.Kind == Token::TK_Tag) {
2333 setError("Already encountered a tag for this node!", T);
Craig Topperc10719f2014-04-07 04:17:22 +00002334 return nullptr;
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002335 }
2336 TagInfo = getNext(); // Consume TK_Tag.
Michael J. Spencer22120c42012-04-03 23:09:22 +00002337 T = peekNext();
2338 goto parse_property;
2339 default:
2340 break;
2341 }
2342
2343 switch (T.Kind) {
2344 case Token::TK_BlockEntry:
2345 // We got an unindented BlockEntry sequence. This is not terminated with
2346 // a BlockEnd.
2347 // Don't eat the TK_BlockEntry, SequenceNode needs it.
2348 return new (NodeAllocator) SequenceNode( stream.CurrentDoc
2349 , AnchorInfo.Range.substr(1)
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002350 , TagInfo.Range
Michael J. Spencer22120c42012-04-03 23:09:22 +00002351 , SequenceNode::ST_Indentless);
2352 case Token::TK_BlockSequenceStart:
2353 getNext();
2354 return new (NodeAllocator)
2355 SequenceNode( stream.CurrentDoc
2356 , AnchorInfo.Range.substr(1)
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002357 , TagInfo.Range
Michael J. Spencer22120c42012-04-03 23:09:22 +00002358 , SequenceNode::ST_Block);
2359 case Token::TK_BlockMappingStart:
2360 getNext();
2361 return new (NodeAllocator)
2362 MappingNode( stream.CurrentDoc
2363 , AnchorInfo.Range.substr(1)
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002364 , TagInfo.Range
Michael J. Spencer22120c42012-04-03 23:09:22 +00002365 , MappingNode::MT_Block);
2366 case Token::TK_FlowSequenceStart:
2367 getNext();
2368 return new (NodeAllocator)
2369 SequenceNode( stream.CurrentDoc
2370 , AnchorInfo.Range.substr(1)
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002371 , TagInfo.Range
Michael J. Spencer22120c42012-04-03 23:09:22 +00002372 , SequenceNode::ST_Flow);
2373 case Token::TK_FlowMappingStart:
2374 getNext();
2375 return new (NodeAllocator)
2376 MappingNode( stream.CurrentDoc
2377 , AnchorInfo.Range.substr(1)
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002378 , TagInfo.Range
Michael J. Spencer22120c42012-04-03 23:09:22 +00002379 , MappingNode::MT_Flow);
2380 case Token::TK_Scalar:
2381 getNext();
2382 return new (NodeAllocator)
2383 ScalarNode( stream.CurrentDoc
2384 , AnchorInfo.Range.substr(1)
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002385 , TagInfo.Range
Michael J. Spencer22120c42012-04-03 23:09:22 +00002386 , T.Range);
Benjamin Kramer72367332015-05-18 21:11:27 +00002387 case Token::TK_BlockScalar: {
Alex Lorenza22b250c2015-05-13 23:10:51 +00002388 getNext();
Alex Lorenz481dca22015-05-21 19:45:02 +00002389 StringRef NullTerminatedStr(T.Value.c_str(), T.Value.length() + 1);
2390 StringRef StrCopy = NullTerminatedStr.copy(NodeAllocator).drop_back();
Alex Lorenza22b250c2015-05-13 23:10:51 +00002391 return new (NodeAllocator)
2392 BlockScalarNode(stream.CurrentDoc, AnchorInfo.Range.substr(1),
Benjamin Kramer72367332015-05-18 21:11:27 +00002393 TagInfo.Range, StrCopy, T.Range);
2394 }
Michael J. Spencer22120c42012-04-03 23:09:22 +00002395 case Token::TK_Key:
2396 // Don't eat the TK_Key, KeyValueNode expects it.
2397 return new (NodeAllocator)
2398 MappingNode( stream.CurrentDoc
2399 , AnchorInfo.Range.substr(1)
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002400 , TagInfo.Range
Michael J. Spencer22120c42012-04-03 23:09:22 +00002401 , MappingNode::MT_Inline);
2402 case Token::TK_DocumentStart:
2403 case Token::TK_DocumentEnd:
2404 case Token::TK_StreamEnd:
2405 default:
2406 // TODO: Properly handle tags. "[!!str ]" should resolve to !!str "", not
2407 // !!null null.
2408 return new (NodeAllocator) NullNode(stream.CurrentDoc);
Thomas Finch092452d2019-11-05 21:51:04 -08002409 case Token::TK_FlowMappingEnd:
2410 case Token::TK_FlowSequenceEnd:
2411 case Token::TK_FlowEntry: {
2412 if (Root && (isa<MappingNode>(Root) || isa<SequenceNode>(Root)))
2413 return new (NodeAllocator) NullNode(stream.CurrentDoc);
2414
2415 setError("Unexpected token", T);
2416 return nullptr;
2417 }
Michael J. Spencer22120c42012-04-03 23:09:22 +00002418 case Token::TK_Error:
Craig Topperc10719f2014-04-07 04:17:22 +00002419 return nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002420 }
2421 llvm_unreachable("Control flow shouldn't reach here.");
Craig Topperc10719f2014-04-07 04:17:22 +00002422 return nullptr;
Michael J. Spencer22120c42012-04-03 23:09:22 +00002423}
2424
2425bool Document::parseDirectives() {
2426 bool isDirective = false;
2427 while (true) {
2428 Token T = peekNext();
2429 if (T.Kind == Token::TK_TagDirective) {
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002430 parseTAGDirective();
Michael J. Spencer22120c42012-04-03 23:09:22 +00002431 isDirective = true;
2432 } else if (T.Kind == Token::TK_VersionDirective) {
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002433 parseYAMLDirective();
Michael J. Spencer22120c42012-04-03 23:09:22 +00002434 isDirective = true;
2435 } else
2436 break;
2437 }
2438 return isDirective;
2439}
2440
Michael J. Spencerc064a9a2013-10-18 22:38:04 +00002441void Document::parseYAMLDirective() {
2442 getNext(); // Eat %YAML <version>
2443}
2444
2445void Document::parseTAGDirective() {
2446 Token Tag = getNext(); // %TAG <handle> <prefix>
2447 StringRef T = Tag.Range;
2448 // Strip %TAG
2449 T = T.substr(T.find_first_of(" \t")).ltrim(" \t");
2450 std::size_t HandleEnd = T.find_first_of(" \t");
2451 StringRef TagHandle = T.substr(0, HandleEnd);
2452 StringRef TagPrefix = T.substr(HandleEnd).ltrim(" \t");
2453 TagMap[TagHandle] = TagPrefix;
2454}
2455
Michael J. Spencer22120c42012-04-03 23:09:22 +00002456bool Document::expectToken(int TK) {
2457 Token T = getNext();
2458 if (T.Kind != TK) {
2459 setError("Unexpected token", T);
2460 return false;
2461 }
2462 return true;
2463}