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