1 //===- lib/Support/YAMLTraits.cpp -----------------------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Support/YAMLTraits.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/Support/Casting.h"
16 #include "llvm/Support/Errc.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/Format.h"
19 #include "llvm/Support/LineIterator.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Unicode.h"
22 #include "llvm/Support/YAMLParser.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <algorithm>
25 #include <cassert>
26 #include <cstdint>
27 #include <cstdlib>
28 #include <cstring>
29 #include <string>
30 #include <vector>
31 
32 using namespace llvm;
33 using namespace yaml;
34 
35 //===----------------------------------------------------------------------===//
36 //  IO
37 //===----------------------------------------------------------------------===//
38 
39 IO::IO(void *Context) : Ctxt(Context) {}
40 
41 IO::~IO() = default;
42 
43 void *IO::getContext() const {
44   return Ctxt;
45 }
46 
47 void IO::setContext(void *Context) {
48   Ctxt = Context;
49 }
50 
51 //===----------------------------------------------------------------------===//
52 //  Input
53 //===----------------------------------------------------------------------===//
54 
55 Input::Input(StringRef InputContent, void *Ctxt,
56              SourceMgr::DiagHandlerTy DiagHandler, void *DiagHandlerCtxt)
57     : IO(Ctxt), Strm(new Stream(InputContent, SrcMgr, false, &EC)) {
58   if (DiagHandler)
59     SrcMgr.setDiagHandler(DiagHandler, DiagHandlerCtxt);
60   DocIterator = Strm->begin();
61 }
62 
63 Input::Input(MemoryBufferRef Input, void *Ctxt,
64              SourceMgr::DiagHandlerTy DiagHandler, void *DiagHandlerCtxt)
65     : IO(Ctxt), Strm(new Stream(Input, SrcMgr, false, &EC)) {
66   if (DiagHandler)
67     SrcMgr.setDiagHandler(DiagHandler, DiagHandlerCtxt);
68   DocIterator = Strm->begin();
69 }
70 
71 Input::~Input() = default;
72 
73 std::error_code Input::error() { return EC; }
74 
75 // Pin the vtables to this file.
76 void Input::HNode::anchor() {}
77 void Input::EmptyHNode::anchor() {}
78 void Input::ScalarHNode::anchor() {}
79 void Input::MapHNode::anchor() {}
80 void Input::SequenceHNode::anchor() {}
81 
82 bool Input::outputting() const {
83   return false;
84 }
85 
86 bool Input::setCurrentDocument() {
87   if (DocIterator != Strm->end()) {
88     Node *N = DocIterator->getRoot();
89     if (!N) {
90       EC = make_error_code(errc::invalid_argument);
91       return false;
92     }
93 
94     if (isa<NullNode>(N)) {
95       // Empty files are allowed and ignored
96       ++DocIterator;
97       return setCurrentDocument();
98     }
99     TopNode = createHNodes(N);
100     CurrentNode = TopNode.get();
101     return true;
102   }
103   return false;
104 }
105 
106 bool Input::nextDocument() {
107   return ++DocIterator != Strm->end();
108 }
109 
110 const Node *Input::getCurrentNode() const {
111   return CurrentNode ? CurrentNode->_node : nullptr;
112 }
113 
114 bool Input::mapTag(StringRef Tag, bool Default) {
115   // CurrentNode can be null if setCurrentDocument() was unable to
116   // parse the document because it was invalid or empty.
117   if (!CurrentNode)
118     return false;
119 
120   std::string foundTag = CurrentNode->_node->getVerbatimTag();
121   if (foundTag.empty()) {
122     // If no tag found and 'Tag' is the default, say it was found.
123     return Default;
124   }
125   // Return true iff found tag matches supplied tag.
126   return Tag.equals(foundTag);
127 }
128 
129 void Input::beginMapping() {
130   if (EC)
131     return;
132   // CurrentNode can be null if the document is empty.
133   MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
134   if (MN) {
135     MN->ValidKeys.clear();
136   }
137 }
138 
139 std::vector<StringRef> Input::keys() {
140   MapHNode *MN = dyn_cast<MapHNode>(CurrentNode);
141   std::vector<StringRef> Ret;
142   if (!MN) {
143     setError(CurrentNode, "not a mapping");
144     return Ret;
145   }
146   for (auto &P : MN->Mapping)
147     Ret.push_back(P.first());
148   return Ret;
149 }
150 
151 bool Input::preflightKey(const char *Key, bool Required, bool, bool &UseDefault,
152                          void *&SaveInfo) {
153   UseDefault = false;
154   if (EC)
155     return false;
156 
157   // CurrentNode is null for empty documents, which is an error in case required
158   // nodes are present.
159   if (!CurrentNode) {
160     if (Required)
161       EC = make_error_code(errc::invalid_argument);
162     return false;
163   }
164 
165   MapHNode *MN = dyn_cast<MapHNode>(CurrentNode);
166   if (!MN) {
167     if (Required || !isa<EmptyHNode>(CurrentNode))
168       setError(CurrentNode, "not a mapping");
169     return false;
170   }
171   MN->ValidKeys.push_back(Key);
172   HNode *Value = MN->Mapping[Key].get();
173   if (!Value) {
174     if (Required)
175       setError(CurrentNode, Twine("missing required key '") + Key + "'");
176     else
177       UseDefault = true;
178     return false;
179   }
180   SaveInfo = CurrentNode;
181   CurrentNode = Value;
182   return true;
183 }
184 
185 void Input::postflightKey(void *saveInfo) {
186   CurrentNode = reinterpret_cast<HNode *>(saveInfo);
187 }
188 
189 void Input::endMapping() {
190   if (EC)
191     return;
192   // CurrentNode can be null if the document is empty.
193   MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
194   if (!MN)
195     return;
196   for (const auto &NN : MN->Mapping) {
197     if (!is_contained(MN->ValidKeys, NN.first())) {
198       setError(NN.second.get(), Twine("unknown key '") + NN.first() + "'");
199       break;
200     }
201   }
202 }
203 
204 void Input::beginFlowMapping() { beginMapping(); }
205 
206 void Input::endFlowMapping() { endMapping(); }
207 
208 unsigned Input::beginSequence() {
209   if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode))
210     return SQ->Entries.size();
211   if (isa<EmptyHNode>(CurrentNode))
212     return 0;
213   // Treat case where there's a scalar "null" value as an empty sequence.
214   if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
215     if (isNull(SN->value()))
216       return 0;
217   }
218   // Any other type of HNode is an error.
219   setError(CurrentNode, "not a sequence");
220   return 0;
221 }
222 
223 void Input::endSequence() {
224 }
225 
226 bool Input::preflightElement(unsigned Index, void *&SaveInfo) {
227   if (EC)
228     return false;
229   if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
230     SaveInfo = CurrentNode;
231     CurrentNode = SQ->Entries[Index].get();
232     return true;
233   }
234   return false;
235 }
236 
237 void Input::postflightElement(void *SaveInfo) {
238   CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
239 }
240 
241 unsigned Input::beginFlowSequence() { return beginSequence(); }
242 
243 bool Input::preflightFlowElement(unsigned index, void *&SaveInfo) {
244   if (EC)
245     return false;
246   if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
247     SaveInfo = CurrentNode;
248     CurrentNode = SQ->Entries[index].get();
249     return true;
250   }
251   return false;
252 }
253 
254 void Input::postflightFlowElement(void *SaveInfo) {
255   CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
256 }
257 
258 void Input::endFlowSequence() {
259 }
260 
261 void Input::beginEnumScalar() {
262   ScalarMatchFound = false;
263 }
264 
265 bool Input::matchEnumScalar(const char *Str, bool) {
266   if (ScalarMatchFound)
267     return false;
268   if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
269     if (SN->value().equals(Str)) {
270       ScalarMatchFound = true;
271       return true;
272     }
273   }
274   return false;
275 }
276 
277 bool Input::matchEnumFallback() {
278   if (ScalarMatchFound)
279     return false;
280   ScalarMatchFound = true;
281   return true;
282 }
283 
284 void Input::endEnumScalar() {
285   if (!ScalarMatchFound) {
286     setError(CurrentNode, "unknown enumerated scalar");
287   }
288 }
289 
290 bool Input::beginBitSetScalar(bool &DoClear) {
291   BitValuesUsed.clear();
292   if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
293     BitValuesUsed.insert(BitValuesUsed.begin(), SQ->Entries.size(), false);
294   } else {
295     setError(CurrentNode, "expected sequence of bit values");
296   }
297   DoClear = true;
298   return true;
299 }
300 
301 bool Input::bitSetMatch(const char *Str, bool) {
302   if (EC)
303     return false;
304   if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
305     unsigned Index = 0;
306     for (auto &N : SQ->Entries) {
307       if (ScalarHNode *SN = dyn_cast<ScalarHNode>(N.get())) {
308         if (SN->value().equals(Str)) {
309           BitValuesUsed[Index] = true;
310           return true;
311         }
312       } else {
313         setError(CurrentNode, "unexpected scalar in sequence of bit values");
314       }
315       ++Index;
316     }
317   } else {
318     setError(CurrentNode, "expected sequence of bit values");
319   }
320   return false;
321 }
322 
323 void Input::endBitSetScalar() {
324   if (EC)
325     return;
326   if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
327     assert(BitValuesUsed.size() == SQ->Entries.size());
328     for (unsigned i = 0; i < SQ->Entries.size(); ++i) {
329       if (!BitValuesUsed[i]) {
330         setError(SQ->Entries[i].get(), "unknown bit value");
331         return;
332       }
333     }
334   }
335 }
336 
337 void Input::scalarString(StringRef &S, QuotingType) {
338   if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
339     S = SN->value();
340   } else {
341     setError(CurrentNode, "unexpected scalar");
342   }
343 }
344 
345 void Input::blockScalarString(StringRef &S) { scalarString(S, QuotingType::None); }
346 
347 void Input::scalarTag(std::string &Tag) {
348   Tag = CurrentNode->_node->getVerbatimTag();
349 }
350 
351 void Input::setError(HNode *hnode, const Twine &message) {
352   assert(hnode && "HNode must not be NULL");
353   setError(hnode->_node, message);
354 }
355 
356 NodeKind Input::getNodeKind() {
357   if (isa<ScalarHNode>(CurrentNode))
358     return NodeKind::Scalar;
359   else if (isa<MapHNode>(CurrentNode))
360     return NodeKind::Map;
361   else if (isa<SequenceHNode>(CurrentNode))
362     return NodeKind::Sequence;
363   llvm_unreachable("Unsupported node kind");
364 }
365 
366 void Input::setError(Node *node, const Twine &message) {
367   Strm->printError(node, message);
368   EC = make_error_code(errc::invalid_argument);
369 }
370 
371 std::unique_ptr<Input::HNode> Input::createHNodes(Node *N) {
372   SmallString<128> StringStorage;
373   if (ScalarNode *SN = dyn_cast<ScalarNode>(N)) {
374     StringRef KeyStr = SN->getValue(StringStorage);
375     if (!StringStorage.empty()) {
376       // Copy string to permanent storage
377       KeyStr = StringStorage.str().copy(StringAllocator);
378     }
379     return std::make_unique<ScalarHNode>(N, KeyStr);
380   } else if (BlockScalarNode *BSN = dyn_cast<BlockScalarNode>(N)) {
381     StringRef ValueCopy = BSN->getValue().copy(StringAllocator);
382     return std::make_unique<ScalarHNode>(N, ValueCopy);
383   } else if (SequenceNode *SQ = dyn_cast<SequenceNode>(N)) {
384     auto SQHNode = std::make_unique<SequenceHNode>(N);
385     for (Node &SN : *SQ) {
386       auto Entry = createHNodes(&SN);
387       if (EC)
388         break;
389       SQHNode->Entries.push_back(std::move(Entry));
390     }
391     return std::move(SQHNode);
392   } else if (MappingNode *Map = dyn_cast<MappingNode>(N)) {
393     auto mapHNode = std::make_unique<MapHNode>(N);
394     for (KeyValueNode &KVN : *Map) {
395       Node *KeyNode = KVN.getKey();
396       ScalarNode *Key = dyn_cast_or_null<ScalarNode>(KeyNode);
397       Node *Value = KVN.getValue();
398       if (!Key || !Value) {
399         if (!Key)
400           setError(KeyNode, "Map key must be a scalar");
401         if (!Value)
402           setError(KeyNode, "Map value must not be empty");
403         break;
404       }
405       StringStorage.clear();
406       StringRef KeyStr = Key->getValue(StringStorage);
407       if (!StringStorage.empty()) {
408         // Copy string to permanent storage
409         KeyStr = StringStorage.str().copy(StringAllocator);
410       }
411       auto ValueHNode = createHNodes(Value);
412       if (EC)
413         break;
414       mapHNode->Mapping[KeyStr] = std::move(ValueHNode);
415     }
416     return std::move(mapHNode);
417   } else if (isa<NullNode>(N)) {
418     return std::make_unique<EmptyHNode>(N);
419   } else {
420     setError(N, "unknown node kind");
421     return nullptr;
422   }
423 }
424 
425 void Input::setError(const Twine &Message) {
426   setError(CurrentNode, Message);
427 }
428 
429 bool Input::canElideEmptySequence() {
430   return false;
431 }
432 
433 //===----------------------------------------------------------------------===//
434 //  Output
435 //===----------------------------------------------------------------------===//
436 
437 Output::Output(raw_ostream &yout, void *context, int WrapColumn)
438     : IO(context), Out(yout), WrapColumn(WrapColumn) {}
439 
440 Output::~Output() = default;
441 
442 bool Output::outputting() const {
443   return true;
444 }
445 
446 void Output::beginMapping() {
447   StateStack.push_back(inMapFirstKey);
448   PaddingBeforeContainer = Padding;
449   Padding = "\n";
450 }
451 
452 bool Output::mapTag(StringRef Tag, bool Use) {
453   if (Use) {
454     // If this tag is being written inside a sequence we should write the start
455     // of the sequence before writing the tag, otherwise the tag won't be
456     // attached to the element in the sequence, but rather the sequence itself.
457     bool SequenceElement = false;
458     if (StateStack.size() > 1) {
459       auto &E = StateStack[StateStack.size() - 2];
460       SequenceElement = inSeqAnyElement(E) || inFlowSeqAnyElement(E);
461     }
462     if (SequenceElement && StateStack.back() == inMapFirstKey) {
463       newLineCheck();
464     } else {
465       output(" ");
466     }
467     output(Tag);
468     if (SequenceElement) {
469       // If we're writing the tag during the first element of a map, the tag
470       // takes the place of the first element in the sequence.
471       if (StateStack.back() == inMapFirstKey) {
472         StateStack.pop_back();
473         StateStack.push_back(inMapOtherKey);
474       }
475       // Tags inside maps in sequences should act as keys in the map from a
476       // formatting perspective, so we always want a newline in a sequence.
477       Padding = "\n";
478     }
479   }
480   return Use;
481 }
482 
483 void Output::endMapping() {
484   // If we did not map anything, we should explicitly emit an empty map
485   if (StateStack.back() == inMapFirstKey) {
486     Padding = PaddingBeforeContainer;
487     newLineCheck();
488     output("{}");
489     Padding = "\n";
490   }
491   StateStack.pop_back();
492 }
493 
494 std::vector<StringRef> Output::keys() {
495   report_fatal_error("invalid call");
496 }
497 
498 bool Output::preflightKey(const char *Key, bool Required, bool SameAsDefault,
499                           bool &UseDefault, void *&) {
500   UseDefault = false;
501   if (Required || !SameAsDefault || WriteDefaultValues) {
502     auto State = StateStack.back();
503     if (State == inFlowMapFirstKey || State == inFlowMapOtherKey) {
504       flowKey(Key);
505     } else {
506       newLineCheck();
507       paddedKey(Key);
508     }
509     return true;
510   }
511   return false;
512 }
513 
514 void Output::postflightKey(void *) {
515   if (StateStack.back() == inMapFirstKey) {
516     StateStack.pop_back();
517     StateStack.push_back(inMapOtherKey);
518   } else if (StateStack.back() == inFlowMapFirstKey) {
519     StateStack.pop_back();
520     StateStack.push_back(inFlowMapOtherKey);
521   }
522 }
523 
524 void Output::beginFlowMapping() {
525   StateStack.push_back(inFlowMapFirstKey);
526   newLineCheck();
527   ColumnAtMapFlowStart = Column;
528   output("{ ");
529 }
530 
531 void Output::endFlowMapping() {
532   StateStack.pop_back();
533   outputUpToEndOfLine(" }");
534 }
535 
536 void Output::beginDocuments() {
537   outputUpToEndOfLine("---");
538 }
539 
540 bool Output::preflightDocument(unsigned index) {
541   if (index > 0)
542     outputUpToEndOfLine("\n---");
543   return true;
544 }
545 
546 void Output::postflightDocument() {
547 }
548 
549 void Output::endDocuments() {
550   output("\n...\n");
551 }
552 
553 unsigned Output::beginSequence() {
554   StateStack.push_back(inSeqFirstElement);
555   PaddingBeforeContainer = Padding;
556   Padding = "\n";
557   return 0;
558 }
559 
560 void Output::endSequence() {
561   // If we did not emit anything, we should explicitly emit an empty sequence
562   if (StateStack.back() == inSeqFirstElement) {
563     Padding = PaddingBeforeContainer;
564     newLineCheck();
565     output("[]");
566     Padding = "\n";
567   }
568   StateStack.pop_back();
569 }
570 
571 bool Output::preflightElement(unsigned, void *&) {
572   return true;
573 }
574 
575 void Output::postflightElement(void *) {
576   if (StateStack.back() == inSeqFirstElement) {
577     StateStack.pop_back();
578     StateStack.push_back(inSeqOtherElement);
579   } else if (StateStack.back() == inFlowSeqFirstElement) {
580     StateStack.pop_back();
581     StateStack.push_back(inFlowSeqOtherElement);
582   }
583 }
584 
585 unsigned Output::beginFlowSequence() {
586   StateStack.push_back(inFlowSeqFirstElement);
587   newLineCheck();
588   ColumnAtFlowStart = Column;
589   output("[ ");
590   NeedFlowSequenceComma = false;
591   return 0;
592 }
593 
594 void Output::endFlowSequence() {
595   StateStack.pop_back();
596   outputUpToEndOfLine(" ]");
597 }
598 
599 bool Output::preflightFlowElement(unsigned, void *&) {
600   if (NeedFlowSequenceComma)
601     output(", ");
602   if (WrapColumn && Column > WrapColumn) {
603     output("\n");
604     for (int i = 0; i < ColumnAtFlowStart; ++i)
605       output(" ");
606     Column = ColumnAtFlowStart;
607     output("  ");
608   }
609   return true;
610 }
611 
612 void Output::postflightFlowElement(void *) {
613   NeedFlowSequenceComma = true;
614 }
615 
616 void Output::beginEnumScalar() {
617   EnumerationMatchFound = false;
618 }
619 
620 bool Output::matchEnumScalar(const char *Str, bool Match) {
621   if (Match && !EnumerationMatchFound) {
622     newLineCheck();
623     outputUpToEndOfLine(Str);
624     EnumerationMatchFound = true;
625   }
626   return false;
627 }
628 
629 bool Output::matchEnumFallback() {
630   if (EnumerationMatchFound)
631     return false;
632   EnumerationMatchFound = true;
633   return true;
634 }
635 
636 void Output::endEnumScalar() {
637   if (!EnumerationMatchFound)
638     llvm_unreachable("bad runtime enum value");
639 }
640 
641 bool Output::beginBitSetScalar(bool &DoClear) {
642   newLineCheck();
643   output("[ ");
644   NeedBitValueComma = false;
645   DoClear = false;
646   return true;
647 }
648 
649 bool Output::bitSetMatch(const char *Str, bool Matches) {
650   if (Matches) {
651     if (NeedBitValueComma)
652       output(", ");
653     output(Str);
654     NeedBitValueComma = true;
655   }
656   return false;
657 }
658 
659 void Output::endBitSetScalar() {
660   outputUpToEndOfLine(" ]");
661 }
662 
663 void Output::scalarString(StringRef &S, QuotingType MustQuote) {
664   newLineCheck();
665   if (S.empty()) {
666     // Print '' for the empty string because leaving the field empty is not
667     // allowed.
668     outputUpToEndOfLine("''");
669     return;
670   }
671   if (MustQuote == QuotingType::None) {
672     // Only quote if we must.
673     outputUpToEndOfLine(S);
674     return;
675   }
676 
677   const char *const Quote = MustQuote == QuotingType::Single ? "'" : "\"";
678   output(Quote); // Starting quote.
679 
680   // When using double-quoted strings (and only in that case), non-printable characters may be
681   // present, and will be escaped using a variety of unicode-scalar and special short-form
682   // escapes. This is handled in yaml::escape.
683   if (MustQuote == QuotingType::Double) {
684     output(yaml::escape(S, /* EscapePrintable= */ false));
685     outputUpToEndOfLine(Quote);
686     return;
687   }
688 
689   unsigned i = 0;
690   unsigned j = 0;
691   unsigned End = S.size();
692   const char *Base = S.data();
693 
694   // When using single-quoted strings, any single quote ' must be doubled to be escaped.
695   while (j < End) {
696     if (S[j] == '\'') {                    // Escape quotes.
697       output(StringRef(&Base[i], j - i));  // "flush".
698       output(StringLiteral("''"));         // Print it as ''
699       i = j + 1;
700     }
701     ++j;
702   }
703   output(StringRef(&Base[i], j - i));
704   outputUpToEndOfLine(Quote); // Ending quote.
705 }
706 
707 void Output::blockScalarString(StringRef &S) {
708   if (!StateStack.empty())
709     newLineCheck();
710   output(" |");
711   outputNewLine();
712 
713   unsigned Indent = StateStack.empty() ? 1 : StateStack.size();
714 
715   auto Buffer = MemoryBuffer::getMemBuffer(S, "", false);
716   for (line_iterator Lines(*Buffer, false); !Lines.is_at_end(); ++Lines) {
717     for (unsigned I = 0; I < Indent; ++I) {
718       output("  ");
719     }
720     output(*Lines);
721     outputNewLine();
722   }
723 }
724 
725 void Output::scalarTag(std::string &Tag) {
726   if (Tag.empty())
727     return;
728   newLineCheck();
729   output(Tag);
730   output(" ");
731 }
732 
733 void Output::setError(const Twine &message) {
734 }
735 
736 bool Output::canElideEmptySequence() {
737   // Normally, with an optional key/value where the value is an empty sequence,
738   // the whole key/value can be not written.  But, that produces wrong yaml
739   // if the key/value is the only thing in the map and the map is used in
740   // a sequence.  This detects if the this sequence is the first key/value
741   // in map that itself is embedded in a sequnce.
742   if (StateStack.size() < 2)
743     return true;
744   if (StateStack.back() != inMapFirstKey)
745     return true;
746   return !inSeqAnyElement(StateStack[StateStack.size() - 2]);
747 }
748 
749 void Output::output(StringRef s) {
750   Column += s.size();
751   Out << s;
752 }
753 
754 void Output::outputUpToEndOfLine(StringRef s) {
755   output(s);
756   if (StateStack.empty() || (!inFlowSeqAnyElement(StateStack.back()) &&
757                              !inFlowMapAnyKey(StateStack.back())))
758     Padding = "\n";
759 }
760 
761 void Output::outputNewLine() {
762   Out << "\n";
763   Column = 0;
764 }
765 
766 // if seq at top, indent as if map, then add "- "
767 // if seq in middle, use "- " if firstKey, else use "  "
768 //
769 
770 void Output::newLineCheck() {
771   if (Padding != "\n") {
772     output(Padding);
773     Padding = {};
774     return;
775   }
776   outputNewLine();
777   Padding = {};
778 
779   if (StateStack.size() == 0)
780     return;
781 
782   unsigned Indent = StateStack.size() - 1;
783   bool OutputDash = false;
784 
785   if (StateStack.back() == inSeqFirstElement ||
786       StateStack.back() == inSeqOtherElement) {
787     OutputDash = true;
788   } else if ((StateStack.size() > 1) &&
789              ((StateStack.back() == inMapFirstKey) ||
790               inFlowSeqAnyElement(StateStack.back()) ||
791               (StateStack.back() == inFlowMapFirstKey)) &&
792              inSeqAnyElement(StateStack[StateStack.size() - 2])) {
793     --Indent;
794     OutputDash = true;
795   }
796 
797   for (unsigned i = 0; i < Indent; ++i) {
798     output("  ");
799   }
800   if (OutputDash) {
801     output("- ");
802   }
803 
804 }
805 
806 void Output::paddedKey(StringRef key) {
807   output(key);
808   output(":");
809   const char *spaces = "                ";
810   if (key.size() < strlen(spaces))
811     Padding = &spaces[key.size()];
812   else
813     Padding = " ";
814 }
815 
816 void Output::flowKey(StringRef Key) {
817   if (StateStack.back() == inFlowMapOtherKey)
818     output(", ");
819   if (WrapColumn && Column > WrapColumn) {
820     output("\n");
821     for (int I = 0; I < ColumnAtMapFlowStart; ++I)
822       output(" ");
823     Column = ColumnAtMapFlowStart;
824     output("  ");
825   }
826   output(Key);
827   output(": ");
828 }
829 
830 NodeKind Output::getNodeKind() { report_fatal_error("invalid call"); }
831 
832 bool Output::inSeqAnyElement(InState State) {
833   return State == inSeqFirstElement || State == inSeqOtherElement;
834 }
835 
836 bool Output::inFlowSeqAnyElement(InState State) {
837   return State == inFlowSeqFirstElement || State == inFlowSeqOtherElement;
838 }
839 
840 bool Output::inMapAnyKey(InState State) {
841   return State == inMapFirstKey || State == inMapOtherKey;
842 }
843 
844 bool Output::inFlowMapAnyKey(InState State) {
845   return State == inFlowMapFirstKey || State == inFlowMapOtherKey;
846 }
847 
848 //===----------------------------------------------------------------------===//
849 //  traits for built-in types
850 //===----------------------------------------------------------------------===//
851 
852 void ScalarTraits<bool>::output(const bool &Val, void *, raw_ostream &Out) {
853   Out << (Val ? "true" : "false");
854 }
855 
856 StringRef ScalarTraits<bool>::input(StringRef Scalar, void *, bool &Val) {
857   if (Scalar.equals("true")) {
858     Val = true;
859     return StringRef();
860   } else if (Scalar.equals("false")) {
861     Val = false;
862     return StringRef();
863   }
864   return "invalid boolean";
865 }
866 
867 void ScalarTraits<StringRef>::output(const StringRef &Val, void *,
868                                      raw_ostream &Out) {
869   Out << Val;
870 }
871 
872 StringRef ScalarTraits<StringRef>::input(StringRef Scalar, void *,
873                                          StringRef &Val) {
874   Val = Scalar;
875   return StringRef();
876 }
877 
878 void ScalarTraits<std::string>::output(const std::string &Val, void *,
879                                      raw_ostream &Out) {
880   Out << Val;
881 }
882 
883 StringRef ScalarTraits<std::string>::input(StringRef Scalar, void *,
884                                          std::string &Val) {
885   Val = Scalar.str();
886   return StringRef();
887 }
888 
889 void ScalarTraits<uint8_t>::output(const uint8_t &Val, void *,
890                                    raw_ostream &Out) {
891   // use temp uin32_t because ostream thinks uint8_t is a character
892   uint32_t Num = Val;
893   Out << Num;
894 }
895 
896 StringRef ScalarTraits<uint8_t>::input(StringRef Scalar, void *, uint8_t &Val) {
897   unsigned long long n;
898   if (getAsUnsignedInteger(Scalar, 0, n))
899     return "invalid number";
900   if (n > 0xFF)
901     return "out of range number";
902   Val = n;
903   return StringRef();
904 }
905 
906 void ScalarTraits<uint16_t>::output(const uint16_t &Val, void *,
907                                     raw_ostream &Out) {
908   Out << Val;
909 }
910 
911 StringRef ScalarTraits<uint16_t>::input(StringRef Scalar, void *,
912                                         uint16_t &Val) {
913   unsigned long long n;
914   if (getAsUnsignedInteger(Scalar, 0, n))
915     return "invalid number";
916   if (n > 0xFFFF)
917     return "out of range number";
918   Val = n;
919   return StringRef();
920 }
921 
922 void ScalarTraits<uint32_t>::output(const uint32_t &Val, void *,
923                                     raw_ostream &Out) {
924   Out << Val;
925 }
926 
927 StringRef ScalarTraits<uint32_t>::input(StringRef Scalar, void *,
928                                         uint32_t &Val) {
929   unsigned long long n;
930   if (getAsUnsignedInteger(Scalar, 0, n))
931     return "invalid number";
932   if (n > 0xFFFFFFFFUL)
933     return "out of range number";
934   Val = n;
935   return StringRef();
936 }
937 
938 void ScalarTraits<uint64_t>::output(const uint64_t &Val, void *,
939                                     raw_ostream &Out) {
940   Out << Val;
941 }
942 
943 StringRef ScalarTraits<uint64_t>::input(StringRef Scalar, void *,
944                                         uint64_t &Val) {
945   unsigned long long N;
946   if (getAsUnsignedInteger(Scalar, 0, N))
947     return "invalid number";
948   Val = N;
949   return StringRef();
950 }
951 
952 void ScalarTraits<int8_t>::output(const int8_t &Val, void *, raw_ostream &Out) {
953   // use temp in32_t because ostream thinks int8_t is a character
954   int32_t Num = Val;
955   Out << Num;
956 }
957 
958 StringRef ScalarTraits<int8_t>::input(StringRef Scalar, void *, int8_t &Val) {
959   long long N;
960   if (getAsSignedInteger(Scalar, 0, N))
961     return "invalid number";
962   if ((N > 127) || (N < -128))
963     return "out of range number";
964   Val = N;
965   return StringRef();
966 }
967 
968 void ScalarTraits<int16_t>::output(const int16_t &Val, void *,
969                                    raw_ostream &Out) {
970   Out << Val;
971 }
972 
973 StringRef ScalarTraits<int16_t>::input(StringRef Scalar, void *, int16_t &Val) {
974   long long N;
975   if (getAsSignedInteger(Scalar, 0, N))
976     return "invalid number";
977   if ((N > INT16_MAX) || (N < INT16_MIN))
978     return "out of range number";
979   Val = N;
980   return StringRef();
981 }
982 
983 void ScalarTraits<int32_t>::output(const int32_t &Val, void *,
984                                    raw_ostream &Out) {
985   Out << Val;
986 }
987 
988 StringRef ScalarTraits<int32_t>::input(StringRef Scalar, void *, int32_t &Val) {
989   long long N;
990   if (getAsSignedInteger(Scalar, 0, N))
991     return "invalid number";
992   if ((N > INT32_MAX) || (N < INT32_MIN))
993     return "out of range number";
994   Val = N;
995   return StringRef();
996 }
997 
998 void ScalarTraits<int64_t>::output(const int64_t &Val, void *,
999                                    raw_ostream &Out) {
1000   Out << Val;
1001 }
1002 
1003 StringRef ScalarTraits<int64_t>::input(StringRef Scalar, void *, int64_t &Val) {
1004   long long N;
1005   if (getAsSignedInteger(Scalar, 0, N))
1006     return "invalid number";
1007   Val = N;
1008   return StringRef();
1009 }
1010 
1011 void ScalarTraits<double>::output(const double &Val, void *, raw_ostream &Out) {
1012   Out << format("%g", Val);
1013 }
1014 
1015 StringRef ScalarTraits<double>::input(StringRef Scalar, void *, double &Val) {
1016   if (to_float(Scalar, Val))
1017     return StringRef();
1018   return "invalid floating point number";
1019 }
1020 
1021 void ScalarTraits<float>::output(const float &Val, void *, raw_ostream &Out) {
1022   Out << format("%g", Val);
1023 }
1024 
1025 StringRef ScalarTraits<float>::input(StringRef Scalar, void *, float &Val) {
1026   if (to_float(Scalar, Val))
1027     return StringRef();
1028   return "invalid floating point number";
1029 }
1030 
1031 void ScalarTraits<Hex8>::output(const Hex8 &Val, void *, raw_ostream &Out) {
1032   uint8_t Num = Val;
1033   Out << format("0x%02X", Num);
1034 }
1035 
1036 StringRef ScalarTraits<Hex8>::input(StringRef Scalar, void *, Hex8 &Val) {
1037   unsigned long long n;
1038   if (getAsUnsignedInteger(Scalar, 0, n))
1039     return "invalid hex8 number";
1040   if (n > 0xFF)
1041     return "out of range hex8 number";
1042   Val = n;
1043   return StringRef();
1044 }
1045 
1046 void ScalarTraits<Hex16>::output(const Hex16 &Val, void *, raw_ostream &Out) {
1047   uint16_t Num = Val;
1048   Out << format("0x%04X", Num);
1049 }
1050 
1051 StringRef ScalarTraits<Hex16>::input(StringRef Scalar, void *, Hex16 &Val) {
1052   unsigned long long n;
1053   if (getAsUnsignedInteger(Scalar, 0, n))
1054     return "invalid hex16 number";
1055   if (n > 0xFFFF)
1056     return "out of range hex16 number";
1057   Val = n;
1058   return StringRef();
1059 }
1060 
1061 void ScalarTraits<Hex32>::output(const Hex32 &Val, void *, raw_ostream &Out) {
1062   uint32_t Num = Val;
1063   Out << format("0x%08X", Num);
1064 }
1065 
1066 StringRef ScalarTraits<Hex32>::input(StringRef Scalar, void *, Hex32 &Val) {
1067   unsigned long long n;
1068   if (getAsUnsignedInteger(Scalar, 0, n))
1069     return "invalid hex32 number";
1070   if (n > 0xFFFFFFFFUL)
1071     return "out of range hex32 number";
1072   Val = n;
1073   return StringRef();
1074 }
1075 
1076 void ScalarTraits<Hex64>::output(const Hex64 &Val, void *, raw_ostream &Out) {
1077   uint64_t Num = Val;
1078   Out << format("0x%016llX", Num);
1079 }
1080 
1081 StringRef ScalarTraits<Hex64>::input(StringRef Scalar, void *, Hex64 &Val) {
1082   unsigned long long Num;
1083   if (getAsUnsignedInteger(Scalar, 0, Num))
1084     return "invalid hex64 number";
1085   Val = Num;
1086   return StringRef();
1087 }
1088