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