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