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