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