xml_reader.odin 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. /*
  2. An XML 1.0 / 1.1 parser
  3. Copyright 2021-2022 Jeroen van Rijn <[email protected]>.
  4. Made available under Odin's BSD-3 license.
  5. A from-scratch XML implementation, loosely modelled on the [spec](https://www.w3.org/TR/2006/REC-xml11-20060816).
  6. Features:
  7. - Supports enough of the XML 1.0/1.1 spec to handle the 99.9% of XML documents in common current usage.
  8. - Simple to understand and use. Small.
  9. Caveats:
  10. - We do NOT support HTML in this package, as that may or may not be valid XML.
  11. If it works, great. If it doesn't, that's not considered a bug.
  12. - We do NOT support UTF-16. If you have a UTF-16 XML file, please convert it to UTF-8 first. Also, our condolences.
  13. - <[!ELEMENT and <[!ATTLIST are not supported, and will be either ignored or return an error depending on the parser options.
  14. MAYBE:
  15. - XML writer?
  16. - Serialize/deserialize Odin types?
  17. List of contributors:
  18. Jeroen van Rijn: Initial implementation.
  19. */
  20. package xml
  21. // An XML 1.0 / 1.1 parser
  22. import "core:bytes"
  23. import "core:encoding/entity"
  24. import "core:intrinsics"
  25. import "core:mem"
  26. import "core:os"
  27. import "core:strings"
  28. import "core:runtime"
  29. likely :: intrinsics.expect
  30. DEFAULT_OPTIONS :: Options{
  31. flags = {.Ignore_Unsupported},
  32. expected_doctype = "",
  33. }
  34. Option_Flag :: enum {
  35. /*
  36. If the caller says that input may be modified, we can perform in-situ parsing.
  37. If this flag isn't provided, the XML parser first duplicates the input so that it can.
  38. */
  39. Input_May_Be_Modified,
  40. /*
  41. Document MUST start with `<?xml` prologue.
  42. */
  43. Must_Have_Prolog,
  44. /*
  45. Document MUST have a `<!DOCTYPE`.
  46. */
  47. Must_Have_DocType,
  48. /*
  49. By default we skip comments. Use this option to intern a comment on a parented Element.
  50. */
  51. Intern_Comments,
  52. /*
  53. How to handle unsupported parts of the specification, like <! other than <!DOCTYPE and <![CDATA[
  54. */
  55. Error_on_Unsupported,
  56. Ignore_Unsupported,
  57. /*
  58. By default CDATA tags are passed-through as-is.
  59. This option unwraps them when encountered.
  60. */
  61. Unbox_CDATA,
  62. /*
  63. By default SGML entities like `&gt;`, `&#32;` and `&#x20;` are passed-through as-is.
  64. This option decodes them when encountered.
  65. */
  66. Decode_SGML_Entities,
  67. /*
  68. If a tag body has a comment, it will be stripped unless this option is given.
  69. */
  70. Keep_Tag_Body_Comments,
  71. }
  72. Option_Flags :: bit_set[Option_Flag; u16]
  73. Document :: struct {
  74. elements: [dynamic]Element,
  75. element_count: Element_ID,
  76. prologue: Attributes,
  77. encoding: Encoding,
  78. doctype: struct {
  79. /*
  80. We only scan the <!DOCTYPE IDENT part and skip the rest.
  81. */
  82. ident: string,
  83. rest: string,
  84. },
  85. /*
  86. If we encounter comments before the root node, and the option to intern comments is given, this is where they'll live.
  87. Otherwise they'll be in the element tree.
  88. */
  89. comments: [dynamic]string,
  90. /*
  91. Internal
  92. */
  93. tokenizer: ^Tokenizer,
  94. allocator: mem.Allocator,
  95. /*
  96. Input. Either the original buffer, or a copy if `.Input_May_Be_Modified` isn't specified.
  97. */
  98. input: []u8,
  99. strings_to_free: [dynamic]string,
  100. }
  101. Element :: struct {
  102. ident: string,
  103. value: [dynamic]Value,
  104. attribs: Attributes,
  105. kind: enum {
  106. Element = 0,
  107. Comment,
  108. },
  109. parent: Element_ID,
  110. }
  111. Value :: union {
  112. string,
  113. Element_ID,
  114. }
  115. Attribute :: struct {
  116. key: string,
  117. val: string,
  118. }
  119. Attributes :: [dynamic]Attribute
  120. Options :: struct {
  121. flags: Option_Flags,
  122. expected_doctype: string,
  123. }
  124. Encoding :: enum {
  125. Unknown,
  126. UTF_8,
  127. ISO_8859_1,
  128. /*
  129. Aliases
  130. */
  131. LATIN_1 = ISO_8859_1,
  132. }
  133. Error :: enum {
  134. /*
  135. General return values.
  136. */
  137. None = 0,
  138. General_Error,
  139. Unexpected_Token,
  140. Invalid_Token,
  141. /*
  142. Couldn't find, open or read file.
  143. */
  144. File_Error,
  145. /*
  146. File too short.
  147. */
  148. Premature_EOF,
  149. /*
  150. XML-specific errors.
  151. */
  152. No_Prolog,
  153. Invalid_Prolog,
  154. Too_Many_Prologs,
  155. No_DocType,
  156. Too_Many_DocTypes,
  157. DocType_Must_Preceed_Elements,
  158. /*
  159. If a DOCTYPE is present _or_ the caller
  160. asked for a specific DOCTYPE and the DOCTYPE
  161. and root tag don't match, we return `.Invalid_DocType`.
  162. */
  163. Invalid_DocType,
  164. Invalid_Tag_Value,
  165. Mismatched_Closing_Tag,
  166. Unclosed_Comment,
  167. Comment_Before_Root_Element,
  168. Invalid_Sequence_In_Comment,
  169. Unsupported_Version,
  170. Unsupported_Encoding,
  171. /*
  172. <!FOO are usually skipped.
  173. */
  174. Unhandled_Bang,
  175. Duplicate_Attribute,
  176. Conflicting_Options,
  177. }
  178. /*
  179. Implementation starts here.
  180. */
  181. parse_bytes :: proc(data: []u8, options := DEFAULT_OPTIONS, path := "", error_handler := default_error_handler, allocator := context.allocator) -> (doc: ^Document, err: Error) {
  182. data := data
  183. context.allocator = allocator
  184. opts := validate_options(options) or_return
  185. /*
  186. If `.Input_May_Be_Modified` is not specified, we duplicate the input so that we can modify it in-place.
  187. */
  188. if .Input_May_Be_Modified not_in opts.flags {
  189. data = bytes.clone(data)
  190. }
  191. t := &Tokenizer{}
  192. init(t, string(data), path, error_handler)
  193. doc = new(Document)
  194. doc.allocator = allocator
  195. doc.tokenizer = t
  196. doc.input = data
  197. doc.elements = make([dynamic]Element, 1024, 1024, allocator)
  198. // strings.intern_init(&doc.intern, allocator, allocator)
  199. err = .Unexpected_Token
  200. element, parent: Element_ID
  201. open: Token
  202. /*
  203. If a DOCTYPE is present, the root tag has to match.
  204. If an expected DOCTYPE is given in options (i.e. it's non-empty), the DOCTYPE (if present) and root tag have to match.
  205. */
  206. expected_doctype := options.expected_doctype
  207. loop: for {
  208. skip_whitespace(t)
  209. // NOTE(Jeroen): This is faster as a switch.
  210. switch t.ch {
  211. case '<':
  212. /*
  213. Consume peeked `<`
  214. */
  215. advance_rune(t)
  216. open = scan(t)
  217. // NOTE(Jeroen): We're not using a switch because this if-else chain ordered by likelihood is 2.5% faster at -o:size and -o:speed.
  218. if likely(open.kind, Token_Kind.Ident) == .Ident {
  219. /*
  220. e.g. <odin - Start of new element.
  221. */
  222. element = new_element(doc)
  223. if element == 0 { // First Element
  224. parent = element
  225. } else {
  226. append(&doc.elements[parent].value, element)
  227. }
  228. doc.elements[element].parent = parent
  229. doc.elements[element].ident = open.text
  230. parse_attributes(doc, &doc.elements[element].attribs) or_return
  231. /*
  232. If a DOCTYPE is present _or_ the caller
  233. asked for a specific DOCTYPE and the DOCTYPE
  234. and root tag don't match, we return .Invalid_Root_Tag.
  235. */
  236. if element == 0 { // Root tag?
  237. if len(expected_doctype) > 0 && expected_doctype != open.text {
  238. error(t, t.offset, "Root Tag doesn't match DOCTYPE. Expected: %v, got: %v\n", expected_doctype, open.text)
  239. return doc, .Invalid_DocType
  240. }
  241. }
  242. /*
  243. One of these should follow:
  244. - `>`, which means we've just opened this tag and expect a later element to close it.
  245. - `/>`, which means this is an 'empty' or self-closing tag.
  246. */
  247. end_token := scan(t)
  248. #partial switch end_token.kind {
  249. case .Gt:
  250. /*
  251. We're now the new parent.
  252. */
  253. parent = element
  254. case .Slash:
  255. /*
  256. Empty tag. Close it.
  257. */
  258. expect(t, .Gt) or_return
  259. parent = doc.elements[element].parent
  260. element = parent
  261. case:
  262. error(t, t.offset, "Expected close tag, got: %#v\n", end_token)
  263. return
  264. }
  265. } else if open.kind == .Slash {
  266. /*
  267. Close tag.
  268. */
  269. ident := expect(t, .Ident) or_return
  270. _ = expect(t, .Gt) or_return
  271. if doc.elements[element].ident != ident.text {
  272. error(t, t.offset, "Mismatched Closing Tag. Expected %v, got %v\n", doc.elements[element].ident, ident.text)
  273. return doc, .Mismatched_Closing_Tag
  274. }
  275. parent = doc.elements[element].parent
  276. element = parent
  277. } else if open.kind == .Exclaim {
  278. /*
  279. <!
  280. */
  281. next := scan(t)
  282. #partial switch next.kind {
  283. case .Ident:
  284. switch next.text {
  285. case "DOCTYPE":
  286. if len(doc.doctype.ident) > 0 {
  287. return doc, .Too_Many_DocTypes
  288. }
  289. if doc.element_count > 0 {
  290. return doc, .DocType_Must_Preceed_Elements
  291. }
  292. parse_doctype(doc) or_return
  293. if len(expected_doctype) > 0 && expected_doctype != doc.doctype.ident {
  294. error(t, t.offset, "Invalid DOCTYPE. Expected: %v, got: %v\n", expected_doctype, doc.doctype.ident)
  295. return doc, .Invalid_DocType
  296. }
  297. expected_doctype = doc.doctype.ident
  298. case:
  299. if .Error_on_Unsupported in opts.flags {
  300. error(t, t.offset, "Unhandled: <!%v\n", next.text)
  301. return doc, .Unhandled_Bang
  302. }
  303. skip_element(t) or_return
  304. }
  305. case .Dash:
  306. /*
  307. Comment: <!-- -->.
  308. The grammar does not allow a comment to end in --->
  309. */
  310. expect(t, .Dash)
  311. comment := scan_comment(t) or_return
  312. if .Intern_Comments in opts.flags {
  313. if len(doc.elements) == 0 {
  314. append(&doc.comments, comment)
  315. } else {
  316. el := new_element(doc)
  317. doc.elements[el].parent = element
  318. doc.elements[el].kind = .Comment
  319. append(&doc.elements[el].value, comment)
  320. append(&doc.elements[element].value, el)
  321. }
  322. }
  323. case:
  324. error(t, t.offset, "Invalid Token after <!. Expected .Ident, got %#v\n", next)
  325. return
  326. }
  327. } else if open.kind == .Question {
  328. /*
  329. <?xml
  330. */
  331. next := scan(t)
  332. #partial switch next.kind {
  333. case .Ident:
  334. if len(next.text) == 3 && strings.equal_fold(next.text, "xml") {
  335. parse_prologue(doc) or_return
  336. } else if len(doc.prologue) > 0 {
  337. /*
  338. We've already seen a prologue.
  339. */
  340. return doc, .Too_Many_Prologs
  341. } else {
  342. /*
  343. Could be `<?xml-stylesheet`, etc. Ignore it.
  344. */
  345. skip_element(t) or_return
  346. }
  347. case:
  348. error(t, t.offset, "Expected \"<?xml\", got \"<?%v\".", next.text)
  349. return
  350. }
  351. } else {
  352. error(t, t.offset, "Invalid Token after <: %#v\n", open)
  353. return
  354. }
  355. case -1:
  356. /*
  357. End of file.
  358. */
  359. break loop
  360. case:
  361. /*
  362. This should be a tag's body text.
  363. */
  364. body_text := scan_string(t, t.offset) or_return
  365. needs_processing := .Unbox_CDATA in opts.flags
  366. needs_processing |= .Decode_SGML_Entities in opts.flags
  367. if !needs_processing {
  368. append(&doc.elements[element].value, body_text)
  369. continue
  370. }
  371. decode_opts := entity.XML_Decode_Options{}
  372. if .Keep_Tag_Body_Comments not_in opts.flags {
  373. decode_opts += { .Comment_Strip }
  374. }
  375. if .Decode_SGML_Entities not_in opts.flags {
  376. decode_opts += { .No_Entity_Decode }
  377. }
  378. if .Unbox_CDATA in opts.flags {
  379. decode_opts += { .Unbox_CDATA }
  380. if .Decode_SGML_Entities in opts.flags {
  381. decode_opts += { .Decode_CDATA }
  382. }
  383. }
  384. decoded, decode_err := entity.decode_xml(body_text, decode_opts)
  385. if decode_err == .None {
  386. append(&doc.elements[element].value, decoded)
  387. append(&doc.strings_to_free, decoded)
  388. } else {
  389. append(&doc.elements[element].value, body_text)
  390. }
  391. }
  392. }
  393. if .Must_Have_Prolog in opts.flags && len(doc.prologue) == 0 {
  394. return doc, .No_Prolog
  395. }
  396. if .Must_Have_DocType in opts.flags && len(doc.doctype.ident) == 0 {
  397. return doc, .No_DocType
  398. }
  399. resize(&doc.elements, int(doc.element_count))
  400. return doc, .None
  401. }
  402. parse_string :: proc(data: string, options := DEFAULT_OPTIONS, path := "", error_handler := default_error_handler, allocator := context.allocator) -> (doc: ^Document, err: Error) {
  403. _data := transmute([]u8)data
  404. return parse_bytes(_data, options, path, error_handler, allocator)
  405. }
  406. parse :: proc { parse_string, parse_bytes }
  407. // Load an XML file
  408. load_from_file :: proc(filename: string, options := DEFAULT_OPTIONS, error_handler := default_error_handler, allocator := context.allocator) -> (doc: ^Document, err: Error) {
  409. context.allocator = allocator
  410. options := options
  411. data, data_ok := os.read_entire_file(filename)
  412. if !data_ok { return {}, .File_Error }
  413. options.flags += { .Input_May_Be_Modified }
  414. return parse_bytes(data, options, filename, error_handler, allocator)
  415. }
  416. destroy :: proc(doc: ^Document) {
  417. if doc == nil { return }
  418. for el in doc.elements {
  419. delete(el.attribs)
  420. delete(el.value)
  421. }
  422. delete(doc.elements)
  423. delete(doc.prologue)
  424. delete(doc.comments)
  425. delete(doc.input)
  426. for s in doc.strings_to_free {
  427. delete(s)
  428. }
  429. delete(doc.strings_to_free)
  430. free(doc)
  431. }
  432. /*
  433. Helpers.
  434. */
  435. validate_options :: proc(options: Options) -> (validated: Options, err: Error) {
  436. validated = options
  437. if .Error_on_Unsupported in validated.flags && .Ignore_Unsupported in validated.flags {
  438. return options, .Conflicting_Options
  439. }
  440. return validated, .None
  441. }
  442. expect :: proc(t: ^Tokenizer, kind: Token_Kind) -> (tok: Token, err: Error) {
  443. tok = scan(t)
  444. if tok.kind == kind { return tok, .None }
  445. error(t, t.offset, "Expected \"%v\", got \"%v\".", kind, tok.kind)
  446. return tok, .Unexpected_Token
  447. }
  448. parse_attribute :: proc(doc: ^Document) -> (attr: Attribute, offset: int, err: Error) {
  449. assert(doc != nil)
  450. context.allocator = doc.allocator
  451. t := doc.tokenizer
  452. key := expect(t, .Ident) or_return
  453. offset = t.offset - len(key.text)
  454. _ = expect(t, .Eq) or_return
  455. value := expect(t, .String) or_return
  456. attr.key = key.text
  457. attr.val = value.text
  458. err = .None
  459. return
  460. }
  461. check_duplicate_attributes :: proc(t: ^Tokenizer, attribs: Attributes, attr: Attribute, offset: int) -> (err: Error) {
  462. for a in attribs {
  463. if attr.key == a.key {
  464. error(t, offset, "Duplicate attribute: %v\n", attr.key)
  465. return .Duplicate_Attribute
  466. }
  467. }
  468. return .None
  469. }
  470. parse_attributes :: proc(doc: ^Document, attribs: ^Attributes) -> (err: Error) {
  471. assert(doc != nil)
  472. context.allocator = doc.allocator
  473. t := doc.tokenizer
  474. for peek(t).kind == .Ident {
  475. attr, offset := parse_attribute(doc) or_return
  476. check_duplicate_attributes(t, attribs^, attr, offset) or_return
  477. append(attribs, attr)
  478. }
  479. skip_whitespace(t)
  480. return .None
  481. }
  482. parse_prologue :: proc(doc: ^Document) -> (err: Error) {
  483. assert(doc != nil)
  484. context.allocator = doc.allocator
  485. t := doc.tokenizer
  486. offset := t.offset
  487. parse_attributes(doc, &doc.prologue) or_return
  488. for attr in doc.prologue {
  489. switch attr.key {
  490. case "version":
  491. switch attr.val {
  492. case "1.0", "1.1":
  493. case:
  494. error(t, offset, "[parse_prologue] Warning: Unhandled XML version: %v\n", attr.val)
  495. }
  496. case "encoding":
  497. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  498. switch strings.to_lower(attr.val, context.temp_allocator) {
  499. case "utf-8", "utf8":
  500. doc.encoding = .UTF_8
  501. case "latin-1", "latin1", "iso-8859-1":
  502. doc.encoding = .LATIN_1
  503. case:
  504. /*
  505. Unrecognized encoding, assume UTF-8.
  506. */
  507. error(t, offset, "[parse_prologue] Warning: Unrecognized encoding: %v\n", attr.val)
  508. }
  509. case:
  510. // Ignored.
  511. }
  512. }
  513. _ = expect(t, .Question) or_return
  514. _ = expect(t, .Gt) or_return
  515. return .None
  516. }
  517. skip_element :: proc(t: ^Tokenizer) -> (err: Error) {
  518. close := 1
  519. loop: for {
  520. tok := scan(t)
  521. #partial switch tok.kind {
  522. case .EOF:
  523. error(t, t.offset, "[skip_element] Premature EOF\n")
  524. return .Premature_EOF
  525. case .Lt:
  526. close += 1
  527. case .Gt:
  528. close -= 1
  529. if close == 0 {
  530. break loop
  531. }
  532. case:
  533. }
  534. }
  535. return .None
  536. }
  537. parse_doctype :: proc(doc: ^Document) -> (err: Error) {
  538. /*
  539. <!DOCTYPE greeting SYSTEM "hello.dtd">
  540. <!DOCTYPE greeting [
  541. <!ELEMENT greeting (#PCDATA)>
  542. ]>
  543. */
  544. assert(doc != nil)
  545. context.allocator = doc.allocator
  546. t := doc.tokenizer
  547. tok := expect(t, .Ident) or_return
  548. doc.doctype.ident = tok.text
  549. skip_whitespace(t)
  550. offset := t.offset
  551. skip_element(t) or_return
  552. /*
  553. -1 because the current offset is that of the closing tag, so the rest of the DOCTYPE tag ends just before it.
  554. */
  555. doc.doctype.rest = string(t.src[offset : t.offset - 1])
  556. return .None
  557. }
  558. Element_ID :: u32
  559. new_element :: proc(doc: ^Document) -> (id: Element_ID) {
  560. element_space := len(doc.elements)
  561. // Need to resize
  562. if int(doc.element_count) + 1 > element_space {
  563. if element_space < 65536 {
  564. element_space *= 2
  565. } else {
  566. element_space += 65536
  567. }
  568. resize(&doc.elements, element_space)
  569. }
  570. cur := doc.element_count
  571. doc.element_count += 1
  572. return cur
  573. }