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