YAMLTraits.cpp 26 KB

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