syntax

package
v0.1.0-alpha.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package syntax implements the moejs front end: a hand-written lexer, a recursive-descent parser producing a compact AST, strict-mode early errors, and a scope-resolution pass whose annotations the compiler consumes directly.

Source is always strict-mode ECMAScript. ParseModule parses an ES module; ParseScript parses a strict-mode script for the runtime's RunString helper.

Index

Constants

View Source
const InvalidCooked = "\xff"

InvalidCooked is the Cooked text of a tagged template chunk with an invalid escape, whose cooked value is undefined. The byte 0xFF never occurs in WTF-8.

View Source
const MaxNestingDepth = 10000

MaxNestingDepth bounds the parser's recursion. Every nested statement, function, assignment expression, unary operator, `new`, class or binding pattern costs one unit, so a source-level construct costs one to three (`(` is an assignment expression and a unary operand). Real plugin code nests a few dozen levels; a 1 MB run of `(` used to overflow the Go stack, which is a fatal error that kills the process. The scope pass and the compiler recurse over the tree the parser produced, so the bound covers them as well.

Variables

This section is empty.

Functions

func DecodeWTF8

func DecodeWTF8(s string) []uint16

DecodeWTF8 converts a WTF-8 string (as produced for StringLit.Value and template cooked text) to UTF-16 code units. Lone surrogates round-trip.

func Dump

func Dump(n Node) string

Dump renders a node as an S-expression for golden tests and debugging. Statements are placed on their own lines and indented; expressions are printed inline.

func Inspect

func Inspect(n Node, f func(Node) bool)

Inspect traverses the tree in depth-first source order, calling f for every node. If f returns false the node's children are skipped.

func IsASCII

func IsASCII(s string) bool

IsASCII reports whether every byte of s is below 0x80.

func Walk

func Walk(v Visitor, n Node)

Walk traverses the tree rooted at n in depth-first source order. Nil children (holes, absent else branches) are skipped; non-computed property keys and member names are visited as *Ident nodes.

Types

type ArrayLit

type ArrayLit struct {
	Span
	Elems []Expr
	// contains filtered or unexported fields
}

ArrayLit is an array literal. A nil element is a hole; *SpreadElem elements are spreads.

type ArrayPattern

type ArrayPattern struct {
	Span
	Elems []Pattern
	Rest  Pattern
}

ArrayPattern is [a, , b = 1, ...rest]. A nil element is an elision.

type AssignExpr

type AssignExpr struct {
	Span
	Op          Token
	ParenTarget bool // Target is a parenthesised identifier: not an IdentifierRef, so the value is not named after it
	Target      Pattern
	Value       Expr
}

AssignExpr is `=` or a compound assignment. Target is *Ident, *MemberExpr, or (for `=` only) a destructuring pattern.

type AssignPattern

type AssignPattern struct {
	Span
	Target  Pattern
	Default Expr
}

AssignPattern is Target = Default inside a pattern or parameter list.

type AwaitExpr

type AwaitExpr struct {
	Span
	X Expr
}

AwaitExpr is `await X`.

type BigIntLit

type BigIntLit struct {
	Span
	Digits string
}

BigIntLit is a BigInt literal; Digits is the value in decimal without a sign, leading zeros or separators, or in hex after "0x" for a 0x, 0o or 0b literal too large for 64 bits.

type BinaryExpr

type BinaryExpr struct {
	Span
	Op   Token
	X, Y Expr
}

BinaryExpr is an arithmetic, bitwise, comparison, `in` or `instanceof` expression.

type BindKind

type BindKind uint8

BindKind classifies bindings.

const (
	BindVar      BindKind = iota // var, hoisted to the function/module scope
	BindLet                      // let
	BindConst                    // const
	BindParam                    // formal parameter
	BindFunction                 // function declaration, instantiated at scope entry (see Scope.Funcs)
	BindCatch                    // catch parameter
	BindClass                    // class declaration (the outer, mutable binding)
	BindFuncName                 // name of a named function expression, immutable, visible inside it
	BindImport                   // import binding (unsupported)
	BindPrivate                  // private name "#x" of a class (ScopeClass)
	BindHidden                   // resolver-created binding of the class/super machinery, named "%..."
	BindArgs                     // the function's arguments object (Function.ArgumentsBinding)
)

func (BindKind) IsLexical

func (k BindKind) IsLexical() bool

IsLexical reports whether the binding is a let/const/class binding, which has a temporal dead zone.

func (BindKind) String

func (k BindKind) String() string

type Binding

type Binding struct {
	Name     string
	Kind     BindKind
	Scope    *Scope // declaring scope
	Slot     int    // index in Scope.Bindings
	Pos      int    // position of the (first) declaring identifier
	Captured bool   // referenced from a function nested inside the declaring function
	NeedsTDZ bool   // let/const/class that may be read before initialisation
	Exported bool   // module binding named by an export entry
	// contains filtered or unexported fields
}

Binding is a declared name. Every Ident that declares or references it points here.

type BlockStmt

type BlockStmt struct {
	Span
	Body  []Stmt
	Scope *Scope
}

BlockStmt is `{ ... }`. Scope is nil unless the block declares lexical bindings (let/const/class/function).

type BoolLit

type BoolLit struct {
	Span
	Value bool
}

BoolLit is `true` or `false`.

type BreakStmt

type BreakStmt struct {
	Span
	Label *Ident
}

BreakStmt is break, optionally labelled.

type CallExpr

type CallExpr struct {
	Span
	Callee   Expr
	Args     []Expr // may contain *SpreadElem
	Optional bool
}

CallExpr is a call. Optional marks `f?.()`.

type Class

type Class struct {
	Span
	Name    *Ident
	Super   Expr
	Members []*ClassMember

	// Scope annotations. Scope (kind ScopeClass) holds the inner name
	// binding, one binding per private name (named "#x") and the hidden
	// bindings of the class machinery; the heritage, the computed keys and
	// every member function are resolved inside it.
	Scope         *Scope
	NameBinding   *Binding  // inner immutable class-name binding (named classes)
	Ctor          *Function // the constructor; synthesized (DefaultCtor) when the body has none
	Fields        *Function // FuncClassFields: instance fields and the private-method brand (nil when none)
	Static        *Function // FuncClassStatic: static fields and blocks in order (nil when none)
	FieldsBinding *Binding  // hidden binding holding the Fields closure, read by the constructor
	BrandBinding  *Binding  // hidden binding holding the brand of the instance private methods (nil when none)
}

Class is a class declaration or expression.

type ClassDecl

type ClassDecl struct {
	Span
	Class *Class
}

ClassDecl is a class declaration (unsupported).

type ClassMember

type ClassMember struct {
	Span
	Kind     ClassMemberKind
	Static   bool
	Key      Expr // *Ident, *StringLit, *NumberLit, *BigIntLit, *PrivateName, or computed Expr
	Computed bool
	Value    Expr       // *Function for methods, initializer for fields (may be nil)
	Body     *BlockStmt // static block body

	// Scope annotations. KeyBinding is the hidden binding that carries a
	// computed field key from class definition to the field initializer.
	// Block is a static block's body as an arrow function nested in
	// Class.Static, which gives it its own var scope and the static
	// initializer's this, home object and new.target.
	KeyBinding *Binding
	Block      *Function
}

ClassMember is one entry of a class body.

type ClassMemberKind

type ClassMemberKind uint8

ClassMemberKind classifies class body entries.

const (
	ClassMethod ClassMemberKind = iota
	ClassGetter
	ClassSetter
	ClassField
	ClassStaticBlock
)

type CondExpr

type CondExpr struct {
	Span
	Test, Cons, Alt Expr
}

CondExpr is Test ? Cons : Alt.

type ContinueStmt

type ContinueStmt struct {
	Span
	Label *Ident
}

ContinueStmt is continue, optionally labelled.

type DebuggerStmt

type DebuggerStmt struct{ Span }

DebuggerStmt is `debugger;` (a no-op).

type DeclKind

type DeclKind uint8

DeclKind is var, let or const.

const (
	DeclVar DeclKind = iota
	DeclLet
	DeclConst
)

func (DeclKind) String

func (k DeclKind) String() string

type Declarator

type Declarator struct {
	Span
	Target Pattern
	Init   Expr // may be nil
}

Declarator is one `Target = Init` of a variable declaration.

type DoWhileStmt

type DoWhileStmt struct {
	Span
	Body Stmt
	Cond Expr
}

DoWhileStmt is do/while.

type EmptyStmt

type EmptyStmt struct{ Span }

EmptyStmt is `;`.

type Error

type Error struct {
	Name string // file name given to ParseModule/ParseScript
	Pos  int    // byte offset into the source
	Line int    // 1-based line
	Col  int    // 1-based column in code points
	Msg  string
}

Error is a syntax error with a position. Msg always starts with "SyntaxError: " so that Error() reads like a compiler diagnostic and Message() yields the text a JS SyntaxError object should carry.

func (*Error) Error

func (e *Error) Error() string

Error formats as name:line:col: msg.

func (*Error) Message

func (e *Error) Message() string

Message returns Msg without the "SyntaxError: " prefix.

type ExportAll

type ExportAll struct {
	Span
	As     *Ident
	Source *StringLit
}

ExportAll is `export * [as x] from "..."` (unsupported).

type ExportDecl

type ExportDecl struct {
	Span
	Decl Stmt // *VarDecl, *FuncDecl or *ClassDecl
}

ExportDecl is `export <declaration>`.

type ExportDefault

type ExportDefault struct {
	Span
	Decl Node
}

ExportDefault is `export default ...`. Decl is a *FuncDecl or *ClassDecl for named/anonymous declarations, or an Expr.

type ExportEntry

type ExportEntry struct {
	Name    string   // exported name
	Local   string   // local binding name ("*default*" for an anonymous default export)
	Binding *Binding // module-scope binding
	Pos     int      // position of the export specifier or declaration
}

ExportEntry describes one exported name of a module.

type ExportNamed

type ExportNamed struct {
	Span
	Specs  []*ExportSpec
	Source *StringLit
}

ExportNamed is `export { ... }` optionally `from "..."` (unsupported).

type ExportSpec

type ExportSpec struct {
	Span
	Local    *Ident
	Exported *Ident
}

ExportSpec is `Local as Exported` (Exported may be spelled as a string).

type Expr

type Expr interface {
	Node
	// contains filtered or unexported methods
}

Expr is an expression node.

type ExprStmt

type ExprStmt struct {
	Span
	X Expr
}

ExprStmt is an expression statement.

type File

type File struct {
	Name string
	Src  string
	// contains filtered or unexported fields
}

File is a parsed source text with a line-start table for mapping byte offsets to (line, col).

func (*File) Line

func (f *File) Line(pos int) int

Line returns the 1-based line containing byte offset pos.

func (*File) LineCount

func (f *File) LineCount() int

LineCount returns the number of lines seen by the lexer.

func (*File) Position

func (f *File) Position(pos int) (line, col int)

Position returns the 1-based line and the 1-based column (counted in code points) of byte offset pos, in O(log lines + runeStride).

type ForInOfStmt

type ForInOfStmt struct {
	Span
	Of    bool
	Await bool // for await
	Left  Node
	Right Expr
	Body  Stmt
	Scope *Scope
}

ForInOfStmt is for-in (Of == false) or for-of. Left is a *VarDecl with a single initializer-less declarator, or a Pattern. Scope is nil unless Left is a let/const declaration.

type ForStmt

type ForStmt struct {
	Span
	Init   Node
	Cond   Expr
	Update Expr
	Body   Stmt
	Scope  *Scope
}

ForStmt is the classic for loop. Init is nil, *VarDecl or an Expr. Scope is nil unless Init is a let/const declaration.

type FuncDecl

type FuncDecl struct {
	Span
	Func *Function
}

FuncDecl is a function declaration in statement position.

type FuncKind

type FuncKind uint8

FuncKind distinguishes the syntactic forms of a function.

const (
	FuncNormal FuncKind = iota
	FuncArrow
	FuncMethod
	FuncGetter
	FuncSetter
	FuncClassConstructor
	// FuncClassFields and FuncClassStatic are the synthetic methods the
	// resolver creates to run a class's instance field initializers and its
	// static fields and blocks (Class.Fields, Class.Static). They have no
	// source of their own and no Body.
	FuncClassFields
	FuncClassStatic
)

type Function

type Function struct {
	Span
	Name        *Ident // nil when anonymous
	Params      []Pattern
	Rest        Pattern    // rest parameter target or nil
	Body        *BlockStmt // nil for a concise arrow body
	ExprBody    Expr       // concise arrow body
	Kind        FuncKind
	IsArrow     bool
	IsAsync     bool
	IsGenerator bool
	IsStrict    bool // always true (strict mode only)

	// Scope annotations.
	Scope           *Scope // parameters, var declarations and body-level lexical declarations (Body.Scope when kept apart)
	SelfBinding     *Binding
	UsesThis        bool // `this` (or super/new.target) appears in the body or in a nested arrow
	UsesArguments   bool // `arguments` appears in the body or in a nested arrow
	HasDirectEval   bool // a call to an unresolved `eval` appears (unsupported)
	ParamCount      int  // formal parameters excluding rest
	Length          int  // ES `length`: formals before the first default or rest
	HasSimpleParams bool // every formal is a plain identifier without default; no rest
	HasRest         bool

	// Class, super and new.target annotations. The hidden bindings live in
	// the function scope (registers or captured slots like any binding) and
	// are nil when unused.
	Derived          bool     // constructor of a class with an extends clause
	DefaultCtor      bool     // constructor synthesized for a class without one
	ThisBinding      *Binding // derived constructor: `this`, in TDZ until super() returns
	CalleeBinding    *Binding // derived constructor: the active function, read by super()
	NewTargetBinding *Binding // new.target, used here or in a nested arrow
	HomeBinding      *Binding // [[HomeObject]], for super property access here or in a nested arrow
}

Function is any function: declaration body, expression, arrow or method. FuncDecl wraps it in statement position. Span covers the whole source text from the first token (`function`, `async`, the method name or the arrow parameters) to the end of the body, for Function.prototype.toString.

func (*Function) ArgumentsBinding

func (fn *Function) ArgumentsBinding() *Binding

ArgumentsBinding returns the binding of the function's own arguments object (BindArgs, declared in Scope), nil when nothing references it. Arrows have none: their `arguments` is the enclosing function's. Strict code declares nothing else named arguments.

type Ident

type Ident struct {
	Span
	Name    string
	Binding *Binding
}

Ident is an identifier. In reference position the scope pass fills Binding (nil means global/unresolvable). In binding position (declarations, parameters, patterns) Binding is the binding it declares. Non-computed property keys and member names are also Idents but are never resolved.

func BoundNames

func BoundNames(pat Pattern) []*Ident

BoundNames returns the identifiers bound by a pattern in source order.

type IfStmt

type IfStmt struct {
	Span
	Cond Expr
	Then Stmt
	Else Stmt // may be nil
}

IfStmt is if/else.

type ImportCall

type ImportCall struct {
	Span
	Source Expr
}

ImportCall is a dynamic `import(x)` (not supported yet).

type ImportDecl

type ImportDecl struct {
	Span
	Default   *Ident
	Namespace *Ident
	Specs     []*ImportSpec
	Source    *StringLit
}

ImportDecl is an import declaration (unsupported).

type ImportMeta

type ImportMeta struct{ Span }

ImportMeta is `import.meta` (not supported yet).

type ImportSpec

type ImportSpec struct {
	Span
	Imported *Ident
	Local    *Ident
}

ImportSpec is `Imported as Local`.

type LabeledStmt

type LabeledStmt struct {
	Span
	Label *Ident
	Body  Stmt
}

LabeledStmt is `Label: Body`.

type LogicalExpr

type LogicalExpr struct {
	Span
	Op   Token
	X, Y Expr
	// contains filtered or unexported fields
}

LogicalExpr is && || ??; Y is evaluated conditionally.

type MemberExpr

type MemberExpr struct {
	Span
	Object   Expr
	Prop     Expr
	Computed bool
	Optional bool
}

MemberExpr is property access. Prop is an *Ident (never resolved) or a *PrivateName when !Computed. Optional marks `a?.b`.

type Module

type Module struct {
	Program
	// Exports lists every export entry in source order. Filled by the scope
	// pass; Binding is the module-scope binding the export reads.
	Exports []*ExportEntry
	// Async is set by the scope pass when the body awaits outside any
	// function (top-level await): the module evaluates asynchronously.
	Async bool
}

Module is a parsed ES module.

func ParseModule

func ParseModule(name, src string, opts Options) (*Module, error)

ParseModule parses src as a strict-mode ES module, runs the early-error and scope-resolution passes, and returns the annotated tree. The error, when non-nil, is always a *Error.

func (*Module) Export

func (m *Module) Export(name string) *Binding

Export returns the binding exported under name, or nil.

type NewExpr

type NewExpr struct {
	Span
	Callee Expr
	Args   []Expr
}

NewExpr is `new Callee(Args)`.

type NewTarget

type NewTarget struct {
	Span
	Binding *Binding
}

NewTarget is `new.target`. Binding is the enclosing non-arrow function's Function.NewTargetBinding.

type Node

type Node interface {
	Range() (pos, end int)
}

Node is any AST node.

type NullLit

type NullLit struct{ Span }

NullLit is `null`.

type NumberLit

type NumberLit struct {
	Span
	Value float64
}

NumberLit is a numeric literal. Legacy octal forms are rejected by the lexer, so Value is always the exact ES mathematical value.

type ObjectLit

type ObjectLit struct {
	Span
	Props []*Property
	// contains filtered or unexported fields
}

ObjectLit is an object literal.

type ObjectPattern

type ObjectPattern struct {
	Span
	Props []*PatternProp
	Rest  Pattern // *Ident or (assignment only) *MemberExpr, or nil
}

ObjectPattern is { a, b: c, ...rest }.

type OptChain

type OptChain struct {
	Span
	X Expr // *MemberExpr or *CallExpr
}

OptChain wraps the whole of an optional chain `a?.b.c()`; when any Optional link short-circuits, the value of the OptChain is undefined.

type Options

type Options struct {
	// AllowUnsupported keeps the parser from rejecting syntax the engine
	// does not implement yet (generators, async, ...). The AST is still
	// produced, so supporting a feature lifts its restriction rather than
	// touching the parser.
	AllowUnsupported bool
}

Options controls parsing.

type Pattern

type Pattern interface {
	Node
	// contains filtered or unexported methods
}

Pattern is a binding or assignment target: *Ident, *MemberExpr (assignment targets only), *ObjectPattern, *ArrayPattern or *AssignPattern.

type PatternProp

type PatternProp struct {
	Span
	Key      Expr // as Property.Key
	Computed bool
	Value    Pattern
}

PatternProp is one entry of an object pattern.

type PrivateName

type PrivateName struct {
	Span
	Name    string // without '#'
	Binding *Binding
}

PrivateName is `#x` in a member, `#x in o` or class element position. Binding is the class-scope binding of the private name (named "#x").

type Program

type Program struct {
	Span
	File  *File
	Body  []Stmt
	Scope *Scope // module or script scope; filled by the scope pass
}

Program is the shared body of Module and Script.

type PropKind

type PropKind uint8

PropKind classifies object literal properties.

const (
	PropInit      PropKind = iota // key: value
	PropShorthand                 // { x }
	PropCoverInit                 // { x = 1 } cover grammar; only valid once converted to a pattern
	PropMethod                    // f() {}
	PropGetter                    // get f() {}
	PropSetter                    // set f(v) {}
	PropSpread                    // ...expr
)

type Property

type Property struct {
	Span
	Kind     PropKind
	Key      Expr // *Ident, *StringLit, *NumberLit, *BigIntLit, or any Expr when Computed; nil for PropSpread
	Computed bool
	Value    Expr // value, method *Function, spread operand, or cover default
}

Property is one object literal entry.

type RegexLit

type RegexLit struct {
	Span
	Pattern string
	Flags   string
}

RegexLit is a regular expression literal. Flags are validated for the set dgimsuvy without duplicates (u and v exclusive) and the pattern by internal/regexpsyntax.

type ReturnStmt

type ReturnStmt struct {
	Span
	Result Expr // may be nil
}

ReturnStmt is return.

type Scope

type Scope struct {
	Kind ScopeKind

	Parent   *Scope
	Func     *Function // enclosing function; nil at module/script level
	Node     Node      // owning node: *Module, *Script, *Function, *BlockStmt, *SwitchStmt, *TryStmt, *ForStmt, *ForInOfStmt, *Class
	Bindings []*Binding
	Funcs    []*FuncDecl // hoisted function declarations to instantiate on entry, in source order
	Children []*Scope
	// contains filtered or unexported fields
}

Scope is a node of the scope tree.

func (*Scope) Lookup

func (s *Scope) Lookup(name string) *Binding

Lookup finds a binding declared directly in s.

func (*Scope) Resolve

func (s *Scope) Resolve(name string) *Binding

Resolve finds the nearest binding for name in s or its ancestors.

type ScopeKind

type ScopeKind uint8

ScopeKind classifies scopes.

const (
	ScopeModule   ScopeKind = iota // module top level
	ScopeScript                    // strict-mode script top level
	ScopeFunction                  // parameters, var declarations and body-level lexical declarations
	ScopeBlock                     // block or switch case block with lexical declarations
	ScopeCatch                     // catch parameter
	ScopeFor                       // for/for-in/for-of head with let/const
	ScopeClass                     // class body: inner name, private names and hidden class bindings
)

func (ScopeKind) String

func (k ScopeKind) String() string

type Script

type Script struct {
	Program
}

Script is a parsed strict-mode script.

func ParseScript

func ParseScript(name, src string, opts Options) (*Script, error)

ParseScript parses src as a strict-mode script (the runtime's RunString input). Import and export declarations are rejected.

type SeqExpr

type SeqExpr struct {
	Span
	Exprs []Expr
}

SeqExpr is the comma operator.

type Span

type Span struct {
	Pos, End int
}

Span is the half-open byte range [Pos, End) of a node in the source. Every node embeds it; File.Position maps offsets to (line, col).

func (Span) Range

func (s Span) Range() (pos, end int)

Range returns the byte range of the node.

type SpreadElem

type SpreadElem struct {
	Span
	X Expr
}

SpreadElem is `...X` in an array literal or argument list.

type Stmt

type Stmt interface {
	Node
	// contains filtered or unexported methods
}

Stmt is a statement or declaration node.

type StringLit

type StringLit struct {
	Span
	Value string
}

StringLit is a string literal. Value is the cooked text in WTF-8 (see wtf8.go): UTF-8, except that lone surrogates written as escapes are encoded as three-byte sequences so that DecodeWTF8 recovers the exact UTF-16 code units.

type SuperExpr

type SuperExpr struct{ Span }

SuperExpr is `super` in a SuperCall `super(args)` or a SuperProperty `super.x` / `super[x]` (the parser rejects any other use).

type SwitchCase

type SwitchCase struct {
	Span
	Test Expr
	Body []Stmt
}

SwitchCase is one case (Test == nil for default).

type SwitchStmt

type SwitchStmt struct {
	Span
	Disc  Expr
	Cases []*SwitchCase
	Scope *Scope
}

SwitchStmt is switch. Scope is nil unless the case block declares lexical bindings; such bindings always need TDZ checks.

type TaggedTemplate

type TaggedTemplate struct {
	Span
	Tag   Expr
	Quasi *TemplateLit
}

TaggedTemplate is tag`...`.

type TemplateElement

type TemplateElement struct {
	Span
	Cooked string // WTF-8 cooked text, or InvalidCooked
	Raw    string // raw text with CR/CRLF normalised to LF
}

TemplateElement is one text chunk of a template literal.

type TemplateLit

type TemplateLit struct {
	Span
	Quasis []TemplateElement
	Exprs  []Expr
}

TemplateLit is an untagged template literal. len(Quasis) == len(Exprs)+1.

type ThisExpr

type ThisExpr struct {
	Span
	Binding *Binding
}

ThisExpr is `this`. Binding is set in a derived class constructor (and the arrows nested in it), where `this` is the constructor's Function.ThisBinding; nil means the ordinary this value.

type ThrowStmt

type ThrowStmt struct {
	Span
	X Expr
}

ThrowStmt is throw.

type Token

type Token uint8

Token is a lexical token kind. Punctuators and keywords each have their own kind so the parser switches on small integers rather than comparing text.

const (
	EOF Token = iota
	Illegal

	// Punctuators.
	LBrace      // {
	RBrace      // }
	LParen      // (
	RParen      // )
	LBrack      // [
	RBrack      // ]
	Dot         // .
	Ellipsis    // ...
	Semicolon   // ;
	Comma       // ,
	Lt          // <
	Gt          // >
	LtEq        // <=
	GtEq        // >=
	Eq          // ==
	NotEq       // !=
	StrictEq    // ===
	StrictNeq   // !==
	Plus        // +
	Minus       // -
	Mul         // *
	Div         // /
	Rem         // %
	Exp         // **
	Inc         // ++
	Dec         // --
	Shl         // <<
	Shr         // >>
	UShr        // >>>
	BitAnd      // &
	BitOr       // |
	BitXor      // ^
	Not         // !
	BitNot      // ~
	LogAnd      // &&
	LogOr       // ||
	Nullish     // ??
	Question    // ?
	QuestionDot // ?.
	Colon       // :
	Assign      // =
	AddAssign   // +=
	SubAssign   // -=
	MulAssign   // *=
	DivAssign   // /=
	RemAssign   // %=
	ExpAssign   // **=
	ShlAssign   // <<=
	ShrAssign   // >>=
	UShrAssign  // >>>=
	AndAssign   // &=
	OrAssign    // |=
	XorAssign   // ^=
	LogAndAssign
	LogOrAssign
	NullishAssign
	Arrow // =>
	Hash  // # (private names, unsupported but tokenised for a clear error)

	// Literals and names.
	Identifier
	PrivateIdent
	EscapedWord // a reserved word spelled with \u escapes: only an IdentifierName
	Number
	BigInt
	String
	Template // a template chunk; see Lexer.template
	Regex

	KwAwait
	KwBreak
	KwCase
	KwCatch
	KwClass
	KwConst
	KwContinue
	KwDebugger
	KwDefault
	KwDelete
	KwDo
	KwElse
	KwEnum
	KwExport
	KwExtends
	KwFalse
	KwFinally
	KwFor
	KwFunction
	KwIf
	KwImport
	KwIn
	KwInstanceof
	KwNew
	KwNull
	KwReturn
	KwSuper
	KwSwitch
	KwThis
	KwThrow
	KwTrue
	KwTry
	KwTypeof
	KwVar
	KwVoid
	KwWhile
	KwWith
	KwYield
	// Strict-mode future reserved words.
	KwImplements
	KwInterface
	KwLet
	KwPackage
	KwPrivate
	KwProtected
	KwPublic
	KwStatic
)

Token kinds. The order groups punctuators, then literals, then keywords so that IsKeyword is a range check.

func (Token) IsKeyword

func (t Token) IsKeyword() bool

IsKeyword reports whether t is spelled like an identifier but reserved in strict mode (including the strict-mode future reserved words and `let`, `await`, `yield`).

func (Token) String

func (t Token) String() string

String returns the spelling of punctuators and keywords and a description for the other kinds.

type TryStmt

type TryStmt struct {
	Span
	Block      *BlockStmt
	Param      Pattern
	Handler    *BlockStmt
	Finalizer  *BlockStmt
	CatchScope *Scope
}

TryStmt is try/catch/finally. Param is nil for `catch {` or when there is no catch clause; CatchScope holds the catch parameter bindings.

type UnaryExpr

type UnaryExpr struct {
	Span
	Op Token
	X  Expr
}

UnaryExpr is a prefix operator: ! ~ - + typeof void delete.

type UpdateExpr

type UpdateExpr struct {
	Span
	Op     Token // Inc or Dec
	Prefix bool
	X      Expr // *Ident or *MemberExpr
}

UpdateExpr is ++ or -- in prefix or postfix form.

type VarDecl

type VarDecl struct {
	Span
	Kind  DeclKind
	Decls []*Declarator
}

VarDecl is a var/let/const declaration.

type Visitor

type Visitor interface {
	Visit(n Node) Visitor
}

Visitor is called by Walk for each node; the returned visitor is used for the node's children, and a nil result skips them (as in go/ast).

type WhileStmt

type WhileStmt struct {
	Span
	Cond Expr
	Body Stmt
}

WhileStmt is while.

type YieldExpr

type YieldExpr struct {
	Span
	X        Expr // may be nil
	Delegate bool
}

YieldExpr is `yield X` or `yield* X`.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL