...
Run Format

Source file src/encoding/xml/xml.go

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

View as plain text