github.com/vmware/govmomi@v0.51.0/vim25/xml/xml.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 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 xml implements a simple XML 1.0 parser that 6 // understands XML name spaces. 7 package xml 8 9 // References: 10 // Annotated XML spec: https://www.xml.com/axml/testaxml.htm 11 // XML name spaces: https://www.w3.org/TR/REC-xml-names/ 12 13 import ( 14 "bufio" 15 "bytes" 16 "errors" 17 "fmt" 18 "io" 19 "reflect" 20 "strconv" 21 "strings" 22 "unicode" 23 "unicode/utf8" 24 ) 25 26 // A SyntaxError represents a syntax error in the XML input stream. 27 type SyntaxError struct { 28 Msg string 29 Line int 30 } 31 32 func (e *SyntaxError) Error() string { 33 return "XML syntax error on line " + strconv.Itoa(e.Line) + ": " + e.Msg 34 } 35 36 // A Name represents an XML name (Local) annotated 37 // with a name space identifier (Space). 38 // In tokens returned by [Decoder.Token], the Space identifier 39 // is given as a canonical URL, not the short prefix used 40 // in the document being parsed. 41 type Name struct { 42 Space, Local string 43 } 44 45 // An Attr represents an attribute in an XML element (Name=Value). 46 type Attr struct { 47 Name Name 48 Value string 49 } 50 51 // A Token is an interface holding one of the token types: 52 // [StartElement], [EndElement], [CharData], [Comment], [ProcInst], or [Directive]. 53 type Token any 54 55 // A StartElement represents an XML start element. 56 type StartElement struct { 57 Name Name 58 Attr []Attr 59 } 60 61 // Copy creates a new copy of StartElement. 62 func (e StartElement) Copy() StartElement { 63 attrs := make([]Attr, len(e.Attr)) 64 copy(attrs, e.Attr) 65 e.Attr = attrs 66 return e 67 } 68 69 // End returns the corresponding XML end element. 70 func (e StartElement) End() EndElement { 71 return EndElement{e.Name} 72 } 73 74 // An EndElement represents an XML end element. 75 type EndElement struct { 76 Name Name 77 } 78 79 // A CharData represents XML character data (raw text), 80 // in which XML escape sequences have been replaced by 81 // the characters they represent. 82 type CharData []byte 83 84 // Copy creates a new copy of CharData. 85 func (c CharData) Copy() CharData { return CharData(bytes.Clone(c)) } 86 87 // A Comment represents an XML comment of the form <!--comment-->. 88 // The bytes do not include the <!-- and --> comment markers. 89 type Comment []byte 90 91 // Copy creates a new copy of Comment. 92 func (c Comment) Copy() Comment { return Comment(bytes.Clone(c)) } 93 94 // A ProcInst represents an XML processing instruction of the form <?target inst?> 95 type ProcInst struct { 96 Target string 97 Inst []byte 98 } 99 100 // Copy creates a new copy of ProcInst. 101 func (p ProcInst) Copy() ProcInst { 102 p.Inst = bytes.Clone(p.Inst) 103 return p 104 } 105 106 // A Directive represents an XML directive of the form <!text>. 107 // The bytes do not include the <! and > markers. 108 type Directive []byte 109 110 // Copy creates a new copy of Directive. 111 func (d Directive) Copy() Directive { return Directive(bytes.Clone(d)) } 112 113 // CopyToken returns a copy of a Token. 114 func CopyToken(t Token) Token { 115 switch v := t.(type) { 116 case CharData: 117 return v.Copy() 118 case Comment: 119 return v.Copy() 120 case Directive: 121 return v.Copy() 122 case ProcInst: 123 return v.Copy() 124 case StartElement: 125 return v.Copy() 126 } 127 return t 128 } 129 130 // A TokenReader is anything that can decode a stream of XML tokens, including a 131 // [Decoder]. 132 // 133 // When Token encounters an error or end-of-file condition after successfully 134 // reading a token, it returns the token. It may return the (non-nil) error from 135 // the same call or return the error (and a nil token) from a subsequent call. 136 // An instance of this general case is that a TokenReader returning a non-nil 137 // token at the end of the token stream may return either io.EOF or a nil error. 138 // The next Read should return nil, [io.EOF]. 139 // 140 // Implementations of Token are discouraged from returning a nil token with a 141 // nil error. Callers should treat a return of nil, nil as indicating that 142 // nothing happened; in particular it does not indicate EOF. 143 type TokenReader interface { 144 Token() (Token, error) 145 } 146 147 // A Decoder represents an XML parser reading a particular input stream. 148 // The parser assumes that its input is encoded in UTF-8. 149 type Decoder struct { 150 // Strict defaults to true, enforcing the requirements 151 // of the XML specification. 152 // If set to false, the parser allows input containing common 153 // mistakes: 154 // * If an element is missing an end tag, the parser invents 155 // end tags as necessary to keep the return values from Token 156 // properly balanced. 157 // * In attribute values and character data, unknown or malformed 158 // character entities (sequences beginning with &) are left alone. 159 // 160 // Setting: 161 // 162 // d.Strict = false 163 // d.AutoClose = xml.HTMLAutoClose 164 // d.Entity = xml.HTMLEntity 165 // 166 // creates a parser that can handle typical HTML. 167 // 168 // Strict mode does not enforce the requirements of the XML name spaces TR. 169 // In particular it does not reject name space tags using undefined prefixes. 170 // Such tags are recorded with the unknown prefix as the name space URL. 171 Strict bool 172 173 // When Strict == false, AutoClose indicates a set of elements to 174 // consider closed immediately after they are opened, regardless 175 // of whether an end element is present. 176 AutoClose []string 177 178 // Entity can be used to map non-standard entity names to string replacements. 179 // The parser behaves as if these standard mappings are present in the map, 180 // regardless of the actual map content: 181 // 182 // "lt": "<", 183 // "gt": ">", 184 // "amp": "&", 185 // "apos": "'", 186 // "quot": `"`, 187 Entity map[string]string 188 189 // CharsetReader, if non-nil, defines a function to generate 190 // charset-conversion readers, converting from the provided 191 // non-UTF-8 charset into UTF-8. If CharsetReader is nil or 192 // returns an error, parsing stops with an error. One of the 193 // CharsetReader's result values must be non-nil. 194 CharsetReader func(charset string, input io.Reader) (io.Reader, error) 195 196 // DefaultSpace sets the default name space used for unadorned tags, 197 // as if the entire XML stream were wrapped in an element containing 198 // the attribute xmlns="DefaultSpace". 199 DefaultSpace string 200 201 // TypeFunc is used to map type names to actual types. 202 TypeFunc func(string) (reflect.Type, bool) 203 204 r io.ByteReader 205 t TokenReader 206 buf bytes.Buffer 207 saved *bytes.Buffer 208 stk *stack 209 free *stack 210 needClose bool 211 toClose Name 212 nextToken Token 213 nextByte int 214 ns map[string]string 215 err error 216 line int 217 linestart int64 218 offset int64 219 unmarshalDepth int 220 } 221 222 // NewDecoder creates a new XML parser reading from r. 223 // If r does not implement [io.ByteReader], NewDecoder will 224 // do its own buffering. 225 func NewDecoder(r io.Reader) *Decoder { 226 d := &Decoder{ 227 ns: make(map[string]string), 228 nextByte: -1, 229 line: 1, 230 Strict: true, 231 } 232 d.switchToReader(r) 233 return d 234 } 235 236 // NewTokenDecoder creates a new XML parser using an underlying token stream. 237 func NewTokenDecoder(t TokenReader) *Decoder { 238 // Is it already a Decoder? 239 if d, ok := t.(*Decoder); ok { 240 return d 241 } 242 d := &Decoder{ 243 ns: make(map[string]string), 244 t: t, 245 nextByte: -1, 246 line: 1, 247 Strict: true, 248 } 249 return d 250 } 251 252 // Token returns the next XML token in the input stream. 253 // At the end of the input stream, Token returns nil, [io.EOF]. 254 // 255 // Slices of bytes in the returned token data refer to the 256 // parser's internal buffer and remain valid only until the next 257 // call to Token. To acquire a copy of the bytes, call [CopyToken] 258 // or the token's Copy method. 259 // 260 // Token expands self-closing elements such as <br> 261 // into separate start and end elements returned by successive calls. 262 // 263 // Token guarantees that the [StartElement] and [EndElement] 264 // tokens it returns are properly nested and matched: 265 // if Token encounters an unexpected end element 266 // or EOF before all expected end elements, 267 // it will return an error. 268 // 269 // If [Decoder.CharsetReader] is called and returns an error, 270 // the error is wrapped and returned. 271 // 272 // Token implements XML name spaces as described by 273 // https://www.w3.org/TR/REC-xml-names/. Each of the 274 // [Name] structures contained in the Token has the Space 275 // set to the URL identifying its name space when known. 276 // If Token encounters an unrecognized name space prefix, 277 // it uses the prefix as the Space rather than report an error. 278 func (d *Decoder) Token() (Token, error) { 279 var t Token 280 var err error 281 if d.stk != nil && d.stk.kind == stkEOF { 282 return nil, io.EOF 283 } 284 if d.nextToken != nil { 285 t = d.nextToken 286 d.nextToken = nil 287 } else { 288 if t, err = d.rawToken(); t == nil && err != nil { 289 if err == io.EOF && d.stk != nil && d.stk.kind != stkEOF { 290 err = d.syntaxError("unexpected EOF") 291 } 292 return nil, err 293 } 294 // We still have a token to process, so clear any 295 // errors (e.g. EOF) and proceed. 296 err = nil 297 } 298 if !d.Strict { 299 if t1, ok := d.autoClose(t); ok { 300 d.nextToken = t 301 t = t1 302 } 303 } 304 switch t1 := t.(type) { 305 case StartElement: 306 // In XML name spaces, the translations listed in the 307 // attributes apply to the element name and 308 // to the other attribute names, so process 309 // the translations first. 310 for _, a := range t1.Attr { 311 if a.Name.Space == xmlnsPrefix { 312 v, ok := d.ns[a.Name.Local] 313 d.pushNs(a.Name.Local, v, ok) 314 d.ns[a.Name.Local] = a.Value 315 } 316 if a.Name.Space == "" && a.Name.Local == xmlnsPrefix { 317 // Default space for untagged names 318 v, ok := d.ns[""] 319 d.pushNs("", v, ok) 320 d.ns[""] = a.Value 321 } 322 } 323 324 d.pushElement(t1.Name) 325 d.translate(&t1.Name, true) 326 for i := range t1.Attr { 327 d.translate(&t1.Attr[i].Name, false) 328 } 329 t = t1 330 331 case EndElement: 332 if !d.popElement(&t1) { 333 return nil, d.err 334 } 335 t = t1 336 } 337 return t, err 338 } 339 340 const ( 341 xmlURL = "http://www.w3.org/XML/1998/namespace" 342 xmlnsPrefix = "xmlns" 343 xmlPrefix = "xml" 344 ) 345 346 // Apply name space translation to name n. 347 // The default name space (for Space=="") 348 // applies only to element names, not to attribute names. 349 func (d *Decoder) translate(n *Name, isElementName bool) { 350 switch { 351 case n.Space == xmlnsPrefix: 352 return 353 case n.Space == "" && !isElementName: 354 return 355 case n.Space == xmlPrefix: 356 n.Space = xmlURL 357 case n.Space == "" && n.Local == xmlnsPrefix: 358 return 359 } 360 if v, ok := d.ns[n.Space]; ok { 361 n.Space = v 362 } else if n.Space == "" { 363 n.Space = d.DefaultSpace 364 } 365 } 366 367 func (d *Decoder) switchToReader(r io.Reader) { 368 // Get efficient byte at a time reader. 369 // Assume that if reader has its own 370 // ReadByte, it's efficient enough. 371 // Otherwise, use bufio. 372 if rb, ok := r.(io.ByteReader); ok { 373 d.r = rb 374 } else { 375 d.r = bufio.NewReader(r) 376 } 377 } 378 379 // Parsing state - stack holds old name space translations 380 // and the current set of open elements. The translations to pop when 381 // ending a given tag are *below* it on the stack, which is 382 // more work but forced on us by XML. 383 type stack struct { 384 next *stack 385 kind int 386 name Name 387 ok bool 388 } 389 390 const ( 391 stkStart = iota 392 stkNs 393 stkEOF 394 ) 395 396 func (d *Decoder) push(kind int) *stack { 397 s := d.free 398 if s != nil { 399 d.free = s.next 400 } else { 401 s = new(stack) 402 } 403 s.next = d.stk 404 s.kind = kind 405 d.stk = s 406 return s 407 } 408 409 func (d *Decoder) pop() *stack { 410 s := d.stk 411 if s != nil { 412 d.stk = s.next 413 s.next = d.free 414 d.free = s 415 } 416 return s 417 } 418 419 // Record that after the current element is finished 420 // (that element is already pushed on the stack) 421 // Token should return EOF until popEOF is called. 422 func (d *Decoder) pushEOF() { 423 // Walk down stack to find Start. 424 // It might not be the top, because there might be stkNs 425 // entries above it. 426 start := d.stk 427 for start.kind != stkStart { 428 start = start.next 429 } 430 // The stkNs entries below a start are associated with that 431 // element too; skip over them. 432 for start.next != nil && start.next.kind == stkNs { 433 start = start.next 434 } 435 s := d.free 436 if s != nil { 437 d.free = s.next 438 } else { 439 s = new(stack) 440 } 441 s.kind = stkEOF 442 s.next = start.next 443 start.next = s 444 } 445 446 // Undo a pushEOF. 447 // The element must have been finished, so the EOF should be at the top of the stack. 448 func (d *Decoder) popEOF() bool { 449 if d.stk == nil || d.stk.kind != stkEOF { 450 return false 451 } 452 d.pop() 453 return true 454 } 455 456 // Record that we are starting an element with the given name. 457 func (d *Decoder) pushElement(name Name) { 458 s := d.push(stkStart) 459 s.name = name 460 } 461 462 // Record that we are changing the value of ns[local]. 463 // The old value is url, ok. 464 func (d *Decoder) pushNs(local string, url string, ok bool) { 465 s := d.push(stkNs) 466 s.name.Local = local 467 s.name.Space = url 468 s.ok = ok 469 } 470 471 // Creates a SyntaxError with the current line number. 472 func (d *Decoder) syntaxError(msg string) error { 473 return &SyntaxError{Msg: msg, Line: d.line} 474 } 475 476 // Record that we are ending an element with the given name. 477 // The name must match the record at the top of the stack, 478 // which must be a pushElement record. 479 // After popping the element, apply any undo records from 480 // the stack to restore the name translations that existed 481 // before we saw this element. 482 func (d *Decoder) popElement(t *EndElement) bool { 483 s := d.pop() 484 name := t.Name 485 switch { 486 case s == nil || s.kind != stkStart: 487 d.err = d.syntaxError("unexpected end element </" + name.Local + ">") 488 return false 489 case s.name.Local != name.Local: 490 if !d.Strict { 491 d.needClose = true 492 d.toClose = t.Name 493 t.Name = s.name 494 return true 495 } 496 d.err = d.syntaxError("element <" + s.name.Local + "> closed by </" + name.Local + ">") 497 return false 498 case s.name.Space != name.Space: 499 ns := name.Space 500 if name.Space == "" { 501 ns = `""` 502 } 503 d.err = d.syntaxError("element <" + s.name.Local + "> in space " + s.name.Space + 504 " closed by </" + name.Local + "> in space " + ns) 505 return false 506 } 507 508 d.translate(&t.Name, true) 509 510 // Pop stack until a Start or EOF is on the top, undoing the 511 // translations that were associated with the element we just closed. 512 for d.stk != nil && d.stk.kind != stkStart && d.stk.kind != stkEOF { 513 s := d.pop() 514 if s.ok { 515 d.ns[s.name.Local] = s.name.Space 516 } else { 517 delete(d.ns, s.name.Local) 518 } 519 } 520 521 return true 522 } 523 524 // If the top element on the stack is autoclosing and 525 // t is not the end tag, invent the end tag. 526 func (d *Decoder) autoClose(t Token) (Token, bool) { 527 if d.stk == nil || d.stk.kind != stkStart { 528 return nil, false 529 } 530 for _, s := range d.AutoClose { 531 if strings.EqualFold(s, d.stk.name.Local) { 532 // This one should be auto closed if t doesn't close it. 533 et, ok := t.(EndElement) 534 if !ok || !strings.EqualFold(et.Name.Local, d.stk.name.Local) { 535 return EndElement{d.stk.name}, true 536 } 537 break 538 } 539 } 540 return nil, false 541 } 542 543 var errRawToken = errors.New("xml: cannot use RawToken from UnmarshalXML method") 544 545 // RawToken is like [Decoder.Token] but does not verify that 546 // start and end elements match and does not translate 547 // name space prefixes to their corresponding URLs. 548 func (d *Decoder) RawToken() (Token, error) { 549 if d.unmarshalDepth > 0 { 550 return nil, errRawToken 551 } 552 return d.rawToken() 553 } 554 555 func (d *Decoder) rawToken() (Token, error) { 556 if d.t != nil { 557 return d.t.Token() 558 } 559 if d.err != nil { 560 return nil, d.err 561 } 562 if d.needClose { 563 // The last element we read was self-closing and 564 // we returned just the StartElement half. 565 // Return the EndElement half now. 566 d.needClose = false 567 return EndElement{d.toClose}, nil 568 } 569 570 b, ok := d.getc() 571 if !ok { 572 return nil, d.err 573 } 574 575 if b != '<' { 576 // Text section. 577 d.ungetc(b) 578 data := d.text(-1, false) 579 if data == nil { 580 return nil, d.err 581 } 582 return CharData(data), nil 583 } 584 585 if b, ok = d.mustgetc(); !ok { 586 return nil, d.err 587 } 588 switch b { 589 case '/': 590 // </: End element 591 var name Name 592 if name, ok = d.nsname(); !ok { 593 if d.err == nil { 594 d.err = d.syntaxError("expected element name after </") 595 } 596 return nil, d.err 597 } 598 d.space() 599 if b, ok = d.mustgetc(); !ok { 600 return nil, d.err 601 } 602 if b != '>' { 603 d.err = d.syntaxError("invalid characters between </" + name.Local + " and >") 604 return nil, d.err 605 } 606 return EndElement{name}, nil 607 608 case '?': 609 // <?: Processing instruction. 610 var target string 611 if target, ok = d.name(); !ok { 612 if d.err == nil { 613 d.err = d.syntaxError("expected target name after <?") 614 } 615 return nil, d.err 616 } 617 d.space() 618 d.buf.Reset() 619 var b0 byte 620 for { 621 if b, ok = d.mustgetc(); !ok { 622 return nil, d.err 623 } 624 d.buf.WriteByte(b) 625 if b0 == '?' && b == '>' { 626 break 627 } 628 b0 = b 629 } 630 data := d.buf.Bytes() 631 data = data[0 : len(data)-2] // chop ?> 632 633 if target == "xml" { 634 content := string(data) 635 ver := procInst("version", content) 636 if ver != "" && ver != "1.0" { 637 d.err = fmt.Errorf("xml: unsupported version %q; only version 1.0 is supported", ver) 638 return nil, d.err 639 } 640 enc := procInst("encoding", content) 641 if enc != "" && enc != "utf-8" && enc != "UTF-8" && !strings.EqualFold(enc, "utf-8") { 642 if d.CharsetReader == nil { 643 d.err = fmt.Errorf("xml: encoding %q declared but Decoder.CharsetReader is nil", enc) 644 return nil, d.err 645 } 646 newr, err := d.CharsetReader(enc, d.r.(io.Reader)) 647 if err != nil { 648 d.err = fmt.Errorf("xml: opening charset %q: %w", enc, err) 649 return nil, d.err 650 } 651 if newr == nil { 652 panic("CharsetReader returned a nil Reader for charset " + enc) 653 } 654 d.switchToReader(newr) 655 } 656 } 657 return ProcInst{target, data}, nil 658 659 case '!': 660 // <!: Maybe comment, maybe CDATA. 661 if b, ok = d.mustgetc(); !ok { 662 return nil, d.err 663 } 664 switch b { 665 case '-': // <!- 666 // Probably <!-- for a comment. 667 if b, ok = d.mustgetc(); !ok { 668 return nil, d.err 669 } 670 if b != '-' { 671 d.err = d.syntaxError("invalid sequence <!- not part of <!--") 672 return nil, d.err 673 } 674 // Look for terminator. 675 d.buf.Reset() 676 var b0, b1 byte 677 for { 678 if b, ok = d.mustgetc(); !ok { 679 return nil, d.err 680 } 681 d.buf.WriteByte(b) 682 if b0 == '-' && b1 == '-' { 683 if b != '>' { 684 d.err = d.syntaxError( 685 `invalid sequence "--" not allowed in comments`) 686 return nil, d.err 687 } 688 break 689 } 690 b0, b1 = b1, b 691 } 692 data := d.buf.Bytes() 693 data = data[0 : len(data)-3] // chop --> 694 return Comment(data), nil 695 696 case '[': // <![ 697 // Probably <![CDATA[. 698 for i := 0; i < 6; i++ { 699 if b, ok = d.mustgetc(); !ok { 700 return nil, d.err 701 } 702 if b != "CDATA["[i] { 703 d.err = d.syntaxError("invalid <![ sequence") 704 return nil, d.err 705 } 706 } 707 // Have <![CDATA[. Read text until ]]>. 708 data := d.text(-1, true) 709 if data == nil { 710 return nil, d.err 711 } 712 return CharData(data), nil 713 } 714 715 // Probably a directive: <!DOCTYPE ...>, <!ENTITY ...>, etc. 716 // We don't care, but accumulate for caller. Quoted angle 717 // brackets do not count for nesting. 718 d.buf.Reset() 719 d.buf.WriteByte(b) 720 inquote := uint8(0) 721 depth := 0 722 for { 723 if b, ok = d.mustgetc(); !ok { 724 return nil, d.err 725 } 726 if inquote == 0 && b == '>' && depth == 0 { 727 break 728 } 729 HandleB: 730 d.buf.WriteByte(b) 731 switch { 732 case b == inquote: 733 inquote = 0 734 735 case inquote != 0: 736 // in quotes, no special action 737 738 case b == '\'' || b == '"': 739 inquote = b 740 741 case b == '>' && inquote == 0: 742 depth-- 743 744 case b == '<' && inquote == 0: 745 // Look for <!-- to begin comment. 746 s := "!--" 747 for i := 0; i < len(s); i++ { 748 if b, ok = d.mustgetc(); !ok { 749 return nil, d.err 750 } 751 if b != s[i] { 752 for j := 0; j < i; j++ { 753 d.buf.WriteByte(s[j]) 754 } 755 depth++ 756 goto HandleB 757 } 758 } 759 760 // Remove < that was written above. 761 d.buf.Truncate(d.buf.Len() - 1) 762 763 // Look for terminator. 764 var b0, b1 byte 765 for { 766 if b, ok = d.mustgetc(); !ok { 767 return nil, d.err 768 } 769 if b0 == '-' && b1 == '-' && b == '>' { 770 break 771 } 772 b0, b1 = b1, b 773 } 774 775 // Replace the comment with a space in the returned Directive 776 // body, so that markup parts that were separated by the comment 777 // (like a "<" and a "!") don't get joined when re-encoding the 778 // Directive, taking new semantic meaning. 779 d.buf.WriteByte(' ') 780 } 781 } 782 return Directive(d.buf.Bytes()), nil 783 } 784 785 // Must be an open element like <a href="foo"> 786 d.ungetc(b) 787 788 var ( 789 name Name 790 empty bool 791 attr []Attr 792 ) 793 if name, ok = d.nsname(); !ok { 794 if d.err == nil { 795 d.err = d.syntaxError("expected element name after <") 796 } 797 return nil, d.err 798 } 799 800 attr = []Attr{} 801 for { 802 d.space() 803 if b, ok = d.mustgetc(); !ok { 804 return nil, d.err 805 } 806 if b == '/' { 807 empty = true 808 if b, ok = d.mustgetc(); !ok { 809 return nil, d.err 810 } 811 if b != '>' { 812 d.err = d.syntaxError("expected /> in element") 813 return nil, d.err 814 } 815 break 816 } 817 if b == '>' { 818 break 819 } 820 d.ungetc(b) 821 822 a := Attr{} 823 if a.Name, ok = d.nsname(); !ok { 824 if d.err == nil { 825 d.err = d.syntaxError("expected attribute name in element") 826 } 827 return nil, d.err 828 } 829 d.space() 830 if b, ok = d.mustgetc(); !ok { 831 return nil, d.err 832 } 833 if b != '=' { 834 if d.Strict { 835 d.err = d.syntaxError("attribute name without = in element") 836 return nil, d.err 837 } 838 d.ungetc(b) 839 a.Value = a.Name.Local 840 } else { 841 d.space() 842 data := d.attrval() 843 if data == nil { 844 return nil, d.err 845 } 846 a.Value = string(data) 847 } 848 attr = append(attr, a) 849 } 850 if empty { 851 d.needClose = true 852 d.toClose = name 853 } 854 return StartElement{name, attr}, nil 855 } 856 857 func (d *Decoder) attrval() []byte { 858 b, ok := d.mustgetc() 859 if !ok { 860 return nil 861 } 862 // Handle quoted attribute values 863 if b == '"' || b == '\'' { 864 return d.text(int(b), false) 865 } 866 // Handle unquoted attribute values for strict parsers 867 if d.Strict { 868 d.err = d.syntaxError("unquoted or missing attribute value in element") 869 return nil 870 } 871 // Handle unquoted attribute values for unstrict parsers 872 d.ungetc(b) 873 d.buf.Reset() 874 for { 875 b, ok = d.mustgetc() 876 if !ok { 877 return nil 878 } 879 // https://www.w3.org/TR/REC-html40/intro/sgmltut.html#h-3.2.2 880 if 'a' <= b && b <= 'z' || 'A' <= b && b <= 'Z' || 881 '0' <= b && b <= '9' || b == '_' || b == ':' || b == '-' { 882 d.buf.WriteByte(b) 883 } else { 884 d.ungetc(b) 885 break 886 } 887 } 888 return d.buf.Bytes() 889 } 890 891 // Skip spaces if any 892 func (d *Decoder) space() { 893 for { 894 b, ok := d.getc() 895 if !ok { 896 return 897 } 898 switch b { 899 case ' ', '\r', '\n', '\t': 900 default: 901 d.ungetc(b) 902 return 903 } 904 } 905 } 906 907 // Read a single byte. 908 // If there is no byte to read, return ok==false 909 // and leave the error in d.err. 910 // Maintain line number. 911 func (d *Decoder) getc() (b byte, ok bool) { 912 if d.err != nil { 913 return 0, false 914 } 915 if d.nextByte >= 0 { 916 b = byte(d.nextByte) 917 d.nextByte = -1 918 } else { 919 b, d.err = d.r.ReadByte() 920 if d.err != nil { 921 return 0, false 922 } 923 if d.saved != nil { 924 d.saved.WriteByte(b) 925 } 926 } 927 if b == '\n' { 928 d.line++ 929 d.linestart = d.offset + 1 930 } 931 d.offset++ 932 return b, true 933 } 934 935 // InputOffset returns the input stream byte offset of the current decoder position. 936 // The offset gives the location of the end of the most recently returned token 937 // and the beginning of the next token. 938 func (d *Decoder) InputOffset() int64 { 939 return d.offset 940 } 941 942 // InputPos returns the line of the current decoder position and the 1 based 943 // input position of the line. The position gives the location of the end of the 944 // most recently returned token. 945 func (d *Decoder) InputPos() (line, column int) { 946 return d.line, int(d.offset-d.linestart) + 1 947 } 948 949 // Return saved offset. 950 // If we did ungetc (nextByte >= 0), have to back up one. 951 func (d *Decoder) savedOffset() int { 952 n := d.saved.Len() 953 if d.nextByte >= 0 { 954 n-- 955 } 956 return n 957 } 958 959 // Must read a single byte. 960 // If there is no byte to read, 961 // set d.err to SyntaxError("unexpected EOF") 962 // and return ok==false 963 func (d *Decoder) mustgetc() (b byte, ok bool) { 964 if b, ok = d.getc(); !ok { 965 if d.err == io.EOF { 966 d.err = d.syntaxError("unexpected EOF") 967 } 968 } 969 return 970 } 971 972 // Unread a single byte. 973 func (d *Decoder) ungetc(b byte) { 974 if b == '\n' { 975 d.line-- 976 } 977 d.nextByte = int(b) 978 d.offset-- 979 } 980 981 var entity = map[string]rune{ 982 "lt": '<', 983 "gt": '>', 984 "amp": '&', 985 "apos": '\'', 986 "quot": '"', 987 } 988 989 // Read plain text section (XML calls it character data). 990 // If quote >= 0, we are in a quoted string and need to find the matching quote. 991 // If cdata == true, we are in a <![CDATA[ section and need to find ]]>. 992 // On failure return nil and leave the error in d.err. 993 func (d *Decoder) text(quote int, cdata bool) []byte { 994 var b0, b1 byte 995 var trunc int 996 d.buf.Reset() 997 Input: 998 for { 999 b, ok := d.getc() 1000 if !ok { 1001 if cdata { 1002 if d.err == io.EOF { 1003 d.err = d.syntaxError("unexpected EOF in CDATA section") 1004 } 1005 return nil 1006 } 1007 break Input 1008 } 1009 1010 // <![CDATA[ section ends with ]]>. 1011 // It is an error for ]]> to appear in ordinary text, 1012 // but it is allowed in quoted strings. 1013 if quote < 0 && b0 == ']' && b1 == ']' && b == '>' { 1014 if cdata { 1015 trunc = 2 1016 break Input 1017 } 1018 d.err = d.syntaxError("unescaped ]]> not in CDATA section") 1019 return nil 1020 } 1021 1022 // Stop reading text if we see a <. 1023 if b == '<' && !cdata { 1024 if quote >= 0 { 1025 d.err = d.syntaxError("unescaped < inside quoted string") 1026 return nil 1027 } 1028 d.ungetc('<') 1029 break Input 1030 } 1031 if quote >= 0 && b == byte(quote) { 1032 break Input 1033 } 1034 if b == '&' && !cdata { 1035 // Read escaped character expression up to semicolon. 1036 // XML in all its glory allows a document to define and use 1037 // its own character names with <!ENTITY ...> directives. 1038 // Parsers are required to recognize lt, gt, amp, apos, and quot 1039 // even if they have not been declared. 1040 before := d.buf.Len() 1041 d.buf.WriteByte('&') 1042 var ok bool 1043 var text string 1044 var haveText bool 1045 if b, ok = d.mustgetc(); !ok { 1046 return nil 1047 } 1048 if b == '#' { 1049 d.buf.WriteByte(b) 1050 if b, ok = d.mustgetc(); !ok { 1051 return nil 1052 } 1053 base := 10 1054 if b == 'x' { 1055 base = 16 1056 d.buf.WriteByte(b) 1057 if b, ok = d.mustgetc(); !ok { 1058 return nil 1059 } 1060 } 1061 start := d.buf.Len() 1062 for '0' <= b && b <= '9' || 1063 base == 16 && 'a' <= b && b <= 'f' || 1064 base == 16 && 'A' <= b && b <= 'F' { 1065 d.buf.WriteByte(b) 1066 if b, ok = d.mustgetc(); !ok { 1067 return nil 1068 } 1069 } 1070 if b != ';' { 1071 d.ungetc(b) 1072 } else { 1073 s := string(d.buf.Bytes()[start:]) 1074 d.buf.WriteByte(';') 1075 n, err := strconv.ParseUint(s, base, 64) 1076 if err == nil && n <= unicode.MaxRune { 1077 text = string(rune(n)) 1078 haveText = true 1079 } 1080 } 1081 } else { 1082 d.ungetc(b) 1083 if !d.readName() { 1084 if d.err != nil { 1085 return nil 1086 } 1087 } 1088 if b, ok = d.mustgetc(); !ok { 1089 return nil 1090 } 1091 if b != ';' { 1092 d.ungetc(b) 1093 } else { 1094 name := d.buf.Bytes()[before+1:] 1095 d.buf.WriteByte(';') 1096 if isName(name) { 1097 s := string(name) 1098 if r, ok := entity[s]; ok { 1099 text = string(r) 1100 haveText = true 1101 } else if d.Entity != nil { 1102 text, haveText = d.Entity[s] 1103 } 1104 } 1105 } 1106 } 1107 1108 if haveText { 1109 d.buf.Truncate(before) 1110 d.buf.WriteString(text) 1111 b0, b1 = 0, 0 1112 continue Input 1113 } 1114 if !d.Strict { 1115 b0, b1 = 0, 0 1116 continue Input 1117 } 1118 ent := string(d.buf.Bytes()[before:]) 1119 if ent[len(ent)-1] != ';' { 1120 ent += " (no semicolon)" 1121 } 1122 d.err = d.syntaxError("invalid character entity " + ent) 1123 return nil 1124 } 1125 1126 // We must rewrite unescaped \r and \r\n into \n. 1127 if b == '\r' { 1128 d.buf.WriteByte('\n') 1129 } else if b1 == '\r' && b == '\n' { 1130 // Skip \r\n--we already wrote \n. 1131 } else { 1132 d.buf.WriteByte(b) 1133 } 1134 1135 b0, b1 = b1, b 1136 } 1137 data := d.buf.Bytes() 1138 data = data[0 : len(data)-trunc] 1139 1140 // Inspect each rune for being a disallowed character. 1141 buf := data 1142 for len(buf) > 0 { 1143 r, size := utf8.DecodeRune(buf) 1144 if r == utf8.RuneError && size == 1 { 1145 d.err = d.syntaxError("invalid UTF-8") 1146 return nil 1147 } 1148 buf = buf[size:] 1149 if !isInCharacterRange(r) { 1150 d.err = d.syntaxError(fmt.Sprintf("illegal character code %U", r)) 1151 return nil 1152 } 1153 } 1154 1155 return data 1156 } 1157 1158 // Decide whether the given rune is in the XML Character Range, per 1159 // the Char production of https://www.xml.com/axml/testaxml.htm, 1160 // Section 2.2 Characters. 1161 func isInCharacterRange(r rune) (inrange bool) { 1162 return r == 0x09 || 1163 r == 0x0A || 1164 r == 0x0D || 1165 r >= 0x20 && r <= 0xD7FF || 1166 r >= 0xE000 && r <= 0xFFFD || 1167 r >= 0x10000 && r <= 0x10FFFF 1168 } 1169 1170 // Get name space name: name with a : stuck in the middle. 1171 // The part before the : is the name space identifier. 1172 func (d *Decoder) nsname() (name Name, ok bool) { 1173 s, ok := d.name() 1174 if !ok { 1175 return 1176 } 1177 if strings.Count(s, ":") > 1 { 1178 return name, false 1179 } else if space, local, ok := strings.Cut(s, ":"); !ok || space == "" || local == "" { 1180 name.Local = s 1181 } else { 1182 name.Space = space 1183 name.Local = local 1184 } 1185 return name, true 1186 } 1187 1188 // Get name: /first(first|second)*/ 1189 // Do not set d.err if the name is missing (unless unexpected EOF is received): 1190 // let the caller provide better context. 1191 func (d *Decoder) name() (s string, ok bool) { 1192 d.buf.Reset() 1193 if !d.readName() { 1194 return "", false 1195 } 1196 1197 // Now we check the characters. 1198 b := d.buf.Bytes() 1199 if !isName(b) { 1200 d.err = d.syntaxError("invalid XML name: " + string(b)) 1201 return "", false 1202 } 1203 return string(b), true 1204 } 1205 1206 // Read a name and append its bytes to d.buf. 1207 // The name is delimited by any single-byte character not valid in names. 1208 // All multi-byte characters are accepted; the caller must check their validity. 1209 func (d *Decoder) readName() (ok bool) { 1210 var b byte 1211 if b, ok = d.mustgetc(); !ok { 1212 return 1213 } 1214 if b < utf8.RuneSelf && !isNameByte(b) { 1215 d.ungetc(b) 1216 return false 1217 } 1218 d.buf.WriteByte(b) 1219 1220 for { 1221 if b, ok = d.mustgetc(); !ok { 1222 return 1223 } 1224 if b < utf8.RuneSelf && !isNameByte(b) { 1225 d.ungetc(b) 1226 break 1227 } 1228 d.buf.WriteByte(b) 1229 } 1230 return true 1231 } 1232 1233 func isNameByte(c byte) bool { 1234 return 'A' <= c && c <= 'Z' || 1235 'a' <= c && c <= 'z' || 1236 '0' <= c && c <= '9' || 1237 c == '_' || c == ':' || c == '.' || c == '-' 1238 } 1239 1240 func isName(s []byte) bool { 1241 if len(s) == 0 { 1242 return false 1243 } 1244 c, n := utf8.DecodeRune(s) 1245 if c == utf8.RuneError && n == 1 { 1246 return false 1247 } 1248 if !unicode.Is(first, c) { 1249 return false 1250 } 1251 for n < len(s) { 1252 s = s[n:] 1253 c, n = utf8.DecodeRune(s) 1254 if c == utf8.RuneError && n == 1 { 1255 return false 1256 } 1257 if !unicode.Is(first, c) && !unicode.Is(second, c) { 1258 return false 1259 } 1260 } 1261 return true 1262 } 1263 1264 func isNameString(s string) bool { 1265 if len(s) == 0 { 1266 return false 1267 } 1268 c, n := utf8.DecodeRuneInString(s) 1269 if c == utf8.RuneError && n == 1 { 1270 return false 1271 } 1272 if !unicode.Is(first, c) { 1273 return false 1274 } 1275 for n < len(s) { 1276 s = s[n:] 1277 c, n = utf8.DecodeRuneInString(s) 1278 if c == utf8.RuneError && n == 1 { 1279 return false 1280 } 1281 if !unicode.Is(first, c) && !unicode.Is(second, c) { 1282 return false 1283 } 1284 } 1285 return true 1286 } 1287 1288 // These tables were generated by cut and paste from Appendix B of 1289 // the XML spec at https://www.xml.com/axml/testaxml.htm 1290 // and then reformatting. First corresponds to (Letter | '_' | ':') 1291 // and second corresponds to NameChar. 1292 1293 var first = &unicode.RangeTable{ 1294 R16: []unicode.Range16{ 1295 {0x003A, 0x003A, 1}, 1296 {0x0041, 0x005A, 1}, 1297 {0x005F, 0x005F, 1}, 1298 {0x0061, 0x007A, 1}, 1299 {0x00C0, 0x00D6, 1}, 1300 {0x00D8, 0x00F6, 1}, 1301 {0x00F8, 0x00FF, 1}, 1302 {0x0100, 0x0131, 1}, 1303 {0x0134, 0x013E, 1}, 1304 {0x0141, 0x0148, 1}, 1305 {0x014A, 0x017E, 1}, 1306 {0x0180, 0x01C3, 1}, 1307 {0x01CD, 0x01F0, 1}, 1308 {0x01F4, 0x01F5, 1}, 1309 {0x01FA, 0x0217, 1}, 1310 {0x0250, 0x02A8, 1}, 1311 {0x02BB, 0x02C1, 1}, 1312 {0x0386, 0x0386, 1}, 1313 {0x0388, 0x038A, 1}, 1314 {0x038C, 0x038C, 1}, 1315 {0x038E, 0x03A1, 1}, 1316 {0x03A3, 0x03CE, 1}, 1317 {0x03D0, 0x03D6, 1}, 1318 {0x03DA, 0x03E0, 2}, 1319 {0x03E2, 0x03F3, 1}, 1320 {0x0401, 0x040C, 1}, 1321 {0x040E, 0x044F, 1}, 1322 {0x0451, 0x045C, 1}, 1323 {0x045E, 0x0481, 1}, 1324 {0x0490, 0x04C4, 1}, 1325 {0x04C7, 0x04C8, 1}, 1326 {0x04CB, 0x04CC, 1}, 1327 {0x04D0, 0x04EB, 1}, 1328 {0x04EE, 0x04F5, 1}, 1329 {0x04F8, 0x04F9, 1}, 1330 {0x0531, 0x0556, 1}, 1331 {0x0559, 0x0559, 1}, 1332 {0x0561, 0x0586, 1}, 1333 {0x05D0, 0x05EA, 1}, 1334 {0x05F0, 0x05F2, 1}, 1335 {0x0621, 0x063A, 1}, 1336 {0x0641, 0x064A, 1}, 1337 {0x0671, 0x06B7, 1}, 1338 {0x06BA, 0x06BE, 1}, 1339 {0x06C0, 0x06CE, 1}, 1340 {0x06D0, 0x06D3, 1}, 1341 {0x06D5, 0x06D5, 1}, 1342 {0x06E5, 0x06E6, 1}, 1343 {0x0905, 0x0939, 1}, 1344 {0x093D, 0x093D, 1}, 1345 {0x0958, 0x0961, 1}, 1346 {0x0985, 0x098C, 1}, 1347 {0x098F, 0x0990, 1}, 1348 {0x0993, 0x09A8, 1}, 1349 {0x09AA, 0x09B0, 1}, 1350 {0x09B2, 0x09B2, 1}, 1351 {0x09B6, 0x09B9, 1}, 1352 {0x09DC, 0x09DD, 1}, 1353 {0x09DF, 0x09E1, 1}, 1354 {0x09F0, 0x09F1, 1}, 1355 {0x0A05, 0x0A0A, 1}, 1356 {0x0A0F, 0x0A10, 1}, 1357 {0x0A13, 0x0A28, 1}, 1358 {0x0A2A, 0x0A30, 1}, 1359 {0x0A32, 0x0A33, 1}, 1360 {0x0A35, 0x0A36, 1}, 1361 {0x0A38, 0x0A39, 1}, 1362 {0x0A59, 0x0A5C, 1}, 1363 {0x0A5E, 0x0A5E, 1}, 1364 {0x0A72, 0x0A74, 1}, 1365 {0x0A85, 0x0A8B, 1}, 1366 {0x0A8D, 0x0A8D, 1}, 1367 {0x0A8F, 0x0A91, 1}, 1368 {0x0A93, 0x0AA8, 1}, 1369 {0x0AAA, 0x0AB0, 1}, 1370 {0x0AB2, 0x0AB3, 1}, 1371 {0x0AB5, 0x0AB9, 1}, 1372 {0x0ABD, 0x0AE0, 0x23}, 1373 {0x0B05, 0x0B0C, 1}, 1374 {0x0B0F, 0x0B10, 1}, 1375 {0x0B13, 0x0B28, 1}, 1376 {0x0B2A, 0x0B30, 1}, 1377 {0x0B32, 0x0B33, 1}, 1378 {0x0B36, 0x0B39, 1}, 1379 {0x0B3D, 0x0B3D, 1}, 1380 {0x0B5C, 0x0B5D, 1}, 1381 {0x0B5F, 0x0B61, 1}, 1382 {0x0B85, 0x0B8A, 1}, 1383 {0x0B8E, 0x0B90, 1}, 1384 {0x0B92, 0x0B95, 1}, 1385 {0x0B99, 0x0B9A, 1}, 1386 {0x0B9C, 0x0B9C, 1}, 1387 {0x0B9E, 0x0B9F, 1}, 1388 {0x0BA3, 0x0BA4, 1}, 1389 {0x0BA8, 0x0BAA, 1}, 1390 {0x0BAE, 0x0BB5, 1}, 1391 {0x0BB7, 0x0BB9, 1}, 1392 {0x0C05, 0x0C0C, 1}, 1393 {0x0C0E, 0x0C10, 1}, 1394 {0x0C12, 0x0C28, 1}, 1395 {0x0C2A, 0x0C33, 1}, 1396 {0x0C35, 0x0C39, 1}, 1397 {0x0C60, 0x0C61, 1}, 1398 {0x0C85, 0x0C8C, 1}, 1399 {0x0C8E, 0x0C90, 1}, 1400 {0x0C92, 0x0CA8, 1}, 1401 {0x0CAA, 0x0CB3, 1}, 1402 {0x0CB5, 0x0CB9, 1}, 1403 {0x0CDE, 0x0CDE, 1}, 1404 {0x0CE0, 0x0CE1, 1}, 1405 {0x0D05, 0x0D0C, 1}, 1406 {0x0D0E, 0x0D10, 1}, 1407 {0x0D12, 0x0D28, 1}, 1408 {0x0D2A, 0x0D39, 1}, 1409 {0x0D60, 0x0D61, 1}, 1410 {0x0E01, 0x0E2E, 1}, 1411 {0x0E30, 0x0E30, 1}, 1412 {0x0E32, 0x0E33, 1}, 1413 {0x0E40, 0x0E45, 1}, 1414 {0x0E81, 0x0E82, 1}, 1415 {0x0E84, 0x0E84, 1}, 1416 {0x0E87, 0x0E88, 1}, 1417 {0x0E8A, 0x0E8D, 3}, 1418 {0x0E94, 0x0E97, 1}, 1419 {0x0E99, 0x0E9F, 1}, 1420 {0x0EA1, 0x0EA3, 1}, 1421 {0x0EA5, 0x0EA7, 2}, 1422 {0x0EAA, 0x0EAB, 1}, 1423 {0x0EAD, 0x0EAE, 1}, 1424 {0x0EB0, 0x0EB0, 1}, 1425 {0x0EB2, 0x0EB3, 1}, 1426 {0x0EBD, 0x0EBD, 1}, 1427 {0x0EC0, 0x0EC4, 1}, 1428 {0x0F40, 0x0F47, 1}, 1429 {0x0F49, 0x0F69, 1}, 1430 {0x10A0, 0x10C5, 1}, 1431 {0x10D0, 0x10F6, 1}, 1432 {0x1100, 0x1100, 1}, 1433 {0x1102, 0x1103, 1}, 1434 {0x1105, 0x1107, 1}, 1435 {0x1109, 0x1109, 1}, 1436 {0x110B, 0x110C, 1}, 1437 {0x110E, 0x1112, 1}, 1438 {0x113C, 0x1140, 2}, 1439 {0x114C, 0x1150, 2}, 1440 {0x1154, 0x1155, 1}, 1441 {0x1159, 0x1159, 1}, 1442 {0x115F, 0x1161, 1}, 1443 {0x1163, 0x1169, 2}, 1444 {0x116D, 0x116E, 1}, 1445 {0x1172, 0x1173, 1}, 1446 {0x1175, 0x119E, 0x119E - 0x1175}, 1447 {0x11A8, 0x11AB, 0x11AB - 0x11A8}, 1448 {0x11AE, 0x11AF, 1}, 1449 {0x11B7, 0x11B8, 1}, 1450 {0x11BA, 0x11BA, 1}, 1451 {0x11BC, 0x11C2, 1}, 1452 {0x11EB, 0x11F0, 0x11F0 - 0x11EB}, 1453 {0x11F9, 0x11F9, 1}, 1454 {0x1E00, 0x1E9B, 1}, 1455 {0x1EA0, 0x1EF9, 1}, 1456 {0x1F00, 0x1F15, 1}, 1457 {0x1F18, 0x1F1D, 1}, 1458 {0x1F20, 0x1F45, 1}, 1459 {0x1F48, 0x1F4D, 1}, 1460 {0x1F50, 0x1F57, 1}, 1461 {0x1F59, 0x1F5B, 0x1F5B - 0x1F59}, 1462 {0x1F5D, 0x1F5D, 1}, 1463 {0x1F5F, 0x1F7D, 1}, 1464 {0x1F80, 0x1FB4, 1}, 1465 {0x1FB6, 0x1FBC, 1}, 1466 {0x1FBE, 0x1FBE, 1}, 1467 {0x1FC2, 0x1FC4, 1}, 1468 {0x1FC6, 0x1FCC, 1}, 1469 {0x1FD0, 0x1FD3, 1}, 1470 {0x1FD6, 0x1FDB, 1}, 1471 {0x1FE0, 0x1FEC, 1}, 1472 {0x1FF2, 0x1FF4, 1}, 1473 {0x1FF6, 0x1FFC, 1}, 1474 {0x2126, 0x2126, 1}, 1475 {0x212A, 0x212B, 1}, 1476 {0x212E, 0x212E, 1}, 1477 {0x2180, 0x2182, 1}, 1478 {0x3007, 0x3007, 1}, 1479 {0x3021, 0x3029, 1}, 1480 {0x3041, 0x3094, 1}, 1481 {0x30A1, 0x30FA, 1}, 1482 {0x3105, 0x312C, 1}, 1483 {0x4E00, 0x9FA5, 1}, 1484 {0xAC00, 0xD7A3, 1}, 1485 }, 1486 } 1487 1488 var second = &unicode.RangeTable{ 1489 R16: []unicode.Range16{ 1490 {0x002D, 0x002E, 1}, 1491 {0x0030, 0x0039, 1}, 1492 {0x00B7, 0x00B7, 1}, 1493 {0x02D0, 0x02D1, 1}, 1494 {0x0300, 0x0345, 1}, 1495 {0x0360, 0x0361, 1}, 1496 {0x0387, 0x0387, 1}, 1497 {0x0483, 0x0486, 1}, 1498 {0x0591, 0x05A1, 1}, 1499 {0x05A3, 0x05B9, 1}, 1500 {0x05BB, 0x05BD, 1}, 1501 {0x05BF, 0x05BF, 1}, 1502 {0x05C1, 0x05C2, 1}, 1503 {0x05C4, 0x0640, 0x0640 - 0x05C4}, 1504 {0x064B, 0x0652, 1}, 1505 {0x0660, 0x0669, 1}, 1506 {0x0670, 0x0670, 1}, 1507 {0x06D6, 0x06DC, 1}, 1508 {0x06DD, 0x06DF, 1}, 1509 {0x06E0, 0x06E4, 1}, 1510 {0x06E7, 0x06E8, 1}, 1511 {0x06EA, 0x06ED, 1}, 1512 {0x06F0, 0x06F9, 1}, 1513 {0x0901, 0x0903, 1}, 1514 {0x093C, 0x093C, 1}, 1515 {0x093E, 0x094C, 1}, 1516 {0x094D, 0x094D, 1}, 1517 {0x0951, 0x0954, 1}, 1518 {0x0962, 0x0963, 1}, 1519 {0x0966, 0x096F, 1}, 1520 {0x0981, 0x0983, 1}, 1521 {0x09BC, 0x09BC, 1}, 1522 {0x09BE, 0x09BF, 1}, 1523 {0x09C0, 0x09C4, 1}, 1524 {0x09C7, 0x09C8, 1}, 1525 {0x09CB, 0x09CD, 1}, 1526 {0x09D7, 0x09D7, 1}, 1527 {0x09E2, 0x09E3, 1}, 1528 {0x09E6, 0x09EF, 1}, 1529 {0x0A02, 0x0A3C, 0x3A}, 1530 {0x0A3E, 0x0A3F, 1}, 1531 {0x0A40, 0x0A42, 1}, 1532 {0x0A47, 0x0A48, 1}, 1533 {0x0A4B, 0x0A4D, 1}, 1534 {0x0A66, 0x0A6F, 1}, 1535 {0x0A70, 0x0A71, 1}, 1536 {0x0A81, 0x0A83, 1}, 1537 {0x0ABC, 0x0ABC, 1}, 1538 {0x0ABE, 0x0AC5, 1}, 1539 {0x0AC7, 0x0AC9, 1}, 1540 {0x0ACB, 0x0ACD, 1}, 1541 {0x0AE6, 0x0AEF, 1}, 1542 {0x0B01, 0x0B03, 1}, 1543 {0x0B3C, 0x0B3C, 1}, 1544 {0x0B3E, 0x0B43, 1}, 1545 {0x0B47, 0x0B48, 1}, 1546 {0x0B4B, 0x0B4D, 1}, 1547 {0x0B56, 0x0B57, 1}, 1548 {0x0B66, 0x0B6F, 1}, 1549 {0x0B82, 0x0B83, 1}, 1550 {0x0BBE, 0x0BC2, 1}, 1551 {0x0BC6, 0x0BC8, 1}, 1552 {0x0BCA, 0x0BCD, 1}, 1553 {0x0BD7, 0x0BD7, 1}, 1554 {0x0BE7, 0x0BEF, 1}, 1555 {0x0C01, 0x0C03, 1}, 1556 {0x0C3E, 0x0C44, 1}, 1557 {0x0C46, 0x0C48, 1}, 1558 {0x0C4A, 0x0C4D, 1}, 1559 {0x0C55, 0x0C56, 1}, 1560 {0x0C66, 0x0C6F, 1}, 1561 {0x0C82, 0x0C83, 1}, 1562 {0x0CBE, 0x0CC4, 1}, 1563 {0x0CC6, 0x0CC8, 1}, 1564 {0x0CCA, 0x0CCD, 1}, 1565 {0x0CD5, 0x0CD6, 1}, 1566 {0x0CE6, 0x0CEF, 1}, 1567 {0x0D02, 0x0D03, 1}, 1568 {0x0D3E, 0x0D43, 1}, 1569 {0x0D46, 0x0D48, 1}, 1570 {0x0D4A, 0x0D4D, 1}, 1571 {0x0D57, 0x0D57, 1}, 1572 {0x0D66, 0x0D6F, 1}, 1573 {0x0E31, 0x0E31, 1}, 1574 {0x0E34, 0x0E3A, 1}, 1575 {0x0E46, 0x0E46, 1}, 1576 {0x0E47, 0x0E4E, 1}, 1577 {0x0E50, 0x0E59, 1}, 1578 {0x0EB1, 0x0EB1, 1}, 1579 {0x0EB4, 0x0EB9, 1}, 1580 {0x0EBB, 0x0EBC, 1}, 1581 {0x0EC6, 0x0EC6, 1}, 1582 {0x0EC8, 0x0ECD, 1}, 1583 {0x0ED0, 0x0ED9, 1}, 1584 {0x0F18, 0x0F19, 1}, 1585 {0x0F20, 0x0F29, 1}, 1586 {0x0F35, 0x0F39, 2}, 1587 {0x0F3E, 0x0F3F, 1}, 1588 {0x0F71, 0x0F84, 1}, 1589 {0x0F86, 0x0F8B, 1}, 1590 {0x0F90, 0x0F95, 1}, 1591 {0x0F97, 0x0F97, 1}, 1592 {0x0F99, 0x0FAD, 1}, 1593 {0x0FB1, 0x0FB7, 1}, 1594 {0x0FB9, 0x0FB9, 1}, 1595 {0x20D0, 0x20DC, 1}, 1596 {0x20E1, 0x3005, 0x3005 - 0x20E1}, 1597 {0x302A, 0x302F, 1}, 1598 {0x3031, 0x3035, 1}, 1599 {0x3099, 0x309A, 1}, 1600 {0x309D, 0x309E, 1}, 1601 {0x30FC, 0x30FE, 1}, 1602 }, 1603 } 1604 1605 // HTMLEntity is an entity map containing translations for the 1606 // standard HTML entity characters. 1607 // 1608 // See the [Decoder.Strict] and [Decoder.Entity] fields' documentation. 1609 var HTMLEntity map[string]string = htmlEntity 1610 1611 var htmlEntity = map[string]string{ 1612 /* 1613 hget http://www.w3.org/TR/html4/sgml/entities.html | 1614 ssam ' 1615 ,y /\>/ x/\<(.|\n)+/ s/\n/ /g 1616 ,x v/^\<!ENTITY/d 1617 ,s/\<!ENTITY ([^ ]+) .*U\+([0-9A-F][0-9A-F][0-9A-F][0-9A-F]) .+/ "\1": "\\u\2",/g 1618 ' 1619 */ 1620 "nbsp": "\u00A0", 1621 "iexcl": "\u00A1", 1622 "cent": "\u00A2", 1623 "pound": "\u00A3", 1624 "curren": "\u00A4", 1625 "yen": "\u00A5", 1626 "brvbar": "\u00A6", 1627 "sect": "\u00A7", 1628 "uml": "\u00A8", 1629 "copy": "\u00A9", 1630 "ordf": "\u00AA", 1631 "laquo": "\u00AB", 1632 "not": "\u00AC", 1633 "shy": "\u00AD", 1634 "reg": "\u00AE", 1635 "macr": "\u00AF", 1636 "deg": "\u00B0", 1637 "plusmn": "\u00B1", 1638 "sup2": "\u00B2", 1639 "sup3": "\u00B3", 1640 "acute": "\u00B4", 1641 "micro": "\u00B5", 1642 "para": "\u00B6", 1643 "middot": "\u00B7", 1644 "cedil": "\u00B8", 1645 "sup1": "\u00B9", 1646 "ordm": "\u00BA", 1647 "raquo": "\u00BB", 1648 "frac14": "\u00BC", 1649 "frac12": "\u00BD", 1650 "frac34": "\u00BE", 1651 "iquest": "\u00BF", 1652 "Agrave": "\u00C0", 1653 "Aacute": "\u00C1", 1654 "Acirc": "\u00C2", 1655 "Atilde": "\u00C3", 1656 "Auml": "\u00C4", 1657 "Aring": "\u00C5", 1658 "AElig": "\u00C6", 1659 "Ccedil": "\u00C7", 1660 "Egrave": "\u00C8", 1661 "Eacute": "\u00C9", 1662 "Ecirc": "\u00CA", 1663 "Euml": "\u00CB", 1664 "Igrave": "\u00CC", 1665 "Iacute": "\u00CD", 1666 "Icirc": "\u00CE", 1667 "Iuml": "\u00CF", 1668 "ETH": "\u00D0", 1669 "Ntilde": "\u00D1", 1670 "Ograve": "\u00D2", 1671 "Oacute": "\u00D3", 1672 "Ocirc": "\u00D4", 1673 "Otilde": "\u00D5", 1674 "Ouml": "\u00D6", 1675 "times": "\u00D7", 1676 "Oslash": "\u00D8", 1677 "Ugrave": "\u00D9", 1678 "Uacute": "\u00DA", 1679 "Ucirc": "\u00DB", 1680 "Uuml": "\u00DC", 1681 "Yacute": "\u00DD", 1682 "THORN": "\u00DE", 1683 "szlig": "\u00DF", 1684 "agrave": "\u00E0", 1685 "aacute": "\u00E1", 1686 "acirc": "\u00E2", 1687 "atilde": "\u00E3", 1688 "auml": "\u00E4", 1689 "aring": "\u00E5", 1690 "aelig": "\u00E6", 1691 "ccedil": "\u00E7", 1692 "egrave": "\u00E8", 1693 "eacute": "\u00E9", 1694 "ecirc": "\u00EA", 1695 "euml": "\u00EB", 1696 "igrave": "\u00EC", 1697 "iacute": "\u00ED", 1698 "icirc": "\u00EE", 1699 "iuml": "\u00EF", 1700 "eth": "\u00F0", 1701 "ntilde": "\u00F1", 1702 "ograve": "\u00F2", 1703 "oacute": "\u00F3", 1704 "ocirc": "\u00F4", 1705 "otilde": "\u00F5", 1706 "ouml": "\u00F6", 1707 "divide": "\u00F7", 1708 "oslash": "\u00F8", 1709 "ugrave": "\u00F9", 1710 "uacute": "\u00FA", 1711 "ucirc": "\u00FB", 1712 "uuml": "\u00FC", 1713 "yacute": "\u00FD", 1714 "thorn": "\u00FE", 1715 "yuml": "\u00FF", 1716 "fnof": "\u0192", 1717 "Alpha": "\u0391", 1718 "Beta": "\u0392", 1719 "Gamma": "\u0393", 1720 "Delta": "\u0394", 1721 "Epsilon": "\u0395", 1722 "Zeta": "\u0396", 1723 "Eta": "\u0397", 1724 "Theta": "\u0398", 1725 "Iota": "\u0399", 1726 "Kappa": "\u039A", 1727 "Lambda": "\u039B", 1728 "Mu": "\u039C", 1729 "Nu": "\u039D", 1730 "Xi": "\u039E", 1731 "Omicron": "\u039F", 1732 "Pi": "\u03A0", 1733 "Rho": "\u03A1", 1734 "Sigma": "\u03A3", 1735 "Tau": "\u03A4", 1736 "Upsilon": "\u03A5", 1737 "Phi": "\u03A6", 1738 "Chi": "\u03A7", 1739 "Psi": "\u03A8", 1740 "Omega": "\u03A9", 1741 "alpha": "\u03B1", 1742 "beta": "\u03B2", 1743 "gamma": "\u03B3", 1744 "delta": "\u03B4", 1745 "epsilon": "\u03B5", 1746 "zeta": "\u03B6", 1747 "eta": "\u03B7", 1748 "theta": "\u03B8", 1749 "iota": "\u03B9", 1750 "kappa": "\u03BA", 1751 "lambda": "\u03BB", 1752 "mu": "\u03BC", 1753 "nu": "\u03BD", 1754 "xi": "\u03BE", 1755 "omicron": "\u03BF", 1756 "pi": "\u03C0", 1757 "rho": "\u03C1", 1758 "sigmaf": "\u03C2", 1759 "sigma": "\u03C3", 1760 "tau": "\u03C4", 1761 "upsilon": "\u03C5", 1762 "phi": "\u03C6", 1763 "chi": "\u03C7", 1764 "psi": "\u03C8", 1765 "omega": "\u03C9", 1766 "thetasym": "\u03D1", 1767 "upsih": "\u03D2", 1768 "piv": "\u03D6", 1769 "bull": "\u2022", 1770 "hellip": "\u2026", 1771 "prime": "\u2032", 1772 "Prime": "\u2033", 1773 "oline": "\u203E", 1774 "frasl": "\u2044", 1775 "weierp": "\u2118", 1776 "image": "\u2111", 1777 "real": "\u211C", 1778 "trade": "\u2122", 1779 "alefsym": "\u2135", 1780 "larr": "\u2190", 1781 "uarr": "\u2191", 1782 "rarr": "\u2192", 1783 "darr": "\u2193", 1784 "harr": "\u2194", 1785 "crarr": "\u21B5", 1786 "lArr": "\u21D0", 1787 "uArr": "\u21D1", 1788 "rArr": "\u21D2", 1789 "dArr": "\u21D3", 1790 "hArr": "\u21D4", 1791 "forall": "\u2200", 1792 "part": "\u2202", 1793 "exist": "\u2203", 1794 "empty": "\u2205", 1795 "nabla": "\u2207", 1796 "isin": "\u2208", 1797 "notin": "\u2209", 1798 "ni": "\u220B", 1799 "prod": "\u220F", 1800 "sum": "\u2211", 1801 "minus": "\u2212", 1802 "lowast": "\u2217", 1803 "radic": "\u221A", 1804 "prop": "\u221D", 1805 "infin": "\u221E", 1806 "ang": "\u2220", 1807 "and": "\u2227", 1808 "or": "\u2228", 1809 "cap": "\u2229", 1810 "cup": "\u222A", 1811 "int": "\u222B", 1812 "there4": "\u2234", 1813 "sim": "\u223C", 1814 "cong": "\u2245", 1815 "asymp": "\u2248", 1816 "ne": "\u2260", 1817 "equiv": "\u2261", 1818 "le": "\u2264", 1819 "ge": "\u2265", 1820 "sub": "\u2282", 1821 "sup": "\u2283", 1822 "nsub": "\u2284", 1823 "sube": "\u2286", 1824 "supe": "\u2287", 1825 "oplus": "\u2295", 1826 "otimes": "\u2297", 1827 "perp": "\u22A5", 1828 "sdot": "\u22C5", 1829 "lceil": "\u2308", 1830 "rceil": "\u2309", 1831 "lfloor": "\u230A", 1832 "rfloor": "\u230B", 1833 "lang": "\u2329", 1834 "rang": "\u232A", 1835 "loz": "\u25CA", 1836 "spades": "\u2660", 1837 "clubs": "\u2663", 1838 "hearts": "\u2665", 1839 "diams": "\u2666", 1840 "quot": "\u0022", 1841 "amp": "\u0026", 1842 "lt": "\u003C", 1843 "gt": "\u003E", 1844 "OElig": "\u0152", 1845 "oelig": "\u0153", 1846 "Scaron": "\u0160", 1847 "scaron": "\u0161", 1848 "Yuml": "\u0178", 1849 "circ": "\u02C6", 1850 "tilde": "\u02DC", 1851 "ensp": "\u2002", 1852 "emsp": "\u2003", 1853 "thinsp": "\u2009", 1854 "zwnj": "\u200C", 1855 "zwj": "\u200D", 1856 "lrm": "\u200E", 1857 "rlm": "\u200F", 1858 "ndash": "\u2013", 1859 "mdash": "\u2014", 1860 "lsquo": "\u2018", 1861 "rsquo": "\u2019", 1862 "sbquo": "\u201A", 1863 "ldquo": "\u201C", 1864 "rdquo": "\u201D", 1865 "bdquo": "\u201E", 1866 "dagger": "\u2020", 1867 "Dagger": "\u2021", 1868 "permil": "\u2030", 1869 "lsaquo": "\u2039", 1870 "rsaquo": "\u203A", 1871 "euro": "\u20AC", 1872 } 1873 1874 // HTMLAutoClose is the set of HTML elements that 1875 // should be considered to close automatically. 1876 // 1877 // See the [Decoder.Strict] and [Decoder.Entity] fields' documentation. 1878 var HTMLAutoClose []string = htmlAutoClose 1879 1880 var htmlAutoClose = []string{ 1881 /* 1882 hget http://www.w3.org/TR/html4/loose.dtd | 1883 9 sed -n 's/<!ELEMENT ([^ ]*) +- O EMPTY.+/ "\1",/p' | tr A-Z a-z 1884 */ 1885 "basefont", 1886 "br", 1887 "area", 1888 "link", 1889 "img", 1890 "param", 1891 "hr", 1892 "input", 1893 "col", 1894 "frame", 1895 "isindex", 1896 "base", 1897 "meta", 1898 } 1899 1900 var ( 1901 escQuot = []byte(""") // shorter than """ 1902 escApos = []byte("'") // shorter than "'" 1903 escAmp = []byte("&") 1904 escLT = []byte("<") 1905 escGT = []byte(">") 1906 escTab = []byte("	") 1907 escNL = []byte("
") 1908 escCR = []byte("
") 1909 escFFFD = []byte("\uFFFD") // Unicode replacement character 1910 ) 1911 1912 // EscapeText writes to w the properly escaped XML equivalent 1913 // of the plain text data s. 1914 func EscapeText(w io.Writer, s []byte) error { 1915 return escapeText(w, s, true) 1916 } 1917 1918 // escapeText writes to w the properly escaped XML equivalent 1919 // of the plain text data s. If escapeNewline is true, newline 1920 // characters will be escaped. 1921 func escapeText(w io.Writer, s []byte, escapeNewline bool) error { 1922 var esc []byte 1923 last := 0 1924 for i := 0; i < len(s); { 1925 r, width := utf8.DecodeRune(s[i:]) 1926 i += width 1927 switch r { 1928 case '"': 1929 esc = escQuot 1930 case '\'': 1931 esc = escApos 1932 case '&': 1933 esc = escAmp 1934 case '<': 1935 esc = escLT 1936 case '>': 1937 esc = escGT 1938 case '\t': 1939 esc = escTab 1940 case '\n': 1941 if !escapeNewline { 1942 continue 1943 } 1944 esc = escNL 1945 case '\r': 1946 esc = escCR 1947 default: 1948 if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) { 1949 esc = escFFFD 1950 break 1951 } 1952 continue 1953 } 1954 if _, err := w.Write(s[last : i-width]); err != nil { 1955 return err 1956 } 1957 if _, err := w.Write(esc); err != nil { 1958 return err 1959 } 1960 last = i 1961 } 1962 _, err := w.Write(s[last:]) 1963 return err 1964 } 1965 1966 // EscapeString writes to p the properly escaped XML equivalent 1967 // of the plain text data s. 1968 func (p *printer) EscapeString(s string) { 1969 var esc []byte 1970 last := 0 1971 for i := 0; i < len(s); { 1972 r, width := utf8.DecodeRuneInString(s[i:]) 1973 i += width 1974 switch r { 1975 case '"': 1976 esc = escQuot 1977 case '\'': 1978 esc = escApos 1979 case '&': 1980 esc = escAmp 1981 case '<': 1982 esc = escLT 1983 case '>': 1984 esc = escGT 1985 case '\t': 1986 esc = escTab 1987 case '\n': 1988 esc = escNL 1989 case '\r': 1990 esc = escCR 1991 default: 1992 if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) { 1993 esc = escFFFD 1994 break 1995 } 1996 continue 1997 } 1998 p.WriteString(s[last : i-width]) 1999 p.Write(esc) 2000 last = i 2001 } 2002 p.WriteString(s[last:]) 2003 } 2004 2005 // Escape is like [EscapeText] but omits the error return value. 2006 // It is provided for backwards compatibility with Go 1.0. 2007 // Code targeting Go 1.1 or later should use [EscapeText]. 2008 func Escape(w io.Writer, s []byte) { 2009 EscapeText(w, s) 2010 } 2011 2012 var ( 2013 cdataStart = []byte("<![CDATA[") 2014 cdataEnd = []byte("]]>") 2015 cdataEscape = []byte("]]]]><![CDATA[>") 2016 ) 2017 2018 // emitCDATA writes to w the CDATA-wrapped plain text data s. 2019 // It escapes CDATA directives nested in s. 2020 func emitCDATA(w io.Writer, s []byte) error { 2021 if len(s) == 0 { 2022 return nil 2023 } 2024 if _, err := w.Write(cdataStart); err != nil { 2025 return err 2026 } 2027 2028 for { 2029 before, after, ok := bytes.Cut(s, cdataEnd) 2030 if !ok { 2031 break 2032 } 2033 // Found a nested CDATA directive end. 2034 if _, err := w.Write(before); err != nil { 2035 return err 2036 } 2037 if _, err := w.Write(cdataEscape); err != nil { 2038 return err 2039 } 2040 s = after 2041 } 2042 2043 if _, err := w.Write(s); err != nil { 2044 return err 2045 } 2046 2047 _, err := w.Write(cdataEnd) 2048 return err 2049 } 2050 2051 // procInst parses the `param="..."` or `param='...'` 2052 // value out of the provided string, returning "" if not found. 2053 func procInst(param, s string) string { 2054 // TODO: this parsing is somewhat lame and not exact. 2055 // It works for all actual cases, though. 2056 param = param + "=" 2057 lenp := len(param) 2058 i := 0 2059 var sep byte 2060 for i < len(s) { 2061 sub := s[i:] 2062 k := strings.Index(sub, param) 2063 if k < 0 || lenp+k >= len(sub) { 2064 return "" 2065 } 2066 i += lenp + k + 1 2067 if c := sub[lenp+k]; c == '\'' || c == '"' { 2068 sep = c 2069 break 2070 } 2071 } 2072 if sep == 0 { 2073 return "" 2074 } 2075 j := strings.IndexByte(s[i:], sep) 2076 if j < 0 { 2077 return "" 2078 } 2079 return s[i : i+j] 2080 }