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