YAMLParser.cpp 70 KB

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