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() {}
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);
286 setError(Message, 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";
738 std::string HexStr =
utohexstr(UnicodeScalarValue.first);
739 if (HexStr.size() <= 2)
740 EscapedInput +=
"\\x" + std::string(2 - HexStr.size(),
'0') + HexStr;
741 else if (HexStr.size() <= 4)
742 EscapedInput +=
"\\u" + std::string(4 - HexStr.size(),
'0') + HexStr;
743 else if (HexStr.size() <= 8)
744 EscapedInput +=
"\\U" + std::string(8 - HexStr.size(),
'0') + HexStr;
746 i += UnicodeScalarValue.second - 1;
748 EscapedInput.push_back(*i);
755 : SM(sm), ShowColors(ShowColors), EC(EC) {
761 : SM(SM_), ShowColors(ShowColors), EC(EC) {
766 InputBuffer = Buffer;
773 IsStartOfStream =
true;
774 IsSimpleKeyAllowed =
true;
776 std::unique_ptr<MemoryBuffer> InputBufferOwner =
784 bool NeedMore =
false;
786 if (TokenQueue.
empty() || NeedMore) {
787 if (!fetchMoreTokens()) {
790 return TokenQueue.
front();
794 "fetchMoreTokens lied about getting tokens!");
796 removeStaleSimpleKeyCandidates();
798 SK.Tok = TokenQueue.
begin();
804 return TokenQueue.
front();
810 if (!TokenQueue.
empty())
815 if (TokenQueue.
empty())
825 if ( *Position == 0x09
826 || (*Position >= 0x20 && *Position <= 0x7E))
830 if (uint8_t(*Position) & 0x80) {
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;
849 if (*Position == 0x0D) {
850 if (Position + 1 != End && *(Position + 1) == 0x0A)
855 if (*Position == 0x0A)
863 if (*Position ==
' ')
871 if (*Position ==
' ' || *Position ==
'\t')
879 if (*Position ==
' ' || *Position ==
'\t')
881 return skip_nb_char(Position);
895 void Scanner::advanceWhile(SkipWhileFunc Func) {
896 auto Final = skip_while(Func, Current);
897 Column += Final - Current;
902 return (C >=
'0' && C <=
'9')
903 || (C >=
'a' && C <=
'z')
904 || (C >=
'A' && C <=
'Z');
909 || (C >=
'a' && C <=
'z')
910 || (C >=
'A' && C <=
'Z');
913 void Scanner::scan_ns_uri_char() {
917 if (( *Current ==
'%'
922 ||
StringRef(Current, 1).find_first_of(
"#;/?:@&=+$,_.!~*'()[]")
932 if (Expected >= 0x80)
936 if (uint8_t(*Current) >= 0x80)
938 if (uint8_t(*Current) == Expected) {
946 void Scanner::skip(
uint32_t Distance) {
949 assert(Current <= End &&
"Skipped past the end");
955 return *Position ==
' ' || *Position ==
'\t' || *Position ==
'\r' ||
959 bool Scanner::consumeLineBreakIfPresent() {
960 auto Next = skip_b_break(Current);
972 if (IsSimpleKeyAllowed) {
976 SK.Column = AtColumn;
977 SK.IsRequired = IsRequired;
978 SK.FlowLevel = FlowLevel;
983 void Scanner::removeStaleSimpleKeyCandidates() {
985 i != SimpleKeys.
end();) {
986 if (i->Line != Line || i->Column + 1024 < Column) {
988 setError(
"Could not find expected : for simple key"
989 , i->Tok->Range.begin());
990 i = SimpleKeys.
erase(i);
996 void Scanner::removeSimpleKeyCandidatesOnFlowLevel(
unsigned Level) {
997 if (!SimpleKeys.
empty() && (SimpleKeys.
end() - 1)->FlowLevel == Level)
1001 bool Scanner::unrollIndent(
int ToColumn) {
1007 while (Indent > ToColumn) {
1017 bool Scanner::rollIndent(
int ToColumn
1022 if (Indent < ToColumn) {
1029 TokenQueue.
insert(InsertPoint, T);
1034 void Scanner::skipComment() {
1035 if (*Current !=
'#')
1048 void Scanner::scanToNextToken() {
1050 while (*Current ==
' ' || *Current ==
'\t') {
1065 IsSimpleKeyAllowed =
true;
1069 bool Scanner::scanStreamStart() {
1070 IsStartOfStream =
false;
1078 Current += EI.second;
1082 bool Scanner::scanStreamEnd() {
1091 IsSimpleKeyAllowed =
false;
1100 bool Scanner::scanDirective() {
1104 IsSimpleKeyAllowed =
false;
1109 Current = skip_while(&Scanner::skip_ns_char, Current);
1111 Current = skip_while(&Scanner::skip_s_white, Current);
1114 if (
Name ==
"YAML") {
1115 Current = skip_while(&Scanner::skip_ns_char, Current);
1120 }
else if(
Name ==
"TAG") {
1121 Current = skip_while(&Scanner::skip_ns_char, Current);
1122 Current = skip_while(&Scanner::skip_s_white, Current);
1123 Current = skip_while(&Scanner::skip_ns_char, Current);
1132 bool Scanner::scanDocumentIndicator(
bool IsStart) {
1135 IsSimpleKeyAllowed =
false;
1145 bool Scanner::scanFlowCollectionStart(
bool IsSequence) {
1154 saveSimpleKeyCandidate(--TokenQueue.
end(), Column - 1,
false);
1157 IsSimpleKeyAllowed =
true;
1162 bool Scanner::scanFlowCollectionEnd(
bool IsSequence) {
1163 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1164 IsSimpleKeyAllowed =
false;
1176 bool Scanner::scanFlowEntry() {
1177 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1178 IsSimpleKeyAllowed =
true;
1187 bool Scanner::scanBlockEntry() {
1189 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1190 IsSimpleKeyAllowed =
true;
1199 bool Scanner::scanKey() {
1203 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1204 IsSimpleKeyAllowed = !FlowLevel;
1214 bool Scanner::scanValue() {
1217 if (!SimpleKeys.
empty()) {
1221 T.
Range = SK.Tok->Range;
1223 for (i = TokenQueue.
begin(), e = TokenQueue.
end(); i != e; ++i) {
1227 assert(i != e &&
"SimpleKey not in token queue!");
1228 i = TokenQueue.
insert(i, T);
1233 IsSimpleKeyAllowed =
false;
1237 IsSimpleKeyAllowed = !FlowLevel;
1257 assert(Position - 1 >= First);
1261 while (I >= First && *I ==
'\\') --
I;
1264 return (Position - 1 - I) % 2 == 1;
1267 bool Scanner::scanFlowScalar(
bool IsDoubleQuoted) {
1269 unsigned ColStart = Column;
1270 if (IsDoubleQuoted) {
1273 while (Current != End && *Current !=
'"')
1277 }
while ( Current != End
1278 && *(Current - 1) ==
'\\'
1284 if (Current + 1 < End && *Current ==
'\'' && *(Current + 1) ==
'\'') {
1287 }
else if (*Current ==
'\'')
1291 i = skip_b_break(Current);
1306 if (Current == End) {
1307 setError(
"Expected quote at end of scalar", Current);
1317 saveSimpleKeyCandidate(--TokenQueue.
end(), ColStart,
false);
1319 IsSimpleKeyAllowed =
false;
1324 bool Scanner::scanPlainScalar() {
1326 unsigned ColStart = Column;
1327 unsigned LeadingBlanks = 0;
1328 assert(Indent >= -1 &&
"Indent must be >= -1 !");
1329 unsigned indent =
static_cast<unsigned>(Indent + 1);
1331 if (*Current ==
'#')
1334 while (!isBlankOrBreak(Current)) {
1335 if ( FlowLevel && *Current ==
':'
1336 && !(isBlankOrBreak(Current + 1) || *(Current + 1) ==
',')) {
1337 setError(
"Found unexpected ':' while scanning a plain scalar", Current);
1342 if ( (*Current ==
':' && isBlankOrBreak(Current + 1))
1344 && (
StringRef(Current, 1).find_first_of(
",:?[]{}")
1356 if (!isBlankOrBreak(Current))
1361 while (isBlankOrBreak(Tmp)) {
1364 if (LeadingBlanks && (Column < indent) && *Tmp ==
'\t') {
1365 setError(
"Found invalid tab character in indentation", Tmp);
1371 i = skip_b_break(Tmp);
1380 if (!FlowLevel && Column < indent)
1385 if (Start == Current) {
1386 setError(
"Got empty plain scalar", Start);
1395 saveSimpleKeyCandidate(--TokenQueue.
end(), ColStart,
false);
1397 IsSimpleKeyAllowed =
false;
1402 bool Scanner::scanAliasOrAnchor(
bool IsAlias) {
1404 unsigned ColStart = Column;
1407 if ( *Current ==
'[' || *Current ==
']'
1408 || *Current ==
'{' || *Current ==
'}'
1419 if (Start == Current) {
1420 setError(
"Got empty alias or anchor", Start);
1430 saveSimpleKeyCandidate(--TokenQueue.
end(), ColStart,
false);
1432 IsSimpleKeyAllowed =
false;
1437 char Scanner::scanBlockChompingIndicator() {
1438 char Indicator =
' ';
1439 if (Current != End && (*Current ==
'+' || *Current ==
'-')) {
1440 Indicator = *Current;
1452 if (ChompingIndicator ==
'-')
1454 if (ChompingIndicator ==
'+')
1457 return Str.
empty() ? 0 : 1;
1460 unsigned Scanner::scanBlockIndentationIndicator() {
1461 unsigned Indent = 0;
1462 if (Current != End && (*Current >=
'1' && *Current <=
'9')) {
1469 bool Scanner::scanBlockScalarHeader(
char &ChompingIndicator,
1470 unsigned &IndentIndicator,
bool &IsDone) {
1471 auto Start = Current;
1473 ChompingIndicator = scanBlockChompingIndicator();
1474 IndentIndicator = scanBlockIndentationIndicator();
1476 if (ChompingIndicator ==
' ')
1477 ChompingIndicator = scanBlockChompingIndicator();
1478 Current = skip_while(&Scanner::skip_s_white, Current);
1481 if (Current == End) {
1490 if (!consumeLineBreakIfPresent()) {
1491 setError(
"Expected a line break after block scalar header", Current);
1497 bool Scanner::findBlockScalarIndent(
unsigned &BlockIndent,
1498 unsigned BlockExitIndent,
1499 unsigned &LineBreaks,
bool &IsDone) {
1500 unsigned MaxAllSpaceLineCharacters = 0;
1504 advanceWhile(&Scanner::skip_s_space);
1505 if (skip_nb_char(Current) != Current) {
1507 if (Column <= BlockExitIndent) {
1512 BlockIndent = Column;
1513 if (MaxAllSpaceLineCharacters > BlockIndent) {
1515 "Leading all-spaces line must be smaller than the block indent",
1516 LongestAllSpaceLine);
1521 if (skip_b_break(Current) != Current &&
1522 Column > MaxAllSpaceLineCharacters) {
1525 MaxAllSpaceLineCharacters = Column;
1526 LongestAllSpaceLine = Current;
1530 if (Current == End) {
1535 if (!consumeLineBreakIfPresent()) {
1544 bool Scanner::scanBlockScalarIndent(
unsigned BlockIndent,
1545 unsigned BlockExitIndent,
bool &IsDone) {
1547 while (Column < BlockIndent) {
1548 auto I = skip_s_space(Current);
1555 if (skip_nb_char(Current) == Current)
1558 if (Column <= BlockExitIndent) {
1563 if (Column < BlockIndent) {
1564 if (Current != End && *Current ==
'#') {
1568 setError(
"A text line is less indented than the block scalar", Current);
1574 bool Scanner::scanBlockScalar(
bool IsLiteral) {
1576 assert(*Current ==
'|' || *Current ==
'>');
1579 char ChompingIndicator;
1580 unsigned BlockIndent;
1581 bool IsDone =
false;
1582 if (!scanBlockScalarHeader(ChompingIndicator, BlockIndent, IsDone))
1587 auto Start = Current;
1588 unsigned BlockExitIndent = Indent < 0 ? 0 : (
unsigned)Indent;
1589 unsigned LineBreaks = 0;
1590 if (BlockIndent == 0) {
1591 if (!findBlockScalarIndent(BlockIndent, BlockExitIndent, LineBreaks,
1599 if (!scanBlockScalarIndent(BlockIndent, BlockExitIndent, IsDone))
1605 auto LineStart = Current;
1606 advanceWhile(&Scanner::skip_nb_char);
1607 if (LineStart != Current) {
1608 Str.
append(LineBreaks,
'\n');
1617 if (!consumeLineBreakIfPresent())
1622 if (Current == End && !LineBreaks)
1629 IsSimpleKeyAllowed =
true;
1639 bool Scanner::scanTag() {
1641 unsigned ColStart = Column;
1643 if (Current == End || isBlankOrBreak(Current));
1644 else if (*Current ==
'<') {
1651 Current = skip_while(&Scanner::skip_ns_char, Current);
1660 saveSimpleKeyCandidate(--TokenQueue.
end(), ColStart,
false);
1662 IsSimpleKeyAllowed =
false;
1667 bool Scanner::fetchMoreTokens() {
1668 if (IsStartOfStream)
1669 return scanStreamStart();
1674 return scanStreamEnd();
1676 removeStaleSimpleKeyCandidates();
1678 unrollIndent(Column);
1680 if (Column == 0 && *Current ==
'%')
1681 return scanDirective();
1683 if (Column == 0 && Current + 4 <= End
1685 && *(Current + 1) ==
'-'
1686 && *(Current + 2) ==
'-'
1687 && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1688 return scanDocumentIndicator(
true);
1690 if (Column == 0 && Current + 4 <= End
1692 && *(Current + 1) ==
'.'
1693 && *(Current + 2) ==
'.'
1694 && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1695 return scanDocumentIndicator(
false);
1697 if (*Current ==
'[')
1698 return scanFlowCollectionStart(
true);
1700 if (*Current ==
'{')
1701 return scanFlowCollectionStart(
false);
1703 if (*Current ==
']')
1704 return scanFlowCollectionEnd(
true);
1706 if (*Current ==
'}')
1707 return scanFlowCollectionEnd(
false);
1709 if (*Current ==
',')
1710 return scanFlowEntry();
1712 if (*Current ==
'-' && isBlankOrBreak(Current + 1))
1713 return scanBlockEntry();
1715 if (*Current ==
'?' && (FlowLevel || isBlankOrBreak(Current + 1)))
1718 if (*Current ==
':' && (FlowLevel || isBlankOrBreak(Current + 1)))
1721 if (*Current ==
'*')
1722 return scanAliasOrAnchor(
true);
1724 if (*Current ==
'&')
1725 return scanAliasOrAnchor(
false);
1727 if (*Current ==
'!')
1730 if (*Current ==
'|' && !FlowLevel)
1731 return scanBlockScalar(
true);
1733 if (*Current ==
'>' && !FlowLevel)
1734 return scanBlockScalar(
false);
1736 if (*Current ==
'\'')
1737 return scanFlowScalar(
false);
1739 if (*Current ==
'"')
1740 return scanFlowScalar(
true);
1744 if (!(isBlankOrBreak(Current)
1745 || FirstChar.find_first_of(
"-?:,[]{}#&*!|>'\"%@`") !=
StringRef::npos)
1746 || (*Current ==
'-' && !isBlankOrBreak(Current + 1))
1747 || (!FlowLevel && (*Current ==
'?' || *Current ==
':')
1748 && isBlankOrBreak(Current + 1))
1749 || (!FlowLevel && *Current ==
':'
1750 && Current + 2 < End
1751 && *(Current + 1) ==
':'
1752 && !isBlankOrBreak(Current + 2)))
1753 return scanPlainScalar();
1755 setError(
"Unrecognized character while tokenizing.");
1760 std::error_code *EC)
1761 : scanner(new
Scanner(Input, SM, ShowColors, EC)), CurrentDoc() {}
1764 std::error_code *EC)
1765 : scanner(new
Scanner(InputBuffer, SM, ShowColors, EC)), CurrentDoc() {}
1785 CurrentDoc.reset(
new Document(*
this));
1800 : Doc(D),
TypeID(Type), Anchor(A),
Tag(T) {
1807 if (!Raw.
empty() && Raw !=
"!") {
1810 Ret =
Doc->getTagMap().find(
"!")->second;
1814 Ret =
Doc->getTagMap().find(
"!!")->second;
1819 std::map<StringRef, StringRef>::const_iterator It =
1820 Doc->getTagMap().find(TagHandle);
1821 if (It !=
Doc->getTagMap().end())
1826 T.
Range = TagHandle;
1836 return "tag:yaml.org,2002:null";
1838 case NK_BlockScalar:
1840 return "tag:yaml.org,2002:str";
1842 return "tag:yaml.org,2002:map";
1844 return "tag:yaml.org,2002:seq";
1851 return Doc->peekNext();
1855 return Doc->getNext();
1863 return Doc->NodeAllocator;
1867 Doc->setError(Msg, Tok);
1870 bool Node::failed()
const {
1871 return Doc->failed();
1876 if (
Value[0] ==
'"') {
1882 return unescapeDoubleQuoted(UnquotedValue, i, Storage);
1883 return UnquotedValue;
1884 }
else if (
Value[0] ==
'\'') {
1894 Storage.
insert(Storage.
end(), Valid.begin(), Valid.end());
1896 UnquotedValue = UnquotedValue.
substr(i + 2);
1901 return UnquotedValue;
1904 return Value.rtrim(
' ');
1917 Storage.
insert(Storage.
end(), Valid.begin(), Valid.end());
1919 UnquotedValue = UnquotedValue.
substr(i);
1921 assert(!UnquotedValue.
empty() &&
"Can't be empty!");
1924 switch (UnquotedValue[0]) {
1928 if ( UnquotedValue.
size() > 1
1929 && (UnquotedValue[1] ==
'\r' || UnquotedValue[1] ==
'\n'))
1930 UnquotedValue = UnquotedValue.
substr(1);
1931 UnquotedValue = UnquotedValue.
substr(1);
1934 if (UnquotedValue.
size() == 1)
1937 UnquotedValue = UnquotedValue.
substr(1);
1938 switch (UnquotedValue[0]) {
1942 setError(
"Unrecognized escape code!", T);
1948 if ( UnquotedValue.
size() > 1
1949 && (UnquotedValue[1] ==
'\r' || UnquotedValue[1] ==
'\n'))
1950 UnquotedValue = UnquotedValue.
substr(1);
2007 if (UnquotedValue.
size() < 3)
2010 unsigned int UnicodeScalarValue;
2013 UnicodeScalarValue = 0xFFFD;
2015 UnquotedValue = UnquotedValue.
substr(2);
2019 if (UnquotedValue.
size() < 5)
2022 unsigned int UnicodeScalarValue;
2025 UnicodeScalarValue = 0xFFFD;
2027 UnquotedValue = UnquotedValue.
substr(4);
2031 if (UnquotedValue.
size() < 9)
2034 unsigned int UnicodeScalarValue;
2037 UnicodeScalarValue = 0xFFFD;
2039 UnquotedValue = UnquotedValue.
substr(8);
2043 UnquotedValue = UnquotedValue.
substr(1);
2056 if ( t.
Kind == Token::TK_BlockEnd
2057 || t.
Kind == Token::TK_Value
2058 || t.
Kind == Token::TK_Error) {
2059 return Key =
new (getAllocator())
NullNode(Doc);
2061 if (t.
Kind == Token::TK_Key)
2067 if (t.
Kind == Token::TK_BlockEnd || t.
Kind == Token::TK_Value) {
2068 return Key =
new (getAllocator())
NullNode(Doc);
2072 return Key = parseBlockNode();
2085 if ( t.
Kind == Token::TK_BlockEnd
2086 || t.
Kind == Token::TK_FlowMappingEnd
2087 || t.
Kind == Token::TK_Key
2088 || t.
Kind == Token::TK_FlowEntry
2089 || t.
Kind == Token::TK_Error) {
2093 if (t.
Kind != Token::TK_Value) {
2094 setError(
"Unexpected token in Key Value.", t);
2102 if (t.
Kind == Token::TK_BlockEnd || t.
Kind == Token::TK_Key) {
2107 return Value = parseBlockNode();
2110 void MappingNode::increment() {
2113 CurrentEntry =
nullptr;
2117 CurrentEntry->skip();
2118 if (
Type == MT_Inline) {
2120 CurrentEntry =
nullptr;
2124 Token T = peekNext();
2125 if (T.
Kind == Token::TK_Key || T.
Kind == Token::TK_Scalar) {
2128 }
else if (
Type == MT_Block) {
2130 case Token::TK_BlockEnd:
2133 CurrentEntry =
nullptr;
2136 setError(
"Unexpected token. Expected Key or Block End", T);
2138 case Token::TK_Error:
2140 CurrentEntry =
nullptr;
2144 case Token::TK_FlowEntry:
2148 case Token::TK_FlowMappingEnd:
2151 case Token::TK_Error:
2154 CurrentEntry =
nullptr;
2157 setError(
"Unexpected token. Expected Key, Flow Entry, or Flow "
2161 CurrentEntry =
nullptr;
2166 void SequenceNode::increment() {
2169 CurrentEntry =
nullptr;
2173 CurrentEntry->skip();
2174 Token T = peekNext();
2175 if (SeqType == ST_Block) {
2177 case Token::TK_BlockEntry:
2179 CurrentEntry = parseBlockNode();
2180 if (!CurrentEntry) {
2182 CurrentEntry =
nullptr;
2185 case Token::TK_BlockEnd:
2188 CurrentEntry =
nullptr;
2191 setError(
"Unexpected token. Expected Block Entry or Block End."
2194 case Token::TK_Error:
2196 CurrentEntry =
nullptr;
2198 }
else if (SeqType == ST_Indentless) {
2200 case Token::TK_BlockEntry:
2202 CurrentEntry = parseBlockNode();
2203 if (!CurrentEntry) {
2205 CurrentEntry =
nullptr;
2209 case Token::TK_Error:
2211 CurrentEntry =
nullptr;
2213 }
else if (SeqType == ST_Flow) {
2215 case Token::TK_FlowEntry:
2218 WasPreviousTokenFlowEntry =
true;
2220 case Token::TK_FlowSequenceEnd:
2223 case Token::TK_Error:
2226 CurrentEntry =
nullptr;
2228 case Token::TK_StreamEnd:
2229 case Token::TK_DocumentEnd:
2230 case Token::TK_DocumentStart:
2231 setError(
"Could not find closing ]!", T);
2234 CurrentEntry =
nullptr;
2237 if (!WasPreviousTokenFlowEntry) {
2238 setError(
"Expected , between entries!", T);
2240 CurrentEntry =
nullptr;
2244 CurrentEntry = parseBlockNode();
2245 if (!CurrentEntry) {
2248 WasPreviousTokenFlowEntry =
false;
2254 Document::Document(
Stream &S) : stream(S), Root(nullptr) {
2257 TagMap[
"!!"] =
"tag:yaml.org,2002:";
2259 if (parseDirectives())
2261 Token &T = peekNext();
2267 if (stream.scanner->failed())
2272 Token &T = peekNext();
2282 Token &Document::peekNext() {
2283 return stream.scanner->peekNext();
2286 Token Document::getNext() {
2287 return stream.scanner->getNext();
2290 void Document::setError(
const Twine &Message,
Token &Location)
const {
2291 stream.scanner->setError(Message, Location.
Range.
begin());
2294 bool Document::failed()
const {
2295 return stream.scanner->failed();
2299 Token T = peekNext();
2310 setError(
"Already encountered an anchor for this node!", T);
2313 AnchorInfo = getNext();
2315 goto parse_property;
2318 setError(
"Already encountered a tag for this node!", T);
2321 TagInfo = getNext();
2323 goto parse_property;
2333 return new (NodeAllocator)
SequenceNode( stream.CurrentDoc
2339 return new (NodeAllocator)
2346 return new (NodeAllocator)
2353 return new (NodeAllocator)
2360 return new (NodeAllocator)
2367 return new (NodeAllocator)
2376 return new (NodeAllocator)
2382 return new (NodeAllocator)
2393 return new (NodeAllocator)
NullNode(stream.CurrentDoc);
2401 bool Document::parseDirectives() {
2402 bool isDirective =
false;
2404 Token T = peekNext();
2406 parseTAGDirective();
2409 parseYAMLDirective();
2417 void Document::parseYAMLDirective() {
2421 void Document::parseTAGDirective() {
2429 TagMap[TagHandle] = TagPrefix;
2432 bool Document::expectToken(
int TK) {
2433 Token T = getNext();
2435 setError(
"Unexpected token", T);
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.
Represents a range in source code.
void push_back(const T &Elt)
std::unique_ptr< Document > & Doc
std::string getVerbatimTag() const
Get the verbatium tag for a given Node.
bool operator==(const BinaryRef &LHS, const BinaryRef &RHS)
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
A linked-list with a custom, local allocator.
Node(unsigned int Type, std::unique_ptr< Document > &, StringRef Anchor, StringRef Tag)
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.
std::pair< UnicodeEncodingForm, unsigned > EncodingInfo
EncodingInfo - Holds the encoding type and length of the byte order mark if it exists.
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
std::string Value
The value of a block scalar node.
StringRef getRawTag() const
Get the tag as it was written in the document.
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)
const char * getBufferStart() const
void resetAlloc()
Reset the underlying allocator.
document_iterator begin()
Represents an alias to a Node with an anchor.
void skip(CollectionType &C)
void reserve(size_type N)
void setError(const Twine &Message, Token &Location) const
static bool is_ns_hex_digit(const char C)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
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.
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
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
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)...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
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)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t find(char C, size_t From=0) const
Search for the first character C in the string.
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_ATTRIBUTE_ALWAYS_INLINE iterator begin()
const char * getBufferEnd() const
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.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
std::string escape(StringRef Input)
Escape Input for a double quoted scalar.
static unsigned getChompedLineBreaks(char ChompingIndicator, unsigned LineBreaks, StringRef Str)
Get the number of line breaks after chomping.
static const unsigned End
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...
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
iterator erase(const_iterator CI)
static wasm::ValType getType(const TargetRegisterClass *RC)
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)
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()
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.
StringRef str() const
Explicit conversion to StringRef.
void setError(const Twine &Message)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
iterator insert(iterator I, T &&Elt)
static UTF8Decoded decodeUTF8(StringRef Range)
LLVM_NODISCARD StringRef copy(Allocator &A) const
static SMLoc getFromPointer(const char *Ptr)
llvm_unreachable("Unknown RegBank!")
SMRange getSourceRange() const
Stream(StringRef Input, SourceMgr &, bool ShowColors=true, std::error_code *EC=nullptr)
This keeps a reference to the string referenced by Input.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
LLVM_NODISCARD StringRef ltrim(char Char) const
Return string with consecutive Char characters starting from the the left removed.
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.
static std::string utohexstr(uint64_t X, bool LowerCase=false)
Scans YAML tokens from a MemoryBuffer.
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.
Iterator abstraction for Documents over a Stream.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
#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...
StringRef - Represent a constant reference to a string, i.e.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
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.
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.
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.