syntax

package
v0.1.0-alpha.6 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

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

ParseModule parses an ES module, which is always strict mode code. ParseScript parses a script, which is sloppy mode code unless its directive prologue says "use strict"; a function with its own "use strict" directive and every class body are strict.

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, a sloppy *CallExpr (not for logical assignment; it throws after the call) 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                   // named or default import binding: immutable, reads the exporter's binding
	BindImportNS                 // import * as binding: immutable, holds the module namespace object
	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
	// AnnexB marks, on the binding of a block-level function declaration of
	// sloppy code, that evaluating the declaration also assigns the var
	// binding of the same name in the enclosing function or script scope
	// (Annex B.3.2); on a script-scope var binding, that only such
	// declarations create it.
	AnnexB bool
	// 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 Eval

type Eval struct {
	Program
	// Strict marks strict eval code; Module marks eval code called in
	// module code; HasDirectEval marks code with a direct eval call, at any
	// depth.
	Strict, Module, HasDirectEval bool
	Func                          *Function
	// Env is the environment the code was resolved against. Levels are the
	// scopes of its levels, innermost first, holding the bindings the code
	// may look up: every one is Captured, its Slot the environment slot.
	Env    *EvalEnv
	Levels []*Scope
	// This is the synthetic function standing for the caller's function of
	// EvalEnv.This (nil at the top level): its hidden bindings are those of
	// the levels. FieldsBinding is the class's %fields binding for a derived
	// constructor.
	This          *Function
	FieldsBinding *Binding
	// The declarations of sloppy eval code in its caller's variable
	// environment (EvalDeclarationInstantiation): the var names, the
	// top-level functions to instantiate (the last declaration of each name,
	// in source order) and the names only Annex B.3.2.3 block functions
	// declare. They have no binding in Scope, and their references resolve
	// dynamically through the %evalvars object (or the global object).
	Vars   []string
	Funcs  []*FuncDecl
	AnnexB []string
}

Eval is parsed and resolved eval code. Its body is the body of Func, a synthetic arrow function whose scope (Scope) is the eval code's lexical environment and, for strict code, its variable environment.

func ParseEval

func ParseEval(name, src string, env *EvalEnv, opts Options) (*Eval, error)

ParseEval parses and resolves the eval code src named name (the referrer) for a direct eval call site described by env, or an indirect eval when env is nil. Eval code is a Script: return is not allowed, await is an identifier, HTML-like comments are allowed. It is strict when the caller is or when it has a "use strict" directive.

type EvalEnv

type EvalEnv struct {
	// Levels are the scopes with a closure environment, innermost first.
	Levels []EvalLevel
	// Var is the level of the caller's variable environment (the scope
	// holding %evalvars), -1 for the global one. This is the outermost level
	// of the function supplying this (-1 outside any function), Fields the
	// level of the %fields binding a derived constructor's super() reads
	// (-1 when there is none).
	Var, This, Fields int
	// FuncKind is the kind of the function supplying this; Derived marks a
	// derived class constructor.
	FuncKind FuncKind
	Derived  bool
	// Strict is the strictness of the calling code; InParams marks a call
	// in the parameter list of a sloppy function with parameter expressions,
	// whose variable environment is outside the parameters; Module marks a
	// call in module code.
	Strict, InParams, Module bool
}

EvalEnv describes the environment of a direct eval call site for ParseEval, as recorded by the compiler (see bytecode.EvalScope, which holds the same data untyped).

type EvalLevel

type EvalLevel interface {
	// Kind is the kind of the scope owning the environment; Len is the
	// number of its slots.
	Kind() ScopeKind
	Len() int
	// Slot returns the slot of the binding named name, or -1 when there is
	// none.
	Slot(name string) int
	// Binding describes slot i: its binding's name ("" for a slot without
	// one), kind and whether it has a TDZ.
	Binding(i int) (name string, kind BindKind, tdz bool)
}

EvalLevel is one level of an EvalEnv: a closure environment, whose slots are named by the bindings owning them. ParseEval looks up the names the eval code uses rather than reading every slot, so that small eval code is cheap next to a large environment.

type ExportAll

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

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

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 "..."`.

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 declarator, or a Pattern. The declarator has no initializer, except a sloppy `for (var x = init in o)` (Annex B). 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 // strict mode code: a class member, inside strict code, or with its own "use strict"

	// 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 direct eval call appears in the function or a function nested in it
	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.

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)`.

type ImportDecl

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

ImportDecl is an import declaration.

type ImportEntry

type ImportEntry struct {
	Request   int      // index in Module.Requests
	Name      string   // imported export name (unset for a namespace import)
	Namespace bool     // import * as Local: the binding is the module namespace object
	Binding   *Binding // local binding (BindImport, or BindImportNS for a namespace import)
	Pos       int      // position of the import specifier
}

ImportEntry binds a local name to an export of a requested module.

type ImportMeta

type ImportMeta struct{ Span }

ImportMeta is `import.meta`, only in module code.

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 local export entry in source order. Filled by the
	// scope pass; Binding is the module-scope binding the export reads.
	Exports []*ExportEntry
	// Requests lists the specifiers of the modules this module requests,
	// each once, in source order. Imports, Reexports and Stars refer to
	// them by index. All four are filled by the scope pass and are empty
	// for a module without import declarations or export ... from.
	Requests  []*ModuleRequest
	Imports   []*ImportEntry
	Reexports []*ReexportEntry
	Stars     []*StarExport
	// Async is set by the scope pass when the body awaits outside any
	// function (top-level await): the module evaluates asynchronously.
	// HasDirectEval is set by the scope pass when a direct eval call
	// appears in the module's code, at any depth.
	Async, HasDirectEval bool
	// contains filtered or unexported fields
}

Module is a parsed ES module.

func ParseModule

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

ParseModule parses src as an ES module (always strict mode code), runs the early-error and scope-resolution passes, and returns the annotated tree. The error, when non-nil, is a *Error, or the error Options.Stop returned.

func (*Module) Export

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

Export returns the binding exported under name, or nil.

type ModuleRequest

type ModuleRequest struct {
	Specifier string // WTF-8 value of the string literal
	Pos       int    // position of its first occurrence
}

ModuleRequest is a requested module specifier.

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, so supporting a feature lifts its restriction
	// rather than touching the parser. No feature is deferred this way at
	// present (the proposals TestUnsupportedModuleSyntax lists fail
	// whatever the options); the option stays for the next one.
	AllowUnsupported bool
	// EarlyExports counts every exported function of a module as called
	// before the module's body runs, so the lexical bindings they read are
	// checked. A module that imports others always is; the linker asks for
	// this variant of an import-free module only when an import cycle can
	// call into it before its body ran (engine.LinkOptions.EarlyExports).
	EarlyExports bool
	// TypeScript makes ParseModule read TypeScript, whose type syntax it
	// erases: the tree is the one the type-erased JavaScript gives, with
	// every position in the TypeScript text. Import specifiers used only as
	// types are dropped, and TypeScript with run-time semantics (enums,
	// namespaces with values, parameter properties, import = require,
	// export =) is a syntax error. ParseScript rejects it: TypeScript code
	// is a module here.
	TypeScript bool
	// Stop, when set, is called before every stopEvery-th statement of each
	// statement list the parser and the resolver go through, the first
	// included: an error it returns ends the parse, which returns that error
	// rather than a *Error. The engine passes one that reports an interrupt,
	// so that one can stop a long compile of code from a string
	// (engine.Compiler); a host compile has none and pays nothing for it.
	Stop func() error
}

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 ReexportEntry

type ReexportEntry struct {
	Name    string // exported name
	Request int    // index in Module.Requests
	Import  string // imported export name (unset when All)
	All     bool   // export * as Name from: the requested module's namespace object
	Pos     int
}

ReexportEntry exports a name of a requested module without a local binding: export {x as y} from, export * as y from (All), and export {y} of an import binding (All for a namespace import).

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, *WithStmt
	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                    // script top level: its declarations are global (see CompileScript)
	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
	ScopeWith                      // with statement body: its one hidden binding holds the object
)

func (ScopeKind) String

func (k ScopeKind) String() string

type Script

type Script struct {
	Program
	Strict, HasDirectEval bool
}

Script is a parsed script. Strict is set when its directive prologue holds a "use strict" directive; otherwise it is sloppy-mode code. HasDirectEval is set by the scope pass when a direct eval call appears in the script's code, at any depth.

func ParseScript

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

ParseScript parses src as a script: sloppy mode code unless its directive prologue holds a "use strict" directive (Script.Strict). Import and export declarations are rejected; HTML-like comments are recognised.

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 StarExport

type StarExport struct {
	Request int // index in Module.Requests
	Pos     int
}

StarExport is export * from: every name of the requested module except default.

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
}

UpdateExpr is ++ or -- in prefix or postfix form. X is *Ident, *MemberExpr or a sloppy *CallExpr (which throws after the call).

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 WithStmt

type WithStmt struct {
	Span
	Object Expr
	Body   Stmt
	Scope  *Scope
}

WithStmt is `with (Object) Body` (sloppy code only). Scope holds the hidden binding of the object environment the body's names consult.

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