| 1 | // Copyright 2015-2019 Brett Vickers. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package etree |
| 6 | |
| 7 | import ( |
| 8 | "io" |
| 9 | "strings" |
| 10 | "unicode/utf8" |
| 11 | ) |
| 12 | |
| 13 | type stack[E any] struct { |
| 14 | data []E |
| 15 | } |
| 16 | |
| 17 | func (s *stack[E]) empty() bool { |
| 18 | return len(s.data) == 0 |
| 19 | } |
| 20 | |
| 21 | func (s *stack[E]) push(value E) { |
| 22 | s.data = append(s.data, value) |
| 23 | } |
| 24 | |
| 25 | func (s *stack[E]) pop() E { |
| 26 | value := s.data[len(s.data)-1] |
| 27 | var empty E |
| 28 | s.data[len(s.data)-1] = empty |
| 29 | s.data = s.data[:len(s.data)-1] |
| 30 | return value |
| 31 | } |
| 32 | |
| 33 | func (s *stack[E]) peek() E { |
| 34 | return s.data[len(s.data)-1] |
| 35 | } |
| 36 | |
| 37 | type queue[E any] struct { |
| 38 | data []E |
| 39 | head, tail int |
| 40 | } |
| 41 | |
| 42 | func (f *queue[E]) add(value E) { |
| 43 | if f.len()+1 >= len(f.data) { |
| 44 | f.grow() |
| 45 | } |
| 46 | f.data[f.tail] = value |
| 47 | if f.tail++; f.tail == len(f.data) { |
| 48 | f.tail = 0 |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | func (f *queue[E]) remove() E { |
| 53 | value := f.data[f.head] |
| 54 | var empty E |
| 55 | f.data[f.head] = empty |
| 56 | if f.head++; f.head == len(f.data) { |
| 57 | f.head = 0 |
| 58 | } |
| 59 | return value |
| 60 | } |
| 61 | |
| 62 | func (f *queue[E]) len() int { |
| 63 | if f.tail >= f.head { |
| 64 | return f.tail - f.head |
| 65 | } |
| 66 | return len(f.data) - f.head + f.tail |
| 67 | } |
| 68 | |
| 69 | func (f *queue[E]) grow() { |
| 70 | c := len(f.data) * 2 |
| 71 | if c == 0 { |
| 72 | c = 4 |
| 73 | } |
| 74 | buf, count := make([]E, c), f.len() |
| 75 | if f.tail >= f.head { |
| 76 | copy(buf[:count], f.data[f.head:f.tail]) |
| 77 | } else { |
| 78 | hindex := len(f.data) - f.head |
| 79 | copy(buf[:hindex], f.data[f.head:]) |
| 80 | copy(buf[hindex:count], f.data[:f.tail]) |
| 81 | } |
| 82 | f.data, f.head, f.tail = buf, 0, count |
| 83 | } |
| 84 | |
| 85 | // xmlReader provides the interface by which an XML byte stream is |
| 86 | // processed and decoded. |
| 87 | type xmlReader interface { |
| 88 | Bytes() int64 |
| 89 | Read(p []byte) (n int, err error) |
| 90 | } |
| 91 | |
| 92 | // xmlSimpleReader implements a proxy reader that counts the number of |
| 93 | // bytes read from its encapsulated reader. |
| 94 | type xmlSimpleReader struct { |
| 95 | r io.Reader |
| 96 | bytes int64 |
| 97 | } |
| 98 | |
| 99 | func newXmlSimpleReader(r io.Reader) xmlReader { |
| 100 | return &xmlSimpleReader{r, 0} |
| 101 | } |
| 102 | |
| 103 | func (xr *xmlSimpleReader) Bytes() int64 { |
| 104 | return xr.bytes |
| 105 | } |
| 106 | |
| 107 | func (xr *xmlSimpleReader) Read(p []byte) (n int, err error) { |
| 108 | n, err = xr.r.Read(p) |
| 109 | xr.bytes += int64(n) |
| 110 | return n, err |
| 111 | } |
| 112 | |
| 113 | // xmlPeekReader implements a proxy reader that counts the number of |
| 114 | // bytes read from its encapsulated reader. It also allows the caller to |
| 115 | // "peek" at the previous portions of the buffer after they have been |
| 116 | // parsed. |
| 117 | type xmlPeekReader struct { |
| 118 | r io.Reader |
| 119 | bytes int64 // total bytes read by the Read function |
| 120 | buf []byte // internal read buffer |
| 121 | bufSize int // total bytes used in the read buffer |
| 122 | bufOffset int64 // total bytes read when buf was last filled |
| 123 | window []byte // current read buffer window |
| 124 | peekBuf []byte // buffer used to store data to be peeked at later |
| 125 | peekOffset int64 // total read offset of the start of the peek buffer |
| 126 | } |
| 127 | |
| 128 | func newXmlPeekReader(r io.Reader) *xmlPeekReader { |
| 129 | buf := make([]byte, 4096) |
| 130 | return &xmlPeekReader{ |
| 131 | r: r, |
| 132 | bytes: 0, |
| 133 | buf: buf, |
| 134 | bufSize: 0, |
| 135 | bufOffset: 0, |
| 136 | window: buf[0:0], |
| 137 | peekBuf: make([]byte, 0), |
| 138 | peekOffset: -1, |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | func (xr *xmlPeekReader) Bytes() int64 { |
| 143 | return xr.bytes |
| 144 | } |
| 145 | |
| 146 | func (xr *xmlPeekReader) Read(p []byte) (n int, err error) { |
| 147 | if len(xr.window) == 0 { |
| 148 | err = xr.fill() |
| 149 | if err != nil { |
| 150 | return 0, err |
| 151 | } |
| 152 | if len(xr.window) == 0 { |
| 153 | return 0, nil |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | if len(xr.window) < len(p) { |
| 158 | n = len(xr.window) |
| 159 | } else { |
| 160 | n = len(p) |
| 161 | } |
| 162 | |
| 163 | copy(p, xr.window) |
| 164 | xr.window = xr.window[n:] |
| 165 | xr.bytes += int64(n) |
| 166 | |
| 167 | return n, err |
| 168 | } |
| 169 | |
| 170 | func (xr *xmlPeekReader) PeekPrepare(offset int64, maxLen int) { |
| 171 | if maxLen > cap(xr.peekBuf) { |
| 172 | xr.peekBuf = make([]byte, 0, maxLen) |
| 173 | } |
| 174 | xr.peekBuf = xr.peekBuf[0:0] |
| 175 | xr.peekOffset = offset |
| 176 | xr.updatePeekBuf() |
| 177 | } |
| 178 | |
| 179 | func (xr *xmlPeekReader) PeekFinalize() []byte { |
| 180 | xr.updatePeekBuf() |
| 181 | return xr.peekBuf |
| 182 | } |
| 183 | |
| 184 | func (xr *xmlPeekReader) fill() error { |
| 185 | xr.bufOffset = xr.bytes |
| 186 | xr.bufSize = 0 |
| 187 | n, err := xr.r.Read(xr.buf) |
| 188 | if err != nil { |
| 189 | xr.window, xr.bufSize = xr.buf[0:0], 0 |
| 190 | return err |
| 191 | } |
| 192 | xr.window, xr.bufSize = xr.buf[:n], n |
| 193 | xr.updatePeekBuf() |
| 194 | return nil |
| 195 | } |
| 196 | |
| 197 | func (xr *xmlPeekReader) updatePeekBuf() { |
| 198 | peekRemain := cap(xr.peekBuf) - len(xr.peekBuf) |
| 199 | if xr.peekOffset >= 0 && peekRemain > 0 { |
| 200 | rangeMin := xr.peekOffset |
| 201 | rangeMax := xr.peekOffset + int64(cap(xr.peekBuf)) |
| 202 | bufMin := xr.bufOffset |
| 203 | bufMax := xr.bufOffset + int64(xr.bufSize) |
| 204 | if rangeMin < bufMin { |
| 205 | rangeMin = bufMin |
| 206 | } |
| 207 | if rangeMax > bufMax { |
| 208 | rangeMax = bufMax |
| 209 | } |
| 210 | if rangeMax > rangeMin { |
| 211 | rangeMin -= xr.bufOffset |
| 212 | rangeMax -= xr.bufOffset |
| 213 | if int(rangeMax-rangeMin) > peekRemain { |
| 214 | rangeMax = rangeMin + int64(peekRemain) |
| 215 | } |
| 216 | xr.peekBuf = append(xr.peekBuf, xr.buf[rangeMin:rangeMax]...) |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | // xmlWriter implements a proxy writer that counts the number of |
| 222 | // bytes written by its encapsulated writer. |
| 223 | type xmlWriter struct { |
| 224 | w io.Writer |
| 225 | bytes int64 |
| 226 | } |
| 227 | |
| 228 | func newXmlWriter(w io.Writer) *xmlWriter { |
| 229 | return &xmlWriter{w: w} |
| 230 | } |
| 231 | |
| 232 | func (xw *xmlWriter) Write(p []byte) (n int, err error) { |
| 233 | n, err = xw.w.Write(p) |
| 234 | xw.bytes += int64(n) |
| 235 | return n, err |
| 236 | } |
| 237 | |
| 238 | // isWhitespace returns true if the byte slice contains only |
| 239 | // whitespace characters. |
| 240 | func isWhitespace(s string) bool { |
| 241 | for i := 0; i < len(s); i++ { |
| 242 | if c := s[i]; c != ' ' && c != '\t' && c != '\n' && c != '\r' { |
| 243 | return false |
| 244 | } |
| 245 | } |
| 246 | return true |
| 247 | } |
| 248 | |
| 249 | // spaceMatch returns true if namespace a is the empty string |
| 250 | // or if namespace a equals namespace b. |
| 251 | func spaceMatch(a, b string) bool { |
| 252 | switch { |
| 253 | case a == "": |
| 254 | return true |
| 255 | default: |
| 256 | return a == b |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | // spaceDecompose breaks a namespace:tag identifier at the ':' |
| 261 | // and returns the two parts. |
| 262 | func spaceDecompose(str string) (space, key string) { |
| 263 | colon := strings.IndexByte(str, ':') |
| 264 | if colon == -1 { |
| 265 | return "", str |
| 266 | } |
| 267 | return str[:colon], str[colon+1:] |
| 268 | } |
| 269 | |
| 270 | // Strings used by indentCRLF and indentLF |
| 271 | const ( |
| 272 | indentSpaces = "\r\n " |
| 273 | indentTabs = "\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" |
| 274 | ) |
| 275 | |
| 276 | // indentCRLF returns a CRLF newline followed by n copies of the first |
| 277 | // non-CRLF character in the source string. |
| 278 | func indentCRLF(n int, source string) string { |
| 279 | switch { |
| 280 | case n < 0: |
| 281 | return source[:2] |
| 282 | case n < len(source)-1: |
| 283 | return source[:n+2] |
| 284 | default: |
| 285 | return source + strings.Repeat(source[2:3], n-len(source)+2) |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | // indentLF returns a LF newline followed by n copies of the first non-LF |
| 290 | // character in the source string. |
| 291 | func indentLF(n int, source string) string { |
| 292 | switch { |
| 293 | case n < 0: |
| 294 | return source[1:2] |
| 295 | case n < len(source)-1: |
| 296 | return source[1 : n+2] |
| 297 | default: |
| 298 | return source[1:] + strings.Repeat(source[2:3], n-len(source)+2) |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | // nextIndex returns the index of the next occurrence of byte ch in s, |
| 303 | // starting from offset. It returns -1 if the byte is not found. |
| 304 | func nextIndex(s string, ch byte, offset int) int { |
| 305 | switch i := strings.IndexByte(s[offset:], ch); i { |
| 306 | case -1: |
| 307 | return -1 |
| 308 | default: |
| 309 | return offset + i |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | // isInteger returns true if the string s contains an integer. |
| 314 | func isInteger(s string) bool { |
| 315 | for i := 0; i < len(s); i++ { |
| 316 | if (s[i] < '0' || s[i] > '9') && !(i == 0 && s[i] == '-') { |
| 317 | return false |
| 318 | } |
| 319 | } |
| 320 | return true |
| 321 | } |
| 322 | |
| 323 | type escapeMode byte |
| 324 | |
| 325 | const ( |
| 326 | escapeNormal escapeMode = iota |
| 327 | escapeCanonicalText |
| 328 | escapeCanonicalAttr |
| 329 | ) |
| 330 | |
| 331 | // escapeString writes an escaped version of a string to the writer. |
| 332 | func escapeString(w Writer, s string, m escapeMode) { |
| 333 | var esc []byte |
| 334 | last := 0 |
| 335 | for i := 0; i < len(s); { |
| 336 | r, width := utf8.DecodeRuneInString(s[i:]) |
| 337 | i += width |
| 338 | switch r { |
| 339 | case '&': |
| 340 | esc = []byte("&") |
| 341 | case '<': |
| 342 | esc = []byte("<") |
| 343 | case '>': |
| 344 | if m == escapeCanonicalAttr { |
| 345 | continue |
| 346 | } |
| 347 | esc = []byte(">") |
| 348 | case '\'': |
| 349 | if m != escapeNormal { |
| 350 | continue |
| 351 | } |
| 352 | esc = []byte("'") |
| 353 | case '"': |
| 354 | if m == escapeCanonicalText { |
| 355 | continue |
| 356 | } |
| 357 | esc = []byte(""") |
| 358 | case '\t': |
| 359 | if m != escapeCanonicalAttr { |
| 360 | continue |
| 361 | } |
| 362 | esc = []byte("	") |
| 363 | case '\n': |
| 364 | if m != escapeCanonicalAttr { |
| 365 | continue |
| 366 | } |
| 367 | esc = []byte("
") |
| 368 | case '\r': |
| 369 | if m == escapeNormal { |
| 370 | continue |
| 371 | } |
| 372 | esc = []byte("
") |
| 373 | default: |
| 374 | if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) { |
| 375 | esc = []byte("\uFFFD") |
| 376 | break |
| 377 | } |
| 378 | continue |
| 379 | } |
| 380 | w.WriteString(s[last : i-width]) |
| 381 | w.Write(esc) |
| 382 | last = i |
| 383 | } |
| 384 | w.WriteString(s[last:]) |
| 385 | } |
| 386 | |
| 387 | // sanitizeCData writes the sanitized contents of a CDATA section to the |
| 388 | // writer. XML provides no way to escape the "]]>" sequence within a CDATA |
| 389 | // section, so any occurrence of it is split across two CDATA sections. |
| 390 | func sanitizeCData(w Writer, s string) { |
| 391 | for { |
| 392 | i := strings.Index(s, "]]>") |
| 393 | if i < 0 { |
| 394 | break |
| 395 | } |
| 396 | w.WriteString(s[:i+2]) |
| 397 | w.WriteString("]]><![CDATA[") |
| 398 | s = s[i+2:] |
| 399 | } |
| 400 | w.WriteString(s) |
| 401 | } |
| 402 | |
| 403 | // sanitizeComment writes the sanitized contents of a comment to the writer. |
| 404 | // An XML comment may not contain the string "--", and it may not end with a |
| 405 | // '-'. Because XML provides no way to escape these sequences, spaces are |
| 406 | // inserted where necessary. |
| 407 | func sanitizeComment(w Writer, s string) { |
| 408 | last, hyphen := 0, false |
| 409 | for i := 0; i < len(s); i++ { |
| 410 | if s[i] != '-' { |
| 411 | hyphen = false |
| 412 | continue |
| 413 | } |
| 414 | if hyphen { |
| 415 | w.WriteString(s[last:i]) |
| 416 | w.WriteByte(' ') |
| 417 | last = i |
| 418 | } |
| 419 | hyphen = true |
| 420 | } |
| 421 | w.WriteString(s[last:]) |
| 422 | if hyphen { |
| 423 | w.WriteByte(' ') |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | // sanitizeProcInst writes the contents of a sanitized processing instruction |
| 428 | // to the writer. XML provides no way to escape the "?>" sequence within a |
| 429 | // processing instruction, so a space is inserted between the two characters. |
| 430 | func sanitizeProcInst(w Writer, s string) { |
| 431 | for { |
| 432 | i := strings.Index(s, "?>") |
| 433 | if i < 0 { |
| 434 | break |
| 435 | } |
| 436 | w.WriteString(s[:i+1]) |
| 437 | w.WriteByte(' ') |
| 438 | s = s[i+1:] |
| 439 | } |
| 440 | w.WriteString(s) |
| 441 | } |
| 442 | |
| 443 | // sanitizeDirective writes the sanitized contents of an XML directive to the |
| 444 | // writer. |
| 445 | func sanitizeDirective(w Writer, s string) { |
| 446 | // The XML decoder reserves the character following "<!" for comments |
| 447 | // ('-') and CDATA sections ('['), and it treats "<!>" as an unterminated |
| 448 | // directive. Insert a space to avoid conflicts with reserved sequences. |
| 449 | scan := s |
| 450 | if s == "" || s[0] == '-' || s[0] == '[' { |
| 451 | w.WriteByte(' ') |
| 452 | } else { |
| 453 | scan = s[1:] |
| 454 | } |
| 455 | |
| 456 | // A directive's contents may legitimately contain '<' and '>' characters, |
| 457 | // so write them without modification when they are balanced. |
| 458 | if isDirectiveBalanced(scan) { |
| 459 | w.WriteString(s) |
| 460 | return |
| 461 | } |
| 462 | |
| 463 | // The contents are unbalanced, so escape every character in the string. |
| 464 | escapeString(w, s, escapeNormal) |
| 465 | } |
| 466 | |
| 467 | // isDirectiveBalanced returns true if the interpreted portion of an XML |
| 468 | // directive's contents may be enclosed by "<!" and ">" without changing the |
| 469 | // extents of the resulting directive. |
| 470 | func isDirectiveBalanced(s string) bool { |
| 471 | var quote byte |
| 472 | var depth int |
| 473 | for i := 0; i < len(s); i++ { |
| 474 | switch c := s[i]; { |
| 475 | case quote != 0: |
| 476 | if c == quote { |
| 477 | quote = 0 |
| 478 | } |
| 479 | case c == '\'' || c == '"': |
| 480 | quote = c |
| 481 | case c == '>': |
| 482 | if depth == 0 { |
| 483 | return false |
| 484 | } |
| 485 | depth-- |
| 486 | case c == '<': |
| 487 | if !strings.HasPrefix(s[i+1:], "!--") { |
| 488 | depth++ |
| 489 | break |
| 490 | } |
| 491 | j := strings.Index(s[i+4:], "-->") |
| 492 | if j < 0 { |
| 493 | return false |
| 494 | } |
| 495 | i += 4 + j + 2 |
| 496 | } |
| 497 | } |
| 498 | return quote == 0 && depth == 0 |
| 499 | } |
| 500 | |
| 501 | func isInCharacterRange(r rune) bool { |
| 502 | return r == 0x09 || |
| 503 | r == 0x0A || |
| 504 | r == 0x0D || |
| 505 | r >= 0x20 && r <= 0xD7FF || |
| 506 | r >= 0xE000 && r <= 0xFFFD || |
| 507 | r >= 0x10000 && r <= 0x10FFFF |
| 508 | } |