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