YAMLTraits.cpp revision 353358
1296417Sdim//===- lib/Support/YAMLTraits.cpp -----------------------------------------===//
2254721Semaste//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6254721Semaste//
7296417Sdim//===----------------------------------------------------------------------===//
8254721Semaste
9254721Semaste#include "llvm/Support/YAMLTraits.h"
10254721Semaste#include "llvm/ADT/STLExtras.h"
11254721Semaste#include "llvm/ADT/SmallString.h"
12254721Semaste#include "llvm/ADT/StringExtras.h"
13254721Semaste#include "llvm/ADT/StringRef.h"
14254721Semaste#include "llvm/ADT/Twine.h"
15296417Sdim#include "llvm/Support/Casting.h"
16296417Sdim#include "llvm/Support/Errc.h"
17254721Semaste#include "llvm/Support/ErrorHandling.h"
18254721Semaste#include "llvm/Support/Format.h"
19254721Semaste#include "llvm/Support/LineIterator.h"
20321369Sdim#include "llvm/Support/MemoryBuffer.h"
21321369Sdim#include "llvm/Support/Unicode.h"
22341825Sdim#include "llvm/Support/YAMLParser.h"
23254721Semaste#include "llvm/Support/raw_ostream.h"
24314564Sdim#include <algorithm>
25254721Semaste#include <cassert>
26314564Sdim#include <cstdint>
27314564Sdim#include <cstdlib>
28314564Sdim#include <cstring>
29314564Sdim#include <string>
30254721Semaste#include <vector>
31341825Sdim
32314564Sdimusing namespace llvm;
33314564Sdimusing namespace yaml;
34341825Sdim
35314564Sdim//===----------------------------------------------------------------------===//
36314564Sdim//  IO
37314564Sdim//===----------------------------------------------------------------------===//
38254721Semaste
39314564SdimIO::IO(void *Context) : Ctxt(Context) {}
40314564Sdim
41254721SemasteIO::~IO() = default;
42314564Sdim
43314564Sdimvoid *IO::getContext() {
44254721Semaste  return Ctxt;
45314564Sdim}
46314564Sdim
47296417Sdimvoid IO::setContext(void *Context) {
48314564Sdim  Ctxt = Context;
49314564Sdim}
50314564Sdim
51314564Sdim//===----------------------------------------------------------------------===//
52314564Sdim//  Input
53314564Sdim//===----------------------------------------------------------------------===//
54314564Sdim
55314564SdimInput::Input(StringRef InputContent, void *Ctxt,
56314564Sdim             SourceMgr::DiagHandlerTy DiagHandler, void *DiagHandlerCtxt)
57314564Sdim    : IO(Ctxt), Strm(new Stream(InputContent, SrcMgr, false, &EC)) {
58254721Semaste  if (DiagHandler)
59314564Sdim    SrcMgr.setDiagHandler(DiagHandler, DiagHandlerCtxt);
60314564Sdim  DocIterator = Strm->begin();
61314564Sdim}
62314564Sdim
63254721SemasteInput::Input(MemoryBufferRef Input, void *Ctxt,
64314564Sdim             SourceMgr::DiagHandlerTy DiagHandler, void *DiagHandlerCtxt)
65254721Semaste    : IO(Ctxt), Strm(new Stream(Input, SrcMgr, false, &EC)) {
66314564Sdim  if (DiagHandler)
67314564Sdim    SrcMgr.setDiagHandler(DiagHandler, DiagHandlerCtxt);
68314564Sdim  DocIterator = Strm->begin();
69314564Sdim}
70314564Sdim
71314564SdimInput::~Input() = default;
72314564Sdim
73314564Sdimstd::error_code Input::error() { return EC; }
74314564Sdim
75314564Sdim// Pin the vtables to this file.
76314564Sdimvoid Input::HNode::anchor() {}
77314564Sdimvoid Input::EmptyHNode::anchor() {}
78314564Sdimvoid Input::ScalarHNode::anchor() {}
79314564Sdimvoid Input::MapHNode::anchor() {}
80314564Sdimvoid Input::SequenceHNode::anchor() {}
81314564Sdim
82314564Sdimbool Input::outputting() {
83314564Sdim  return false;
84314564Sdim}
85314564Sdim
86314564Sdimbool Input::setCurrentDocument() {
87314564Sdim  if (DocIterator != Strm->end()) {
88314564Sdim    Node *N = DocIterator->getRoot();
89314564Sdim    if (!N) {
90314564Sdim      assert(Strm->failed() && "Root is NULL iff parsing failed");
91314564Sdim      EC = make_error_code(errc::invalid_argument);
92314564Sdim      return false;
93314564Sdim    }
94314564Sdim
95314564Sdim    if (isa<NullNode>(N)) {
96314564Sdim      // Empty files are allowed and ignored
97314564Sdim      ++DocIterator;
98314564Sdim      return setCurrentDocument();
99314564Sdim    }
100314564Sdim    TopNode = createHNodes(N);
101314564Sdim    CurrentNode = TopNode.get();
102314564Sdim    return true;
103314564Sdim  }
104314564Sdim  return false;
105314564Sdim}
106314564Sdim
107314564Sdimbool Input::nextDocument() {
108254721Semaste  return ++DocIterator != Strm->end();
109314564Sdim}
110314564Sdim
111314564Sdimconst Node *Input::getCurrentNode() const {
112254721Semaste  return CurrentNode ? CurrentNode->_node : nullptr;
113314564Sdim}
114254721Semaste
115254721Semastebool Input::mapTag(StringRef Tag, bool Default) {
116314564Sdim  // CurrentNode can be null if setCurrentDocument() was unable to
117314564Sdim  // parse the document because it was invalid or empty.
118314564Sdim  if (!CurrentNode)
119314564Sdim    return false;
120314564Sdim
121314564Sdim  std::string foundTag = CurrentNode->_node->getVerbatimTag();
122314564Sdim  if (foundTag.empty()) {
123314564Sdim    // If no tag found and 'Tag' is the default, say it was found.
124314564Sdim    return Default;
125314564Sdim  }
126314564Sdim  // Return true iff found tag matches supplied tag.
127314564Sdim  return Tag.equals(foundTag);
128314564Sdim}
129314564Sdim
130314564Sdimvoid Input::beginMapping() {
131314564Sdim  if (EC)
132314564Sdim    return;
133314564Sdim  // CurrentNode can be null if the document is empty.
134314564Sdim  MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
135314564Sdim  if (MN) {
136314564Sdim    MN->ValidKeys.clear();
137314564Sdim  }
138254721Semaste}
139314564Sdim
140314564Sdimstd::vector<StringRef> Input::keys() {
141314564Sdim  MapHNode *MN = dyn_cast<MapHNode>(CurrentNode);
142314564Sdim  std::vector<StringRef> Ret;
143314564Sdim  if (!MN) {
144314564Sdim    setError(CurrentNode, "not a mapping");
145314564Sdim    return Ret;
146314564Sdim  }
147314564Sdim  for (auto &P : MN->Mapping)
148314564Sdim    Ret.push_back(P.first());
149314564Sdim  return Ret;
150314564Sdim}
151314564Sdim
152314564Sdimbool Input::preflightKey(const char *Key, bool Required, bool, bool &UseDefault,
153314564Sdim                         void *&SaveInfo) {
154314564Sdim  UseDefault = false;
155321369Sdim  if (EC)
156254721Semaste    return false;
157296417Sdim
158314564Sdim  // CurrentNode is null for empty documents, which is an error in case required
159314564Sdim  // nodes are present.
160314564Sdim  if (!CurrentNode) {
161314564Sdim    if (Required)
162254721Semaste      EC = make_error_code(errc::invalid_argument);
163314564Sdim    return false;
164314564Sdim  }
165314564Sdim
166314564Sdim  MapHNode *MN = dyn_cast<MapHNode>(CurrentNode);
167314564Sdim  if (!MN) {
168314564Sdim    if (Required || !isa<EmptyHNode>(CurrentNode))
169314564Sdim      setError(CurrentNode, "not a mapping");
170314564Sdim    return false;
171314564Sdim  }
172314564Sdim  MN->ValidKeys.push_back(Key);
173314564Sdim  HNode *Value = MN->Mapping[Key].get();
174314564Sdim  if (!Value) {
175314564Sdim    if (Required)
176254721Semaste      setError(CurrentNode, Twine("missing required key '") + Key + "'");
177314564Sdim    else
178254721Semaste      UseDefault = true;
179314564Sdim    return false;
180314564Sdim  }
181314564Sdim  SaveInfo = CurrentNode;
182321369Sdim  CurrentNode = Value;
183314564Sdim  return true;
184296417Sdim}
185314564Sdim
186327952Sdimvoid Input::postflightKey(void *saveInfo) {
187314564Sdim  CurrentNode = reinterpret_cast<HNode *>(saveInfo);
188327952Sdim}
189327952Sdim
190314564Sdimvoid Input::endMapping() {
191296417Sdim  if (EC)
192314564Sdim    return;
193327952Sdim  // CurrentNode can be null if the document is empty.
194314564Sdim  MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
195327952Sdim  if (!MN)
196327952Sdim    return;
197314564Sdim  for (const auto &NN : MN->Mapping) {
198309124Sdim    if (!is_contained(MN->ValidKeys, NN.first())) {
199314564Sdim      setError(NN.second.get(), Twine("unknown key '") + NN.first() + "'");
200327952Sdim      break;
201314564Sdim    }
202327952Sdim  }
203327952Sdim}
204314564Sdim
205254721Semastevoid Input::beginFlowMapping() { beginMapping(); }
206341825Sdim
207341825Sdimvoid Input::endFlowMapping() { endMapping(); }
208314564Sdim
209254721Semasteunsigned Input::beginSequence() {
210314564Sdim  if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode))
211314564Sdim    return SQ->Entries.size();
212314564Sdim  if (isa<EmptyHNode>(CurrentNode))
213314564Sdim    return 0;
214314564Sdim  // Treat case where there's a scalar "null" value as an empty sequence.
215314564Sdim  if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
216314564Sdim    if (isNull(SN->value()))
217314564Sdim      return 0;
218314564Sdim  }
219314564Sdim  // Any other type of HNode is an error.
220314564Sdim  setError(CurrentNode, "not a sequence");
221314564Sdim  return 0;
222314564Sdim}
223314564Sdim
224314564Sdimvoid Input::endSequence() {
225314564Sdim}
226314564Sdim
227314564Sdimbool Input::preflightElement(unsigned Index, void *&SaveInfo) {
228314564Sdim  if (EC)
229314564Sdim    return false;
230314564Sdim  if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
231314564Sdim    SaveInfo = CurrentNode;
232314564Sdim    CurrentNode = SQ->Entries[Index].get();
233314564Sdim    return true;
234314564Sdim  }
235314564Sdim  return false;
236314564Sdim}
237314564Sdim
238314564Sdimvoid Input::postflightElement(void *SaveInfo) {
239314564Sdim  CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
240314564Sdim}
241321369Sdim
242314564Sdimunsigned Input::beginFlowSequence() { return beginSequence(); }
243254721Semaste
244314564Sdimbool Input::preflightFlowElement(unsigned index, void *&SaveInfo) {
245254721Semaste  if (EC)
246314564Sdim    return false;
247314564Sdim  if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
248314564Sdim    SaveInfo = CurrentNode;
249254721Semaste    CurrentNode = SQ->Entries[index].get();
250314564Sdim    return true;
251314564Sdim  }
252314564Sdim  return false;
253254721Semaste}
254341825Sdim
255341825Sdimvoid Input::postflightFlowElement(void *SaveInfo) {
256341825Sdim  CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
257341825Sdim}
258341825Sdim
259341825Sdimvoid Input::endFlowSequence() {
260314564Sdim}
261254721Semaste
262314564Sdimvoid Input::beginEnumScalar() {
263314564Sdim  ScalarMatchFound = false;
264254721Semaste}
265314564Sdim
266314564Sdimbool Input::matchEnumScalar(const char *Str, bool) {
267341825Sdim  if (ScalarMatchFound)
268341825Sdim    return false;
269341825Sdim  if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
270341825Sdim    if (SN->value().equals(Str)) {
271341825Sdim      ScalarMatchFound = true;
272341825Sdim      return true;
273341825Sdim    }
274341825Sdim  }
275341825Sdim  return false;
276341825Sdim}
277341825Sdim
278341825Sdimbool Input::matchEnumFallback() {
279341825Sdim  if (ScalarMatchFound)
280314564Sdim    return false;
281314564Sdim  ScalarMatchFound = true;
282254721Semaste  return true;
283314564Sdim}
284314564Sdim
285314564Sdimvoid Input::endEnumScalar() {
286314564Sdim  if (!ScalarMatchFound) {
287314564Sdim    setError(CurrentNode, "unknown enumerated scalar");
288314564Sdim  }
289314564Sdim}
290314564Sdim
291314564Sdimbool Input::beginBitSetScalar(bool &DoClear) {
292314564Sdim  BitValuesUsed.clear();
293314564Sdim  if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
294314564Sdim    BitValuesUsed.insert(BitValuesUsed.begin(), SQ->Entries.size(), false);
295314564Sdim  } else {
296314564Sdim    setError(CurrentNode, "expected sequence of bit values");
297254721Semaste  }
298314564Sdim  DoClear = true;
299314564Sdim  return true;
300254721Semaste}
301314564Sdim
302314564Sdimbool Input::bitSetMatch(const char *Str, bool) {
303314564Sdim  if (EC)
304314564Sdim    return false;
305314564Sdim  if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
306314564Sdim    unsigned Index = 0;
307314564Sdim    for (auto &N : SQ->Entries) {
308254721Semaste      if (ScalarHNode *SN = dyn_cast<ScalarHNode>(N.get())) {
309254721Semaste        if (SN->value().equals(Str)) {
310296417Sdim          BitValuesUsed[Index] = true;
311          return true;
312        }
313      } else {
314        setError(CurrentNode, "unexpected scalar in sequence of bit values");
315      }
316      ++Index;
317    }
318  } else {
319    setError(CurrentNode, "expected sequence of bit values");
320  }
321  return false;
322}
323
324void Input::endBitSetScalar() {
325  if (EC)
326    return;
327  if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
328    assert(BitValuesUsed.size() == SQ->Entries.size());
329    for (unsigned i = 0; i < SQ->Entries.size(); ++i) {
330      if (!BitValuesUsed[i]) {
331        setError(SQ->Entries[i].get(), "unknown bit value");
332        return;
333      }
334    }
335  }
336}
337
338void Input::scalarString(StringRef &S, QuotingType) {
339  if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
340    S = SN->value();
341  } else {
342    setError(CurrentNode, "unexpected scalar");
343  }
344}
345
346void Input::blockScalarString(StringRef &S) { scalarString(S, QuotingType::None); }
347
348void Input::scalarTag(std::string &Tag) {
349  Tag = CurrentNode->_node->getVerbatimTag();
350}
351
352void Input::setError(HNode *hnode, const Twine &message) {
353  assert(hnode && "HNode must not be NULL");
354  setError(hnode->_node, message);
355}
356
357NodeKind Input::getNodeKind() {
358  if (isa<ScalarHNode>(CurrentNode))
359    return NodeKind::Scalar;
360  else if (isa<MapHNode>(CurrentNode))
361    return NodeKind::Map;
362  else if (isa<SequenceHNode>(CurrentNode))
363    return NodeKind::Sequence;
364  llvm_unreachable("Unsupported node kind");
365}
366
367void Input::setError(Node *node, const Twine &message) {
368  Strm->printError(node, message);
369  EC = make_error_code(errc::invalid_argument);
370}
371
372std::unique_ptr<Input::HNode> Input::createHNodes(Node *N) {
373  SmallString<128> StringStorage;
374  if (ScalarNode *SN = dyn_cast<ScalarNode>(N)) {
375    StringRef KeyStr = SN->getValue(StringStorage);
376    if (!StringStorage.empty()) {
377      // Copy string to permanent storage
378      KeyStr = StringStorage.str().copy(StringAllocator);
379    }
380    return llvm::make_unique<ScalarHNode>(N, KeyStr);
381  } else if (BlockScalarNode *BSN = dyn_cast<BlockScalarNode>(N)) {
382    StringRef ValueCopy = BSN->getValue().copy(StringAllocator);
383    return llvm::make_unique<ScalarHNode>(N, ValueCopy);
384  } else if (SequenceNode *SQ = dyn_cast<SequenceNode>(N)) {
385    auto SQHNode = llvm::make_unique<SequenceHNode>(N);
386    for (Node &SN : *SQ) {
387      auto Entry = createHNodes(&SN);
388      if (EC)
389        break;
390      SQHNode->Entries.push_back(std::move(Entry));
391    }
392    return std::move(SQHNode);
393  } else if (MappingNode *Map = dyn_cast<MappingNode>(N)) {
394    auto mapHNode = llvm::make_unique<MapHNode>(N);
395    for (KeyValueNode &KVN : *Map) {
396      Node *KeyNode = KVN.getKey();
397      ScalarNode *Key = dyn_cast<ScalarNode>(KeyNode);
398      Node *Value = KVN.getValue();
399      if (!Key || !Value) {
400        if (!Key)
401          setError(KeyNode, "Map key must be a scalar");
402        if (!Value)
403          setError(KeyNode, "Map value must not be empty");
404        break;
405      }
406      StringStorage.clear();
407      StringRef KeyStr = Key->getValue(StringStorage);
408      if (!StringStorage.empty()) {
409        // Copy string to permanent storage
410        KeyStr = StringStorage.str().copy(StringAllocator);
411      }
412      auto ValueHNode = createHNodes(Value);
413      if (EC)
414        break;
415      mapHNode->Mapping[KeyStr] = std::move(ValueHNode);
416    }
417    return std::move(mapHNode);
418  } else if (isa<NullNode>(N)) {
419    return llvm::make_unique<EmptyHNode>(N);
420  } else {
421    setError(N, "unknown node kind");
422    return nullptr;
423  }
424}
425
426void Input::setError(const Twine &Message) {
427  setError(CurrentNode, Message);
428}
429
430bool Input::canElideEmptySequence() {
431  return false;
432}
433
434//===----------------------------------------------------------------------===//
435//  Output
436//===----------------------------------------------------------------------===//
437
438Output::Output(raw_ostream &yout, void *context, int WrapColumn)
439    : IO(context), Out(yout), WrapColumn(WrapColumn) {}
440
441Output::~Output() = default;
442
443bool Output::outputting() {
444  return true;
445}
446
447void Output::beginMapping() {
448  StateStack.push_back(inMapFirstKey);
449  PaddingBeforeContainer = Padding;
450  Padding = "\n";
451}
452
453bool Output::mapTag(StringRef Tag, bool Use) {
454  if (Use) {
455    // If this tag is being written inside a sequence we should write the start
456    // of the sequence before writing the tag, otherwise the tag won't be
457    // attached to the element in the sequence, but rather the sequence itself.
458    bool SequenceElement = false;
459    if (StateStack.size() > 1) {
460      auto &E = StateStack[StateStack.size() - 2];
461      SequenceElement = inSeqAnyElement(E) || inFlowSeqAnyElement(E);
462    }
463    if (SequenceElement && StateStack.back() == inMapFirstKey) {
464      newLineCheck();
465    } else {
466      output(" ");
467    }
468    output(Tag);
469    if (SequenceElement) {
470      // If we're writing the tag during the first element of a map, the tag
471      // takes the place of the first element in the sequence.
472      if (StateStack.back() == inMapFirstKey) {
473        StateStack.pop_back();
474        StateStack.push_back(inMapOtherKey);
475      }
476      // Tags inside maps in sequences should act as keys in the map from a
477      // formatting perspective, so we always want a newline in a sequence.
478      Padding = "\n";
479    }
480  }
481  return Use;
482}
483
484void Output::endMapping() {
485  // If we did not map anything, we should explicitly emit an empty map
486  if (StateStack.back() == inMapFirstKey) {
487    Padding = PaddingBeforeContainer;
488    newLineCheck();
489    output("{}");
490    Padding = "\n";
491  }
492  StateStack.pop_back();
493}
494
495std::vector<StringRef> Output::keys() {
496  report_fatal_error("invalid call");
497}
498
499bool Output::preflightKey(const char *Key, bool Required, bool SameAsDefault,
500                          bool &UseDefault, void *&) {
501  UseDefault = false;
502  if (Required || !SameAsDefault || WriteDefaultValues) {
503    auto State = StateStack.back();
504    if (State == inFlowMapFirstKey || State == inFlowMapOtherKey) {
505      flowKey(Key);
506    } else {
507      newLineCheck();
508      paddedKey(Key);
509    }
510    return true;
511  }
512  return false;
513}
514
515void Output::postflightKey(void *) {
516  if (StateStack.back() == inMapFirstKey) {
517    StateStack.pop_back();
518    StateStack.push_back(inMapOtherKey);
519  } else if (StateStack.back() == inFlowMapFirstKey) {
520    StateStack.pop_back();
521    StateStack.push_back(inFlowMapOtherKey);
522  }
523}
524
525void Output::beginFlowMapping() {
526  StateStack.push_back(inFlowMapFirstKey);
527  newLineCheck();
528  ColumnAtMapFlowStart = Column;
529  output("{ ");
530}
531
532void Output::endFlowMapping() {
533  StateStack.pop_back();
534  outputUpToEndOfLine(" }");
535}
536
537void Output::beginDocuments() {
538  outputUpToEndOfLine("---");
539}
540
541bool Output::preflightDocument(unsigned index) {
542  if (index > 0)
543    outputUpToEndOfLine("\n---");
544  return true;
545}
546
547void Output::postflightDocument() {
548}
549
550void Output::endDocuments() {
551  output("\n...\n");
552}
553
554unsigned Output::beginSequence() {
555  StateStack.push_back(inSeqFirstElement);
556  PaddingBeforeContainer = Padding;
557  Padding = "\n";
558  return 0;
559}
560
561void Output::endSequence() {
562  // If we did not emit anything, we should explicitly emit an empty sequence
563  if (StateStack.back() == inSeqFirstElement) {
564    Padding = PaddingBeforeContainer;
565    newLineCheck();
566    output("[]");
567    Padding = "\n";
568  }
569  StateStack.pop_back();
570}
571
572bool Output::preflightElement(unsigned, void *&) {
573  return true;
574}
575
576void Output::postflightElement(void *) {
577  if (StateStack.back() == inSeqFirstElement) {
578    StateStack.pop_back();
579    StateStack.push_back(inSeqOtherElement);
580  } else if (StateStack.back() == inFlowSeqFirstElement) {
581    StateStack.pop_back();
582    StateStack.push_back(inFlowSeqOtherElement);
583  }
584}
585
586unsigned Output::beginFlowSequence() {
587  StateStack.push_back(inFlowSeqFirstElement);
588  newLineCheck();
589  ColumnAtFlowStart = Column;
590  output("[ ");
591  NeedFlowSequenceComma = false;
592  return 0;
593}
594
595void Output::endFlowSequence() {
596  StateStack.pop_back();
597  outputUpToEndOfLine(" ]");
598}
599
600bool Output::preflightFlowElement(unsigned, void *&) {
601  if (NeedFlowSequenceComma)
602    output(", ");
603  if (WrapColumn && Column > WrapColumn) {
604    output("\n");
605    for (int i = 0; i < ColumnAtFlowStart; ++i)
606      output(" ");
607    Column = ColumnAtFlowStart;
608    output("  ");
609  }
610  return true;
611}
612
613void Output::postflightFlowElement(void *) {
614  NeedFlowSequenceComma = true;
615}
616
617void Output::beginEnumScalar() {
618  EnumerationMatchFound = false;
619}
620
621bool Output::matchEnumScalar(const char *Str, bool Match) {
622  if (Match && !EnumerationMatchFound) {
623    newLineCheck();
624    outputUpToEndOfLine(Str);
625    EnumerationMatchFound = true;
626  }
627  return false;
628}
629
630bool Output::matchEnumFallback() {
631  if (EnumerationMatchFound)
632    return false;
633  EnumerationMatchFound = true;
634  return true;
635}
636
637void Output::endEnumScalar() {
638  if (!EnumerationMatchFound)
639    llvm_unreachable("bad runtime enum value");
640}
641
642bool Output::beginBitSetScalar(bool &DoClear) {
643  newLineCheck();
644  output("[ ");
645  NeedBitValueComma = false;
646  DoClear = false;
647  return true;
648}
649
650bool Output::bitSetMatch(const char *Str, bool Matches) {
651  if (Matches) {
652    if (NeedBitValueComma)
653      output(", ");
654    output(Str);
655    NeedBitValueComma = true;
656  }
657  return false;
658}
659
660void Output::endBitSetScalar() {
661  outputUpToEndOfLine(" ]");
662}
663
664void Output::scalarString(StringRef &S, QuotingType MustQuote) {
665  newLineCheck();
666  if (S.empty()) {
667    // Print '' for the empty string because leaving the field empty is not
668    // allowed.
669    outputUpToEndOfLine("''");
670    return;
671  }
672  if (MustQuote == QuotingType::None) {
673    // Only quote if we must.
674    outputUpToEndOfLine(S);
675    return;
676  }
677
678  const char *const Quote = MustQuote == QuotingType::Single ? "'" : "\"";
679  output(Quote); // Starting quote.
680
681  // When using double-quoted strings (and only in that case), non-printable characters may be
682  // present, and will be escaped using a variety of unicode-scalar and special short-form
683  // escapes. This is handled in yaml::escape.
684  if (MustQuote == QuotingType::Double) {
685    output(yaml::escape(S, /* EscapePrintable= */ false));
686    outputUpToEndOfLine(Quote);
687    return;
688  }
689
690  unsigned i = 0;
691  unsigned j = 0;
692  unsigned End = S.size();
693  const char *Base = S.data();
694
695  // When using single-quoted strings, any single quote ' must be doubled to be escaped.
696  while (j < End) {
697    if (S[j] == '\'') {                    // Escape quotes.
698      output(StringRef(&Base[i], j - i));  // "flush".
699      output(StringLiteral("''"));         // Print it as ''
700      i = j + 1;
701    }
702    ++j;
703  }
704  output(StringRef(&Base[i], j - i));
705  outputUpToEndOfLine(Quote); // Ending quote.
706}
707
708void Output::blockScalarString(StringRef &S) {
709  if (!StateStack.empty())
710    newLineCheck();
711  output(" |");
712  outputNewLine();
713
714  unsigned Indent = StateStack.empty() ? 1 : StateStack.size();
715
716  auto Buffer = MemoryBuffer::getMemBuffer(S, "", false);
717  for (line_iterator Lines(*Buffer, false); !Lines.is_at_end(); ++Lines) {
718    for (unsigned I = 0; I < Indent; ++I) {
719      output("  ");
720    }
721    output(*Lines);
722    outputNewLine();
723  }
724}
725
726void Output::scalarTag(std::string &Tag) {
727  if (Tag.empty())
728    return;
729  newLineCheck();
730  output(Tag);
731  output(" ");
732}
733
734void Output::setError(const Twine &message) {
735}
736
737bool Output::canElideEmptySequence() {
738  // Normally, with an optional key/value where the value is an empty sequence,
739  // the whole key/value can be not written.  But, that produces wrong yaml
740  // if the key/value is the only thing in the map and the map is used in
741  // a sequence.  This detects if the this sequence is the first key/value
742  // in map that itself is embedded in a sequnce.
743  if (StateStack.size() < 2)
744    return true;
745  if (StateStack.back() != inMapFirstKey)
746    return true;
747  return !inSeqAnyElement(StateStack[StateStack.size() - 2]);
748}
749
750void Output::output(StringRef s) {
751  Column += s.size();
752  Out << s;
753}
754
755void Output::outputUpToEndOfLine(StringRef s) {
756  output(s);
757  if (StateStack.empty() || (!inFlowSeqAnyElement(StateStack.back()) &&
758                             !inFlowMapAnyKey(StateStack.back())))
759    Padding = "\n";
760}
761
762void Output::outputNewLine() {
763  Out << "\n";
764  Column = 0;
765}
766
767// if seq at top, indent as if map, then add "- "
768// if seq in middle, use "- " if firstKey, else use "  "
769//
770
771void Output::newLineCheck() {
772  if (Padding != "\n") {
773    output(Padding);
774    Padding = {};
775    return;
776  }
777  outputNewLine();
778  Padding = {};
779
780  if (StateStack.size() == 0)
781    return;
782
783  unsigned Indent = StateStack.size() - 1;
784  bool OutputDash = false;
785
786  if (StateStack.back() == inSeqFirstElement ||
787      StateStack.back() == inSeqOtherElement) {
788    OutputDash = true;
789  } else if ((StateStack.size() > 1) &&
790             ((StateStack.back() == inMapFirstKey) ||
791              inFlowSeqAnyElement(StateStack.back()) ||
792              (StateStack.back() == inFlowMapFirstKey)) &&
793             inSeqAnyElement(StateStack[StateStack.size() - 2])) {
794    --Indent;
795    OutputDash = true;
796  }
797
798  for (unsigned i = 0; i < Indent; ++i) {
799    output("  ");
800  }
801  if (OutputDash) {
802    output("- ");
803  }
804
805}
806
807void Output::paddedKey(StringRef key) {
808  output(key);
809  output(":");
810  const char *spaces = "                ";
811  if (key.size() < strlen(spaces))
812    Padding = &spaces[key.size()];
813  else
814    Padding = " ";
815}
816
817void Output::flowKey(StringRef Key) {
818  if (StateStack.back() == inFlowMapOtherKey)
819    output(", ");
820  if (WrapColumn && Column > WrapColumn) {
821    output("\n");
822    for (int I = 0; I < ColumnAtMapFlowStart; ++I)
823      output(" ");
824    Column = ColumnAtMapFlowStart;
825    output("  ");
826  }
827  output(Key);
828  output(": ");
829}
830
831NodeKind Output::getNodeKind() { report_fatal_error("invalid call"); }
832
833bool Output::inSeqAnyElement(InState State) {
834  return State == inSeqFirstElement || State == inSeqOtherElement;
835}
836
837bool Output::inFlowSeqAnyElement(InState State) {
838  return State == inFlowSeqFirstElement || State == inFlowSeqOtherElement;
839}
840
841bool Output::inMapAnyKey(InState State) {
842  return State == inMapFirstKey || State == inMapOtherKey;
843}
844
845bool Output::inFlowMapAnyKey(InState State) {
846  return State == inFlowMapFirstKey || State == inFlowMapOtherKey;
847}
848
849//===----------------------------------------------------------------------===//
850//  traits for built-in types
851//===----------------------------------------------------------------------===//
852
853void ScalarTraits<bool>::output(const bool &Val, void *, raw_ostream &Out) {
854  Out << (Val ? "true" : "false");
855}
856
857StringRef ScalarTraits<bool>::input(StringRef Scalar, void *, bool &Val) {
858  if (Scalar.equals("true")) {
859    Val = true;
860    return StringRef();
861  } else if (Scalar.equals("false")) {
862    Val = false;
863    return StringRef();
864  }
865  return "invalid boolean";
866}
867
868void ScalarTraits<StringRef>::output(const StringRef &Val, void *,
869                                     raw_ostream &Out) {
870  Out << Val;
871}
872
873StringRef ScalarTraits<StringRef>::input(StringRef Scalar, void *,
874                                         StringRef &Val) {
875  Val = Scalar;
876  return StringRef();
877}
878
879void ScalarTraits<std::string>::output(const std::string &Val, void *,
880                                     raw_ostream &Out) {
881  Out << Val;
882}
883
884StringRef ScalarTraits<std::string>::input(StringRef Scalar, void *,
885                                         std::string &Val) {
886  Val = Scalar.str();
887  return StringRef();
888}
889
890void ScalarTraits<uint8_t>::output(const uint8_t &Val, void *,
891                                   raw_ostream &Out) {
892  // use temp uin32_t because ostream thinks uint8_t is a character
893  uint32_t Num = Val;
894  Out << Num;
895}
896
897StringRef ScalarTraits<uint8_t>::input(StringRef Scalar, void *, uint8_t &Val) {
898  unsigned long long n;
899  if (getAsUnsignedInteger(Scalar, 0, n))
900    return "invalid number";
901  if (n > 0xFF)
902    return "out of range number";
903  Val = n;
904  return StringRef();
905}
906
907void ScalarTraits<uint16_t>::output(const uint16_t &Val, void *,
908                                    raw_ostream &Out) {
909  Out << Val;
910}
911
912StringRef ScalarTraits<uint16_t>::input(StringRef Scalar, void *,
913                                        uint16_t &Val) {
914  unsigned long long n;
915  if (getAsUnsignedInteger(Scalar, 0, n))
916    return "invalid number";
917  if (n > 0xFFFF)
918    return "out of range number";
919  Val = n;
920  return StringRef();
921}
922
923void ScalarTraits<uint32_t>::output(const uint32_t &Val, void *,
924                                    raw_ostream &Out) {
925  Out << Val;
926}
927
928StringRef ScalarTraits<uint32_t>::input(StringRef Scalar, void *,
929                                        uint32_t &Val) {
930  unsigned long long n;
931  if (getAsUnsignedInteger(Scalar, 0, n))
932    return "invalid number";
933  if (n > 0xFFFFFFFFUL)
934    return "out of range number";
935  Val = n;
936  return StringRef();
937}
938
939void ScalarTraits<uint64_t>::output(const uint64_t &Val, void *,
940                                    raw_ostream &Out) {
941  Out << Val;
942}
943
944StringRef ScalarTraits<uint64_t>::input(StringRef Scalar, void *,
945                                        uint64_t &Val) {
946  unsigned long long N;
947  if (getAsUnsignedInteger(Scalar, 0, N))
948    return "invalid number";
949  Val = N;
950  return StringRef();
951}
952
953void ScalarTraits<int8_t>::output(const int8_t &Val, void *, raw_ostream &Out) {
954  // use temp in32_t because ostream thinks int8_t is a character
955  int32_t Num = Val;
956  Out << Num;
957}
958
959StringRef ScalarTraits<int8_t>::input(StringRef Scalar, void *, int8_t &Val) {
960  long long N;
961  if (getAsSignedInteger(Scalar, 0, N))
962    return "invalid number";
963  if ((N > 127) || (N < -128))
964    return "out of range number";
965  Val = N;
966  return StringRef();
967}
968
969void ScalarTraits<int16_t>::output(const int16_t &Val, void *,
970                                   raw_ostream &Out) {
971  Out << Val;
972}
973
974StringRef ScalarTraits<int16_t>::input(StringRef Scalar, void *, int16_t &Val) {
975  long long N;
976  if (getAsSignedInteger(Scalar, 0, N))
977    return "invalid number";
978  if ((N > INT16_MAX) || (N < INT16_MIN))
979    return "out of range number";
980  Val = N;
981  return StringRef();
982}
983
984void ScalarTraits<int32_t>::output(const int32_t &Val, void *,
985                                   raw_ostream &Out) {
986  Out << Val;
987}
988
989StringRef ScalarTraits<int32_t>::input(StringRef Scalar, void *, int32_t &Val) {
990  long long N;
991  if (getAsSignedInteger(Scalar, 0, N))
992    return "invalid number";
993  if ((N > INT32_MAX) || (N < INT32_MIN))
994    return "out of range number";
995  Val = N;
996  return StringRef();
997}
998
999void ScalarTraits<int64_t>::output(const int64_t &Val, void *,
1000                                   raw_ostream &Out) {
1001  Out << Val;
1002}
1003
1004StringRef ScalarTraits<int64_t>::input(StringRef Scalar, void *, int64_t &Val) {
1005  long long N;
1006  if (getAsSignedInteger(Scalar, 0, N))
1007    return "invalid number";
1008  Val = N;
1009  return StringRef();
1010}
1011
1012void ScalarTraits<double>::output(const double &Val, void *, raw_ostream &Out) {
1013  Out << format("%g", Val);
1014}
1015
1016StringRef ScalarTraits<double>::input(StringRef Scalar, void *, double &Val) {
1017  if (to_float(Scalar, Val))
1018    return StringRef();
1019  return "invalid floating point number";
1020}
1021
1022void ScalarTraits<float>::output(const float &Val, void *, raw_ostream &Out) {
1023  Out << format("%g", Val);
1024}
1025
1026StringRef ScalarTraits<float>::input(StringRef Scalar, void *, float &Val) {
1027  if (to_float(Scalar, Val))
1028    return StringRef();
1029  return "invalid floating point number";
1030}
1031
1032void ScalarTraits<Hex8>::output(const Hex8 &Val, void *, raw_ostream &Out) {
1033  uint8_t Num = Val;
1034  Out << format("0x%02X", Num);
1035}
1036
1037StringRef ScalarTraits<Hex8>::input(StringRef Scalar, void *, Hex8 &Val) {
1038  unsigned long long n;
1039  if (getAsUnsignedInteger(Scalar, 0, n))
1040    return "invalid hex8 number";
1041  if (n > 0xFF)
1042    return "out of range hex8 number";
1043  Val = n;
1044  return StringRef();
1045}
1046
1047void ScalarTraits<Hex16>::output(const Hex16 &Val, void *, raw_ostream &Out) {
1048  uint16_t Num = Val;
1049  Out << format("0x%04X", Num);
1050}
1051
1052StringRef ScalarTraits<Hex16>::input(StringRef Scalar, void *, Hex16 &Val) {
1053  unsigned long long n;
1054  if (getAsUnsignedInteger(Scalar, 0, n))
1055    return "invalid hex16 number";
1056  if (n > 0xFFFF)
1057    return "out of range hex16 number";
1058  Val = n;
1059  return StringRef();
1060}
1061
1062void ScalarTraits<Hex32>::output(const Hex32 &Val, void *, raw_ostream &Out) {
1063  uint32_t Num = Val;
1064  Out << format("0x%08X", Num);
1065}
1066
1067StringRef ScalarTraits<Hex32>::input(StringRef Scalar, void *, Hex32 &Val) {
1068  unsigned long long n;
1069  if (getAsUnsignedInteger(Scalar, 0, n))
1070    return "invalid hex32 number";
1071  if (n > 0xFFFFFFFFUL)
1072    return "out of range hex32 number";
1073  Val = n;
1074  return StringRef();
1075}
1076
1077void ScalarTraits<Hex64>::output(const Hex64 &Val, void *, raw_ostream &Out) {
1078  uint64_t Num = Val;
1079  Out << format("0x%016llX", Num);
1080}
1081
1082StringRef ScalarTraits<Hex64>::input(StringRef Scalar, void *, Hex64 &Val) {
1083  unsigned long long Num;
1084  if (getAsUnsignedInteger(Scalar, 0, Num))
1085    return "invalid hex64 number";
1086  Val = Num;
1087  return StringRef();
1088}
1089