summaryrefslogtreecommitdiff
path: root/vendor/github.com/tdewolff/parse/v2
diff options
context:
space:
mode:
authorMitja Felicijan <mitja.felicijan@gmail.com>2024-10-25 00:47:47 +0200
committerMitja Felicijan <mitja.felicijan@gmail.com>2024-10-25 00:47:47 +0200
commitc6cc0108ca7738023b45e0eeac0fa2390532dd93 (patch)
tree36890e6cd3091bbab8efbe686cc56f467f645bfd /vendor/github.com/tdewolff/parse/v2
parent0130404a1dc663d4aa68d780c9bcb23a4243e68d (diff)
downloadjbmafp-c6cc0108ca7738023b45e0eeac0fa2390532dd93.tar.gz
Added vendor lock on depsHEADmaster
Diffstat (limited to 'vendor/github.com/tdewolff/parse/v2')
-rw-r--r--vendor/github.com/tdewolff/parse/v2/.gitattributes1
-rw-r--r--vendor/github.com/tdewolff/parse/v2/.gitignore5
-rw-r--r--vendor/github.com/tdewolff/parse/v2/.golangci.yml16
-rw-r--r--vendor/github.com/tdewolff/parse/v2/LICENSE.md22
-rw-r--r--vendor/github.com/tdewolff/parse/v2/README.md64
-rw-r--r--vendor/github.com/tdewolff/parse/v2/buffer/buffer.go12
-rw-r--r--vendor/github.com/tdewolff/parse/v2/buffer/lexer.go164
-rw-r--r--vendor/github.com/tdewolff/parse/v2/buffer/reader.go44
-rw-r--r--vendor/github.com/tdewolff/parse/v2/buffer/streamlexer.go223
-rw-r--r--vendor/github.com/tdewolff/parse/v2/buffer/writer.go65
-rw-r--r--vendor/github.com/tdewolff/parse/v2/common.go237
-rw-r--r--vendor/github.com/tdewolff/parse/v2/css/README.md170
-rw-r--r--vendor/github.com/tdewolff/parse/v2/css/hash.go75
-rw-r--r--vendor/github.com/tdewolff/parse/v2/css/lex.go698
-rw-r--r--vendor/github.com/tdewolff/parse/v2/css/parse.go462
-rw-r--r--vendor/github.com/tdewolff/parse/v2/css/util.go47
-rw-r--r--vendor/github.com/tdewolff/parse/v2/error.go47
-rw-r--r--vendor/github.com/tdewolff/parse/v2/html/README.md98
-rw-r--r--vendor/github.com/tdewolff/parse/v2/html/hash.go81
-rw-r--r--vendor/github.com/tdewolff/parse/v2/html/lex.go494
-rw-r--r--vendor/github.com/tdewolff/parse/v2/html/util.go113
-rw-r--r--vendor/github.com/tdewolff/parse/v2/input.go173
-rw-r--r--vendor/github.com/tdewolff/parse/v2/js/README.md80
-rw-r--r--vendor/github.com/tdewolff/parse/v2/js/ast.go3884
-rw-r--r--vendor/github.com/tdewolff/parse/v2/js/lex.go793
-rw-r--r--vendor/github.com/tdewolff/parse/v2/js/parse.go2292
-rw-r--r--vendor/github.com/tdewolff/parse/v2/js/table.go142
-rw-r--r--vendor/github.com/tdewolff/parse/v2/js/tokentype.go404
-rw-r--r--vendor/github.com/tdewolff/parse/v2/js/util.go38
-rw-r--r--vendor/github.com/tdewolff/parse/v2/js/walk.go288
-rw-r--r--vendor/github.com/tdewolff/parse/v2/position.go95
-rw-r--r--vendor/github.com/tdewolff/parse/v2/strconv/float.go257
-rw-r--r--vendor/github.com/tdewolff/parse/v2/strconv/int.go108
-rw-r--r--vendor/github.com/tdewolff/parse/v2/strconv/price.go83
-rw-r--r--vendor/github.com/tdewolff/parse/v2/util.go481
35 files changed, 12256 insertions, 0 deletions
diff --git a/vendor/github.com/tdewolff/parse/v2/.gitattributes b/vendor/github.com/tdewolff/parse/v2/.gitattributes
new file mode 100644
index 0000000..9f4b74c
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/.gitattributes
@@ -0,0 +1 @@
+tests/*/corpus/* linguist-generated
diff --git a/vendor/github.com/tdewolff/parse/v2/.gitignore b/vendor/github.com/tdewolff/parse/v2/.gitignore
new file mode 100644
index 0000000..6144b69
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/.gitignore
@@ -0,0 +1,5 @@
+tests/*/fuzz-fuzz.zip
+tests/*/crashers
+tests/*/suppressions
+tests/*/corpus/*
+!tests/*/corpus/*.*
diff --git a/vendor/github.com/tdewolff/parse/v2/.golangci.yml b/vendor/github.com/tdewolff/parse/v2/.golangci.yml
new file mode 100644
index 0000000..7009f92
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/.golangci.yml
@@ -0,0 +1,16 @@
+linters:
+ enable:
+ - depguard
+ - dogsled
+ - gofmt
+ - goimports
+ - golint
+ - gosec
+ - govet
+ - megacheck
+ - misspell
+ - nakedret
+ - prealloc
+ - unconvert
+ - unparam
+ - wastedassign
diff --git a/vendor/github.com/tdewolff/parse/v2/LICENSE.md b/vendor/github.com/tdewolff/parse/v2/LICENSE.md
new file mode 100644
index 0000000..41677de
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/LICENSE.md
@@ -0,0 +1,22 @@
+Copyright (c) 2015 Taco de Wolff
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the "Software"), to deal in the Software without
+ restriction, including without limitation the rights to use,
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the
+ Software is furnished to do so, subject to the following
+ conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file
diff --git a/vendor/github.com/tdewolff/parse/v2/README.md b/vendor/github.com/tdewolff/parse/v2/README.md
new file mode 100644
index 0000000..837c281
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/README.md
@@ -0,0 +1,64 @@
+# Parse [![API reference](https://img.shields.io/badge/godoc-reference-5272B4)](https://pkg.go.dev/github.com/tdewolff/parse/v2?tab=doc) [![Go Report Card](https://goreportcard.com/badge/github.com/tdewolff/parse)](https://goreportcard.com/report/github.com/tdewolff/parse) [![Coverage Status](https://coveralls.io/repos/github/tdewolff/parse/badge.svg?branch=master)](https://coveralls.io/github/tdewolff/parse?branch=master) [![Donate](https://img.shields.io/badge/patreon-donate-DFB317)](https://www.patreon.com/tdewolff)
+
+This package contains several lexers and parsers written in [Go][1]. All subpackages are built to be streaming, high performance and to be in accordance with the official (latest) specifications.
+
+The lexers are implemented using `buffer.Lexer` in https://github.com/tdewolff/parse/buffer and the parsers work on top of the lexers. Some subpackages have hashes defined (using [Hasher](https://github.com/tdewolff/hasher)) that speed up common byte-slice comparisons.
+
+## Buffer
+### Reader
+Reader is a wrapper around a `[]byte` that implements the `io.Reader` interface. It is comparable to `bytes.Reader` but has slightly different semantics (and a slightly smaller memory footprint).
+
+### Writer
+Writer is a buffer that implements the `io.Writer` interface and expands the buffer as needed. The reset functionality allows for better memory reuse. After calling `Reset`, it will overwrite the current buffer and thus reduce allocations.
+
+### Lexer
+Lexer is a read buffer specifically designed for building lexers. It keeps track of two positions: a start and end position. The start position is the beginning of the current token being parsed, the end position is being moved forward until a valid token is found. Calling `Shift` will collapse the positions to the end and return the parsed `[]byte`.
+
+Moving the end position can go through `Move(int)` which also accepts negative integers. One can also use `Pos() int` to try and parse a token, and if it fails rewind with `Rewind(int)`, passing the previously saved position.
+
+`Peek(int) byte` will peek forward (relative to the end position) and return the byte at that location. `PeekRune(int) (rune, int)` returns UTF-8 runes and its length at the given **byte** position. Upon an error `Peek` will return `0`, the **user must peek at every character** and not skip any, otherwise it may skip a `0` and panic on out-of-bounds indexing.
+
+`Lexeme() []byte` will return the currently selected bytes, `Skip()` will collapse the selection. `Shift() []byte` is a combination of `Lexeme() []byte` and `Skip()`.
+
+When the passed `io.Reader` returned an error, `Err() error` will return that error even if not at the end of the buffer.
+
+### StreamLexer
+StreamLexer behaves like Lexer but uses a buffer pool to read in chunks from `io.Reader`, retaining old buffers in memory that are still in use, and re-using old buffers otherwise. Calling `Free(n int)` frees up `n` bytes from the internal buffer(s). It holds an array of buffers to accommodate for keeping everything in-memory. Calling `ShiftLen() int` returns the number of bytes that have been shifted since the previous call to `ShiftLen`, which can be used to specify how many bytes need to be freed up from the buffer. If you don't need to keep returned byte slices around, call `Free(ShiftLen())` after every `Shift` call.
+
+## Strconv
+This package contains string conversion function much like the standard library's `strconv` package, but it is specifically tailored for the performance needs within the `minify` package.
+
+For example, the floating-point to string conversion function is approximately twice as fast as the standard library, but it is not as precise.
+
+## CSS
+This package is a CSS3 lexer and parser. Both follow the specification at [CSS Syntax Module Level 3](http://www.w3.org/TR/css-syntax-3/). The lexer takes an io.Reader and converts it into tokens until the EOF. The parser returns a parse tree of the full io.Reader input stream, but the low-level `Next` function can be used for stream parsing to returns grammar units until the EOF.
+
+[See README here](https://github.com/tdewolff/parse/tree/master/css).
+
+## HTML
+This package is an HTML5 lexer. It follows the specification at [The HTML syntax](http://www.w3.org/TR/html5/syntax.html). The lexer takes an io.Reader and converts it into tokens until the EOF.
+
+[See README here](https://github.com/tdewolff/parse/tree/master/html).
+
+## JS
+This package is a JS lexer (ECMA-262, edition 6.0). It follows the specification at [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/6.0/). The lexer takes an io.Reader and converts it into tokens until the EOF.
+
+[See README here](https://github.com/tdewolff/parse/tree/master/js).
+
+## JSON
+This package is a JSON parser (ECMA-404). It follows the specification at [JSON](http://json.org/). The parser takes an io.Reader and converts it into tokens until the EOF.
+
+[See README here](https://github.com/tdewolff/parse/tree/master/json).
+
+## SVG
+This package contains common hashes for SVG1.1 tags and attributes.
+
+## XML
+This package is an XML1.0 lexer. It follows the specification at [Extensible Markup Language (XML) 1.0 (Fifth Edition)](http://www.w3.org/TR/xml/). The lexer takes an io.Reader and converts it into tokens until the EOF.
+
+[See README here](https://github.com/tdewolff/parse/tree/master/xml).
+
+## License
+Released under the [MIT license](LICENSE.md).
+
+[1]: http://golang.org/ "Go Language"
diff --git a/vendor/github.com/tdewolff/parse/v2/buffer/buffer.go b/vendor/github.com/tdewolff/parse/v2/buffer/buffer.go
new file mode 100644
index 0000000..671b380
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/buffer/buffer.go
@@ -0,0 +1,12 @@
+// Package buffer contains buffer and wrapper types for byte slices. It is useful for writing lexers or other high-performance byte slice handling.
+// The `Reader` and `Writer` types implement the `io.Reader` and `io.Writer` respectively and provide a thinner and faster interface than `bytes.Buffer`.
+// The `Lexer` type is useful for building lexers because it keeps track of the start and end position of a byte selection, and shifts the bytes whenever a valid token is found.
+// The `StreamLexer` does the same, but keeps a buffer pool so that it reads a limited amount at a time, allowing to parse from streaming sources.
+package buffer
+
+// defaultBufSize specifies the default initial length of internal buffers.
+var defaultBufSize = 4096
+
+// MinBuf specifies the default initial length of internal buffers.
+// Solely here to support old versions of parse.
+var MinBuf = defaultBufSize
diff --git a/vendor/github.com/tdewolff/parse/v2/buffer/lexer.go b/vendor/github.com/tdewolff/parse/v2/buffer/lexer.go
new file mode 100644
index 0000000..46e6bda
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/buffer/lexer.go
@@ -0,0 +1,164 @@
+package buffer
+
+import (
+ "io"
+ "io/ioutil"
+)
+
+var nullBuffer = []byte{0}
+
+// Lexer is a buffered reader that allows peeking forward and shifting, taking an io.Reader.
+// It keeps data in-memory until Free, taking a byte length, is called to move beyond the data.
+type Lexer struct {
+ buf []byte
+ pos int // index in buf
+ start int // index in buf
+ err error
+
+ restore func()
+}
+
+// NewLexer returns a new Lexer for a given io.Reader, and uses ioutil.ReadAll to read it into a byte slice.
+// If the io.Reader implements Bytes, that is used instead.
+// It will append a NULL at the end of the buffer.
+func NewLexer(r io.Reader) *Lexer {
+ var b []byte
+ if r != nil {
+ if buffer, ok := r.(interface {
+ Bytes() []byte
+ }); ok {
+ b = buffer.Bytes()
+ } else {
+ var err error
+ b, err = ioutil.ReadAll(r)
+ if err != nil {
+ return &Lexer{
+ buf: nullBuffer,
+ err: err,
+ }
+ }
+ }
+ }
+ return NewLexerBytes(b)
+}
+
+// NewLexerBytes returns a new Lexer for a given byte slice, and appends NULL at the end.
+// To avoid reallocation, make sure the capacity has room for one more byte.
+func NewLexerBytes(b []byte) *Lexer {
+ z := &Lexer{
+ buf: b,
+ }
+
+ n := len(b)
+ if n == 0 {
+ z.buf = nullBuffer
+ } else {
+ // Append NULL to buffer, but try to avoid reallocation
+ if cap(b) > n {
+ // Overwrite next byte but restore when done
+ b = b[:n+1]
+ c := b[n]
+ b[n] = 0
+
+ z.buf = b
+ z.restore = func() {
+ b[n] = c
+ }
+ } else {
+ z.buf = append(b, 0)
+ }
+ }
+ return z
+}
+
+// Restore restores the replaced byte past the end of the buffer by NULL.
+func (z *Lexer) Restore() {
+ if z.restore != nil {
+ z.restore()
+ z.restore = nil
+ }
+}
+
+// Err returns the error returned from io.Reader or io.EOF when the end has been reached.
+func (z *Lexer) Err() error {
+ return z.PeekErr(0)
+}
+
+// PeekErr returns the error at position pos. When pos is zero, this is the same as calling Err().
+func (z *Lexer) PeekErr(pos int) error {
+ if z.err != nil {
+ return z.err
+ } else if z.pos+pos >= len(z.buf)-1 {
+ return io.EOF
+ }
+ return nil
+}
+
+// Peek returns the ith byte relative to the end position.
+// Peek returns 0 when an error has occurred, Err returns the error.
+func (z *Lexer) Peek(pos int) byte {
+ pos += z.pos
+ return z.buf[pos]
+}
+
+// PeekRune returns the rune and rune length of the ith byte relative to the end position.
+func (z *Lexer) PeekRune(pos int) (rune, int) {
+ // from unicode/utf8
+ c := z.Peek(pos)
+ if c < 0xC0 || z.Peek(pos+1) == 0 {
+ return rune(c), 1
+ } else if c < 0xE0 || z.Peek(pos+2) == 0 {
+ return rune(c&0x1F)<<6 | rune(z.Peek(pos+1)&0x3F), 2
+ } else if c < 0xF0 || z.Peek(pos+3) == 0 {
+ return rune(c&0x0F)<<12 | rune(z.Peek(pos+1)&0x3F)<<6 | rune(z.Peek(pos+2)&0x3F), 3
+ }
+ return rune(c&0x07)<<18 | rune(z.Peek(pos+1)&0x3F)<<12 | rune(z.Peek(pos+2)&0x3F)<<6 | rune(z.Peek(pos+3)&0x3F), 4
+}
+
+// Move advances the position.
+func (z *Lexer) Move(n int) {
+ z.pos += n
+}
+
+// Pos returns a mark to which can be rewinded.
+func (z *Lexer) Pos() int {
+ return z.pos - z.start
+}
+
+// Rewind rewinds the position to the given position.
+func (z *Lexer) Rewind(pos int) {
+ z.pos = z.start + pos
+}
+
+// Lexeme returns the bytes of the current selection.
+func (z *Lexer) Lexeme() []byte {
+ return z.buf[z.start:z.pos:z.pos]
+}
+
+// Skip collapses the position to the end of the selection.
+func (z *Lexer) Skip() {
+ z.start = z.pos
+}
+
+// Shift returns the bytes of the current selection and collapses the position to the end of the selection.
+func (z *Lexer) Shift() []byte {
+ b := z.buf[z.start:z.pos:z.pos]
+ z.start = z.pos
+ return b
+}
+
+// Offset returns the character position in the buffer.
+func (z *Lexer) Offset() int {
+ return z.pos
+}
+
+// Bytes returns the underlying buffer.
+func (z *Lexer) Bytes() []byte {
+ return z.buf[: len(z.buf)-1 : len(z.buf)-1]
+}
+
+// Reset resets position to the underlying buffer.
+func (z *Lexer) Reset() {
+ z.start = 0
+ z.pos = 0
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/buffer/reader.go b/vendor/github.com/tdewolff/parse/v2/buffer/reader.go
new file mode 100644
index 0000000..9926eef
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/buffer/reader.go
@@ -0,0 +1,44 @@
+package buffer
+
+import "io"
+
+// Reader implements an io.Reader over a byte slice.
+type Reader struct {
+ buf []byte
+ pos int
+}
+
+// NewReader returns a new Reader for a given byte slice.
+func NewReader(buf []byte) *Reader {
+ return &Reader{
+ buf: buf,
+ }
+}
+
+// Read reads bytes into the given byte slice and returns the number of bytes read and an error if occurred.
+func (r *Reader) Read(b []byte) (n int, err error) {
+ if len(b) == 0 {
+ return 0, nil
+ }
+ if r.pos >= len(r.buf) {
+ return 0, io.EOF
+ }
+ n = copy(b, r.buf[r.pos:])
+ r.pos += n
+ return
+}
+
+// Bytes returns the underlying byte slice.
+func (r *Reader) Bytes() []byte {
+ return r.buf
+}
+
+// Reset resets the position of the read pointer to the beginning of the underlying byte slice.
+func (r *Reader) Reset() {
+ r.pos = 0
+}
+
+// Len returns the length of the buffer.
+func (r *Reader) Len() int {
+ return len(r.buf)
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/buffer/streamlexer.go b/vendor/github.com/tdewolff/parse/v2/buffer/streamlexer.go
new file mode 100644
index 0000000..5ea2dd5
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/buffer/streamlexer.go
@@ -0,0 +1,223 @@
+package buffer
+
+import (
+ "io"
+)
+
+type block struct {
+ buf []byte
+ next int // index in pool plus one
+ active bool
+}
+
+type bufferPool struct {
+ pool []block
+ head int // index in pool plus one
+ tail int // index in pool plus one
+
+ pos int // byte pos in tail
+}
+
+func (z *bufferPool) swap(oldBuf []byte, size int) []byte {
+ // find new buffer that can be reused
+ swap := -1
+ for i := 0; i < len(z.pool); i++ {
+ if !z.pool[i].active && size <= cap(z.pool[i].buf) {
+ swap = i
+ break
+ }
+ }
+ if swap == -1 { // no free buffer found for reuse
+ if z.tail == 0 && z.pos >= len(oldBuf) && size <= cap(oldBuf) { // but we can reuse the current buffer!
+ z.pos -= len(oldBuf)
+ return oldBuf[:0]
+ }
+ // allocate new
+ z.pool = append(z.pool, block{make([]byte, 0, size), 0, true})
+ swap = len(z.pool) - 1
+ }
+
+ newBuf := z.pool[swap].buf
+
+ // put current buffer into pool
+ z.pool[swap] = block{oldBuf, 0, true}
+ if z.head != 0 {
+ z.pool[z.head-1].next = swap + 1
+ }
+ z.head = swap + 1
+ if z.tail == 0 {
+ z.tail = swap + 1
+ }
+
+ return newBuf[:0]
+}
+
+func (z *bufferPool) free(n int) {
+ z.pos += n
+ // move the tail over to next buffers
+ for z.tail != 0 && z.pos >= len(z.pool[z.tail-1].buf) {
+ z.pos -= len(z.pool[z.tail-1].buf)
+ newTail := z.pool[z.tail-1].next
+ z.pool[z.tail-1].active = false // after this, any thread may pick up the inactive buffer, so it can't be used anymore
+ z.tail = newTail
+ }
+ if z.tail == 0 {
+ z.head = 0
+ }
+}
+
+// StreamLexer is a buffered reader that allows peeking forward and shifting, taking an io.Reader.
+// It keeps data in-memory until Free, taking a byte length, is called to move beyond the data.
+type StreamLexer struct {
+ r io.Reader
+ err error
+
+ pool bufferPool
+
+ buf []byte
+ start int // index in buf
+ pos int // index in buf
+ prevStart int
+
+ free int
+}
+
+// NewStreamLexer returns a new StreamLexer for a given io.Reader with a 4kB estimated buffer size.
+// If the io.Reader implements Bytes, that buffer is used instead.
+func NewStreamLexer(r io.Reader) *StreamLexer {
+ return NewStreamLexerSize(r, defaultBufSize)
+}
+
+// NewStreamLexerSize returns a new StreamLexer for a given io.Reader and estimated required buffer size.
+// If the io.Reader implements Bytes, that buffer is used instead.
+func NewStreamLexerSize(r io.Reader, size int) *StreamLexer {
+ // if reader has the bytes in memory already, use that instead
+ if buffer, ok := r.(interface {
+ Bytes() []byte
+ }); ok {
+ return &StreamLexer{
+ err: io.EOF,
+ buf: buffer.Bytes(),
+ }
+ }
+ return &StreamLexer{
+ r: r,
+ buf: make([]byte, 0, size),
+ }
+}
+
+func (z *StreamLexer) read(pos int) byte {
+ if z.err != nil {
+ return 0
+ }
+
+ // free unused bytes
+ z.pool.free(z.free)
+ z.free = 0
+
+ // get new buffer
+ c := cap(z.buf)
+ p := pos - z.start + 1
+ if 2*p > c { // if the token is larger than half the buffer, increase buffer size
+ c = 2*c + p
+ }
+ d := len(z.buf) - z.start
+ buf := z.pool.swap(z.buf[:z.start], c)
+ copy(buf[:d], z.buf[z.start:]) // copy the left-overs (unfinished token) from the old buffer
+
+ // read in new data for the rest of the buffer
+ var n int
+ for pos-z.start >= d && z.err == nil {
+ n, z.err = z.r.Read(buf[d:cap(buf)])
+ d += n
+ }
+ pos -= z.start
+ z.pos -= z.start
+ z.start, z.buf = 0, buf[:d]
+ if pos >= d {
+ return 0
+ }
+ return z.buf[pos]
+}
+
+// Err returns the error returned from io.Reader. It may still return valid bytes for a while though.
+func (z *StreamLexer) Err() error {
+ if z.err == io.EOF && z.pos < len(z.buf) {
+ return nil
+ }
+ return z.err
+}
+
+// Free frees up bytes of length n from previously shifted tokens.
+// Each call to Shift should at one point be followed by a call to Free with a length returned by ShiftLen.
+func (z *StreamLexer) Free(n int) {
+ z.free += n
+}
+
+// Peek returns the ith byte relative to the end position and possibly does an allocation.
+// Peek returns zero when an error has occurred, Err returns the error.
+// TODO: inline function
+func (z *StreamLexer) Peek(pos int) byte {
+ pos += z.pos
+ if uint(pos) < uint(len(z.buf)) { // uint for BCE
+ return z.buf[pos]
+ }
+ return z.read(pos)
+}
+
+// PeekRune returns the rune and rune length of the ith byte relative to the end position.
+func (z *StreamLexer) PeekRune(pos int) (rune, int) {
+ // from unicode/utf8
+ c := z.Peek(pos)
+ if c < 0xC0 {
+ return rune(c), 1
+ } else if c < 0xE0 {
+ return rune(c&0x1F)<<6 | rune(z.Peek(pos+1)&0x3F), 2
+ } else if c < 0xF0 {
+ return rune(c&0x0F)<<12 | rune(z.Peek(pos+1)&0x3F)<<6 | rune(z.Peek(pos+2)&0x3F), 3
+ }
+ return rune(c&0x07)<<18 | rune(z.Peek(pos+1)&0x3F)<<12 | rune(z.Peek(pos+2)&0x3F)<<6 | rune(z.Peek(pos+3)&0x3F), 4
+}
+
+// Move advances the position.
+func (z *StreamLexer) Move(n int) {
+ z.pos += n
+}
+
+// Pos returns a mark to which can be rewinded.
+func (z *StreamLexer) Pos() int {
+ return z.pos - z.start
+}
+
+// Rewind rewinds the position to the given position.
+func (z *StreamLexer) Rewind(pos int) {
+ z.pos = z.start + pos
+}
+
+// Lexeme returns the bytes of the current selection.
+func (z *StreamLexer) Lexeme() []byte {
+ return z.buf[z.start:z.pos]
+}
+
+// Skip collapses the position to the end of the selection.
+func (z *StreamLexer) Skip() {
+ z.start = z.pos
+}
+
+// Shift returns the bytes of the current selection and collapses the position to the end of the selection.
+// It also returns the number of bytes we moved since the last call to Shift. This can be used in calls to Free.
+func (z *StreamLexer) Shift() []byte {
+ if z.pos > len(z.buf) { // make sure we peeked at least as much as we shift
+ z.read(z.pos - 1)
+ }
+ b := z.buf[z.start:z.pos]
+ z.start = z.pos
+ return b
+}
+
+// ShiftLen returns the number of bytes moved since the last call to ShiftLen. This can be used in calls to Free because it takes into account multiple Shifts or Skips.
+func (z *StreamLexer) ShiftLen() int {
+ n := z.start - z.prevStart
+ z.prevStart = z.start
+ return n
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/buffer/writer.go b/vendor/github.com/tdewolff/parse/v2/buffer/writer.go
new file mode 100644
index 0000000..6c94201
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/buffer/writer.go
@@ -0,0 +1,65 @@
+package buffer
+
+import (
+ "io"
+)
+
+// Writer implements an io.Writer over a byte slice.
+type Writer struct {
+ buf []byte
+ err error
+ expand bool
+}
+
+// NewWriter returns a new Writer for a given byte slice.
+func NewWriter(buf []byte) *Writer {
+ return &Writer{
+ buf: buf,
+ expand: true,
+ }
+}
+
+// NewStaticWriter returns a new Writer for a given byte slice. It does not reallocate and expand the byte-slice.
+func NewStaticWriter(buf []byte) *Writer {
+ return &Writer{
+ buf: buf,
+ expand: false,
+ }
+}
+
+// Write writes bytes from the given byte slice and returns the number of bytes written and an error if occurred. When err != nil, n == 0.
+func (w *Writer) Write(b []byte) (int, error) {
+ n := len(b)
+ end := len(w.buf)
+ if end+n > cap(w.buf) {
+ if !w.expand {
+ w.err = io.EOF
+ return 0, io.EOF
+ }
+ buf := make([]byte, end, 2*cap(w.buf)+n)
+ copy(buf, w.buf)
+ w.buf = buf
+ }
+ w.buf = w.buf[:end+n]
+ return copy(w.buf[end:], b), nil
+}
+
+// Len returns the length of the underlying byte slice.
+func (w *Writer) Len() int {
+ return len(w.buf)
+}
+
+// Bytes returns the underlying byte slice.
+func (w *Writer) Bytes() []byte {
+ return w.buf
+}
+
+// Reset empties and reuses the current buffer. Subsequent writes will overwrite the buffer, so any reference to the underlying slice is invalidated after this call.
+func (w *Writer) Reset() {
+ w.buf = w.buf[:0]
+}
+
+// Close returns the last error.
+func (w *Writer) Close() error {
+ return w.err
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/common.go b/vendor/github.com/tdewolff/parse/v2/common.go
new file mode 100644
index 0000000..da46cc3
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/common.go
@@ -0,0 +1,237 @@
+// Package parse contains a collection of parsers for various formats in its subpackages.
+package parse
+
+import (
+ "bytes"
+ "encoding/base64"
+ "errors"
+)
+
+var (
+ dataSchemeBytes = []byte("data:")
+ base64Bytes = []byte("base64")
+ textMimeBytes = []byte("text/plain")
+)
+
+// ErrBadDataURI is returned by DataURI when the byte slice does not start with 'data:' or is too short.
+var ErrBadDataURI = errors.New("not a data URI")
+
+// Number returns the number of bytes that parse as a number of the regex format (+|-)?([0-9]+(\.[0-9]+)?|\.[0-9]+)((e|E)(+|-)?[0-9]+)?.
+func Number(b []byte) int {
+ if len(b) == 0 {
+ return 0
+ }
+ i := 0
+ if b[i] == '+' || b[i] == '-' {
+ i++
+ if i >= len(b) {
+ return 0
+ }
+ }
+ firstDigit := (b[i] >= '0' && b[i] <= '9')
+ if firstDigit {
+ i++
+ for i < len(b) && b[i] >= '0' && b[i] <= '9' {
+ i++
+ }
+ }
+ if i < len(b) && b[i] == '.' {
+ i++
+ if i < len(b) && b[i] >= '0' && b[i] <= '9' {
+ i++
+ for i < len(b) && b[i] >= '0' && b[i] <= '9' {
+ i++
+ }
+ } else if firstDigit {
+ // . could belong to the next token
+ i--
+ return i
+ } else {
+ return 0
+ }
+ } else if !firstDigit {
+ return 0
+ }
+ iOld := i
+ if i < len(b) && (b[i] == 'e' || b[i] == 'E') {
+ i++
+ if i < len(b) && (b[i] == '+' || b[i] == '-') {
+ i++
+ }
+ if i >= len(b) || b[i] < '0' || b[i] > '9' {
+ // e could belong to next token
+ return iOld
+ }
+ for i < len(b) && b[i] >= '0' && b[i] <= '9' {
+ i++
+ }
+ }
+ return i
+}
+
+// Dimension parses a byte-slice and returns the length of the number and its unit.
+func Dimension(b []byte) (int, int) {
+ num := Number(b)
+ if num == 0 || num == len(b) {
+ return num, 0
+ } else if b[num] == '%' {
+ return num, 1
+ } else if b[num] >= 'a' && b[num] <= 'z' || b[num] >= 'A' && b[num] <= 'Z' {
+ i := num + 1
+ for i < len(b) && (b[i] >= 'a' && b[i] <= 'z' || b[i] >= 'A' && b[i] <= 'Z') {
+ i++
+ }
+ return num, i - num
+ }
+ return num, 0
+}
+
+// Mediatype parses a given mediatype and splits the mimetype from the parameters.
+// It works similar to mime.ParseMediaType but is faster.
+func Mediatype(b []byte) ([]byte, map[string]string) {
+ i := 0
+ for i < len(b) && b[i] == ' ' {
+ i++
+ }
+ b = b[i:]
+ n := len(b)
+ mimetype := b
+ var params map[string]string
+ for i := 3; i < n; i++ { // mimetype is at least three characters long
+ if b[i] == ';' || b[i] == ' ' {
+ mimetype = b[:i]
+ if b[i] == ' ' {
+ i++ // space
+ for i < n && b[i] == ' ' {
+ i++
+ }
+ if n <= i || b[i] != ';' {
+ break
+ }
+ }
+ params = map[string]string{}
+ s := string(b)
+ PARAM:
+ i++ // semicolon
+ for i < n && s[i] == ' ' {
+ i++
+ }
+ start := i
+ for i < n && s[i] != '=' && s[i] != ';' && s[i] != ' ' {
+ i++
+ }
+ key := s[start:i]
+ for i < n && s[i] == ' ' {
+ i++
+ }
+ if i < n && s[i] == '=' {
+ i++
+ for i < n && s[i] == ' ' {
+ i++
+ }
+ start = i
+ for i < n && s[i] != ';' && s[i] != ' ' {
+ i++
+ }
+ } else {
+ start = i
+ }
+ params[key] = s[start:i]
+ for i < n && s[i] == ' ' {
+ i++
+ }
+ if i < n && s[i] == ';' {
+ goto PARAM
+ }
+ break
+ }
+ }
+ return mimetype, params
+}
+
+// DataURI parses the given data URI and returns the mediatype, data and ok.
+func DataURI(dataURI []byte) ([]byte, []byte, error) {
+ if len(dataURI) > 5 && bytes.Equal(dataURI[:5], dataSchemeBytes) {
+ dataURI = dataURI[5:]
+ inBase64 := false
+ var mediatype []byte
+ i := 0
+ for j := 0; j < len(dataURI); j++ {
+ c := dataURI[j]
+ if c == '=' || c == ';' || c == ',' {
+ if c != '=' && bytes.Equal(TrimWhitespace(dataURI[i:j]), base64Bytes) {
+ if len(mediatype) > 0 {
+ mediatype = mediatype[:len(mediatype)-1]
+ }
+ inBase64 = true
+ i = j
+ } else if c != ',' {
+ mediatype = append(append(mediatype, TrimWhitespace(dataURI[i:j])...), c)
+ i = j + 1
+ } else {
+ mediatype = append(mediatype, TrimWhitespace(dataURI[i:j])...)
+ }
+ if c == ',' {
+ if len(mediatype) == 0 || mediatype[0] == ';' {
+ mediatype = textMimeBytes
+ }
+ data := dataURI[j+1:]
+ if inBase64 {
+ decoded := make([]byte, base64.StdEncoding.DecodedLen(len(data)))
+ n, err := base64.StdEncoding.Decode(decoded, data)
+ if err != nil {
+ return nil, nil, err
+ }
+ data = decoded[:n]
+ } else {
+ data = DecodeURL(data)
+ }
+ return mediatype, data, nil
+ }
+ }
+ }
+ }
+ return nil, nil, ErrBadDataURI
+}
+
+// QuoteEntity parses the given byte slice and returns the quote that got matched (' or ") and its entity length.
+// TODO: deprecated
+func QuoteEntity(b []byte) (quote byte, n int) {
+ if len(b) < 5 || b[0] != '&' {
+ return 0, 0
+ }
+ if b[1] == '#' {
+ if b[2] == 'x' {
+ i := 3
+ for i < len(b) && b[i] == '0' {
+ i++
+ }
+ if i+2 < len(b) && b[i] == '2' && b[i+2] == ';' {
+ if b[i+1] == '2' {
+ return '"', i + 3 // &#x22;
+ } else if b[i+1] == '7' {
+ return '\'', i + 3 // &#x27;
+ }
+ }
+ } else {
+ i := 2
+ for i < len(b) && b[i] == '0' {
+ i++
+ }
+ if i+2 < len(b) && b[i] == '3' && b[i+2] == ';' {
+ if b[i+1] == '4' {
+ return '"', i + 3 // &#34;
+ } else if b[i+1] == '9' {
+ return '\'', i + 3 // &#39;
+ }
+ }
+ }
+ } else if len(b) >= 6 && b[5] == ';' {
+ if bytes.Equal(b[1:5], []byte{'q', 'u', 'o', 't'}) {
+ return '"', 6 // &quot;
+ } else if bytes.Equal(b[1:5], []byte{'a', 'p', 'o', 's'}) {
+ return '\'', 6 // &apos;
+ }
+ }
+ return 0, 0
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/css/README.md b/vendor/github.com/tdewolff/parse/v2/css/README.md
new file mode 100644
index 0000000..02797a7
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/css/README.md
@@ -0,0 +1,170 @@
+# CSS [![API reference](https://img.shields.io/badge/godoc-reference-5272B4)](https://pkg.go.dev/github.com/tdewolff/parse/v2/css?tab=doc)
+
+This package is a CSS3 lexer and parser written in [Go][1]. Both follow the specification at [CSS Syntax Module Level 3](http://www.w3.org/TR/css-syntax-3/). The lexer takes an io.Reader and converts it into tokens until the EOF. The parser returns a parse tree of the full io.Reader input stream, but the low-level `Next` function can be used for stream parsing to returns grammar units until the EOF.
+
+## Installation
+Run the following command
+
+ go get -u github.com/tdewolff/parse/v2/css
+
+or add the following import and run project with `go get`
+
+ import "github.com/tdewolff/parse/v2/css"
+
+## Lexer
+### Usage
+The following initializes a new Lexer with io.Reader `r`:
+``` go
+l := css.NewLexer(parse.NewInput(r))
+```
+
+To tokenize until EOF an error, use:
+``` go
+for {
+ tt, text := l.Next()
+ switch tt {
+ case css.ErrorToken:
+ // error or EOF set in l.Err()
+ return
+ // ...
+ }
+}
+```
+
+All tokens (see [CSS Syntax Module Level 3](http://www.w3.org/TR/css3-syntax/)):
+``` go
+ErrorToken // non-official token, returned when errors occur
+IdentToken
+FunctionToken // rgb( rgba( ...
+AtKeywordToken // @abc
+HashToken // #abc
+StringToken
+BadStringToken
+URLToken // url(
+BadURLToken
+DelimToken // any unmatched character
+NumberToken // 5
+PercentageToken // 5%
+DimensionToken // 5em
+UnicodeRangeToken
+IncludeMatchToken // ~=
+DashMatchToken // |=
+PrefixMatchToken // ^=
+SuffixMatchToken // $=
+SubstringMatchToken // *=
+ColumnToken // ||
+WhitespaceToken
+CDOToken // <!--
+CDCToken // -->
+ColonToken
+SemicolonToken
+CommaToken
+BracketToken // ( ) [ ] { }, all bracket tokens use this, Data() can distinguish between the brackets
+CommentToken // non-official token
+```
+
+### Examples
+``` go
+package main
+
+import (
+ "os"
+
+ "github.com/tdewolff/parse/v2/css"
+)
+
+// Tokenize CSS3 from stdin.
+func main() {
+ l := css.NewLexer(parse.NewInput(os.Stdin))
+ for {
+ tt, text := l.Next()
+ switch tt {
+ case css.ErrorToken:
+ if l.Err() != io.EOF {
+ fmt.Println("Error on line", l.Line(), ":", l.Err())
+ }
+ return
+ case css.IdentToken:
+ fmt.Println("Identifier", string(text))
+ case css.NumberToken:
+ fmt.Println("Number", string(text))
+ // ...
+ }
+ }
+}
+```
+
+## Parser
+### Usage
+The following creates a new Parser.
+``` go
+// true because this is the content of an inline style attribute
+p := css.NewParser(parse.NewInput(bytes.NewBufferString("color: red;")), true)
+```
+
+To iterate over the stylesheet, use:
+``` go
+for {
+ gt, _, data := p.Next()
+ if gt == css.ErrorGrammar {
+ break
+ }
+ // ...
+}
+```
+
+All grammar units returned by `Next`:
+``` go
+ErrorGrammar
+AtRuleGrammar
+EndAtRuleGrammar
+RulesetGrammar
+EndRulesetGrammar
+DeclarationGrammar
+TokenGrammar
+```
+
+### Examples
+``` go
+package main
+
+import (
+ "bytes"
+ "fmt"
+
+ "github.com/tdewolff/parse/v2/css"
+)
+
+func main() {
+ // true because this is the content of an inline style attribute
+ p := css.NewParser(parse.NewInput(bytes.NewBufferString("color: red;")), true)
+ out := ""
+ for {
+ gt, _, data := p.Next()
+ if gt == css.ErrorGrammar {
+ break
+ } else if gt == css.AtRuleGrammar || gt == css.BeginAtRuleGrammar || gt == css.BeginRulesetGrammar || gt == css.DeclarationGrammar {
+ out += string(data)
+ if gt == css.DeclarationGrammar {
+ out += ":"
+ }
+ for _, val := range p.Values() {
+ out += string(val.Data)
+ }
+ if gt == css.BeginAtRuleGrammar || gt == css.BeginRulesetGrammar {
+ out += "{"
+ } else if gt == css.AtRuleGrammar || gt == css.DeclarationGrammar {
+ out += ";"
+ }
+ } else {
+ out += string(data)
+ }
+ }
+ fmt.Println(out)
+}
+```
+
+## License
+Released under the [MIT license](https://github.com/tdewolff/parse/blob/master/LICENSE.md).
+
+[1]: http://golang.org/ "Go Language"
diff --git a/vendor/github.com/tdewolff/parse/v2/css/hash.go b/vendor/github.com/tdewolff/parse/v2/css/hash.go
new file mode 100644
index 0000000..25d2f7c
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/css/hash.go
@@ -0,0 +1,75 @@
+package css
+
+// generated by hasher -type=Hash -file=hash.go; DO NOT EDIT, except for adding more constants to the list and rerun go generate
+
+// uses github.com/tdewolff/hasher
+//go:generate hasher -type=Hash -file=hash.go
+
+// Hash defines perfect hashes for a predefined list of strings
+type Hash uint32
+
+// Unique hash definitions to be used instead of strings
+const (
+ Document Hash = 0x8 // document
+ Font_Face Hash = 0x809 // font-face
+ Keyframes Hash = 0x1109 // keyframes
+ Media Hash = 0x2105 // media
+ Page Hash = 0x2604 // page
+ Supports Hash = 0x1908 // supports
+)
+
+// String returns the hash' name.
+func (i Hash) String() string {
+ start := uint32(i >> 8)
+ n := uint32(i & 0xff)
+ if start+n > uint32(len(_Hash_text)) {
+ return ""
+ }
+ return _Hash_text[start : start+n]
+}
+
+// ToHash returns the hash whose name is s. It returns zero if there is no
+// such hash. It is case sensitive.
+func ToHash(s []byte) Hash {
+ if len(s) == 0 || len(s) > _Hash_maxLen {
+ return 0
+ }
+ h := uint32(_Hash_hash0)
+ for i := 0; i < len(s); i++ {
+ h ^= uint32(s[i])
+ h *= 16777619
+ }
+ if i := _Hash_table[h&uint32(len(_Hash_table)-1)]; int(i&0xff) == len(s) {
+ t := _Hash_text[i>>8 : i>>8+i&0xff]
+ for i := 0; i < len(s); i++ {
+ if t[i] != s[i] {
+ goto NEXT
+ }
+ }
+ return i
+ }
+NEXT:
+ if i := _Hash_table[(h>>16)&uint32(len(_Hash_table)-1)]; int(i&0xff) == len(s) {
+ t := _Hash_text[i>>8 : i>>8+i&0xff]
+ for i := 0; i < len(s); i++ {
+ if t[i] != s[i] {
+ return 0
+ }
+ }
+ return i
+ }
+ return 0
+}
+
+const _Hash_hash0 = 0x9acb0442
+const _Hash_maxLen = 9
+const _Hash_text = "documentfont-facekeyframesupportsmediapage"
+
+var _Hash_table = [1 << 3]Hash{
+ 0x1: 0x2604, // page
+ 0x2: 0x2105, // media
+ 0x3: 0x809, // font-face
+ 0x5: 0x1109, // keyframes
+ 0x6: 0x1908, // supports
+ 0x7: 0x8, // document
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/css/lex.go b/vendor/github.com/tdewolff/parse/v2/css/lex.go
new file mode 100644
index 0000000..3d1ff7e
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/css/lex.go
@@ -0,0 +1,698 @@
+// Package css is a CSS3 lexer and parser following the specifications at http://www.w3.org/TR/css-syntax-3/.
+package css
+
+// TODO: \uFFFD replacement character for NULL bytes in strings for example, or atleast don't end the string early
+
+import (
+ "bytes"
+ "io"
+ "strconv"
+
+ "github.com/tdewolff/parse/v2"
+)
+
+// TokenType determines the type of token, eg. a number or a semicolon.
+type TokenType uint32
+
+// TokenType values.
+const (
+ ErrorToken TokenType = iota // extra token when errors occur
+ IdentToken
+ FunctionToken // rgb( rgba( ...
+ AtKeywordToken // @abc
+ HashToken // #abc
+ StringToken
+ BadStringToken
+ URLToken
+ BadURLToken
+ DelimToken // any unmatched character
+ NumberToken // 5
+ PercentageToken // 5%
+ DimensionToken // 5em
+ UnicodeRangeToken // U+554A
+ IncludeMatchToken // ~=
+ DashMatchToken // |=
+ PrefixMatchToken // ^=
+ SuffixMatchToken // $=
+ SubstringMatchToken // *=
+ ColumnToken // ||
+ WhitespaceToken // space \t \r \n \f
+ CDOToken // <!--
+ CDCToken // -->
+ ColonToken // :
+ SemicolonToken // ;
+ CommaToken // ,
+ LeftBracketToken // [
+ RightBracketToken // ]
+ LeftParenthesisToken // (
+ RightParenthesisToken // )
+ LeftBraceToken // {
+ RightBraceToken // }
+ CommentToken // extra token for comments
+ EmptyToken
+ CustomPropertyNameToken
+ CustomPropertyValueToken
+)
+
+// String returns the string representation of a TokenType.
+func (tt TokenType) String() string {
+ switch tt {
+ case ErrorToken:
+ return "Error"
+ case IdentToken:
+ return "Ident"
+ case FunctionToken:
+ return "Function"
+ case AtKeywordToken:
+ return "AtKeyword"
+ case HashToken:
+ return "Hash"
+ case StringToken:
+ return "String"
+ case BadStringToken:
+ return "BadString"
+ case URLToken:
+ return "URL"
+ case BadURLToken:
+ return "BadURL"
+ case DelimToken:
+ return "Delim"
+ case NumberToken:
+ return "Number"
+ case PercentageToken:
+ return "Percentage"
+ case DimensionToken:
+ return "Dimension"
+ case UnicodeRangeToken:
+ return "UnicodeRange"
+ case IncludeMatchToken:
+ return "IncludeMatch"
+ case DashMatchToken:
+ return "DashMatch"
+ case PrefixMatchToken:
+ return "PrefixMatch"
+ case SuffixMatchToken:
+ return "SuffixMatch"
+ case SubstringMatchToken:
+ return "SubstringMatch"
+ case ColumnToken:
+ return "Column"
+ case WhitespaceToken:
+ return "Whitespace"
+ case CDOToken:
+ return "CDO"
+ case CDCToken:
+ return "CDC"
+ case ColonToken:
+ return "Colon"
+ case SemicolonToken:
+ return "Semicolon"
+ case CommaToken:
+ return "Comma"
+ case LeftBracketToken:
+ return "LeftBracket"
+ case RightBracketToken:
+ return "RightBracket"
+ case LeftParenthesisToken:
+ return "LeftParenthesis"
+ case RightParenthesisToken:
+ return "RightParenthesis"
+ case LeftBraceToken:
+ return "LeftBrace"
+ case RightBraceToken:
+ return "RightBrace"
+ case CommentToken:
+ return "Comment"
+ case EmptyToken:
+ return "Empty"
+ case CustomPropertyNameToken:
+ return "CustomPropertyName"
+ case CustomPropertyValueToken:
+ return "CustomPropertyValue"
+ }
+ return "Invalid(" + strconv.Itoa(int(tt)) + ")"
+}
+
+////////////////////////////////////////////////////////////////
+
+// Lexer is the state for the lexer.
+type Lexer struct {
+ r *parse.Input
+}
+
+// NewLexer returns a new Lexer for a given io.Reader.
+func NewLexer(r *parse.Input) *Lexer {
+ return &Lexer{
+ r: r,
+ }
+}
+
+// Err returns the error encountered during lexing, this is often io.EOF but also other errors can be returned.
+func (l *Lexer) Err() error {
+ return l.r.Err()
+}
+
+// Next returns the next Token. It returns ErrorToken when an error was encountered. Using Err() one can retrieve the error message.
+func (l *Lexer) Next() (TokenType, []byte) {
+ switch l.r.Peek(0) {
+ case ' ', '\t', '\n', '\r', '\f':
+ l.r.Move(1)
+ for l.consumeWhitespace() {
+ }
+ return WhitespaceToken, l.r.Shift()
+ case ':':
+ l.r.Move(1)
+ return ColonToken, l.r.Shift()
+ case ';':
+ l.r.Move(1)
+ return SemicolonToken, l.r.Shift()
+ case ',':
+ l.r.Move(1)
+ return CommaToken, l.r.Shift()
+ case '(', ')', '[', ']', '{', '}':
+ if t := l.consumeBracket(); t != ErrorToken {
+ return t, l.r.Shift()
+ }
+ case '#':
+ if l.consumeHashToken() {
+ return HashToken, l.r.Shift()
+ }
+ case '"', '\'':
+ if t := l.consumeString(); t != ErrorToken {
+ return t, l.r.Shift()
+ }
+ case '.', '+':
+ if t := l.consumeNumeric(); t != ErrorToken {
+ return t, l.r.Shift()
+ }
+ case '-':
+ if t := l.consumeNumeric(); t != ErrorToken {
+ return t, l.r.Shift()
+ } else if t := l.consumeIdentlike(); t != ErrorToken {
+ return t, l.r.Shift()
+ } else if l.consumeCDCToken() {
+ return CDCToken, l.r.Shift()
+ } else if l.consumeCustomVariableToken() {
+ return CustomPropertyNameToken, l.r.Shift()
+ }
+ case '@':
+ if l.consumeAtKeywordToken() {
+ return AtKeywordToken, l.r.Shift()
+ }
+ case '$', '*', '^', '~':
+ if t := l.consumeMatch(); t != ErrorToken {
+ return t, l.r.Shift()
+ }
+ case '/':
+ if l.consumeComment() {
+ return CommentToken, l.r.Shift()
+ }
+ case '<':
+ if l.consumeCDOToken() {
+ return CDOToken, l.r.Shift()
+ }
+ case '\\':
+ if t := l.consumeIdentlike(); t != ErrorToken {
+ return t, l.r.Shift()
+ }
+ case 'u', 'U':
+ if l.consumeUnicodeRangeToken() {
+ return UnicodeRangeToken, l.r.Shift()
+ } else if t := l.consumeIdentlike(); t != ErrorToken {
+ return t, l.r.Shift()
+ }
+ case '|':
+ if t := l.consumeMatch(); t != ErrorToken {
+ return t, l.r.Shift()
+ } else if l.consumeColumnToken() {
+ return ColumnToken, l.r.Shift()
+ }
+ case 0:
+ if l.r.Err() != nil {
+ return ErrorToken, nil
+ }
+ default:
+ if t := l.consumeNumeric(); t != ErrorToken {
+ return t, l.r.Shift()
+ } else if t := l.consumeIdentlike(); t != ErrorToken {
+ return t, l.r.Shift()
+ }
+ }
+ // can't be rune because consumeIdentlike consumes that as an identifier
+ l.r.Move(1)
+ return DelimToken, l.r.Shift()
+}
+
+////////////////////////////////////////////////////////////////
+
+/*
+The following functions follow the railroad diagrams in http://www.w3.org/TR/css3-syntax/
+*/
+
+func (l *Lexer) consumeByte(c byte) bool {
+ if l.r.Peek(0) == c {
+ l.r.Move(1)
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeComment() bool {
+ if l.r.Peek(0) != '/' || l.r.Peek(1) != '*' {
+ return false
+ }
+ l.r.Move(2)
+ for {
+ c := l.r.Peek(0)
+ if c == 0 && l.r.Err() != nil {
+ break
+ } else if c == '*' && l.r.Peek(1) == '/' {
+ l.r.Move(2)
+ return true
+ }
+ l.r.Move(1)
+ }
+ return true
+}
+
+func (l *Lexer) consumeNewline() bool {
+ c := l.r.Peek(0)
+ if c == '\n' || c == '\f' {
+ l.r.Move(1)
+ return true
+ } else if c == '\r' {
+ if l.r.Peek(1) == '\n' {
+ l.r.Move(2)
+ } else {
+ l.r.Move(1)
+ }
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeWhitespace() bool {
+ c := l.r.Peek(0)
+ if c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' {
+ l.r.Move(1)
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeDigit() bool {
+ c := l.r.Peek(0)
+ if c >= '0' && c <= '9' {
+ l.r.Move(1)
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeHexDigit() bool {
+ c := l.r.Peek(0)
+ if (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') {
+ l.r.Move(1)
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeEscape() bool {
+ if l.r.Peek(0) != '\\' {
+ return false
+ }
+ mark := l.r.Pos()
+ l.r.Move(1)
+ if l.consumeNewline() {
+ l.r.Rewind(mark)
+ return false
+ } else if l.consumeHexDigit() {
+ for k := 1; k < 6; k++ {
+ if !l.consumeHexDigit() {
+ break
+ }
+ }
+ l.consumeWhitespace()
+ return true
+ } else {
+ c := l.r.Peek(0)
+ if c >= 0xC0 {
+ _, n := l.r.PeekRune(0)
+ l.r.Move(n)
+ return true
+ } else if c == 0 && l.r.Err() != nil {
+ l.r.Rewind(mark)
+ return false
+ }
+ }
+ l.r.Move(1)
+ return true
+}
+
+func (l *Lexer) consumeIdentToken() bool {
+ mark := l.r.Pos()
+ if l.r.Peek(0) == '-' {
+ l.r.Move(1)
+ }
+ c := l.r.Peek(0)
+ if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c >= 0x80) {
+ if c != '\\' || !l.consumeEscape() {
+ l.r.Rewind(mark)
+ return false
+ }
+ } else {
+ l.r.Move(1)
+ }
+ for {
+ c := l.r.Peek(0)
+ if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c >= 0x80) {
+ if c != '\\' || !l.consumeEscape() {
+ break
+ }
+ } else {
+ l.r.Move(1)
+ }
+ }
+ return true
+}
+
+// support custom variables, https://www.w3.org/TR/css-variables-1/
+func (l *Lexer) consumeCustomVariableToken() bool {
+ // expect to be on a '-'
+ l.r.Move(1)
+ if l.r.Peek(0) != '-' {
+ l.r.Move(-1)
+ return false
+ }
+ if !l.consumeIdentToken() {
+ l.r.Move(-1)
+ return false
+ }
+ return true
+}
+
+func (l *Lexer) consumeAtKeywordToken() bool {
+ // expect to be on an '@'
+ l.r.Move(1)
+ if !l.consumeIdentToken() {
+ l.r.Move(-1)
+ return false
+ }
+ return true
+}
+
+func (l *Lexer) consumeHashToken() bool {
+ // expect to be on a '#'
+ mark := l.r.Pos()
+ l.r.Move(1)
+ c := l.r.Peek(0)
+ if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c >= 0x80) {
+ if c != '\\' || !l.consumeEscape() {
+ l.r.Rewind(mark)
+ return false
+ }
+ } else {
+ l.r.Move(1)
+ }
+ for {
+ c := l.r.Peek(0)
+ if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c >= 0x80) {
+ if c != '\\' || !l.consumeEscape() {
+ break
+ }
+ } else {
+ l.r.Move(1)
+ }
+ }
+ return true
+}
+
+func (l *Lexer) consumeNumberToken() bool {
+ mark := l.r.Pos()
+ c := l.r.Peek(0)
+ if c == '+' || c == '-' {
+ l.r.Move(1)
+ }
+ firstDigit := l.consumeDigit()
+ if firstDigit {
+ for l.consumeDigit() {
+ }
+ }
+ if l.r.Peek(0) == '.' {
+ l.r.Move(1)
+ if l.consumeDigit() {
+ for l.consumeDigit() {
+ }
+ } else if firstDigit {
+ // . could belong to the next token
+ l.r.Move(-1)
+ return true
+ } else {
+ l.r.Rewind(mark)
+ return false
+ }
+ } else if !firstDigit {
+ l.r.Rewind(mark)
+ return false
+ }
+ mark = l.r.Pos()
+ c = l.r.Peek(0)
+ if c == 'e' || c == 'E' {
+ l.r.Move(1)
+ c = l.r.Peek(0)
+ if c == '+' || c == '-' {
+ l.r.Move(1)
+ }
+ if !l.consumeDigit() {
+ // e could belong to next token
+ l.r.Rewind(mark)
+ return true
+ }
+ for l.consumeDigit() {
+ }
+ }
+ return true
+}
+
+func (l *Lexer) consumeUnicodeRangeToken() bool {
+ c := l.r.Peek(0)
+ if (c != 'u' && c != 'U') || l.r.Peek(1) != '+' {
+ return false
+ }
+ mark := l.r.Pos()
+ l.r.Move(2)
+
+ // consume up to 6 hexDigits
+ k := 0
+ for l.consumeHexDigit() {
+ k++
+ }
+
+ // either a minus or a question mark or the end is expected
+ if l.consumeByte('-') {
+ if k == 0 || 6 < k {
+ l.r.Rewind(mark)
+ return false
+ }
+
+ // consume another up to 6 hexDigits
+ if l.consumeHexDigit() {
+ k = 1
+ for l.consumeHexDigit() {
+ k++
+ }
+ } else {
+ l.r.Rewind(mark)
+ return false
+ }
+ } else if l.consumeByte('?') {
+ // could be filled up to 6 characters with question marks or else regular hexDigits
+ k++
+ for l.consumeByte('?') {
+ k++
+ }
+ }
+ if k == 0 || 6 < k {
+ l.r.Rewind(mark)
+ return false
+ }
+ return true
+}
+
+func (l *Lexer) consumeColumnToken() bool {
+ if l.r.Peek(0) == '|' && l.r.Peek(1) == '|' {
+ l.r.Move(2)
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeCDOToken() bool {
+ if l.r.Peek(0) == '<' && l.r.Peek(1) == '!' && l.r.Peek(2) == '-' && l.r.Peek(3) == '-' {
+ l.r.Move(4)
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeCDCToken() bool {
+ if l.r.Peek(0) == '-' && l.r.Peek(1) == '-' && l.r.Peek(2) == '>' {
+ l.r.Move(3)
+ return true
+ }
+ return false
+}
+
+////////////////////////////////////////////////////////////////
+
+// consumeMatch consumes any MatchToken.
+func (l *Lexer) consumeMatch() TokenType {
+ if l.r.Peek(1) == '=' {
+ switch l.r.Peek(0) {
+ case '~':
+ l.r.Move(2)
+ return IncludeMatchToken
+ case '|':
+ l.r.Move(2)
+ return DashMatchToken
+ case '^':
+ l.r.Move(2)
+ return PrefixMatchToken
+ case '$':
+ l.r.Move(2)
+ return SuffixMatchToken
+ case '*':
+ l.r.Move(2)
+ return SubstringMatchToken
+ }
+ }
+ return ErrorToken
+}
+
+// consumeBracket consumes any bracket token.
+func (l *Lexer) consumeBracket() TokenType {
+ switch l.r.Peek(0) {
+ case '(':
+ l.r.Move(1)
+ return LeftParenthesisToken
+ case ')':
+ l.r.Move(1)
+ return RightParenthesisToken
+ case '[':
+ l.r.Move(1)
+ return LeftBracketToken
+ case ']':
+ l.r.Move(1)
+ return RightBracketToken
+ case '{':
+ l.r.Move(1)
+ return LeftBraceToken
+ case '}':
+ l.r.Move(1)
+ return RightBraceToken
+ }
+ return ErrorToken
+}
+
+// consumeNumeric consumes NumberToken, PercentageToken or DimensionToken.
+func (l *Lexer) consumeNumeric() TokenType {
+ if l.consumeNumberToken() {
+ if l.consumeByte('%') {
+ return PercentageToken
+ } else if l.consumeIdentToken() {
+ return DimensionToken
+ }
+ return NumberToken
+ }
+ return ErrorToken
+}
+
+// consumeString consumes a string and may return BadStringToken when a newline is encountered.
+func (l *Lexer) consumeString() TokenType {
+ // assume to be on " or '
+ delim := l.r.Peek(0)
+ l.r.Move(1)
+ for {
+ c := l.r.Peek(0)
+ if c == 0 && l.r.Err() != nil {
+ break
+ } else if c == '\n' || c == '\r' || c == '\f' {
+ l.r.Move(1)
+ return BadStringToken
+ } else if c == delim {
+ l.r.Move(1)
+ break
+ } else if c == '\\' {
+ if !l.consumeEscape() {
+ // either newline or EOF after backslash
+ l.r.Move(1)
+ l.consumeNewline()
+ }
+ } else {
+ l.r.Move(1)
+ }
+ }
+ return StringToken
+}
+
+func (l *Lexer) consumeUnquotedURL() bool {
+ for {
+ c := l.r.Peek(0)
+ if c == 0 && l.r.Err() != nil || c == ')' {
+ break
+ } else if c == '"' || c == '\'' || c == '(' || c == '\\' || c == ' ' || c <= 0x1F || c == 0x7F {
+ if c != '\\' || !l.consumeEscape() {
+ return false
+ }
+ } else {
+ l.r.Move(1)
+ }
+ }
+ return true
+}
+
+// consumeRemnantsBadUrl consumes bytes of a BadUrlToken so that normal tokenization may continue.
+func (l *Lexer) consumeRemnantsBadURL() {
+ for {
+ if l.consumeByte(')') || l.r.Err() != nil {
+ break
+ } else if !l.consumeEscape() {
+ l.r.Move(1)
+ }
+ }
+}
+
+// consumeIdentlike consumes IdentToken, FunctionToken or UrlToken.
+func (l *Lexer) consumeIdentlike() TokenType {
+ if l.consumeIdentToken() {
+ if l.r.Peek(0) != '(' {
+ return IdentToken
+ } else if !parse.EqualFold(bytes.Replace(l.r.Lexeme(), []byte{'\\'}, nil, -1), []byte{'u', 'r', 'l'}) {
+ l.r.Move(1)
+ return FunctionToken
+ }
+ l.r.Move(1)
+
+ // consume url
+ for l.consumeWhitespace() {
+ }
+ if c := l.r.Peek(0); c == '"' || c == '\'' {
+ if l.consumeString() == BadStringToken {
+ l.consumeRemnantsBadURL()
+ return BadURLToken
+ }
+ } else if !l.consumeUnquotedURL() && !l.consumeWhitespace() { // if unquoted URL fails due to encountering whitespace, continue
+ l.consumeRemnantsBadURL()
+ return BadURLToken
+ }
+ for l.consumeWhitespace() {
+ }
+ if !l.consumeByte(')') && l.r.Err() != io.EOF {
+ l.consumeRemnantsBadURL()
+ return BadURLToken
+ }
+ return URLToken
+ }
+ return ErrorToken
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/css/parse.go b/vendor/github.com/tdewolff/parse/v2/css/parse.go
new file mode 100644
index 0000000..8daa40a
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/css/parse.go
@@ -0,0 +1,462 @@
+package css
+
+import (
+ "bytes"
+ "fmt"
+ "strconv"
+
+ "github.com/tdewolff/parse/v2"
+ "github.com/tdewolff/parse/v2/buffer"
+)
+
+var wsBytes = []byte(" ")
+var endBytes = []byte("}")
+var emptyBytes = []byte("")
+
+// GrammarType determines the type of grammar.
+type GrammarType uint32
+
+// GrammarType values.
+const (
+ ErrorGrammar GrammarType = iota // extra token when errors occur
+ CommentGrammar
+ AtRuleGrammar
+ BeginAtRuleGrammar
+ EndAtRuleGrammar
+ QualifiedRuleGrammar
+ BeginRulesetGrammar
+ EndRulesetGrammar
+ DeclarationGrammar
+ TokenGrammar
+ CustomPropertyGrammar
+)
+
+// String returns the string representation of a GrammarType.
+func (tt GrammarType) String() string {
+ switch tt {
+ case ErrorGrammar:
+ return "Error"
+ case CommentGrammar:
+ return "Comment"
+ case AtRuleGrammar:
+ return "AtRule"
+ case BeginAtRuleGrammar:
+ return "BeginAtRule"
+ case EndAtRuleGrammar:
+ return "EndAtRule"
+ case QualifiedRuleGrammar:
+ return "QualifiedRule"
+ case BeginRulesetGrammar:
+ return "BeginRuleset"
+ case EndRulesetGrammar:
+ return "EndRuleset"
+ case DeclarationGrammar:
+ return "Declaration"
+ case TokenGrammar:
+ return "Token"
+ case CustomPropertyGrammar:
+ return "CustomProperty"
+ }
+ return "Invalid(" + strconv.Itoa(int(tt)) + ")"
+}
+
+////////////////////////////////////////////////////////////////
+
+// State is the state function the parser currently is in.
+type State func(*Parser) GrammarType
+
+// Token is a single TokenType and its associated data.
+type Token struct {
+ TokenType
+ Data []byte
+}
+
+func (t Token) String() string {
+ return t.TokenType.String() + "('" + string(t.Data) + "')"
+}
+
+// Parser is the state for the parser.
+type Parser struct {
+ l *Lexer
+ state []State
+ err string
+ errPos int
+
+ buf []Token
+ level int
+
+ data []byte
+ tt TokenType
+ keepWS bool
+ prevWS bool
+ prevEnd bool
+ prevComment bool
+}
+
+// NewParser returns a new CSS parser from an io.Reader. isInline specifies whether this is an inline style attribute.
+func NewParser(r *parse.Input, isInline bool) *Parser {
+ l := NewLexer(r)
+ p := &Parser{
+ l: l,
+ state: make([]State, 0, 4),
+ }
+
+ if isInline {
+ p.state = append(p.state, (*Parser).parseDeclarationList)
+ } else {
+ p.state = append(p.state, (*Parser).parseStylesheet)
+ }
+ return p
+}
+
+// HasParseError returns true if there is a parse error (and not a read error).
+func (p *Parser) HasParseError() bool {
+ return p.err != ""
+}
+
+// Err returns the error encountered during parsing, this is often io.EOF but also other errors can be returned.
+func (p *Parser) Err() error {
+ if p.err != "" {
+ r := buffer.NewReader(p.l.r.Bytes())
+ return parse.NewError(r, p.errPos, p.err)
+ }
+ return p.l.Err()
+}
+
+// Next returns the next Grammar. It returns ErrorGrammar when an error was encountered. Using Err() one can retrieve the error message.
+func (p *Parser) Next() (GrammarType, TokenType, []byte) {
+ p.err = ""
+
+ if p.prevEnd {
+ p.tt, p.data = RightBraceToken, endBytes
+ p.prevEnd = false
+ } else {
+ p.tt, p.data = p.popToken(true)
+ }
+ gt := p.state[len(p.state)-1](p)
+ return gt, p.tt, p.data
+}
+
+// Offset return offset for current Grammar
+func (p *Parser) Offset() int {
+ return p.l.r.Offset()
+}
+
+// Values returns a slice of Tokens for the last Grammar. Only AtRuleGrammar, BeginAtRuleGrammar, BeginRulesetGrammar and Declaration will return the at-rule components, ruleset selector and declaration values respectively.
+func (p *Parser) Values() []Token {
+ return p.buf
+}
+
+func (p *Parser) popToken(allowComment bool) (TokenType, []byte) {
+ p.prevWS = false
+ p.prevComment = false
+ tt, data := p.l.Next()
+ for !p.keepWS && tt == WhitespaceToken || tt == CommentToken {
+ if tt == WhitespaceToken {
+ p.prevWS = true
+ } else {
+ p.prevComment = true
+ if allowComment && len(p.state) == 1 {
+ break
+ }
+ }
+ tt, data = p.l.Next()
+ }
+ return tt, data
+}
+
+func (p *Parser) initBuf() {
+ p.buf = p.buf[:0]
+}
+
+func (p *Parser) pushBuf(tt TokenType, data []byte) {
+ p.buf = append(p.buf, Token{tt, data})
+}
+
+////////////////////////////////////////////////////////////////
+
+func (p *Parser) parseStylesheet() GrammarType {
+ if p.tt == CDOToken || p.tt == CDCToken {
+ return TokenGrammar
+ } else if p.tt == AtKeywordToken {
+ return p.parseAtRule()
+ } else if p.tt == CommentToken {
+ return CommentGrammar
+ } else if p.tt == ErrorToken {
+ return ErrorGrammar
+ }
+ return p.parseQualifiedRule()
+}
+
+func (p *Parser) parseDeclarationList() GrammarType {
+ if p.tt == CommentToken {
+ p.tt, p.data = p.popToken(false)
+ }
+ for p.tt == SemicolonToken {
+ p.tt, p.data = p.popToken(false)
+ }
+
+ // IE hack: *color:red;
+ if p.tt == DelimToken && p.data[0] == '*' {
+ tt, data := p.popToken(false)
+ p.tt = tt
+ p.data = append(p.data, data...)
+ }
+
+ if p.tt == ErrorToken {
+ return ErrorGrammar
+ } else if p.tt == AtKeywordToken {
+ return p.parseAtRule()
+ } else if p.tt == IdentToken || p.tt == DelimToken {
+ return p.parseDeclaration()
+ } else if p.tt == CustomPropertyNameToken {
+ return p.parseCustomProperty()
+ }
+
+ // parse error
+ p.initBuf()
+ p.l.r.Move(-len(p.data))
+ p.err, p.errPos = fmt.Sprintf("CSS parse error: unexpected token '%s' in declaration", string(p.data)), p.l.r.Offset()
+ p.l.r.Move(len(p.data))
+
+ if p.tt == RightBraceToken {
+ // right brace token will occur when we've had a decl error that ended in a right brace token
+ // as these are not handled by decl error, we handle it here explicitly. Normally its used to end eg. the qual rule.
+ p.pushBuf(p.tt, p.data)
+ return ErrorGrammar
+ }
+ return p.parseDeclarationError(p.tt, p.data)
+}
+
+////////////////////////////////////////////////////////////////
+
+func (p *Parser) parseAtRule() GrammarType {
+ p.initBuf()
+ p.data = parse.ToLower(parse.Copy(p.data))
+ atRuleName := p.data
+ if len(atRuleName) > 0 && atRuleName[1] == '-' {
+ if i := bytes.IndexByte(atRuleName[2:], '-'); i != -1 {
+ atRuleName = atRuleName[i+2:] // skip vendor specific prefix
+ }
+ }
+ atRule := ToHash(atRuleName[1:])
+
+ first := true
+ skipWS := false
+ for {
+ tt, data := p.popToken(false)
+ if tt == LeftBraceToken && p.level == 0 {
+ if atRule == Font_Face || atRule == Page {
+ p.state = append(p.state, (*Parser).parseAtRuleDeclarationList)
+ } else if atRule == Document || atRule == Keyframes || atRule == Media || atRule == Supports {
+ p.state = append(p.state, (*Parser).parseAtRuleRuleList)
+ } else {
+ p.state = append(p.state, (*Parser).parseAtRuleUnknown)
+ }
+ return BeginAtRuleGrammar
+ } else if (tt == SemicolonToken || tt == RightBraceToken) && p.level == 0 || tt == ErrorToken {
+ p.prevEnd = (tt == RightBraceToken)
+ return AtRuleGrammar
+ } else if tt == LeftParenthesisToken || tt == LeftBraceToken || tt == LeftBracketToken || tt == FunctionToken {
+ p.level++
+ } else if tt == RightParenthesisToken || tt == RightBraceToken || tt == RightBracketToken {
+ p.level--
+ }
+ if first {
+ if tt == LeftParenthesisToken || tt == LeftBracketToken {
+ p.prevWS = false
+ }
+ first = false
+ }
+ if len(data) == 1 && (data[0] == ',' || data[0] == ':') {
+ skipWS = true
+ } else if p.prevWS && !skipWS && tt != RightParenthesisToken {
+ p.pushBuf(WhitespaceToken, wsBytes)
+ } else {
+ skipWS = false
+ }
+ if tt == LeftParenthesisToken {
+ skipWS = true
+ }
+ p.pushBuf(tt, data)
+ }
+}
+
+func (p *Parser) parseAtRuleRuleList() GrammarType {
+ if p.tt == RightBraceToken || p.tt == ErrorToken {
+ p.state = p.state[:len(p.state)-1]
+ return EndAtRuleGrammar
+ } else if p.tt == AtKeywordToken {
+ return p.parseAtRule()
+ } else {
+ return p.parseQualifiedRule()
+ }
+}
+
+func (p *Parser) parseAtRuleDeclarationList() GrammarType {
+ for p.tt == SemicolonToken {
+ p.tt, p.data = p.popToken(false)
+ }
+ if p.tt == RightBraceToken || p.tt == ErrorToken {
+ p.state = p.state[:len(p.state)-1]
+ return EndAtRuleGrammar
+ }
+ return p.parseDeclarationList()
+}
+
+func (p *Parser) parseAtRuleUnknown() GrammarType {
+ p.keepWS = true
+ if p.tt == RightBraceToken && p.level == 0 || p.tt == ErrorToken {
+ p.state = p.state[:len(p.state)-1]
+ p.keepWS = false
+ return EndAtRuleGrammar
+ }
+ if p.tt == LeftParenthesisToken || p.tt == LeftBraceToken || p.tt == LeftBracketToken || p.tt == FunctionToken {
+ p.level++
+ } else if p.tt == RightParenthesisToken || p.tt == RightBraceToken || p.tt == RightBracketToken {
+ p.level--
+ }
+ return TokenGrammar
+}
+
+func (p *Parser) parseQualifiedRule() GrammarType {
+ p.initBuf()
+ first := true
+ inAttrSel := false
+ skipWS := true
+ var tt TokenType
+ var data []byte
+ for {
+ if first {
+ tt, data = p.tt, p.data
+ p.tt = WhitespaceToken
+ p.data = emptyBytes
+ first = false
+ } else {
+ tt, data = p.popToken(false)
+ }
+ if tt == LeftBraceToken && p.level == 0 {
+ p.state = append(p.state, (*Parser).parseQualifiedRuleDeclarationList)
+ return BeginRulesetGrammar
+ } else if tt == ErrorToken {
+ p.err, p.errPos = "CSS parse error: unexpected ending in qualified rule", p.l.r.Offset()
+ return ErrorGrammar
+ } else if tt == LeftParenthesisToken || tt == LeftBraceToken || tt == LeftBracketToken || tt == FunctionToken {
+ p.level++
+ } else if tt == RightParenthesisToken || tt == RightBraceToken || tt == RightBracketToken {
+ p.level--
+ }
+ if len(data) == 1 && (data[0] == ',' || data[0] == '>' || data[0] == '+' || data[0] == '~') {
+ if data[0] == ',' {
+ return QualifiedRuleGrammar
+ }
+ skipWS = true
+ } else if p.prevWS && !skipWS && !inAttrSel {
+ p.pushBuf(WhitespaceToken, wsBytes)
+ } else {
+ skipWS = false
+ }
+ if tt == LeftBracketToken {
+ inAttrSel = true
+ } else if tt == RightBracketToken {
+ inAttrSel = false
+ }
+ p.pushBuf(tt, data)
+ }
+}
+
+func (p *Parser) parseQualifiedRuleDeclarationList() GrammarType {
+ for p.tt == SemicolonToken {
+ p.tt, p.data = p.popToken(false)
+ }
+ if p.tt == RightBraceToken || p.tt == ErrorToken {
+ p.state = p.state[:len(p.state)-1]
+ return EndRulesetGrammar
+ }
+ return p.parseDeclarationList()
+}
+
+func (p *Parser) parseDeclaration() GrammarType {
+ p.initBuf()
+ p.data = parse.ToLower(parse.Copy(p.data))
+
+ ttName, dataName := p.tt, p.data
+ tt, data := p.popToken(false)
+ if tt != ColonToken {
+ p.l.r.Move(-len(data))
+ p.err, p.errPos = "CSS parse error: expected colon in declaration", p.l.r.Offset()
+ p.l.r.Move(len(data))
+ p.pushBuf(ttName, dataName)
+ return p.parseDeclarationError(tt, data)
+ }
+
+ skipWS := true
+ for {
+ tt, data := p.popToken(false)
+ if (tt == SemicolonToken || tt == RightBraceToken) && p.level == 0 || tt == ErrorToken {
+ p.prevEnd = (tt == RightBraceToken)
+ return DeclarationGrammar
+ } else if tt == LeftParenthesisToken || tt == LeftBraceToken || tt == LeftBracketToken || tt == FunctionToken {
+ p.level++
+ } else if tt == RightParenthesisToken || tt == RightBraceToken || tt == RightBracketToken {
+ p.level--
+ }
+ if len(data) == 1 && (data[0] == ',' || data[0] == '/' || data[0] == ':' || data[0] == '!' || data[0] == '=') {
+ skipWS = true
+ } else if (p.prevWS || p.prevComment) && !skipWS {
+ p.pushBuf(WhitespaceToken, wsBytes)
+ } else {
+ skipWS = false
+ }
+ p.pushBuf(tt, data)
+ }
+}
+
+func (p *Parser) parseDeclarationError(tt TokenType, data []byte) GrammarType {
+ // we're on the offending (tt,data), keep popping tokens till we reach ;, }, or EOF
+ p.tt, p.data = tt, data
+ for {
+ if (tt == SemicolonToken || tt == RightBraceToken) && p.level == 0 || tt == ErrorToken {
+ p.prevEnd = (tt == RightBraceToken)
+ if tt == SemicolonToken {
+ p.pushBuf(tt, data)
+ }
+ return ErrorGrammar
+ } else if tt == LeftParenthesisToken || tt == LeftBraceToken || tt == LeftBracketToken || tt == FunctionToken {
+ p.level++
+ } else if tt == RightParenthesisToken || tt == RightBraceToken || tt == RightBracketToken {
+ p.level--
+ }
+
+ if p.prevWS {
+ p.pushBuf(WhitespaceToken, wsBytes)
+ }
+ p.pushBuf(tt, data)
+
+ tt, data = p.popToken(false)
+ }
+}
+
+func (p *Parser) parseCustomProperty() GrammarType {
+ p.initBuf()
+ if tt, data := p.popToken(false); tt != ColonToken {
+ p.l.r.Move(-len(data))
+ p.err, p.errPos = "CSS parse error: expected colon in custom property", p.l.r.Offset()
+ p.l.r.Move(len(data))
+ return ErrorGrammar
+ }
+ val := []byte{}
+ for {
+ tt, data := p.l.Next()
+ if (tt == SemicolonToken || tt == RightBraceToken) && p.level == 0 || tt == ErrorToken {
+ p.prevEnd = (tt == RightBraceToken)
+ p.pushBuf(CustomPropertyValueToken, val)
+ return CustomPropertyGrammar
+ } else if tt == LeftParenthesisToken || tt == LeftBraceToken || tt == LeftBracketToken || tt == FunctionToken {
+ p.level++
+ } else if tt == RightParenthesisToken || tt == RightBraceToken || tt == RightBracketToken {
+ p.level--
+ }
+ val = append(val, data...)
+ }
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/css/util.go b/vendor/github.com/tdewolff/parse/v2/css/util.go
new file mode 100644
index 0000000..20b99a7
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/css/util.go
@@ -0,0 +1,47 @@
+package css
+
+import "github.com/tdewolff/parse/v2"
+
+// IsIdent returns true if the bytes are a valid identifier.
+func IsIdent(b []byte) bool {
+ l := NewLexer(parse.NewInputBytes(b))
+ l.consumeIdentToken()
+ l.r.Restore()
+ return l.r.Pos() == len(b)
+}
+
+// IsURLUnquoted returns true if the bytes are a valid unquoted URL.
+func IsURLUnquoted(b []byte) bool {
+ l := NewLexer(parse.NewInputBytes(b))
+ l.consumeUnquotedURL()
+ l.r.Restore()
+ return l.r.Pos() == len(b)
+}
+
+// HSL2RGB converts HSL to RGB with all of range [0,1]
+// from http://www.w3.org/TR/css3-color/#hsl-color
+func HSL2RGB(h, s, l float64) (float64, float64, float64) {
+ m2 := l * (s + 1)
+ if l > 0.5 {
+ m2 = l + s - l*s
+ }
+ m1 := l*2 - m2
+ return hue2rgb(m1, m2, h+1.0/3.0), hue2rgb(m1, m2, h), hue2rgb(m1, m2, h-1.0/3.0)
+}
+
+func hue2rgb(m1, m2, h float64) float64 {
+ if h < 0.0 {
+ h += 1.0
+ }
+ if h > 1.0 {
+ h -= 1.0
+ }
+ if h*6.0 < 1.0 {
+ return m1 + (m2-m1)*h*6.0
+ } else if h*2.0 < 1.0 {
+ return m2
+ } else if h*3.0 < 2.0 {
+ return m1 + (m2-m1)*(2.0/3.0-h)*6.0
+ }
+ return m1
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/error.go b/vendor/github.com/tdewolff/parse/v2/error.go
new file mode 100644
index 0000000..f6657f7
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/error.go
@@ -0,0 +1,47 @@
+package parse
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+)
+
+// Error is a parsing error returned by parser. It contains a message and an offset at which the error occurred.
+type Error struct {
+ Message string
+ Line int
+ Column int
+ Context string
+}
+
+// NewError creates a new error
+func NewError(r io.Reader, offset int, message string, a ...interface{}) *Error {
+ line, column, context := Position(r, offset)
+ if 0 < len(a) {
+ message = fmt.Sprintf(message, a...)
+ }
+ return &Error{
+ Message: message,
+ Line: line,
+ Column: column,
+ Context: context,
+ }
+}
+
+// NewErrorLexer creates a new error from an active Lexer.
+func NewErrorLexer(l *Input, message string, a ...interface{}) *Error {
+ r := bytes.NewBuffer(l.Bytes())
+ offset := l.Offset()
+ return NewError(r, offset, message, a...)
+}
+
+// Position returns the line, column, and context of the error.
+// Context is the entire line at which the error occurred.
+func (e *Error) Position() (int, int, string) {
+ return e.Line, e.Column, e.Context
+}
+
+// Error returns the error string, containing the context and line + column number.
+func (e *Error) Error() string {
+ return fmt.Sprintf("%s on line %d and column %d\n%s", e.Message, e.Line, e.Column, e.Context)
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/html/README.md b/vendor/github.com/tdewolff/parse/v2/html/README.md
new file mode 100644
index 0000000..53145db
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/html/README.md
@@ -0,0 +1,98 @@
+# HTML [![API reference](https://img.shields.io/badge/godoc-reference-5272B4)](https://pkg.go.dev/github.com/tdewolff/parse/v2/html?tab=doc)
+
+This package is an HTML5 lexer written in [Go][1]. It follows the specification at [The HTML syntax](http://www.w3.org/TR/html5/syntax.html). The lexer takes an io.Reader and converts it into tokens until the EOF.
+
+## Installation
+Run the following command
+
+ go get -u github.com/tdewolff/parse/v2/html
+
+or add the following import and run project with `go get`
+
+ import "github.com/tdewolff/parse/v2/html"
+
+## Lexer
+### Usage
+The following initializes a new Lexer with io.Reader `r`:
+``` go
+l := html.NewLexer(parse.NewInput(r))
+```
+
+To tokenize until EOF an error, use:
+``` go
+for {
+ tt, data := l.Next()
+ switch tt {
+ case html.ErrorToken:
+ // error or EOF set in l.Err()
+ return
+ case html.StartTagToken:
+ // ...
+ for {
+ ttAttr, dataAttr := l.Next()
+ if ttAttr != html.AttributeToken {
+ break
+ }
+ // ...
+ }
+ // ...
+ }
+}
+```
+
+All tokens:
+``` go
+ErrorToken TokenType = iota // extra token when errors occur
+CommentToken
+DoctypeToken
+StartTagToken
+StartTagCloseToken
+StartTagVoidToken
+EndTagToken
+AttributeToken
+TextToken
+```
+
+### Examples
+``` go
+package main
+
+import (
+ "os"
+
+ "github.com/tdewolff/parse/v2/html"
+)
+
+// Tokenize HTML from stdin.
+func main() {
+ l := html.NewLexer(parse.NewInput(os.Stdin))
+ for {
+ tt, data := l.Next()
+ switch tt {
+ case html.ErrorToken:
+ if l.Err() != io.EOF {
+ fmt.Println("Error on line", l.Line(), ":", l.Err())
+ }
+ return
+ case html.StartTagToken:
+ fmt.Println("Tag", string(data))
+ for {
+ ttAttr, dataAttr := l.Next()
+ if ttAttr != html.AttributeToken {
+ break
+ }
+
+ key := dataAttr
+ val := l.AttrVal()
+ fmt.Println("Attribute", string(key), "=", string(val))
+ }
+ // ...
+ }
+ }
+}
+```
+
+## License
+Released under the [MIT license](https://github.com/tdewolff/parse/blob/master/LICENSE.md).
+
+[1]: http://golang.org/ "Go Language"
diff --git a/vendor/github.com/tdewolff/parse/v2/html/hash.go b/vendor/github.com/tdewolff/parse/v2/html/hash.go
new file mode 100644
index 0000000..16432ad
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/html/hash.go
@@ -0,0 +1,81 @@
+package html
+
+// generated by hasher -type=Hash -file=hash.go; DO NOT EDIT, except for adding more constants to the list and rerun go generate
+
+// uses github.com/tdewolff/hasher
+//go:generate hasher -type=Hash -file=hash.go
+
+// Hash defines perfect hashes for a predefined list of strings
+type Hash uint32
+
+// Unique hash definitions to be used instead of strings
+const (
+ Iframe Hash = 0x6 // iframe
+ Math Hash = 0x604 // math
+ Plaintext Hash = 0x1e09 // plaintext
+ Script Hash = 0xa06 // script
+ Style Hash = 0x1405 // style
+ Svg Hash = 0x1903 // svg
+ Textarea Hash = 0x2308 // textarea
+ Title Hash = 0xf05 // title
+ Xmp Hash = 0x1c03 // xmp
+)
+
+// String returns the hash' name.
+func (i Hash) String() string {
+ start := uint32(i >> 8)
+ n := uint32(i & 0xff)
+ if start+n > uint32(len(_Hash_text)) {
+ return ""
+ }
+ return _Hash_text[start : start+n]
+}
+
+// ToHash returns the hash whose name is s. It returns zero if there is no
+// such hash. It is case sensitive.
+func ToHash(s []byte) Hash {
+ if len(s) == 0 || len(s) > _Hash_maxLen {
+ return 0
+ }
+ h := uint32(_Hash_hash0)
+ for i := 0; i < len(s); i++ {
+ h ^= uint32(s[i])
+ h *= 16777619
+ }
+ if i := _Hash_table[h&uint32(len(_Hash_table)-1)]; int(i&0xff) == len(s) {
+ t := _Hash_text[i>>8 : i>>8+i&0xff]
+ for i := 0; i < len(s); i++ {
+ if t[i] != s[i] {
+ goto NEXT
+ }
+ }
+ return i
+ }
+NEXT:
+ if i := _Hash_table[(h>>16)&uint32(len(_Hash_table)-1)]; int(i&0xff) == len(s) {
+ t := _Hash_text[i>>8 : i>>8+i&0xff]
+ for i := 0; i < len(s); i++ {
+ if t[i] != s[i] {
+ return 0
+ }
+ }
+ return i
+ }
+ return 0
+}
+
+const _Hash_hash0 = 0x9acb0442
+const _Hash_maxLen = 9
+const _Hash_text = "iframemathscriptitlestylesvgxmplaintextarea"
+
+var _Hash_table = [1 << 4]Hash{
+ 0x0: 0x2308, // textarea
+ 0x2: 0x6, // iframe
+ 0x4: 0xf05, // title
+ 0x5: 0x1e09, // plaintext
+ 0x7: 0x1405, // style
+ 0x8: 0x604, // math
+ 0x9: 0xa06, // script
+ 0xa: 0x1903, // svg
+ 0xb: 0x1c03, // xmp
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/html/lex.go b/vendor/github.com/tdewolff/parse/v2/html/lex.go
new file mode 100644
index 0000000..4325024
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/html/lex.go
@@ -0,0 +1,494 @@
+// Package html is an HTML5 lexer following the specifications at http://www.w3.org/TR/html5/syntax.html.
+package html
+
+import (
+ "strconv"
+
+ "github.com/tdewolff/parse/v2"
+)
+
+// TokenType determines the type of token, eg. a number or a semicolon.
+type TokenType uint32
+
+// TokenType values.
+const (
+ ErrorToken TokenType = iota // extra token when errors occur
+ CommentToken
+ DoctypeToken
+ StartTagToken
+ StartTagCloseToken
+ StartTagVoidToken
+ EndTagToken
+ AttributeToken
+ TextToken
+ SvgToken
+ MathToken
+)
+
+// String returns the string representation of a TokenType.
+func (tt TokenType) String() string {
+ switch tt {
+ case ErrorToken:
+ return "Error"
+ case CommentToken:
+ return "Comment"
+ case DoctypeToken:
+ return "Doctype"
+ case StartTagToken:
+ return "StartTag"
+ case StartTagCloseToken:
+ return "StartTagClose"
+ case StartTagVoidToken:
+ return "StartTagVoid"
+ case EndTagToken:
+ return "EndTag"
+ case AttributeToken:
+ return "Attribute"
+ case TextToken:
+ return "Text"
+ case SvgToken:
+ return "Svg"
+ case MathToken:
+ return "Math"
+ }
+ return "Invalid(" + strconv.Itoa(int(tt)) + ")"
+}
+
+////////////////////////////////////////////////////////////////
+
+// Lexer is the state for the lexer.
+type Lexer struct {
+ r *parse.Input
+ err error
+
+ rawTag Hash
+ inTag bool
+
+ text []byte
+ attrVal []byte
+}
+
+// NewLexer returns a new Lexer for a given io.Reader.
+func NewLexer(r *parse.Input) *Lexer {
+ return &Lexer{
+ r: r,
+ }
+}
+
+// Err returns the error encountered during lexing, this is often io.EOF but also other errors can be returned.
+func (l *Lexer) Err() error {
+ if l.err != nil {
+ return l.err
+ }
+ return l.r.Err()
+}
+
+// Text returns the textual representation of a token. This excludes delimiters and additional leading/trailing characters.
+func (l *Lexer) Text() []byte {
+ return l.text
+}
+
+// AttrVal returns the attribute value when an AttributeToken was returned from Next.
+func (l *Lexer) AttrVal() []byte {
+ return l.attrVal
+}
+
+// Next returns the next Token. It returns ErrorToken when an error was encountered. Using Err() one can retrieve the error message.
+func (l *Lexer) Next() (TokenType, []byte) {
+ l.text = nil
+ var c byte
+ if l.inTag {
+ l.attrVal = nil
+ for { // before attribute name state
+ if c = l.r.Peek(0); c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' {
+ l.r.Move(1)
+ continue
+ }
+ break
+ }
+ if c == 0 && l.r.Err() != nil {
+ return ErrorToken, nil
+ } else if c != '>' && (c != '/' || l.r.Peek(1) != '>') {
+ return AttributeToken, l.shiftAttribute()
+ }
+ l.r.Skip()
+ l.inTag = false
+ if c == '/' {
+ l.r.Move(2)
+ return StartTagVoidToken, l.r.Shift()
+ }
+ l.r.Move(1)
+ return StartTagCloseToken, l.r.Shift()
+ }
+
+ if l.rawTag != 0 {
+ if rawText := l.shiftRawText(); len(rawText) > 0 {
+ l.text = rawText
+ l.rawTag = 0
+ return TextToken, rawText
+ }
+ l.rawTag = 0
+ }
+
+ for {
+ c = l.r.Peek(0)
+ if c == '<' {
+ c = l.r.Peek(1)
+ isEndTag := c == '/' && l.r.Peek(2) != '>' && (l.r.Peek(2) != 0 || l.r.PeekErr(2) == nil)
+ if l.r.Pos() > 0 {
+ if isEndTag || 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '!' || c == '?' {
+ // return currently buffered texttoken so that we can return tag next iteration
+ l.text = l.r.Shift()
+ return TextToken, l.text
+ }
+ } else if isEndTag {
+ l.r.Move(2)
+ // only endtags that are not followed by > or EOF arrive here
+ if c = l.r.Peek(0); !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') {
+ return CommentToken, l.shiftBogusComment()
+ }
+ return EndTagToken, l.shiftEndTag()
+ } else if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
+ l.r.Move(1)
+ l.inTag = true
+ return l.shiftStartTag()
+ } else if c == '!' {
+ l.r.Move(2)
+ return l.readMarkup()
+ } else if c == '?' {
+ l.r.Move(1)
+ return CommentToken, l.shiftBogusComment()
+ }
+ } else if c == 0 && l.r.Err() != nil {
+ if l.r.Pos() > 0 {
+ l.text = l.r.Shift()
+ return TextToken, l.text
+ }
+ return ErrorToken, nil
+ }
+ l.r.Move(1)
+ }
+}
+
+////////////////////////////////////////////////////////////////
+
+// The following functions follow the specifications at https://html.spec.whatwg.org/multipage/parsing.html
+
+func (l *Lexer) shiftRawText() []byte {
+ if l.rawTag == Plaintext {
+ for {
+ if l.r.Peek(0) == 0 && l.r.Err() != nil {
+ return l.r.Shift()
+ }
+ l.r.Move(1)
+ }
+ } else { // RCDATA, RAWTEXT and SCRIPT
+ for {
+ c := l.r.Peek(0)
+ if c == '<' {
+ if l.r.Peek(1) == '/' {
+ mark := l.r.Pos()
+ l.r.Move(2)
+ for {
+ if c = l.r.Peek(0); !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') {
+ break
+ }
+ l.r.Move(1)
+ }
+ if h := ToHash(parse.ToLower(parse.Copy(l.r.Lexeme()[mark+2:]))); h == l.rawTag { // copy so that ToLower doesn't change the case of the underlying slice
+ l.r.Rewind(mark)
+ return l.r.Shift()
+ }
+ } else if l.rawTag == Script && l.r.Peek(1) == '!' && l.r.Peek(2) == '-' && l.r.Peek(3) == '-' {
+ l.r.Move(4)
+ inScript := false
+ for {
+ c := l.r.Peek(0)
+ if c == '-' && l.r.Peek(1) == '-' && l.r.Peek(2) == '>' {
+ l.r.Move(3)
+ break
+ } else if c == '<' {
+ isEnd := l.r.Peek(1) == '/'
+ if isEnd {
+ l.r.Move(2)
+ } else {
+ l.r.Move(1)
+ }
+ mark := l.r.Pos()
+ for {
+ if c = l.r.Peek(0); !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') {
+ break
+ }
+ l.r.Move(1)
+ }
+ if h := ToHash(parse.ToLower(parse.Copy(l.r.Lexeme()[mark:]))); h == Script { // copy so that ToLower doesn't change the case of the underlying slice
+ if !isEnd {
+ inScript = true
+ } else {
+ if !inScript {
+ l.r.Rewind(mark - 2)
+ return l.r.Shift()
+ }
+ inScript = false
+ }
+ }
+ } else if c == 0 && l.r.Err() != nil {
+ return l.r.Shift()
+ } else {
+ l.r.Move(1)
+ }
+ }
+ } else {
+ l.r.Move(1)
+ }
+ } else if c == 0 && l.r.Err() != nil {
+ return l.r.Shift()
+ } else {
+ l.r.Move(1)
+ }
+ }
+ }
+}
+
+func (l *Lexer) readMarkup() (TokenType, []byte) {
+ if l.at('-', '-') {
+ l.r.Move(2)
+ for {
+ if l.r.Peek(0) == 0 && l.r.Err() != nil {
+ l.text = l.r.Lexeme()[4:]
+ return CommentToken, l.r.Shift()
+ } else if l.at('-', '-', '>') {
+ l.text = l.r.Lexeme()[4:]
+ l.r.Move(3)
+ return CommentToken, l.r.Shift()
+ } else if l.at('-', '-', '!', '>') {
+ l.text = l.r.Lexeme()[4:]
+ l.r.Move(4)
+ return CommentToken, l.r.Shift()
+ }
+ l.r.Move(1)
+ }
+ } else if l.at('[', 'C', 'D', 'A', 'T', 'A', '[') {
+ l.r.Move(7)
+ for {
+ if l.r.Peek(0) == 0 && l.r.Err() != nil {
+ l.text = l.r.Lexeme()[9:]
+ return TextToken, l.r.Shift()
+ } else if l.at(']', ']', '>') {
+ l.text = l.r.Lexeme()[9:]
+ l.r.Move(3)
+ return TextToken, l.r.Shift()
+ }
+ l.r.Move(1)
+ }
+ } else {
+ if l.atCaseInsensitive('d', 'o', 'c', 't', 'y', 'p', 'e') {
+ l.r.Move(7)
+ if l.r.Peek(0) == ' ' {
+ l.r.Move(1)
+ }
+ for {
+ if c := l.r.Peek(0); c == '>' || c == 0 && l.r.Err() != nil {
+ l.text = l.r.Lexeme()[9:]
+ if c == '>' {
+ l.r.Move(1)
+ }
+ return DoctypeToken, l.r.Shift()
+ }
+ l.r.Move(1)
+ }
+ }
+ }
+ return CommentToken, l.shiftBogusComment()
+}
+
+func (l *Lexer) shiftBogusComment() []byte {
+ for {
+ c := l.r.Peek(0)
+ if c == '>' {
+ l.text = l.r.Lexeme()[2:]
+ l.r.Move(1)
+ return l.r.Shift()
+ } else if c == 0 && l.r.Err() != nil {
+ l.text = l.r.Lexeme()[2:]
+ return l.r.Shift()
+ }
+ l.r.Move(1)
+ }
+}
+
+func (l *Lexer) shiftStartTag() (TokenType, []byte) {
+ for {
+ if c := l.r.Peek(0); c == ' ' || c == '>' || c == '/' && l.r.Peek(1) == '>' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == 0 && l.r.Err() != nil {
+ break
+ }
+ l.r.Move(1)
+ }
+ l.text = parse.ToLower(l.r.Lexeme()[1:])
+ if h := ToHash(l.text); h == Textarea || h == Title || h == Style || h == Xmp || h == Iframe || h == Script || h == Plaintext || h == Svg || h == Math {
+ if h == Svg || h == Math {
+ data := l.shiftXML(h)
+ if l.err != nil {
+ return ErrorToken, nil
+ }
+
+ l.inTag = false
+ if h == Svg {
+ return SvgToken, data
+ }
+ return MathToken, data
+ }
+ l.rawTag = h
+ }
+ return StartTagToken, l.r.Shift()
+}
+
+func (l *Lexer) shiftAttribute() []byte {
+ nameStart := l.r.Pos()
+ var c byte
+ for { // attribute name state
+ if c = l.r.Peek(0); c == ' ' || c == '=' || c == '>' || c == '/' && l.r.Peek(1) == '>' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == 0 && l.r.Err() != nil {
+ break
+ }
+ l.r.Move(1)
+ }
+ nameEnd := l.r.Pos()
+ for { // after attribute name state
+ if c = l.r.Peek(0); c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' {
+ l.r.Move(1)
+ continue
+ }
+ break
+ }
+ if c == '=' {
+ l.r.Move(1)
+ for { // before attribute value state
+ if c = l.r.Peek(0); c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' {
+ l.r.Move(1)
+ continue
+ }
+ break
+ }
+ attrPos := l.r.Pos()
+ delim := c
+ if delim == '"' || delim == '\'' { // attribute value single- and double-quoted state
+ l.r.Move(1)
+ for {
+ c := l.r.Peek(0)
+ if c == delim {
+ l.r.Move(1)
+ break
+ } else if c == 0 && l.r.Err() != nil {
+ break
+ }
+ l.r.Move(1)
+ }
+ } else { // attribute value unquoted state
+ for {
+ if c := l.r.Peek(0); c == ' ' || c == '>' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == 0 && l.r.Err() != nil {
+ break
+ }
+ l.r.Move(1)
+ }
+ }
+ l.attrVal = l.r.Lexeme()[attrPos:]
+ } else {
+ l.r.Rewind(nameEnd)
+ l.attrVal = nil
+ }
+ l.text = parse.ToLower(l.r.Lexeme()[nameStart:nameEnd])
+ return l.r.Shift()
+}
+
+func (l *Lexer) shiftEndTag() []byte {
+ for {
+ c := l.r.Peek(0)
+ if c == '>' {
+ l.text = l.r.Lexeme()[2:]
+ l.r.Move(1)
+ break
+ } else if c == 0 && l.r.Err() != nil {
+ l.text = l.r.Lexeme()[2:]
+ break
+ }
+ l.r.Move(1)
+ }
+
+ end := len(l.text)
+ for end > 0 {
+ if c := l.text[end-1]; c == ' ' || c == '\t' || c == '\n' || c == '\r' {
+ end--
+ continue
+ }
+ break
+ }
+ l.text = l.text[:end]
+ return parse.ToLower(l.r.Shift())
+}
+
+// shiftXML parses the content of a svg or math tag according to the XML 1.1 specifications, including the tag itself.
+// So far we have already parsed `<svg` or `<math`.
+func (l *Lexer) shiftXML(rawTag Hash) []byte {
+ inQuote := false
+ for {
+ c := l.r.Peek(0)
+ if c == '"' {
+ inQuote = !inQuote
+ l.r.Move(1)
+ } else if c == '<' && !inQuote && l.r.Peek(1) == '/' {
+ mark := l.r.Pos()
+ l.r.Move(2)
+ for {
+ if c = l.r.Peek(0); !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') {
+ break
+ }
+ l.r.Move(1)
+ }
+ if h := ToHash(parse.ToLower(parse.Copy(l.r.Lexeme()[mark+2:]))); h == rawTag { // copy so that ToLower doesn't change the case of the underlying slice
+ break
+ }
+ } else if c == 0 {
+ if l.r.Err() == nil {
+ l.err = parse.NewErrorLexer(l.r, "HTML parse error: unexpected NULL character")
+ }
+ return l.r.Shift()
+ } else {
+ l.r.Move(1)
+ }
+ }
+
+ for {
+ c := l.r.Peek(0)
+ if c == '>' {
+ l.r.Move(1)
+ break
+ } else if c == 0 {
+ if l.r.Err() == nil {
+ l.err = parse.NewErrorLexer(l.r, "HTML parse error: unexpected NULL character")
+ }
+ return l.r.Shift()
+ }
+ l.r.Move(1)
+ }
+ return l.r.Shift()
+}
+
+////////////////////////////////////////////////////////////////
+
+func (l *Lexer) at(b ...byte) bool {
+ for i, c := range b {
+ if l.r.Peek(i) != c {
+ return false
+ }
+ }
+ return true
+}
+
+func (l *Lexer) atCaseInsensitive(b ...byte) bool {
+ for i, c := range b {
+ if l.r.Peek(i) != c && (l.r.Peek(i)+('a'-'A')) != c {
+ return false
+ }
+ }
+ return true
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/html/util.go b/vendor/github.com/tdewolff/parse/v2/html/util.go
new file mode 100644
index 0000000..0dbd52c
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/html/util.go
@@ -0,0 +1,113 @@
+package html
+
+var (
+ singleQuoteEntityBytes = []byte("&#39;")
+ doubleQuoteEntityBytes = []byte("&#34;")
+)
+
+// EscapeAttrVal returns the escaped attribute value bytes with quotes. Either single or double quotes are used, whichever is shorter. If there are no quotes present in the value and the value is in HTML (not XML), it will return the value without quotes.
+func EscapeAttrVal(buf *[]byte, b []byte, origQuote byte, mustQuote, isXML bool) []byte {
+ singles := 0
+ doubles := 0
+ unquoted := true
+ for _, c := range b {
+ if charTable[c] {
+ unquoted = false
+ if c == '"' {
+ doubles++
+ } else if c == '\'' {
+ singles++
+ }
+ }
+ }
+ if unquoted && (!mustQuote || origQuote == 0) && !isXML {
+ return b
+ } else if singles == 0 && origQuote == '\'' && !isXML || doubles == 0 && origQuote == '"' {
+ if len(b)+2 > cap(*buf) {
+ *buf = make([]byte, 0, len(b)+2)
+ }
+ t := (*buf)[:len(b)+2]
+ t[0] = origQuote
+ copy(t[1:], b)
+ t[1+len(b)] = origQuote
+ return t
+ }
+
+ n := len(b) + 2
+ var quote byte
+ var escapedQuote []byte
+ if singles >= doubles || isXML {
+ n += doubles * 4
+ quote = '"'
+ escapedQuote = doubleQuoteEntityBytes
+ if singles == doubles && origQuote == '\'' && !isXML {
+ quote = '\''
+ escapedQuote = singleQuoteEntityBytes
+ }
+ } else {
+ n += singles * 4
+ quote = '\''
+ escapedQuote = singleQuoteEntityBytes
+ }
+ if n > cap(*buf) {
+ *buf = make([]byte, 0, n) // maximum size, not actual size
+ }
+ t := (*buf)[:n] // maximum size, not actual size
+ t[0] = quote
+ j := 1
+ start := 0
+ for i, c := range b {
+ if c == quote {
+ j += copy(t[j:], b[start:i])
+ j += copy(t[j:], escapedQuote)
+ start = i + 1
+ }
+ }
+ j += copy(t[j:], b[start:])
+ t[j] = quote
+ return t[:j+1]
+}
+
+var charTable = [256]bool{
+ // ASCII
+ false, false, false, false, false, false, false, false,
+ false, true, true, false, true, true, false, false, // tab, line feed, form feed, carriage return
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ true, false, true, false, false, false, false, true, // space, "), '
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, true, true, true, false, // <, =, >
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ true, false, false, false, false, false, false, false, // `
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ // non-ASCII
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/input.go b/vendor/github.com/tdewolff/parse/v2/input.go
new file mode 100644
index 0000000..5b6d8f5
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/input.go
@@ -0,0 +1,173 @@
+package parse
+
+import (
+ "io"
+ "io/ioutil"
+)
+
+var nullBuffer = []byte{0}
+
+// Input is a buffered reader that allows peeking forward and shifting, taking an io.Input.
+// It keeps data in-memory until Free, taking a byte length, is called to move beyond the data.
+type Input struct {
+ buf []byte
+ pos int // index in buf
+ start int // index in buf
+ err error
+
+ restore func()
+}
+
+// NewInput returns a new Input for a given io.Input and uses ioutil.ReadAll to read it into a byte slice.
+// If the io.Input implements Bytes, that is used instead. It will append a NULL at the end of the buffer.
+func NewInput(r io.Reader) *Input {
+ var b []byte
+ if r != nil {
+ if buffer, ok := r.(interface {
+ Bytes() []byte
+ }); ok {
+ b = buffer.Bytes()
+ } else {
+ var err error
+ b, err = ioutil.ReadAll(r)
+ if err != nil {
+ return &Input{
+ buf: nullBuffer,
+ err: err,
+ }
+ }
+ }
+ }
+ return NewInputBytes(b)
+}
+
+// NewInputString returns a new Input for a given string and appends NULL at the end.
+func NewInputString(s string) *Input {
+ return NewInputBytes([]byte(s))
+}
+
+// NewInputBytes returns a new Input for a given byte slice and appends NULL at the end.
+// To avoid reallocation, make sure the capacity has room for one more byte.
+func NewInputBytes(b []byte) *Input {
+ z := &Input{
+ buf: b,
+ }
+
+ n := len(b)
+ if n == 0 {
+ z.buf = nullBuffer
+ } else {
+ // Append NULL to buffer, but try to avoid reallocation
+ if cap(b) > n {
+ // Overwrite next byte but restore when done
+ b = b[:n+1]
+ c := b[n]
+ b[n] = 0
+
+ z.buf = b
+ z.restore = func() {
+ b[n] = c
+ }
+ } else {
+ z.buf = append(b, 0)
+ }
+ }
+ return z
+}
+
+// Restore restores the replaced byte past the end of the buffer by NULL.
+func (z *Input) Restore() {
+ if z.restore != nil {
+ z.restore()
+ z.restore = nil
+ }
+}
+
+// Err returns the error returned from io.Input or io.EOF when the end has been reached.
+func (z *Input) Err() error {
+ return z.PeekErr(0)
+}
+
+// PeekErr returns the error at position pos. When pos is zero, this is the same as calling Err().
+func (z *Input) PeekErr(pos int) error {
+ if z.err != nil {
+ return z.err
+ } else if z.pos+pos >= len(z.buf)-1 {
+ return io.EOF
+ }
+ return nil
+}
+
+// Peek returns the ith byte relative to the end position.
+// Peek returns 0 when an error has occurred, Err returns the erroz.
+func (z *Input) Peek(pos int) byte {
+ pos += z.pos
+ return z.buf[pos]
+}
+
+// PeekRune returns the rune and rune length of the ith byte relative to the end position.
+func (z *Input) PeekRune(pos int) (rune, int) {
+ // from unicode/utf8
+ c := z.Peek(pos)
+ if c < 0xC0 || z.Peek(pos+1) == 0 {
+ return rune(c), 1
+ } else if c < 0xE0 || z.Peek(pos+2) == 0 {
+ return rune(c&0x1F)<<6 | rune(z.Peek(pos+1)&0x3F), 2
+ } else if c < 0xF0 || z.Peek(pos+3) == 0 {
+ return rune(c&0x0F)<<12 | rune(z.Peek(pos+1)&0x3F)<<6 | rune(z.Peek(pos+2)&0x3F), 3
+ }
+ return rune(c&0x07)<<18 | rune(z.Peek(pos+1)&0x3F)<<12 | rune(z.Peek(pos+2)&0x3F)<<6 | rune(z.Peek(pos+3)&0x3F), 4
+}
+
+// Move advances the position.
+func (z *Input) Move(n int) {
+ z.pos += n
+}
+
+// Pos returns a mark to which can be rewinded.
+func (z *Input) Pos() int {
+ return z.pos - z.start
+}
+
+// Rewind rewinds the position to the given position.
+func (z *Input) Rewind(pos int) {
+ z.pos = z.start + pos
+}
+
+// Lexeme returns the bytes of the current selection.
+func (z *Input) Lexeme() []byte {
+ return z.buf[z.start:z.pos:z.pos]
+}
+
+// Skip collapses the position to the end of the selection.
+func (z *Input) Skip() {
+ z.start = z.pos
+}
+
+// Shift returns the bytes of the current selection and collapses the position to the end of the selection.
+func (z *Input) Shift() []byte {
+ b := z.buf[z.start:z.pos:z.pos]
+ z.start = z.pos
+ return b
+}
+
+// Offset returns the character position in the buffez.
+func (z *Input) Offset() int {
+ return z.pos
+}
+
+// Bytes returns the underlying buffez.
+func (z *Input) Bytes() []byte {
+ return z.buf[: len(z.buf)-1 : len(z.buf)-1]
+}
+
+// Len returns the length of the underlying buffez.
+func (z *Input) Len() int {
+ return len(z.buf) - 1
+}
+
+// Reset resets position to the underlying buffez.
+func (z *Input) Reset() {
+ z.start = 0
+ z.pos = 0
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/js/README.md b/vendor/github.com/tdewolff/parse/v2/js/README.md
new file mode 100644
index 0000000..e1d4007
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/js/README.md
@@ -0,0 +1,80 @@
+# JS [![API reference](https://img.shields.io/badge/godoc-reference-5272B4)](https://pkg.go.dev/github.com/tdewolff/minify/v2/parse/js?tab=doc)
+
+This package is a JS lexer (ECMAScript 2020) written in [Go][1]. It follows the specification at [ECMAScript 2020 Language Specification](https://tc39.es/ecma262/). The lexer takes an io.Reader and converts it into tokens until the EOF.
+
+## Installation
+Run the following command
+
+ go get -u github.com/tdewolff/parse/v2/js
+
+or add the following import and run project with `go get`
+
+ import "github.com/tdewolff/parse/v2/js"
+
+## Lexer
+### Usage
+The following initializes a new Lexer with io.Reader `r`:
+``` go
+l := js.NewLexer(parse.NewInput(r))
+```
+
+To tokenize until EOF an error, use:
+``` go
+for {
+ tt, text := l.Next()
+ switch tt {
+ case js.ErrorToken:
+ // error or EOF set in l.Err()
+ return
+ // ...
+ }
+}
+```
+
+### Regular Expressions
+The ECMAScript specification for `PunctuatorToken` (of which the `/` and `/=` symbols) and `RegExpToken` depend on a parser state to differentiate between the two. The lexer will always parse the first token as `/` or `/=` operator, upon which the parser can rescan that token to scan a regular expression using `RegExp()`.
+
+### Examples
+``` go
+package main
+
+import (
+ "os"
+
+ "github.com/tdewolff/parse/v2/js"
+)
+
+// Tokenize JS from stdin.
+func main() {
+ l := js.NewLexer(parse.NewInput(os.Stdin))
+ for {
+ tt, text := l.Next()
+ switch tt {
+ case js.ErrorToken:
+ if l.Err() != io.EOF {
+ fmt.Println("Error on line", l.Line(), ":", l.Err())
+ }
+ return
+ case js.IdentifierToken:
+ fmt.Println("Identifier", string(text))
+ case js.NumericToken:
+ fmt.Println("Numeric", string(text))
+ // ...
+ }
+ }
+}
+```
+
+## Parser
+### Usage
+The following parses a file and returns an abstract syntax tree (AST).
+``` go
+ast, err := js.NewParser(parse.NewInputString("if (state == 5) { console.log('In state five'); }"))
+```
+
+See [ast.go](https://github.com/tdewolff/parse/blob/master/js/ast.go) for all available data structures that can represent the abstact syntax tree.
+
+## License
+Released under the [MIT license](https://github.com/tdewolff/parse/blob/master/LICENSE.md).
+
+[1]: http://golang.org/ "Go Language"
diff --git a/vendor/github.com/tdewolff/parse/v2/js/ast.go b/vendor/github.com/tdewolff/parse/v2/js/ast.go
new file mode 100644
index 0000000..92e80d7
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/js/ast.go
@@ -0,0 +1,3884 @@
+package js
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "strconv"
+
+ "github.com/tdewolff/parse/v2"
+)
+
+var ErrInvalidJSON = fmt.Errorf("invalid JSON")
+
+type JSONer interface {
+ JSON(*bytes.Buffer) error
+}
+
+// AST is the full ECMAScript abstract syntax tree.
+type AST struct {
+ Comments [][]byte // first comments in file
+ BlockStmt // module
+}
+
+func (ast *AST) String() string {
+ s := ""
+ for i, item := range ast.BlockStmt.List {
+ if i != 0 {
+ s += " "
+ }
+ s += item.String()
+ }
+ return s
+}
+
+////////////////////////////////////////////////////////////////
+
+// DeclType specifies the kind of declaration.
+type DeclType uint16
+
+// DeclType values.
+const (
+ NoDecl DeclType = iota // undeclared variables
+ VariableDecl // var
+ FunctionDecl // function
+ ArgumentDecl // function and method arguments
+ LexicalDecl // let, const, class
+ CatchDecl // catch statement argument
+ ExprDecl // function expression name or class expression name
+)
+
+func (decl DeclType) String() string {
+ switch decl {
+ case NoDecl:
+ return "NoDecl"
+ case VariableDecl:
+ return "VariableDecl"
+ case FunctionDecl:
+ return "FunctionDecl"
+ case ArgumentDecl:
+ return "ArgumentDecl"
+ case LexicalDecl:
+ return "LexicalDecl"
+ case CatchDecl:
+ return "CatchDecl"
+ case ExprDecl:
+ return "ExprDecl"
+ }
+ return "Invalid(" + strconv.Itoa(int(decl)) + ")"
+}
+
+// Var is a variable, where Decl is the type of declaration and can be var|function for function scoped variables, let|const|class for block scoped variables.
+type Var struct {
+ Data []byte
+ Link *Var // is set when merging variable uses, as in: {a} {var a} where the first links to the second, only used for undeclared variables
+ Uses uint16
+ Decl DeclType
+}
+
+// Name returns the variable name.
+func (v *Var) Name() []byte {
+ for v.Link != nil {
+ v = v.Link
+ }
+ return v.Data
+}
+
+func (v Var) String() string {
+ return string(v.Name())
+}
+
+// JS converts the node back to valid JavaScript
+func (v Var) JS() string {
+ return v.String()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (v Var) JSWriteTo(w io.Writer) (i int, err error) {
+ return w.Write(v.Name())
+}
+
+// VarsByUses is sortable by uses in descending order.
+// TODO: write custom sorter for varsbyuses
+type VarsByUses VarArray
+
+func (vs VarsByUses) Len() int {
+ return len(vs)
+}
+
+func (vs VarsByUses) Swap(i, j int) {
+ vs[i], vs[j] = vs[j], vs[i]
+}
+
+func (vs VarsByUses) Less(i, j int) bool {
+ return vs[i].Uses > vs[j].Uses
+}
+
+////////////////////////////////////////////////////////////////
+
+// VarArray is a set of variables in scopes.
+type VarArray []*Var
+
+func (vs VarArray) String() string {
+ s := "["
+ for i, v := range vs {
+ if i != 0 {
+ s += ", "
+ }
+ links := 0
+ for v.Link != nil {
+ v = v.Link
+ links++
+ }
+ s += fmt.Sprintf("Var{%v %s %v %v}", v.Decl, string(v.Data), links, v.Uses)
+ }
+ return s + "]"
+}
+
+// Scope is a function or block scope with a list of variables declared and used.
+type Scope struct {
+ Parent, Func *Scope // Parent is nil for global scope
+ Declared VarArray // Link in Var are always nil
+ Undeclared VarArray
+ VarDecls []*VarDecl
+ NumForDecls uint16 // offset into Declared to mark variables used in for statements
+ NumFuncArgs uint16 // offset into Declared to mark variables used in function arguments
+ NumArgUses uint16 // offset into Undeclared to mark variables used in arguments
+ IsGlobalOrFunc bool
+ HasWith bool
+}
+
+func (s Scope) String() string {
+ return "Scope{Declared: " + s.Declared.String() + ", Undeclared: " + s.Undeclared.String() + "}"
+}
+
+// Declare declares a new variable.
+func (s *Scope) Declare(decl DeclType, name []byte) (*Var, bool) {
+ // refer to new variable for previously undeclared symbols in the current and lower scopes
+ // this happens in `{ a = 5; } var a` where both a's refer to the same variable
+ curScope := s
+ if decl == VariableDecl || decl == FunctionDecl {
+ // find function scope for var and function declarations
+ for s != s.Func {
+ // make sure that `{let i;{var i}}` is an error
+ if v := s.findDeclared(name, false); v != nil && v.Decl != decl && v.Decl != CatchDecl {
+ return nil, false
+ }
+ s = s.Parent
+ }
+ }
+
+ if v := s.findDeclared(name, true); v != nil {
+ // variable already declared, might be an error or a duplicate declaration
+ if (ArgumentDecl < v.Decl || FunctionDecl < decl) && v.Decl != ExprDecl {
+ // only allow (v.Decl,decl) of: (var|function|argument,var|function), (expr,*), any other combination is a syntax error
+ return nil, false
+ }
+ if v.Decl == ExprDecl {
+ v.Decl = decl
+ }
+ v.Uses++
+ for s != curScope {
+ curScope.AddUndeclared(v) // add variable declaration as used variable to the current scope
+ curScope = curScope.Parent
+ }
+ return v, true
+ }
+
+ var v *Var
+ // reuse variable if previously used, as in: a;var a
+ if decl != ArgumentDecl { // in case of function f(a=b,b), where the first b is different from the second
+ for i, uv := range s.Undeclared[s.NumArgUses:] {
+ // no need to evaluate v.Link as v.Data stays the same and Link is nil in the active scope
+ if 0 < uv.Uses && uv.Decl == NoDecl && bytes.Equal(name, uv.Data) {
+ // must be NoDecl so that it can't be a var declaration that has been added
+ v = uv
+ s.Undeclared = append(s.Undeclared[:int(s.NumArgUses)+i], s.Undeclared[int(s.NumArgUses)+i+1:]...)
+ break
+ }
+ }
+ }
+ if v == nil {
+ // add variable to the context list and to the scope
+ v = &Var{name, nil, 0, decl}
+ } else {
+ v.Decl = decl
+ }
+ v.Uses++
+ s.Declared = append(s.Declared, v)
+ for s != curScope {
+ curScope.AddUndeclared(v) // add variable declaration as used variable to the current scope
+ curScope = curScope.Parent
+ }
+ return v, true
+}
+
+// Use increments the usage of a variable.
+func (s *Scope) Use(name []byte) *Var {
+ // check if variable is declared in the current scope
+ v := s.findDeclared(name, false)
+ if v == nil {
+ // check if variable is already used before in the current or lower scopes
+ v = s.findUndeclared(name)
+ if v == nil {
+ // add variable to the context list and to the scope's undeclared
+ v = &Var{name, nil, 0, NoDecl}
+ s.Undeclared = append(s.Undeclared, v)
+ }
+ }
+ v.Uses++
+ return v
+}
+
+// findDeclared finds a declared variable in the current scope.
+func (s *Scope) findDeclared(name []byte, skipForDeclared bool) *Var {
+ start := 0
+ if skipForDeclared {
+ // we skip the for initializer for declarations (only has effect for let/const)
+ start = int(s.NumForDecls)
+ }
+ // reverse order to find the inner let first in `for(let a in []){let a; {a}}`
+ for i := len(s.Declared) - 1; start <= i; i-- {
+ v := s.Declared[i]
+ // no need to evaluate v.Link as v.Data stays the same, and Link is always nil in Declared
+ if bytes.Equal(name, v.Data) {
+ return v
+ }
+ }
+ return nil
+}
+
+// findUndeclared finds an undeclared variable in the current and contained scopes.
+func (s *Scope) findUndeclared(name []byte) *Var {
+ for _, v := range s.Undeclared {
+ // no need to evaluate v.Link as v.Data stays the same and Link is nil in the active scope
+ if 0 < v.Uses && bytes.Equal(name, v.Data) {
+ return v
+ }
+ }
+ return nil
+}
+
+// add undeclared variable to scope, this is called for the block scope when declaring a var in it
+func (s *Scope) AddUndeclared(v *Var) {
+ // don't add undeclared symbol if it's already there
+ for _, vorig := range s.Undeclared {
+ if v == vorig {
+ return
+ }
+ }
+ s.Undeclared = append(s.Undeclared, v) // add variable declaration as used variable to the current scope
+}
+
+// MarkForStmt marks the declared variables in current scope as for statement initializer to distinguish from declarations in body.
+func (s *Scope) MarkForStmt() {
+ s.NumForDecls = uint16(len(s.Declared))
+ s.NumArgUses = uint16(len(s.Undeclared)) // ensures for different b's in for(var a in b){let b}
+}
+
+// MarkFuncArgs marks the declared/undeclared variables in the current scope as function arguments.
+func (s *Scope) MarkFuncArgs() {
+ s.NumFuncArgs = uint16(len(s.Declared))
+ s.NumArgUses = uint16(len(s.Undeclared)) // ensures different b's in `function f(a=b){var b}`.
+}
+
+// HoistUndeclared copies all undeclared variables of the current scope to the parent scope.
+func (s *Scope) HoistUndeclared() {
+ for i, vorig := range s.Undeclared {
+ // no need to evaluate vorig.Link as vorig.Data stays the same
+ if 0 < vorig.Uses && vorig.Decl == NoDecl {
+ if v := s.Parent.findDeclared(vorig.Data, false); v != nil {
+ // check if variable is declared in parent scope
+ v.Uses += vorig.Uses
+ vorig.Link = v
+ s.Undeclared[i] = v // point reference to existing var (to avoid many Link chains)
+ } else if v := s.Parent.findUndeclared(vorig.Data); v != nil {
+ // check if variable is already used before in parent scope
+ v.Uses += vorig.Uses
+ vorig.Link = v
+ s.Undeclared[i] = v // point reference to existing var (to avoid many Link chains)
+ } else {
+ // add variable to the context list and to the scope's undeclared
+ s.Parent.Undeclared = append(s.Parent.Undeclared, vorig)
+ }
+ }
+ }
+}
+
+// UndeclareScope undeclares all declared variables in the current scope and adds them to the parent scope.
+// Called when possible arrow func ends up being a parenthesized expression, scope is not further used.
+func (s *Scope) UndeclareScope() {
+ // look if the variable already exists in the parent scope, if so replace the Var pointer in original use
+ for _, vorig := range s.Declared {
+ // no need to evaluate vorig.Link as vorig.Data stays the same, and Link is always nil in Declared
+ // vorig.Uses will be atleast 1
+ if v := s.Parent.findDeclared(vorig.Data, false); v != nil {
+ // check if variable has been declared in this scope
+ v.Uses += vorig.Uses
+ vorig.Link = v
+ } else if v := s.Parent.findUndeclared(vorig.Data); v != nil {
+ // check if variable is already used before in the current or lower scopes
+ v.Uses += vorig.Uses
+ vorig.Link = v
+ } else {
+ // add variable to the context list and to the scope's undeclared
+ vorig.Decl = NoDecl
+ s.Parent.Undeclared = append(s.Parent.Undeclared, vorig)
+ }
+ }
+ s.Declared = s.Declared[:0]
+ s.Undeclared = s.Undeclared[:0]
+}
+
+// Unscope moves all declared variables of the current scope to the parent scope. Undeclared variables are already in the parent scope.
+func (s *Scope) Unscope() {
+ for _, vorig := range s.Declared {
+ // no need to evaluate vorig.Link as vorig.Data stays the same, and Link is always nil in Declared
+ // vorig.Uses will be atleast 1
+ s.Parent.Declared = append(s.Parent.Declared, vorig)
+ }
+ s.Declared = s.Declared[:0]
+ s.Undeclared = s.Undeclared[:0]
+}
+
+////////////////////////////////////////////////////////////////
+
+// INode is an interface for AST nodes
+type INode interface {
+ String() string
+ JS() string
+ JSWriteTo(io.Writer) (int, error)
+}
+
+// IStmt is a dummy interface for statements.
+type IStmt interface {
+ INode
+ stmtNode()
+}
+
+// IBinding is a dummy interface for bindings.
+type IBinding interface {
+ INode
+ bindingNode()
+}
+
+// IExpr is a dummy interface for expressions.
+type IExpr interface {
+ INode
+ exprNode()
+}
+
+////////////////////////////////////////////////////////////////
+
+// BlockStmt is a block statement.
+type BlockStmt struct {
+ List []IStmt
+ Scope
+}
+
+func (n BlockStmt) String() string {
+ s := "Stmt({"
+ for _, item := range n.List {
+ s += " " + item.String()
+ }
+ return s + " })"
+}
+
+// JS converts the node back to valid JavaScript
+func (n BlockStmt) JS() string {
+ s := ""
+ if n.Scope.Parent != nil {
+ s += "{ "
+ }
+ for _, item := range n.List {
+ if _, isEmpty := item.(*EmptyStmt); !isEmpty {
+ s += item.JS() + "; "
+ }
+ }
+ if n.Scope.Parent != nil {
+ s += "}"
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n BlockStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.Scope.Parent != nil {
+ wn, err = w.Write([]byte("{ "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ for _, item := range n.List {
+ if _, isEmpty := item.(*EmptyStmt); !isEmpty {
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte("; "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ }
+ if n.Scope.Parent != nil {
+ wn, err = w.Write([]byte{'}'})
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// EmptyStmt is an empty statement.
+type EmptyStmt struct {
+}
+
+func (n EmptyStmt) String() string {
+ return "Stmt(;)"
+}
+
+// JS converts the node back to valid JavaScript
+func (n EmptyStmt) JS() string {
+ return ";"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n EmptyStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ wn, err := w.Write([]byte{';'})
+ i = wn
+ return
+}
+
+// ExprStmt is an expression statement.
+type ExprStmt struct {
+ Value IExpr
+}
+
+func (n ExprStmt) String() string {
+ val := n.Value.String()
+ if val[0] == '(' && val[len(val)-1] == ')' {
+ return "Stmt" + n.Value.String()
+ }
+ return "Stmt(" + n.Value.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ExprStmt) JS() string {
+ return n.Value.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ExprStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ return n.Value.JSWriteTo(w)
+}
+
+// IfStmt is an if statement.
+type IfStmt struct {
+ Cond IExpr
+ Body IStmt
+ Else IStmt // can be nil
+}
+
+func (n IfStmt) String() string {
+ s := "Stmt(if " + n.Cond.String() + " " + n.Body.String()
+ if n.Else != nil {
+ s += " else " + n.Else.String()
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n IfStmt) JS() string {
+ s := "if (" + n.Cond.JS() + ") "
+ switch n.Body.(type) {
+ case *BlockStmt:
+ s += n.Body.JS()
+ default:
+ s += "{ " + n.Body.JS() + " }"
+ }
+ if n.Else != nil {
+ switch n.Else.(type) {
+ case *BlockStmt:
+ s += " else " + n.Else.JS()
+ default:
+ s += " else { " + n.Else.JS() + " }"
+ }
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n IfStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("if ("))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Cond.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(") "))
+ i += wn
+ if err != nil {
+ return
+ }
+ switch n.Body.(type) {
+ case *BlockStmt:
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ default:
+ wn, err = w.Write([]byte("{ "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" }"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Else != nil {
+ switch n.Else.(type) {
+ case *BlockStmt:
+ wn, err = w.Write([]byte(" else "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Else.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ default:
+ wn, err = w.Write([]byte(" else { "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Else.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" }"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ }
+ return
+}
+
+// DoWhileStmt is a do-while iteration statement.
+type DoWhileStmt struct {
+ Cond IExpr
+ Body IStmt
+}
+
+func (n DoWhileStmt) String() string {
+ return "Stmt(do " + n.Body.String() + " while " + n.Cond.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n DoWhileStmt) JS() string {
+ s := "do "
+ switch n.Body.(type) {
+ case *BlockStmt:
+ s += n.Body.JS()
+ default:
+ s += "{ " + n.Body.JS() + " }"
+ }
+ return s + " while (" + n.Cond.JS() + ")"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n DoWhileStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("do "))
+ i += wn
+ if err != nil {
+ return
+ }
+ switch n.Body.(type) {
+ case *BlockStmt:
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ default:
+ wn, err = w.Write([]byte("{ "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" }"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(" while ("))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Cond.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(")"))
+ i += wn
+ return
+}
+
+// WhileStmt is a while iteration statement.
+type WhileStmt struct {
+ Cond IExpr
+ Body IStmt
+}
+
+func (n WhileStmt) String() string {
+ return "Stmt(while " + n.Cond.String() + " " + n.Body.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n WhileStmt) JS() string {
+ s := "while (" + n.Cond.JS() + ") "
+ if n.Body != nil {
+ s += n.Body.JS()
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n WhileStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("while ("))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Cond.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(") "))
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Body != nil {
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// ForStmt is a regular for iteration statement.
+type ForStmt struct {
+ Init IExpr // can be nil
+ Cond IExpr // can be nil
+ Post IExpr // can be nil
+ Body *BlockStmt
+}
+
+func (n ForStmt) String() string {
+ s := "Stmt(for"
+ if v, ok := n.Init.(*VarDecl); !ok && n.Init != nil || ok && len(v.List) != 0 {
+ s += " " + n.Init.String()
+ }
+ s += " ;"
+ if n.Cond != nil {
+ s += " " + n.Cond.String()
+ }
+ s += " ;"
+ if n.Post != nil {
+ s += " " + n.Post.String()
+ }
+ return s + " " + n.Body.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ForStmt) JS() string {
+ s := "for ("
+ if v, ok := n.Init.(*VarDecl); !ok && n.Init != nil || ok && len(v.List) != 0 {
+ s += n.Init.JS()
+ } else {
+ s += " "
+ }
+ s += "; "
+ if n.Cond != nil {
+ s += n.Cond.JS()
+ }
+ s += "; "
+ if n.Post != nil {
+ s += n.Post.JS()
+ }
+ return s + ") " + n.Body.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ForStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("for ("))
+ i += wn
+ if err != nil {
+ return
+ }
+ if v, ok := n.Init.(*VarDecl); !ok && n.Init != nil || ok && len(v.List) != 0 {
+ wn, err = n.Init.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ } else {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("; "))
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Cond != nil {
+ wn, err = n.Cond.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("; "))
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Post != nil {
+ wn, err = n.Post.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(") "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// ForInStmt is a for-in iteration statement.
+type ForInStmt struct {
+ Init IExpr
+ Value IExpr
+ Body *BlockStmt
+}
+
+func (n ForInStmt) String() string {
+ return "Stmt(for " + n.Init.String() + " in " + n.Value.String() + " " + n.Body.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ForInStmt) JS() string {
+ return "for (" + n.Init.JS() + " in " + n.Value.JS() + ") " + n.Body.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ForInStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("for ("))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Init.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" in "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Value.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(") "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// ForOfStmt is a for-of iteration statement.
+type ForOfStmt struct {
+ Await bool
+ Init IExpr
+ Value IExpr
+ Body *BlockStmt
+}
+
+func (n ForOfStmt) String() string {
+ s := "Stmt(for"
+ if n.Await {
+ s += " await"
+ }
+ return s + " " + n.Init.String() + " of " + n.Value.String() + " " + n.Body.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ForOfStmt) JS() string {
+ s := "for"
+ if n.Await {
+ s += " await"
+ }
+ return s + " (" + n.Init.JS() + " of " + n.Value.JS() + ") " + n.Body.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ForOfStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("for"))
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Await {
+ wn, err = w.Write([]byte(" await"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(" ("))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Init.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" of "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Value.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(") "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// CaseClause is a case clause or default clause for a switch statement.
+type CaseClause struct {
+ TokenType
+ Cond IExpr // can be nil
+ List []IStmt
+}
+
+func (n CaseClause) String() string {
+ s := " Clause(" + n.TokenType.String()
+ if n.Cond != nil {
+ s += " " + n.Cond.String()
+ }
+ for _, item := range n.List {
+ s += " " + item.String()
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n CaseClause) JS() string {
+ s := " "
+ if n.Cond != nil {
+ s += "case " + n.Cond.JS()
+ } else {
+ s += "default"
+ }
+ s += ":"
+ for _, item := range n.List {
+ s += " " + item.JS() + ";"
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n CaseClause) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Cond != nil {
+ wn, err = w.Write([]byte("case "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Cond.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ } else {
+ wn, err = w.Write([]byte("default"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(":"))
+ i += wn
+ if err != nil {
+ return
+ }
+ for _, item := range n.List {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(";"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// SwitchStmt is a switch statement.
+type SwitchStmt struct {
+ Init IExpr
+ List []CaseClause
+ Scope
+}
+
+func (n SwitchStmt) String() string {
+ s := "Stmt(switch " + n.Init.String()
+ for _, clause := range n.List {
+ s += clause.String()
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n SwitchStmt) JS() string {
+ s := "switch (" + n.Init.JS() + ") {"
+ for _, clause := range n.List {
+ s += clause.JS()
+ }
+ return s + " }"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n SwitchStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("switch ("))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Init.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(") {"))
+ i += wn
+ if err != nil {
+ return
+ }
+ for _, clause := range n.List {
+ wn, err = clause.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(" }"))
+ i += wn
+ return
+}
+
+// BranchStmt is a continue or break statement.
+type BranchStmt struct {
+ Type TokenType
+ Label []byte // can be nil
+}
+
+func (n BranchStmt) String() string {
+ s := "Stmt(" + n.Type.String()
+ if n.Label != nil {
+ s += " " + string(n.Label)
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n BranchStmt) JS() string {
+ s := n.Type.String()
+ if n.Label != nil {
+ s += " " + string(n.Label)
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n BranchStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write(n.Type.Bytes())
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Label != nil {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write(n.Label)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// ReturnStmt is a return statement.
+type ReturnStmt struct {
+ Value IExpr // can be nil
+}
+
+func (n ReturnStmt) String() string {
+ s := "Stmt(return"
+ if n.Value != nil {
+ s += " " + n.Value.String()
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ReturnStmt) JS() string {
+ s := "return"
+ if n.Value != nil {
+ s += " " + n.Value.JS()
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ReturnStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("return"))
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Value != nil {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Value.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// WithStmt is a with statement.
+type WithStmt struct {
+ Cond IExpr
+ Body IStmt
+}
+
+func (n WithStmt) String() string {
+ return "Stmt(with " + n.Cond.String() + " " + n.Body.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n WithStmt) JS() string {
+ return "with (" + n.Cond.JS() + ") " + n.Body.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n WithStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("with ("))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Cond.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(") "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// LabelledStmt is a labelled statement.
+type LabelledStmt struct {
+ Label []byte
+ Value IStmt
+}
+
+func (n LabelledStmt) String() string {
+ return "Stmt(" + string(n.Label) + " : " + n.Value.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n LabelledStmt) JS() string {
+ return string(n.Label) + ": " + n.Value.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n LabelledStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write(n.Label)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(": "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Value.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// ThrowStmt is a throw statement.
+type ThrowStmt struct {
+ Value IExpr
+}
+
+func (n ThrowStmt) String() string {
+ return "Stmt(throw " + n.Value.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ThrowStmt) JS() string {
+ return "throw " + n.Value.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ThrowStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("throw "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Value.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// TryStmt is a try statement.
+type TryStmt struct {
+ Body *BlockStmt
+ Binding IBinding // can be nil
+ Catch *BlockStmt // can be nil
+ Finally *BlockStmt // can be nil
+}
+
+func (n TryStmt) String() string {
+ s := "Stmt(try " + n.Body.String()
+ if n.Catch != nil {
+ s += " catch"
+ if n.Binding != nil {
+ s += " Binding(" + n.Binding.String() + ")"
+ }
+ s += " " + n.Catch.String()
+ }
+ if n.Finally != nil {
+ s += " finally " + n.Finally.String()
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n TryStmt) JS() string {
+ s := "try " + n.Body.JS()
+ if n.Catch != nil {
+ s += " catch"
+ if n.Binding != nil {
+ s += "(" + n.Binding.JS() + ")"
+ }
+ s += " " + n.Catch.JS()
+ }
+ if n.Finally != nil {
+ s += " finally " + n.Finally.JS()
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n TryStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("try "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Catch != nil {
+ wn, err = w.Write([]byte(" catch"))
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Binding != nil {
+ wn, err = w.Write([]byte("("))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Binding.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(")"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Catch.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Finally != nil {
+ wn, err = w.Write([]byte(" finally "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Finally.JSWriteTo(w)
+ i += wn
+ }
+ return
+}
+
+// DebuggerStmt is a debugger statement.
+type DebuggerStmt struct {
+}
+
+func (n DebuggerStmt) String() string {
+ return "Stmt(debugger)"
+}
+
+// JS converts the node back to valid JavaScript
+func (n DebuggerStmt) JS() string {
+ return "debugger"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n DebuggerStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("debugger"))
+ i += wn
+ return
+}
+
+// Alias is a name space import or import/export specifier for import/export statements.
+type Alias struct {
+ Name []byte // can be nil
+ Binding []byte // can be nil
+}
+
+func (alias Alias) String() string {
+ s := ""
+ if alias.Name != nil {
+ s += string(alias.Name) + " as "
+ }
+ return s + string(alias.Binding)
+}
+
+// JS converts the node back to valid JavaScript
+func (alias Alias) JS() string {
+ return alias.String()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (alias Alias) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if alias.Name != nil {
+ wn, err = w.Write(alias.Name)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" as "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write(alias.Binding)
+ i += wn
+ return
+}
+
+// ImportStmt is an import statement.
+type ImportStmt struct {
+ List []Alias
+ Default []byte // can be nil
+ Module []byte
+}
+
+func (n ImportStmt) String() string {
+ s := "Stmt(import"
+ if n.Default != nil {
+ s += " " + string(n.Default)
+ if len(n.List) != 0 {
+ s += " ,"
+ }
+ }
+ if len(n.List) == 1 && len(n.List[0].Name) == 1 && n.List[0].Name[0] == '*' {
+ s += " " + n.List[0].String()
+ } else if 0 < len(n.List) {
+ s += " {"
+ for i, item := range n.List {
+ if i != 0 {
+ s += " ,"
+ }
+ if item.Binding != nil {
+ s += " " + item.String()
+ }
+ }
+ s += " }"
+ }
+ if n.Default != nil || len(n.List) != 0 {
+ s += " from"
+ }
+ return s + " " + string(n.Module) + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ImportStmt) JS() string {
+ s := "import"
+ if n.Default != nil {
+ s += " " + string(n.Default)
+ if len(n.List) != 0 {
+ s += " ,"
+ }
+ }
+ if len(n.List) == 1 && len(n.List[0].Name) == 1 && n.List[0].Name[0] == '*' {
+ s += " " + n.List[0].JS()
+ } else if 0 < len(n.List) {
+ s += " {"
+ for i, item := range n.List {
+ if i != 0 {
+ s += " ,"
+ }
+ if item.Binding != nil {
+ s += " " + item.JS()
+ }
+ }
+ s += " }"
+ }
+ if n.Default != nil || len(n.List) != 0 {
+ s += " from"
+ }
+ return s + " " + string(n.Module)
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ImportStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("import"))
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Default != nil {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write(n.Default)
+ i += wn
+ if err != nil {
+ return
+ }
+ if len(n.List) != 0 {
+ wn, err = w.Write([]byte(" ,"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ }
+ if len(n.List) == 1 && len(n.List[0].Name) == 1 && n.List[0].Name[0] == '*' {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.List[0].JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ } else if 0 < len(n.List) {
+ wn, err = w.Write([]byte(" {"))
+ i += wn
+ if err != nil {
+ return
+ }
+ for j, item := range n.List {
+ if j != 0 {
+ wn, err = w.Write([]byte(" ,"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if item.Binding != nil {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ }
+ wn, err = w.Write([]byte(" }"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Default != nil || len(n.List) != 0 {
+ wn, err = w.Write([]byte(" from"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write(n.Module)
+ i += wn
+ return
+}
+
+// ExportStmt is an export statement.
+type ExportStmt struct {
+ List []Alias
+ Module []byte // can be nil
+ Default bool
+ Decl IExpr
+}
+
+func (n ExportStmt) String() string {
+ s := "Stmt(export"
+ if n.Decl != nil {
+ if n.Default {
+ s += " default"
+ }
+ return s + " " + n.Decl.String() + ")"
+ } else if len(n.List) == 1 && (len(n.List[0].Name) == 1 && n.List[0].Name[0] == '*' || n.List[0].Name == nil && len(n.List[0].Binding) == 1 && n.List[0].Binding[0] == '*') {
+ s += " " + n.List[0].String()
+ } else if 0 < len(n.List) {
+ s += " {"
+ for i, item := range n.List {
+ if i != 0 {
+ s += " ,"
+ }
+ if item.Binding != nil {
+ s += " " + item.String()
+ }
+ }
+ s += " }"
+ }
+ if n.Module != nil {
+ s += " from " + string(n.Module)
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ExportStmt) JS() string {
+ s := "export"
+ if n.Decl != nil {
+ if n.Default {
+ s += " default"
+ }
+ return s + " " + n.Decl.JS()
+ } else if len(n.List) == 1 && (len(n.List[0].Name) == 1 && n.List[0].Name[0] == '*' || n.List[0].Name == nil && len(n.List[0].Binding) == 1 && n.List[0].Binding[0] == '*') {
+ s += " " + n.List[0].JS()
+ } else if 0 < len(n.List) {
+ s += " {"
+ for i, item := range n.List {
+ if i != 0 {
+ s += " ,"
+ }
+ if item.Binding != nil {
+ s += " " + item.JS()
+ }
+ }
+ s += " }"
+ }
+ if n.Module != nil {
+ s += " from " + string(n.Module)
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ExportStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("export"))
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Decl != nil {
+ if n.Default {
+ wn, err = w.Write([]byte(" default"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Decl.JSWriteTo(w)
+ i += wn
+ return
+ } else if len(n.List) == 1 && (len(n.List[0].Name) == 1 && n.List[0].Name[0] == '*' || n.List[0].Name == nil && len(n.List[0].Binding) == 1 && n.List[0].Binding[0] == '*') {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.List[0].JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ } else if 0 < len(n.List) {
+ wn, err = w.Write([]byte(" {"))
+ i += wn
+ if err != nil {
+ return
+ }
+ for j, item := range n.List {
+ if j != 0 {
+ wn, err = w.Write([]byte(" ,"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if item.Binding != nil {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ }
+ wn, err = w.Write([]byte(" }"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Module != nil {
+ wn, err = w.Write([]byte(" from "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write(n.Module)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// DirectivePrologueStmt is a string literal at the beginning of a function or module (usually "use strict").
+type DirectivePrologueStmt struct {
+ Value []byte
+}
+
+func (n DirectivePrologueStmt) String() string {
+ return "Stmt(" + string(n.Value) + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n DirectivePrologueStmt) JS() string {
+ return string(n.Value)
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n DirectivePrologueStmt) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write(n.Value)
+ i += wn
+ return
+}
+
+func (n BlockStmt) stmtNode() {}
+func (n EmptyStmt) stmtNode() {}
+func (n ExprStmt) stmtNode() {}
+func (n IfStmt) stmtNode() {}
+func (n DoWhileStmt) stmtNode() {}
+func (n WhileStmt) stmtNode() {}
+func (n ForStmt) stmtNode() {}
+func (n ForInStmt) stmtNode() {}
+func (n ForOfStmt) stmtNode() {}
+func (n SwitchStmt) stmtNode() {}
+func (n BranchStmt) stmtNode() {}
+func (n ReturnStmt) stmtNode() {}
+func (n WithStmt) stmtNode() {}
+func (n LabelledStmt) stmtNode() {}
+func (n ThrowStmt) stmtNode() {}
+func (n TryStmt) stmtNode() {}
+func (n DebuggerStmt) stmtNode() {}
+func (n ImportStmt) stmtNode() {}
+func (n ExportStmt) stmtNode() {}
+func (n DirectivePrologueStmt) stmtNode() {}
+
+////////////////////////////////////////////////////////////////
+
+// PropertyName is a property name for binding properties, method names, and in object literals.
+type PropertyName struct {
+ Literal LiteralExpr
+ Computed IExpr // can be nil
+}
+
+// IsSet returns true is PropertyName is not nil.
+func (n PropertyName) IsSet() bool {
+ return n.IsComputed() || n.Literal.TokenType != ErrorToken
+}
+
+// IsComputed returns true if PropertyName is computed.
+func (n PropertyName) IsComputed() bool {
+ return n.Computed != nil
+}
+
+// IsIdent returns true if PropertyName equals the given identifier name.
+func (n PropertyName) IsIdent(data []byte) bool {
+ return !n.IsComputed() && n.Literal.TokenType == IdentifierToken && bytes.Equal(data, n.Literal.Data)
+}
+
+func (n PropertyName) String() string {
+ if n.Computed != nil {
+ val := n.Computed.String()
+ if val[0] == '(' {
+ return "[" + val[1:len(val)-1] + "]"
+ }
+ return "[" + val + "]"
+ }
+ return string(n.Literal.Data)
+}
+
+// JS converts the node back to valid JavaScript
+func (n PropertyName) JS() string {
+ if n.Computed != nil {
+ return "[" + n.Computed.JS() + "]"
+ }
+ return string(n.Literal.Data)
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n PropertyName) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.Computed != nil {
+ wn, err = w.Write([]byte("["))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Computed.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte("]"))
+ i += wn
+ return
+ }
+ wn, err = w.Write(n.Literal.Data)
+ i += wn
+ return
+}
+
+// BindingArray is an array binding pattern.
+type BindingArray struct {
+ List []BindingElement
+ Rest IBinding // can be nil
+}
+
+func (n BindingArray) String() string {
+ s := "["
+ for i, item := range n.List {
+ if i != 0 {
+ s += ","
+ }
+ s += " " + item.String()
+ }
+ if n.Rest != nil {
+ if len(n.List) != 0 {
+ s += ","
+ }
+ s += " ...Binding(" + n.Rest.String() + ")"
+ }
+ return s + " ]"
+}
+
+// JS converts the node back to valid JavaScript
+func (n BindingArray) JS() string {
+ s := "["
+ for i, item := range n.List {
+ if i != 0 {
+ s += ", "
+ }
+ s += item.JS()
+ }
+ if n.Rest != nil {
+ if len(n.List) != 0 {
+ s += ", "
+ }
+ s += "..." + n.Rest.JS()
+ }
+ return s + "]"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n BindingArray) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("["))
+ i += wn
+ if err != nil {
+ return
+ }
+ for j, item := range n.List {
+ if j != 0 {
+ wn, err = w.Write([]byte(", "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Rest != nil {
+ if len(n.List) != 0 {
+ wn, err = w.Write([]byte(", "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("..."))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Rest.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("]"))
+ i += wn
+ return
+}
+
+// BindingObjectItem is a binding property.
+type BindingObjectItem struct {
+ Key *PropertyName // can be nil
+ Value BindingElement
+}
+
+func (n BindingObjectItem) String() string {
+ s := ""
+ if n.Key != nil {
+ if v, ok := n.Value.Binding.(*Var); !ok || !n.Key.IsIdent(v.Data) {
+ s += " " + n.Key.String() + ":"
+ }
+ }
+ return s + " " + n.Value.String()
+}
+
+// JS converts the node back to valid JavaScript
+func (n BindingObjectItem) JS() string {
+ s := ""
+ if n.Key != nil {
+ if v, ok := n.Value.Binding.(*Var); !ok || !n.Key.IsIdent(v.Data) {
+ s += n.Key.JS() + ": "
+ }
+ }
+ return s + n.Value.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n BindingObjectItem) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.Key != nil {
+ if v, ok := n.Value.Binding.(*Var); !ok || !n.Key.IsIdent(v.Data) {
+ wn, err = n.Key.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(": "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ }
+ wn, err = n.Value.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// BindingObject is an object binding pattern.
+type BindingObject struct {
+ List []BindingObjectItem
+ Rest *Var // can be nil
+}
+
+func (n BindingObject) String() string {
+ s := "{"
+ for i, item := range n.List {
+ if i != 0 {
+ s += ","
+ }
+ s += item.String()
+ }
+ if n.Rest != nil {
+ if len(n.List) != 0 {
+ s += ","
+ }
+ s += " ...Binding(" + string(n.Rest.Data) + ")"
+ }
+ return s + " }"
+}
+
+// JS converts the node back to valid JavaScript
+func (n BindingObject) JS() string {
+ s := "{"
+ for i, item := range n.List {
+ if i != 0 {
+ s += ", "
+ }
+ s += item.JS()
+ }
+ if n.Rest != nil {
+ if len(n.List) != 0 {
+ s += ", "
+ }
+ s += "..." + string(n.Rest.Data)
+ }
+ return s + "}"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n BindingObject) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("{"))
+ i += wn
+ if err != nil {
+ return
+ }
+ for j, item := range n.List {
+ if j != 0 {
+ wn, err = w.Write([]byte(", "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Rest != nil {
+ if len(n.List) != 0 {
+ wn, err = w.Write([]byte(", "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("..."))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write(n.Rest.Data)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("}"))
+ i += wn
+ return
+}
+
+// BindingElement is a binding element.
+type BindingElement struct {
+ Binding IBinding // can be nil (in case of ellision)
+ Default IExpr // can be nil
+}
+
+func (n BindingElement) String() string {
+ if n.Binding == nil {
+ return "Binding()"
+ }
+ s := "Binding(" + n.Binding.String()
+ if n.Default != nil {
+ s += " = " + n.Default.String()
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n BindingElement) JS() string {
+ if n.Binding == nil {
+ return ""
+ }
+ s := n.Binding.JS()
+ if n.Default != nil {
+ s += " = " + n.Default.JS()
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n BindingElement) JSWriteTo(w io.Writer) (i int, err error) {
+ if n.Binding == nil {
+ return
+ }
+ var wn int
+ wn, err = n.Binding.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Default != nil {
+ wn, err = w.Write([]byte(" = "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Default.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+func (v *Var) bindingNode() {}
+func (n BindingArray) bindingNode() {}
+func (n BindingObject) bindingNode() {}
+
+////////////////////////////////////////////////////////////////
+
+// VarDecl is a variable statement or lexical declaration.
+type VarDecl struct {
+ TokenType
+ List []BindingElement
+ Scope *Scope
+ InFor, InForInOf bool
+}
+
+func (n VarDecl) String() string {
+ s := "Decl(" + n.TokenType.String()
+ for _, item := range n.List {
+ s += " " + item.String()
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n VarDecl) JS() string {
+ s := n.TokenType.String()
+ for i, item := range n.List {
+ if i != 0 {
+ s += ","
+ }
+ s += " " + item.JS()
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n VarDecl) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write(n.TokenType.Bytes())
+ i += wn
+ if err != nil {
+ return
+ }
+ for j, item := range n.List {
+ if j != 0 {
+ wn, err = w.Write([]byte(","))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// Params is a list of parameters for functions, methods, and arrow function.
+type Params struct {
+ List []BindingElement
+ Rest IBinding // can be nil
+}
+
+func (n Params) String() string {
+ s := "Params("
+ for i, item := range n.List {
+ if i != 0 {
+ s += ", "
+ }
+ s += item.String()
+ }
+ if n.Rest != nil {
+ if len(n.List) != 0 {
+ s += ", "
+ }
+ s += "...Binding(" + n.Rest.String() + ")"
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n Params) JS() string {
+ s := "("
+ for i, item := range n.List {
+ if i != 0 {
+ s += ", "
+ }
+ s += item.JS()
+ }
+ if n.Rest != nil {
+ if len(n.List) != 0 {
+ s += ", "
+ }
+ s += "..." + n.Rest.JS()
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n Params) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("("))
+ i += wn
+ if err != nil {
+ return
+ }
+ for j, item := range n.List {
+ if j != 0 {
+ wn, err = w.Write([]byte(", "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Rest != nil {
+ if len(n.List) != 0 {
+ wn, err = w.Write([]byte(", "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("..."))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Rest.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(")"))
+ i += wn
+ return
+}
+
+// FuncDecl is an (async) (generator) function declaration or expression.
+type FuncDecl struct {
+ Async bool
+ Generator bool
+ Name *Var // can be nil
+ Params Params
+ Body BlockStmt
+}
+
+func (n FuncDecl) String() string {
+ s := "Decl("
+ if n.Async {
+ s += "async function"
+ } else {
+ s += "function"
+ }
+ if n.Generator {
+ s += "*"
+ }
+ if n.Name != nil {
+ s += " " + string(n.Name.Data)
+ }
+ return s + " " + n.Params.String() + " " + n.Body.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n FuncDecl) JS() string {
+ s := ""
+ if n.Async {
+ s += "async function"
+ } else {
+ s += "function"
+ }
+ if n.Generator {
+ s += "*"
+ }
+ if n.Name != nil {
+ s += " " + string(n.Name.Data)
+ }
+ return s + " " + n.Params.JS() + " " + n.Body.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n FuncDecl) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.Async {
+ wn, err = w.Write([]byte("async function"))
+ } else {
+ wn, err = w.Write([]byte("function"))
+ }
+ i += wn
+ if err != nil {
+ return
+ }
+
+ if n.Generator {
+ wn, err = w.Write([]byte("*"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Name != nil {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write(n.Name.Data)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Params.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// MethodDecl is a method definition in a class declaration.
+type MethodDecl struct {
+ Static bool
+ Async bool
+ Generator bool
+ Get bool
+ Set bool
+ Name PropertyName
+ Params Params
+ Body BlockStmt
+}
+
+func (n MethodDecl) String() string {
+ s := ""
+ if n.Static {
+ s += " static"
+ }
+ if n.Async {
+ s += " async"
+ }
+ if n.Generator {
+ s += " *"
+ }
+ if n.Get {
+ s += " get"
+ }
+ if n.Set {
+ s += " set"
+ }
+ s += " " + n.Name.String() + " " + n.Params.String() + " " + n.Body.String()
+ return "Method(" + s[1:] + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n MethodDecl) JS() string {
+ s := ""
+ if n.Static {
+ s += " static"
+ }
+ if n.Async {
+ s += " async"
+ }
+ if n.Generator {
+ s += " *"
+ }
+ if n.Get {
+ s += " get"
+ }
+ if n.Set {
+ s += " set"
+ }
+ s += " " + n.Name.JS() + " " + n.Params.JS() + " " + n.Body.JS()
+ return s[1:]
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n MethodDecl) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.Static {
+ wn, err = w.Write([]byte("static"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Async {
+ if wn > 0 {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("async"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Generator {
+ if wn > 0 {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("*"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Get {
+ if wn > 0 {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("get"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Set {
+ if wn > 0 {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("set"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if wn > 0 {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = n.Name.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Params.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// Field is a field definition in a class declaration.
+type Field struct {
+ Static bool
+ Name PropertyName
+ Init IExpr
+}
+
+func (n Field) String() string {
+ s := "Field("
+ if n.Static {
+ s += "static "
+ }
+ s += n.Name.String()
+ if n.Init != nil {
+ s += " = " + n.Init.String()
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n Field) JS() string {
+ s := ""
+ if n.Static {
+ s += "static "
+ }
+ s += n.Name.String()
+ if n.Init != nil {
+ s += " = " + n.Init.JS()
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n Field) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.Static {
+ wn, err = w.Write([]byte("static "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = n.Name.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Init != nil {
+ wn, err = w.Write([]byte(" = "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Init.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// ClassElement is a class element that is either a static block, a field definition, or a class method
+type ClassElement struct {
+ StaticBlock *BlockStmt // can be nil
+ Method *MethodDecl // can be nil
+ Field
+}
+
+func (n ClassElement) String() string {
+ if n.StaticBlock != nil {
+ return "Static(" + n.StaticBlock.String() + ")"
+ } else if n.Method != nil {
+ return n.Method.String()
+ }
+ return n.Field.String()
+}
+
+// JS converts the node back to valid JavaScript
+func (n ClassElement) JS() string {
+ if n.StaticBlock != nil {
+ return "static " + n.StaticBlock.JS()
+ } else if n.Method != nil {
+ return n.Method.JS()
+ }
+ return n.Field.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ClassElement) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.StaticBlock != nil {
+ wn, err = w.Write([]byte("static "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.StaticBlock.JSWriteTo(w)
+ i += wn
+ return
+ } else if n.Method != nil {
+ wn, err = n.Method.JSWriteTo(w)
+ i += wn
+ return
+ }
+ wn, err = n.Field.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// ClassDecl is a class declaration.
+type ClassDecl struct {
+ Name *Var // can be nil
+ Extends IExpr // can be nil
+ List []ClassElement
+}
+
+func (n ClassDecl) String() string {
+ s := "Decl(class"
+ if n.Name != nil {
+ s += " " + string(n.Name.Data)
+ }
+ if n.Extends != nil {
+ s += " extends " + n.Extends.String()
+ }
+ for _, item := range n.List {
+ s += " " + item.String()
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ClassDecl) JS() string {
+ s := "class"
+ if n.Name != nil {
+ s += " " + string(n.Name.Data)
+ }
+ if n.Extends != nil {
+ s += " extends " + n.Extends.JS()
+ }
+ s += " { "
+ for _, item := range n.List {
+ s += item.JS() + "; "
+ }
+ return s + "}"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ClassDecl) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("class"))
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Name != nil {
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write(n.Name.Data)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if n.Extends != nil {
+ wn, err = w.Write([]byte(" extends "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Extends.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(" { "))
+ i += wn
+ if err != nil {
+ return
+ }
+ for _, item := range n.List {
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte("; "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("}"))
+ i += wn
+ return
+}
+
+func (n VarDecl) stmtNode() {}
+func (n FuncDecl) stmtNode() {}
+func (n ClassDecl) stmtNode() {}
+
+func (n VarDecl) exprNode() {} // not a real IExpr, used for ForInit and ExportDecl
+func (n FuncDecl) exprNode() {}
+func (n ClassDecl) exprNode() {}
+func (n MethodDecl) exprNode() {} // not a real IExpr, used for ObjectExpression PropertyName
+
+////////////////////////////////////////////////////////////////
+
+// LiteralExpr can be this, null, boolean, numeric, string, or regular expression literals.
+type LiteralExpr struct {
+ TokenType
+ Data []byte
+}
+
+func (n LiteralExpr) String() string {
+ return string(n.Data)
+}
+
+// JS converts the node back to valid JavaScript
+func (n LiteralExpr) JS() string {
+ return string(n.Data)
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n LiteralExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write(n.Data)
+ i += wn
+ return
+}
+
+// JSON converts the node back to valid JSON
+func (n LiteralExpr) JSON(buf *bytes.Buffer) error {
+ if n.TokenType == TrueToken || n.TokenType == FalseToken || n.TokenType == NullToken || n.TokenType == DecimalToken {
+ buf.Write(n.Data)
+ return nil
+ } else if n.TokenType == StringToken {
+ data := n.Data
+ if n.Data[0] == '\'' {
+ data = parse.Copy(data)
+ data = bytes.ReplaceAll(data, []byte(`"`), []byte(`\"`))
+ data[0] = '"'
+ data[len(data)-1] = '"'
+ }
+ buf.Write(data)
+ return nil
+ }
+ return ErrInvalidJSON
+}
+
+// Element is an array literal element.
+type Element struct {
+ Value IExpr // can be nil
+ Spread bool
+}
+
+func (n Element) String() string {
+ s := ""
+ if n.Value != nil {
+ if n.Spread {
+ s += "..."
+ }
+ s += n.Value.String()
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript
+func (n Element) JS() string {
+ s := ""
+ if n.Value != nil {
+ if n.Spread {
+ s += "..."
+ }
+ s += n.Value.JS()
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n Element) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.Value != nil {
+ if n.Spread {
+ wn, err = w.Write([]byte("..."))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = n.Value.JSWriteTo(w)
+ i += wn
+ }
+ return
+}
+
+// ArrayExpr is an array literal.
+type ArrayExpr struct {
+ List []Element
+}
+
+func (n ArrayExpr) String() string {
+ s := "["
+ for i, item := range n.List {
+ if i != 0 {
+ s += ", "
+ }
+ if item.Value != nil {
+ if item.Spread {
+ s += "..."
+ }
+ s += item.Value.String()
+ }
+ }
+ if 0 < len(n.List) && n.List[len(n.List)-1].Value == nil {
+ s += ","
+ }
+ return s + "]"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ArrayExpr) JS() string {
+ s := "["
+ for i, item := range n.List {
+ if i != 0 {
+ s += ", "
+ }
+ if item.Value != nil {
+ if item.Spread {
+ s += "..."
+ }
+ s += item.Value.JS()
+ }
+ }
+ if 0 < len(n.List) && n.List[len(n.List)-1].Value == nil {
+ s += ","
+ }
+ return s + "]"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ArrayExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("["))
+ i += wn
+ if err != nil {
+ return
+ }
+ for j, item := range n.List {
+ if j != 0 {
+ wn, err = w.Write([]byte(", "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ if item.Value != nil {
+ if item.Spread {
+ wn, err = w.Write([]byte("..."))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = item.Value.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ }
+ if 0 < len(n.List) && n.List[len(n.List)-1].Value == nil {
+ wn, err = w.Write([]byte(","))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("]"))
+ i += wn
+ return
+}
+
+// JSON converts the node back to valid JSON
+func (n ArrayExpr) JSON(buf *bytes.Buffer) error {
+ buf.WriteByte('[')
+ for i, item := range n.List {
+ if i != 0 {
+ buf.WriteString(", ")
+ }
+ if item.Value == nil || item.Spread {
+ return ErrInvalidJSON
+ }
+ val, ok := item.Value.(JSONer)
+ if !ok {
+ return ErrInvalidJSON
+ } else if err := val.JSON(buf); err != nil {
+ return err
+ }
+ }
+ buf.WriteByte(']')
+ return nil
+}
+
+// Property is a property definition in an object literal.
+type Property struct {
+ // either Name or Spread are set. When Spread is set then Value is AssignmentExpression
+ // if Init is set then Value is IdentifierReference, otherwise it can also be MethodDefinition
+ Name *PropertyName // can be nil
+ Spread bool
+ Value IExpr
+ Init IExpr // can be nil
+}
+
+func (n Property) String() string {
+ s := ""
+ if n.Name != nil {
+ if v, ok := n.Value.(*Var); !ok || !n.Name.IsIdent(v.Data) {
+ s += n.Name.String() + ": "
+ }
+ } else if n.Spread {
+ s += "..."
+ }
+ s += n.Value.String()
+ if n.Init != nil {
+ s += " = " + n.Init.String()
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript
+func (n Property) JS() string {
+ s := ""
+ if n.Name != nil {
+ if v, ok := n.Value.(*Var); !ok || !n.Name.IsIdent(v.Data) {
+ s += n.Name.JS() + ": "
+ }
+ } else if n.Spread {
+ s += "..."
+ }
+ s += n.Value.JS()
+ if n.Init != nil {
+ s += " = " + n.Init.JS()
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n Property) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.Name != nil {
+ if v, ok := n.Value.(*Var); !ok || !n.Name.IsIdent(v.Data) {
+ wn, err = n.Name.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(": "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ } else if n.Spread {
+ wn, err = w.Write([]byte("..."))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = n.Value.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Init != nil {
+ wn, err = w.Write([]byte(" = "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Init.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// JSON converts the node back to valid JSON
+func (n Property) JSON(buf *bytes.Buffer) error {
+ if n.Name == nil || n.Name.Literal.TokenType != StringToken && n.Name.Literal.TokenType != IdentifierToken || n.Spread || n.Init != nil {
+ return ErrInvalidJSON
+ } else if n.Name.Literal.TokenType == IdentifierToken {
+ buf.WriteByte('"')
+ buf.Write(n.Name.Literal.Data)
+ buf.WriteByte('"')
+ } else {
+ _ = n.Name.Literal.JSON(buf)
+ }
+ buf.WriteString(": ")
+
+ val, ok := n.Value.(JSONer)
+ if !ok {
+ return ErrInvalidJSON
+ } else if err := val.JSON(buf); err != nil {
+ return err
+ }
+ return nil
+}
+
+// ObjectExpr is an object literal.
+type ObjectExpr struct {
+ List []Property
+}
+
+func (n ObjectExpr) String() string {
+ s := "{"
+ for i, item := range n.List {
+ if i != 0 {
+ s += ", "
+ }
+ s += item.String()
+ }
+ return s + "}"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ObjectExpr) JS() string {
+ s := "{"
+ for i, item := range n.List {
+ if i != 0 {
+ s += ", "
+ }
+ s += item.JS()
+ }
+ return s + "}"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ObjectExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("{"))
+ i += wn
+ if err != nil {
+ return
+ }
+ for j, item := range n.List {
+ if j != 0 {
+ wn, err = w.Write([]byte(", "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte("}"))
+ i += wn
+ return
+}
+
+// JSON converts the node back to valid JSON
+func (n ObjectExpr) JSON(buf *bytes.Buffer) error {
+ buf.WriteByte('{')
+ for i, item := range n.List {
+ if i != 0 {
+ buf.WriteString(", ")
+ }
+ if err := item.JSON(buf); err != nil {
+ return err
+ }
+ }
+ buf.WriteByte('}')
+ return nil
+}
+
+// TemplatePart is a template head or middle.
+type TemplatePart struct {
+ Value []byte
+ Expr IExpr
+}
+
+func (n TemplatePart) String() string {
+ return string(n.Value) + n.Expr.String()
+}
+
+// JS converts the node back to valid JavaScript
+func (n TemplatePart) JS() string {
+ return string(n.Value) + n.Expr.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n TemplatePart) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write(n.Value)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Expr.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// TemplateExpr is a template literal or member/call expression, super property, or optional chain with template literal.
+type TemplateExpr struct {
+ Tag IExpr // can be nil
+ List []TemplatePart
+ Tail []byte
+ Prec OpPrec
+ Optional bool
+}
+
+func (n TemplateExpr) String() string {
+ s := ""
+ if n.Tag != nil {
+ s += n.Tag.String()
+ if n.Optional {
+ s += "?."
+ }
+ }
+ for _, item := range n.List {
+ s += item.String()
+ }
+ return s + string(n.Tail)
+}
+
+// JS converts the node back to valid JavaScript
+func (n TemplateExpr) JS() string {
+ s := ""
+ if n.Tag != nil {
+ s += n.Tag.JS()
+ if n.Optional {
+ s += "?."
+ }
+ }
+ for _, item := range n.List {
+ s += item.JS()
+ }
+ return s + string(n.Tail)
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n TemplateExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.Tag != nil {
+ wn, err = n.Tag.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Optional {
+ wn, err = w.Write([]byte("?."))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ }
+ for _, item := range n.List {
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write(n.Tail)
+ i += wn
+ return
+}
+
+// GroupExpr is a parenthesized expression.
+type GroupExpr struct {
+ X IExpr
+}
+
+func (n GroupExpr) String() string {
+ return "(" + n.X.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n GroupExpr) JS() string {
+ return "(" + n.X.JS() + ")"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n GroupExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("("))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.X.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(")"))
+ i += wn
+ return
+}
+
+// IndexExpr is a member/call expression, super property, or optional chain with an index expression.
+type IndexExpr struct {
+ X IExpr
+ Y IExpr
+ Prec OpPrec
+ Optional bool
+}
+
+func (n IndexExpr) String() string {
+ if n.Optional {
+ return "(" + n.X.String() + "?.[" + n.Y.String() + "])"
+ }
+ return "(" + n.X.String() + "[" + n.Y.String() + "])"
+}
+
+// JS converts the node back to valid JavaScript
+func (n IndexExpr) JS() string {
+ if n.Optional {
+ return n.X.JS() + "?.[" + n.Y.JS() + "]"
+ }
+ return n.X.JS() + "[" + n.Y.JS() + "]"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n IndexExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = n.X.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Optional {
+ wn, err = w.Write([]byte("?.["))
+ i += wn
+ if err != nil {
+ return
+ }
+ } else {
+ wn, err = w.Write([]byte("["))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = n.Y.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte("]"))
+ i += wn
+ return
+}
+
+// DotExpr is a member/call expression, super property, or optional chain with a dot expression.
+type DotExpr struct {
+ X IExpr
+ Y LiteralExpr
+ Prec OpPrec
+ Optional bool
+}
+
+func (n DotExpr) String() string {
+ if n.Optional {
+ return "(" + n.X.String() + "?." + n.Y.String() + ")"
+ }
+ return "(" + n.X.String() + "." + n.Y.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n DotExpr) JS() string {
+ if n.Optional {
+ return n.X.JS() + "?." + n.Y.JS()
+ }
+ return n.X.JS() + "." + n.Y.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n DotExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = n.X.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Optional {
+ wn, err = w.Write([]byte("?."))
+ i += wn
+ if err != nil {
+ return
+ }
+ } else {
+ wn, err = w.Write([]byte("."))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = n.Y.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// NewTargetExpr is a new target meta property.
+type NewTargetExpr struct {
+}
+
+func (n NewTargetExpr) String() string {
+ return "(new.target)"
+}
+
+// JS converts the node back to valid JavaScript
+func (n NewTargetExpr) JS() string {
+ return "new.target"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n NewTargetExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("new.target"))
+ i += wn
+ return
+}
+
+// ImportMetaExpr is a import meta meta property.
+type ImportMetaExpr struct {
+}
+
+func (n ImportMetaExpr) String() string {
+ return "(import.meta)"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ImportMetaExpr) JS() string {
+ return "import.meta"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ImportMetaExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("import.meta"))
+ i += wn
+ return
+}
+
+type Arg struct {
+ Value IExpr
+ Rest bool
+}
+
+func (n Arg) String() string {
+ s := ""
+ if n.Rest {
+ s += "..."
+ }
+ return s + n.Value.String()
+}
+
+// JS converts the node back to valid JavaScript
+func (n Arg) JS() string {
+ s := ""
+ if n.Rest {
+ s += "..."
+ }
+ return s + n.Value.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n Arg) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.Rest {
+ wn, err = w.Write([]byte("..."))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = n.Value.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// Args is a list of arguments as used by new and call expressions.
+type Args struct {
+ List []Arg
+}
+
+func (n Args) String() string {
+ s := "("
+ for i, item := range n.List {
+ if i != 0 {
+ s += ", "
+ }
+ s += item.String()
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n Args) JS() string {
+ s := ""
+ for i, item := range n.List {
+ if i != 0 {
+ s += ", "
+ }
+ s += item.JS()
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n Args) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ for j, item := range n.List {
+ if j != 0 {
+ wn, err = w.Write([]byte(", "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// NewExpr is a new expression or new member expression.
+type NewExpr struct {
+ X IExpr
+ Args *Args // can be nil
+}
+
+func (n NewExpr) String() string {
+ if n.Args != nil {
+ return "(new " + n.X.String() + n.Args.String() + ")"
+ }
+ return "(new " + n.X.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n NewExpr) JS() string {
+ if n.Args != nil {
+ return "new " + n.X.JS() + "(" + n.Args.JS() + ")"
+ }
+
+ // always use parentheses to prevent errors when chaining e.g. new Date().getTime()
+ return "new " + n.X.JS() + "()"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n NewExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("new "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.X.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Args != nil {
+ wn, err = w.Write([]byte("("))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Args.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(")"))
+ i += wn
+ if err != nil {
+ return
+ }
+ } else {
+ wn, err = w.Write([]byte("()"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+// CallExpr is a call expression.
+type CallExpr struct {
+ X IExpr
+ Args Args
+ Optional bool
+}
+
+func (n CallExpr) String() string {
+ if n.Optional {
+ return "(" + n.X.String() + "?." + n.Args.String() + ")"
+ }
+ return "(" + n.X.String() + n.Args.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n CallExpr) JS() string {
+ if n.Optional {
+ return n.X.JS() + "?.(" + n.Args.JS() + ")"
+ }
+ return n.X.JS() + "(" + n.Args.JS() + ")"
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n CallExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = n.X.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.Optional {
+ wn, err = w.Write([]byte("?.("))
+ i += wn
+ if err != nil {
+ return
+ }
+ } else {
+ wn, err = w.Write([]byte("("))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = n.Args.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(")"))
+ i += wn
+ if err != nil {
+ return
+ }
+ return
+}
+
+// UnaryExpr is an update or unary expression.
+type UnaryExpr struct {
+ Op TokenType
+ X IExpr
+}
+
+func (n UnaryExpr) String() string {
+ if n.Op == PostIncrToken || n.Op == PostDecrToken {
+ return "(" + n.X.String() + n.Op.String() + ")"
+ } else if IsIdentifierName(n.Op) {
+ return "(" + n.Op.String() + " " + n.X.String() + ")"
+ }
+ return "(" + n.Op.String() + n.X.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n UnaryExpr) JS() string {
+ if n.Op == PostIncrToken || n.Op == PostDecrToken {
+ return n.X.JS() + n.Op.String()
+ } else if IsIdentifierName(n.Op) {
+ return n.Op.String() + " " + n.X.JS()
+ }
+ return n.Op.String() + n.X.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n UnaryExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.Op == PostIncrToken || n.Op == PostDecrToken {
+ wn, err = n.X.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write(n.Op.Bytes())
+ i += wn
+ return
+ } else if IsIdentifierName(n.Op) {
+ wn, err = w.Write(n.Op.Bytes())
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.X.JSWriteTo(w)
+ i += wn
+ return
+ }
+ wn, err = w.Write(n.Op.Bytes())
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.X.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// JSON converts the node back to valid JSON
+func (n UnaryExpr) JSON(buf *bytes.Buffer) error {
+ if lit, ok := n.X.(*LiteralExpr); ok && n.Op == NegToken && lit.TokenType == DecimalToken {
+ buf.WriteByte('-')
+ buf.Write(lit.Data)
+ return nil
+ }
+ return ErrInvalidJSON
+}
+
+// BinaryExpr is a binary expression.
+type BinaryExpr struct {
+ Op TokenType
+ X, Y IExpr
+}
+
+func (n BinaryExpr) String() string {
+ if IsIdentifierName(n.Op) {
+ return "(" + n.X.String() + " " + n.Op.String() + " " + n.Y.String() + ")"
+ }
+ return "(" + n.X.String() + n.Op.String() + n.Y.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n BinaryExpr) JS() string {
+ return n.X.JS() + " " + n.Op.String() + " " + n.Y.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n BinaryExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = n.X.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write(n.Op.Bytes())
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Y.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// CondExpr is a conditional expression.
+type CondExpr struct {
+ Cond, X, Y IExpr
+}
+
+func (n CondExpr) String() string {
+ return "(" + n.Cond.String() + " ? " + n.X.String() + " : " + n.Y.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n CondExpr) JS() string {
+ return n.Cond.JS() + " ? " + n.X.JS() + " : " + n.Y.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n CondExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = n.Cond.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" ? "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.X.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" : "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Y.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// YieldExpr is a yield expression.
+type YieldExpr struct {
+ Generator bool
+ X IExpr // can be nil
+}
+
+func (n YieldExpr) String() string {
+ if n.X == nil {
+ return "(yield)"
+ }
+ s := "(yield"
+ if n.Generator {
+ s += "*"
+ }
+ return s + " " + n.X.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n YieldExpr) JS() string {
+ if n.X == nil {
+ return "yield"
+ }
+ s := "yield"
+ if n.Generator {
+ s += "*"
+ }
+ return s + " " + n.X.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n YieldExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ wn, err = w.Write([]byte("yield"))
+ i += wn
+ if err != nil {
+ return
+ }
+ if n.X == nil {
+ return
+ }
+ if n.Generator {
+ wn, err = w.Write([]byte("*"))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = w.Write([]byte(" "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.X.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// ArrowFunc is an (async) arrow function.
+type ArrowFunc struct {
+ Async bool
+ Params Params
+ Body BlockStmt
+}
+
+func (n ArrowFunc) String() string {
+ s := "("
+ if n.Async {
+ s += "async "
+ }
+ return s + n.Params.String() + " => " + n.Body.String() + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n ArrowFunc) JS() string {
+ s := ""
+ if n.Async {
+ s += "async "
+ }
+ return s + n.Params.JS() + " => " + n.Body.JS()
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n ArrowFunc) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ if n.Async {
+ wn, err = w.Write([]byte("async "))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = n.Params.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = w.Write([]byte(" => "))
+ i += wn
+ if err != nil {
+ return
+ }
+ wn, err = n.Body.JSWriteTo(w)
+ i += wn
+ return
+}
+
+// CommaExpr is a series of comma expressions.
+type CommaExpr struct {
+ List []IExpr
+}
+
+func (n CommaExpr) String() string {
+ s := "("
+ for i, item := range n.List {
+ if i != 0 {
+ s += ","
+ }
+ s += item.String()
+ }
+ return s + ")"
+}
+
+// JS converts the node back to valid JavaScript
+func (n CommaExpr) JS() string {
+ s := ""
+ for i, item := range n.List {
+ if i != 0 {
+ s += ","
+ }
+ s += item.JS()
+ }
+ return s
+}
+
+// JS converts the node back to valid JavaScript (writes to io.Writer)
+func (n CommaExpr) JSWriteTo(w io.Writer) (i int, err error) {
+ var wn int
+ for j, item := range n.List {
+ if j != 0 {
+ wn, err = w.Write([]byte(","))
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ wn, err = item.JSWriteTo(w)
+ i += wn
+ if err != nil {
+ return
+ }
+ }
+ return
+}
+
+func (v *Var) exprNode() {}
+func (n LiteralExpr) exprNode() {}
+func (n ArrayExpr) exprNode() {}
+func (n ObjectExpr) exprNode() {}
+func (n TemplateExpr) exprNode() {}
+func (n GroupExpr) exprNode() {}
+func (n DotExpr) exprNode() {}
+func (n IndexExpr) exprNode() {}
+func (n NewTargetExpr) exprNode() {}
+func (n ImportMetaExpr) exprNode() {}
+func (n NewExpr) exprNode() {}
+func (n CallExpr) exprNode() {}
+func (n UnaryExpr) exprNode() {}
+func (n BinaryExpr) exprNode() {}
+func (n CondExpr) exprNode() {}
+func (n YieldExpr) exprNode() {}
+func (n ArrowFunc) exprNode() {}
+func (n CommaExpr) exprNode() {}
diff --git a/vendor/github.com/tdewolff/parse/v2/js/lex.go b/vendor/github.com/tdewolff/parse/v2/js/lex.go
new file mode 100644
index 0000000..7d75bf5
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/js/lex.go
@@ -0,0 +1,793 @@
+// Package js is an ECMAScript5.1 lexer following the specifications at http://www.ecma-international.org/ecma-262/5.1/.
+package js
+
+import (
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/tdewolff/parse/v2"
+)
+
+var identifierStart = []*unicode.RangeTable{unicode.Lu, unicode.Ll, unicode.Lt, unicode.Lm, unicode.Lo, unicode.Nl, unicode.Other_ID_Start}
+var identifierContinue = []*unicode.RangeTable{unicode.Lu, unicode.Ll, unicode.Lt, unicode.Lm, unicode.Lo, unicode.Nl, unicode.Mn, unicode.Mc, unicode.Nd, unicode.Pc, unicode.Other_ID_Continue}
+
+// IsIdentifierStart returns true if the byte-slice start is the start of an identifier
+func IsIdentifierStart(b []byte) bool {
+ r, _ := utf8.DecodeRune(b)
+ return r == '$' || r == '\\' || r == '_' || unicode.IsOneOf(identifierStart, r)
+}
+
+// IsIdentifierContinue returns true if the byte-slice start is a continuation of an identifier
+func IsIdentifierContinue(b []byte) bool {
+ r, _ := utf8.DecodeRune(b)
+ return r == '$' || r == '\\' || r == '\u200C' || r == '\u200D' || unicode.IsOneOf(identifierContinue, r)
+}
+
+// IsIdentifierEnd returns true if the byte-slice end is a start or continuation of an identifier
+func IsIdentifierEnd(b []byte) bool {
+ r, _ := utf8.DecodeLastRune(b)
+ return r == '$' || r == '\\' || r == '\u200C' || r == '\u200D' || unicode.IsOneOf(identifierContinue, r)
+}
+
+////////////////////////////////////////////////////////////////
+
+// Lexer is the state for the lexer.
+type Lexer struct {
+ r *parse.Input
+ err error
+ prevLineTerminator bool
+ prevNumericLiteral bool
+ level int
+ templateLevels []int
+}
+
+// NewLexer returns a new Lexer for a given io.Reader.
+func NewLexer(r *parse.Input) *Lexer {
+ return &Lexer{
+ r: r,
+ prevLineTerminator: true,
+ level: 0,
+ templateLevels: []int{},
+ }
+}
+
+// Err returns the error encountered during lexing, this is often io.EOF but also other errors can be returned.
+func (l *Lexer) Err() error {
+ if l.err != nil {
+ return l.err
+ }
+ return l.r.Err()
+}
+
+// RegExp reparses the input stream for a regular expression. It is assumed that we just received DivToken or DivEqToken with Next(). This function will go back and read that as a regular expression.
+func (l *Lexer) RegExp() (TokenType, []byte) {
+ if 0 < l.r.Offset() && l.r.Peek(-1) == '/' {
+ l.r.Move(-1)
+ } else if 1 < l.r.Offset() && l.r.Peek(-1) == '=' && l.r.Peek(-2) == '/' {
+ l.r.Move(-2)
+ } else {
+ l.err = parse.NewErrorLexer(l.r, "expected / or /=")
+ return ErrorToken, nil
+ }
+ l.r.Skip() // trick to set start = pos
+
+ if l.consumeRegExpToken() {
+ return RegExpToken, l.r.Shift()
+ }
+ l.err = parse.NewErrorLexer(l.r, "unexpected EOF or newline")
+ return ErrorToken, nil
+}
+
+// Next returns the next Token. It returns ErrorToken when an error was encountered. Using Err() one can retrieve the error message.
+func (l *Lexer) Next() (TokenType, []byte) {
+ prevLineTerminator := l.prevLineTerminator
+ l.prevLineTerminator = false
+
+ prevNumericLiteral := l.prevNumericLiteral
+ l.prevNumericLiteral = false
+
+ // study on 50x jQuery shows:
+ // spaces: 20k
+ // alpha: 16k
+ // newlines: 14.4k
+ // operators: 4k
+ // numbers and dot: 3.6k
+ // (): 3.4k
+ // {}: 1.8k
+ // []: 0.9k
+ // "': 1k
+ // semicolon: 2.4k
+ // colon: 0.8k
+ // comma: 2.4k
+ // slash: 1.4k
+ // `~: almost 0
+
+ c := l.r.Peek(0)
+ switch c {
+ case ' ', '\t', '\v', '\f':
+ l.r.Move(1)
+ for l.consumeWhitespace() {
+ }
+ l.prevLineTerminator = prevLineTerminator
+ return WhitespaceToken, l.r.Shift()
+ case '\n', '\r':
+ l.r.Move(1)
+ for l.consumeLineTerminator() {
+ }
+ l.prevLineTerminator = true
+ return LineTerminatorToken, l.r.Shift()
+ case '>', '=', '!', '+', '*', '%', '&', '|', '^', '~', '?':
+ if tt := l.consumeOperatorToken(); tt != ErrorToken {
+ return tt, l.r.Shift()
+ }
+ case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.':
+ if tt := l.consumeNumericToken(); tt != ErrorToken || l.r.Pos() != 0 {
+ l.prevNumericLiteral = true
+ return tt, l.r.Shift()
+ } else if c == '.' {
+ l.r.Move(1)
+ if l.r.Peek(0) == '.' && l.r.Peek(1) == '.' {
+ l.r.Move(2)
+ return EllipsisToken, l.r.Shift()
+ }
+ return DotToken, l.r.Shift()
+ }
+ case ',':
+ l.r.Move(1)
+ return CommaToken, l.r.Shift()
+ case ';':
+ l.r.Move(1)
+ return SemicolonToken, l.r.Shift()
+ case '(':
+ l.level++
+ l.r.Move(1)
+ return OpenParenToken, l.r.Shift()
+ case ')':
+ l.level--
+ l.r.Move(1)
+ return CloseParenToken, l.r.Shift()
+ case '/':
+ if tt := l.consumeCommentToken(); tt != ErrorToken {
+ return tt, l.r.Shift()
+ } else if tt := l.consumeOperatorToken(); tt != ErrorToken {
+ return tt, l.r.Shift()
+ }
+ case '{':
+ l.level++
+ l.r.Move(1)
+ return OpenBraceToken, l.r.Shift()
+ case '}':
+ l.level--
+ if len(l.templateLevels) != 0 && l.level == l.templateLevels[len(l.templateLevels)-1] {
+ return l.consumeTemplateToken(), l.r.Shift()
+ }
+ l.r.Move(1)
+ return CloseBraceToken, l.r.Shift()
+ case ':':
+ l.r.Move(1)
+ return ColonToken, l.r.Shift()
+ case '\'', '"':
+ return l.consumeStringToken(), l.r.Shift()
+ case ']':
+ l.r.Move(1)
+ return CloseBracketToken, l.r.Shift()
+ case '[':
+ l.r.Move(1)
+ return OpenBracketToken, l.r.Shift()
+ case '<', '-':
+ if l.consumeHTMLLikeCommentToken(prevLineTerminator) {
+ return CommentToken, l.r.Shift()
+ } else if tt := l.consumeOperatorToken(); tt != ErrorToken {
+ return tt, l.r.Shift()
+ }
+ case '`':
+ l.templateLevels = append(l.templateLevels, l.level)
+ return l.consumeTemplateToken(), l.r.Shift()
+ case '#':
+ l.r.Move(1)
+ if l.consumeIdentifierToken() {
+ return PrivateIdentifierToken, l.r.Shift()
+ }
+ return ErrorToken, nil
+ default:
+ if l.consumeIdentifierToken() {
+ if prevNumericLiteral {
+ l.err = parse.NewErrorLexer(l.r, "unexpected identifier after number")
+ return ErrorToken, nil
+ } else if keyword, ok := Keywords[string(l.r.Lexeme())]; ok {
+ return keyword, l.r.Shift()
+ }
+ return IdentifierToken, l.r.Shift()
+ }
+ if 0xC0 <= c {
+ if l.consumeWhitespace() {
+ for l.consumeWhitespace() {
+ }
+ l.prevLineTerminator = prevLineTerminator
+ return WhitespaceToken, l.r.Shift()
+ } else if l.consumeLineTerminator() {
+ for l.consumeLineTerminator() {
+ }
+ l.prevLineTerminator = true
+ return LineTerminatorToken, l.r.Shift()
+ }
+ } else if c == 0 && l.r.Err() != nil {
+ return ErrorToken, nil
+ }
+ }
+
+ r, _ := l.r.PeekRune(0)
+ l.err = parse.NewErrorLexer(l.r, "unexpected %s", parse.Printable(r))
+ return ErrorToken, l.r.Shift()
+}
+
+////////////////////////////////////////////////////////////////
+
+/*
+The following functions follow the specifications at http://www.ecma-international.org/ecma-262/5.1/
+*/
+
+func (l *Lexer) consumeWhitespace() bool {
+ c := l.r.Peek(0)
+ if c == ' ' || c == '\t' || c == '\v' || c == '\f' {
+ l.r.Move(1)
+ return true
+ } else if 0xC0 <= c {
+ if r, n := l.r.PeekRune(0); r == '\u00A0' || r == '\uFEFF' || unicode.Is(unicode.Zs, r) {
+ l.r.Move(n)
+ return true
+ }
+ }
+ return false
+}
+
+func (l *Lexer) isLineTerminator() bool {
+ c := l.r.Peek(0)
+ if c == '\n' || c == '\r' {
+ return true
+ } else if c == 0xE2 && l.r.Peek(1) == 0x80 && (l.r.Peek(2) == 0xA8 || l.r.Peek(2) == 0xA9) {
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeLineTerminator() bool {
+ c := l.r.Peek(0)
+ if c == '\n' {
+ l.r.Move(1)
+ return true
+ } else if c == '\r' {
+ if l.r.Peek(1) == '\n' {
+ l.r.Move(2)
+ } else {
+ l.r.Move(1)
+ }
+ return true
+ } else if c == 0xE2 && l.r.Peek(1) == 0x80 && (l.r.Peek(2) == 0xA8 || l.r.Peek(2) == 0xA9) {
+ l.r.Move(3)
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeDigit() bool {
+ if c := l.r.Peek(0); c >= '0' && c <= '9' {
+ l.r.Move(1)
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeHexDigit() bool {
+ if c := l.r.Peek(0); (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') {
+ l.r.Move(1)
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeBinaryDigit() bool {
+ if c := l.r.Peek(0); c == '0' || c == '1' {
+ l.r.Move(1)
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeOctalDigit() bool {
+ if c := l.r.Peek(0); c >= '0' && c <= '7' {
+ l.r.Move(1)
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeUnicodeEscape() bool {
+ if l.r.Peek(0) != '\\' || l.r.Peek(1) != 'u' {
+ return false
+ }
+ mark := l.r.Pos()
+ l.r.Move(2)
+ if c := l.r.Peek(0); c == '{' {
+ l.r.Move(1)
+ if l.consumeHexDigit() {
+ for l.consumeHexDigit() {
+ }
+ if c := l.r.Peek(0); c == '}' {
+ l.r.Move(1)
+ return true
+ }
+ }
+ l.r.Rewind(mark)
+ return false
+ } else if !l.consumeHexDigit() || !l.consumeHexDigit() || !l.consumeHexDigit() || !l.consumeHexDigit() {
+ l.r.Rewind(mark)
+ return false
+ }
+ return true
+}
+
+func (l *Lexer) consumeSingleLineComment() {
+ for {
+ c := l.r.Peek(0)
+ if c == '\r' || c == '\n' || c == 0 && l.r.Err() != nil {
+ break
+ } else if 0xC0 <= c {
+ if r, _ := l.r.PeekRune(0); r == '\u2028' || r == '\u2029' {
+ break
+ }
+ }
+ l.r.Move(1)
+ }
+}
+
+////////////////////////////////////////////////////////////////
+
+func (l *Lexer) consumeHTMLLikeCommentToken(prevLineTerminator bool) bool {
+ c := l.r.Peek(0)
+ if c == '<' && l.r.Peek(1) == '!' && l.r.Peek(2) == '-' && l.r.Peek(3) == '-' {
+ // opening HTML-style single line comment
+ l.r.Move(4)
+ l.consumeSingleLineComment()
+ return true
+ } else if prevLineTerminator && c == '-' && l.r.Peek(1) == '-' && l.r.Peek(2) == '>' {
+ // closing HTML-style single line comment
+ // (only if current line didn't contain any meaningful tokens)
+ l.r.Move(3)
+ l.consumeSingleLineComment()
+ return true
+ }
+ return false
+}
+
+func (l *Lexer) consumeCommentToken() TokenType {
+ c := l.r.Peek(1)
+ if c == '/' {
+ // single line comment
+ l.r.Move(2)
+ l.consumeSingleLineComment()
+ return CommentToken
+ } else if c == '*' {
+ l.r.Move(2)
+ tt := CommentToken
+ for {
+ c := l.r.Peek(0)
+ if c == '*' && l.r.Peek(1) == '/' {
+ l.r.Move(2)
+ break
+ } else if c == 0 && l.r.Err() != nil {
+ break
+ } else if l.consumeLineTerminator() {
+ l.prevLineTerminator = true
+ tt = CommentLineTerminatorToken
+ } else {
+ l.r.Move(1)
+ }
+ }
+ return tt
+ }
+ return ErrorToken
+}
+
+var opTokens = map[byte]TokenType{
+ '=': EqToken,
+ '!': NotToken,
+ '<': LtToken,
+ '>': GtToken,
+ '+': AddToken,
+ '-': SubToken,
+ '*': MulToken,
+ '/': DivToken,
+ '%': ModToken,
+ '&': BitAndToken,
+ '|': BitOrToken,
+ '^': BitXorToken,
+ '~': BitNotToken,
+ '?': QuestionToken,
+}
+
+var opEqTokens = map[byte]TokenType{
+ '=': EqEqToken,
+ '!': NotEqToken,
+ '<': LtEqToken,
+ '>': GtEqToken,
+ '+': AddEqToken,
+ '-': SubEqToken,
+ '*': MulEqToken,
+ '/': DivEqToken,
+ '%': ModEqToken,
+ '&': BitAndEqToken,
+ '|': BitOrEqToken,
+ '^': BitXorEqToken,
+}
+
+var opOpTokens = map[byte]TokenType{
+ '<': LtLtToken,
+ '+': IncrToken,
+ '-': DecrToken,
+ '*': ExpToken,
+ '&': AndToken,
+ '|': OrToken,
+ '?': NullishToken,
+}
+
+var opOpEqTokens = map[byte]TokenType{
+ '<': LtLtEqToken,
+ '*': ExpEqToken,
+ '&': AndEqToken,
+ '|': OrEqToken,
+ '?': NullishEqToken,
+}
+
+func (l *Lexer) consumeOperatorToken() TokenType {
+ c := l.r.Peek(0)
+ l.r.Move(1)
+ if l.r.Peek(0) == '=' {
+ l.r.Move(1)
+ if l.r.Peek(0) == '=' && (c == '!' || c == '=') {
+ l.r.Move(1)
+ if c == '!' {
+ return NotEqEqToken
+ }
+ return EqEqEqToken
+ }
+ return opEqTokens[c]
+ } else if l.r.Peek(0) == c && (c == '+' || c == '-' || c == '*' || c == '&' || c == '|' || c == '?' || c == '<') {
+ l.r.Move(1)
+ if l.r.Peek(0) == '=' && c != '+' && c != '-' {
+ l.r.Move(1)
+ return opOpEqTokens[c]
+ }
+ return opOpTokens[c]
+ } else if c == '?' && l.r.Peek(0) == '.' && (l.r.Peek(1) < '0' || l.r.Peek(1) > '9') {
+ l.r.Move(1)
+ return OptChainToken
+ } else if c == '=' && l.r.Peek(0) == '>' {
+ l.r.Move(1)
+ return ArrowToken
+ } else if c == '>' && l.r.Peek(0) == '>' {
+ l.r.Move(1)
+ if l.r.Peek(0) == '>' {
+ l.r.Move(1)
+ if l.r.Peek(0) == '=' {
+ l.r.Move(1)
+ return GtGtGtEqToken
+ }
+ return GtGtGtToken
+ } else if l.r.Peek(0) == '=' {
+ l.r.Move(1)
+ return GtGtEqToken
+ }
+ return GtGtToken
+ }
+ return opTokens[c]
+}
+
+func (l *Lexer) consumeIdentifierToken() bool {
+ c := l.r.Peek(0)
+ if identifierStartTable[c] {
+ l.r.Move(1)
+ } else if 0xC0 <= c {
+ if r, n := l.r.PeekRune(0); unicode.IsOneOf(identifierStart, r) {
+ l.r.Move(n)
+ } else {
+ return false
+ }
+ } else if !l.consumeUnicodeEscape() {
+ return false
+ }
+ for {
+ c := l.r.Peek(0)
+ if identifierTable[c] {
+ l.r.Move(1)
+ } else if 0xC0 <= c {
+ if r, n := l.r.PeekRune(0); r == '\u200C' || r == '\u200D' || unicode.IsOneOf(identifierContinue, r) {
+ l.r.Move(n)
+ } else {
+ break
+ }
+ } else if !l.consumeUnicodeEscape() {
+ break
+ }
+ }
+ return true
+}
+
+func (l *Lexer) consumeNumericSeparator(f func() bool) bool {
+ if l.r.Peek(0) != '_' {
+ return false
+ }
+ l.r.Move(1)
+ if !f() {
+ l.r.Move(-1)
+ return false
+ }
+ return true
+}
+
+func (l *Lexer) consumeNumericToken() TokenType {
+ // assume to be on 0 1 2 3 4 5 6 7 8 9 .
+ first := l.r.Peek(0)
+ if first == '0' {
+ l.r.Move(1)
+ if l.r.Peek(0) == 'x' || l.r.Peek(0) == 'X' {
+ l.r.Move(1)
+ if l.consumeHexDigit() {
+ for l.consumeHexDigit() || l.consumeNumericSeparator(l.consumeHexDigit) {
+ }
+ return HexadecimalToken
+ }
+ l.err = parse.NewErrorLexer(l.r, "invalid hexadecimal number")
+ return ErrorToken
+ } else if l.r.Peek(0) == 'b' || l.r.Peek(0) == 'B' {
+ l.r.Move(1)
+ if l.consumeBinaryDigit() {
+ for l.consumeBinaryDigit() || l.consumeNumericSeparator(l.consumeBinaryDigit) {
+ }
+ return BinaryToken
+ }
+ l.err = parse.NewErrorLexer(l.r, "invalid binary number")
+ return ErrorToken
+ } else if l.r.Peek(0) == 'o' || l.r.Peek(0) == 'O' {
+ l.r.Move(1)
+ if l.consumeOctalDigit() {
+ for l.consumeOctalDigit() || l.consumeNumericSeparator(l.consumeOctalDigit) {
+ }
+ return OctalToken
+ }
+ l.err = parse.NewErrorLexer(l.r, "invalid octal number")
+ return ErrorToken
+ } else if l.r.Peek(0) == 'n' {
+ l.r.Move(1)
+ return BigIntToken
+ } else if '0' <= l.r.Peek(0) && l.r.Peek(0) <= '9' {
+ l.err = parse.NewErrorLexer(l.r, "legacy octal numbers are not supported")
+ return ErrorToken
+ }
+ } else if first != '.' {
+ for l.consumeDigit() || l.consumeNumericSeparator(l.consumeDigit) {
+ }
+ }
+ // we have parsed a 0 or an integer number
+ c := l.r.Peek(0)
+ if c == '.' {
+ l.r.Move(1)
+ if l.consumeDigit() {
+ for l.consumeDigit() || l.consumeNumericSeparator(l.consumeDigit) {
+ }
+ c = l.r.Peek(0)
+ } else if first == '.' {
+ // number starts with a dot and must be followed by digits
+ l.r.Move(-1)
+ return ErrorToken // may be dot or ellipsis
+ } else {
+ c = l.r.Peek(0)
+ }
+ } else if c == 'n' {
+ l.r.Move(1)
+ return BigIntToken
+ }
+ if c == 'e' || c == 'E' {
+ l.r.Move(1)
+ c = l.r.Peek(0)
+ if c == '+' || c == '-' {
+ l.r.Move(1)
+ }
+ if !l.consumeDigit() {
+ l.err = parse.NewErrorLexer(l.r, "invalid number")
+ return ErrorToken
+ }
+ for l.consumeDigit() || l.consumeNumericSeparator(l.consumeDigit) {
+ }
+ }
+ return DecimalToken
+}
+
+func (l *Lexer) consumeStringToken() TokenType {
+ // assume to be on ' or "
+ delim := l.r.Peek(0)
+ l.r.Move(1)
+ for {
+ c := l.r.Peek(0)
+ if c == delim {
+ l.r.Move(1)
+ break
+ } else if c == '\\' {
+ l.r.Move(1)
+ if !l.consumeLineTerminator() {
+ if c := l.r.Peek(0); c == delim || c == '\\' {
+ l.r.Move(1)
+ }
+ }
+ continue
+ } else if c == '\n' || c == '\r' || c == 0 && l.r.Err() != nil {
+ l.err = parse.NewErrorLexer(l.r, "unterminated string literal")
+ return ErrorToken
+ }
+ l.r.Move(1)
+ }
+ return StringToken
+}
+
+func (l *Lexer) consumeRegExpToken() bool {
+ // assume to be on /
+ l.r.Move(1)
+ inClass := false
+ for {
+ c := l.r.Peek(0)
+ if !inClass && c == '/' {
+ l.r.Move(1)
+ break
+ } else if c == '[' {
+ inClass = true
+ } else if c == ']' {
+ inClass = false
+ } else if c == '\\' {
+ l.r.Move(1)
+ if l.isLineTerminator() || l.r.Peek(0) == 0 && l.r.Err() != nil {
+ return false
+ }
+ } else if l.isLineTerminator() || c == 0 && l.r.Err() != nil {
+ return false
+ }
+ l.r.Move(1)
+ }
+ // flags
+ for {
+ c := l.r.Peek(0)
+ if identifierTable[c] {
+ l.r.Move(1)
+ } else if 0xC0 <= c {
+ if r, n := l.r.PeekRune(0); r == '\u200C' || r == '\u200D' || unicode.IsOneOf(identifierContinue, r) {
+ l.r.Move(n)
+ } else {
+ break
+ }
+ } else {
+ break
+ }
+ }
+ return true
+}
+
+func (l *Lexer) consumeTemplateToken() TokenType {
+ // assume to be on ` or } when already within template
+ continuation := l.r.Peek(0) == '}'
+ l.r.Move(1)
+ for {
+ c := l.r.Peek(0)
+ if c == '`' {
+ l.templateLevels = l.templateLevels[:len(l.templateLevels)-1]
+ l.r.Move(1)
+ if continuation {
+ return TemplateEndToken
+ }
+ return TemplateToken
+ } else if c == '$' && l.r.Peek(1) == '{' {
+ l.level++
+ l.r.Move(2)
+ if continuation {
+ return TemplateMiddleToken
+ }
+ return TemplateStartToken
+ } else if c == '\\' {
+ l.r.Move(1)
+ if c := l.r.Peek(0); c != 0 {
+ l.r.Move(1)
+ }
+ continue
+ } else if c == 0 && l.r.Err() != nil {
+ l.err = parse.NewErrorLexer(l.r, "unterminated template literal")
+ return ErrorToken
+ }
+ l.r.Move(1)
+ }
+}
+
+var identifierStartTable = [256]bool{
+ // ASCII
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, true, false, false, false, // $
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, true, true, true, true, true, true, true, // A, B, C, D, E, F, G
+ true, true, true, true, true, true, true, true, // H, I, J, K, L, M, N, O
+ true, true, true, true, true, true, true, true, // P, Q, R, S, T, U, V, W
+ true, true, true, false, false, false, false, true, // X, Y, Z, _
+
+ false, true, true, true, true, true, true, true, // a, b, c, d, e, f, g
+ true, true, true, true, true, true, true, true, // h, i, j, k, l, m, n, o
+ true, true, true, true, true, true, true, true, // p, q, r, s, t, u, v, w
+ true, true, true, false, false, false, false, false, // x, y, z
+
+ // non-ASCII
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+}
+
+var identifierTable = [256]bool{
+ // ASCII
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, true, false, false, false, // $
+ false, false, false, false, false, false, false, false,
+ true, true, true, true, true, true, true, true, // 0, 1, 2, 3, 4, 5, 6, 7
+ true, true, false, false, false, false, false, false, // 8, 9
+
+ false, true, true, true, true, true, true, true, // A, B, C, D, E, F, G
+ true, true, true, true, true, true, true, true, // H, I, J, K, L, M, N, O
+ true, true, true, true, true, true, true, true, // P, Q, R, S, T, U, V, W
+ true, true, true, false, false, false, false, true, // X, Y, Z, _
+
+ false, true, true, true, true, true, true, true, // a, b, c, d, e, f, g
+ true, true, true, true, true, true, true, true, // h, i, j, k, l, m, n, o
+ true, true, true, true, true, true, true, true, // p, q, r, s, t, u, v, w
+ true, true, true, false, false, false, false, false, // x, y, z
+
+ // non-ASCII
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/js/parse.go b/vendor/github.com/tdewolff/parse/v2/js/parse.go
new file mode 100644
index 0000000..3d06237
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/js/parse.go
@@ -0,0 +1,2292 @@
+package js
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+
+ "github.com/tdewolff/parse/v2"
+ "github.com/tdewolff/parse/v2/buffer"
+)
+
+type Options struct {
+ WhileToFor bool
+}
+
+// Parser is the state for the parser.
+type Parser struct {
+ l *Lexer
+ o Options
+ err error
+
+ data []byte
+ tt TokenType
+ prevLT bool
+ inFor bool
+ await, yield bool
+ assumeArrowFunc bool
+ allowDirectivePrologue bool
+
+ stmtLevel int
+ exprLevel int
+
+ scope *Scope
+}
+
+// Parse returns a JS AST tree of.
+func Parse(r *parse.Input, o Options) (*AST, error) {
+ ast := &AST{}
+ p := &Parser{
+ l: NewLexer(r),
+ o: o,
+ tt: WhitespaceToken, // trick so that next() works
+ await: true,
+ }
+
+ // process shebang
+ if r.Peek(0) == '#' && r.Peek(1) == '!' {
+ r.Move(2)
+ p.l.consumeSingleLineComment() // consume till end-of-line
+ ast.Comments = append(ast.Comments, r.Shift())
+ }
+
+ p.tt, p.data = p.l.Next()
+ for p.tt == CommentToken || p.tt == CommentLineTerminatorToken {
+ ast.Comments = append(ast.Comments, p.data)
+ p.tt, p.data = p.l.Next()
+ if p.tt == WhitespaceToken || p.tt == LineTerminatorToken {
+ p.tt, p.data = p.l.Next()
+ }
+ }
+ if p.tt == WhitespaceToken || p.tt == LineTerminatorToken {
+ p.next()
+ }
+ // prevLT may be wrong but that is not a problem
+ ast.BlockStmt = p.parseModule()
+
+ if p.err == nil {
+ p.err = p.l.Err()
+ } else {
+ offset := p.l.r.Offset() - len(p.data)
+ p.err = parse.NewError(buffer.NewReader(p.l.r.Bytes()), offset, p.err.Error())
+ }
+ if p.err == io.EOF {
+ p.err = nil
+ }
+ return ast, p.err
+}
+
+////////////////////////////////////////////////////////////////
+
+func (p *Parser) next() {
+ p.prevLT = false
+ p.tt, p.data = p.l.Next()
+ for p.tt == WhitespaceToken || p.tt == LineTerminatorToken || p.tt == CommentToken || p.tt == CommentLineTerminatorToken {
+ if p.tt == LineTerminatorToken || p.tt == CommentLineTerminatorToken {
+ p.prevLT = true
+ }
+ p.tt, p.data = p.l.Next()
+ }
+}
+
+func (p *Parser) failMessage(msg string, args ...interface{}) {
+ if p.err == nil {
+ p.err = fmt.Errorf(msg, args...)
+ p.tt = ErrorToken
+ }
+}
+
+func (p *Parser) fail(in string, expected ...TokenType) {
+ if p.err == nil {
+ msg := "unexpected"
+ if 0 < len(expected) {
+ msg = "expected"
+ for i, tt := range expected[:len(expected)-1] {
+ if 0 < i {
+ msg += ","
+ }
+ msg += " " + tt.String() + ""
+ }
+ if 2 < len(expected) {
+ msg += ", or"
+ } else if 1 < len(expected) {
+ msg += " or"
+ }
+ msg += " " + expected[len(expected)-1].String() + " instead of"
+ }
+
+ if p.tt == ErrorToken {
+ if p.l.Err() == io.EOF {
+ msg += " EOF"
+ } else if lexerErr, ok := p.l.Err().(*parse.Error); ok {
+ msg = lexerErr.Message
+ } else {
+ // does not happen
+ }
+ } else {
+ msg += " " + string(p.data) + ""
+ }
+ if in != "" {
+ msg += " in " + in
+ }
+
+ p.err = errors.New(msg)
+ p.tt = ErrorToken
+ }
+}
+
+func (p *Parser) consume(in string, tt TokenType) bool {
+ if p.tt != tt {
+ p.fail(in, tt)
+ return false
+ }
+ p.next()
+ return true
+}
+
+// TODO: refactor
+//type ScopeState struct {
+// scope *Scope
+// async bool
+// generator bool
+// assumeArrowFunc bool
+//}
+
+func (p *Parser) enterScope(scope *Scope, isFunc bool) *Scope {
+ // create a new scope object and add it to the parent
+ parent := p.scope
+ p.scope = scope
+ *scope = Scope{
+ Parent: parent,
+ }
+ if isFunc {
+ scope.Func = scope
+ } else if parent != nil {
+ scope.Func = parent.Func
+ }
+ return parent
+}
+
+func (p *Parser) exitScope(parent *Scope) {
+ p.scope.HoistUndeclared()
+ p.scope = parent
+}
+
+func (p *Parser) parseModule() (module BlockStmt) {
+ p.enterScope(&module.Scope, true)
+ p.allowDirectivePrologue = true
+ for {
+ switch p.tt {
+ case ErrorToken:
+ return
+ case ImportToken:
+ p.next()
+ if p.tt == OpenParenToken {
+ // could be an import call expression
+ left := &LiteralExpr{ImportToken, []byte("import")}
+ p.exprLevel++
+ suffix := p.parseExpressionSuffix(left, OpExpr, OpCall)
+ p.exprLevel--
+ module.List = append(module.List, &ExprStmt{suffix})
+ } else {
+ importStmt := p.parseImportStmt()
+ module.List = append(module.List, &importStmt)
+ }
+ case ExportToken:
+ exportStmt := p.parseExportStmt()
+ module.List = append(module.List, &exportStmt)
+ default:
+ module.List = append(module.List, p.parseStmt(true))
+ }
+ }
+}
+
+func (p *Parser) parseStmt(allowDeclaration bool) (stmt IStmt) {
+ p.stmtLevel++
+ if 1000 < p.stmtLevel {
+ p.failMessage("too many nested statements")
+ return nil
+ }
+
+ allowDirectivePrologue := p.allowDirectivePrologue
+ p.allowDirectivePrologue = false
+
+ switch tt := p.tt; tt {
+ case OpenBraceToken:
+ stmt = p.parseBlockStmt("block statement")
+ case ConstToken, VarToken:
+ if !allowDeclaration && tt == ConstToken {
+ p.fail("statement")
+ return
+ }
+ p.next()
+ varDecl := p.parseVarDecl(tt, true)
+ stmt = varDecl
+ if !p.prevLT && p.tt != SemicolonToken && p.tt != CloseBraceToken && p.tt != ErrorToken {
+ if tt == ConstToken {
+ p.fail("const declaration")
+ } else {
+ p.fail("var statement")
+ }
+ return
+ }
+ case LetToken:
+ let := p.data
+ p.next()
+ if allowDeclaration && (IsIdentifier(p.tt) || p.tt == YieldToken || p.tt == AwaitToken || p.tt == OpenBracketToken || p.tt == OpenBraceToken) {
+ stmt = p.parseVarDecl(tt, false)
+ if !p.prevLT && p.tt != SemicolonToken && p.tt != CloseBraceToken && p.tt != ErrorToken {
+ p.fail("let declaration")
+ return
+ }
+ } else {
+ // expression
+ stmt = &ExprStmt{p.parseIdentifierExpression(OpExpr, let)}
+ if !p.prevLT && p.tt != SemicolonToken && p.tt != CloseBraceToken && p.tt != ErrorToken {
+ p.fail("expression")
+ return
+ }
+ }
+ case IfToken:
+ p.next()
+ if !p.consume("if statement", OpenParenToken) {
+ return
+ }
+ cond := p.parseExpression(OpExpr)
+ if !p.consume("if statement", CloseParenToken) {
+ return
+ }
+ body := p.parseStmt(false)
+
+ var elseBody IStmt
+ if p.tt == ElseToken {
+ p.next()
+ elseBody = p.parseStmt(false)
+ }
+ stmt = &IfStmt{cond, body, elseBody}
+ case ContinueToken, BreakToken:
+ tt := p.tt
+ p.next()
+ var label []byte
+ if !p.prevLT && p.isIdentifierReference(p.tt) {
+ label = p.data
+ p.next()
+ }
+ stmt = &BranchStmt{tt, label}
+ case ReturnToken:
+ p.next()
+ var value IExpr
+ if !p.prevLT && p.tt != SemicolonToken && p.tt != CloseBraceToken && p.tt != ErrorToken {
+ value = p.parseExpression(OpExpr)
+ }
+ stmt = &ReturnStmt{value}
+ case WithToken:
+ p.next()
+ if !p.consume("with statement", OpenParenToken) {
+ return
+ }
+ cond := p.parseExpression(OpExpr)
+ if !p.consume("with statement", CloseParenToken) {
+ return
+ }
+
+ p.scope.Func.HasWith = true
+ stmt = &WithStmt{cond, p.parseStmt(false)}
+ case DoToken:
+ stmt = &DoWhileStmt{}
+ p.next()
+ body := p.parseStmt(false)
+ if !p.consume("do-while statement", WhileToken) {
+ return
+ }
+ if !p.consume("do-while statement", OpenParenToken) {
+ return
+ }
+ stmt = &DoWhileStmt{p.parseExpression(OpExpr), body}
+ if !p.consume("do-while statement", CloseParenToken) {
+ return
+ }
+ case WhileToken:
+ p.next()
+ if !p.consume("while statement", OpenParenToken) {
+ return
+ }
+ cond := p.parseExpression(OpExpr)
+ if !p.consume("while statement", CloseParenToken) {
+ return
+ }
+ body := p.parseStmt(false)
+ if p.o.WhileToFor {
+ varDecl := &VarDecl{TokenType: VarToken, Scope: p.scope, InFor: true}
+ p.scope.Func.VarDecls = append(p.scope.Func.VarDecls, varDecl)
+
+ block, ok := body.(*BlockStmt)
+ if !ok {
+ block = &BlockStmt{List: []IStmt{body}}
+ }
+ stmt = &ForStmt{varDecl, cond, nil, block}
+ } else {
+ stmt = &WhileStmt{cond, body}
+ }
+ case ForToken:
+ p.next()
+ await := p.await && p.tt == AwaitToken
+ if await {
+ p.next()
+ }
+ if !p.consume("for statement", OpenParenToken) {
+ return
+ }
+
+ body := &BlockStmt{}
+ parent := p.enterScope(&body.Scope, false)
+
+ var init IExpr
+ p.inFor = true
+ if p.tt == VarToken || p.tt == LetToken || p.tt == ConstToken {
+ tt := p.tt
+ p.next()
+ varDecl := p.parseVarDecl(tt, true)
+ if p.tt != SemicolonToken && (1 < len(varDecl.List) || varDecl.List[0].Default != nil) {
+ p.fail("for statement")
+ return
+ } else if p.tt == SemicolonToken && varDecl.List[0].Default == nil {
+ // all but the first item were already verified
+ if _, ok := varDecl.List[0].Binding.(*Var); !ok {
+ p.fail("for statement")
+ return
+ }
+ }
+ init = varDecl
+ } else if p.tt != SemicolonToken {
+ init = p.parseExpression(OpExpr)
+ }
+ p.inFor = false
+
+ if p.tt == SemicolonToken {
+ var cond, post IExpr
+ if await {
+ p.fail("for statement", OfToken)
+ return
+ }
+ p.next()
+ if p.tt != SemicolonToken {
+ cond = p.parseExpression(OpExpr)
+ }
+ if !p.consume("for statement", SemicolonToken) {
+ return
+ }
+ if p.tt != CloseParenToken {
+ post = p.parseExpression(OpExpr)
+ }
+ if !p.consume("for statement", CloseParenToken) {
+ return
+ }
+ p.scope.MarkForStmt()
+ if p.tt == OpenBraceToken {
+ body.List = p.parseStmtList("")
+ } else if p.tt != SemicolonToken {
+ body.List = []IStmt{p.parseStmt(false)}
+ }
+ if init == nil {
+ varDecl := &VarDecl{TokenType: VarToken, Scope: p.scope, InFor: true}
+ p.scope.Func.VarDecls = append(p.scope.Func.VarDecls, varDecl)
+ init = varDecl
+ } else if varDecl, ok := init.(*VarDecl); ok {
+ varDecl.InFor = true
+ }
+ stmt = &ForStmt{init, cond, post, body}
+ } else if p.tt == InToken {
+ if await {
+ p.fail("for statement", OfToken)
+ return
+ }
+ p.next()
+ value := p.parseExpression(OpExpr)
+ if !p.consume("for statement", CloseParenToken) {
+ return
+ }
+ p.scope.MarkForStmt()
+ if p.tt == OpenBraceToken {
+ body.List = p.parseStmtList("")
+ } else if p.tt != SemicolonToken {
+ body.List = []IStmt{p.parseStmt(false)}
+ }
+ if varDecl, ok := init.(*VarDecl); ok {
+ varDecl.InForInOf = true
+ }
+ stmt = &ForInStmt{init, value, body}
+ } else if p.tt == OfToken {
+ p.next()
+ value := p.parseExpression(OpAssign)
+ if !p.consume("for statement", CloseParenToken) {
+ return
+ }
+ p.scope.MarkForStmt()
+ if p.tt == OpenBraceToken {
+ body.List = p.parseStmtList("")
+ } else if p.tt != SemicolonToken {
+ body.List = []IStmt{p.parseStmt(false)}
+ }
+ if varDecl, ok := init.(*VarDecl); ok {
+ varDecl.InForInOf = true
+ }
+ stmt = &ForOfStmt{await, init, value, body}
+ } else {
+ p.fail("for statement", InToken, OfToken, SemicolonToken)
+ return
+ }
+ p.exitScope(parent)
+ case SwitchToken:
+ p.next()
+ if !p.consume("switch statement", OpenParenToken) {
+ return
+ }
+ init := p.parseExpression(OpExpr)
+ if !p.consume("switch statement", CloseParenToken) {
+ return
+ }
+
+ // case block
+ if !p.consume("switch statement", OpenBraceToken) {
+ return
+ }
+
+ switchStmt := &SwitchStmt{Init: init}
+ parent := p.enterScope(&switchStmt.Scope, false)
+ for {
+ if p.tt == ErrorToken {
+ p.fail("switch statement")
+ return
+ } else if p.tt == CloseBraceToken {
+ p.next()
+ break
+ }
+
+ clause := p.tt
+ var list IExpr
+ if p.tt == CaseToken {
+ p.next()
+ list = p.parseExpression(OpExpr)
+ } else if p.tt == DefaultToken {
+ p.next()
+ } else {
+ p.fail("switch statement", CaseToken, DefaultToken)
+ return
+ }
+ if !p.consume("switch statement", ColonToken) {
+ return
+ }
+
+ var stmts []IStmt
+ for p.tt != CaseToken && p.tt != DefaultToken && p.tt != CloseBraceToken && p.tt != ErrorToken {
+ stmts = append(stmts, p.parseStmt(true))
+ }
+ switchStmt.List = append(switchStmt.List, CaseClause{clause, list, stmts})
+ }
+ p.exitScope(parent)
+ stmt = switchStmt
+ case FunctionToken:
+ if !allowDeclaration {
+ p.fail("statement")
+ return
+ }
+ stmt = p.parseFuncDecl()
+ case AsyncToken: // async function
+ if !allowDeclaration {
+ p.fail("statement")
+ return
+ }
+ async := p.data
+ p.next()
+ if p.tt == FunctionToken && !p.prevLT {
+ stmt = p.parseAsyncFuncDecl()
+ } else {
+ // expression
+ stmt = &ExprStmt{p.parseAsyncExpression(OpExpr, async)}
+ if !p.prevLT && p.tt != SemicolonToken && p.tt != CloseBraceToken && p.tt != ErrorToken {
+ p.fail("expression")
+ return
+ }
+ }
+ case ClassToken:
+ if !allowDeclaration {
+ p.fail("statement")
+ return
+ }
+ stmt = p.parseClassDecl()
+ case ThrowToken:
+ p.next()
+ var value IExpr
+ if !p.prevLT {
+ value = p.parseExpression(OpExpr)
+ }
+ stmt = &ThrowStmt{value}
+ case TryToken:
+ p.next()
+ body := p.parseBlockStmt("try statement")
+ var binding IBinding
+ var catch, finally *BlockStmt
+ if p.tt == CatchToken {
+ p.next()
+ catch = &BlockStmt{}
+ parent := p.enterScope(&catch.Scope, false)
+ if p.tt == OpenParenToken {
+ p.next()
+ binding = p.parseBinding(CatchDecl) // local to block scope of catch
+ if !p.consume("try-catch statement", CloseParenToken) {
+ return
+ }
+ }
+ catch.List = p.parseStmtList("try-catch statement")
+ p.exitScope(parent)
+ } else if p.tt != FinallyToken {
+ p.fail("try statement", CatchToken, FinallyToken)
+ return
+ }
+ if p.tt == FinallyToken {
+ p.next()
+ finally = p.parseBlockStmt("try-finally statement")
+ }
+ stmt = &TryStmt{body, binding, catch, finally}
+ case DebuggerToken:
+ p.next()
+ stmt = &DebuggerStmt{}
+ case SemicolonToken, ErrorToken:
+ stmt = &EmptyStmt{}
+ default:
+ if p.isIdentifierReference(p.tt) {
+ // labelled statement or expression
+ label := p.data
+ p.next()
+ if p.tt == ColonToken {
+ p.next()
+ stmt = &LabelledStmt{label, p.parseStmt(true)} // allows illegal async function, generator function, let, const, or class declarations
+ } else {
+ // expression
+ stmt = &ExprStmt{p.parseIdentifierExpression(OpExpr, label)}
+ if !p.prevLT && p.tt != SemicolonToken && p.tt != CloseBraceToken && p.tt != ErrorToken {
+ p.fail("expression")
+ return
+ }
+ }
+ } else {
+ // expression
+ stmt = &ExprStmt{p.parseExpression(OpExpr)}
+ if !p.prevLT && p.tt != SemicolonToken && p.tt != CloseBraceToken && p.tt != ErrorToken {
+ p.fail("expression")
+ return
+ } else if lit, ok := stmt.(*ExprStmt).Value.(*LiteralExpr); ok && allowDirectivePrologue && lit.TokenType == StringToken && len(lit.Data) == 12 && bytes.Equal(lit.Data[1:11], []byte("use strict")) {
+ stmt = &DirectivePrologueStmt{lit.Data}
+ p.allowDirectivePrologue = true
+ }
+ }
+ }
+ if p.tt == SemicolonToken {
+ p.next()
+ }
+ p.stmtLevel--
+ return
+}
+
+func (p *Parser) parseStmtList(in string) (list []IStmt) {
+ if !p.consume(in, OpenBraceToken) {
+ return
+ }
+ for {
+ if p.tt == ErrorToken {
+ p.fail("")
+ return
+ } else if p.tt == CloseBraceToken {
+ p.next()
+ break
+ }
+ list = append(list, p.parseStmt(true))
+ }
+ return
+}
+
+func (p *Parser) parseBlockStmt(in string) (blockStmt *BlockStmt) {
+ blockStmt = &BlockStmt{}
+ parent := p.enterScope(&blockStmt.Scope, false)
+ blockStmt.List = p.parseStmtList(in)
+ p.exitScope(parent)
+ return
+}
+
+func (p *Parser) parseImportStmt() (importStmt ImportStmt) {
+ // assume we're passed import
+ if p.tt == StringToken {
+ importStmt.Module = p.data
+ p.next()
+ } else {
+ if IsIdentifier(p.tt) || p.tt == YieldToken {
+ importStmt.Default = p.data
+ p.next()
+ if p.tt == CommaToken {
+ p.next()
+ }
+ }
+ if p.tt == MulToken {
+ star := p.data
+ p.next()
+ if !p.consume("import statement", AsToken) {
+ return
+ }
+ if !IsIdentifier(p.tt) && p.tt != YieldToken {
+ p.fail("import statement", IdentifierToken)
+ return
+ }
+ importStmt.List = []Alias{Alias{star, p.data}}
+ p.next()
+ } else if p.tt == OpenBraceToken {
+ p.next()
+ for IsIdentifierName(p.tt) || p.tt == StringToken {
+ tt := p.tt
+ var name, binding []byte = nil, p.data
+ p.next()
+ if p.tt == AsToken {
+ p.next()
+ if !IsIdentifier(p.tt) && p.tt != YieldToken {
+ p.fail("import statement", IdentifierToken)
+ return
+ }
+ name = binding
+ binding = p.data
+ p.next()
+ } else if !IsIdentifier(tt) && tt != YieldToken || tt == StringToken {
+ p.fail("import statement", IdentifierToken, StringToken)
+ return
+ }
+ importStmt.List = append(importStmt.List, Alias{name, binding})
+ if p.tt == CommaToken {
+ p.next()
+ if p.tt == CloseBraceToken {
+ importStmt.List = append(importStmt.List, Alias{})
+ break
+ }
+ }
+ }
+ if !p.consume("import statement", CloseBraceToken) {
+ return
+ }
+ }
+ if importStmt.Default == nil && len(importStmt.List) == 0 {
+ p.fail("import statement", StringToken, IdentifierToken, MulToken, OpenBraceToken)
+ return
+ }
+
+ if !p.consume("import statement", FromToken) {
+ return
+ }
+ if p.tt != StringToken {
+ p.fail("import statement", StringToken)
+ return
+ }
+ importStmt.Module = p.data
+ p.next()
+ }
+ if p.tt == SemicolonToken {
+ p.next()
+ }
+ return
+}
+
+func (p *Parser) parseExportStmt() (exportStmt ExportStmt) {
+ // assume we're at export
+ p.next()
+ if p.tt == MulToken || p.tt == OpenBraceToken {
+ if p.tt == MulToken {
+ star := p.data
+ p.next()
+ if p.tt == AsToken {
+ p.next()
+ if !IsIdentifierName(p.tt) && p.tt != StringToken {
+ p.fail("export statement", IdentifierToken, StringToken)
+ return
+ }
+ exportStmt.List = []Alias{Alias{star, p.data}}
+ p.next()
+ } else {
+ exportStmt.List = []Alias{Alias{nil, star}}
+ }
+ if p.tt != FromToken {
+ p.fail("export statement", FromToken)
+ return
+ }
+ } else {
+ p.next()
+ for IsIdentifierName(p.tt) || p.tt == StringToken {
+ var name, binding []byte = nil, p.data
+ p.next()
+ if p.tt == AsToken {
+ p.next()
+ if !IsIdentifierName(p.tt) && p.tt != StringToken {
+ p.fail("export statement", IdentifierToken, StringToken)
+ return
+ }
+ name = binding
+ binding = p.data
+ p.next()
+ }
+ exportStmt.List = append(exportStmt.List, Alias{name, binding})
+ if p.tt == CommaToken {
+ p.next()
+ if p.tt == CloseBraceToken {
+ exportStmt.List = append(exportStmt.List, Alias{})
+ break
+ }
+ }
+ }
+ if !p.consume("export statement", CloseBraceToken) {
+ return
+ }
+ }
+ if p.tt == FromToken {
+ p.next()
+ if p.tt != StringToken {
+ p.fail("export statement", StringToken)
+ return
+ }
+ exportStmt.Module = p.data
+ p.next()
+ }
+ } else if p.tt == VarToken || p.tt == ConstToken || p.tt == LetToken {
+ tt := p.tt
+ p.next()
+ exportStmt.Decl = p.parseVarDecl(tt, false)
+ } else if p.tt == FunctionToken {
+ exportStmt.Decl = p.parseFuncDecl()
+ } else if p.tt == AsyncToken { // async function
+ p.next()
+ if p.tt != FunctionToken || p.prevLT {
+ p.fail("export statement", FunctionToken)
+ return
+ }
+ exportStmt.Decl = p.parseAsyncFuncDecl()
+ } else if p.tt == ClassToken {
+ exportStmt.Decl = p.parseClassDecl()
+ } else if p.tt == DefaultToken {
+ exportStmt.Default = true
+ p.next()
+ if p.tt == FunctionToken {
+ exportStmt.Decl = p.parseFuncDeclDefault()
+ } else if p.tt == AsyncToken { // async function or async arrow function
+ async := p.data
+ p.next()
+ if p.tt == FunctionToken && !p.prevLT {
+ exportStmt.Decl = p.parseAsyncFuncDeclDefault()
+ } else {
+ // expression
+ exportStmt.Decl = p.parseAsyncExpression(OpExpr, async)
+ }
+ } else if p.tt == ClassToken {
+ exportStmt.Decl = p.parseClassDeclDefault()
+ } else {
+ exportStmt.Decl = p.parseExpression(OpAssign)
+ }
+ } else {
+ p.fail("export statement", MulToken, OpenBraceToken, VarToken, LetToken, ConstToken, FunctionToken, AsyncToken, ClassToken, DefaultToken)
+ return
+ }
+ if p.tt == SemicolonToken {
+ p.next()
+ }
+ return
+}
+
+func (p *Parser) parseVarDecl(tt TokenType, canBeHoisted bool) (varDecl *VarDecl) {
+ // assume we're past var, let or const
+ varDecl = &VarDecl{
+ TokenType: tt,
+ Scope: p.scope,
+ }
+ declType := LexicalDecl
+ if tt == VarToken {
+ declType = VariableDecl
+ if canBeHoisted {
+ p.scope.Func.VarDecls = append(p.scope.Func.VarDecls, varDecl)
+ }
+ }
+ for {
+ // binding element, var declaration in for-in or for-of can never have a default
+ var bindingElement BindingElement
+ parentInFor := p.inFor
+ p.inFor = false
+ bindingElement.Binding = p.parseBinding(declType)
+ p.inFor = parentInFor
+ if p.tt == EqToken {
+ p.next()
+ bindingElement.Default = p.parseExpression(OpAssign)
+ } else if _, ok := bindingElement.Binding.(*Var); !ok && (!p.inFor || 0 < len(varDecl.List)) {
+ p.fail("var statement", EqToken)
+ return
+ } else if tt == ConstToken && (!p.inFor || p.inFor && p.tt != OfToken && p.tt != InToken) {
+ p.fail("const statement", EqToken)
+ }
+
+ varDecl.List = append(varDecl.List, bindingElement)
+ if p.tt == CommaToken {
+ p.next()
+ } else {
+ break
+ }
+ }
+ return
+}
+
+func (p *Parser) parseFuncParams(in string) (params Params) {
+ if !p.consume(in, OpenParenToken) {
+ return
+ }
+
+ for p.tt != CloseParenToken && p.tt != ErrorToken {
+ if p.tt == EllipsisToken {
+ // binding rest element
+ p.next()
+ params.Rest = p.parseBinding(ArgumentDecl)
+ p.consume(in, CloseParenToken)
+ return
+ }
+ params.List = append(params.List, p.parseBindingElement(ArgumentDecl))
+ if p.tt != CommaToken {
+ break
+ }
+ p.next()
+ }
+ if p.tt != CloseParenToken {
+ p.fail(in)
+ return
+ }
+ p.next()
+
+ // mark undeclared vars as arguments in `function f(a=b){var b}` where the b's are different vars
+ p.scope.MarkFuncArgs()
+ return
+}
+
+func (p *Parser) parseFuncDecl() (funcDecl *FuncDecl) {
+ return p.parseAnyFunc(false, false, false)
+}
+
+func (p *Parser) parseFuncDeclDefault() (funcDecl *FuncDecl) {
+ return p.parseAnyFunc(false, true, false)
+}
+
+func (p *Parser) parseAsyncFuncDecl() (funcDecl *FuncDecl) {
+ return p.parseAnyFunc(true, false, false)
+}
+
+func (p *Parser) parseAsyncFuncDeclDefault() (funcDecl *FuncDecl) {
+ return p.parseAnyFunc(true, true, false)
+}
+
+func (p *Parser) parseFuncExpr() (funcDecl *FuncDecl) {
+ return p.parseAnyFunc(false, false, true)
+}
+
+func (p *Parser) parseAsyncFuncExpr() (funcDecl *FuncDecl) {
+ return p.parseAnyFunc(true, false, true)
+}
+
+func (p *Parser) parseAnyFunc(async, exportDefault, expr bool) (funcDecl *FuncDecl) {
+ // assume we're at function
+ p.next()
+ funcDecl = &FuncDecl{}
+ funcDecl.Async = async
+ funcDecl.Generator = p.tt == MulToken
+ if funcDecl.Generator {
+ p.next()
+ }
+ var ok bool
+ var name []byte
+ if expr && (IsIdentifier(p.tt) || p.tt == YieldToken || p.tt == AwaitToken) || !expr && p.isIdentifierReference(p.tt) {
+ name = p.data
+ if !expr {
+ funcDecl.Name, ok = p.scope.Declare(FunctionDecl, p.data)
+ if !ok {
+ p.failMessage("identifier %s has already been declared", string(p.data))
+ return
+ }
+ }
+ p.next()
+ } else if !expr && !exportDefault {
+ p.fail("function declaration", IdentifierToken)
+ return
+ } else if p.tt != OpenParenToken {
+ p.fail("function declaration", IdentifierToken, OpenParenToken)
+ return
+ }
+ parent := p.enterScope(&funcDecl.Body.Scope, true)
+ parentAwait, parentYield := p.await, p.yield
+ p.await, p.yield = funcDecl.Async, funcDecl.Generator
+
+ if expr && name != nil {
+ funcDecl.Name, _ = p.scope.Declare(ExprDecl, name) // cannot fail
+ }
+ funcDecl.Params = p.parseFuncParams("function declaration")
+ p.allowDirectivePrologue = true
+ funcDecl.Body.List = p.parseStmtList("function declaration")
+
+ p.await, p.yield = parentAwait, parentYield
+ p.exitScope(parent)
+ return
+}
+
+func (p *Parser) parseClassDecl() (classDecl *ClassDecl) {
+ return p.parseAnyClass(false, false)
+}
+
+func (p *Parser) parseClassDeclDefault() (classDecl *ClassDecl) {
+ return p.parseAnyClass(true, false)
+}
+
+func (p *Parser) parseClassExpr() (classDecl *ClassDecl) {
+ return p.parseAnyClass(false, true)
+}
+
+func (p *Parser) parseAnyClass(exportDefault, expr bool) (classDecl *ClassDecl) {
+ // assume we're at class
+ p.next()
+ classDecl = &ClassDecl{}
+ if IsIdentifier(p.tt) || p.tt == YieldToken || p.tt == AwaitToken {
+ if !expr {
+ var ok bool
+ classDecl.Name, ok = p.scope.Declare(LexicalDecl, p.data)
+ if !ok {
+ p.failMessage("identifier %s has already been declared", string(p.data))
+ return
+ }
+ } else {
+ //classDecl.Name, ok = p.scope.Declare(ExprDecl, p.data) // classes do not register vars
+ classDecl.Name = &Var{p.data, nil, 1, ExprDecl}
+ }
+ p.next()
+ } else if !expr && !exportDefault {
+ p.fail("class declaration", IdentifierToken)
+ return
+ }
+ if p.tt == ExtendsToken {
+ p.next()
+ classDecl.Extends = p.parseExpression(OpLHS)
+ }
+
+ if !p.consume("class declaration", OpenBraceToken) {
+ return
+ }
+ for {
+ if p.tt == ErrorToken {
+ p.fail("class declaration")
+ return
+ } else if p.tt == SemicolonToken {
+ p.next()
+ continue
+ } else if p.tt == CloseBraceToken {
+ p.next()
+ break
+ }
+
+ classDecl.List = append(classDecl.List, p.parseClassElement())
+ }
+ return
+}
+
+func (p *Parser) parseClassElement() ClassElement {
+ method := &MethodDecl{}
+ var data []byte // either static, async, get, or set
+ if p.tt == StaticToken {
+ method.Static = true
+ data = p.data
+ p.next()
+ if p.tt == OpenBraceToken {
+ return ClassElement{StaticBlock: p.parseBlockStmt("class static block")}
+ }
+ }
+ if p.tt == MulToken {
+ method.Generator = true
+ p.next()
+ } else if p.tt == AsyncToken {
+ data = p.data
+ p.next()
+ if !p.prevLT {
+ method.Async = true
+ if p.tt == MulToken {
+ method.Generator = true
+ data = nil
+ p.next()
+ }
+ }
+ } else if p.tt == GetToken {
+ method.Get = true
+ data = p.data
+ p.next()
+ } else if p.tt == SetToken {
+ method.Set = true
+ data = p.data
+ p.next()
+ }
+
+ isField := false
+ if data != nil && p.tt == OpenParenToken {
+ // (static) method name is: static, async, get, or set
+ method.Name.Literal = LiteralExpr{IdentifierToken, data}
+ if method.Async || method.Get || method.Set {
+ method.Async = false
+ method.Get = false
+ method.Set = false
+ } else {
+ method.Static = false
+ }
+ } else if data != nil && (p.tt == EqToken || p.tt == SemicolonToken || p.tt == CloseBraceToken) {
+ // (static) field name is: static, async, get, or set
+ method.Name.Literal = LiteralExpr{IdentifierToken, data}
+ if !method.Async && !method.Get && !method.Set {
+ method.Static = false
+ }
+ isField = true
+ } else {
+ if p.tt == PrivateIdentifierToken {
+ method.Name.Literal = LiteralExpr{p.tt, p.data}
+ p.next()
+ } else {
+ method.Name = p.parsePropertyName("method or field definition")
+ }
+ if (data == nil || method.Static) && p.tt != OpenParenToken {
+ isField = true
+ }
+ }
+
+ if isField {
+ var init IExpr
+ if p.tt == EqToken {
+ p.next()
+ init = p.parseExpression(OpAssign)
+ }
+ return ClassElement{Field: Field{Static: method.Static, Name: method.Name, Init: init}}
+ }
+
+ parent := p.enterScope(&method.Body.Scope, true)
+ parentAwait, parentYield := p.await, p.yield
+ p.await, p.yield = method.Async, method.Generator
+
+ method.Params = p.parseFuncParams("method definition")
+ p.allowDirectivePrologue = true
+ method.Body.List = p.parseStmtList("method definition")
+
+ p.await, p.yield = parentAwait, parentYield
+ p.exitScope(parent)
+ return ClassElement{Method: method}
+}
+
+func (p *Parser) parsePropertyName(in string) (propertyName PropertyName) {
+ if IsIdentifierName(p.tt) {
+ propertyName.Literal = LiteralExpr{IdentifierToken, p.data}
+ p.next()
+ } else if p.tt == StringToken {
+ // reinterpret string as identifier or number if we can, except for empty strings
+ if isIdent := AsIdentifierName(p.data[1 : len(p.data)-1]); isIdent {
+ propertyName.Literal = LiteralExpr{IdentifierToken, p.data[1 : len(p.data)-1]}
+ } else if isNum := AsDecimalLiteral(p.data[1 : len(p.data)-1]); isNum {
+ propertyName.Literal = LiteralExpr{DecimalToken, p.data[1 : len(p.data)-1]}
+ } else {
+ propertyName.Literal = LiteralExpr{p.tt, p.data}
+ }
+ p.next()
+ } else if IsNumeric(p.tt) {
+ propertyName.Literal = LiteralExpr{p.tt, p.data}
+ p.next()
+ } else if p.tt == OpenBracketToken {
+ p.next()
+ propertyName.Computed = p.parseExpression(OpAssign)
+ if !p.consume(in, CloseBracketToken) {
+ return
+ }
+ } else {
+ p.fail(in, IdentifierToken, StringToken, NumericToken, OpenBracketToken)
+ return
+ }
+ return
+}
+
+func (p *Parser) parseBindingElement(decl DeclType) (bindingElement BindingElement) {
+ // binding element
+ bindingElement.Binding = p.parseBinding(decl)
+ if p.tt == EqToken {
+ p.next()
+ bindingElement.Default = p.parseExpression(OpAssign)
+ }
+ return
+}
+
+func (p *Parser) parseBinding(decl DeclType) (binding IBinding) {
+ // binding identifier or binding pattern
+ if p.isIdentifierReference(p.tt) {
+ var ok bool
+ binding, ok = p.scope.Declare(decl, p.data)
+ if !ok {
+ p.failMessage("identifier %s has already been declared", string(p.data))
+ return
+ }
+ p.next()
+ } else if p.tt == OpenBracketToken {
+ p.next()
+ array := BindingArray{}
+ if p.tt == CommaToken {
+ array.List = append(array.List, BindingElement{})
+ }
+ last := 0
+ for p.tt != CloseBracketToken {
+ // elision
+ for p.tt == CommaToken {
+ p.next()
+ if p.tt == CommaToken {
+ array.List = append(array.List, BindingElement{})
+ }
+ }
+ // binding rest element
+ if p.tt == EllipsisToken {
+ p.next()
+ array.Rest = p.parseBinding(decl)
+ if p.tt != CloseBracketToken {
+ p.fail("array binding pattern", CloseBracketToken)
+ return
+ }
+ break
+ } else if p.tt == CloseBracketToken {
+ array.List = array.List[:last]
+ break
+ }
+
+ array.List = append(array.List, p.parseBindingElement(decl))
+ last = len(array.List)
+
+ if p.tt != CommaToken && p.tt != CloseBracketToken {
+ p.fail("array binding pattern", CommaToken, CloseBracketToken)
+ return
+ }
+ }
+ p.next() // always CloseBracketToken
+ binding = &array
+ } else if p.tt == OpenBraceToken {
+ p.next()
+ object := BindingObject{}
+ for p.tt != CloseBraceToken {
+ // binding rest property
+ if p.tt == EllipsisToken {
+ p.next()
+ if !p.isIdentifierReference(p.tt) {
+ p.fail("object binding pattern", IdentifierToken)
+ return
+ }
+ var ok bool
+ object.Rest, ok = p.scope.Declare(decl, p.data)
+ if !ok {
+ p.failMessage("identifier %s has already been declared", string(p.data))
+ return
+ }
+ p.next()
+ if p.tt != CloseBraceToken {
+ p.fail("object binding pattern", CloseBraceToken)
+ return
+ }
+ break
+ }
+
+ item := BindingObjectItem{}
+ if p.isIdentifierReference(p.tt) {
+ name := p.data
+ item.Key = &PropertyName{LiteralExpr{IdentifierToken, p.data}, nil}
+ p.next()
+ if p.tt == ColonToken {
+ // property name + : + binding element
+ p.next()
+ item.Value = p.parseBindingElement(decl)
+ } else {
+ // single name binding
+ var ok bool
+ item.Key.Literal.Data = parse.Copy(item.Key.Literal.Data) // copy so that renaming doesn't rename the key
+ item.Value.Binding, ok = p.scope.Declare(decl, name)
+ if !ok {
+ p.failMessage("identifier %s has already been declared", string(name))
+ return
+ }
+ if p.tt == EqToken {
+ p.next()
+ item.Value.Default = p.parseExpression(OpAssign)
+ }
+ }
+ } else {
+ propertyName := p.parsePropertyName("object binding pattern")
+ item.Key = &propertyName
+ if !p.consume("object binding pattern", ColonToken) {
+ return
+ }
+ item.Value = p.parseBindingElement(decl)
+ }
+ object.List = append(object.List, item)
+
+ if p.tt == CommaToken {
+ p.next()
+ } else if p.tt != CloseBraceToken {
+ p.fail("object binding pattern", CommaToken, CloseBraceToken)
+ return
+ }
+ }
+ p.next() // always CloseBracketToken
+ binding = &object
+ } else {
+ p.fail("binding")
+ return
+ }
+ return
+}
+
+func (p *Parser) parseArrayLiteral() (array ArrayExpr) {
+ // assume we're on [
+ p.next()
+ prevComma := true
+ for {
+ if p.tt == ErrorToken {
+ p.fail("expression")
+ return
+ } else if p.tt == CloseBracketToken {
+ p.next()
+ break
+ } else if p.tt == CommaToken {
+ if prevComma {
+ array.List = append(array.List, Element{})
+ }
+ prevComma = true
+ p.next()
+ } else {
+ spread := p.tt == EllipsisToken
+ if spread {
+ p.next()
+ }
+ array.List = append(array.List, Element{p.parseAssignmentExpression(), spread})
+ prevComma = false
+ if spread && p.tt != CloseBracketToken {
+ p.assumeArrowFunc = false
+ }
+ }
+ }
+ return
+}
+
+func (p *Parser) parseObjectLiteral() (object ObjectExpr) {
+ // assume we're on {
+ p.next()
+ for {
+ if p.tt == ErrorToken {
+ p.fail("object literal", CloseBraceToken)
+ return
+ } else if p.tt == CloseBraceToken {
+ p.next()
+ break
+ }
+
+ property := Property{}
+ if p.tt == EllipsisToken {
+ p.next()
+ property.Spread = true
+ property.Value = p.parseAssignmentExpression()
+ if _, isIdent := property.Value.(*Var); !isIdent || p.tt != CloseBraceToken {
+ p.assumeArrowFunc = false
+ }
+ } else {
+ // try to parse as MethodDefinition, otherwise fall back to PropertyName:AssignExpr or IdentifierReference
+ var data []byte
+ method := MethodDecl{}
+ if p.tt == MulToken {
+ p.next()
+ method.Generator = true
+ } else if p.tt == AsyncToken {
+ data = p.data
+ p.next()
+ if !p.prevLT {
+ method.Async = true
+ if p.tt == MulToken {
+ p.next()
+ method.Generator = true
+ data = nil
+ }
+ } else {
+ method.Name.Literal = LiteralExpr{IdentifierToken, data}
+ data = nil
+ }
+ } else if p.tt == GetToken {
+ data = p.data
+ p.next()
+ method.Get = true
+ } else if p.tt == SetToken {
+ data = p.data
+ p.next()
+ method.Set = true
+ }
+
+ // PropertyName
+ if data != nil && !method.Generator && (p.tt == EqToken || p.tt == CommaToken || p.tt == CloseBraceToken || p.tt == ColonToken || p.tt == OpenParenToken) {
+ method.Name.Literal = LiteralExpr{IdentifierToken, data}
+ method.Async = false
+ method.Get = false
+ method.Set = false
+ } else if !method.Name.IsSet() { // did not parse async [LT]
+ method.Name = p.parsePropertyName("object literal")
+ if !method.Name.IsSet() {
+ return
+ }
+ }
+
+ if p.tt == OpenParenToken {
+ // MethodDefinition
+ parent := p.enterScope(&method.Body.Scope, true)
+ parentAwait, parentYield := p.await, p.yield
+ p.await, p.yield = method.Async, method.Generator
+
+ method.Params = p.parseFuncParams("method definition")
+ method.Body.List = p.parseStmtList("method definition")
+
+ p.await, p.yield = parentAwait, parentYield
+ p.exitScope(parent)
+ property.Value = &method
+ p.assumeArrowFunc = false
+ } else if p.tt == ColonToken {
+ // PropertyName : AssignmentExpression
+ p.next()
+ property.Name = &method.Name
+ property.Value = p.parseAssignmentExpression()
+ } else if method.Name.IsComputed() || !p.isIdentifierReference(method.Name.Literal.TokenType) {
+ p.fail("object literal", ColonToken, OpenParenToken)
+ return
+ } else {
+ // IdentifierReference (= AssignmentExpression)?
+ name := method.Name.Literal.Data
+ method.Name.Literal.Data = parse.Copy(method.Name.Literal.Data) // copy so that renaming doesn't rename the key
+ property.Name = &method.Name // set key explicitly so after renaming the original is still known
+ if p.assumeArrowFunc {
+ var ok bool
+ property.Value, ok = p.scope.Declare(ArgumentDecl, name)
+ if !ok {
+ property.Value = p.scope.Use(name)
+ p.assumeArrowFunc = false
+ }
+ } else {
+ property.Value = p.scope.Use(name)
+ }
+ if p.tt == EqToken {
+ p.next()
+ parentAssumeArrowFunc := p.assumeArrowFunc
+ p.assumeArrowFunc = false
+ property.Init = p.parseExpression(OpAssign)
+ p.assumeArrowFunc = parentAssumeArrowFunc
+ }
+ }
+ }
+ object.List = append(object.List, property)
+ if p.tt == CommaToken {
+ p.next()
+ } else if p.tt != CloseBraceToken {
+ p.fail("object literal")
+ return
+ }
+ }
+ return
+}
+
+func (p *Parser) parseTemplateLiteral(precLeft OpPrec) (template TemplateExpr) {
+ // assume we're on 'Template' or 'TemplateStart'
+ template.Prec = OpMember
+ if precLeft < OpMember {
+ template.Prec = OpCall
+ }
+ for p.tt == TemplateStartToken || p.tt == TemplateMiddleToken {
+ tpl := p.data
+ p.next()
+ template.List = append(template.List, TemplatePart{tpl, p.parseExpression(OpExpr)})
+ }
+ if p.tt != TemplateToken && p.tt != TemplateEndToken {
+ p.fail("template literal", TemplateToken)
+ return
+ }
+ template.Tail = p.data
+ p.next() // TemplateEndToken
+ return
+}
+
+func (p *Parser) parseArguments() (args Args) {
+ // assume we're on (
+ p.next()
+ args.List = make([]Arg, 0, 4)
+ for {
+ rest := p.tt == EllipsisToken
+ if rest {
+ p.next()
+ }
+
+ if p.tt == CloseParenToken || p.tt == ErrorToken {
+ break
+ }
+ args.List = append(args.List, Arg{
+ Value: p.parseExpression(OpAssign),
+ Rest: rest,
+ })
+ if p.tt == CommaToken {
+ p.next()
+ }
+ }
+ p.consume("arguments", CloseParenToken)
+ return
+}
+
+func (p *Parser) parseAsyncArrowFunc() (arrowFunc *ArrowFunc) {
+ // expect we're at Identifier or Yield or (
+ arrowFunc = &ArrowFunc{}
+ parent := p.enterScope(&arrowFunc.Body.Scope, true)
+ parentAwait, parentYield := p.await, p.yield
+ p.await, p.yield = true, false
+
+ if IsIdentifier(p.tt) || !p.yield && p.tt == YieldToken {
+ ref, _ := p.scope.Declare(ArgumentDecl, p.data) // cannot fail
+ p.next()
+ arrowFunc.Params.List = []BindingElement{{Binding: ref}}
+ } else {
+ arrowFunc.Params = p.parseFuncParams("arrow function")
+
+ // could be CallExpression of: async(params)
+ if p.tt != ArrowToken {
+ // TODO?
+ }
+ }
+
+ p.await, p.yield = true, parentYield
+ arrowFunc.Async = true
+ arrowFunc.Body.List = p.parseArrowFuncBody()
+
+ p.await, p.yield = parentAwait, parentYield
+ p.exitScope(parent)
+ return
+}
+
+func (p *Parser) parseIdentifierArrowFunc(v *Var) (arrowFunc *ArrowFunc) {
+ // expect we're at =>
+ arrowFunc = &ArrowFunc{}
+ parent := p.enterScope(&arrowFunc.Body.Scope, true)
+ parentAwait, parentYield := p.await, p.yield
+
+ if 1 < v.Uses {
+ v.Uses--
+ v, _ = p.scope.Declare(ArgumentDecl, parse.Copy(v.Data)) // cannot fail
+ } else {
+ // if v.Uses==1 it must be undeclared and be the last added
+ p.scope.Parent.Undeclared = p.scope.Parent.Undeclared[:len(p.scope.Parent.Undeclared)-1]
+ v.Decl = ArgumentDecl
+ p.scope.Declared = append(p.scope.Declared, v)
+ }
+
+ p.await = false
+ arrowFunc.Params.List = []BindingElement{{v, nil}}
+ arrowFunc.Body.List = p.parseArrowFuncBody()
+
+ p.await, p.yield = parentAwait, parentYield
+ p.exitScope(parent)
+ return
+}
+
+func (p *Parser) parseArrowFuncBody() (list []IStmt) {
+ // expect we're at arrow
+ if p.tt != ArrowToken {
+ p.fail("arrow function", ArrowToken)
+ return
+ } else if p.prevLT {
+ p.fail("expression")
+ return
+ }
+ p.next()
+
+ // mark undeclared vars as arguments in `function f(a=b){var b}` where the b's are different vars
+ p.scope.MarkFuncArgs()
+
+ if p.tt == OpenBraceToken {
+ parentInFor := p.inFor
+ p.inFor = false
+ p.yield = false
+ p.allowDirectivePrologue = true
+ list = p.parseStmtList("arrow function")
+ p.inFor = parentInFor
+ } else {
+ list = []IStmt{&ReturnStmt{p.parseExpression(OpAssign)}}
+ }
+ return
+}
+
+func (p *Parser) parseIdentifierExpression(prec OpPrec, ident []byte) IExpr {
+ var left IExpr
+ left = p.scope.Use(ident)
+ return p.parseExpressionSuffix(left, prec, OpPrimary)
+}
+
+func (p *Parser) parseAsyncExpression(prec OpPrec, async []byte) IExpr {
+ // assume we're at a token after async
+ var left IExpr
+ precLeft := OpPrimary
+ if !p.prevLT && p.tt == FunctionToken {
+ // primary expression
+ left = p.parseAsyncFuncExpr()
+ } else if !p.prevLT && prec <= OpAssign && (p.tt == OpenParenToken || IsIdentifier(p.tt) || !p.yield && p.tt == YieldToken || p.tt == AwaitToken) {
+ // async arrow function expression
+ if p.tt == AwaitToken {
+ p.fail("arrow function")
+ return nil
+ } else if p.tt == OpenParenToken {
+ return p.parseParenthesizedExpressionOrArrowFunc(prec, async)
+ }
+ left = p.parseAsyncArrowFunc()
+ precLeft = OpAssign
+ } else {
+ left = p.scope.Use(async)
+ }
+ return p.parseExpressionSuffix(left, prec, precLeft)
+}
+
+// parseExpression parses an expression that has a precedence of prec or higher.
+func (p *Parser) parseExpression(prec OpPrec) IExpr {
+ p.exprLevel++
+ if 1000 < p.exprLevel {
+ p.failMessage("too many nested expressions")
+ return nil
+ }
+
+ // reparse input if we have / or /= as the beginning of a new expression, this should be a regular expression!
+ if p.tt == DivToken || p.tt == DivEqToken {
+ p.tt, p.data = p.l.RegExp()
+ if p.tt == ErrorToken {
+ p.fail("regular expression")
+ return nil
+ }
+ }
+
+ var left IExpr
+ precLeft := OpPrimary
+
+ if IsIdentifier(p.tt) && p.tt != AsyncToken {
+ left = p.scope.Use(p.data)
+ p.next()
+ suffix := p.parseExpressionSuffix(left, prec, precLeft)
+ p.exprLevel--
+ return suffix
+ } else if IsNumeric(p.tt) {
+ left = &LiteralExpr{p.tt, p.data}
+ p.next()
+ suffix := p.parseExpressionSuffix(left, prec, precLeft)
+ p.exprLevel--
+ return suffix
+ }
+
+ switch tt := p.tt; tt {
+ case StringToken, ThisToken, NullToken, TrueToken, FalseToken, RegExpToken:
+ left = &LiteralExpr{p.tt, p.data}
+ p.next()
+ case OpenBracketToken:
+ parentInFor := p.inFor
+ p.inFor = false
+ array := p.parseArrayLiteral()
+ left = &array
+ p.inFor = parentInFor
+ case OpenBraceToken:
+ parentInFor := p.inFor
+ p.inFor = false
+ object := p.parseObjectLiteral()
+ left = &object
+ p.inFor = parentInFor
+ case OpenParenToken:
+ // parenthesized expression or arrow parameter list
+ if OpAssign < prec {
+ // must be a parenthesized expression
+ p.next()
+ parentInFor := p.inFor
+ p.inFor = false
+ left = &GroupExpr{p.parseExpression(OpExpr)}
+ p.inFor = parentInFor
+ if !p.consume("expression", CloseParenToken) {
+ return nil
+ }
+ break
+ }
+ suffix := p.parseParenthesizedExpressionOrArrowFunc(prec, nil)
+ p.exprLevel--
+ return suffix
+ case NotToken, BitNotToken, TypeofToken, VoidToken, DeleteToken:
+ if OpUnary < prec {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &UnaryExpr{tt, p.parseExpression(OpUnary)}
+ precLeft = OpUnary
+ case AddToken:
+ if OpUnary < prec {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &UnaryExpr{PosToken, p.parseExpression(OpUnary)}
+ precLeft = OpUnary
+ case SubToken:
+ if OpUnary < prec {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &UnaryExpr{NegToken, p.parseExpression(OpUnary)}
+ precLeft = OpUnary
+ case IncrToken:
+ if OpUpdate < prec {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &UnaryExpr{PreIncrToken, p.parseExpression(OpUnary)}
+ precLeft = OpUnary
+ case DecrToken:
+ if OpUpdate < prec {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &UnaryExpr{PreDecrToken, p.parseExpression(OpUnary)}
+ precLeft = OpUnary
+ case AwaitToken:
+ // either accepted as IdentifierReference or as AwaitExpression
+ if p.await && prec <= OpUnary {
+ p.next()
+ left = &UnaryExpr{tt, p.parseExpression(OpUnary)}
+ precLeft = OpUnary
+ } else if p.await {
+ p.fail("expression")
+ return nil
+ } else {
+ left = p.scope.Use(p.data)
+ p.next()
+ }
+ case NewToken:
+ p.next()
+ if p.tt == DotToken {
+ p.next()
+ if !p.consume("new.target expression", TargetToken) {
+ return nil
+ }
+ left = &NewTargetExpr{}
+ precLeft = OpMember
+ } else {
+ newExpr := &NewExpr{p.parseExpression(OpNew), nil}
+ if p.tt == OpenParenToken {
+ args := p.parseArguments()
+ if len(args.List) != 0 {
+ newExpr.Args = &args
+ }
+ precLeft = OpMember
+ } else {
+ precLeft = OpNew
+ }
+ left = newExpr
+ }
+ case ImportToken:
+ // OpMember < prec does never happen
+ left = &LiteralExpr{p.tt, p.data}
+ p.next()
+ if p.tt == DotToken {
+ p.next()
+ if !p.consume("import.meta expression", MetaToken) {
+ return nil
+ }
+ left = &ImportMetaExpr{}
+ precLeft = OpMember
+ } else if p.tt != OpenParenToken {
+ p.fail("import expression", OpenParenToken)
+ return nil
+ } else if OpCall < prec {
+ p.fail("expression")
+ return nil
+ } else {
+ precLeft = OpCall
+ }
+ case SuperToken:
+ // OpMember < prec does never happen
+ left = &LiteralExpr{p.tt, p.data}
+ p.next()
+ if OpCall < prec && p.tt != DotToken && p.tt != OpenBracketToken {
+ p.fail("super expression", OpenBracketToken, DotToken)
+ return nil
+ } else if p.tt != DotToken && p.tt != OpenBracketToken && p.tt != OpenParenToken {
+ p.fail("super expression", OpenBracketToken, OpenParenToken, DotToken)
+ return nil
+ }
+ if OpCall < prec {
+ precLeft = OpMember
+ } else {
+ precLeft = OpCall
+ }
+ case YieldToken:
+ // either accepted as IdentifierReference or as YieldExpression
+ if p.yield && prec <= OpAssign {
+ // YieldExpression
+ p.next()
+ yieldExpr := YieldExpr{}
+ if !p.prevLT {
+ yieldExpr.Generator = p.tt == MulToken
+ if yieldExpr.Generator {
+ p.next()
+ yieldExpr.X = p.parseExpression(OpAssign)
+ } else if p.tt != CloseBraceToken && p.tt != CloseBracketToken && p.tt != CloseParenToken && p.tt != ColonToken && p.tt != CommaToken && p.tt != SemicolonToken {
+ yieldExpr.X = p.parseExpression(OpAssign)
+ }
+ }
+ left = &yieldExpr
+ precLeft = OpAssign
+ } else if p.yield {
+ p.fail("expression")
+ return nil
+ } else {
+ left = p.scope.Use(p.data)
+ p.next()
+ }
+ case AsyncToken:
+ async := p.data
+ p.next()
+ left = p.parseAsyncExpression(prec, async)
+ case ClassToken:
+ parentInFor := p.inFor
+ p.inFor = false
+ left = p.parseClassExpr()
+ p.inFor = parentInFor
+ case FunctionToken:
+ parentInFor := p.inFor
+ p.inFor = false
+ left = p.parseFuncExpr()
+ p.inFor = parentInFor
+ case TemplateToken, TemplateStartToken:
+ parentInFor := p.inFor
+ p.inFor = false
+ template := p.parseTemplateLiteral(precLeft)
+ left = &template
+ p.inFor = parentInFor
+ default:
+ p.fail("expression")
+ return nil
+ }
+ suffix := p.parseExpressionSuffix(left, prec, precLeft)
+ p.exprLevel--
+ return suffix
+}
+
+func (p *Parser) parseExpressionSuffix(left IExpr, prec, precLeft OpPrec) IExpr {
+ for i := 0; ; i++ {
+ if 1000 < p.exprLevel+i {
+ p.failMessage("too many nested expressions")
+ return nil
+ }
+
+ switch tt := p.tt; tt {
+ case EqToken, MulEqToken, DivEqToken, ModEqToken, ExpEqToken, AddEqToken, SubEqToken, LtLtEqToken, GtGtEqToken, GtGtGtEqToken, BitAndEqToken, BitXorEqToken, BitOrEqToken, AndEqToken, OrEqToken, NullishEqToken:
+ if OpAssign < prec {
+ return left
+ } else if precLeft < OpLHS {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpAssign)}
+ precLeft = OpAssign
+ case LtToken, LtEqToken, GtToken, GtEqToken, InToken, InstanceofToken:
+ if OpCompare < prec || p.inFor && tt == InToken {
+ return left
+ } else if precLeft < OpCompare {
+ // can only fail after a yield or arrow function expression
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpShift)}
+ precLeft = OpCompare
+ case EqEqToken, NotEqToken, EqEqEqToken, NotEqEqToken:
+ if OpEquals < prec {
+ return left
+ } else if precLeft < OpEquals {
+ // can only fail after a yield or arrow function expression
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpCompare)}
+ precLeft = OpEquals
+ case AndToken:
+ if OpAnd < prec {
+ return left
+ } else if precLeft < OpAnd {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpBitOr)}
+ precLeft = OpAnd
+ case OrToken:
+ if OpOr < prec {
+ return left
+ } else if precLeft < OpOr {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpAnd)}
+ precLeft = OpOr
+ case NullishToken:
+ if OpCoalesce < prec {
+ return left
+ } else if precLeft < OpBitOr && precLeft != OpCoalesce {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpBitOr)}
+ precLeft = OpCoalesce
+ case DotToken:
+ // OpMember < prec does never happen
+ if precLeft < OpCall {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ if !IsIdentifierName(p.tt) && p.tt != PrivateIdentifierToken {
+ p.fail("dot expression", IdentifierToken)
+ return nil
+ }
+ exprPrec := OpMember
+ if precLeft < OpMember {
+ exprPrec = OpCall
+ }
+ if p.tt != PrivateIdentifierToken {
+ p.tt = IdentifierToken
+ }
+ left = &DotExpr{left, LiteralExpr{p.tt, p.data}, exprPrec, false}
+ p.next()
+ if precLeft < OpMember {
+ precLeft = OpCall
+ } else {
+ precLeft = OpMember
+ }
+ case OpenBracketToken:
+ // OpMember < prec does never happen
+ if precLeft < OpCall {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ exprPrec := OpMember
+ if precLeft < OpMember {
+ exprPrec = OpCall
+ }
+ parentInFor := p.inFor
+ p.inFor = false
+ left = &IndexExpr{left, p.parseExpression(OpExpr), exprPrec, false}
+ p.inFor = parentInFor
+ if !p.consume("index expression", CloseBracketToken) {
+ return nil
+ }
+ if precLeft < OpMember {
+ precLeft = OpCall
+ } else {
+ precLeft = OpMember
+ }
+ case OpenParenToken:
+ if OpCall < prec {
+ return left
+ } else if precLeft < OpCall {
+ p.fail("expression")
+ return nil
+ }
+ parentInFor := p.inFor
+ p.inFor = false
+ left = &CallExpr{left, p.parseArguments(), false}
+ precLeft = OpCall
+ p.inFor = parentInFor
+ case TemplateToken, TemplateStartToken:
+ // OpMember < prec does never happen
+ if precLeft < OpCall {
+ p.fail("expression")
+ return nil
+ }
+ parentInFor := p.inFor
+ p.inFor = false
+ template := p.parseTemplateLiteral(precLeft)
+ template.Tag = left
+ left = &template
+ if precLeft < OpMember {
+ precLeft = OpCall
+ } else {
+ precLeft = OpMember
+ }
+ p.inFor = parentInFor
+ case OptChainToken:
+ if OpCall < prec {
+ return left
+ }
+ p.next()
+ if p.tt == OpenParenToken {
+ left = &CallExpr{left, p.parseArguments(), true}
+ } else if p.tt == OpenBracketToken {
+ p.next()
+ left = &IndexExpr{left, p.parseExpression(OpExpr), OpCall, true}
+ if !p.consume("optional chaining expression", CloseBracketToken) {
+ return nil
+ }
+ } else if p.tt == TemplateToken || p.tt == TemplateStartToken {
+ template := p.parseTemplateLiteral(precLeft)
+ template.Prec = OpCall
+ template.Tag = left
+ template.Optional = true
+ left = &template
+ } else if IsIdentifierName(p.tt) {
+ left = &DotExpr{left, LiteralExpr{IdentifierToken, p.data}, OpCall, true}
+ p.next()
+ } else if p.tt == PrivateIdentifierToken {
+ left = &DotExpr{left, LiteralExpr{p.tt, p.data}, OpCall, true}
+ p.next()
+ } else {
+ p.fail("optional chaining expression", IdentifierToken, OpenParenToken, OpenBracketToken, TemplateToken)
+ return nil
+ }
+ precLeft = OpCall
+ case IncrToken:
+ if p.prevLT || OpUpdate < prec {
+ return left
+ } else if precLeft < OpLHS {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &UnaryExpr{PostIncrToken, left}
+ precLeft = OpUpdate
+ case DecrToken:
+ if p.prevLT || OpUpdate < prec {
+ return left
+ } else if precLeft < OpLHS {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &UnaryExpr{PostDecrToken, left}
+ precLeft = OpUpdate
+ case ExpToken:
+ if OpExp < prec {
+ return left
+ } else if precLeft < OpUpdate {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpExp)}
+ precLeft = OpExp
+ case MulToken, DivToken, ModToken:
+ if OpMul < prec {
+ return left
+ } else if precLeft < OpMul {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpExp)}
+ precLeft = OpMul
+ case AddToken, SubToken:
+ if OpAdd < prec {
+ return left
+ } else if precLeft < OpAdd {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpMul)}
+ precLeft = OpAdd
+ case LtLtToken, GtGtToken, GtGtGtToken:
+ if OpShift < prec {
+ return left
+ } else if precLeft < OpShift {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpAdd)}
+ precLeft = OpShift
+ case BitAndToken:
+ if OpBitAnd < prec {
+ return left
+ } else if precLeft < OpBitAnd {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpEquals)}
+ precLeft = OpBitAnd
+ case BitXorToken:
+ if OpBitXor < prec {
+ return left
+ } else if precLeft < OpBitXor {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpBitAnd)}
+ precLeft = OpBitXor
+ case BitOrToken:
+ if OpBitOr < prec {
+ return left
+ } else if precLeft < OpBitOr {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ left = &BinaryExpr{tt, left, p.parseExpression(OpBitXor)}
+ precLeft = OpBitOr
+ case QuestionToken:
+ if OpAssign < prec {
+ return left
+ } else if precLeft < OpCoalesce {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ ifExpr := p.parseExpression(OpAssign)
+ if !p.consume("conditional expression", ColonToken) {
+ return nil
+ }
+ elseExpr := p.parseExpression(OpAssign)
+ left = &CondExpr{left, ifExpr, elseExpr}
+ precLeft = OpAssign
+ case CommaToken:
+ if OpExpr < prec {
+ return left
+ }
+ p.next()
+ if commaExpr, ok := left.(*CommaExpr); ok {
+ commaExpr.List = append(commaExpr.List, p.parseExpression(OpAssign))
+ i-- // adjust expression nesting limit
+ } else {
+ left = &CommaExpr{[]IExpr{left, p.parseExpression(OpAssign)}}
+ }
+ precLeft = OpExpr
+ case ArrowToken:
+ // handle identifier => ..., where identifier could also be yield or await
+ if OpAssign < prec {
+ return left
+ } else if precLeft < OpPrimary {
+ p.fail("expression")
+ return nil
+ }
+
+ v, ok := left.(*Var)
+ if !ok {
+ p.fail("expression")
+ return nil
+ }
+
+ left = p.parseIdentifierArrowFunc(v)
+ precLeft = OpAssign
+ default:
+ return left
+ }
+ }
+}
+
+func (p *Parser) parseAssignmentExpression() IExpr {
+ // this could be a BindingElement or an AssignmentExpression. Here we handle BindingIdentifier with a possible Initializer, BindingPattern will be handled by parseArrayLiteral or parseObjectLiteral
+ if p.assumeArrowFunc && p.isIdentifierReference(p.tt) {
+ tt := p.tt
+ data := p.data
+ p.next()
+ if p.tt == EqToken || p.tt == CommaToken || p.tt == CloseParenToken || p.tt == CloseBraceToken || p.tt == CloseBracketToken {
+ var ok bool
+ var left IExpr
+ left, ok = p.scope.Declare(ArgumentDecl, data)
+ if ok {
+ p.assumeArrowFunc = false
+ left = p.parseExpressionSuffix(left, OpAssign, OpPrimary)
+ p.assumeArrowFunc = true
+ return left
+ }
+ }
+ p.assumeArrowFunc = false
+ if tt == AsyncToken {
+ return p.parseAsyncExpression(OpAssign, data)
+ }
+ return p.parseIdentifierExpression(OpAssign, data)
+ } else if p.tt != OpenBracketToken && p.tt != OpenBraceToken {
+ p.assumeArrowFunc = false
+ }
+ return p.parseExpression(OpAssign)
+}
+
+func (p *Parser) parseParenthesizedExpressionOrArrowFunc(prec OpPrec, async []byte) IExpr {
+ var left IExpr
+ precLeft := OpPrimary
+
+ // expect to be at (
+ p.next()
+
+ isAsync := async != nil
+ arrowFunc := &ArrowFunc{}
+ parent := p.enterScope(&arrowFunc.Body.Scope, true)
+ parentAssumeArrowFunc, parentInFor := p.assumeArrowFunc, p.inFor
+ p.assumeArrowFunc, p.inFor = true, false
+
+ // parse a parenthesized expression but assume we might be parsing an (async) arrow function. If this is really an arrow function, parsing as a parenthesized expression cannot fail as AssignmentExpression, ArrayLiteral, and ObjectLiteral are supersets of SingleNameBinding, ArrayBindingPattern, and ObjectBindingPattern respectively. Any identifier that would be a BindingIdentifier in case of an arrow function, will be added as such. If finally this is not an arrow function, we will demote those variables an undeclared and merge them with the parent scope.
+
+ var list []IExpr
+ var rest IExpr
+ for p.tt != CloseParenToken && p.tt != ErrorToken {
+ if p.tt == EllipsisToken && p.assumeArrowFunc {
+ p.next()
+ if isAsync {
+ rest = p.parseAssignmentExpression()
+ if p.tt == CommaToken {
+ p.next()
+ }
+ } else if p.isIdentifierReference(p.tt) {
+ var ok bool
+ rest, ok = p.scope.Declare(ArgumentDecl, p.data)
+ if !ok {
+ p.failMessage("identifier %s has already been declared", string(p.data))
+ return nil
+ }
+ p.next()
+ } else if p.tt == OpenBracketToken {
+ array := p.parseArrayLiteral()
+ rest = &array
+ } else if p.tt == OpenBraceToken {
+ object := p.parseObjectLiteral()
+ rest = &object
+ } else {
+ p.fail("arrow function")
+ return nil
+ }
+ break
+ }
+
+ list = append(list, p.parseAssignmentExpression())
+ if p.tt != CommaToken {
+ break
+ }
+ p.next()
+ }
+ if p.tt != CloseParenToken {
+ p.fail("expression")
+ return nil
+ }
+ p.next()
+ isArrowFunc := p.tt == ArrowToken && p.assumeArrowFunc
+ p.assumeArrowFunc, p.inFor = parentAssumeArrowFunc, parentInFor
+
+ if isArrowFunc {
+ parentAwait, parentYield := p.await, p.yield
+ p.await = isAsync
+
+ // arrow function
+ arrowFunc.Params = Params{List: make([]BindingElement, len(list))}
+ for i, item := range list {
+ arrowFunc.Params.List[i] = p.exprToBindingElement(item) // can not fail when assumArrowFunc is set
+ }
+ arrowFunc.Async = isAsync
+ arrowFunc.Params.Rest = p.exprToBinding(rest)
+ arrowFunc.Body.List = p.parseArrowFuncBody()
+
+ p.await, p.yield = parentAwait, parentYield
+ p.exitScope(parent)
+
+ left = arrowFunc
+ precLeft = OpAssign
+ } else if len(list) == 0 || !isAsync && rest != nil || isAsync && OpCall < prec {
+ p.fail("arrow function", ArrowToken)
+ return nil
+ } else {
+ p.exitScope(parent)
+
+ // for any nested FuncExpr/ArrowFunc scope, Parent will point to the temporary scope created in case this was an arrow function instead of a parenthesized expression. This is not a problem as Parent is only used for defining new variables, and we already parsed all the nested scopes so that Parent (not Func) are not relevant anymore. Anyways, the Parent will just point to an empty scope, whose Parent/Func will point to valid scopes. This should not be a big deal.
+ // Here we move all declared ArgumentDecls (in case of an arrow function) to its parent scope as undeclared variables (identifiers used in a parenthesized expression).
+ arrowFunc.Body.Scope.UndeclareScope()
+
+ if isAsync {
+ // call expression
+ args := Args{}
+ for _, item := range list {
+ args.List = append(args.List, Arg{Value: item, Rest: false})
+ }
+ if rest != nil {
+ args.List = append(args.List, Arg{Value: rest, Rest: true})
+ }
+ left = p.scope.Use(async)
+ left = &CallExpr{left, args, false}
+ precLeft = OpCall
+ } else {
+ // parenthesized expression
+ if 1 < len(list) {
+ left = &GroupExpr{&CommaExpr{list}}
+ } else {
+ left = &GroupExpr{list[0]}
+ }
+ }
+ }
+ return p.parseExpressionSuffix(left, prec, precLeft)
+}
+
+// exprToBinding converts a CoverParenthesizedExpressionAndArrowParameterList into FormalParameters
+// Any unbound variables of the parameters (Initializer, ComputedPropertyName) are kept in the parent scope
+func (p *Parser) exprToBinding(expr IExpr) (binding IBinding) {
+ if v, ok := expr.(*Var); ok {
+ binding = v
+ } else if array, ok := expr.(*ArrayExpr); ok {
+ bindingArray := BindingArray{}
+ for _, item := range array.List {
+ if item.Spread {
+ // can only BindingIdentifier or BindingPattern
+ bindingArray.Rest = p.exprToBinding(item.Value)
+ break
+ }
+ var bindingElement BindingElement
+ bindingElement = p.exprToBindingElement(item.Value)
+ bindingArray.List = append(bindingArray.List, bindingElement)
+ }
+ binding = &bindingArray
+ } else if object, ok := expr.(*ObjectExpr); ok {
+ bindingObject := BindingObject{}
+ for _, item := range object.List {
+ if item.Spread {
+ // can only be BindingIdentifier
+ bindingObject.Rest = item.Value.(*Var)
+ break
+ }
+ var bindingElement BindingElement
+ bindingElement.Binding = p.exprToBinding(item.Value)
+ if bindingElement.Binding == nil {
+ bindingElement = p.exprToBindingElement(item.Value)
+ } else if item.Init != nil {
+ bindingElement.Default = item.Init
+ }
+ bindingObject.List = append(bindingObject.List, BindingObjectItem{Key: item.Name, Value: bindingElement})
+ }
+ binding = &bindingObject
+ }
+ return
+}
+
+func (p *Parser) exprToBindingElement(expr IExpr) (bindingElement BindingElement) {
+ if assign, ok := expr.(*BinaryExpr); ok && assign.Op == EqToken {
+ bindingElement.Binding = p.exprToBinding(assign.X)
+ bindingElement.Default = assign.Y
+ } else {
+ bindingElement.Binding = p.exprToBinding(expr)
+ }
+ return
+}
+
+func (p *Parser) isIdentifierReference(tt TokenType) bool {
+ return IsIdentifier(tt) || tt == YieldToken && !p.yield || tt == AwaitToken && !p.await
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/js/table.go b/vendor/github.com/tdewolff/parse/v2/js/table.go
new file mode 100644
index 0000000..2533091
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/js/table.go
@@ -0,0 +1,142 @@
+package js
+
+import "strconv"
+
+// OpPrec is the operator precedence
+type OpPrec int
+
+// OpPrec values.
+const (
+ OpExpr OpPrec = iota // a,b
+ OpAssign // a?b:c, yield x, ()=>x, async ()=>x, a=b, a+=b, ...
+ OpCoalesce // a??b
+ OpOr // a||b
+ OpAnd // a&&b
+ OpBitOr // a|b
+ OpBitXor // a^b
+ OpBitAnd // a&b
+ OpEquals // a==b, a!=b, a===b, a!==b
+ OpCompare // a<b, a>b, a<=b, a>=b, a instanceof b, a in b
+ OpShift // a<<b, a>>b, a>>>b
+ OpAdd // a+b, a-b
+ OpMul // a*b, a/b, a%b
+ OpExp // a**b
+ OpUnary // ++x, --x, delete x, void x, typeof x, +x, -x, ~x, !x, await x
+ OpUpdate // x++, x--
+ OpLHS // CallExpr/OptChainExpr or NewExpr
+ OpCall // a?.b, a(b), super(a), import(a)
+ OpNew // new a
+ OpMember // a[b], a.b, a`b`, super[x], super.x, new.target, import.meta, new a(b)
+ OpPrimary // literal, function, class, parenthesized
+)
+
+func (prec OpPrec) String() string {
+ switch prec {
+ case OpExpr:
+ return "OpExpr"
+ case OpAssign:
+ return "OpAssign"
+ case OpCoalesce:
+ return "OpCoalesce"
+ case OpOr:
+ return "OpOr"
+ case OpAnd:
+ return "OpAnd"
+ case OpBitOr:
+ return "OpBitOr"
+ case OpBitXor:
+ return "OpBitXor"
+ case OpBitAnd:
+ return "OpBitAnd"
+ case OpEquals:
+ return "OpEquals"
+ case OpCompare:
+ return "OpCompare"
+ case OpShift:
+ return "OpShift"
+ case OpAdd:
+ return "OAdd"
+ case OpMul:
+ return "OpMul"
+ case OpExp:
+ return "OpExp"
+ case OpUnary:
+ return "OpUnary"
+ case OpUpdate:
+ return "OpUpdate"
+ case OpLHS:
+ return "OpLHS"
+ case OpCall:
+ return "OpCall"
+ case OpNew:
+ return "OpNew"
+ case OpMember:
+ return "OpMember"
+ case OpPrimary:
+ return "OpPrimary"
+ }
+ return "Invalid(" + strconv.Itoa(int(prec)) + ")"
+}
+
+// Keywords is a map of reserved, strict, and other keywords
+var Keywords = map[string]TokenType{
+ // reserved
+ "await": AwaitToken,
+ "break": BreakToken,
+ "case": CaseToken,
+ "catch": CatchToken,
+ "class": ClassToken,
+ "const": ConstToken,
+ "continue": ContinueToken,
+ "debugger": DebuggerToken,
+ "default": DefaultToken,
+ "delete": DeleteToken,
+ "do": DoToken,
+ "else": ElseToken,
+ "enum": EnumToken,
+ "export": ExportToken,
+ "extends": ExtendsToken,
+ "false": FalseToken,
+ "finally": FinallyToken,
+ "for": ForToken,
+ "function": FunctionToken,
+ "if": IfToken,
+ "import": ImportToken,
+ "in": InToken,
+ "instanceof": InstanceofToken,
+ "new": NewToken,
+ "null": NullToken,
+ "return": ReturnToken,
+ "super": SuperToken,
+ "switch": SwitchToken,
+ "this": ThisToken,
+ "throw": ThrowToken,
+ "true": TrueToken,
+ "try": TryToken,
+ "typeof": TypeofToken,
+ "var": VarToken,
+ "void": VoidToken,
+ "while": WhileToken,
+ "with": WithToken,
+ "yield": YieldToken,
+
+ // strict mode
+ "let": LetToken,
+ "static": StaticToken,
+ "implements": ImplementsToken,
+ "interface": InterfaceToken,
+ "package": PackageToken,
+ "private": PrivateToken,
+ "protected": ProtectedToken,
+ "public": PublicToken,
+
+ // extra
+ "as": AsToken,
+ "async": AsyncToken,
+ "from": FromToken,
+ "get": GetToken,
+ "meta": MetaToken,
+ "of": OfToken,
+ "set": SetToken,
+ "target": TargetToken,
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/js/tokentype.go b/vendor/github.com/tdewolff/parse/v2/js/tokentype.go
new file mode 100644
index 0000000..4f310be
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/js/tokentype.go
@@ -0,0 +1,404 @@
+package js
+
+import "strconv"
+
+// TokenType determines the type of token, eg. a number or a semicolon.
+type TokenType uint16 // from LSB to MSB: 8 bits for tokens per category, 1 bit for numeric, 1 bit for punctuator, 1 bit for operator, 1 bit for identifier, 4 bits unused
+
+// TokenType values.
+const (
+ ErrorToken TokenType = iota // extra token when errors occur
+ WhitespaceToken
+ LineTerminatorToken // \r \n \r\n
+ CommentToken
+ CommentLineTerminatorToken
+ StringToken
+ TemplateToken
+ TemplateStartToken
+ TemplateMiddleToken
+ TemplateEndToken
+ RegExpToken
+ PrivateIdentifierToken
+)
+
+// Numeric token values.
+const (
+ NumericToken TokenType = 0x0100 + iota
+ DecimalToken
+ BinaryToken
+ OctalToken
+ HexadecimalToken
+ BigIntToken
+)
+
+// Punctuator token values.
+const (
+ PunctuatorToken TokenType = 0x0200 + iota
+ OpenBraceToken // {
+ CloseBraceToken // }
+ OpenParenToken // (
+ CloseParenToken // )
+ OpenBracketToken // [
+ CloseBracketToken // ]
+ DotToken // .
+ SemicolonToken // ;
+ CommaToken // ,
+ QuestionToken // ?
+ ColonToken // :
+ ArrowToken // =>
+ EllipsisToken // ...
+)
+
+// Operator token values.
+const (
+ OperatorToken TokenType = 0x0600 + iota
+ EqToken // =
+ EqEqToken // ==
+ EqEqEqToken // ===
+ NotToken // !
+ NotEqToken // !=
+ NotEqEqToken // !==
+ LtToken // <
+ LtEqToken // <=
+ LtLtToken // <<
+ LtLtEqToken // <<=
+ GtToken // >
+ GtEqToken // >=
+ GtGtToken // >>
+ GtGtEqToken // >>=
+ GtGtGtToken // >>>
+ GtGtGtEqToken // >>>=
+ AddToken // +
+ AddEqToken // +=
+ IncrToken // ++
+ SubToken // -
+ SubEqToken // -=
+ DecrToken // --
+ MulToken // *
+ MulEqToken // *=
+ ExpToken // **
+ ExpEqToken // **=
+ DivToken // /
+ DivEqToken // /=
+ ModToken // %
+ ModEqToken // %=
+ BitAndToken // &
+ BitOrToken // |
+ BitXorToken // ^
+ BitNotToken // ~
+ BitAndEqToken // &=
+ BitOrEqToken // |=
+ BitXorEqToken // ^=
+ AndToken // &&
+ OrToken // ||
+ NullishToken // ??
+ AndEqToken // &&=
+ OrEqToken // ||=
+ NullishEqToken // ??=
+ OptChainToken // ?.
+
+ // unused in lexer
+ PosToken // +a
+ NegToken // -a
+ PreIncrToken // ++a
+ PreDecrToken // --a
+ PostIncrToken // a++
+ PostDecrToken // a--
+)
+
+// Reserved token values.
+const (
+ ReservedToken TokenType = 0x0800 + iota
+ AwaitToken
+ BreakToken
+ CaseToken
+ CatchToken
+ ClassToken
+ ConstToken
+ ContinueToken
+ DebuggerToken
+ DefaultToken
+ DeleteToken
+ DoToken
+ ElseToken
+ EnumToken
+ ExportToken
+ ExtendsToken
+ FalseToken
+ FinallyToken
+ ForToken
+ FunctionToken
+ IfToken
+ ImportToken
+ InToken
+ InstanceofToken
+ NewToken
+ NullToken
+ ReturnToken
+ SuperToken
+ SwitchToken
+ ThisToken
+ ThrowToken
+ TrueToken
+ TryToken
+ TypeofToken
+ YieldToken
+ VarToken
+ VoidToken
+ WhileToken
+ WithToken
+)
+
+// Identifier token values.
+const (
+ IdentifierToken TokenType = 0x1000 + iota
+ AsToken
+ AsyncToken
+ FromToken
+ GetToken
+ ImplementsToken
+ InterfaceToken
+ LetToken
+ MetaToken
+ OfToken
+ PackageToken
+ PrivateToken
+ ProtectedToken
+ PublicToken
+ SetToken
+ StaticToken
+ TargetToken
+)
+
+// IsNumeric return true if token is numeric.
+func IsNumeric(tt TokenType) bool {
+ return tt&0x0100 != 0
+}
+
+// IsPunctuator return true if token is a punctuator.
+func IsPunctuator(tt TokenType) bool {
+ return tt&0x0200 != 0
+}
+
+// IsOperator return true if token is an operator.
+func IsOperator(tt TokenType) bool {
+ return tt&0x0400 != 0
+}
+
+// IsIdentifierName matches IdentifierName, i.e. any identifier
+func IsIdentifierName(tt TokenType) bool {
+ return tt&0x1800 != 0
+}
+
+// IsReservedWord matches ReservedWord
+func IsReservedWord(tt TokenType) bool {
+ return tt&0x0800 != 0
+}
+
+// IsIdentifier matches Identifier, i.e. IdentifierName but not ReservedWord. Does not match yield or await.
+func IsIdentifier(tt TokenType) bool {
+ return tt&0x1000 != 0
+}
+
+func (tt TokenType) String() string {
+ s := tt.Bytes()
+ if s == nil {
+ return "Invalid(" + strconv.Itoa(int(tt)) + ")"
+ }
+ return string(s)
+}
+
+var operatorBytes = [][]byte{
+ []byte("Operator"),
+ []byte("="),
+ []byte("=="),
+ []byte("==="),
+ []byte("!"),
+ []byte("!="),
+ []byte("!=="),
+ []byte("<"),
+ []byte("<="),
+ []byte("<<"),
+ []byte("<<="),
+ []byte(">"),
+ []byte(">="),
+ []byte(">>"),
+ []byte(">>="),
+ []byte(">>>"),
+ []byte(">>>="),
+ []byte("+"),
+ []byte("+="),
+ []byte("++"),
+ []byte("-"),
+ []byte("-="),
+ []byte("--"),
+ []byte("*"),
+ []byte("*="),
+ []byte("**"),
+ []byte("**="),
+ []byte("/"),
+ []byte("/="),
+ []byte("%"),
+ []byte("%="),
+ []byte("&"),
+ []byte("|"),
+ []byte("^"),
+ []byte("~"),
+ []byte("&="),
+ []byte("|="),
+ []byte("^="),
+ []byte("&&"),
+ []byte("||"),
+ []byte("??"),
+ []byte("&&="),
+ []byte("||="),
+ []byte("??="),
+ []byte("?."),
+ []byte("+"),
+ []byte("-"),
+ []byte("++"),
+ []byte("--"),
+ []byte("++"),
+ []byte("--"),
+}
+
+var reservedWordBytes = [][]byte{
+ []byte("Reserved"),
+ []byte("await"),
+ []byte("break"),
+ []byte("case"),
+ []byte("catch"),
+ []byte("class"),
+ []byte("const"),
+ []byte("continue"),
+ []byte("debugger"),
+ []byte("default"),
+ []byte("delete"),
+ []byte("do"),
+ []byte("else"),
+ []byte("enum"),
+ []byte("export"),
+ []byte("extends"),
+ []byte("false"),
+ []byte("finally"),
+ []byte("for"),
+ []byte("function"),
+ []byte("if"),
+ []byte("import"),
+ []byte("in"),
+ []byte("instanceof"),
+ []byte("new"),
+ []byte("null"),
+ []byte("return"),
+ []byte("super"),
+ []byte("switch"),
+ []byte("this"),
+ []byte("throw"),
+ []byte("true"),
+ []byte("try"),
+ []byte("typeof"),
+ []byte("yield"),
+ []byte("var"),
+ []byte("void"),
+ []byte("while"),
+ []byte("with"),
+}
+
+var identifierBytes = [][]byte{
+ []byte("Identifier"),
+ []byte("as"),
+ []byte("async"),
+ []byte("from"),
+ []byte("get"),
+ []byte("implements"),
+ []byte("interface"),
+ []byte("let"),
+ []byte("meta"),
+ []byte("of"),
+ []byte("package"),
+ []byte("private"),
+ []byte("protected"),
+ []byte("public"),
+ []byte("set"),
+ []byte("static"),
+ []byte("target"),
+}
+
+// Bytes returns the string representation of a TokenType.
+func (tt TokenType) Bytes() []byte {
+ if IsOperator(tt) && int(tt-OperatorToken) < len(operatorBytes) {
+ return operatorBytes[tt-OperatorToken]
+ } else if IsReservedWord(tt) && int(tt-ReservedToken) < len(reservedWordBytes) {
+ return reservedWordBytes[tt-ReservedToken]
+ } else if IsIdentifier(tt) && int(tt-IdentifierToken) < len(identifierBytes) {
+ return identifierBytes[tt-IdentifierToken]
+ }
+
+ switch tt {
+ case ErrorToken:
+ return []byte("Error")
+ case WhitespaceToken:
+ return []byte("Whitespace")
+ case LineTerminatorToken:
+ return []byte("LineTerminator")
+ case CommentToken:
+ return []byte("Comment")
+ case CommentLineTerminatorToken:
+ return []byte("CommentLineTerminator")
+ case StringToken:
+ return []byte("String")
+ case TemplateToken:
+ return []byte("Template")
+ case TemplateStartToken:
+ return []byte("TemplateStart")
+ case TemplateMiddleToken:
+ return []byte("TemplateMiddle")
+ case TemplateEndToken:
+ return []byte("TemplateEnd")
+ case RegExpToken:
+ return []byte("RegExp")
+ case PrivateIdentifierToken:
+ return []byte("PrivateIdentifier")
+ case NumericToken:
+ return []byte("Numeric")
+ case DecimalToken:
+ return []byte("Decimal")
+ case BinaryToken:
+ return []byte("Binary")
+ case OctalToken:
+ return []byte("Octal")
+ case HexadecimalToken:
+ return []byte("Hexadecimal")
+ case BigIntToken:
+ return []byte("BigInt")
+ case PunctuatorToken:
+ return []byte("Punctuator")
+ case OpenBraceToken:
+ return []byte("{")
+ case CloseBraceToken:
+ return []byte("}")
+ case OpenParenToken:
+ return []byte("(")
+ case CloseParenToken:
+ return []byte(")")
+ case OpenBracketToken:
+ return []byte("[")
+ case CloseBracketToken:
+ return []byte("]")
+ case DotToken:
+ return []byte(".")
+ case SemicolonToken:
+ return []byte(";")
+ case CommaToken:
+ return []byte(",")
+ case QuestionToken:
+ return []byte("?")
+ case ColonToken:
+ return []byte(":")
+ case ArrowToken:
+ return []byte("=>")
+ case EllipsisToken:
+ return []byte("...")
+ }
+ return nil
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/js/util.go b/vendor/github.com/tdewolff/parse/v2/js/util.go
new file mode 100644
index 0000000..78a629c
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/js/util.go
@@ -0,0 +1,38 @@
+package js
+
+// AsIdentifierName returns true if a valid identifier name is given.
+func AsIdentifierName(b []byte) bool {
+ if len(b) == 0 || !identifierStartTable[b[0]] {
+ return false
+ }
+
+ i := 1
+ for i < len(b) {
+ if identifierTable[b[i]] {
+ i++
+ } else {
+ return false
+ }
+ }
+ return true
+}
+
+// AsDecimalLiteral returns true if a valid decimal literal is given.
+func AsDecimalLiteral(b []byte) bool {
+ if len(b) == 0 || (b[0] < '0' || '9' < b[0]) && (b[0] != '.' || len(b) == 1) {
+ return false
+ } else if b[0] == '0' {
+ return len(b) == 1
+ }
+ i := 1
+ for i < len(b) && '0' <= b[i] && b[i] <= '9' {
+ i++
+ }
+ if i < len(b) && b[i] == '.' && b[0] != '.' {
+ i++
+ for i < len(b) && '0' <= b[i] && b[i] <= '9' {
+ i++
+ }
+ }
+ return i == len(b)
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/js/walk.go b/vendor/github.com/tdewolff/parse/v2/js/walk.go
new file mode 100644
index 0000000..5c94473
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/js/walk.go
@@ -0,0 +1,288 @@
+package js
+
+// IVisitor represents the AST Visitor
+// Each INode encountered by `Walk` is passed to `Enter`, children nodes will be ignored if the returned IVisitor is nil
+// `Exit` is called upon the exit of a node
+type IVisitor interface {
+ Enter(n INode) IVisitor
+ Exit(n INode)
+}
+
+// Walk traverses an AST in depth-first order
+func Walk(v IVisitor, n INode) {
+ if n == nil {
+ return
+ }
+
+ if v = v.Enter(n); v == nil {
+ return
+ }
+
+ defer v.Exit(n)
+
+ switch n := n.(type) {
+ case *AST:
+ Walk(v, &n.BlockStmt)
+ case *Var:
+ return
+ case *BlockStmt:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, n.List[i])
+ }
+ }
+ case *EmptyStmt:
+ return
+ case *ExprStmt:
+ Walk(v, n.Value)
+ case *IfStmt:
+ Walk(v, n.Body)
+ Walk(v, n.Else)
+ Walk(v, n.Cond)
+ case *DoWhileStmt:
+ Walk(v, n.Body)
+ Walk(v, n.Cond)
+ case *WhileStmt:
+ Walk(v, n.Body)
+ Walk(v, n.Cond)
+ case *ForStmt:
+ if n.Body != nil {
+ Walk(v, n.Body)
+ }
+
+ Walk(v, n.Init)
+ Walk(v, n.Cond)
+ Walk(v, n.Post)
+ case *ForInStmt:
+ if n.Body != nil {
+ Walk(v, n.Body)
+ }
+
+ Walk(v, n.Init)
+ Walk(v, n.Value)
+ case *ForOfStmt:
+ if n.Body != nil {
+ Walk(v, n.Body)
+ }
+
+ Walk(v, n.Init)
+ Walk(v, n.Value)
+ case *CaseClause:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, n.List[i])
+ }
+ }
+
+ Walk(v, n.Cond)
+ case *SwitchStmt:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, &n.List[i])
+ }
+ }
+
+ Walk(v, n.Init)
+ case *BranchStmt:
+ return
+ case *ReturnStmt:
+ Walk(v, n.Value)
+ case *WithStmt:
+ Walk(v, n.Body)
+ Walk(v, n.Cond)
+ case *LabelledStmt:
+ Walk(v, n.Value)
+ case *ThrowStmt:
+ Walk(v, n.Value)
+ case *TryStmt:
+ if n.Body != nil {
+ Walk(v, n.Body)
+ }
+
+ if n.Catch != nil {
+ Walk(v, n.Catch)
+ }
+
+ if n.Finally != nil {
+ Walk(v, n.Finally)
+ }
+
+ Walk(v, n.Binding)
+ case *DebuggerStmt:
+ return
+ case *Alias:
+ return
+ case *ImportStmt:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, &n.List[i])
+ }
+ }
+ case *ExportStmt:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, &n.List[i])
+ }
+ }
+
+ Walk(v, n.Decl)
+ case *DirectivePrologueStmt:
+ return
+ case *PropertyName:
+ Walk(v, &n.Literal)
+ Walk(v, n.Computed)
+ case *BindingArray:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, &n.List[i])
+ }
+ }
+
+ Walk(v, n.Rest)
+ case *BindingObjectItem:
+ if n.Key != nil {
+ Walk(v, n.Key)
+ }
+
+ Walk(v, &n.Value)
+ case *BindingObject:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, &n.List[i])
+ }
+ }
+
+ if n.Rest != nil {
+ Walk(v, n.Rest)
+ }
+ case *BindingElement:
+ Walk(v, n.Binding)
+ Walk(v, n.Default)
+ case *VarDecl:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, &n.List[i])
+ }
+ }
+ case *Params:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, &n.List[i])
+ }
+ }
+
+ Walk(v, n.Rest)
+ case *FuncDecl:
+ Walk(v, &n.Body)
+ Walk(v, &n.Params)
+
+ if n.Name != nil {
+ Walk(v, n.Name)
+ }
+ case *MethodDecl:
+ Walk(v, &n.Body)
+ Walk(v, &n.Params)
+ Walk(v, &n.Name)
+ case *Field:
+ Walk(v, &n.Name)
+ Walk(v, n.Init)
+ case *ClassDecl:
+ if n.Name != nil {
+ Walk(v, n.Name)
+ }
+
+ Walk(v, n.Extends)
+
+ for _, item := range n.List {
+ if item.StaticBlock != nil {
+ Walk(v, item.StaticBlock)
+ } else if item.Method != nil {
+ Walk(v, item.Method)
+ } else {
+ Walk(v, &item.Field)
+ }
+ }
+ case *LiteralExpr:
+ return
+ case *Element:
+ Walk(v, n.Value)
+ case *ArrayExpr:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, &n.List[i])
+ }
+ }
+ case *Property:
+ if n.Name != nil {
+ Walk(v, n.Name)
+ }
+
+ Walk(v, n.Value)
+ Walk(v, n.Init)
+ case *ObjectExpr:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, &n.List[i])
+ }
+ }
+ case *TemplatePart:
+ Walk(v, n.Expr)
+ case *TemplateExpr:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, &n.List[i])
+ }
+ }
+
+ Walk(v, n.Tag)
+ case *GroupExpr:
+ Walk(v, n.X)
+ case *IndexExpr:
+ Walk(v, n.X)
+ Walk(v, n.Y)
+ case *DotExpr:
+ Walk(v, n.X)
+ Walk(v, &n.Y)
+ case *NewTargetExpr:
+ return
+ case *ImportMetaExpr:
+ return
+ case *Arg:
+ Walk(v, n.Value)
+ case *Args:
+ if n.List != nil {
+ for i := 0; i < len(n.List); i++ {
+ Walk(v, &n.List[i])
+ }
+ }
+ case *NewExpr:
+ if n.Args != nil {
+ Walk(v, n.Args)
+ }
+
+ Walk(v, n.X)
+ case *CallExpr:
+ Walk(v, &n.Args)
+ Walk(v, n.X)
+ case *UnaryExpr:
+ Walk(v, n.X)
+ case *BinaryExpr:
+ Walk(v, n.X)
+ Walk(v, n.Y)
+ case *CondExpr:
+ Walk(v, n.Cond)
+ Walk(v, n.X)
+ Walk(v, n.Y)
+ case *YieldExpr:
+ Walk(v, n.X)
+ case *ArrowFunc:
+ Walk(v, &n.Body)
+ Walk(v, &n.Params)
+ case *CommaExpr:
+ for _, item := range n.List {
+ Walk(v, item)
+ }
+ default:
+ return
+ }
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/position.go b/vendor/github.com/tdewolff/parse/v2/position.go
new file mode 100644
index 0000000..38e38ce
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/position.go
@@ -0,0 +1,95 @@
+package parse
+
+import (
+ "fmt"
+ "io"
+ "strings"
+ "unicode"
+)
+
+// Position returns the line and column number for a certain position in a file. It is useful for recovering the position in a file that caused an error.
+// It only treates \n, \r, and \r\n as newlines, which might be different from some languages also recognizing \f, \u2028, and \u2029 to be newlines.
+func Position(r io.Reader, offset int) (line, col int, context string) {
+ l := NewInput(r)
+ line = 1
+ for l.Pos() < offset {
+ c := l.Peek(0)
+ n := 1
+ newline := false
+ if c == '\n' {
+ newline = true
+ } else if c == '\r' {
+ if l.Peek(1) == '\n' {
+ newline = true
+ n = 2
+ } else {
+ newline = true
+ }
+ } else if c >= 0xC0 {
+ var r rune
+ if r, n = l.PeekRune(0); r == '\u2028' || r == '\u2029' {
+ newline = true
+ }
+ } else if c == 0 && l.Err() != nil {
+ break
+ }
+
+ if 1 < n && offset < l.Pos()+n {
+ break
+ }
+ l.Move(n)
+
+ if newline {
+ line++
+ offset -= l.Pos()
+ l.Skip()
+ }
+ }
+
+ col = len([]rune(string(l.Lexeme()))) + 1
+ context = positionContext(l, line, col)
+ return
+}
+
+func positionContext(l *Input, line, col int) (context string) {
+ for {
+ c := l.Peek(0)
+ if c == 0 && l.Err() != nil || c == '\n' || c == '\r' {
+ break
+ }
+ l.Move(1)
+ }
+ rs := []rune(string(l.Lexeme()))
+
+ // cut off front or rear of context to stay between 60 characters
+ limit := 60
+ offset := 20
+ ellipsisFront := ""
+ ellipsisRear := ""
+ if limit < len(rs) {
+ if col <= limit-offset {
+ ellipsisRear = "..."
+ rs = rs[:limit-3]
+ } else if col >= len(rs)-offset-3 {
+ ellipsisFront = "..."
+ col -= len(rs) - offset - offset - 7
+ rs = rs[len(rs)-offset-offset-4:]
+ } else {
+ ellipsisFront = "..."
+ ellipsisRear = "..."
+ rs = rs[col-offset-1 : col+offset]
+ col = offset + 4
+ }
+ }
+
+ // replace unprintable characters by a space
+ for i, r := range rs {
+ if !unicode.IsGraphic(r) {
+ rs[i] = 'ยท'
+ }
+ }
+
+ context += fmt.Sprintf("%5d: %s%s%s\n", line, ellipsisFront, string(rs), ellipsisRear)
+ context += fmt.Sprintf("%s^", strings.Repeat(" ", 6+col))
+ return
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/strconv/float.go b/vendor/github.com/tdewolff/parse/v2/strconv/float.go
new file mode 100644
index 0000000..c89bdb2
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/strconv/float.go
@@ -0,0 +1,257 @@
+package strconv
+
+import (
+ "math"
+)
+
+var float64pow10 = []float64{
+ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
+ 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
+ 1e20, 1e21, 1e22,
+}
+
+// ParseFloat parses a byte-slice and returns the float it represents.
+// If an invalid character is encountered, it will stop there.
+func ParseFloat(b []byte) (float64, int) {
+ i := 0
+ neg := false
+ if i < len(b) && (b[i] == '+' || b[i] == '-') {
+ neg = b[i] == '-'
+ i++
+ }
+ start := i
+ dot := -1
+ trunk := -1
+ n := uint64(0)
+ for ; i < len(b); i++ {
+ c := b[i]
+ if c >= '0' && c <= '9' {
+ if trunk == -1 {
+ if n > math.MaxUint64/10 {
+ trunk = i
+ } else {
+ n *= 10
+ n += uint64(c - '0')
+ }
+ }
+ } else if dot == -1 && c == '.' {
+ dot = i
+ } else {
+ break
+ }
+ }
+ if i == start || i == start+1 && dot == start {
+ return 0.0, 0
+ }
+
+ f := float64(n)
+ if neg {
+ f = -f
+ }
+
+ mantExp := int64(0)
+ if dot != -1 {
+ if trunk == -1 {
+ trunk = i
+ }
+ mantExp = int64(trunk - dot - 1)
+ } else if trunk != -1 {
+ mantExp = int64(trunk - i)
+ }
+ expExp := int64(0)
+ if i < len(b) && (b[i] == 'e' || b[i] == 'E') {
+ startExp := i
+ i++
+ if e, expLen := ParseInt(b[i:]); expLen > 0 {
+ expExp = e
+ i += expLen
+ } else {
+ i = startExp
+ }
+ }
+ exp := expExp - mantExp
+
+ // copied from strconv/atof.go
+ if exp == 0 {
+ return f, i
+ } else if exp > 0 && exp <= 15+22 { // int * 10^k
+ // If exponent is big but number of digits is not,
+ // can move a few zeros into the integer part.
+ if exp > 22 {
+ f *= float64pow10[exp-22]
+ exp = 22
+ }
+ if f <= 1e15 && f >= -1e15 {
+ return f * float64pow10[exp], i
+ }
+ } else if exp < 0 && exp >= -22 { // int / 10^k
+ return f / float64pow10[-exp], i
+ }
+ f *= math.Pow10(int(-mantExp))
+ return f * math.Pow10(int(expExp)), i
+}
+
+const log2 = 0.3010299956639812
+
+func float64exp(f float64) int {
+ exp2 := 0
+ if f != 0.0 {
+ x := math.Float64bits(f)
+ exp2 = int(x>>(64-11-1))&0x7FF - 1023 + 1
+ }
+
+ exp10 := float64(exp2) * log2
+ if exp10 < 0 {
+ exp10 -= 1.0
+ }
+ return int(exp10)
+}
+
+// AppendFloat appends a float to `b` with precision `prec`. It returns the new slice and whether successful or not. Precision is the number of decimals to display, thus prec + 1 == number of significant digits.
+func AppendFloat(b []byte, f float64, prec int) ([]byte, bool) {
+ if math.IsNaN(f) || math.IsInf(f, 0) {
+ return b, false
+ }
+
+ neg := false
+ if f < 0.0 {
+ f = -f
+ neg = true
+ }
+ if prec < 0 || 17 < prec {
+ prec = 17 // maximum number of significant digits in double
+ }
+ prec -= float64exp(f) // number of digits in front of the dot
+ f *= math.Pow10(prec)
+
+ // calculate mantissa and exponent
+ mant := int64(f)
+ mantLen := LenInt(mant)
+ mantExp := mantLen - prec - 1
+ if mant == 0 {
+ return append(b, '0'), true
+ }
+
+ // expLen is zero for positive exponents, because positive exponents are determined later on in the big conversion loop
+ exp := 0
+ expLen := 0
+ if mantExp > 0 {
+ // positive exponent is determined in the loop below
+ // but if we initially decreased the exponent to fit in an integer, we can't set the new exponent in the loop alone,
+ // since the number of zeros at the end determines the positive exponent in the loop, and we just artificially lost zeros
+ if prec < 0 {
+ exp = mantExp
+ }
+ expLen = 1 + LenInt(int64(exp)) // e + digits
+ } else if mantExp < -3 {
+ exp = mantExp
+ expLen = 2 + LenInt(int64(exp)) // e + minus + digits
+ } else if mantExp < -1 {
+ mantLen += -mantExp - 1 // extra zero between dot and first digit
+ }
+
+ // reserve space in b
+ i := len(b)
+ maxLen := 1 + mantLen + expLen // dot + mantissa digits + exponent
+ if neg {
+ maxLen++
+ }
+ if i+maxLen > cap(b) {
+ b = append(b, make([]byte, maxLen)...)
+ } else {
+ b = b[:i+maxLen]
+ }
+
+ // write to string representation
+ if neg {
+ b[i] = '-'
+ i++
+ }
+
+ // big conversion loop, start at the end and move to the front
+ // initially print trailing zeros and remove them later on
+ // for example if the first non-zero digit is three positions in front of the dot, it will overwrite the zeros with a positive exponent
+ zero := true
+ last := i + mantLen // right-most position of digit that is non-zero + dot
+ dot := last - prec - exp // position of dot
+ j := last
+ for mant > 0 {
+ if j == dot {
+ b[j] = '.'
+ j--
+ }
+ newMant := mant / 10
+ digit := mant - 10*newMant
+ if zero && digit > 0 {
+ // first non-zero digit, if we are still behind the dot we can trim the end to this position
+ // otherwise trim to the dot (including the dot)
+ if j > dot {
+ i = j + 1
+ // decrease negative exponent further to get rid of dot
+ if exp < 0 {
+ newExp := exp - (j - dot)
+ // getting rid of the dot shouldn't lower the exponent to more digits (e.g. -9 -> -10)
+ if LenInt(int64(newExp)) == LenInt(int64(exp)) {
+ exp = newExp
+ dot = j
+ j--
+ i--
+ }
+ }
+ } else {
+ i = dot
+ }
+ last = j
+ zero = false
+ }
+ b[j] = '0' + byte(digit)
+ j--
+ mant = newMant
+ }
+
+ if j > dot {
+ // extra zeros behind the dot
+ for j > dot {
+ b[j] = '0'
+ j--
+ }
+ b[j] = '.'
+ } else if last+3 < dot {
+ // add positive exponent because we have 3 or more zeros in front of the dot
+ i = last + 1
+ exp = dot - last - 1
+ } else if j == dot {
+ // handle 0.1
+ b[j] = '.'
+ }
+
+ // exponent
+ if exp != 0 {
+ if exp == 1 {
+ b[i] = '0'
+ i++
+ } else if exp == 2 {
+ b[i] = '0'
+ b[i+1] = '0'
+ i += 2
+ } else {
+ b[i] = 'e'
+ i++
+ if exp < 0 {
+ b[i] = '-'
+ i++
+ exp = -exp
+ }
+ i += LenInt(int64(exp))
+ j := i
+ for exp > 0 {
+ newExp := exp / 10
+ digit := exp - 10*newExp
+ j--
+ b[j] = '0' + byte(digit)
+ exp = newExp
+ }
+ }
+ }
+ return b[:i], true
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/strconv/int.go b/vendor/github.com/tdewolff/parse/v2/strconv/int.go
new file mode 100644
index 0000000..e3483bd
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/strconv/int.go
@@ -0,0 +1,108 @@
+package strconv
+
+import (
+ "math"
+)
+
+// ParseInt parses a byte-slice and returns the integer it represents.
+// If an invalid character is encountered, it will stop there.
+func ParseInt(b []byte) (int64, int) {
+ i := 0
+ neg := false
+ if len(b) > 0 && (b[0] == '+' || b[0] == '-') {
+ neg = b[0] == '-'
+ i++
+ }
+ start := i
+ n := uint64(0)
+ for i < len(b) {
+ c := b[i]
+ if n > math.MaxUint64/10 {
+ return 0, 0
+ } else if c >= '0' && c <= '9' {
+ n *= 10
+ n += uint64(c - '0')
+ } else {
+ break
+ }
+ i++
+ }
+ if i == start {
+ return 0, 0
+ }
+ if !neg && n > uint64(math.MaxInt64) || n > uint64(math.MaxInt64)+1 {
+ return 0, 0
+ } else if neg {
+ return -int64(n), i
+ }
+ return int64(n), i
+}
+
+// ParseUint parses a byte-slice and returns the integer it represents.
+// If an invalid character is encountered, it will stop there.
+func ParseUint(b []byte) (uint64, int) {
+ i := 0
+ n := uint64(0)
+ for i < len(b) {
+ c := b[i]
+ if n > math.MaxUint64/10 {
+ return 0, 0
+ } else if c >= '0' && c <= '9' {
+ n *= 10
+ n += uint64(c - '0')
+ } else {
+ break
+ }
+ i++
+ }
+ return n, i
+}
+
+// LenInt returns the written length of an integer.
+func LenInt(i int64) int {
+ if i < 0 {
+ if i == -9223372036854775808 {
+ return 19
+ }
+ i = -i
+ }
+ switch {
+ case i < 10:
+ return 1
+ case i < 100:
+ return 2
+ case i < 1000:
+ return 3
+ case i < 10000:
+ return 4
+ case i < 100000:
+ return 5
+ case i < 1000000:
+ return 6
+ case i < 10000000:
+ return 7
+ case i < 100000000:
+ return 8
+ case i < 1000000000:
+ return 9
+ case i < 10000000000:
+ return 10
+ case i < 100000000000:
+ return 11
+ case i < 1000000000000:
+ return 12
+ case i < 10000000000000:
+ return 13
+ case i < 100000000000000:
+ return 14
+ case i < 1000000000000000:
+ return 15
+ case i < 10000000000000000:
+ return 16
+ case i < 100000000000000000:
+ return 17
+ case i < 1000000000000000000:
+ return 18
+ }
+ return 19
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/strconv/price.go b/vendor/github.com/tdewolff/parse/v2/strconv/price.go
new file mode 100644
index 0000000..94b3834
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/strconv/price.go
@@ -0,0 +1,83 @@
+package strconv
+
+// AppendPrice will append an int64 formatted as a price, where the int64 is the price in cents.
+// It does not display whether a price is negative or not.
+func AppendPrice(b []byte, price int64, dec bool, milSeparator byte, decSeparator byte) []byte {
+ if price < 0 {
+ if price == -9223372036854775808 {
+ x := []byte("92 233 720 368 547 758 08")
+ x[2] = milSeparator
+ x[6] = milSeparator
+ x[10] = milSeparator
+ x[14] = milSeparator
+ x[18] = milSeparator
+ x[22] = decSeparator
+ return append(b, x...)
+ }
+ price = -price
+ }
+
+ // rounding
+ if !dec {
+ firstDec := (price / 10) % 10
+ if firstDec >= 5 {
+ price += 100
+ }
+ }
+
+ // calculate size
+ n := LenInt(price) - 2
+ if n > 0 {
+ n += (n - 1) / 3 // mil separator
+ } else {
+ n = 1
+ }
+ if dec {
+ n += 2 + 1 // decimals + dec separator
+ }
+
+ // resize byte slice
+ i := len(b)
+ if i+n > cap(b) {
+ b = append(b, make([]byte, n)...)
+ } else {
+ b = b[:i+n]
+ }
+
+ // print fractional-part
+ i += n - 1
+ if dec {
+ for j := 0; j < 2; j++ {
+ c := byte(price%10) + '0'
+ price /= 10
+ b[i] = c
+ i--
+ }
+ b[i] = decSeparator
+ i--
+ } else {
+ price /= 100
+ }
+
+ if price == 0 {
+ b[i] = '0'
+ return b
+ }
+
+ // print integer-part
+ j := 0
+ for price > 0 {
+ if j == 3 {
+ b[i] = milSeparator
+ i--
+ j = 0
+ }
+
+ c := byte(price%10) + '0'
+ price /= 10
+ b[i] = c
+ i--
+ j++
+ }
+ return b
+}
diff --git a/vendor/github.com/tdewolff/parse/v2/util.go b/vendor/github.com/tdewolff/parse/v2/util.go
new file mode 100644
index 0000000..db706d4
--- /dev/null
+++ b/vendor/github.com/tdewolff/parse/v2/util.go
@@ -0,0 +1,481 @@
+package parse
+
+import (
+ "bytes"
+ "fmt"
+ "strconv"
+ "unicode"
+)
+
+// Copy returns a copy of the given byte slice.
+func Copy(src []byte) (dst []byte) {
+ dst = make([]byte, len(src))
+ copy(dst, src)
+ return
+}
+
+// ToLower converts all characters in the byte slice from A-Z to a-z.
+func ToLower(src []byte) []byte {
+ for i, c := range src {
+ if c >= 'A' && c <= 'Z' {
+ src[i] = c + ('a' - 'A')
+ }
+ }
+ return src
+}
+
+// EqualFold returns true when s matches case-insensitively the targetLower (which must be lowercase).
+func EqualFold(s, targetLower []byte) bool {
+ if len(s) != len(targetLower) {
+ return false
+ }
+ for i, c := range targetLower {
+ d := s[i]
+ if d != c && (d < 'A' || d > 'Z' || d+('a'-'A') != c) {
+ return false
+ }
+ }
+ return true
+}
+
+// Printable returns a printable string for given rune
+func Printable(r rune) string {
+ if unicode.IsGraphic(r) {
+ return fmt.Sprintf("%c", r)
+ } else if r < 128 {
+ return fmt.Sprintf("0x%02X", r)
+ }
+ return fmt.Sprintf("%U", r)
+}
+
+var whitespaceTable = [256]bool{
+ // ASCII
+ false, false, false, false, false, false, false, false,
+ false, true, true, false, true, true, false, false, // tab, new line, form feed, carriage return
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ true, false, false, false, false, false, false, false, // space
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ // non-ASCII
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+}
+
+// IsWhitespace returns true for space, \n, \r, \t, \f.
+func IsWhitespace(c byte) bool {
+ return whitespaceTable[c]
+}
+
+var newlineTable = [256]bool{
+ // ASCII
+ false, false, false, false, false, false, false, false,
+ false, false, true, false, false, true, false, false, // new line, carriage return
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ // non-ASCII
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+}
+
+// IsNewline returns true for \n, \r.
+func IsNewline(c byte) bool {
+ return newlineTable[c]
+}
+
+// IsAllWhitespace returns true when the entire byte slice consists of space, \n, \r, \t, \f.
+func IsAllWhitespace(b []byte) bool {
+ for _, c := range b {
+ if !IsWhitespace(c) {
+ return false
+ }
+ }
+ return true
+}
+
+// TrimWhitespace removes any leading and trailing whitespace characters.
+func TrimWhitespace(b []byte) []byte {
+ n := len(b)
+ start := n
+ for i := 0; i < n; i++ {
+ if !IsWhitespace(b[i]) {
+ start = i
+ break
+ }
+ }
+ end := n
+ for i := n - 1; i >= start; i-- {
+ if !IsWhitespace(b[i]) {
+ end = i + 1
+ break
+ }
+ }
+ return b[start:end]
+}
+
+// ReplaceMultipleWhitespace replaces character series of space, \n, \t, \f, \r into a single space or newline (when the serie contained a \n or \r).
+func ReplaceMultipleWhitespace(b []byte) []byte {
+ j, k := 0, 0 // j is write position, k is start of next text section
+ for i := 0; i < len(b); i++ {
+ if IsWhitespace(b[i]) {
+ start := i
+ newline := IsNewline(b[i])
+ i++
+ for ; i < len(b) && IsWhitespace(b[i]); i++ {
+ if IsNewline(b[i]) {
+ newline = true
+ }
+ }
+ if newline {
+ b[start] = '\n'
+ } else {
+ b[start] = ' '
+ }
+ if 1 < i-start { // more than one whitespace
+ if j == 0 {
+ j = start + 1
+ } else {
+ j += copy(b[j:], b[k:start+1])
+ }
+ k = i
+ }
+ }
+ }
+ if j == 0 {
+ return b
+ } else if j == 1 { // only if starts with whitespace
+ b[k-1] = b[0]
+ return b[k-1:]
+ } else if k < len(b) {
+ j += copy(b[j:], b[k:])
+ }
+ return b[:j]
+}
+
+// replaceEntities will replace in b at index i, assuming that b[i] == '&' and that i+3<len(b). The returned int will be the last character of the entity, so that the next iteration can safely do i++ to continue and not miss any entitites.
+func replaceEntities(b []byte, i int, entitiesMap map[string][]byte, revEntitiesMap map[byte][]byte) ([]byte, int) {
+ const MaxEntityLength = 31 // longest HTML entity: CounterClockwiseContourIntegral
+ var r []byte
+ j := i + 1
+ if b[j] == '#' {
+ j++
+ if b[j] == 'x' {
+ j++
+ c := 0
+ for ; j < len(b) && (b[j] >= '0' && b[j] <= '9' || b[j] >= 'a' && b[j] <= 'f' || b[j] >= 'A' && b[j] <= 'F'); j++ {
+ if b[j] <= '9' {
+ c = c<<4 + int(b[j]-'0')
+ } else if b[j] <= 'F' {
+ c = c<<4 + int(b[j]-'A') + 10
+ } else if b[j] <= 'f' {
+ c = c<<4 + int(b[j]-'a') + 10
+ }
+ }
+ if j <= i+3 || 10000 <= c {
+ return b, j - 1
+ }
+ if c < 128 {
+ r = []byte{byte(c)}
+ } else {
+ r = append(r, '&', '#')
+ r = strconv.AppendInt(r, int64(c), 10)
+ r = append(r, ';')
+ }
+ } else {
+ c := 0
+ for ; j < len(b) && c < 128 && b[j] >= '0' && b[j] <= '9'; j++ {
+ c = c*10 + int(b[j]-'0')
+ }
+ if j <= i+2 || 128 <= c {
+ return b, j - 1
+ }
+ r = []byte{byte(c)}
+ }
+ } else {
+ for ; j < len(b) && j-i-1 <= MaxEntityLength && b[j] != ';'; j++ {
+ }
+ if j <= i+1 || len(b) <= j {
+ return b, j - 1
+ }
+
+ var ok bool
+ r, ok = entitiesMap[string(b[i+1:j])]
+ if !ok {
+ return b, j
+ }
+ }
+
+ // j is at semicolon
+ n := j + 1 - i
+ if j < len(b) && b[j] == ';' && 2 < n {
+ if len(r) == 1 {
+ if q, ok := revEntitiesMap[r[0]]; ok {
+ if len(q) == len(b[i:j+1]) && bytes.Equal(q, b[i:j+1]) {
+ return b, j
+ }
+ r = q
+ } else if r[0] == '&' {
+ // check if for example &amp; is followed by something that could potentially be an entity
+ k := j + 1
+ if k < len(b) && (b[k] >= '0' && b[k] <= '9' || b[k] >= 'a' && b[k] <= 'z' || b[k] >= 'A' && b[k] <= 'Z' || b[k] == '#') {
+ return b, k
+ }
+ }
+ }
+
+ copy(b[i:], r)
+ copy(b[i+len(r):], b[j+1:])
+ b = b[:len(b)-n+len(r)]
+ return b, i + len(r) - 1
+ }
+ return b, i
+}
+
+// ReplaceEntities replaces all occurrences of entites (such as &quot;) to their respective unencoded bytes.
+func ReplaceEntities(b []byte, entitiesMap map[string][]byte, revEntitiesMap map[byte][]byte) []byte {
+ for i := 0; i < len(b); i++ {
+ if b[i] == '&' && i+3 < len(b) {
+ b, i = replaceEntities(b, i, entitiesMap, revEntitiesMap)
+ }
+ }
+ return b
+}
+
+// ReplaceMultipleWhitespaceAndEntities is a combination of ReplaceMultipleWhitespace and ReplaceEntities. It is faster than executing both sequentially.
+func ReplaceMultipleWhitespaceAndEntities(b []byte, entitiesMap map[string][]byte, revEntitiesMap map[byte][]byte) []byte {
+ j, k := 0, 0 // j is write position, k is start of next text section
+ for i := 0; i < len(b); i++ {
+ if IsWhitespace(b[i]) {
+ start := i
+ newline := IsNewline(b[i])
+ i++
+ for ; i < len(b) && IsWhitespace(b[i]); i++ {
+ if IsNewline(b[i]) {
+ newline = true
+ }
+ }
+ if newline {
+ b[start] = '\n'
+ } else {
+ b[start] = ' '
+ }
+ if 1 < i-start { // more than one whitespace
+ if j == 0 {
+ j = start + 1
+ } else {
+ j += copy(b[j:], b[k:start+1])
+ }
+ k = i
+ }
+ }
+ if i+3 < len(b) && b[i] == '&' {
+ b, i = replaceEntities(b, i, entitiesMap, revEntitiesMap)
+ }
+ }
+ if j == 0 {
+ return b
+ } else if j == 1 { // only if starts with whitespace
+ b[k-1] = b[0]
+ return b[k-1:]
+ } else if k < len(b) {
+ j += copy(b[j:], b[k:])
+ }
+ return b[:j]
+}
+
+// URLEncodingTable is a charmap for which characters need escaping in the URL encoding scheme
+var URLEncodingTable = [256]bool{
+ // ASCII
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+
+ true, false, true, true, true, true, true, false, // space, ", #, $, %, &
+ false, false, false, true, true, false, false, true, // +, comma, /
+ false, false, false, false, false, false, false, false,
+ false, false, true, true, true, true, true, true, // :, ;, <, =, >, ?
+
+ true, false, false, false, false, false, false, false, // @
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, true, true, true, true, false, // [, \, ], ^
+
+ true, false, false, false, false, false, false, false, // `
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, true, true, true, false, true, // {, |, }, DEL
+
+ // non-ASCII
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+}
+
+// DataURIEncodingTable is a charmap for which characters need escaping in the Data URI encoding scheme
+// Escape only non-printable characters, unicode and %, #, &.
+// IE11 additionally requires encoding of \, [, ], ", <, >, `, {, }, |, ^ which is not required by Chrome, Firefox, Opera, Edge, Safari, Yandex
+// To pass the HTML validator, restricted URL characters must be escaped: non-printable characters, space, <, >, #, %, "
+var DataURIEncodingTable = [256]bool{
+ // ASCII
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+
+ true, false, true, true, false, true, true, false, // space, ", #, %, &
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, true, false, true, false, // <, >
+
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, true, true, true, true, false, // [, \, ], ^
+
+ true, false, false, false, false, false, false, false, // `
+ false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false,
+ false, false, false, true, true, true, false, true, // {, |, }, DEL
+
+ // non-ASCII
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+ true, true, true, true, true, true, true, true,
+}
+
+// EncodeURL encodes bytes using the URL encoding scheme
+func EncodeURL(b []byte, table [256]bool) []byte {
+ for i := 0; i < len(b); i++ {
+ c := b[i]
+ if table[c] {
+ b = append(b, 0, 0)
+ copy(b[i+3:], b[i+1:])
+ b[i+0] = '%'
+ b[i+1] = "0123456789ABCDEF"[c>>4]
+ b[i+2] = "0123456789ABCDEF"[c&15]
+ }
+ }
+ return b
+}
+
+// DecodeURL decodes an URL encoded using the URL encoding scheme
+func DecodeURL(b []byte) []byte {
+ for i := 0; i < len(b); i++ {
+ if b[i] == '%' && i+2 < len(b) {
+ j := i + 1
+ c := 0
+ for ; j < i+3 && (b[j] >= '0' && b[j] <= '9' || b[j] >= 'a' && b[j] <= 'f' || b[j] >= 'A' && b[j] <= 'F'); j++ {
+ if b[j] <= '9' {
+ c = c<<4 + int(b[j]-'0')
+ } else if b[j] <= 'F' {
+ c = c<<4 + int(b[j]-'A') + 10
+ } else if b[j] <= 'f' {
+ c = c<<4 + int(b[j]-'a') + 10
+ }
+ }
+ if j == i+3 && c < 128 {
+ b[i] = byte(c)
+ b = append(b[:i+1], b[i+3:]...)
+ }
+ } else if b[i] == '+' {
+ b[i] = ' '
+ }
+ }
+ return b
+}