YAMLParser.cpp 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599
  1. //===- YAMLParser.cpp - Simple YAML parser --------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements a YAML parser.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Support/YAMLParser.h"
  13. #include "llvm/ADT/AllocatorList.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/ADT/Twine.h"
  21. #include "llvm/Support/Compiler.h"
  22. #include "llvm/Support/ErrorHandling.h"
  23. #include "llvm/Support/MemoryBuffer.h"
  24. #include "llvm/Support/SMLoc.h"
  25. #include "llvm/Support/SourceMgr.h"
  26. #include "llvm/Support/Unicode.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <cassert>
  29. #include <cstddef>
  30. #include <cstdint>
  31. #include <map>
  32. #include <memory>
  33. #include <string>
  34. #include <system_error>
  35. #include <utility>
  36. using namespace llvm;
  37. using namespace yaml;
  38. enum UnicodeEncodingForm {
  39. UEF_UTF32_LE, ///< UTF-32 Little Endian
  40. UEF_UTF32_BE, ///< UTF-32 Big Endian
  41. UEF_UTF16_LE, ///< UTF-16 Little Endian
  42. UEF_UTF16_BE, ///< UTF-16 Big Endian
  43. UEF_UTF8, ///< UTF-8 or ascii.
  44. UEF_Unknown ///< Not a valid Unicode encoding.
  45. };
  46. /// EncodingInfo - Holds the encoding type and length of the byte order mark if
  47. /// it exists. Length is in {0, 2, 3, 4}.
  48. using EncodingInfo = std::pair<UnicodeEncodingForm, unsigned>;
  49. /// getUnicodeEncoding - Reads up to the first 4 bytes to determine the Unicode
  50. /// encoding form of \a Input.
  51. ///
  52. /// @param Input A string of length 0 or more.
  53. /// @returns An EncodingInfo indicating the Unicode encoding form of the input
  54. /// and how long the byte order mark is if one exists.
  55. static EncodingInfo getUnicodeEncoding(StringRef Input) {
  56. if (Input.empty())
  57. return std::make_pair(UEF_Unknown, 0);
  58. switch (uint8_t(Input[0])) {
  59. case 0x00:
  60. if (Input.size() >= 4) {
  61. if ( Input[1] == 0
  62. && uint8_t(Input[2]) == 0xFE
  63. && uint8_t(Input[3]) == 0xFF)
  64. return std::make_pair(UEF_UTF32_BE, 4);
  65. if (Input[1] == 0 && Input[2] == 0 && Input[3] != 0)
  66. return std::make_pair(UEF_UTF32_BE, 0);
  67. }
  68. if (Input.size() >= 2 && Input[1] != 0)
  69. return std::make_pair(UEF_UTF16_BE, 0);
  70. return std::make_pair(UEF_Unknown, 0);
  71. case 0xFF:
  72. if ( Input.size() >= 4
  73. && uint8_t(Input[1]) == 0xFE
  74. && Input[2] == 0
  75. && Input[3] == 0)
  76. return std::make_pair(UEF_UTF32_LE, 4);
  77. if (Input.size() >= 2 && uint8_t(Input[1]) == 0xFE)
  78. return std::make_pair(UEF_UTF16_LE, 2);
  79. return std::make_pair(UEF_Unknown, 0);
  80. case 0xFE:
  81. if (Input.size() >= 2 && uint8_t(Input[1]) == 0xFF)
  82. return std::make_pair(UEF_UTF16_BE, 2);
  83. return std::make_pair(UEF_Unknown, 0);
  84. case 0xEF:
  85. if ( Input.size() >= 3
  86. && uint8_t(Input[1]) == 0xBB
  87. && uint8_t(Input[2]) == 0xBF)
  88. return std::make_pair(UEF_UTF8, 3);
  89. return std::make_pair(UEF_Unknown, 0);
  90. }
  91. // It could still be utf-32 or utf-16.
  92. if (Input.size() >= 4 && Input[1] == 0 && Input[2] == 0 && Input[3] == 0)
  93. return std::make_pair(UEF_UTF32_LE, 0);
  94. if (Input.size() >= 2 && Input[1] == 0)
  95. return std::make_pair(UEF_UTF16_LE, 0);
  96. return std::make_pair(UEF_UTF8, 0);
  97. }
  98. /// Pin the vtables to this file.
  99. void Node::anchor() {}
  100. void NullNode::anchor() {}
  101. void ScalarNode::anchor() {}
  102. void BlockScalarNode::anchor() {}
  103. void KeyValueNode::anchor() {}
  104. void MappingNode::anchor() {}
  105. void SequenceNode::anchor() {}
  106. void AliasNode::anchor() {}
  107. namespace llvm {
  108. namespace yaml {
  109. /// Token - A single YAML token.
  110. struct Token {
  111. enum TokenKind {
  112. TK_Error, // Uninitialized token.
  113. TK_StreamStart,
  114. TK_StreamEnd,
  115. TK_VersionDirective,
  116. TK_TagDirective,
  117. TK_DocumentStart,
  118. TK_DocumentEnd,
  119. TK_BlockEntry,
  120. TK_BlockEnd,
  121. TK_BlockSequenceStart,
  122. TK_BlockMappingStart,
  123. TK_FlowEntry,
  124. TK_FlowSequenceStart,
  125. TK_FlowSequenceEnd,
  126. TK_FlowMappingStart,
  127. TK_FlowMappingEnd,
  128. TK_Key,
  129. TK_Value,
  130. TK_Scalar,
  131. TK_BlockScalar,
  132. TK_Alias,
  133. TK_Anchor,
  134. TK_Tag
  135. } Kind = TK_Error;
  136. /// A string of length 0 or more whose begin() points to the logical location
  137. /// of the token in the input.
  138. StringRef Range;
  139. /// The value of a block scalar node.
  140. std::string Value;
  141. Token() = default;
  142. };
  143. } // end namespace yaml
  144. } // end namespace llvm
  145. using TokenQueueT = BumpPtrList<Token>;
  146. namespace {
  147. /// This struct is used to track simple keys.
  148. ///
  149. /// Simple keys are handled by creating an entry in SimpleKeys for each Token
  150. /// which could legally be the start of a simple key. When peekNext is called,
  151. /// if the Token To be returned is referenced by a SimpleKey, we continue
  152. /// tokenizing until that potential simple key has either been found to not be
  153. /// a simple key (we moved on to the next line or went further than 1024 chars).
  154. /// Or when we run into a Value, and then insert a Key token (and possibly
  155. /// others) before the SimpleKey's Tok.
  156. struct SimpleKey {
  157. TokenQueueT::iterator Tok;
  158. unsigned Column = 0;
  159. unsigned Line = 0;
  160. unsigned FlowLevel = 0;
  161. bool IsRequired = false;
  162. bool operator ==(const SimpleKey &Other) {
  163. return Tok == Other.Tok;
  164. }
  165. };
  166. } // end anonymous namespace
  167. /// The Unicode scalar value of a UTF-8 minimal well-formed code unit
  168. /// subsequence and the subsequence's length in code units (uint8_t).
  169. /// A length of 0 represents an error.
  170. using UTF8Decoded = std::pair<uint32_t, unsigned>;
  171. static UTF8Decoded decodeUTF8(StringRef Range) {
  172. StringRef::iterator Position= Range.begin();
  173. StringRef::iterator End = Range.end();
  174. // 1 byte: [0x00, 0x7f]
  175. // Bit pattern: 0xxxxxxx
  176. if (Position < End && (*Position & 0x80) == 0) {
  177. return std::make_pair(*Position, 1);
  178. }
  179. // 2 bytes: [0x80, 0x7ff]
  180. // Bit pattern: 110xxxxx 10xxxxxx
  181. if (Position + 1 < End && ((*Position & 0xE0) == 0xC0) &&
  182. ((*(Position + 1) & 0xC0) == 0x80)) {
  183. uint32_t codepoint = ((*Position & 0x1F) << 6) |
  184. (*(Position + 1) & 0x3F);
  185. if (codepoint >= 0x80)
  186. return std::make_pair(codepoint, 2);
  187. }
  188. // 3 bytes: [0x8000, 0xffff]
  189. // Bit pattern: 1110xxxx 10xxxxxx 10xxxxxx
  190. if (Position + 2 < End && ((*Position & 0xF0) == 0xE0) &&
  191. ((*(Position + 1) & 0xC0) == 0x80) &&
  192. ((*(Position + 2) & 0xC0) == 0x80)) {
  193. uint32_t codepoint = ((*Position & 0x0F) << 12) |
  194. ((*(Position + 1) & 0x3F) << 6) |
  195. (*(Position + 2) & 0x3F);
  196. // Codepoints between 0xD800 and 0xDFFF are invalid, as
  197. // they are high / low surrogate halves used by UTF-16.
  198. if (codepoint >= 0x800 &&
  199. (codepoint < 0xD800 || codepoint > 0xDFFF))
  200. return std::make_pair(codepoint, 3);
  201. }
  202. // 4 bytes: [0x10000, 0x10FFFF]
  203. // Bit pattern: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  204. if (Position + 3 < End && ((*Position & 0xF8) == 0xF0) &&
  205. ((*(Position + 1) & 0xC0) == 0x80) &&
  206. ((*(Position + 2) & 0xC0) == 0x80) &&
  207. ((*(Position + 3) & 0xC0) == 0x80)) {
  208. uint32_t codepoint = ((*Position & 0x07) << 18) |
  209. ((*(Position + 1) & 0x3F) << 12) |
  210. ((*(Position + 2) & 0x3F) << 6) |
  211. (*(Position + 3) & 0x3F);
  212. if (codepoint >= 0x10000 && codepoint <= 0x10FFFF)
  213. return std::make_pair(codepoint, 4);
  214. }
  215. return std::make_pair(0, 0);
  216. }
  217. namespace llvm {
  218. namespace yaml {
  219. /// Scans YAML tokens from a MemoryBuffer.
  220. class Scanner {
  221. public:
  222. Scanner(StringRef Input, SourceMgr &SM, bool ShowColors = true,
  223. std::error_code *EC = nullptr);
  224. Scanner(MemoryBufferRef Buffer, SourceMgr &SM_, bool ShowColors = true,
  225. std::error_code *EC = nullptr);
  226. /// Parse the next token and return it without popping it.
  227. Token &peekNext();
  228. /// Parse the next token and pop it from the queue.
  229. Token getNext();
  230. void printError(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Message,
  231. ArrayRef<SMRange> Ranges = std::nullopt) {
  232. SM.PrintMessage(Loc, Kind, Message, Ranges, /* FixIts= */ std::nullopt,
  233. ShowColors);
  234. }
  235. void setError(const Twine &Message, StringRef::iterator Position) {
  236. if (Position >= End)
  237. Position = End - 1;
  238. // propagate the error if possible
  239. if (EC)
  240. *EC = make_error_code(std::errc::invalid_argument);
  241. // Don't print out more errors after the first one we encounter. The rest
  242. // are just the result of the first, and have no meaning.
  243. if (!Failed)
  244. printError(SMLoc::getFromPointer(Position), SourceMgr::DK_Error, Message);
  245. Failed = true;
  246. }
  247. /// Returns true if an error occurred while parsing.
  248. bool failed() {
  249. return Failed;
  250. }
  251. private:
  252. void init(MemoryBufferRef Buffer);
  253. StringRef currentInput() {
  254. return StringRef(Current, End - Current);
  255. }
  256. /// Decode a UTF-8 minimal well-formed code unit subsequence starting
  257. /// at \a Position.
  258. ///
  259. /// If the UTF-8 code units starting at Position do not form a well-formed
  260. /// code unit subsequence, then the Unicode scalar value is 0, and the length
  261. /// is 0.
  262. UTF8Decoded decodeUTF8(StringRef::iterator Position) {
  263. return ::decodeUTF8(StringRef(Position, End - Position));
  264. }
  265. // The following functions are based on the gramar rules in the YAML spec. The
  266. // style of the function names it meant to closely match how they are written
  267. // in the spec. The number within the [] is the number of the grammar rule in
  268. // the spec.
  269. //
  270. // See 4.2 [Production Naming Conventions] for the meaning of the prefixes.
  271. //
  272. // c-
  273. // A production starting and ending with a special character.
  274. // b-
  275. // A production matching a single line break.
  276. // nb-
  277. // A production starting and ending with a non-break character.
  278. // s-
  279. // A production starting and ending with a white space character.
  280. // ns-
  281. // A production starting and ending with a non-space character.
  282. // l-
  283. // A production matching complete line(s).
  284. /// Skip a single nb-char[27] starting at Position.
  285. ///
  286. /// A nb-char is 0x9 | [0x20-0x7E] | 0x85 | [0xA0-0xD7FF] | [0xE000-0xFEFE]
  287. /// | [0xFF00-0xFFFD] | [0x10000-0x10FFFF]
  288. ///
  289. /// @returns The code unit after the nb-char, or Position if it's not an
  290. /// nb-char.
  291. StringRef::iterator skip_nb_char(StringRef::iterator Position);
  292. /// Skip a single b-break[28] starting at Position.
  293. ///
  294. /// A b-break is 0xD 0xA | 0xD | 0xA
  295. ///
  296. /// @returns The code unit after the b-break, or Position if it's not a
  297. /// b-break.
  298. StringRef::iterator skip_b_break(StringRef::iterator Position);
  299. /// Skip a single s-space[31] starting at Position.
  300. ///
  301. /// An s-space is 0x20
  302. ///
  303. /// @returns The code unit after the s-space, or Position if it's not a
  304. /// s-space.
  305. StringRef::iterator skip_s_space(StringRef::iterator Position);
  306. /// Skip a single s-white[33] starting at Position.
  307. ///
  308. /// A s-white is 0x20 | 0x9
  309. ///
  310. /// @returns The code unit after the s-white, or Position if it's not a
  311. /// s-white.
  312. StringRef::iterator skip_s_white(StringRef::iterator Position);
  313. /// Skip a single ns-char[34] starting at Position.
  314. ///
  315. /// A ns-char is nb-char - s-white
  316. ///
  317. /// @returns The code unit after the ns-char, or Position if it's not a
  318. /// ns-char.
  319. StringRef::iterator skip_ns_char(StringRef::iterator Position);
  320. using SkipWhileFunc = StringRef::iterator (Scanner::*)(StringRef::iterator);
  321. /// Skip minimal well-formed code unit subsequences until Func
  322. /// returns its input.
  323. ///
  324. /// @returns The code unit after the last minimal well-formed code unit
  325. /// subsequence that Func accepted.
  326. StringRef::iterator skip_while( SkipWhileFunc Func
  327. , StringRef::iterator Position);
  328. /// Skip minimal well-formed code unit subsequences until Func returns its
  329. /// input.
  330. void advanceWhile(SkipWhileFunc Func);
  331. /// Scan ns-uri-char[39]s starting at Cur.
  332. ///
  333. /// This updates Cur and Column while scanning.
  334. void scan_ns_uri_char();
  335. /// Consume a minimal well-formed code unit subsequence starting at
  336. /// \a Cur. Return false if it is not the same Unicode scalar value as
  337. /// \a Expected. This updates \a Column.
  338. bool consume(uint32_t Expected);
  339. /// Skip \a Distance UTF-8 code units. Updates \a Cur and \a Column.
  340. void skip(uint32_t Distance);
  341. /// Return true if the minimal well-formed code unit subsequence at
  342. /// Pos is whitespace or a new line
  343. bool isBlankOrBreak(StringRef::iterator Position);
  344. /// Return true if the line is a line break, false otherwise.
  345. bool isLineEmpty(StringRef Line);
  346. /// Consume a single b-break[28] if it's present at the current position.
  347. ///
  348. /// Return false if the code unit at the current position isn't a line break.
  349. bool consumeLineBreakIfPresent();
  350. /// If IsSimpleKeyAllowed, create and push_back a new SimpleKey.
  351. void saveSimpleKeyCandidate( TokenQueueT::iterator Tok
  352. , unsigned AtColumn
  353. , bool IsRequired);
  354. /// Remove simple keys that can no longer be valid simple keys.
  355. ///
  356. /// Invalid simple keys are not on the current line or are further than 1024
  357. /// columns back.
  358. void removeStaleSimpleKeyCandidates();
  359. /// Remove all simple keys on FlowLevel \a Level.
  360. void removeSimpleKeyCandidatesOnFlowLevel(unsigned Level);
  361. /// Unroll indentation in \a Indents back to \a Col. Creates BlockEnd
  362. /// tokens if needed.
  363. bool unrollIndent(int ToColumn);
  364. /// Increase indent to \a Col. Creates \a Kind token at \a InsertPoint
  365. /// if needed.
  366. bool rollIndent( int ToColumn
  367. , Token::TokenKind Kind
  368. , TokenQueueT::iterator InsertPoint);
  369. /// Skip a single-line comment when the comment starts at the current
  370. /// position of the scanner.
  371. void skipComment();
  372. /// Skip whitespace and comments until the start of the next token.
  373. void scanToNextToken();
  374. /// Must be the first token generated.
  375. bool scanStreamStart();
  376. /// Generate tokens needed to close out the stream.
  377. bool scanStreamEnd();
  378. /// Scan a %BLAH directive.
  379. bool scanDirective();
  380. /// Scan a ... or ---.
  381. bool scanDocumentIndicator(bool IsStart);
  382. /// Scan a [ or { and generate the proper flow collection start token.
  383. bool scanFlowCollectionStart(bool IsSequence);
  384. /// Scan a ] or } and generate the proper flow collection end token.
  385. bool scanFlowCollectionEnd(bool IsSequence);
  386. /// Scan the , that separates entries in a flow collection.
  387. bool scanFlowEntry();
  388. /// Scan the - that starts block sequence entries.
  389. bool scanBlockEntry();
  390. /// Scan an explicit ? indicating a key.
  391. bool scanKey();
  392. /// Scan an explicit : indicating a value.
  393. bool scanValue();
  394. /// Scan a quoted scalar.
  395. bool scanFlowScalar(bool IsDoubleQuoted);
  396. /// Scan an unquoted scalar.
  397. bool scanPlainScalar();
  398. /// Scan an Alias or Anchor starting with * or &.
  399. bool scanAliasOrAnchor(bool IsAlias);
  400. /// Scan a block scalar starting with | or >.
  401. bool scanBlockScalar(bool IsLiteral);
  402. /// Scan a block scalar style indicator and header.
  403. ///
  404. /// Note: This is distinct from scanBlockScalarHeader to mirror the fact that
  405. /// YAML does not consider the style indicator to be a part of the header.
  406. ///
  407. /// Return false if an error occurred.
  408. bool scanBlockScalarIndicators(char &StyleIndicator, char &ChompingIndicator,
  409. unsigned &IndentIndicator, bool &IsDone);
  410. /// Scan a style indicator in a block scalar header.
  411. char scanBlockStyleIndicator();
  412. /// Scan a chomping indicator in a block scalar header.
  413. char scanBlockChompingIndicator();
  414. /// Scan an indentation indicator in a block scalar header.
  415. unsigned scanBlockIndentationIndicator();
  416. /// Scan a block scalar header.
  417. ///
  418. /// Return false if an error occurred.
  419. bool scanBlockScalarHeader(char &ChompingIndicator, unsigned &IndentIndicator,
  420. bool &IsDone);
  421. /// Look for the indentation level of a block scalar.
  422. ///
  423. /// Return false if an error occurred.
  424. bool findBlockScalarIndent(unsigned &BlockIndent, unsigned BlockExitIndent,
  425. unsigned &LineBreaks, bool &IsDone);
  426. /// Scan the indentation of a text line in a block scalar.
  427. ///
  428. /// Return false if an error occurred.
  429. bool scanBlockScalarIndent(unsigned BlockIndent, unsigned BlockExitIndent,
  430. bool &IsDone);
  431. /// Scan a tag of the form !stuff.
  432. bool scanTag();
  433. /// Dispatch to the next scanning function based on \a *Cur.
  434. bool fetchMoreTokens();
  435. /// The SourceMgr used for diagnostics and buffer management.
  436. SourceMgr &SM;
  437. /// The original input.
  438. MemoryBufferRef InputBuffer;
  439. /// The current position of the scanner.
  440. StringRef::iterator Current;
  441. /// The end of the input (one past the last character).
  442. StringRef::iterator End;
  443. /// Current YAML indentation level in spaces.
  444. int Indent;
  445. /// Current column number in Unicode code points.
  446. unsigned Column;
  447. /// Current line number.
  448. unsigned Line;
  449. /// How deep we are in flow style containers. 0 Means at block level.
  450. unsigned FlowLevel;
  451. /// Are we at the start of the stream?
  452. bool IsStartOfStream;
  453. /// Can the next token be the start of a simple key?
  454. bool IsSimpleKeyAllowed;
  455. /// True if an error has occurred.
  456. bool Failed;
  457. /// Should colors be used when printing out the diagnostic messages?
  458. bool ShowColors;
  459. /// Queue of tokens. This is required to queue up tokens while looking
  460. /// for the end of a simple key. And for cases where a single character
  461. /// can produce multiple tokens (e.g. BlockEnd).
  462. TokenQueueT TokenQueue;
  463. /// Indentation levels.
  464. SmallVector<int, 4> Indents;
  465. /// Potential simple keys.
  466. SmallVector<SimpleKey, 4> SimpleKeys;
  467. std::error_code *EC;
  468. };
  469. } // end namespace yaml
  470. } // end namespace llvm
  471. /// encodeUTF8 - Encode \a UnicodeScalarValue in UTF-8 and append it to result.
  472. static void encodeUTF8( uint32_t UnicodeScalarValue
  473. , SmallVectorImpl<char> &Result) {
  474. if (UnicodeScalarValue <= 0x7F) {
  475. Result.push_back(UnicodeScalarValue & 0x7F);
  476. } else if (UnicodeScalarValue <= 0x7FF) {
  477. uint8_t FirstByte = 0xC0 | ((UnicodeScalarValue & 0x7C0) >> 6);
  478. uint8_t SecondByte = 0x80 | (UnicodeScalarValue & 0x3F);
  479. Result.push_back(FirstByte);
  480. Result.push_back(SecondByte);
  481. } else if (UnicodeScalarValue <= 0xFFFF) {
  482. uint8_t FirstByte = 0xE0 | ((UnicodeScalarValue & 0xF000) >> 12);
  483. uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
  484. uint8_t ThirdByte = 0x80 | (UnicodeScalarValue & 0x3F);
  485. Result.push_back(FirstByte);
  486. Result.push_back(SecondByte);
  487. Result.push_back(ThirdByte);
  488. } else if (UnicodeScalarValue <= 0x10FFFF) {
  489. uint8_t FirstByte = 0xF0 | ((UnicodeScalarValue & 0x1F0000) >> 18);
  490. uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0x3F000) >> 12);
  491. uint8_t ThirdByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
  492. uint8_t FourthByte = 0x80 | (UnicodeScalarValue & 0x3F);
  493. Result.push_back(FirstByte);
  494. Result.push_back(SecondByte);
  495. Result.push_back(ThirdByte);
  496. Result.push_back(FourthByte);
  497. }
  498. }
  499. bool yaml::dumpTokens(StringRef Input, raw_ostream &OS) {
  500. SourceMgr SM;
  501. Scanner scanner(Input, SM);
  502. while (true) {
  503. Token T = scanner.getNext();
  504. switch (T.Kind) {
  505. case Token::TK_StreamStart:
  506. OS << "Stream-Start: ";
  507. break;
  508. case Token::TK_StreamEnd:
  509. OS << "Stream-End: ";
  510. break;
  511. case Token::TK_VersionDirective:
  512. OS << "Version-Directive: ";
  513. break;
  514. case Token::TK_TagDirective:
  515. OS << "Tag-Directive: ";
  516. break;
  517. case Token::TK_DocumentStart:
  518. OS << "Document-Start: ";
  519. break;
  520. case Token::TK_DocumentEnd:
  521. OS << "Document-End: ";
  522. break;
  523. case Token::TK_BlockEntry:
  524. OS << "Block-Entry: ";
  525. break;
  526. case Token::TK_BlockEnd:
  527. OS << "Block-End: ";
  528. break;
  529. case Token::TK_BlockSequenceStart:
  530. OS << "Block-Sequence-Start: ";
  531. break;
  532. case Token::TK_BlockMappingStart:
  533. OS << "Block-Mapping-Start: ";
  534. break;
  535. case Token::TK_FlowEntry:
  536. OS << "Flow-Entry: ";
  537. break;
  538. case Token::TK_FlowSequenceStart:
  539. OS << "Flow-Sequence-Start: ";
  540. break;
  541. case Token::TK_FlowSequenceEnd:
  542. OS << "Flow-Sequence-End: ";
  543. break;
  544. case Token::TK_FlowMappingStart:
  545. OS << "Flow-Mapping-Start: ";
  546. break;
  547. case Token::TK_FlowMappingEnd:
  548. OS << "Flow-Mapping-End: ";
  549. break;
  550. case Token::TK_Key:
  551. OS << "Key: ";
  552. break;
  553. case Token::TK_Value:
  554. OS << "Value: ";
  555. break;
  556. case Token::TK_Scalar:
  557. OS << "Scalar: ";
  558. break;
  559. case Token::TK_BlockScalar:
  560. OS << "Block Scalar: ";
  561. break;
  562. case Token::TK_Alias:
  563. OS << "Alias: ";
  564. break;
  565. case Token::TK_Anchor:
  566. OS << "Anchor: ";
  567. break;
  568. case Token::TK_Tag:
  569. OS << "Tag: ";
  570. break;
  571. case Token::TK_Error:
  572. break;
  573. }
  574. OS << T.Range << "\n";
  575. if (T.Kind == Token::TK_StreamEnd)
  576. break;
  577. else if (T.Kind == Token::TK_Error)
  578. return false;
  579. }
  580. return true;
  581. }
  582. bool yaml::scanTokens(StringRef Input) {
  583. SourceMgr SM;
  584. Scanner scanner(Input, SM);
  585. while (true) {
  586. Token T = scanner.getNext();
  587. if (T.Kind == Token::TK_StreamEnd)
  588. break;
  589. else if (T.Kind == Token::TK_Error)
  590. return false;
  591. }
  592. return true;
  593. }
  594. std::string yaml::escape(StringRef Input, bool EscapePrintable) {
  595. std::string EscapedInput;
  596. for (StringRef::iterator i = Input.begin(), e = Input.end(); i != e; ++i) {
  597. if (*i == '\\')
  598. EscapedInput += "\\\\";
  599. else if (*i == '"')
  600. EscapedInput += "\\\"";
  601. else if (*i == 0)
  602. EscapedInput += "\\0";
  603. else if (*i == 0x07)
  604. EscapedInput += "\\a";
  605. else if (*i == 0x08)
  606. EscapedInput += "\\b";
  607. else if (*i == 0x09)
  608. EscapedInput += "\\t";
  609. else if (*i == 0x0A)
  610. EscapedInput += "\\n";
  611. else if (*i == 0x0B)
  612. EscapedInput += "\\v";
  613. else if (*i == 0x0C)
  614. EscapedInput += "\\f";
  615. else if (*i == 0x0D)
  616. EscapedInput += "\\r";
  617. else if (*i == 0x1B)
  618. EscapedInput += "\\e";
  619. else if ((unsigned char)*i < 0x20) { // Control characters not handled above.
  620. std::string HexStr = utohexstr(*i);
  621. EscapedInput += "\\x" + std::string(2 - HexStr.size(), '0') + HexStr;
  622. } else if (*i & 0x80) { // UTF-8 multiple code unit subsequence.
  623. UTF8Decoded UnicodeScalarValue
  624. = decodeUTF8(StringRef(i, Input.end() - i));
  625. if (UnicodeScalarValue.second == 0) {
  626. // Found invalid char.
  627. SmallString<4> Val;
  628. encodeUTF8(0xFFFD, Val);
  629. llvm::append_range(EscapedInput, Val);
  630. // FIXME: Error reporting.
  631. return EscapedInput;
  632. }
  633. if (UnicodeScalarValue.first == 0x85)
  634. EscapedInput += "\\N";
  635. else if (UnicodeScalarValue.first == 0xA0)
  636. EscapedInput += "\\_";
  637. else if (UnicodeScalarValue.first == 0x2028)
  638. EscapedInput += "\\L";
  639. else if (UnicodeScalarValue.first == 0x2029)
  640. EscapedInput += "\\P";
  641. else if (!EscapePrintable &&
  642. sys::unicode::isPrintable(UnicodeScalarValue.first))
  643. EscapedInput += StringRef(i, UnicodeScalarValue.second);
  644. else {
  645. std::string HexStr = utohexstr(UnicodeScalarValue.first);
  646. if (HexStr.size() <= 2)
  647. EscapedInput += "\\x" + std::string(2 - HexStr.size(), '0') + HexStr;
  648. else if (HexStr.size() <= 4)
  649. EscapedInput += "\\u" + std::string(4 - HexStr.size(), '0') + HexStr;
  650. else if (HexStr.size() <= 8)
  651. EscapedInput += "\\U" + std::string(8 - HexStr.size(), '0') + HexStr;
  652. }
  653. i += UnicodeScalarValue.second - 1;
  654. } else
  655. EscapedInput.push_back(*i);
  656. }
  657. return EscapedInput;
  658. }
  659. std::optional<bool> yaml::parseBool(StringRef S) {
  660. switch (S.size()) {
  661. case 1:
  662. switch (S.front()) {
  663. case 'y':
  664. case 'Y':
  665. return true;
  666. case 'n':
  667. case 'N':
  668. return false;
  669. default:
  670. return std::nullopt;
  671. }
  672. case 2:
  673. switch (S.front()) {
  674. case 'O':
  675. if (S[1] == 'N') // ON
  676. return true;
  677. [[fallthrough]];
  678. case 'o':
  679. if (S[1] == 'n') //[Oo]n
  680. return true;
  681. return std::nullopt;
  682. case 'N':
  683. if (S[1] == 'O') // NO
  684. return false;
  685. [[fallthrough]];
  686. case 'n':
  687. if (S[1] == 'o') //[Nn]o
  688. return false;
  689. return std::nullopt;
  690. default:
  691. return std::nullopt;
  692. }
  693. case 3:
  694. switch (S.front()) {
  695. case 'O':
  696. if (S.drop_front() == "FF") // OFF
  697. return false;
  698. [[fallthrough]];
  699. case 'o':
  700. if (S.drop_front() == "ff") //[Oo]ff
  701. return false;
  702. return std::nullopt;
  703. case 'Y':
  704. if (S.drop_front() == "ES") // YES
  705. return true;
  706. [[fallthrough]];
  707. case 'y':
  708. if (S.drop_front() == "es") //[Yy]es
  709. return true;
  710. return std::nullopt;
  711. default:
  712. return std::nullopt;
  713. }
  714. case 4:
  715. switch (S.front()) {
  716. case 'T':
  717. if (S.drop_front() == "RUE") // TRUE
  718. return true;
  719. [[fallthrough]];
  720. case 't':
  721. if (S.drop_front() == "rue") //[Tt]rue
  722. return true;
  723. return std::nullopt;
  724. default:
  725. return std::nullopt;
  726. }
  727. case 5:
  728. switch (S.front()) {
  729. case 'F':
  730. if (S.drop_front() == "ALSE") // FALSE
  731. return false;
  732. [[fallthrough]];
  733. case 'f':
  734. if (S.drop_front() == "alse") //[Ff]alse
  735. return false;
  736. return std::nullopt;
  737. default:
  738. return std::nullopt;
  739. }
  740. default:
  741. return std::nullopt;
  742. }
  743. }
  744. Scanner::Scanner(StringRef Input, SourceMgr &sm, bool ShowColors,
  745. std::error_code *EC)
  746. : SM(sm), ShowColors(ShowColors), EC(EC) {
  747. init(MemoryBufferRef(Input, "YAML"));
  748. }
  749. Scanner::Scanner(MemoryBufferRef Buffer, SourceMgr &SM_, bool ShowColors,
  750. std::error_code *EC)
  751. : SM(SM_), ShowColors(ShowColors), EC(EC) {
  752. init(Buffer);
  753. }
  754. void Scanner::init(MemoryBufferRef Buffer) {
  755. InputBuffer = Buffer;
  756. Current = InputBuffer.getBufferStart();
  757. End = InputBuffer.getBufferEnd();
  758. Indent = -1;
  759. Column = 0;
  760. Line = 0;
  761. FlowLevel = 0;
  762. IsStartOfStream = true;
  763. IsSimpleKeyAllowed = true;
  764. Failed = false;
  765. std::unique_ptr<MemoryBuffer> InputBufferOwner =
  766. MemoryBuffer::getMemBuffer(Buffer, /*RequiresNullTerminator=*/false);
  767. SM.AddNewSourceBuffer(std::move(InputBufferOwner), SMLoc());
  768. }
  769. Token &Scanner::peekNext() {
  770. // If the current token is a possible simple key, keep parsing until we
  771. // can confirm.
  772. bool NeedMore = false;
  773. while (true) {
  774. if (TokenQueue.empty() || NeedMore) {
  775. if (!fetchMoreTokens()) {
  776. TokenQueue.clear();
  777. SimpleKeys.clear();
  778. TokenQueue.push_back(Token());
  779. return TokenQueue.front();
  780. }
  781. }
  782. assert(!TokenQueue.empty() &&
  783. "fetchMoreTokens lied about getting tokens!");
  784. removeStaleSimpleKeyCandidates();
  785. SimpleKey SK;
  786. SK.Tok = TokenQueue.begin();
  787. if (!is_contained(SimpleKeys, SK))
  788. break;
  789. else
  790. NeedMore = true;
  791. }
  792. return TokenQueue.front();
  793. }
  794. Token Scanner::getNext() {
  795. Token Ret = peekNext();
  796. // TokenQueue can be empty if there was an error getting the next token.
  797. if (!TokenQueue.empty())
  798. TokenQueue.pop_front();
  799. // There cannot be any referenced Token's if the TokenQueue is empty. So do a
  800. // quick deallocation of them all.
  801. if (TokenQueue.empty())
  802. TokenQueue.resetAlloc();
  803. return Ret;
  804. }
  805. StringRef::iterator Scanner::skip_nb_char(StringRef::iterator Position) {
  806. if (Position == End)
  807. return Position;
  808. // Check 7 bit c-printable - b-char.
  809. if ( *Position == 0x09
  810. || (*Position >= 0x20 && *Position <= 0x7E))
  811. return Position + 1;
  812. // Check for valid UTF-8.
  813. if (uint8_t(*Position) & 0x80) {
  814. UTF8Decoded u8d = decodeUTF8(Position);
  815. if ( u8d.second != 0
  816. && u8d.first != 0xFEFF
  817. && ( u8d.first == 0x85
  818. || ( u8d.first >= 0xA0
  819. && u8d.first <= 0xD7FF)
  820. || ( u8d.first >= 0xE000
  821. && u8d.first <= 0xFFFD)
  822. || ( u8d.first >= 0x10000
  823. && u8d.first <= 0x10FFFF)))
  824. return Position + u8d.second;
  825. }
  826. return Position;
  827. }
  828. StringRef::iterator Scanner::skip_b_break(StringRef::iterator Position) {
  829. if (Position == End)
  830. return Position;
  831. if (*Position == 0x0D) {
  832. if (Position + 1 != End && *(Position + 1) == 0x0A)
  833. return Position + 2;
  834. return Position + 1;
  835. }
  836. if (*Position == 0x0A)
  837. return Position + 1;
  838. return Position;
  839. }
  840. StringRef::iterator Scanner::skip_s_space(StringRef::iterator Position) {
  841. if (Position == End)
  842. return Position;
  843. if (*Position == ' ')
  844. return Position + 1;
  845. return Position;
  846. }
  847. StringRef::iterator Scanner::skip_s_white(StringRef::iterator Position) {
  848. if (Position == End)
  849. return Position;
  850. if (*Position == ' ' || *Position == '\t')
  851. return Position + 1;
  852. return Position;
  853. }
  854. StringRef::iterator Scanner::skip_ns_char(StringRef::iterator Position) {
  855. if (Position == End)
  856. return Position;
  857. if (*Position == ' ' || *Position == '\t')
  858. return Position;
  859. return skip_nb_char(Position);
  860. }
  861. StringRef::iterator Scanner::skip_while( SkipWhileFunc Func
  862. , StringRef::iterator Position) {
  863. while (true) {
  864. StringRef::iterator i = (this->*Func)(Position);
  865. if (i == Position)
  866. break;
  867. Position = i;
  868. }
  869. return Position;
  870. }
  871. void Scanner::advanceWhile(SkipWhileFunc Func) {
  872. auto Final = skip_while(Func, Current);
  873. Column += Final - Current;
  874. Current = Final;
  875. }
  876. static bool is_ns_hex_digit(const char C) { return isAlnum(C); }
  877. static bool is_ns_word_char(const char C) { return C == '-' || isAlpha(C); }
  878. void Scanner::scan_ns_uri_char() {
  879. while (true) {
  880. if (Current == End)
  881. break;
  882. if (( *Current == '%'
  883. && Current + 2 < End
  884. && is_ns_hex_digit(*(Current + 1))
  885. && is_ns_hex_digit(*(Current + 2)))
  886. || is_ns_word_char(*Current)
  887. || StringRef(Current, 1).find_first_of("#;/?:@&=+$,_.!~*'()[]")
  888. != StringRef::npos) {
  889. ++Current;
  890. ++Column;
  891. } else
  892. break;
  893. }
  894. }
  895. bool Scanner::consume(uint32_t Expected) {
  896. if (Expected >= 0x80) {
  897. setError("Cannot consume non-ascii characters", Current);
  898. return false;
  899. }
  900. if (Current == End)
  901. return false;
  902. if (uint8_t(*Current) >= 0x80) {
  903. setError("Cannot consume non-ascii characters", Current);
  904. return false;
  905. }
  906. if (uint8_t(*Current) == Expected) {
  907. ++Current;
  908. ++Column;
  909. return true;
  910. }
  911. return false;
  912. }
  913. void Scanner::skip(uint32_t Distance) {
  914. Current += Distance;
  915. Column += Distance;
  916. assert(Current <= End && "Skipped past the end");
  917. }
  918. bool Scanner::isBlankOrBreak(StringRef::iterator Position) {
  919. if (Position == End)
  920. return false;
  921. return *Position == ' ' || *Position == '\t' || *Position == '\r' ||
  922. *Position == '\n';
  923. }
  924. bool Scanner::isLineEmpty(StringRef Line) {
  925. for (const auto *Position = Line.begin(); Position != Line.end(); ++Position)
  926. if (!isBlankOrBreak(Position))
  927. return false;
  928. return true;
  929. }
  930. bool Scanner::consumeLineBreakIfPresent() {
  931. auto Next = skip_b_break(Current);
  932. if (Next == Current)
  933. return false;
  934. Column = 0;
  935. ++Line;
  936. Current = Next;
  937. return true;
  938. }
  939. void Scanner::saveSimpleKeyCandidate( TokenQueueT::iterator Tok
  940. , unsigned AtColumn
  941. , bool IsRequired) {
  942. if (IsSimpleKeyAllowed) {
  943. SimpleKey SK;
  944. SK.Tok = Tok;
  945. SK.Line = Line;
  946. SK.Column = AtColumn;
  947. SK.IsRequired = IsRequired;
  948. SK.FlowLevel = FlowLevel;
  949. SimpleKeys.push_back(SK);
  950. }
  951. }
  952. void Scanner::removeStaleSimpleKeyCandidates() {
  953. for (SmallVectorImpl<SimpleKey>::iterator i = SimpleKeys.begin();
  954. i != SimpleKeys.end();) {
  955. if (i->Line != Line || i->Column + 1024 < Column) {
  956. if (i->IsRequired)
  957. setError( "Could not find expected : for simple key"
  958. , i->Tok->Range.begin());
  959. i = SimpleKeys.erase(i);
  960. } else
  961. ++i;
  962. }
  963. }
  964. void Scanner::removeSimpleKeyCandidatesOnFlowLevel(unsigned Level) {
  965. if (!SimpleKeys.empty() && (SimpleKeys.end() - 1)->FlowLevel == Level)
  966. SimpleKeys.pop_back();
  967. }
  968. bool Scanner::unrollIndent(int ToColumn) {
  969. Token T;
  970. // Indentation is ignored in flow.
  971. if (FlowLevel != 0)
  972. return true;
  973. while (Indent > ToColumn) {
  974. T.Kind = Token::TK_BlockEnd;
  975. T.Range = StringRef(Current, 1);
  976. TokenQueue.push_back(T);
  977. Indent = Indents.pop_back_val();
  978. }
  979. return true;
  980. }
  981. bool Scanner::rollIndent( int ToColumn
  982. , Token::TokenKind Kind
  983. , TokenQueueT::iterator InsertPoint) {
  984. if (FlowLevel)
  985. return true;
  986. if (Indent < ToColumn) {
  987. Indents.push_back(Indent);
  988. Indent = ToColumn;
  989. Token T;
  990. T.Kind = Kind;
  991. T.Range = StringRef(Current, 0);
  992. TokenQueue.insert(InsertPoint, T);
  993. }
  994. return true;
  995. }
  996. void Scanner::skipComment() {
  997. if (Current == End || *Current != '#')
  998. return;
  999. while (true) {
  1000. // This may skip more than one byte, thus Column is only incremented
  1001. // for code points.
  1002. StringRef::iterator I = skip_nb_char(Current);
  1003. if (I == Current)
  1004. break;
  1005. Current = I;
  1006. ++Column;
  1007. }
  1008. }
  1009. void Scanner::scanToNextToken() {
  1010. while (true) {
  1011. while (Current != End && (*Current == ' ' || *Current == '\t')) {
  1012. skip(1);
  1013. }
  1014. skipComment();
  1015. // Skip EOL.
  1016. StringRef::iterator i = skip_b_break(Current);
  1017. if (i == Current)
  1018. break;
  1019. Current = i;
  1020. ++Line;
  1021. Column = 0;
  1022. // New lines may start a simple key.
  1023. if (!FlowLevel)
  1024. IsSimpleKeyAllowed = true;
  1025. }
  1026. }
  1027. bool Scanner::scanStreamStart() {
  1028. IsStartOfStream = false;
  1029. EncodingInfo EI = getUnicodeEncoding(currentInput());
  1030. Token T;
  1031. T.Kind = Token::TK_StreamStart;
  1032. T.Range = StringRef(Current, EI.second);
  1033. TokenQueue.push_back(T);
  1034. Current += EI.second;
  1035. return true;
  1036. }
  1037. bool Scanner::scanStreamEnd() {
  1038. // Force an ending new line if one isn't present.
  1039. if (Column != 0) {
  1040. Column = 0;
  1041. ++Line;
  1042. }
  1043. unrollIndent(-1);
  1044. SimpleKeys.clear();
  1045. IsSimpleKeyAllowed = false;
  1046. Token T;
  1047. T.Kind = Token::TK_StreamEnd;
  1048. T.Range = StringRef(Current, 0);
  1049. TokenQueue.push_back(T);
  1050. return true;
  1051. }
  1052. bool Scanner::scanDirective() {
  1053. // Reset the indentation level.
  1054. unrollIndent(-1);
  1055. SimpleKeys.clear();
  1056. IsSimpleKeyAllowed = false;
  1057. StringRef::iterator Start = Current;
  1058. consume('%');
  1059. StringRef::iterator NameStart = Current;
  1060. Current = skip_while(&Scanner::skip_ns_char, Current);
  1061. StringRef Name(NameStart, Current - NameStart);
  1062. Current = skip_while(&Scanner::skip_s_white, Current);
  1063. Token T;
  1064. if (Name == "YAML") {
  1065. Current = skip_while(&Scanner::skip_ns_char, Current);
  1066. T.Kind = Token::TK_VersionDirective;
  1067. T.Range = StringRef(Start, Current - Start);
  1068. TokenQueue.push_back(T);
  1069. return true;
  1070. } else if(Name == "TAG") {
  1071. Current = skip_while(&Scanner::skip_ns_char, Current);
  1072. Current = skip_while(&Scanner::skip_s_white, Current);
  1073. Current = skip_while(&Scanner::skip_ns_char, Current);
  1074. T.Kind = Token::TK_TagDirective;
  1075. T.Range = StringRef(Start, Current - Start);
  1076. TokenQueue.push_back(T);
  1077. return true;
  1078. }
  1079. return false;
  1080. }
  1081. bool Scanner::scanDocumentIndicator(bool IsStart) {
  1082. unrollIndent(-1);
  1083. SimpleKeys.clear();
  1084. IsSimpleKeyAllowed = false;
  1085. Token T;
  1086. T.Kind = IsStart ? Token::TK_DocumentStart : Token::TK_DocumentEnd;
  1087. T.Range = StringRef(Current, 3);
  1088. skip(3);
  1089. TokenQueue.push_back(T);
  1090. return true;
  1091. }
  1092. bool Scanner::scanFlowCollectionStart(bool IsSequence) {
  1093. Token T;
  1094. T.Kind = IsSequence ? Token::TK_FlowSequenceStart
  1095. : Token::TK_FlowMappingStart;
  1096. T.Range = StringRef(Current, 1);
  1097. skip(1);
  1098. TokenQueue.push_back(T);
  1099. // [ and { may begin a simple key.
  1100. saveSimpleKeyCandidate(--TokenQueue.end(), Column - 1, false);
  1101. // And may also be followed by a simple key.
  1102. IsSimpleKeyAllowed = true;
  1103. ++FlowLevel;
  1104. return true;
  1105. }
  1106. bool Scanner::scanFlowCollectionEnd(bool IsSequence) {
  1107. removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
  1108. IsSimpleKeyAllowed = false;
  1109. Token T;
  1110. T.Kind = IsSequence ? Token::TK_FlowSequenceEnd
  1111. : Token::TK_FlowMappingEnd;
  1112. T.Range = StringRef(Current, 1);
  1113. skip(1);
  1114. TokenQueue.push_back(T);
  1115. if (FlowLevel)
  1116. --FlowLevel;
  1117. return true;
  1118. }
  1119. bool Scanner::scanFlowEntry() {
  1120. removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
  1121. IsSimpleKeyAllowed = true;
  1122. Token T;
  1123. T.Kind = Token::TK_FlowEntry;
  1124. T.Range = StringRef(Current, 1);
  1125. skip(1);
  1126. TokenQueue.push_back(T);
  1127. return true;
  1128. }
  1129. bool Scanner::scanBlockEntry() {
  1130. rollIndent(Column, Token::TK_BlockSequenceStart, TokenQueue.end());
  1131. removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
  1132. IsSimpleKeyAllowed = true;
  1133. Token T;
  1134. T.Kind = Token::TK_BlockEntry;
  1135. T.Range = StringRef(Current, 1);
  1136. skip(1);
  1137. TokenQueue.push_back(T);
  1138. return true;
  1139. }
  1140. bool Scanner::scanKey() {
  1141. if (!FlowLevel)
  1142. rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
  1143. removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
  1144. IsSimpleKeyAllowed = !FlowLevel;
  1145. Token T;
  1146. T.Kind = Token::TK_Key;
  1147. T.Range = StringRef(Current, 1);
  1148. skip(1);
  1149. TokenQueue.push_back(T);
  1150. return true;
  1151. }
  1152. bool Scanner::scanValue() {
  1153. // If the previous token could have been a simple key, insert the key token
  1154. // into the token queue.
  1155. if (!SimpleKeys.empty()) {
  1156. SimpleKey SK = SimpleKeys.pop_back_val();
  1157. Token T;
  1158. T.Kind = Token::TK_Key;
  1159. T.Range = SK.Tok->Range;
  1160. TokenQueueT::iterator i, e;
  1161. for (i = TokenQueue.begin(), e = TokenQueue.end(); i != e; ++i) {
  1162. if (i == SK.Tok)
  1163. break;
  1164. }
  1165. if (i == e) {
  1166. Failed = true;
  1167. return false;
  1168. }
  1169. i = TokenQueue.insert(i, T);
  1170. // We may also need to add a Block-Mapping-Start token.
  1171. rollIndent(SK.Column, Token::TK_BlockMappingStart, i);
  1172. IsSimpleKeyAllowed = false;
  1173. } else {
  1174. if (!FlowLevel)
  1175. rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
  1176. IsSimpleKeyAllowed = !FlowLevel;
  1177. }
  1178. Token T;
  1179. T.Kind = Token::TK_Value;
  1180. T.Range = StringRef(Current, 1);
  1181. skip(1);
  1182. TokenQueue.push_back(T);
  1183. return true;
  1184. }
  1185. // Forbidding inlining improves performance by roughly 20%.
  1186. // FIXME: Remove once llvm optimizes this to the faster version without hints.
  1187. LLVM_ATTRIBUTE_NOINLINE static bool
  1188. wasEscaped(StringRef::iterator First, StringRef::iterator Position);
  1189. // Returns whether a character at 'Position' was escaped with a leading '\'.
  1190. // 'First' specifies the position of the first character in the string.
  1191. static bool wasEscaped(StringRef::iterator First,
  1192. StringRef::iterator Position) {
  1193. assert(Position - 1 >= First);
  1194. StringRef::iterator I = Position - 1;
  1195. // We calculate the number of consecutive '\'s before the current position
  1196. // by iterating backwards through our string.
  1197. while (I >= First && *I == '\\') --I;
  1198. // (Position - 1 - I) now contains the number of '\'s before the current
  1199. // position. If it is odd, the character at 'Position' was escaped.
  1200. return (Position - 1 - I) % 2 == 1;
  1201. }
  1202. bool Scanner::scanFlowScalar(bool IsDoubleQuoted) {
  1203. StringRef::iterator Start = Current;
  1204. unsigned ColStart = Column;
  1205. if (IsDoubleQuoted) {
  1206. do {
  1207. ++Current;
  1208. while (Current != End && *Current != '"')
  1209. ++Current;
  1210. // Repeat until the previous character was not a '\' or was an escaped
  1211. // backslash.
  1212. } while ( Current != End
  1213. && *(Current - 1) == '\\'
  1214. && wasEscaped(Start + 1, Current));
  1215. } else {
  1216. skip(1);
  1217. while (Current != End) {
  1218. // Skip a ' followed by another '.
  1219. if (Current + 1 < End && *Current == '\'' && *(Current + 1) == '\'') {
  1220. skip(2);
  1221. continue;
  1222. } else if (*Current == '\'')
  1223. break;
  1224. StringRef::iterator i = skip_nb_char(Current);
  1225. if (i == Current) {
  1226. i = skip_b_break(Current);
  1227. if (i == Current)
  1228. break;
  1229. Current = i;
  1230. Column = 0;
  1231. ++Line;
  1232. } else {
  1233. if (i == End)
  1234. break;
  1235. Current = i;
  1236. ++Column;
  1237. }
  1238. }
  1239. }
  1240. if (Current == End) {
  1241. setError("Expected quote at end of scalar", Current);
  1242. return false;
  1243. }
  1244. skip(1); // Skip ending quote.
  1245. Token T;
  1246. T.Kind = Token::TK_Scalar;
  1247. T.Range = StringRef(Start, Current - Start);
  1248. TokenQueue.push_back(T);
  1249. saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
  1250. IsSimpleKeyAllowed = false;
  1251. return true;
  1252. }
  1253. bool Scanner::scanPlainScalar() {
  1254. StringRef::iterator Start = Current;
  1255. unsigned ColStart = Column;
  1256. unsigned LeadingBlanks = 0;
  1257. assert(Indent >= -1 && "Indent must be >= -1 !");
  1258. unsigned indent = static_cast<unsigned>(Indent + 1);
  1259. while (Current != End) {
  1260. if (*Current == '#')
  1261. break;
  1262. while (Current != End && !isBlankOrBreak(Current)) {
  1263. if (FlowLevel && *Current == ':' &&
  1264. (Current + 1 == End ||
  1265. !(isBlankOrBreak(Current + 1) || *(Current + 1) == ','))) {
  1266. setError("Found unexpected ':' while scanning a plain scalar", Current);
  1267. return false;
  1268. }
  1269. // Check for the end of the plain scalar.
  1270. if ( (*Current == ':' && isBlankOrBreak(Current + 1))
  1271. || ( FlowLevel
  1272. && (StringRef(Current, 1).find_first_of(",:?[]{}")
  1273. != StringRef::npos)))
  1274. break;
  1275. StringRef::iterator i = skip_nb_char(Current);
  1276. if (i == Current)
  1277. break;
  1278. Current = i;
  1279. ++Column;
  1280. }
  1281. // Are we at the end?
  1282. if (!isBlankOrBreak(Current))
  1283. break;
  1284. // Eat blanks.
  1285. StringRef::iterator Tmp = Current;
  1286. while (isBlankOrBreak(Tmp)) {
  1287. StringRef::iterator i = skip_s_white(Tmp);
  1288. if (i != Tmp) {
  1289. if (LeadingBlanks && (Column < indent) && *Tmp == '\t') {
  1290. setError("Found invalid tab character in indentation", Tmp);
  1291. return false;
  1292. }
  1293. Tmp = i;
  1294. ++Column;
  1295. } else {
  1296. i = skip_b_break(Tmp);
  1297. if (!LeadingBlanks)
  1298. LeadingBlanks = 1;
  1299. Tmp = i;
  1300. Column = 0;
  1301. ++Line;
  1302. }
  1303. }
  1304. if (!FlowLevel && Column < indent)
  1305. break;
  1306. Current = Tmp;
  1307. }
  1308. if (Start == Current) {
  1309. setError("Got empty plain scalar", Start);
  1310. return false;
  1311. }
  1312. Token T;
  1313. T.Kind = Token::TK_Scalar;
  1314. T.Range = StringRef(Start, Current - Start);
  1315. TokenQueue.push_back(T);
  1316. // Plain scalars can be simple keys.
  1317. saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
  1318. IsSimpleKeyAllowed = false;
  1319. return true;
  1320. }
  1321. bool Scanner::scanAliasOrAnchor(bool IsAlias) {
  1322. StringRef::iterator Start = Current;
  1323. unsigned ColStart = Column;
  1324. skip(1);
  1325. while (Current != End) {
  1326. if ( *Current == '[' || *Current == ']'
  1327. || *Current == '{' || *Current == '}'
  1328. || *Current == ','
  1329. || *Current == ':')
  1330. break;
  1331. StringRef::iterator i = skip_ns_char(Current);
  1332. if (i == Current)
  1333. break;
  1334. Current = i;
  1335. ++Column;
  1336. }
  1337. if (Start + 1 == Current) {
  1338. setError("Got empty alias or anchor", Start);
  1339. return false;
  1340. }
  1341. Token T;
  1342. T.Kind = IsAlias ? Token::TK_Alias : Token::TK_Anchor;
  1343. T.Range = StringRef(Start, Current - Start);
  1344. TokenQueue.push_back(T);
  1345. // Alias and anchors can be simple keys.
  1346. saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
  1347. IsSimpleKeyAllowed = false;
  1348. return true;
  1349. }
  1350. bool Scanner::scanBlockScalarIndicators(char &StyleIndicator,
  1351. char &ChompingIndicator,
  1352. unsigned &IndentIndicator,
  1353. bool &IsDone) {
  1354. StyleIndicator = scanBlockStyleIndicator();
  1355. if (!scanBlockScalarHeader(ChompingIndicator, IndentIndicator, IsDone))
  1356. return false;
  1357. return true;
  1358. }
  1359. char Scanner::scanBlockStyleIndicator() {
  1360. char Indicator = ' ';
  1361. if (Current != End && (*Current == '>' || *Current == '|')) {
  1362. Indicator = *Current;
  1363. skip(1);
  1364. }
  1365. return Indicator;
  1366. }
  1367. char Scanner::scanBlockChompingIndicator() {
  1368. char Indicator = ' ';
  1369. if (Current != End && (*Current == '+' || *Current == '-')) {
  1370. Indicator = *Current;
  1371. skip(1);
  1372. }
  1373. return Indicator;
  1374. }
  1375. /// Get the number of line breaks after chomping.
  1376. ///
  1377. /// Return the number of trailing line breaks to emit, depending on
  1378. /// \p ChompingIndicator.
  1379. static unsigned getChompedLineBreaks(char ChompingIndicator,
  1380. unsigned LineBreaks, StringRef Str) {
  1381. if (ChompingIndicator == '-') // Strip all line breaks.
  1382. return 0;
  1383. if (ChompingIndicator == '+') // Keep all line breaks.
  1384. return LineBreaks;
  1385. // Clip trailing lines.
  1386. return Str.empty() ? 0 : 1;
  1387. }
  1388. unsigned Scanner::scanBlockIndentationIndicator() {
  1389. unsigned Indent = 0;
  1390. if (Current != End && (*Current >= '1' && *Current <= '9')) {
  1391. Indent = unsigned(*Current - '0');
  1392. skip(1);
  1393. }
  1394. return Indent;
  1395. }
  1396. bool Scanner::scanBlockScalarHeader(char &ChompingIndicator,
  1397. unsigned &IndentIndicator, bool &IsDone) {
  1398. auto Start = Current;
  1399. ChompingIndicator = scanBlockChompingIndicator();
  1400. IndentIndicator = scanBlockIndentationIndicator();
  1401. // Check for the chomping indicator once again.
  1402. if (ChompingIndicator == ' ')
  1403. ChompingIndicator = scanBlockChompingIndicator();
  1404. Current = skip_while(&Scanner::skip_s_white, Current);
  1405. skipComment();
  1406. if (Current == End) { // EOF, we have an empty scalar.
  1407. Token T;
  1408. T.Kind = Token::TK_BlockScalar;
  1409. T.Range = StringRef(Start, Current - Start);
  1410. TokenQueue.push_back(T);
  1411. IsDone = true;
  1412. return true;
  1413. }
  1414. if (!consumeLineBreakIfPresent()) {
  1415. setError("Expected a line break after block scalar header", Current);
  1416. return false;
  1417. }
  1418. return true;
  1419. }
  1420. bool Scanner::findBlockScalarIndent(unsigned &BlockIndent,
  1421. unsigned BlockExitIndent,
  1422. unsigned &LineBreaks, bool &IsDone) {
  1423. unsigned MaxAllSpaceLineCharacters = 0;
  1424. StringRef::iterator LongestAllSpaceLine;
  1425. while (true) {
  1426. advanceWhile(&Scanner::skip_s_space);
  1427. if (skip_nb_char(Current) != Current) {
  1428. // This line isn't empty, so try and find the indentation.
  1429. if (Column <= BlockExitIndent) { // End of the block literal.
  1430. IsDone = true;
  1431. return true;
  1432. }
  1433. // We found the block's indentation.
  1434. BlockIndent = Column;
  1435. if (MaxAllSpaceLineCharacters > BlockIndent) {
  1436. setError(
  1437. "Leading all-spaces line must be smaller than the block indent",
  1438. LongestAllSpaceLine);
  1439. return false;
  1440. }
  1441. return true;
  1442. }
  1443. if (skip_b_break(Current) != Current &&
  1444. Column > MaxAllSpaceLineCharacters) {
  1445. // Record the longest all-space line in case it's longer than the
  1446. // discovered block indent.
  1447. MaxAllSpaceLineCharacters = Column;
  1448. LongestAllSpaceLine = Current;
  1449. }
  1450. // Check for EOF.
  1451. if (Current == End) {
  1452. IsDone = true;
  1453. return true;
  1454. }
  1455. if (!consumeLineBreakIfPresent()) {
  1456. IsDone = true;
  1457. return true;
  1458. }
  1459. ++LineBreaks;
  1460. }
  1461. return true;
  1462. }
  1463. bool Scanner::scanBlockScalarIndent(unsigned BlockIndent,
  1464. unsigned BlockExitIndent, bool &IsDone) {
  1465. // Skip the indentation.
  1466. while (Column < BlockIndent) {
  1467. auto I = skip_s_space(Current);
  1468. if (I == Current)
  1469. break;
  1470. Current = I;
  1471. ++Column;
  1472. }
  1473. if (skip_nb_char(Current) == Current)
  1474. return true;
  1475. if (Column <= BlockExitIndent) { // End of the block literal.
  1476. IsDone = true;
  1477. return true;
  1478. }
  1479. if (Column < BlockIndent) {
  1480. if (Current != End && *Current == '#') { // Trailing comment.
  1481. IsDone = true;
  1482. return true;
  1483. }
  1484. setError("A text line is less indented than the block scalar", Current);
  1485. return false;
  1486. }
  1487. return true; // A normal text line.
  1488. }
  1489. bool Scanner::scanBlockScalar(bool IsLiteral) {
  1490. assert(*Current == '|' || *Current == '>');
  1491. char StyleIndicator;
  1492. char ChompingIndicator;
  1493. unsigned BlockIndent;
  1494. bool IsDone = false;
  1495. if (!scanBlockScalarIndicators(StyleIndicator, ChompingIndicator, BlockIndent,
  1496. IsDone))
  1497. return false;
  1498. if (IsDone)
  1499. return true;
  1500. bool IsFolded = StyleIndicator == '>';
  1501. const auto *Start = Current;
  1502. unsigned BlockExitIndent = Indent < 0 ? 0 : (unsigned)Indent;
  1503. unsigned LineBreaks = 0;
  1504. if (BlockIndent == 0) {
  1505. if (!findBlockScalarIndent(BlockIndent, BlockExitIndent, LineBreaks,
  1506. IsDone))
  1507. return false;
  1508. }
  1509. // Scan the block's scalars body.
  1510. SmallString<256> Str;
  1511. while (!IsDone) {
  1512. if (!scanBlockScalarIndent(BlockIndent, BlockExitIndent, IsDone))
  1513. return false;
  1514. if (IsDone)
  1515. break;
  1516. // Parse the current line.
  1517. auto LineStart = Current;
  1518. advanceWhile(&Scanner::skip_nb_char);
  1519. if (LineStart != Current) {
  1520. if (LineBreaks && IsFolded && !Scanner::isLineEmpty(Str)) {
  1521. // The folded style "folds" any single line break between content into a
  1522. // single space, except when that content is "empty" (only contains
  1523. // whitespace) in which case the line break is left as-is.
  1524. if (LineBreaks == 1) {
  1525. Str.append(LineBreaks,
  1526. isLineEmpty(StringRef(LineStart, Current - LineStart))
  1527. ? '\n'
  1528. : ' ');
  1529. }
  1530. // If we saw a single line break, we are completely replacing it and so
  1531. // want `LineBreaks == 0`. Otherwise this decrement accounts for the
  1532. // fact that the first line break is "trimmed", only being used to
  1533. // signal a sequence of line breaks which should not be folded.
  1534. LineBreaks--;
  1535. }
  1536. Str.append(LineBreaks, '\n');
  1537. Str.append(StringRef(LineStart, Current - LineStart));
  1538. LineBreaks = 0;
  1539. }
  1540. // Check for EOF.
  1541. if (Current == End)
  1542. break;
  1543. if (!consumeLineBreakIfPresent())
  1544. break;
  1545. ++LineBreaks;
  1546. }
  1547. if (Current == End && !LineBreaks)
  1548. // Ensure that there is at least one line break before the end of file.
  1549. LineBreaks = 1;
  1550. Str.append(getChompedLineBreaks(ChompingIndicator, LineBreaks, Str), '\n');
  1551. // New lines may start a simple key.
  1552. if (!FlowLevel)
  1553. IsSimpleKeyAllowed = true;
  1554. Token T;
  1555. T.Kind = Token::TK_BlockScalar;
  1556. T.Range = StringRef(Start, Current - Start);
  1557. T.Value = std::string(Str);
  1558. TokenQueue.push_back(T);
  1559. return true;
  1560. }
  1561. bool Scanner::scanTag() {
  1562. StringRef::iterator Start = Current;
  1563. unsigned ColStart = Column;
  1564. skip(1); // Eat !.
  1565. if (Current == End || isBlankOrBreak(Current)); // An empty tag.
  1566. else if (*Current == '<') {
  1567. skip(1);
  1568. scan_ns_uri_char();
  1569. if (!consume('>'))
  1570. return false;
  1571. } else {
  1572. // FIXME: Actually parse the c-ns-shorthand-tag rule.
  1573. Current = skip_while(&Scanner::skip_ns_char, Current);
  1574. }
  1575. Token T;
  1576. T.Kind = Token::TK_Tag;
  1577. T.Range = StringRef(Start, Current - Start);
  1578. TokenQueue.push_back(T);
  1579. // Tags can be simple keys.
  1580. saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
  1581. IsSimpleKeyAllowed = false;
  1582. return true;
  1583. }
  1584. bool Scanner::fetchMoreTokens() {
  1585. if (IsStartOfStream)
  1586. return scanStreamStart();
  1587. scanToNextToken();
  1588. if (Current == End)
  1589. return scanStreamEnd();
  1590. removeStaleSimpleKeyCandidates();
  1591. unrollIndent(Column);
  1592. if (Column == 0 && *Current == '%')
  1593. return scanDirective();
  1594. if (Column == 0 && Current + 4 <= End
  1595. && *Current == '-'
  1596. && *(Current + 1) == '-'
  1597. && *(Current + 2) == '-'
  1598. && (Current + 3 == End || isBlankOrBreak(Current + 3)))
  1599. return scanDocumentIndicator(true);
  1600. if (Column == 0 && Current + 4 <= End
  1601. && *Current == '.'
  1602. && *(Current + 1) == '.'
  1603. && *(Current + 2) == '.'
  1604. && (Current + 3 == End || isBlankOrBreak(Current + 3)))
  1605. return scanDocumentIndicator(false);
  1606. if (*Current == '[')
  1607. return scanFlowCollectionStart(true);
  1608. if (*Current == '{')
  1609. return scanFlowCollectionStart(false);
  1610. if (*Current == ']')
  1611. return scanFlowCollectionEnd(true);
  1612. if (*Current == '}')
  1613. return scanFlowCollectionEnd(false);
  1614. if (*Current == ',')
  1615. return scanFlowEntry();
  1616. if (*Current == '-' && isBlankOrBreak(Current + 1))
  1617. return scanBlockEntry();
  1618. if (*Current == '?' && (FlowLevel || isBlankOrBreak(Current + 1)))
  1619. return scanKey();
  1620. if (*Current == ':' && (FlowLevel || isBlankOrBreak(Current + 1)))
  1621. return scanValue();
  1622. if (*Current == '*')
  1623. return scanAliasOrAnchor(true);
  1624. if (*Current == '&')
  1625. return scanAliasOrAnchor(false);
  1626. if (*Current == '!')
  1627. return scanTag();
  1628. if (*Current == '|' && !FlowLevel)
  1629. return scanBlockScalar(true);
  1630. if (*Current == '>' && !FlowLevel)
  1631. return scanBlockScalar(false);
  1632. if (*Current == '\'')
  1633. return scanFlowScalar(false);
  1634. if (*Current == '"')
  1635. return scanFlowScalar(true);
  1636. // Get a plain scalar.
  1637. StringRef FirstChar(Current, 1);
  1638. if (!(isBlankOrBreak(Current)
  1639. || FirstChar.find_first_of("-?:,[]{}#&*!|>'\"%@`") != StringRef::npos)
  1640. || (*Current == '-' && !isBlankOrBreak(Current + 1))
  1641. || (!FlowLevel && (*Current == '?' || *Current == ':')
  1642. && isBlankOrBreak(Current + 1))
  1643. || (!FlowLevel && *Current == ':'
  1644. && Current + 2 < End
  1645. && *(Current + 1) == ':'
  1646. && !isBlankOrBreak(Current + 2)))
  1647. return scanPlainScalar();
  1648. setError("Unrecognized character while tokenizing.", Current);
  1649. return false;
  1650. }
  1651. Stream::Stream(StringRef Input, SourceMgr &SM, bool ShowColors,
  1652. std::error_code *EC)
  1653. : scanner(new Scanner(Input, SM, ShowColors, EC)) {}
  1654. Stream::Stream(MemoryBufferRef InputBuffer, SourceMgr &SM, bool ShowColors,
  1655. std::error_code *EC)
  1656. : scanner(new Scanner(InputBuffer, SM, ShowColors, EC)) {}
  1657. Stream::~Stream() = default;
  1658. bool Stream::failed() { return scanner->failed(); }
  1659. void Stream::printError(Node *N, const Twine &Msg, SourceMgr::DiagKind Kind) {
  1660. printError(N ? N->getSourceRange() : SMRange(), Msg, Kind);
  1661. }
  1662. void Stream::printError(const SMRange &Range, const Twine &Msg,
  1663. SourceMgr::DiagKind Kind) {
  1664. scanner->printError(Range.Start, Kind, Msg, Range);
  1665. }
  1666. document_iterator Stream::begin() {
  1667. if (CurrentDoc)
  1668. report_fatal_error("Can only iterate over the stream once");
  1669. // Skip Stream-Start.
  1670. scanner->getNext();
  1671. CurrentDoc.reset(new Document(*this));
  1672. return document_iterator(CurrentDoc);
  1673. }
  1674. document_iterator Stream::end() {
  1675. return document_iterator();
  1676. }
  1677. void Stream::skip() {
  1678. for (Document &Doc : *this)
  1679. Doc.skip();
  1680. }
  1681. Node::Node(unsigned int Type, std::unique_ptr<Document> &D, StringRef A,
  1682. StringRef T)
  1683. : Doc(D), TypeID(Type), Anchor(A), Tag(T) {
  1684. SMLoc Start = SMLoc::getFromPointer(peekNext().Range.begin());
  1685. SourceRange = SMRange(Start, Start);
  1686. }
  1687. std::string Node::getVerbatimTag() const {
  1688. StringRef Raw = getRawTag();
  1689. if (!Raw.empty() && Raw != "!") {
  1690. std::string Ret;
  1691. if (Raw.find_last_of('!') == 0) {
  1692. Ret = std::string(Doc->getTagMap().find("!")->second);
  1693. Ret += Raw.substr(1);
  1694. return Ret;
  1695. } else if (Raw.startswith("!!")) {
  1696. Ret = std::string(Doc->getTagMap().find("!!")->second);
  1697. Ret += Raw.substr(2);
  1698. return Ret;
  1699. } else {
  1700. StringRef TagHandle = Raw.substr(0, Raw.find_last_of('!') + 1);
  1701. std::map<StringRef, StringRef>::const_iterator It =
  1702. Doc->getTagMap().find(TagHandle);
  1703. if (It != Doc->getTagMap().end())
  1704. Ret = std::string(It->second);
  1705. else {
  1706. Token T;
  1707. T.Kind = Token::TK_Tag;
  1708. T.Range = TagHandle;
  1709. setError(Twine("Unknown tag handle ") + TagHandle, T);
  1710. }
  1711. Ret += Raw.substr(Raw.find_last_of('!') + 1);
  1712. return Ret;
  1713. }
  1714. }
  1715. switch (getType()) {
  1716. case NK_Null:
  1717. return "tag:yaml.org,2002:null";
  1718. case NK_Scalar:
  1719. case NK_BlockScalar:
  1720. // TODO: Tag resolution.
  1721. return "tag:yaml.org,2002:str";
  1722. case NK_Mapping:
  1723. return "tag:yaml.org,2002:map";
  1724. case NK_Sequence:
  1725. return "tag:yaml.org,2002:seq";
  1726. }
  1727. return "";
  1728. }
  1729. Token &Node::peekNext() {
  1730. return Doc->peekNext();
  1731. }
  1732. Token Node::getNext() {
  1733. return Doc->getNext();
  1734. }
  1735. Node *Node::parseBlockNode() {
  1736. return Doc->parseBlockNode();
  1737. }
  1738. BumpPtrAllocator &Node::getAllocator() {
  1739. return Doc->NodeAllocator;
  1740. }
  1741. void Node::setError(const Twine &Msg, Token &Tok) const {
  1742. Doc->setError(Msg, Tok);
  1743. }
  1744. bool Node::failed() const {
  1745. return Doc->failed();
  1746. }
  1747. StringRef ScalarNode::getValue(SmallVectorImpl<char> &Storage) const {
  1748. // TODO: Handle newlines properly. We need to remove leading whitespace.
  1749. if (Value[0] == '"') { // Double quoted.
  1750. // Pull off the leading and trailing "s.
  1751. StringRef UnquotedValue = Value.substr(1, Value.size() - 2);
  1752. // Search for characters that would require unescaping the value.
  1753. StringRef::size_type i = UnquotedValue.find_first_of("\\\r\n");
  1754. if (i != StringRef::npos)
  1755. return unescapeDoubleQuoted(UnquotedValue, i, Storage);
  1756. return UnquotedValue;
  1757. } else if (Value[0] == '\'') { // Single quoted.
  1758. // Pull off the leading and trailing 's.
  1759. StringRef UnquotedValue = Value.substr(1, Value.size() - 2);
  1760. StringRef::size_type i = UnquotedValue.find('\'');
  1761. if (i != StringRef::npos) {
  1762. // We're going to need Storage.
  1763. Storage.clear();
  1764. Storage.reserve(UnquotedValue.size());
  1765. for (; i != StringRef::npos; i = UnquotedValue.find('\'')) {
  1766. StringRef Valid(UnquotedValue.begin(), i);
  1767. llvm::append_range(Storage, Valid);
  1768. Storage.push_back('\'');
  1769. UnquotedValue = UnquotedValue.substr(i + 2);
  1770. }
  1771. llvm::append_range(Storage, UnquotedValue);
  1772. return StringRef(Storage.begin(), Storage.size());
  1773. }
  1774. return UnquotedValue;
  1775. }
  1776. // Plain or block.
  1777. return Value.rtrim(' ');
  1778. }
  1779. StringRef ScalarNode::unescapeDoubleQuoted( StringRef UnquotedValue
  1780. , StringRef::size_type i
  1781. , SmallVectorImpl<char> &Storage)
  1782. const {
  1783. // Use Storage to build proper value.
  1784. Storage.clear();
  1785. Storage.reserve(UnquotedValue.size());
  1786. for (; i != StringRef::npos; i = UnquotedValue.find_first_of("\\\r\n")) {
  1787. // Insert all previous chars into Storage.
  1788. StringRef Valid(UnquotedValue.begin(), i);
  1789. llvm::append_range(Storage, Valid);
  1790. // Chop off inserted chars.
  1791. UnquotedValue = UnquotedValue.substr(i);
  1792. assert(!UnquotedValue.empty() && "Can't be empty!");
  1793. // Parse escape or line break.
  1794. switch (UnquotedValue[0]) {
  1795. case '\r':
  1796. case '\n':
  1797. Storage.push_back('\n');
  1798. if ( UnquotedValue.size() > 1
  1799. && (UnquotedValue[1] == '\r' || UnquotedValue[1] == '\n'))
  1800. UnquotedValue = UnquotedValue.substr(1);
  1801. UnquotedValue = UnquotedValue.substr(1);
  1802. break;
  1803. default:
  1804. if (UnquotedValue.size() == 1) {
  1805. Token T;
  1806. T.Range = StringRef(UnquotedValue.begin(), 1);
  1807. setError("Unrecognized escape code", T);
  1808. return "";
  1809. }
  1810. UnquotedValue = UnquotedValue.substr(1);
  1811. switch (UnquotedValue[0]) {
  1812. default: {
  1813. Token T;
  1814. T.Range = StringRef(UnquotedValue.begin(), 1);
  1815. setError("Unrecognized escape code", T);
  1816. return "";
  1817. }
  1818. case '\r':
  1819. case '\n':
  1820. // Remove the new line.
  1821. if ( UnquotedValue.size() > 1
  1822. && (UnquotedValue[1] == '\r' || UnquotedValue[1] == '\n'))
  1823. UnquotedValue = UnquotedValue.substr(1);
  1824. // If this was just a single byte newline, it will get skipped
  1825. // below.
  1826. break;
  1827. case '0':
  1828. Storage.push_back(0x00);
  1829. break;
  1830. case 'a':
  1831. Storage.push_back(0x07);
  1832. break;
  1833. case 'b':
  1834. Storage.push_back(0x08);
  1835. break;
  1836. case 't':
  1837. case 0x09:
  1838. Storage.push_back(0x09);
  1839. break;
  1840. case 'n':
  1841. Storage.push_back(0x0A);
  1842. break;
  1843. case 'v':
  1844. Storage.push_back(0x0B);
  1845. break;
  1846. case 'f':
  1847. Storage.push_back(0x0C);
  1848. break;
  1849. case 'r':
  1850. Storage.push_back(0x0D);
  1851. break;
  1852. case 'e':
  1853. Storage.push_back(0x1B);
  1854. break;
  1855. case ' ':
  1856. Storage.push_back(0x20);
  1857. break;
  1858. case '"':
  1859. Storage.push_back(0x22);
  1860. break;
  1861. case '/':
  1862. Storage.push_back(0x2F);
  1863. break;
  1864. case '\\':
  1865. Storage.push_back(0x5C);
  1866. break;
  1867. case 'N':
  1868. encodeUTF8(0x85, Storage);
  1869. break;
  1870. case '_':
  1871. encodeUTF8(0xA0, Storage);
  1872. break;
  1873. case 'L':
  1874. encodeUTF8(0x2028, Storage);
  1875. break;
  1876. case 'P':
  1877. encodeUTF8(0x2029, Storage);
  1878. break;
  1879. case 'x': {
  1880. if (UnquotedValue.size() < 3)
  1881. // TODO: Report error.
  1882. break;
  1883. unsigned int UnicodeScalarValue;
  1884. if (UnquotedValue.substr(1, 2).getAsInteger(16, UnicodeScalarValue))
  1885. // TODO: Report error.
  1886. UnicodeScalarValue = 0xFFFD;
  1887. encodeUTF8(UnicodeScalarValue, Storage);
  1888. UnquotedValue = UnquotedValue.substr(2);
  1889. break;
  1890. }
  1891. case 'u': {
  1892. if (UnquotedValue.size() < 5)
  1893. // TODO: Report error.
  1894. break;
  1895. unsigned int UnicodeScalarValue;
  1896. if (UnquotedValue.substr(1, 4).getAsInteger(16, UnicodeScalarValue))
  1897. // TODO: Report error.
  1898. UnicodeScalarValue = 0xFFFD;
  1899. encodeUTF8(UnicodeScalarValue, Storage);
  1900. UnquotedValue = UnquotedValue.substr(4);
  1901. break;
  1902. }
  1903. case 'U': {
  1904. if (UnquotedValue.size() < 9)
  1905. // TODO: Report error.
  1906. break;
  1907. unsigned int UnicodeScalarValue;
  1908. if (UnquotedValue.substr(1, 8).getAsInteger(16, UnicodeScalarValue))
  1909. // TODO: Report error.
  1910. UnicodeScalarValue = 0xFFFD;
  1911. encodeUTF8(UnicodeScalarValue, Storage);
  1912. UnquotedValue = UnquotedValue.substr(8);
  1913. break;
  1914. }
  1915. }
  1916. UnquotedValue = UnquotedValue.substr(1);
  1917. }
  1918. }
  1919. llvm::append_range(Storage, UnquotedValue);
  1920. return StringRef(Storage.begin(), Storage.size());
  1921. }
  1922. Node *KeyValueNode::getKey() {
  1923. if (Key)
  1924. return Key;
  1925. // Handle implicit null keys.
  1926. {
  1927. Token &t = peekNext();
  1928. if ( t.Kind == Token::TK_BlockEnd
  1929. || t.Kind == Token::TK_Value
  1930. || t.Kind == Token::TK_Error) {
  1931. return Key = new (getAllocator()) NullNode(Doc);
  1932. }
  1933. if (t.Kind == Token::TK_Key)
  1934. getNext(); // skip TK_Key.
  1935. }
  1936. // Handle explicit null keys.
  1937. Token &t = peekNext();
  1938. if (t.Kind == Token::TK_BlockEnd || t.Kind == Token::TK_Value) {
  1939. return Key = new (getAllocator()) NullNode(Doc);
  1940. }
  1941. // We've got a normal key.
  1942. return Key = parseBlockNode();
  1943. }
  1944. Node *KeyValueNode::getValue() {
  1945. if (Value)
  1946. return Value;
  1947. if (Node* Key = getKey())
  1948. Key->skip();
  1949. else {
  1950. setError("Null key in Key Value.", peekNext());
  1951. return Value = new (getAllocator()) NullNode(Doc);
  1952. }
  1953. if (failed())
  1954. return Value = new (getAllocator()) NullNode(Doc);
  1955. // Handle implicit null values.
  1956. {
  1957. Token &t = peekNext();
  1958. if ( t.Kind == Token::TK_BlockEnd
  1959. || t.Kind == Token::TK_FlowMappingEnd
  1960. || t.Kind == Token::TK_Key
  1961. || t.Kind == Token::TK_FlowEntry
  1962. || t.Kind == Token::TK_Error) {
  1963. return Value = new (getAllocator()) NullNode(Doc);
  1964. }
  1965. if (t.Kind != Token::TK_Value) {
  1966. setError("Unexpected token in Key Value.", t);
  1967. return Value = new (getAllocator()) NullNode(Doc);
  1968. }
  1969. getNext(); // skip TK_Value.
  1970. }
  1971. // Handle explicit null values.
  1972. Token &t = peekNext();
  1973. if (t.Kind == Token::TK_BlockEnd || t.Kind == Token::TK_Key) {
  1974. return Value = new (getAllocator()) NullNode(Doc);
  1975. }
  1976. // We got a normal value.
  1977. return Value = parseBlockNode();
  1978. }
  1979. void MappingNode::increment() {
  1980. if (failed()) {
  1981. IsAtEnd = true;
  1982. CurrentEntry = nullptr;
  1983. return;
  1984. }
  1985. if (CurrentEntry) {
  1986. CurrentEntry->skip();
  1987. if (Type == MT_Inline) {
  1988. IsAtEnd = true;
  1989. CurrentEntry = nullptr;
  1990. return;
  1991. }
  1992. }
  1993. Token T = peekNext();
  1994. if (T.Kind == Token::TK_Key || T.Kind == Token::TK_Scalar) {
  1995. // KeyValueNode eats the TK_Key. That way it can detect null keys.
  1996. CurrentEntry = new (getAllocator()) KeyValueNode(Doc);
  1997. } else if (Type == MT_Block) {
  1998. switch (T.Kind) {
  1999. case Token::TK_BlockEnd:
  2000. getNext();
  2001. IsAtEnd = true;
  2002. CurrentEntry = nullptr;
  2003. break;
  2004. default:
  2005. setError("Unexpected token. Expected Key or Block End", T);
  2006. [[fallthrough]];
  2007. case Token::TK_Error:
  2008. IsAtEnd = true;
  2009. CurrentEntry = nullptr;
  2010. }
  2011. } else {
  2012. switch (T.Kind) {
  2013. case Token::TK_FlowEntry:
  2014. // Eat the flow entry and recurse.
  2015. getNext();
  2016. return increment();
  2017. case Token::TK_FlowMappingEnd:
  2018. getNext();
  2019. [[fallthrough]];
  2020. case Token::TK_Error:
  2021. // Set this to end iterator.
  2022. IsAtEnd = true;
  2023. CurrentEntry = nullptr;
  2024. break;
  2025. default:
  2026. setError( "Unexpected token. Expected Key, Flow Entry, or Flow "
  2027. "Mapping End."
  2028. , T);
  2029. IsAtEnd = true;
  2030. CurrentEntry = nullptr;
  2031. }
  2032. }
  2033. }
  2034. void SequenceNode::increment() {
  2035. if (failed()) {
  2036. IsAtEnd = true;
  2037. CurrentEntry = nullptr;
  2038. return;
  2039. }
  2040. if (CurrentEntry)
  2041. CurrentEntry->skip();
  2042. Token T = peekNext();
  2043. if (SeqType == ST_Block) {
  2044. switch (T.Kind) {
  2045. case Token::TK_BlockEntry:
  2046. getNext();
  2047. CurrentEntry = parseBlockNode();
  2048. if (!CurrentEntry) { // An error occurred.
  2049. IsAtEnd = true;
  2050. CurrentEntry = nullptr;
  2051. }
  2052. break;
  2053. case Token::TK_BlockEnd:
  2054. getNext();
  2055. IsAtEnd = true;
  2056. CurrentEntry = nullptr;
  2057. break;
  2058. default:
  2059. setError( "Unexpected token. Expected Block Entry or Block End."
  2060. , T);
  2061. [[fallthrough]];
  2062. case Token::TK_Error:
  2063. IsAtEnd = true;
  2064. CurrentEntry = nullptr;
  2065. }
  2066. } else if (SeqType == ST_Indentless) {
  2067. switch (T.Kind) {
  2068. case Token::TK_BlockEntry:
  2069. getNext();
  2070. CurrentEntry = parseBlockNode();
  2071. if (!CurrentEntry) { // An error occurred.
  2072. IsAtEnd = true;
  2073. CurrentEntry = nullptr;
  2074. }
  2075. break;
  2076. default:
  2077. case Token::TK_Error:
  2078. IsAtEnd = true;
  2079. CurrentEntry = nullptr;
  2080. }
  2081. } else if (SeqType == ST_Flow) {
  2082. switch (T.Kind) {
  2083. case Token::TK_FlowEntry:
  2084. // Eat the flow entry and recurse.
  2085. getNext();
  2086. WasPreviousTokenFlowEntry = true;
  2087. return increment();
  2088. case Token::TK_FlowSequenceEnd:
  2089. getNext();
  2090. [[fallthrough]];
  2091. case Token::TK_Error:
  2092. // Set this to end iterator.
  2093. IsAtEnd = true;
  2094. CurrentEntry = nullptr;
  2095. break;
  2096. case Token::TK_StreamEnd:
  2097. case Token::TK_DocumentEnd:
  2098. case Token::TK_DocumentStart:
  2099. setError("Could not find closing ]!", T);
  2100. // Set this to end iterator.
  2101. IsAtEnd = true;
  2102. CurrentEntry = nullptr;
  2103. break;
  2104. default:
  2105. if (!WasPreviousTokenFlowEntry) {
  2106. setError("Expected , between entries!", T);
  2107. IsAtEnd = true;
  2108. CurrentEntry = nullptr;
  2109. break;
  2110. }
  2111. // Otherwise it must be a flow entry.
  2112. CurrentEntry = parseBlockNode();
  2113. if (!CurrentEntry) {
  2114. IsAtEnd = true;
  2115. }
  2116. WasPreviousTokenFlowEntry = false;
  2117. break;
  2118. }
  2119. }
  2120. }
  2121. Document::Document(Stream &S) : stream(S), Root(nullptr) {
  2122. // Tag maps starts with two default mappings.
  2123. TagMap["!"] = "!";
  2124. TagMap["!!"] = "tag:yaml.org,2002:";
  2125. if (parseDirectives())
  2126. expectToken(Token::TK_DocumentStart);
  2127. Token &T = peekNext();
  2128. if (T.Kind == Token::TK_DocumentStart)
  2129. getNext();
  2130. }
  2131. bool Document::skip() {
  2132. if (stream.scanner->failed())
  2133. return false;
  2134. if (!Root && !getRoot())
  2135. return false;
  2136. Root->skip();
  2137. Token &T = peekNext();
  2138. if (T.Kind == Token::TK_StreamEnd)
  2139. return false;
  2140. if (T.Kind == Token::TK_DocumentEnd) {
  2141. getNext();
  2142. return skip();
  2143. }
  2144. return true;
  2145. }
  2146. Token &Document::peekNext() {
  2147. return stream.scanner->peekNext();
  2148. }
  2149. Token Document::getNext() {
  2150. return stream.scanner->getNext();
  2151. }
  2152. void Document::setError(const Twine &Message, Token &Location) const {
  2153. stream.scanner->setError(Message, Location.Range.begin());
  2154. }
  2155. bool Document::failed() const {
  2156. return stream.scanner->failed();
  2157. }
  2158. Node *Document::parseBlockNode() {
  2159. Token T = peekNext();
  2160. // Handle properties.
  2161. Token AnchorInfo;
  2162. Token TagInfo;
  2163. parse_property:
  2164. switch (T.Kind) {
  2165. case Token::TK_Alias:
  2166. getNext();
  2167. return new (NodeAllocator) AliasNode(stream.CurrentDoc, T.Range.substr(1));
  2168. case Token::TK_Anchor:
  2169. if (AnchorInfo.Kind == Token::TK_Anchor) {
  2170. setError("Already encountered an anchor for this node!", T);
  2171. return nullptr;
  2172. }
  2173. AnchorInfo = getNext(); // Consume TK_Anchor.
  2174. T = peekNext();
  2175. goto parse_property;
  2176. case Token::TK_Tag:
  2177. if (TagInfo.Kind == Token::TK_Tag) {
  2178. setError("Already encountered a tag for this node!", T);
  2179. return nullptr;
  2180. }
  2181. TagInfo = getNext(); // Consume TK_Tag.
  2182. T = peekNext();
  2183. goto parse_property;
  2184. default:
  2185. break;
  2186. }
  2187. switch (T.Kind) {
  2188. case Token::TK_BlockEntry:
  2189. // We got an unindented BlockEntry sequence. This is not terminated with
  2190. // a BlockEnd.
  2191. // Don't eat the TK_BlockEntry, SequenceNode needs it.
  2192. return new (NodeAllocator) SequenceNode( stream.CurrentDoc
  2193. , AnchorInfo.Range.substr(1)
  2194. , TagInfo.Range
  2195. , SequenceNode::ST_Indentless);
  2196. case Token::TK_BlockSequenceStart:
  2197. getNext();
  2198. return new (NodeAllocator)
  2199. SequenceNode( stream.CurrentDoc
  2200. , AnchorInfo.Range.substr(1)
  2201. , TagInfo.Range
  2202. , SequenceNode::ST_Block);
  2203. case Token::TK_BlockMappingStart:
  2204. getNext();
  2205. return new (NodeAllocator)
  2206. MappingNode( stream.CurrentDoc
  2207. , AnchorInfo.Range.substr(1)
  2208. , TagInfo.Range
  2209. , MappingNode::MT_Block);
  2210. case Token::TK_FlowSequenceStart:
  2211. getNext();
  2212. return new (NodeAllocator)
  2213. SequenceNode( stream.CurrentDoc
  2214. , AnchorInfo.Range.substr(1)
  2215. , TagInfo.Range
  2216. , SequenceNode::ST_Flow);
  2217. case Token::TK_FlowMappingStart:
  2218. getNext();
  2219. return new (NodeAllocator)
  2220. MappingNode( stream.CurrentDoc
  2221. , AnchorInfo.Range.substr(1)
  2222. , TagInfo.Range
  2223. , MappingNode::MT_Flow);
  2224. case Token::TK_Scalar:
  2225. getNext();
  2226. return new (NodeAllocator)
  2227. ScalarNode( stream.CurrentDoc
  2228. , AnchorInfo.Range.substr(1)
  2229. , TagInfo.Range
  2230. , T.Range);
  2231. case Token::TK_BlockScalar: {
  2232. getNext();
  2233. StringRef NullTerminatedStr(T.Value.c_str(), T.Value.length() + 1);
  2234. StringRef StrCopy = NullTerminatedStr.copy(NodeAllocator).drop_back();
  2235. return new (NodeAllocator)
  2236. BlockScalarNode(stream.CurrentDoc, AnchorInfo.Range.substr(1),
  2237. TagInfo.Range, StrCopy, T.Range);
  2238. }
  2239. case Token::TK_Key:
  2240. // Don't eat the TK_Key, KeyValueNode expects it.
  2241. return new (NodeAllocator)
  2242. MappingNode( stream.CurrentDoc
  2243. , AnchorInfo.Range.substr(1)
  2244. , TagInfo.Range
  2245. , MappingNode::MT_Inline);
  2246. case Token::TK_DocumentStart:
  2247. case Token::TK_DocumentEnd:
  2248. case Token::TK_StreamEnd:
  2249. default:
  2250. // TODO: Properly handle tags. "[!!str ]" should resolve to !!str "", not
  2251. // !!null null.
  2252. return new (NodeAllocator) NullNode(stream.CurrentDoc);
  2253. case Token::TK_FlowMappingEnd:
  2254. case Token::TK_FlowSequenceEnd:
  2255. case Token::TK_FlowEntry: {
  2256. if (Root && (isa<MappingNode>(Root) || isa<SequenceNode>(Root)))
  2257. return new (NodeAllocator) NullNode(stream.CurrentDoc);
  2258. setError("Unexpected token", T);
  2259. return nullptr;
  2260. }
  2261. case Token::TK_Error:
  2262. return nullptr;
  2263. }
  2264. llvm_unreachable("Control flow shouldn't reach here.");
  2265. return nullptr;
  2266. }
  2267. bool Document::parseDirectives() {
  2268. bool isDirective = false;
  2269. while (true) {
  2270. Token T = peekNext();
  2271. if (T.Kind == Token::TK_TagDirective) {
  2272. parseTAGDirective();
  2273. isDirective = true;
  2274. } else if (T.Kind == Token::TK_VersionDirective) {
  2275. parseYAMLDirective();
  2276. isDirective = true;
  2277. } else
  2278. break;
  2279. }
  2280. return isDirective;
  2281. }
  2282. void Document::parseYAMLDirective() {
  2283. getNext(); // Eat %YAML <version>
  2284. }
  2285. void Document::parseTAGDirective() {
  2286. Token Tag = getNext(); // %TAG <handle> <prefix>
  2287. StringRef T = Tag.Range;
  2288. // Strip %TAG
  2289. T = T.substr(T.find_first_of(" \t")).ltrim(" \t");
  2290. std::size_t HandleEnd = T.find_first_of(" \t");
  2291. StringRef TagHandle = T.substr(0, HandleEnd);
  2292. StringRef TagPrefix = T.substr(HandleEnd).ltrim(" \t");
  2293. TagMap[TagHandle] = TagPrefix;
  2294. }
  2295. bool Document::expectToken(int TK) {
  2296. Token T = getNext();
  2297. if (T.Kind != TK) {
  2298. setError("Unexpected token", T);
  2299. return false;
  2300. }
  2301. return true;
  2302. }