xml_reader.odin 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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: string,
  104. attribs: Attributes,
  105. kind: enum {
  106. Element = 0,
  107. Comment,
  108. },
  109. parent: Element_ID,
  110. children: [dynamic]Element_ID,
  111. }
  112. Attribute :: struct {
  113. key: string,
  114. val: string,
  115. }
  116. Attributes :: [dynamic]Attribute
  117. Options :: struct {
  118. flags: Option_Flags,
  119. expected_doctype: string,
  120. }
  121. Encoding :: enum {
  122. Unknown,
  123. UTF_8,
  124. ISO_8859_1,
  125. /*
  126. Aliases
  127. */
  128. LATIN_1 = ISO_8859_1,
  129. }
  130. Error :: enum {
  131. /*
  132. General return values.
  133. */
  134. None = 0,
  135. General_Error,
  136. Unexpected_Token,
  137. Invalid_Token,
  138. /*
  139. Couldn't find, open or read file.
  140. */
  141. File_Error,
  142. /*
  143. File too short.
  144. */
  145. Premature_EOF,
  146. /*
  147. XML-specific errors.
  148. */
  149. No_Prolog,
  150. Invalid_Prolog,
  151. Too_Many_Prologs,
  152. No_DocType,
  153. Too_Many_DocTypes,
  154. DocType_Must_Preceed_Elements,
  155. /*
  156. If a DOCTYPE is present _or_ the caller
  157. asked for a specific DOCTYPE and the DOCTYPE
  158. and root tag don't match, we return `.Invalid_DocType`.
  159. */
  160. Invalid_DocType,
  161. Invalid_Tag_Value,
  162. Mismatched_Closing_Tag,
  163. Unclosed_Comment,
  164. Comment_Before_Root_Element,
  165. Invalid_Sequence_In_Comment,
  166. Unsupported_Version,
  167. Unsupported_Encoding,
  168. /*
  169. <!FOO are usually skipped.
  170. */
  171. Unhandled_Bang,
  172. Duplicate_Attribute,
  173. Conflicting_Options,
  174. }
  175. /*
  176. Implementation starts here.
  177. */
  178. parse_bytes :: proc(data: []u8, options := DEFAULT_OPTIONS, path := "", error_handler := default_error_handler, allocator := context.allocator) -> (doc: ^Document, err: Error) {
  179. data := data
  180. context.allocator = allocator
  181. opts := validate_options(options) or_return
  182. /*
  183. If `.Input_May_Be_Modified` is not specified, we duplicate the input so that we can modify it in-place.
  184. */
  185. if .Input_May_Be_Modified not_in opts.flags {
  186. data = bytes.clone(data)
  187. }
  188. t := &Tokenizer{}
  189. init(t, string(data), path, error_handler)
  190. doc = new(Document)
  191. doc.allocator = allocator
  192. doc.tokenizer = t
  193. doc.input = data
  194. doc.elements = make([dynamic]Element, 1024, 1024, allocator)
  195. // strings.intern_init(&doc.intern, allocator, allocator)
  196. err = .Unexpected_Token
  197. element, parent: Element_ID
  198. tag_is_open := false
  199. first_element := true
  200. open: Token
  201. /*
  202. If a DOCTYPE is present, the root tag has to match.
  203. If an expected DOCTYPE is given in options (i.e. it's non-empty), the DOCTYPE (if present) and root tag have to match.
  204. */
  205. expected_doctype := options.expected_doctype
  206. loop: for {
  207. skip_whitespace(t)
  208. // NOTE(Jeroen): This is faster as a switch.
  209. switch t.ch {
  210. case '<':
  211. /*
  212. Consume peeked `<`
  213. */
  214. advance_rune(t)
  215. open = scan(t)
  216. // 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.
  217. if likely(open.kind, Token_Kind.Ident) == .Ident {
  218. /*
  219. e.g. <odin - Start of new element.
  220. */
  221. element = new_element(doc)
  222. tag_is_open = true
  223. if first_element {
  224. /*
  225. First element.
  226. */
  227. parent = element
  228. first_element = false
  229. } else {
  230. append(&doc.elements[parent].children, element)
  231. }
  232. doc.elements[element].parent = parent
  233. doc.elements[element].ident = open.text
  234. parse_attributes(doc, &doc.elements[element].attribs) or_return
  235. /*
  236. If a DOCTYPE is present _or_ the caller
  237. asked for a specific DOCTYPE and the DOCTYPE
  238. and root tag don't match, we return .Invalid_Root_Tag.
  239. */
  240. if element == 0 { // Root tag?
  241. if len(expected_doctype) > 0 && expected_doctype != open.text {
  242. error(t, t.offset, "Root Tag doesn't match DOCTYPE. Expected: %v, got: %v\n", expected_doctype, open.text)
  243. return doc, .Invalid_DocType
  244. }
  245. }
  246. /*
  247. One of these should follow:
  248. - `>`, which means we've just opened this tag and expect a later element to close it.
  249. - `/>`, which means this is an 'empty' or self-closing tag.
  250. */
  251. end_token := scan(t)
  252. #partial switch end_token.kind {
  253. case .Gt:
  254. /*
  255. We're now the new parent.
  256. */
  257. parent = element
  258. case .Slash:
  259. /*
  260. Empty tag. Close it.
  261. */
  262. expect(t, .Gt) or_return
  263. parent = doc.elements[element].parent
  264. element = parent
  265. tag_is_open = false
  266. case:
  267. error(t, t.offset, "Expected close tag, got: %#v\n", end_token)
  268. return
  269. }
  270. } else if open.kind == .Slash {
  271. /*
  272. Close tag.
  273. */
  274. ident := expect(t, .Ident) or_return
  275. _ = expect(t, .Gt) or_return
  276. if doc.elements[element].ident != ident.text {
  277. error(t, t.offset, "Mismatched Closing Tag. Expected %v, got %v\n", doc.elements[element].ident, ident.text)
  278. return doc, .Mismatched_Closing_Tag
  279. }
  280. parent = doc.elements[element].parent
  281. element = parent
  282. tag_is_open = false
  283. } else if open.kind == .Exclaim {
  284. /*
  285. <!
  286. */
  287. next := scan(t)
  288. #partial switch next.kind {
  289. case .Ident:
  290. switch next.text {
  291. case "DOCTYPE":
  292. if len(doc.doctype.ident) > 0 {
  293. return doc, .Too_Many_DocTypes
  294. }
  295. if doc.element_count > 0 {
  296. return doc, .DocType_Must_Preceed_Elements
  297. }
  298. parse_doctype(doc) or_return
  299. if len(expected_doctype) > 0 && expected_doctype != doc.doctype.ident {
  300. error(t, t.offset, "Invalid DOCTYPE. Expected: %v, got: %v\n", expected_doctype, doc.doctype.ident)
  301. return doc, .Invalid_DocType
  302. }
  303. expected_doctype = doc.doctype.ident
  304. case:
  305. if .Error_on_Unsupported in opts.flags {
  306. error(t, t.offset, "Unhandled: <!%v\n", next.text)
  307. return doc, .Unhandled_Bang
  308. }
  309. skip_element(t) or_return
  310. }
  311. case .Dash:
  312. /*
  313. Comment: <!-- -->.
  314. The grammar does not allow a comment to end in --->
  315. */
  316. expect(t, .Dash)
  317. comment := scan_comment(t) or_return
  318. if .Intern_Comments in opts.flags {
  319. if len(doc.elements) == 0 {
  320. append(&doc.comments, comment)
  321. } else {
  322. el := new_element(doc)
  323. doc.elements[el].parent = element
  324. doc.elements[el].kind = .Comment
  325. doc.elements[el].value = comment
  326. append(&doc.elements[element].children, el)
  327. }
  328. }
  329. case:
  330. error(t, t.offset, "Invalid Token after <!. Expected .Ident, got %#v\n", next)
  331. return
  332. }
  333. } else if open.kind == .Question {
  334. /*
  335. <?xml
  336. */
  337. next := scan(t)
  338. #partial switch next.kind {
  339. case .Ident:
  340. if len(next.text) == 3 && strings.equal_fold(next.text, "xml") {
  341. parse_prologue(doc) or_return
  342. } else if len(doc.prologue) > 0 {
  343. /*
  344. We've already seen a prologue.
  345. */
  346. return doc, .Too_Many_Prologs
  347. } else {
  348. /*
  349. Could be `<?xml-stylesheet`, etc. Ignore it.
  350. */
  351. skip_element(t) or_return
  352. }
  353. case:
  354. error(t, t.offset, "Expected \"<?xml\", got \"<?%v\".", next.text)
  355. return
  356. }
  357. } else {
  358. error(t, t.offset, "Invalid Token after <: %#v\n", open)
  359. return
  360. }
  361. case -1:
  362. /*
  363. End of file.
  364. */
  365. if tag_is_open {
  366. return doc, .Premature_EOF
  367. }
  368. break loop
  369. case:
  370. /*
  371. This should be a tag's body text.
  372. */
  373. body_text := scan_string(t, t.offset) or_return
  374. needs_processing := .Unbox_CDATA in opts.flags
  375. needs_processing |= .Decode_SGML_Entities in opts.flags
  376. if !needs_processing {
  377. doc.elements[element].value = body_text
  378. continue
  379. }
  380. decode_opts := entity.XML_Decode_Options{}
  381. if .Keep_Tag_Body_Comments not_in opts.flags {
  382. decode_opts += { .Comment_Strip }
  383. }
  384. if .Decode_SGML_Entities not_in opts.flags {
  385. decode_opts += { .No_Entity_Decode }
  386. }
  387. if .Unbox_CDATA in opts.flags {
  388. decode_opts += { .Unbox_CDATA }
  389. if .Decode_SGML_Entities in opts.flags {
  390. decode_opts += { .Decode_CDATA }
  391. }
  392. }
  393. decoded, decode_err := entity.decode_xml(body_text, decode_opts)
  394. if decode_err == .None {
  395. doc.elements[element].value = decoded
  396. append(&doc.strings_to_free, decoded)
  397. } else {
  398. doc.elements[element].value = body_text
  399. }
  400. }
  401. }
  402. if .Must_Have_Prolog in opts.flags && len(doc.prologue) == 0 {
  403. return doc, .No_Prolog
  404. }
  405. if .Must_Have_DocType in opts.flags && len(doc.doctype.ident) == 0 {
  406. return doc, .No_DocType
  407. }
  408. resize(&doc.elements, int(doc.element_count))
  409. return doc, .None
  410. }
  411. parse_string :: proc(data: string, options := DEFAULT_OPTIONS, path := "", error_handler := default_error_handler, allocator := context.allocator) -> (doc: ^Document, err: Error) {
  412. _data := transmute([]u8)data
  413. return parse_bytes(_data, options, path, error_handler, allocator)
  414. }
  415. parse :: proc { parse_string, parse_bytes }
  416. // Load an XML file
  417. load_from_file :: proc(filename: string, options := DEFAULT_OPTIONS, error_handler := default_error_handler, allocator := context.allocator) -> (doc: ^Document, err: Error) {
  418. context.allocator = allocator
  419. options := options
  420. data, data_ok := os.read_entire_file(filename)
  421. if !data_ok { return {}, .File_Error }
  422. options.flags += { .Input_May_Be_Modified }
  423. return parse_bytes(data, options, filename, error_handler, allocator)
  424. }
  425. destroy :: proc(doc: ^Document) {
  426. if doc == nil { return }
  427. for el in doc.elements {
  428. delete(el.attribs)
  429. delete(el.children)
  430. }
  431. delete(doc.elements)
  432. delete(doc.prologue)
  433. delete(doc.comments)
  434. delete(doc.input)
  435. for s in doc.strings_to_free {
  436. delete(s)
  437. }
  438. delete(doc.strings_to_free)
  439. free(doc)
  440. }
  441. /*
  442. Helpers.
  443. */
  444. validate_options :: proc(options: Options) -> (validated: Options, err: Error) {
  445. validated = options
  446. if .Error_on_Unsupported in validated.flags && .Ignore_Unsupported in validated.flags {
  447. return options, .Conflicting_Options
  448. }
  449. return validated, .None
  450. }
  451. expect :: proc(t: ^Tokenizer, kind: Token_Kind) -> (tok: Token, err: Error) {
  452. tok = scan(t)
  453. if tok.kind == kind { return tok, .None }
  454. error(t, t.offset, "Expected \"%v\", got \"%v\".", kind, tok.kind)
  455. return tok, .Unexpected_Token
  456. }
  457. parse_attribute :: proc(doc: ^Document) -> (attr: Attribute, offset: int, err: Error) {
  458. assert(doc != nil)
  459. context.allocator = doc.allocator
  460. t := doc.tokenizer
  461. key := expect(t, .Ident) or_return
  462. offset = t.offset - len(key.text)
  463. _ = expect(t, .Eq) or_return
  464. value := expect(t, .String) or_return
  465. attr.key = key.text
  466. attr.val = value.text
  467. err = .None
  468. return
  469. }
  470. check_duplicate_attributes :: proc(t: ^Tokenizer, attribs: Attributes, attr: Attribute, offset: int) -> (err: Error) {
  471. for a in attribs {
  472. if attr.key == a.key {
  473. error(t, offset, "Duplicate attribute: %v\n", attr.key)
  474. return .Duplicate_Attribute
  475. }
  476. }
  477. return .None
  478. }
  479. parse_attributes :: proc(doc: ^Document, attribs: ^Attributes) -> (err: Error) {
  480. assert(doc != nil)
  481. context.allocator = doc.allocator
  482. t := doc.tokenizer
  483. for peek(t).kind == .Ident {
  484. attr, offset := parse_attribute(doc) or_return
  485. check_duplicate_attributes(t, attribs^, attr, offset) or_return
  486. append(attribs, attr)
  487. }
  488. skip_whitespace(t)
  489. return .None
  490. }
  491. parse_prologue :: proc(doc: ^Document) -> (err: Error) {
  492. assert(doc != nil)
  493. context.allocator = doc.allocator
  494. t := doc.tokenizer
  495. offset := t.offset
  496. parse_attributes(doc, &doc.prologue) or_return
  497. for attr in doc.prologue {
  498. switch attr.key {
  499. case "version":
  500. switch attr.val {
  501. case "1.0", "1.1":
  502. case:
  503. error(t, offset, "[parse_prologue] Warning: Unhandled XML version: %v\n", attr.val)
  504. }
  505. case "encoding":
  506. runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
  507. switch strings.to_lower(attr.val, context.temp_allocator) {
  508. case "utf-8", "utf8":
  509. doc.encoding = .UTF_8
  510. case "latin-1", "latin1", "iso-8859-1":
  511. doc.encoding = .LATIN_1
  512. case:
  513. /*
  514. Unrecognized encoding, assume UTF-8.
  515. */
  516. error(t, offset, "[parse_prologue] Warning: Unrecognized encoding: %v\n", attr.val)
  517. }
  518. case:
  519. // Ignored.
  520. }
  521. }
  522. _ = expect(t, .Question) or_return
  523. _ = expect(t, .Gt) or_return
  524. return .None
  525. }
  526. skip_element :: proc(t: ^Tokenizer) -> (err: Error) {
  527. close := 1
  528. loop: for {
  529. tok := scan(t)
  530. #partial switch tok.kind {
  531. case .EOF:
  532. error(t, t.offset, "[skip_element] Premature EOF\n")
  533. return .Premature_EOF
  534. case .Lt:
  535. close += 1
  536. case .Gt:
  537. close -= 1
  538. if close == 0 {
  539. break loop
  540. }
  541. case:
  542. }
  543. }
  544. return .None
  545. }
  546. parse_doctype :: proc(doc: ^Document) -> (err: Error) {
  547. /*
  548. <!DOCTYPE greeting SYSTEM "hello.dtd">
  549. <!DOCTYPE greeting [
  550. <!ELEMENT greeting (#PCDATA)>
  551. ]>
  552. */
  553. assert(doc != nil)
  554. context.allocator = doc.allocator
  555. t := doc.tokenizer
  556. tok := expect(t, .Ident) or_return
  557. doc.doctype.ident = tok.text
  558. skip_whitespace(t)
  559. offset := t.offset
  560. skip_element(t) or_return
  561. /*
  562. -1 because the current offset is that of the closing tag, so the rest of the DOCTYPE tag ends just before it.
  563. */
  564. doc.doctype.rest = string(t.src[offset : t.offset - 1])
  565. return .None
  566. }
  567. Element_ID :: u32
  568. new_element :: proc(doc: ^Document) -> (id: Element_ID) {
  569. element_space := len(doc.elements)
  570. // Need to resize
  571. if int(doc.element_count) + 1 > element_space {
  572. if element_space < 65536 {
  573. element_space *= 2
  574. } else {
  575. element_space += 65536
  576. }
  577. resize(&doc.elements, element_space)
  578. }
  579. cur := doc.element_count
  580. doc.element_count += 1
  581. return cur
  582. }