entity.odin 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /*
  2. Copyright 2021 Jeroen van Rijn <[email protected]>.
  3. Made available under Odin's BSD-3 license.
  4. List of contributors:
  5. Jeroen van Rijn: Initial implementation.
  6. */
  7. /*
  8. A unicode entity encoder/decoder.
  9. This code has several procedures to map unicode runes to/from different textual encodings.
  10. - SGML/XML/HTML entity
  11. - &#<decimal>;
  12. - &#x<hexadecimal>;
  13. - &<entity name>; (If the lookup tables are compiled in).
  14. Reference: [[ https://www.w3.org/2003/entities/2007xml/unicode.xml ]]
  15. - URL encode / decode %hex entity
  16. Reference: [[ https://datatracker.ietf.org/doc/html/rfc3986/#section-2.1 ]]
  17. */
  18. package encoding_unicode_entity
  19. import "core:unicode/utf8"
  20. import "core:unicode"
  21. import "core:strings"
  22. MAX_RUNE_CODEPOINT :: int(unicode.MAX_RUNE)
  23. write_rune :: strings.write_rune
  24. write_string :: strings.write_string
  25. Error :: enum u8 {
  26. None = 0,
  27. Tokenizer_Is_Nil,
  28. Illegal_NUL_Character,
  29. Illegal_UTF_Encoding,
  30. Illegal_BOM,
  31. CDATA_Not_Terminated,
  32. Comment_Not_Terminated,
  33. Invalid_Entity_Encoding,
  34. }
  35. Tokenizer :: struct {
  36. r: rune,
  37. w: int,
  38. src: string,
  39. offset: int,
  40. read_offset: int,
  41. }
  42. CDATA_START :: "<![CDATA["
  43. CDATA_END :: "]]>"
  44. COMMENT_START :: "<!--"
  45. COMMENT_END :: "-->"
  46. // Default: CDATA and comments are passed through unchanged.
  47. XML_Decode_Option :: enum u8 {
  48. // Do not decode & entities. It decodes by default. If given, overrides `Decode_CDATA`.
  49. No_Entity_Decode,
  50. // CDATA is unboxed.
  51. Unbox_CDATA,
  52. // Unboxed CDATA is decoded as well. Ignored if `.Unbox_CDATA` is not given.
  53. Decode_CDATA,
  54. // Comments are stripped.
  55. Comment_Strip,
  56. // Normalize whitespace
  57. Normalize_Whitespace,
  58. }
  59. XML_Decode_Options :: bit_set[XML_Decode_Option; u8]
  60. // Decode a string that may include SGML/XML/HTML entities.
  61. // The caller has to free the result.
  62. decode_xml :: proc(input: string, options := XML_Decode_Options{}, allocator := context.allocator) -> (decoded: string, err: Error) {
  63. context.allocator = allocator
  64. l := len(input)
  65. if l == 0 { return "", .None }
  66. builder := strings.builder_make()
  67. defer strings.builder_destroy(&builder)
  68. t := Tokenizer{src=input}
  69. in_data := false
  70. prev: rune = ' '
  71. loop: for {
  72. advance(&t) or_return
  73. if t.r < 0 { break loop }
  74. // Below here we're never inside a CDATA tag. At most we'll see the start of one,
  75. // but that doesn't affect the logic.
  76. switch t.r {
  77. case '<':
  78. /*
  79. Might be the start of a CDATA tag or comment.
  80. We don't need to check if we need to write a `<`, because if it isn't CDATA or a comment,
  81. it couldn't have been part of an XML tag body to be decoded here.
  82. Keep in mind that we could already *be* inside a CDATA tag.
  83. If so, write `<` as a literal and continue.
  84. */
  85. if in_data {
  86. write_rune(&builder, '<')
  87. continue
  88. }
  89. in_data = _handle_xml_special(&t, &builder, options) or_return
  90. case ']':
  91. // If we're unboxing _and_ decoding CDATA, we'll have to check for the end tag.
  92. if in_data {
  93. if strings.has_prefix(t.src[t.offset:], CDATA_END) {
  94. in_data = false
  95. t.read_offset += len(CDATA_END) - 1
  96. }
  97. continue
  98. } else {
  99. write_rune(&builder, ']')
  100. }
  101. case:
  102. if in_data && .Decode_CDATA not_in options {
  103. // Unboxed, but undecoded.
  104. write_rune(&builder, t.r)
  105. continue
  106. }
  107. if t.r == '&' {
  108. if entity, entity_err := _extract_xml_entity(&t); entity_err != .None {
  109. // We read to the end of the string without closing the entity. Pass through as-is.
  110. write_string(&builder, entity)
  111. } else {
  112. if .No_Entity_Decode not_in options {
  113. if decoded, ok := xml_decode_entity(entity); ok {
  114. write_rune(&builder, decoded)
  115. continue
  116. }
  117. }
  118. // Literal passthrough because the decode failed or we want entities not decoded.
  119. write_string(&builder, "&")
  120. write_string(&builder, entity)
  121. write_string(&builder, ";")
  122. }
  123. } else {
  124. // Handle AV Normalization: https://www.w3.org/TR/2006/REC-xml11-20060816/#AVNormalize
  125. if .Normalize_Whitespace in options {
  126. switch t.r {
  127. case ' ', '\r', '\n', '\t':
  128. if prev != ' ' {
  129. write_rune(&builder, ' ')
  130. prev = ' '
  131. }
  132. case:
  133. write_rune(&builder, t.r)
  134. prev = t.r
  135. }
  136. } else {
  137. // https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-line-ends
  138. switch t.r {
  139. case '\n', 0x85, 0x2028:
  140. write_rune(&builder, '\n')
  141. case '\r': // Do nothing until next character
  142. case:
  143. if prev == '\r' { // Turn a single carriage return into a \n
  144. write_rune(&builder, '\n')
  145. }
  146. write_rune(&builder, t.r)
  147. }
  148. prev = t.r
  149. }
  150. }
  151. }
  152. }
  153. return strings.clone(strings.to_string(builder), allocator), err
  154. }
  155. advance :: proc(t: ^Tokenizer) -> (err: Error) {
  156. if t == nil { return .Tokenizer_Is_Nil }
  157. #no_bounds_check {
  158. if t.read_offset < len(t.src) {
  159. t.offset = t.read_offset
  160. t.r, t.w = rune(t.src[t.read_offset]), 1
  161. switch {
  162. case t.r == 0:
  163. return .Illegal_NUL_Character
  164. case t.r >= utf8.RUNE_SELF:
  165. t.r, t.w = utf8.decode_rune_in_string(t.src[t.read_offset:])
  166. if t.r == utf8.RUNE_ERROR && t.w == 1 {
  167. return .Illegal_UTF_Encoding
  168. } else if t.r == utf8.RUNE_BOM && t.offset > 0 {
  169. return .Illegal_BOM
  170. }
  171. }
  172. t.read_offset += t.w
  173. return .None
  174. } else {
  175. t.offset = len(t.src)
  176. t.r = -1
  177. return
  178. }
  179. }
  180. }
  181. xml_decode_entity :: proc(entity: string) -> (decoded: rune, ok: bool) {
  182. entity := entity
  183. if len(entity) == 0 { return -1, false }
  184. switch entity[0] {
  185. case '#':
  186. base := 10
  187. val := 0
  188. entity = entity[1:]
  189. if len(entity) == 0 { return -1, false }
  190. if entity[0] == 'x' || entity[0] == 'X' {
  191. base = 16
  192. entity = entity[1:]
  193. }
  194. for len(entity) > 0 {
  195. r := entity[0]
  196. switch r {
  197. case '0'..='9':
  198. val *= base
  199. val += int(r - '0')
  200. case 'a'..='f':
  201. if base == 10 { return -1, false }
  202. val *= base
  203. val += int(r - 'a' + 10)
  204. case 'A'..='F':
  205. if base == 10 { return -1, false }
  206. val *= base
  207. val += int(r - 'A' + 10)
  208. case:
  209. return -1, false
  210. }
  211. if val > MAX_RUNE_CODEPOINT { return -1, false }
  212. entity = entity[1:]
  213. }
  214. return rune(val), true
  215. case:
  216. // Named entity.
  217. return named_xml_entity_to_rune(entity)
  218. }
  219. }
  220. // Private XML helper to extract `&<stuff>;` entity.
  221. @(private="file")
  222. _extract_xml_entity :: proc(t: ^Tokenizer) -> (entity: string, err: Error) {
  223. assert(t != nil && t.r == '&')
  224. // All of these would be in the ASCII range.
  225. // Even if one is not, it doesn't matter. All characters we need to compare to extract are.
  226. length := len(t.src)
  227. found := false
  228. #no_bounds_check {
  229. for t.read_offset < length {
  230. if t.src[t.read_offset] == ';' {
  231. t.read_offset += 1
  232. found = true
  233. break
  234. }
  235. t.read_offset += 1
  236. }
  237. }
  238. if found {
  239. return string(t.src[t.offset + 1 : t.read_offset - 1]), .None
  240. }
  241. return string(t.src[t.offset : t.read_offset]), .Invalid_Entity_Encoding
  242. }
  243. // Private XML helper for CDATA and comments.
  244. @(private="file")
  245. _handle_xml_special :: proc(t: ^Tokenizer, builder: ^strings.Builder, options: XML_Decode_Options) -> (in_data: bool, err: Error) {
  246. assert(t != nil && t.r == '<')
  247. if t.read_offset + len(CDATA_START) >= len(t.src) { return false, .None }
  248. s := string(t.src[t.offset:])
  249. if strings.has_prefix(s, CDATA_START) {
  250. if .Unbox_CDATA in options && .Decode_CDATA in options {
  251. // We're unboxing _and_ decoding CDATA
  252. t.read_offset += len(CDATA_START) - 1
  253. return true, .None
  254. }
  255. // CDATA is passed through. Scan until end of CDATA.
  256. start_offset := t.offset
  257. t.read_offset += len(CDATA_START)
  258. for {
  259. advance(t)
  260. if t.r < 0 {
  261. // error(t, offset, "[scan_string] CDATA was not terminated\n")
  262. return true, .CDATA_Not_Terminated
  263. }
  264. // Scan until the end of a CDATA tag.
  265. if s = string(t.src[t.read_offset:]); strings.has_prefix(s, CDATA_END) {
  266. t.read_offset += len(CDATA_END)
  267. cdata := string(t.src[start_offset:t.read_offset])
  268. if .Unbox_CDATA in options {
  269. cdata = cdata[len(CDATA_START):]
  270. cdata = cdata[:len(cdata) - len(CDATA_END)]
  271. }
  272. write_string(builder, cdata)
  273. return false, .None
  274. }
  275. }
  276. } else if strings.has_prefix(s, COMMENT_START) {
  277. t.read_offset += len(COMMENT_START)
  278. // Comment is passed through by default.
  279. offset := t.offset
  280. // Scan until end of Comment.
  281. for {
  282. advance(t) or_return
  283. if t.r < 0 { return true, .Comment_Not_Terminated }
  284. if t.read_offset + len(COMMENT_END) < len(t.src) {
  285. if string(t.src[t.offset:][:len(COMMENT_END)]) == COMMENT_END {
  286. t.read_offset += len(COMMENT_END) - 1
  287. if .Comment_Strip not_in options {
  288. comment := string(t.src[offset : t.read_offset])
  289. write_string(builder, comment)
  290. }
  291. return false, .None
  292. }
  293. }
  294. }
  295. }
  296. return false, .None
  297. }