37 #include <system_error> 66 switch (uint8_t(Input[0])) {
68 if (Input.
size() >= 4) {
70 && uint8_t(Input[2]) == 0xFE
71 && uint8_t(Input[3]) == 0xFF)
73 if (Input[1] == 0 && Input[2] == 0 && Input[3] != 0)
77 if (Input.
size() >= 2 && Input[1] != 0)
81 if ( Input.
size() >= 4
82 && uint8_t(Input[1]) == 0xFE
87 if (Input.
size() >= 2 && uint8_t(Input[1]) == 0xFE)
91 if (Input.
size() >= 2 && uint8_t(Input[1]) == 0xFF)
95 if ( Input.
size() >= 3
96 && uint8_t(Input[1]) == 0xBB
97 && uint8_t(Input[2]) == 0xBF)
103 if (Input.
size() >= 4 && Input[1] == 0 && Input[2] == 0 && Input[3] == 0)
106 if (Input.
size() >= 2 && Input[1] == 0)
113 void Node::anchor() {}
114 void NullNode::anchor() {}
115 void ScalarNode::anchor() {}
116 void BlockScalarNode::anchor() {}
117 void KeyValueNode::anchor() {}
118 void MappingNode::anchor() {}
119 void SequenceNode::anchor() {}
120 void AliasNode::anchor() {}
183 unsigned FlowLevel = 0;
184 bool IsRequired =
false;
187 return Tok == Other.Tok;
203 if ((*Position & 0x80) == 0) {
204 return std::make_pair(*Position, 1);
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);
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);
227 if (codepoint >= 0x800 &&
228 (codepoint < 0xD800 || codepoint > 0xDFFF))
229 return std::make_pair(codepoint, 3);
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);
245 return std::make_pair(0, 0);
255 std::error_code *EC =
nullptr);
257 std::error_code *EC =
nullptr);
298 return StringRef(Current, End - Current);
384 void advanceWhile(SkipWhileFunc Func);
389 void scan_ns_uri_char();
406 bool consumeLineBreakIfPresent();
417 void removeStaleSimpleKeyCandidates();
420 void removeSimpleKeyCandidatesOnFlowLevel(
unsigned Level);
424 bool unrollIndent(
int ToColumn);
428 bool rollIndent(
int ToColumn
437 void scanToNextToken();
440 bool scanStreamStart();
443 bool scanStreamEnd();
446 bool scanDirective();
449 bool scanDocumentIndicator(
bool IsStart);
452 bool scanFlowCollectionStart(
bool IsSequence);
455 bool scanFlowCollectionEnd(
bool IsSequence);
458 bool scanFlowEntry();
461 bool scanBlockEntry();
470 bool scanFlowScalar(
bool IsDoubleQuoted);
473 bool scanPlainScalar();
476 bool scanAliasOrAnchor(
bool IsAlias);
479 bool scanBlockScalar(
bool IsLiteral);
482 char scanBlockChompingIndicator();
485 unsigned scanBlockIndentationIndicator();
490 bool scanBlockScalarHeader(
char &ChompingIndicator,
unsigned &IndentIndicator,
496 bool findBlockScalarIndent(
unsigned &BlockIndent,
unsigned BlockExitIndent,
497 unsigned &LineBreaks,
bool &IsDone);
502 bool scanBlockScalarIndent(
unsigned BlockIndent,
unsigned BlockExitIndent,
509 bool fetchMoreTokens();
536 bool IsStartOfStream;
539 bool IsSimpleKeyAllowed;
567 if (UnicodeScalarValue <= 0x7F) {
568 Result.
push_back(UnicodeScalarValue & 0x7F);
569 }
else if (UnicodeScalarValue <= 0x7FF) {
570 uint8_t FirstByte = 0xC0 | ((UnicodeScalarValue & 0x7C0) >> 6);
571 uint8_t SecondByte = 0x80 | (UnicodeScalarValue & 0x3F);
574 }
else if (UnicodeScalarValue <= 0xFFFF) {
575 uint8_t FirstByte = 0xE0 | ((UnicodeScalarValue & 0xF000) >> 12);
576 uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
577 uint8_t ThirdByte = 0x80 | (UnicodeScalarValue & 0x3F);
581 }
else if (UnicodeScalarValue <= 0x10FFFF) {
582 uint8_t FirstByte = 0xF0 | ((UnicodeScalarValue & 0x1F0000) >> 18);
583 uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0x3F000) >> 12);
584 uint8_t ThirdByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
585 uint8_t FourthByte = 0x80 | (UnicodeScalarValue & 0x3F);
600 OS <<
"Stream-Start: ";
603 OS <<
"Stream-End: ";
606 OS <<
"Version-Directive: ";
609 OS <<
"Tag-Directive: ";
612 OS <<
"Document-Start: ";
615 OS <<
"Document-End: ";
618 OS <<
"Block-Entry: ";
624 OS <<
"Block-Sequence-Start: ";
627 OS <<
"Block-Mapping-Start: ";
630 OS <<
"Flow-Entry: ";
633 OS <<
"Flow-Sequence-Start: ";
636 OS <<
"Flow-Sequence-End: ";
639 OS <<
"Flow-Mapping-Start: ";
642 OS <<
"Flow-Mapping-End: ";
654 OS <<
"Block Scalar: ";
668 OS << T.
Range <<
"\n";
691 std::string EscapedInput;
694 EscapedInput +=
"\\\\";
696 EscapedInput +=
"\\\"";
698 EscapedInput +=
"\\0";
700 EscapedInput +=
"\\a";
702 EscapedInput +=
"\\b";
704 EscapedInput +=
"\\t";
706 EscapedInput +=
"\\n";
708 EscapedInput +=
"\\v";
710 EscapedInput +=
"\\f";
712 EscapedInput +=
"\\r";
714 EscapedInput +=
"\\e";
715 else if ((
unsigned char)*i < 0x20) {
717 EscapedInput +=
"\\x" + std::string(2 - HexStr.size(),
'0') + HexStr;
718 }
else if (*i & 0x80) {
721 if (UnicodeScalarValue.second == 0) {
725 EscapedInput.insert(EscapedInput.end(), Val.
begin(), Val.
end());
729 if (UnicodeScalarValue.first == 0x85)
730 EscapedInput +=
"\\N";
731 else if (UnicodeScalarValue.first == 0xA0)
732 EscapedInput +=
"\\_";
733 else if (UnicodeScalarValue.first == 0x2028)
734 EscapedInput +=
"\\L";
735 else if (UnicodeScalarValue.first == 0x2029)
736 EscapedInput +=
"\\P";
737 else if (!EscapePrintable &&
739 EscapedInput +=
StringRef(i, UnicodeScalarValue.second);
741 std::string HexStr =
utohexstr(UnicodeScalarValue.first);
742 if (HexStr.size() <= 2)
743 EscapedInput +=
"\\x" + std::string(2 - HexStr.size(),
'0') + HexStr;
744 else if (HexStr.size() <= 4)
745 EscapedInput +=
"\\u" + std::string(4 - HexStr.size(),
'0') + HexStr;
746 else if (HexStr.size() <= 8)
747 EscapedInput +=
"\\U" + std::string(8 - HexStr.size(),
'0') + HexStr;
749 i += UnicodeScalarValue.second - 1;
751 EscapedInput.push_back(*i);
758 : SM(sm), ShowColors(ShowColors), EC(EC) {
764 : SM(SM_), ShowColors(ShowColors), EC(EC) {
769 InputBuffer = Buffer;
776 IsStartOfStream =
true;
777 IsSimpleKeyAllowed =
true;
779 std::unique_ptr<MemoryBuffer> InputBufferOwner =
787 bool NeedMore =
false;
789 if (TokenQueue.
empty() || NeedMore) {
790 if (!fetchMoreTokens()) {
794 return TokenQueue.
front();
798 "fetchMoreTokens lied about getting tokens!");
800 removeStaleSimpleKeyCandidates();
802 SK.Tok = TokenQueue.
begin();
808 return TokenQueue.
front();
814 if (!TokenQueue.
empty())
819 if (TokenQueue.
empty())
829 if ( *Position == 0x09
830 || (*Position >= 0x20 && *Position <= 0x7E))
834 if (uint8_t(*Position) & 0x80) {
837 && u8d.first != 0xFEFF
838 && ( u8d.first == 0x85
839 || ( u8d.first >= 0xA0
840 && u8d.first <= 0xD7FF)
841 || ( u8d.first >= 0xE000
842 && u8d.first <= 0xFFFD)
843 || ( u8d.first >= 0x10000
844 && u8d.first <= 0x10FFFF)))
845 return Position + u8d.second;
853 if (*Position == 0x0D) {
854 if (Position + 1 != End && *(Position + 1) == 0x0A)
859 if (*Position == 0x0A)
867 if (*Position ==
' ')
875 if (*Position ==
' ' || *Position ==
'\t')
883 if (*Position ==
' ' || *Position ==
'\t')
885 return skip_nb_char(Position);
899 void Scanner::advanceWhile(SkipWhileFunc Func) {
900 auto Final = skip_while(Func, Current);
901 Column += Final - Current;
906 return (C >=
'0' && C <=
'9')
907 || (C >=
'a' && C <=
'z')
908 || (C >=
'A' && C <=
'Z');
913 || (C >=
'a' && C <=
'z')
914 || (C >=
'A' && C <=
'Z');
917 void Scanner::scan_ns_uri_char() {
921 if (( *Current ==
'%' 926 ||
StringRef(Current, 1).find_first_of(
"#;/?:@&=+$,_.!~*'()[]")
936 if (Expected >= 0x80) {
937 setError(
"Cannot consume non-ascii characters");
942 if (uint8_t(*Current) >= 0x80) {
943 setError(
"Cannot consume non-ascii characters");
946 if (uint8_t(*Current) == Expected) {
954 void Scanner::skip(
uint32_t Distance) {
957 assert(Current <= End &&
"Skipped past the end");
963 return *Position ==
' ' || *Position ==
'\t' || *Position ==
'\r' ||
967 bool Scanner::consumeLineBreakIfPresent() {
968 auto Next = skip_b_break(Current);
980 if (IsSimpleKeyAllowed) {
984 SK.Column = AtColumn;
985 SK.IsRequired = IsRequired;
986 SK.FlowLevel = FlowLevel;
991 void Scanner::removeStaleSimpleKeyCandidates() {
993 i != SimpleKeys.
end();) {
994 if (i->Line != Line || i->Column + 1024 < Column) {
996 setError(
"Could not find expected : for simple key" 997 , i->Tok->Range.begin());
998 i = SimpleKeys.
erase(i);
1004 void Scanner::removeSimpleKeyCandidatesOnFlowLevel(
unsigned Level) {
1005 if (!SimpleKeys.
empty() && (SimpleKeys.
end() - 1)->FlowLevel == Level)
1009 bool Scanner::unrollIndent(
int ToColumn) {
1015 while (Indent > ToColumn) {
1025 bool Scanner::rollIndent(
int ToColumn
1030 if (Indent < ToColumn) {
1037 TokenQueue.
insert(InsertPoint, T);
1042 void Scanner::skipComment() {
1043 if (*Current !=
'#')
1056 void Scanner::scanToNextToken() {
1058 while (*Current ==
' ' || *Current ==
'\t') {
1073 IsSimpleKeyAllowed =
true;
1077 bool Scanner::scanStreamStart() {
1078 IsStartOfStream =
false;
1086 Current += EI.second;
1090 bool Scanner::scanStreamEnd() {
1099 IsSimpleKeyAllowed =
false;
1108 bool Scanner::scanDirective() {
1112 IsSimpleKeyAllowed =
false;
1117 Current = skip_while(&Scanner::skip_ns_char, Current);
1119 Current = skip_while(&Scanner::skip_s_white, Current);
1122 if (Name ==
"YAML") {
1123 Current = skip_while(&Scanner::skip_ns_char, Current);
1128 }
else if(Name ==
"TAG") {
1129 Current = skip_while(&Scanner::skip_ns_char, Current);
1130 Current = skip_while(&Scanner::skip_s_white, Current);
1131 Current = skip_while(&Scanner::skip_ns_char, Current);
1140 bool Scanner::scanDocumentIndicator(
bool IsStart) {
1143 IsSimpleKeyAllowed =
false;
1153 bool Scanner::scanFlowCollectionStart(
bool IsSequence) {
1162 saveSimpleKeyCandidate(--TokenQueue.
end(), Column - 1,
false);
1165 IsSimpleKeyAllowed =
true;
1170 bool Scanner::scanFlowCollectionEnd(
bool IsSequence) {
1171 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1172 IsSimpleKeyAllowed =
false;
1184 bool Scanner::scanFlowEntry() {
1185 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1186 IsSimpleKeyAllowed =
true;
1195 bool Scanner::scanBlockEntry() {
1197 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1198 IsSimpleKeyAllowed =
true;
1207 bool Scanner::scanKey() {
1211 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1212 IsSimpleKeyAllowed = !FlowLevel;
1222 bool Scanner::scanValue() {
1225 if (!SimpleKeys.
empty()) {
1229 T.
Range = SK.Tok->Range;
1231 for (i = TokenQueue.
begin(), e = TokenQueue.
end(); i !=
e; ++i) {
1239 i = TokenQueue.
insert(i, T);
1244 IsSimpleKeyAllowed =
false;
1248 IsSimpleKeyAllowed = !FlowLevel;
1268 assert(Position - 1 >= First);
1272 while (I >= First && *I ==
'\\') --
I;
1275 return (Position - 1 - I) % 2 == 1;
1278 bool Scanner::scanFlowScalar(
bool IsDoubleQuoted) {
1280 unsigned ColStart = Column;
1281 if (IsDoubleQuoted) {
1284 while (Current != End && *Current !=
'"')
1288 }
while ( Current != End
1289 && *(Current - 1) ==
'\\' 1295 if (Current + 1 < End && *Current ==
'\'' && *(Current + 1) ==
'\'') {
1298 }
else if (*Current ==
'\'')
1302 i = skip_b_break(Current);
1317 if (Current == End) {
1318 setError(
"Expected quote at end of scalar", Current);
1328 saveSimpleKeyCandidate(--TokenQueue.
end(), ColStart,
false);
1330 IsSimpleKeyAllowed =
false;
1335 bool Scanner::scanPlainScalar() {
1337 unsigned ColStart = Column;
1338 unsigned LeadingBlanks = 0;
1339 assert(Indent >= -1 &&
"Indent must be >= -1 !");
1340 unsigned indent =
static_cast<unsigned>(Indent + 1);
1342 if (*Current ==
'#')
1345 while (!isBlankOrBreak(Current)) {
1346 if ( FlowLevel && *Current ==
':' 1347 && !(isBlankOrBreak(Current + 1) || *(Current + 1) ==
',')) {
1348 setError(
"Found unexpected ':' while scanning a plain scalar", Current);
1353 if ( (*Current ==
':' && isBlankOrBreak(Current + 1))
1355 && (
StringRef(Current, 1).find_first_of(
",:?[]{}")
1367 if (!isBlankOrBreak(Current))
1372 while (isBlankOrBreak(Tmp)) {
1375 if (LeadingBlanks && (Column < indent) && *Tmp ==
'\t') {
1376 setError(
"Found invalid tab character in indentation", Tmp);
1382 i = skip_b_break(Tmp);
1391 if (!FlowLevel && Column < indent)
1396 if (Start == Current) {
1397 setError(
"Got empty plain scalar", Start);
1406 saveSimpleKeyCandidate(--TokenQueue.
end(), ColStart,
false);
1408 IsSimpleKeyAllowed =
false;
1413 bool Scanner::scanAliasOrAnchor(
bool IsAlias) {
1415 unsigned ColStart = Column;
1418 if ( *Current ==
'[' || *Current ==
']' 1419 || *Current ==
'{' || *Current ==
'}' 1430 if (Start == Current) {
1431 setError(
"Got empty alias or anchor", Start);
1441 saveSimpleKeyCandidate(--TokenQueue.
end(), ColStart,
false);
1443 IsSimpleKeyAllowed =
false;
1448 char Scanner::scanBlockChompingIndicator() {
1449 char Indicator =
' ';
1450 if (Current != End && (*Current ==
'+' || *Current ==
'-')) {
1451 Indicator = *Current;
1463 if (ChompingIndicator ==
'-')
1465 if (ChompingIndicator ==
'+')
1468 return Str.
empty() ? 0 : 1;
1471 unsigned Scanner::scanBlockIndentationIndicator() {
1472 unsigned Indent = 0;
1473 if (Current != End && (*Current >=
'1' && *Current <=
'9')) {
1480 bool Scanner::scanBlockScalarHeader(
char &ChompingIndicator,
1481 unsigned &IndentIndicator,
bool &IsDone) {
1482 auto Start = Current;
1484 ChompingIndicator = scanBlockChompingIndicator();
1485 IndentIndicator = scanBlockIndentationIndicator();
1487 if (ChompingIndicator ==
' ')
1488 ChompingIndicator = scanBlockChompingIndicator();
1489 Current = skip_while(&Scanner::skip_s_white, Current);
1492 if (Current == End) {
1501 if (!consumeLineBreakIfPresent()) {
1502 setError(
"Expected a line break after block scalar header", Current);
1508 bool Scanner::findBlockScalarIndent(
unsigned &BlockIndent,
1509 unsigned BlockExitIndent,
1510 unsigned &LineBreaks,
bool &IsDone) {
1511 unsigned MaxAllSpaceLineCharacters = 0;
1515 advanceWhile(&Scanner::skip_s_space);
1516 if (skip_nb_char(Current) != Current) {
1518 if (Column <= BlockExitIndent) {
1523 BlockIndent = Column;
1524 if (MaxAllSpaceLineCharacters > BlockIndent) {
1526 "Leading all-spaces line must be smaller than the block indent",
1527 LongestAllSpaceLine);
1532 if (skip_b_break(Current) != Current &&
1533 Column > MaxAllSpaceLineCharacters) {
1536 MaxAllSpaceLineCharacters = Column;
1537 LongestAllSpaceLine = Current;
1541 if (Current == End) {
1546 if (!consumeLineBreakIfPresent()) {
1555 bool Scanner::scanBlockScalarIndent(
unsigned BlockIndent,
1556 unsigned BlockExitIndent,
bool &IsDone) {
1558 while (Column < BlockIndent) {
1559 auto I = skip_s_space(Current);
1566 if (skip_nb_char(Current) == Current)
1569 if (Column <= BlockExitIndent) {
1574 if (Column < BlockIndent) {
1575 if (Current != End && *Current ==
'#') {
1579 setError(
"A text line is less indented than the block scalar", Current);
1585 bool Scanner::scanBlockScalar(
bool IsLiteral) {
1587 assert(*Current ==
'|' || *Current ==
'>');
1590 char ChompingIndicator;
1591 unsigned BlockIndent;
1592 bool IsDone =
false;
1593 if (!scanBlockScalarHeader(ChompingIndicator, BlockIndent, IsDone))
1598 auto Start = Current;
1599 unsigned BlockExitIndent = Indent < 0 ? 0 : (
unsigned)Indent;
1600 unsigned LineBreaks = 0;
1601 if (BlockIndent == 0) {
1602 if (!findBlockScalarIndent(BlockIndent, BlockExitIndent, LineBreaks,
1610 if (!scanBlockScalarIndent(BlockIndent, BlockExitIndent, IsDone))
1616 auto LineStart = Current;
1617 advanceWhile(&Scanner::skip_nb_char);
1618 if (LineStart != Current) {
1619 Str.
append(LineBreaks,
'\n');
1628 if (!consumeLineBreakIfPresent())
1633 if (Current == End && !LineBreaks)
1640 IsSimpleKeyAllowed =
true;
1650 bool Scanner::scanTag() {
1652 unsigned ColStart = Column;
1654 if (Current == End || isBlankOrBreak(Current));
1655 else if (*Current ==
'<') {
1662 Current = skip_while(&Scanner::skip_ns_char, Current);
1671 saveSimpleKeyCandidate(--TokenQueue.
end(), ColStart,
false);
1673 IsSimpleKeyAllowed =
false;
1678 bool Scanner::fetchMoreTokens() {
1679 if (IsStartOfStream)
1680 return scanStreamStart();
1685 return scanStreamEnd();
1687 removeStaleSimpleKeyCandidates();
1689 unrollIndent(Column);
1691 if (Column == 0 && *Current ==
'%')
1692 return scanDirective();
1694 if (Column == 0 && Current + 4 <= End
1696 && *(Current + 1) ==
'-' 1697 && *(Current + 2) ==
'-' 1698 && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1699 return scanDocumentIndicator(
true);
1701 if (Column == 0 && Current + 4 <= End
1703 && *(Current + 1) ==
'.' 1704 && *(Current + 2) ==
'.' 1705 && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1706 return scanDocumentIndicator(
false);
1708 if (*Current ==
'[')
1709 return scanFlowCollectionStart(
true);
1711 if (*Current ==
'{')
1712 return scanFlowCollectionStart(
false);
1714 if (*Current ==
']')
1715 return scanFlowCollectionEnd(
true);
1717 if (*Current ==
'}')
1718 return scanFlowCollectionEnd(
false);
1720 if (*Current ==
',')
1721 return scanFlowEntry();
1723 if (*Current ==
'-' && isBlankOrBreak(Current + 1))
1724 return scanBlockEntry();
1726 if (*Current ==
'?' && (FlowLevel || isBlankOrBreak(Current + 1)))
1729 if (*Current ==
':' && (FlowLevel || isBlankOrBreak(Current + 1)))
1732 if (*Current ==
'*')
1733 return scanAliasOrAnchor(
true);
1735 if (*Current ==
'&')
1736 return scanAliasOrAnchor(
false);
1738 if (*Current ==
'!')
1741 if (*Current ==
'|' && !FlowLevel)
1742 return scanBlockScalar(
true);
1744 if (*Current ==
'>' && !FlowLevel)
1745 return scanBlockScalar(
false);
1747 if (*Current ==
'\'')
1748 return scanFlowScalar(
false);
1750 if (*Current ==
'"')
1751 return scanFlowScalar(
true);
1755 if (!(isBlankOrBreak(Current)
1757 || (*Current ==
'-' && !isBlankOrBreak(Current + 1))
1758 || (!FlowLevel && (*Current ==
'?' || *Current ==
':')
1759 && isBlankOrBreak(Current + 1))
1760 || (!FlowLevel && *Current ==
':' 1761 && Current + 2 < End
1762 && *(Current + 1) ==
':' 1763 && !isBlankOrBreak(Current + 2)))
1764 return scanPlainScalar();
1766 setError(
"Unrecognized character while tokenizing.");
1771 std::error_code *EC)
1772 : scanner(new
Scanner(Input, SM, ShowColors, EC)), CurrentDoc() {}
1775 std::error_code *EC)
1776 : scanner(new
Scanner(InputBuffer, SM, ShowColors, EC)), CurrentDoc() {}
1784 scanner->printError( Range.
Start 1797 CurrentDoc.reset(
new Document(*
this));
1812 : Doc(D),
TypeID(Type), Anchor(A), Tag(T) {
1819 if (!Raw.
empty() && Raw !=
"!") {
1822 Ret =
Doc->getTagMap().find(
"!")->second;
1826 Ret =
Doc->getTagMap().find(
"!!")->second;
1831 std::map<StringRef, StringRef>::const_iterator It =
1832 Doc->getTagMap().find(TagHandle);
1833 if (It !=
Doc->getTagMap().end())
1838 T.Range = TagHandle;
1848 return "tag:yaml.org,2002:null";
1852 return "tag:yaml.org,2002:str";
1854 return "tag:yaml.org,2002:map";
1856 return "tag:yaml.org,2002:seq";
1863 return Doc->peekNext();
1867 return Doc->getNext();
1871 return Doc->parseBlockNode();
1875 return Doc->NodeAllocator;
1879 Doc->setError(Msg, Tok);
1883 return Doc->failed();
1888 if (
Value[0] ==
'"') {
1894 return unescapeDoubleQuoted(UnquotedValue, i, Storage);
1895 return UnquotedValue;
1896 }
else if (
Value[0] ==
'\'') {
1906 Storage.
insert(Storage.
end(), Valid.begin(), Valid.end());
1908 UnquotedValue = UnquotedValue.
substr(i + 2);
1913 return UnquotedValue;
1916 return Value.rtrim(
' ');
1929 Storage.
insert(Storage.
end(), Valid.begin(), Valid.end());
1931 UnquotedValue = UnquotedValue.
substr(i);
1933 assert(!UnquotedValue.
empty() &&
"Can't be empty!");
1936 switch (UnquotedValue[0]) {
1940 if ( UnquotedValue.
size() > 1
1941 && (UnquotedValue[1] ==
'\r' || UnquotedValue[1] ==
'\n'))
1942 UnquotedValue = UnquotedValue.
substr(1);
1943 UnquotedValue = UnquotedValue.
substr(1);
1946 if (UnquotedValue.
size() == 1) {
1949 setError(
"Unrecognized escape code", T);
1952 UnquotedValue = UnquotedValue.
substr(1);
1953 switch (UnquotedValue[0]) {
1957 setError(
"Unrecognized escape code", T);
1963 if ( UnquotedValue.
size() > 1
1964 && (UnquotedValue[1] ==
'\r' || UnquotedValue[1] ==
'\n'))
1965 UnquotedValue = UnquotedValue.
substr(1);
2022 if (UnquotedValue.
size() < 3)
2025 unsigned int UnicodeScalarValue;
2028 UnicodeScalarValue = 0xFFFD;
2030 UnquotedValue = UnquotedValue.
substr(2);
2034 if (UnquotedValue.
size() < 5)
2037 unsigned int UnicodeScalarValue;
2040 UnicodeScalarValue = 0xFFFD;
2042 UnquotedValue = UnquotedValue.
substr(4);
2046 if (UnquotedValue.
size() < 9)
2049 unsigned int UnicodeScalarValue;
2052 UnicodeScalarValue = 0xFFFD;
2054 UnquotedValue = UnquotedValue.
substr(8);
2058 UnquotedValue = UnquotedValue.
substr(1);
2116 setError(
"Unexpected token in Key Value.", t);
2132 void MappingNode::increment() {
2135 CurrentEntry =
nullptr;
2139 CurrentEntry->skip();
2140 if (
Type == MT_Inline) {
2142 CurrentEntry =
nullptr;
2150 }
else if (
Type == MT_Block) {
2155 CurrentEntry =
nullptr;
2158 setError(
"Unexpected token. Expected Key or Block End", T);
2162 CurrentEntry =
nullptr;
2176 CurrentEntry =
nullptr;
2179 setError(
"Unexpected token. Expected Key, Flow Entry, or Flow " 2183 CurrentEntry =
nullptr;
2191 CurrentEntry =
nullptr;
2195 CurrentEntry->skip();
2197 if (SeqType == ST_Block) {
2202 if (!CurrentEntry) {
2204 CurrentEntry =
nullptr;
2210 CurrentEntry =
nullptr;
2213 setError(
"Unexpected token. Expected Block Entry or Block End." 2218 CurrentEntry =
nullptr;
2220 }
else if (SeqType == ST_Indentless) {
2225 if (!CurrentEntry) {
2227 CurrentEntry =
nullptr;
2233 CurrentEntry =
nullptr;
2235 }
else if (SeqType == ST_Flow) {
2240 WasPreviousTokenFlowEntry =
true;
2248 CurrentEntry =
nullptr;
2253 setError(
"Could not find closing ]!", T);
2256 CurrentEntry =
nullptr;
2259 if (!WasPreviousTokenFlowEntry) {
2260 setError(
"Expected , between entries!", T);
2262 CurrentEntry =
nullptr;
2267 if (!CurrentEntry) {
2270 WasPreviousTokenFlowEntry =
false;
2279 TagMap[
"!!"] =
"tag:yaml.org,2002:";
2281 if (parseDirectives())
2289 if (stream.scanner->failed())
2304 Token &Document::peekNext() {
2305 return stream.scanner->peekNext();
2308 Token Document::getNext() {
2309 return stream.scanner->getNext();
2312 void Document::setError(
const Twine &Message,
Token &Location)
const {
2313 stream.scanner->setError(Message, Location.
Range.
begin());
2316 bool Document::failed()
const {
2317 return stream.scanner->failed();
2332 setError(
"Already encountered an anchor for this node!", T);
2335 AnchorInfo = getNext();
2337 goto parse_property;
2340 setError(
"Already encountered a tag for this node!", T);
2343 TagInfo = getNext();
2345 goto parse_property;
2355 return new (NodeAllocator)
SequenceNode( stream.CurrentDoc
2361 return new (NodeAllocator)
2368 return new (NodeAllocator)
2375 return new (NodeAllocator)
2382 return new (NodeAllocator)
2389 return new (NodeAllocator)
2398 return new (NodeAllocator)
2404 return new (NodeAllocator)
2415 return new (NodeAllocator)
NullNode(stream.CurrentDoc);
2419 if (Root && (isa<MappingNode>(Root) || isa<SequenceNode>(Root)))
2420 return new (NodeAllocator)
NullNode(stream.CurrentDoc);
2422 setError(
"Unexpected token", T);
2432 bool Document::parseDirectives() {
2433 bool isDirective =
false;
2437 parseTAGDirective();
2440 parseYAMLDirective();
2448 void Document::parseYAMLDirective() {
2452 void Document::parseTAGDirective() {
2453 Token Tag = getNext();
2460 TagMap[TagHandle] = TagPrefix;
2463 bool Document::expectToken(
int TK) {
2466 setError(
"Unexpected token", T);
Represents a range in source code.
std::unique_ptr< Document > & Doc
bool operator==(const BinaryRef &LHS, const BinaryRef &RHS)
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
StringRef getRawTag() const
Get the tag as it was written in the document.
const char * getBufferEnd() const
A linked-list with a custom, local allocator.
Node(unsigned int Type, std::unique_ptr< Document > &, StringRef Anchor, StringRef Tag)
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
Not a valid Unicode encoding.
Scanner(StringRef Input, SourceMgr &SM, bool ShowColors=true, std::error_code *EC=nullptr)
bool scanTokens(StringRef Input)
Scans all tokens in input without outputting anything.
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
std::pair< UnicodeEncodingForm, unsigned > EncodingInfo
EncodingInfo - Holds the encoding type and length of the byte order mark if it exists.
void push_back(const T &Elt)
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
Optional< std::vector< StOtherPiece > > Other
std::string Value
The value of a block scalar node.
Represents a YAML sequence created from either a block sequence for a flow sequence.
static LLVM_ATTRIBUTE_NOINLINE bool wasEscaped(StringRef::iterator First, StringRef::iterator Position)
LLVM_NODISCARD size_t find_last_of(char C, size_t From=npos) const
Find the last character in the string that is C, or npos if not found.
Node * getKey()
Parse and return the key.
std::string escape(StringRef Input, bool EscapePrintable=true)
Escape Input for a double quoted scalar; if EscapePrintable is true, all UTF8 sequences will be escap...
void resetAlloc()
Reset the underlying allocator.
document_iterator begin()
Represents an alias to a Node with an anchor.
LLVM_NODISCARD StringRef ltrim(char Char) const
Return string with consecutive Char characters starting from the the left removed.
void reserve(size_type N)
void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges=None, ArrayRef< SMFixIt > FixIts=None, bool ShowColors=true) const
Emit a message about the specified location with the specified string.
static bool is_ns_hex_digit(const char C)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_NODISCARD StringRef copy(Allocator &A) const
bool failed()
Returns true if an error occurred while parsing.
std::error_code make_error_code(BitcodeError E)
TypeID
Definitions of all of the base types for the Type system.
Tagged union holding either a T or a Error.
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
static EncodingInfo getUnicodeEncoding(StringRef Input)
getUnicodeEncoding - Reads up to the first 4 bytes to determine the Unicode encoding form of Input...
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Position
Position to insert a new instruction relative to an existing instruction.
StringRef str() const
Explicit conversion to StringRef.
bool isPrintable(int UCS)
Determines if a character is likely to be displayed correctly on the terminal.
Node * getRoot()
Parse and return the root level node.
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
LLVM_NODISCARD size_t size() const
size - Get the string size.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
std::pair< uint32_t, unsigned > UTF8Decoded
The Unicode scalar value of a UTF-8 minimal well-formed code unit subsequence and the subsequence's l...
void append(in_iter S, in_iter E)
Append from an iterator pair.
bool dumpTokens(StringRef Input, raw_ostream &)
Dump all the tokens in this stream to OS.
initializer< Ty > init(const Ty &Val)
IteratorImpl< T, typename list_type::iterator > iterator
The instances of the Type class are immutable: once they are created, they are never changed...
void printError(Node *N, const Twine &Msg)
Allocate memory in an ever growing pool, as if by bump-pointer.
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
static unsigned getChompedLineBreaks(char ChompingIndicator, unsigned LineBreaks, StringRef Str)
Get the number of line breaks after chomping.
Document(Stream &ParentStream)
StringRef Range
A string of length 0 or more whose begin() points to the logical location of the token in the input...
void printError(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Message, ArrayRef< SMRange > Ranges=None)
Token getNext()
Parse the next token and pop it from the queue.
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling...
iterator erase(const_iterator CI)
BumpPtrAllocator & getAllocator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
A scalar node is an opaque datum that can be presented as a series of zero or more Unicode scalar val...
static Cursor skipComment(Cursor C)
Skip a line comment and return the updated cursor.
void setError(const Twine &Message, StringRef::iterator Position)
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
void setError(const Twine &Message, Token &Location) const
Node * getValue()
Parse and return the value.
testing::Matcher< const detail::ErrorHolder & > Failed()
bool skip()
Finish parsing the current document and return true if there are more.
enum llvm::yaml::Token::TokenKind Kind
Token & peekNext()
Parse the next token and return it without popping it.
This class represents a YAML stream potentially containing multiple documents.
#define LLVM_ATTRIBUTE_NOINLINE
LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, mark a method "not for inl...
LLVM_NODISCARD T pop_back_val()
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
iterator insert(iterator I, T &&V)
static void encodeUTF8(uint32_t UnicodeScalarValue, SmallVectorImpl< char > &Result)
encodeUTF8 - Encode UnicodeScalarValue in UTF-8 and append it to result.
void setError(const Twine &Message)
iterator insert(iterator I, T &&Elt)
static UTF8Decoded decodeUTF8(StringRef Range)
static SMLoc getFromPointer(const char *Ptr)
Stream(StringRef Input, SourceMgr &, bool ShowColors=true, std::error_code *EC=nullptr)
This keeps a reference to the string referenced by Input.
unsigned int getType() const
LLVM_NODISCARD bool empty() const
LLVM_NODISCARD size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Token - A single YAML token.
A block scalar node is an opaque datum that can be presented as a series of zero or more Unicode scal...
Represents a YAML map created from either a block map for a flow map.
Scans YAML tokens from a MemoryBuffer.
Iterator abstraction for Documents over a Stream.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const char * getBufferStart() const
LLVM Value Representation.
LLVM_NODISCARD StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
This class implements an extremely fast bulk output stream that can only output to a stream...
std::string getVerbatimTag() const
Get the verbatium tag for a given Node.
StringRef - Represent a constant reference to a string, i.e.
StringRef getValue(SmallVectorImpl< char > &Storage) const
Gets the value of this node as a StringRef.
Represents a location in source code.
An inline mapping node is used for "[key: value]".
Node * parseBlockNode()
Root for parsing a node. Returns a single node.
SMRange getSourceRange() const
std::string utohexstr(uint64_t X, bool LowerCase=false)
Abstract base class for all Nodes.
static bool is_ns_word_char(const char C)
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.