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