syntax

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package syntax implements a lossless, error-tolerant, version-aware PHP lexer and parser (PHP 5.3 – 8.5).

The token stream covers the source contiguously (trivia included), so any byte range can be edited precisely and every node maps back to exact bytes.

Index

Constants

View Source
const MaxDepth = 4000

MaxDepth bounds syntax nesting (parser recursion and AST depth). Real code stays far below it; deeper input is reported and not analyzed, so that no recursive consumer can overflow the stack.

View Source
const MaxErrors = 1000

MaxErrors caps the syntax errors reported for one file.

View Source
const MaxFileSize = 10 << 20

MaxFileSize is the largest source analyzed (bytes); larger files get one error and an empty tree.

Variables

MirroredComparison maps an ordering comparison to the one that holds with its operands swapped (`a < b` is `b > a`).

Functions

func Children

func Children(n Node, fn func(Node))

Children calls fn for each direct child of n, in source order. Nil children are skipped.

func Endless

func Endless(n Node) bool

Endless reports a loop that control never falls out of, wherever it entered it: `while (true)`, `for (;;)` or `do … while (true)` without a `break` or `goto` that leaves it. The search for those jumps is cached on the loop, so that asking for every label of a long body stays linear overall.

func Escapes

func Escapes(loop Node) bool

Escapes reports whether a loop can be left other than by its condition turning false: a `break` that leaves it, or a `goto` to a label outside it. Past a loop that does not escape, its condition is known to be false.

func ExitInvocation

func ExitInvocation(e Expr) bool

ExitInvocation reports a direct exit/die call, including an immediate invocation of its first-class callable. Creating a callable does not exit.

func ExitInvokes

func ExitInvokes(n *Exit) bool

ExitInvokes reports whether evaluating exit/die calls the function rather than producing its first-class callable.

func FirstTerminating

func FirstTerminating(p Node) int

FirstTerminating returns the index of the first statement of the list owned by p (*File, *Block, *Case or *Namespace) that Terminates, or the list length when none does (also for other nodes: 0). The result is cached on the node, so callers asking "does a statement before index i terminate?" for many i stay linear overall instead of quadratic on long lists.

func Inspect

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

Inspect walks the tree depth-first in source order. If fn returns false the node's children are skipped.

func InspectFile

func InspectFile(f *File, fn func(Node) bool)

InspectFile walks every top-level statement of f.

func IsFuncLike

func IsFuncLike(n Node) bool

IsFuncLike reports whether n is a function, method, closure, arrow function or property hook.

func IsNullConst

func IsNullConst(e Expr) bool

IsNullConst reports whether e is the constant null (any case, optionally `\`-qualified). Parentheses are not looked through.

func IsVariableScope

func IsVariableScope(n Node) bool

IsVariableScope reports whether n owns local variables. Property hooks own locals independently of their class or promoting constructor.

func Lex

func Lex(src []byte, opt LexOptions) ([]Token, []LexError)

Lex tokenizes src. The returned tokens cover src contiguously.

func LiteralArrayKey

func LiteralArrayKey(x Expr) (string, bool)

LiteralArrayKey returns the canonical array key of a literal key expression (integer or plain string literal, optionally negated): "0", "-1", "name".

func LiteralStringValue

func LiteralStringValue(literal *Literal) (string, bool)

LiteralStringValue decodes a parsed, noninterpolated string, including a complete heredoc or nowdoc. Its owning file supplies the PHP version.

func LiteralStringValueForVersion

func LiteralStringValueForVersion(literal *Literal, version phpversion.Version) (string, bool)

LiteralStringValueForVersion is LiteralStringValue under the escape rules of the given PHP version (zero for the latest).

func MinVersion

func MinVersion(n Node) phpversion.Version

MinVersion returns the minimum supported PHP version for selected modern syntax features. Other nodes return the engine's baseline version. This is feature metadata; it does not change parsing or emit compatibility reports.

func PlainStringLiteral

func PlainStringLiteral(raw string) (string, bool)

PlainStringLiteral decodes a quoted string literal without escapes that need interpretation beyond `\\` and `\'` in single quotes. Narrower than StringLiteralValue on purpose: a double-quoted key with escapes or `$` is not given a shape key.

func ScopeMemo

func ScopeMemo[T any](scope Node, build func(scope Node) *T) *T

ScopeMemo returns what build makes of a variable scope with a block body, kept on that body so that it is made once per scope; nil for another scope. One caller owns the slot: every call must ask for the same type.

func SetParents

func SetParents(f *File)

SetParents links every node to its parent (top-level statements have a file as parent). It also moves parent span starts back to cover their children, which only matters for zero-width nodes created by error recovery. Ends need no widening: a parser node ends at the last consumed token, after all its children were parsed (lastEnd never decreases).

func SourceVersion

func SourceVersion(node Node) phpversion.Version

SourceVersion returns the parser version of a node's owning file. Detached nodes and files without an explicit version use the latest supported PHP.

func StmtIndex

func StmtIndex(list []Stmt, s Node) int

StmtIndex returns the index of s in list, or -1. Statement lists are in source order, so the lookup is a binary search on the start offset (O(log n)) with a linear fallback should the order assumption ever fail for a statement whose parent owns the list.

func StrictTypes

func StrictTypes(f *File) bool

StrictTypes reports whether f declares `strict_types=1`. PHP only accepts the directive as the file's first statement with a literal 0 or 1, and matches its name case-insensitively.

func StringLiteralValue

func StringLiteralValue(raw string) (val string, ok bool)

StringLiteralValue decodes a quoted PHP string literal without interpolation. Heredoc, nowdoc and non-string source return false.

func StringLiteralValueForVersion

func StringLiteralValueForVersion(raw string, version phpversion.Version) (val string, ok bool)

StringLiteralValueForVersion decodes quoted strings using the selected PHP escape rules. Version zero selects the latest supported version.

func Superglobal

func Superglobal(name string) bool

Superglobal reports whether name (without '$') is one of PHP's superglobal arrays, visible in every scope without a `global` statement.

func Terminates

func Terminates(s Stmt) bool

Terminates reports whether control never falls through s to the next statement of its list: return, throw, exit/die, break, continue, goto, blocks containing such a statement, if/else chains (with an else) whose every branch terminates, try statements whose body and catches all terminate (or whose finally terminates), switches with a default where every case ends abruptly without break, and infinite loops (`while (true)`, `for (;;)`, `do … while (true)`) without break.

func TreeDepth

func TreeDepth(stmts []Stmt) int

TreeDepth returns the maximum node depth of the given statements. The walk stops descending as soon as MaxDepth is exceeded, so its recursion is bounded (MaxDepth+1 levels) and safe on arbitrarily deep trees; unlike an explicit stack it allocates nothing per node (an explicit stack of every pending sibling cost ~1 GB of allocations on a 3 MB file of 1M top-level statements).

Types

type Arg

type Arg struct {
	Name   *Identifier // named argument (8.0), or nil
	Value  Expr
	ByRef  bool // legacy call-time pass-by-reference
	Unpack bool // ...$args
	// contains filtered or unexported fields
}

Arg is a call argument.

func (*Arg) Kind

func (*Arg) Kind() NodeKind

type ArgList

type ArgList struct {
	Args []Expr // *Arg or *VariadicPlaceholder
	// contains filtered or unexported fields
}

ArgList is a parenthesised argument list.

func (*ArgList) Kind

func (*ArgList) Kind() NodeKind

type Array

type Array struct {
	Items []*ArrayItem // nil entries for empty slots
	Short bool
	// contains filtered or unexported fields
}

Array is array(...) or [...] (also used for [..] destructuring targets).

func (*Array) Kind

func (*Array) Kind() NodeKind

type ArrayDimFetch

type ArrayDimFetch struct {
	Var   Expr
	Dim   Expr // nil for $a[]
	Curly bool // legacy $a{0}
	// contains filtered or unexported fields
}

func (*ArrayDimFetch) Kind

func (*ArrayDimFetch) Kind() NodeKind

type ArrayItem

type ArrayItem struct {
	Key    Expr
	Value  Expr // nil for skipped list() slots
	ByRef  bool
	Unpack bool
	// contains filtered or unexported fields
}

ArrayItem is one element of an array literal or list().

func (*ArrayItem) Kind

func (*ArrayItem) Kind() NodeKind

type ArrowFunction

type ArrowFunction struct {
	Attrs      []*AttributeGroup
	Static     bool
	ByRef      bool
	Params     []*Param
	ReturnType Expr
	Expr       Expr
	// contains filtered or unexported fields
}

func (*ArrowFunction) Kind

func (*ArrowFunction) Kind() NodeKind

type Assign

type Assign struct {
	Var   Expr
	Op    TokenRef // '=' or compound operator
	Value Expr
	ByRef bool // $a = &$b
	// contains filtered or unexported fields
}

func (*Assign) Kind

func (*Assign) Kind() NodeKind

type Attribute

type Attribute struct {
	Name *Name
	Args *ArgList
	// contains filtered or unexported fields
}

func (*Attribute) Kind

func (*Attribute) Kind() NodeKind

type AttributeGroup

type AttributeGroup struct {
	Attrs []*Attribute
	// contains filtered or unexported fields
}

func (*AttributeGroup) Kind

func (*AttributeGroup) Kind() NodeKind

type BadExpr

type BadExpr struct {
	// contains filtered or unexported fields
}

BadExpr marks a region that failed to parse.

func (*BadExpr) Kind

func (*BadExpr) Kind() NodeKind

type BadStmt

type BadStmt struct {
	// contains filtered or unexported fields
}

BadStmt marks a region that failed to parse.

func (*BadStmt) Kind

func (*BadStmt) Kind() NodeKind

type Binary

type Binary struct {
	Left  Expr
	Op    TokenRef
	Right Expr
	// contains filtered or unexported fields
}

func (*Binary) Kind

func (*Binary) Kind() NodeKind

type Block

type Block struct {
	Stmts []Stmt
	Alt   bool
	// contains filtered or unexported fields
}

Block is { ... } or, for alternative syntax, the statement list between ':' and the end keyword (Alt = true).

func FuncLikeBody

func FuncLikeBody(n Node) *Block

FuncLikeBody returns the braced body of a function-like (nil for arrow functions, expression hooks and abstract declarations).

func (*Block) Kind

func (*Block) Kind() NodeKind

type Break

type Break struct {
	Num Expr
	// contains filtered or unexported fields
}

func (*Break) Kind

func (*Break) Kind() NodeKind

type Case

type Case struct {
	Cond  Expr // nil for default
	Stmts []Stmt
	// contains filtered or unexported fields
}

func (*Case) Kind

func (*Case) Kind() NodeKind

type Catch

type Catch struct {
	Types []*Name
	Var   *Variable // nil since 8.0 allowed
	Body  *Block
	// contains filtered or unexported fields
}

func (*Catch) Kind

func (*Catch) Kind() NodeKind

type ClassConst

type ClassConst struct {
	Attrs     []*AttributeGroup
	Modifiers Modifiers
	Type      Expr // typed class constants (8.3)
	Consts    []*ConstItem
	// contains filtered or unexported fields
}

func (*ClassConst) Kind

func (*ClassConst) Kind() NodeKind

type ClassConstFetch

type ClassConstFetch struct {
	Class Expr // *Name or expression
	Name  Expr // *Identifier (or expression for ::{expr}, 8.3)
	// contains filtered or unexported fields
}

func (*ClassConstFetch) Kind

func (*ClassConstFetch) Kind() NodeKind

type ClassKind

type ClassKind uint8

ClassKind distinguishes class-like declarations.

const (
	KindClass ClassKind = iota
	KindInterface
	KindTrait
	KindEnum
)

type ClassLike

type ClassLike struct {
	Attrs      []*AttributeGroup
	Modifiers  Modifiers
	ClassKind  ClassKind
	Name       *Identifier
	Extends    []*Name // one for classes, many for interfaces
	Implements []*Name
	EnumType   Expr // backed enum scalar type
	Members    []Stmt
	Args       *ArgList // anonymous class constructor args
	LBrace     Span
	// contains filtered or unexported fields
}

ClassLike is a class, interface, trait or enum declaration. Anonymous classes (`new class`) have a nil Name.

func EnclosingClass

func EnclosingClass(n Node) *ClassLike

EnclosingClass returns the class-like declaration containing n (nil outside one).

func (*ClassLike) Kind

func (*ClassLike) Kind() NodeKind

type Clone

type Clone struct {
	Args *ArgList // PHP 8.5 function-like form; nil for legacy unary syntax
	Expr Expr     // statically bound object argument
	With Expr     // PHP 8.5 `clone($obj, [...])` property overrides, or nil
	// contains filtered or unexported fields
}

func (*Clone) Kind

func (*Clone) Kind() NodeKind

type Closure

type Closure struct {
	Attrs      []*AttributeGroup
	Static     bool
	ByRef      bool
	Params     []*Param
	Uses       []*ClosureUse
	ReturnType Expr // type node or nil
	Body       *Block
	// contains filtered or unexported fields
}

func (*Closure) Kind

func (*Closure) Kind() NodeKind

type ClosureUse

type ClosureUse struct {
	Var   *Variable
	ByRef bool
	// contains filtered or unexported fields
}

func (*ClosureUse) Kind

func (*ClosureUse) Kind() NodeKind

type ConstFetch

type ConstFetch struct {
	Name *Name
	// contains filtered or unexported fields
}

func (*ConstFetch) Kind

func (*ConstFetch) Kind() NodeKind

type ConstItem

type ConstItem struct {
	Name  *Identifier
	Value Expr
	// contains filtered or unexported fields
}

func (*ConstItem) Kind

func (*ConstItem) Kind() NodeKind

type ConstStmt

type ConstStmt struct {
	Attrs  []*AttributeGroup
	Consts []*ConstItem
	// contains filtered or unexported fields
}

ConstStmt is a top-level `const A = 1;`.

func (*ConstStmt) Kind

func (*ConstStmt) Kind() NodeKind

type Continue

type Continue struct {
	Num Expr
	// contains filtered or unexported fields
}

func (*Continue) Kind

func (*Continue) Kind() NodeKind

type Declare

type Declare struct {
	Items []*DeclareItem
	Body  Stmt // nil for `declare(...);`
	Alt   bool
	// contains filtered or unexported fields
}

func (*Declare) Kind

func (*Declare) Kind() NodeKind

type DeclareItem

type DeclareItem struct {
	Key   *Identifier
	Value Expr
	// contains filtered or unexported fields
}

func (*DeclareItem) Kind

func (*DeclareItem) Kind() NodeKind

type DecodedString

type DecodedString struct {
	Value   string
	Sources []Span
}

DecodedString pairs a constant PHP string with the source range of each decoded byte. Bytes produced by one escape share its entire source range.

func DecodeLiteralString

func DecodeLiteralString(literal *Literal) (DecodedString, bool)

DecodeLiteralString decodes a complete noninterpolated literal and preserves its byte mapping, including indentation removal in flexible heredocs.

type DoWhile

type DoWhile struct {
	Body Stmt
	Cond Expr
	// contains filtered or unexported fields
}

func (*DoWhile) Kind

func (*DoWhile) Kind() NodeKind

type Echo

type Echo struct {
	Exprs []Expr
	Short bool // <?= ... (no echo keyword)
	// contains filtered or unexported fields
}

func (*Echo) Kind

func (*Echo) Kind() NodeKind

type Else

type Else struct {
	Body Stmt
	// contains filtered or unexported fields
}

func (*Else) Kind

func (*Else) Kind() NodeKind

type ElseIf

type ElseIf struct {
	Cond Expr
	Body Stmt
	// contains filtered or unexported fields
}

func (*ElseIf) Kind

func (*ElseIf) Kind() NodeKind

type Empty

type Empty struct {
	Expr Expr
	// contains filtered or unexported fields
}

func (*Empty) Kind

func (*Empty) Kind() NodeKind

type EnumCase

type EnumCase struct {
	Attrs []*AttributeGroup
	Name  *Identifier
	Value Expr
	// contains filtered or unexported fields
}

func (*EnumCase) Kind

func (*EnumCase) Kind() NodeKind

type Error

type Error struct {
	Span Span
	Msg  string
}

Error is a syntax error (the tree is still complete; see BadExpr/BadStmt).

func (Error) Error

func (e Error) Error() string

type Eval

type Eval struct {
	Expr Expr
	// contains filtered or unexported fields
}

func (*Eval) Kind

func (*Eval) Kind() NodeKind

type Exit

type Exit struct {
	Keyword TokenRef // exit / die
	Args    *ArgList // nil when bare
	// contains filtered or unexported fields
}

func (*Exit) Kind

func (*Exit) Kind() NodeKind

type Expr

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

Expr is an expression node.

func UnwrapParens

func UnwrapParens(e Expr) Expr

UnwrapParens strips any number of enclosing parentheses from e (a Paren without an inner expression is returned as is).

type ExprStmt

type ExprStmt struct {
	Expr Expr
	// contains filtered or unexported fields
}

func (*ExprStmt) Kind

func (*ExprStmt) Kind() NodeKind

type File

type File struct {
	Path    string
	Src     []byte
	Version phpversion.Version
	Tokens  []Token // complete token stream (trivia included)
	Stmts   []Stmt
	Errors  []Error
	// contains filtered or unexported fields
}

File is a parsed PHP source file.

func Parse

func Parse(path string, src []byte, opt Options) *File

Parse parses src (which is retained by the returned File and must not be modified afterwards). It never fails: syntax errors are reported in File.Errors and the tree contains Bad* nodes where recovery happened.

func ParseBest

func ParseBest(path string, src []byte, opt Options) *File

ParseBest parses src at opt.Version and, when that yields syntax errors, re-parses with the newest grammar (permissive) and keeps the result with fewer errors. The interpreter that runs the code, not the project's minimum version, decides what parses (a PHP 8.1-targeting project may contain 8.4 test fixtures); parsing at the target version first keeps old code that uses later keywords (`fn`, `match`, `enum`) as identifiers working.

func (*File) Kind

func (*File) Kind() NodeKind

func (*File) Memo

func (f *File) Memo(key any, fn func() any) any

Memo returns the value cached on the file under key, computing it with fn on first use. Analysis helpers use it for derived per-file data (indexes over the tree) that would otherwise be recomputed per node — quadratic on large files. fn runs without the lock held (it may use Memo itself); concurrent first uses may both compute, the first stored value wins.

func (*File) Parent

func (b *File) Parent() Node

func (*File) Span

func (b *File) Span() Span

type Finally

type Finally struct {
	Body *Block
	// contains filtered or unexported fields
}

func (*Finally) Kind

func (*Finally) Kind() NodeKind

type For

type For struct {
	Init []Expr
	Cond []Expr
	Loop []Expr
	Body Stmt
	Alt  bool
	// contains filtered or unexported fields
}

func (*For) Kind

func (*For) Kind() NodeKind

type Foreach

type Foreach struct {
	Expr  Expr
	Key   Expr // may be nil
	Value Expr
	ByRef bool
	Body  Stmt
	Alt   bool
	// contains filtered or unexported fields
}

func (*Foreach) Kind

func (*Foreach) Kind() NodeKind

type FuncCall

type FuncCall struct {
	Name Expr // *Name or expression
	Args *ArgList
	// contains filtered or unexported fields
}

func (*FuncCall) Kind

func (*FuncCall) Kind() NodeKind

type Function

type Function struct {
	Attrs      []*AttributeGroup
	ByRef      bool
	Name       *Identifier
	Params     []*Param
	ReturnType Expr
	Body       *Block
	// contains filtered or unexported fields
}

func (*Function) Kind

func (*Function) Kind() NodeKind

type Global

type Global struct {
	Vars []Expr
	// contains filtered or unexported fields
}

func (*Global) Kind

func (*Global) Kind() NodeKind

type Goto

type Goto struct {
	Label *Identifier
	// contains filtered or unexported fields
}

func ScopeGotos

func ScopeGotos(scope Node) []*Goto

ScopeGotos returns the `goto` statements of a variable scope in source order, the ones of the functions, closures and classes declared in it left out. They are read once per scope. A scope without a block body has none.

func (*Goto) Kind

func (*Goto) Kind() NodeKind

type HaltCompiler

type HaltCompiler struct {
	Data string
	// contains filtered or unexported fields
}

func (*HaltCompiler) Kind

func (*HaltCompiler) Kind() NodeKind

type Identifier

type Identifier struct {
	Value string
	// contains filtered or unexported fields
}

Identifier is a simple, non-namespaced identifier (member names, labels). Reserved words are allowed in member positions.

func (*Identifier) Kind

func (*Identifier) Kind() NodeKind

type If

type If struct {
	Cond    Expr
	Body    Stmt // *Block or single statement
	ElseIfs []*ElseIf
	Else    *Else
	Alt     bool
	// contains filtered or unexported fields
}

func (*If) Kind

func (*If) Kind() NodeKind

type IncDec

type IncDec struct {
	Var    Expr
	Op     TokenRef
	Prefix bool
	// contains filtered or unexported fields
}

IncDec is ++/-- in prefix or postfix position.

func (*IncDec) Kind

func (*IncDec) Kind() NodeKind

type Include

type Include struct {
	Keyword TokenRef // include, include_once, require, require_once
	Expr    Expr
	// contains filtered or unexported fields
}

func (*Include) Kind

func (*Include) Kind() NodeKind

type InlineHTML

type InlineHTML struct {
	Raw string
	// contains filtered or unexported fields
}

func (*InlineHTML) Kind

func (*InlineHTML) Kind() NodeKind

type Instanceof

type Instanceof struct {
	Expr  Expr
	Class Expr // *Name or expression
	// contains filtered or unexported fields
}

func (*Instanceof) Kind

func (*Instanceof) Kind() NodeKind

type InterpolatedString

type InterpolatedString struct {
	Parts    []Expr
	Heredoc  bool
	Backtick bool // shell exec
	// contains filtered or unexported fields
}

InterpolatedString is a double-quoted string, heredoc or backtick command with embedded expressions. Parts are *StringPart or expressions.

func (*InterpolatedString) Kind

func (*InterpolatedString) Kind() NodeKind

type IntersectionType

type IntersectionType struct {
	Types []Expr
	// contains filtered or unexported fields
}

IntersectionType is A&B.

func (*IntersectionType) Kind

func (*IntersectionType) Kind() NodeKind

type Isset

type Isset struct {
	Vars []Expr
	// contains filtered or unexported fields
}

func (*Isset) Kind

func (*Isset) Kind() NodeKind

type Label

type Label struct {
	Name *Identifier
	// contains filtered or unexported fields
}

func ScopeLabels

func ScopeLabels(scope Node) []*Label

ScopeLabels returns the labels of a variable scope in source order, read with its `goto` statements and with the same ones left out.

func (*Label) Kind

func (*Label) Kind() NodeKind

type LexError

type LexError struct {
	Pos uint32
	Msg string
}

LexError is a lexical problem (the token stream is still complete).

type LexOptions

type LexOptions struct {
	Version phpversion.Version
	// ShortOpenTag enables `<?` as an open tag (php.ini short_open_tag).
	ShortOpenTag bool
}

LexOptions configure the lexer.

type LineIndex

type LineIndex struct {
	// contains filtered or unexported fields
}

LineIndex maps byte offsets to line/column positions.

func NewLineIndex

func NewLineIndex(src []byte) *LineIndex

NewLineIndex indexes line starts of src (\n, \r\n and \r terminate lines).

func (*LineIndex) LineSpan

func (l *LineIndex) LineSpan(line int) Span

LineSpan returns the span of 0-based line in the source, without its line ending (an empty span at 0 for a line out of range).

func (*LineIndex) Lines

func (l *LineIndex) Lines() int

Lines returns the number of lines.

func (*LineIndex) OffsetUTF16

func (l *LineIndex) OffsetUTF16(line, col int) uint32

OffsetUTF16 converts an LSP position (0-based line, UTF-16 column) to a byte offset.

func (*LineIndex) Position

func (l *LineIndex) Position(offset uint32) (line, col int)

Position returns the 0-based line and 0-based byte column of offset.

func (*LineIndex) RuneColumn

func (l *LineIndex) RuneColumn(offset uint32) (line, col int)

RuneColumn returns the 0-based column of offset counted in runes.

func (*LineIndex) UTF16Column

func (l *LineIndex) UTF16Column(offset uint32) (line, col int)

UTF16Column returns the 0-based line and column in UTF-16 code units (LSP default).

type List

type List struct {
	Items []*ArrayItem
	// contains filtered or unexported fields
}

List is list(...) destructuring.

func (*List) Kind

func (*List) Kind() NodeKind

type Literal

type Literal struct {
	LitKind LiteralKind
	Raw     string
	// contains filtered or unexported fields
}

Literal is an int, float or non-interpolated string literal. Raw is the source text (quotes included for strings).

func (*Literal) Kind

func (*Literal) Kind() NodeKind

type LiteralKind

type LiteralKind uint8

LiteralKind classifies scalar literals.

const (
	LitInt LiteralKind = iota
	LitFloat
	LitString // single/double quoted without interpolation, or nowdoc
)

type MagicConst

type MagicConst struct {
	Token TokenRef
	// contains filtered or unexported fields
}

func (*MagicConst) Kind

func (*MagicConst) Kind() NodeKind

type Match

type Match struct {
	Cond Expr
	Arms []*MatchArm
	// contains filtered or unexported fields
}

func (*Match) Kind

func (*Match) Kind() NodeKind

type MatchArm

type MatchArm struct {
	Conds []Expr // nil for default
	Body  Expr
	// contains filtered or unexported fields
}

func (*MatchArm) Kind

func (*MatchArm) Kind() NodeKind

type Method

type Method struct {
	Attrs      []*AttributeGroup
	Modifiers  Modifiers
	ByRef      bool
	Name       *Identifier
	Params     []*Param
	ReturnType Expr
	Body       *Block // nil for abstract/interface methods
	// contains filtered or unexported fields
}

func (*Method) Kind

func (*Method) Kind() NodeKind

type MethodCall

type MethodCall struct {
	Var      Expr
	Name     Expr // *Identifier or expression
	Args     *ArgList
	NullSafe bool
	// contains filtered or unexported fields
}

func (*MethodCall) Kind

func (*MethodCall) Kind() NodeKind

type Modifiers

type Modifiers []TokenRef

Modifiers is an ordered list of modifier keywords as written.

func (Modifiers) Has

func (m Modifiers) Has(k TokenKind) bool

Has reports whether a modifier of kind k is present.

type Name

type Name struct {
	Value string // source text, e.g. `\Foo\Bar`
	NameKind
	// contains filtered or unexported fields
}

Name is a (possibly qualified) class/function/constant name as written.

func (*Name) Kind

func (*Name) Kind() NodeKind

type NameKind

type NameKind uint8

NameKind classifies a name as written.

const (
	NameUnqualified    NameKind = iota // Foo
	NameQualified                      // Foo\Bar
	NameFullyQualified                 // \Foo\Bar
	NameRelative                       // namespace\Foo
)

type Namespace

type Namespace struct {
	Name   *Name // nil for global namespace block
	Stmts  []Stmt
	Braced bool
	// contains filtered or unexported fields
}

func (*Namespace) Kind

func (*Namespace) Kind() NodeKind

type New

type New struct {
	Class Expr     // *Name, expression, or *ClassLike (anonymous class)
	Args  *ArgList // nil when written without parentheses
	// contains filtered or unexported fields
}

func (*New) Kind

func (*New) Kind() NodeKind

type Node

type Node interface {
	Span() Span
	Parent() Node
	Kind() NodeKind
	// contains filtered or unexported methods
}

Node is implemented by every AST node.

func EnclosingFuncLike

func EnclosingFuncLike(n Node) Node

EnclosingFuncLike returns the nearest function-like strictly enclosing n (nil in top-level code).

func EnclosingVariableScope

func EnclosingVariableScope(n Node) Node

EnclosingVariableScope returns the nearest strictly enclosing local scope.

func VariableScopeBody

func VariableScopeBody(n Node) Node

VariableScopeBody returns a block or expression body, or nil for a scope without a body. Unlike FuncLikeBody it includes arrows and property hooks.

type NodeIdentity

type NodeIdentity struct {
	// contains filtered or unexported fields
}

NodeIdentity is a comparable key for one node within a parsed tree. It retains the node's storage and distinguishes nodes with identical kinds and spans. It is not a persistent identifier across parses.

func Identity

func Identity(node Node) NodeIdentity

Identity returns a compact identity key without retaining the node's dynamic interface type. A nil interface has the zero identity.

type NodeKind

type NodeKind uint8

NodeKind identifies the concrete type of a node (used for rule dispatch).

const (
	KindInvalid NodeKind = iota
	KFile
	KName
	KIdentifier
	KVariable
	KArrayDimFetch
	KPropertyFetch
	KStaticPropertyFetch
	KClassConstFetch
	KConstFetch
	KArg
	KVariadicPlaceholder
	KArgList
	KFuncCall
	KMethodCall
	KStaticCall
	KNew
	KAssign
	KBinary
	KUnary
	KIncDec
	KTernary
	KInstanceof
	KIsset
	KEmpty
	KExit
	KPrint
	KInclude
	KEval
	KClone
	KThrow
	KYield
	KYieldFrom
	KArrayItem
	KArray
	KList
	KClosureUse
	KClosure
	KArrowFunction
	KMatchArm
	KMatch
	KLiteral
	KStringPart
	KInterpolatedString
	KMagicConst
	KParen
	KBadExpr
	KNullableType
	KUnionType
	KIntersectionType
	KAttribute
	KAttributeGroup
	KPropertyHook
	KParam
	KBlock
	KExprStmt
	KEcho
	KInlineHTML
	KNop
	KIf
	KElseIf
	KElse
	KWhile
	KDoWhile
	KFor
	KForeach
	KCase
	KSwitch
	KBreak
	KContinue
	KReturn
	KGlobal
	KStaticVar
	KStaticStmt
	KUnset
	KGoto
	KLabel
	KCatch
	KFinally
	KTry
	KDeclareItem
	KDeclare
	KHaltCompiler
	KUseItem
	KUse
	KNamespace
	KConstItem
	KConstStmt
	KFunction
	KClassLike
	KMethod
	KPropertyItem
	KProperty
	KClassConst
	KEnumCase
	KTraitAdaptation
	KTraitUse
	KBadStmt
	NumNodeKinds
)

func (NodeKind) String

func (k NodeKind) String() string

type Nop

type Nop struct {
	// contains filtered or unexported fields
}

Nop is an empty statement `;` (also stray close/open tag pairs are trivia).

func (*Nop) Kind

func (*Nop) Kind() NodeKind

type NullableType

type NullableType struct {
	Type Expr
	// contains filtered or unexported fields
}

NullableType is ?T.

func (*NullableType) Kind

func (*NullableType) Kind() NodeKind

type Options

type Options struct {
	Version      phpversion.Version // default phpversion.Default
	ShortOpenTag bool
	// Permissive additionally accepts syntax removed in Version (e.g. legacy
	// `$s{0}` offsets in PHP 8), the way IDEs parse code at any level.
	Permissive bool
	// CopyText gives node strings their own storage, so extracted metadata
	// can outlive the tree without retaining its entire source buffer.
	CopyText bool
}

Options configure parsing.

type Param

type Param struct {
	Attrs     []*AttributeGroup
	Modifiers Modifiers // constructor promotion
	Type      Expr
	ByRef     bool
	Variadic  bool
	Var       *Variable
	Default   Expr
	Hooks     []*PropertyHook
	// contains filtered or unexported fields
}

func FuncLikeParams

func FuncLikeParams(n Node) []*Param

FuncLikeParams returns the parameters of a function-like.

func VariableScopeParams

func VariableScopeParams(n Node) []*Param

VariableScopeParams returns the explicit parameters of a local scope. The implicit setter parameter is not an AST parameter.

func (*Param) Kind

func (*Param) Kind() NodeKind

type Paren

type Paren struct {
	Expr Expr
	// contains filtered or unexported fields
}

Paren is a parenthesised expression (kept for exact ranges).

func (*Paren) Kind

func (*Paren) Kind() NodeKind

type Print

type Print struct {
	Expr Expr
	// contains filtered or unexported fields
}

func (*Print) Kind

func (*Print) Kind() NodeKind

type Property

type Property struct {
	Attrs     []*AttributeGroup
	Modifiers Modifiers
	Type      Expr
	Props     []*PropertyItem
	Hooks     []*PropertyHook
	// contains filtered or unexported fields
}

func (*Property) Kind

func (*Property) Kind() NodeKind

type PropertyFetch

type PropertyFetch struct {
	Var      Expr
	Name     Expr // *Identifier or expression ({$x} / $x)
	NullSafe bool
	// contains filtered or unexported fields
}

func (*PropertyFetch) Kind

func (*PropertyFetch) Kind() NodeKind

type PropertyHook

type PropertyHook struct {
	Attrs     []*AttributeGroup
	Modifiers Modifiers
	ByRef     bool
	Name      *Identifier
	Params    []*Param
	Body      Node // *Block, Expr (for => expr), or nil (abstract)
	// contains filtered or unexported fields
}

PropertyHook is a property hook (get/set), PHP 8.4.

func (*PropertyHook) Kind

func (*PropertyHook) Kind() NodeKind

type PropertyItem

type PropertyItem struct {
	Var     *Variable
	Default Expr
	// contains filtered or unexported fields
}

func (*PropertyItem) Kind

func (*PropertyItem) Kind() NodeKind

type Return

type Return struct {
	Expr Expr
	// contains filtered or unexported fields
}

func (*Return) Kind

func (*Return) Kind() NodeKind

type Span

type Span struct {
	Start uint32
	End   uint32
}

Span is a byte range [Start, End) in the source.

func (Span) Contains

func (s Span) Contains(o Span) bool

Contains reports whether o lies within s.

func (Span) Len

func (s Span) Len() uint32

Len returns the span length in bytes.

type StaticCall

type StaticCall struct {
	Class Expr // *Name or expression
	Name  Expr // *Identifier or expression
	Args  *ArgList
	// contains filtered or unexported fields
}

func (*StaticCall) Kind

func (*StaticCall) Kind() NodeKind

type StaticPropertyFetch

type StaticPropertyFetch struct {
	Class Expr // *Name or expression
	Name  Expr // *Variable (or expression for ::${expr})
	// contains filtered or unexported fields
}

func (*StaticPropertyFetch) Kind

func (*StaticPropertyFetch) Kind() NodeKind

type StaticStmt

type StaticStmt struct {
	Vars []*StaticVar
	// contains filtered or unexported fields
}

func (*StaticStmt) Kind

func (*StaticStmt) Kind() NodeKind

type StaticVar

type StaticVar struct {
	Var     *Variable
	Default Expr
	// contains filtered or unexported fields
}

func (*StaticVar) Kind

func (*StaticVar) Kind() NodeKind

type Stmt

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

Stmt is a statement node.

func StmtListOf

func StmtListOf(p Node) (list []Stmt, ok bool)

StmtListOf returns the statement list owned by p (a *File, *Block, *Case or *Namespace); ok is false for any other node.

type StringPart

type StringPart struct {
	Raw string
	// contains filtered or unexported fields
}

StringPart is a literal fragment of an interpolated string.

func (*StringPart) Kind

func (*StringPart) Kind() NodeKind

type Switch

type Switch struct {
	Cond  Expr
	Cases []*Case
	Alt   bool
	// contains filtered or unexported fields
}

func (*Switch) Kind

func (*Switch) Kind() NodeKind

type Tail

type Tail struct {
	// Labels holds the labels written in those statements at any depth, in
	// source order, the ones of the functions, closures and classes declared
	// there left out.
	Labels []*Label
	// contains filtered or unexported fields
}

Tail describes the statements of a list from its first terminating one on: code that only a jump can reach.

func TailOf

func TailOf(p Node) *Tail

TailOf returns the Tail of the list owned by p (a *File, *Block, *Case or *Namespace), or nil for another node or a list no statement ends. It is read once per list, so asking it for every node of a long list stays linear overall.

func (*Tail) LastTerminating

func (t *Tail) LastTerminating(i int) int

LastTerminating returns the greatest index at or below i of a statement of the list that terminates. i must not lie before the first one.

type Ternary

type Ternary struct {
	Cond     Expr
	Question Span
	Then     Expr // nil for short ternary ?:
	Colon    Span
	Else     Expr
	// contains filtered or unexported fields
}

func (*Ternary) Kind

func (*Ternary) Kind() NodeKind

type Throw

type Throw struct {
	Expr Expr
	// contains filtered or unexported fields
}

func (*Throw) Kind

func (*Throw) Kind() NodeKind

type Token

type Token struct {
	Kind  TokenKind
	Start uint32
	End   uint32
}

Token is one lexical token: kind and byte span [Start, End).

type TokenKind

type TokenKind uint16

TokenKind identifies a lexical token.

const (
	TEOF TokenKind = iota
	TBadCharacter

	// Trivia.
	TWhitespace
	TComment    // // # /* */
	TDocComment // /** */

	// Mode switches.
	TInlineHTML
	TOpenTag         // <?php or <?  (includes one trailing newline/space)
	TOpenTagWithEcho // <?=
	TCloseTag        // ?> (includes one trailing newline)

	// Literals and names.
	TVariable               // $name
	TString                 // identifier / label
	TNameQualified          // Foo\Bar
	TNameFullyQualified     // \Foo\Bar
	TNameRelative           // namespace\Foo
	TLNumber                // integer literal
	TDNumber                // float literal
	TConstantEncapsedString // '...' or "..." without interpolation
	TEncapsedAndWhitespace  // literal part inside an interpolated string
	TStringVarname          // name in "${name}"
	TNumString              // offset in "$a[0]"
	TStartHeredoc           // <<<ID / <<<'ID' (incl. newline)
	TEndHeredoc             // closing identifier
	TDollarOpenCurlyBraces  // ${ inside strings
	TCurlyOpen              // {$ inside strings
	TDoubleQuote            // " opening/closing an interpolated string
	TBacktick               // `
	THaltCompilerData       // everything after __halt_compiler();

	// Casts.
	TIntCast
	TDoubleCast // (float) (double) (real)
	TStringCast // (string) (binary)
	TArrayCast
	TObjectCast
	TBoolCast
	TUnsetCast
	TVoidCast // (void), PHP 8.5

	// Operators and punctuation (multi-char).
	TObjectOperator         // ->
	TNullsafeObjectOperator // ?->
	TDoubleArrow            // =>
	TPaamayimNekudotayim    // ::
	TNsSeparator            // \ (only alone, e.g. in group use)
	TEllipsis               // ...
	TCoalesce               // ??
	TCoalesceEqual          // ??=
	TPow                    // **
	TPowEqual               // **=
	TInc                    // ++
	TDec                    // --
	TIsEqual                // ==
	TIsNotEqual             // != <>
	TIsIdentical            // ===
	TIsNotIdentical         // !==
	TIsSmallerOrEqual       // <=
	TIsGreaterOrEqual       // >=
	TSpaceship              // <=>
	TPlusEqual              // +=
	TMinusEqual             // -=
	TMulEqual               // *=
	TDivEqual               // /=
	TConcatEqual            // .=
	TModEqual               // %=
	TAndEqual               // &=
	TOrEqual                // |=
	TXorEqual               // ^=
	TSlEqual                // <<=
	TSrEqual                // >>=
	TSl                     // <<
	TSr                     // >>
	TBooleanOr              // ||
	TBooleanAnd             // &&
	TPipe                   // |>
	TAttribute              // #[

	// Single-character punctuation.
	TSemicolon // ;
	TComma     // ,
	TDot       // .
	TLBrace    // {
	TRBrace    // }
	TLParen    // (
	TRParen    // )
	TLBracket  // [
	TRBracket  // ]
	TPlus      // +
	TMinus     // -
	TMul       // *
	TDiv       // /
	TMod       // %
	TEqual     // =
	TLess      // <
	TGreater   // >
	TExclaim   // !
	TQuestion  // ?
	TColon     // :
	TAmpersand // &
	TBar       // |
	TCaret     // ^
	TTilde     // ~
	TAt        // @
	TDollar    // $
	TBackslash // never produced; names absorb backslashes (kept for completeness)

	TAbstract
	TAnd // and
	TArray
	TAs
	TBreak
	TCallable
	TCase
	TCatch
	TClass
	TClone
	TConst
	TContinue
	TDeclare
	TDefault
	TDo
	TEcho
	TElse
	TElseif
	TEmpty
	TEnddeclare
	TEndfor
	TEndforeach
	TEndif
	TEndswitch
	TEndwhile
	TEnum
	TEval
	TExit // exit / die
	TExtends
	TFinal
	TFinally
	TFn
	TFor
	TForeach
	TFunction
	TGlobal
	TGoto
	TIf
	TImplements
	TInclude
	TIncludeOnce
	TInstanceof
	TInsteadof
	TInterface
	TIsset
	TList
	TMatch
	TNamespace
	TNew
	TOr // or
	TPrint
	TPrivate
	TProtected
	TPublic
	TPrivateSet   // private(set)
	TProtectedSet // protected(set)
	TPublicSet    // public(set)
	TReadonly
	TRequire
	TRequireOnce
	TReturn
	TStatic
	TSwitch
	TThrow
	TTrait
	TTry
	TUnset
	TUse
	TVar
	TWhile
	TXor // xor
	TYield
	TYieldFrom
	THaltCompiler

	// Magic constants.
	TLine
	TFile
	TDir
	TClassC
	TTraitC
	TMethodC
	TFuncC
	TNsC
	TPropertyC
)

func (TokenKind) IsAssignOp

func (k TokenKind) IsAssignOp() bool

IsAssignOp reports whether k is a compound assignment operator.

func (TokenKind) IsCast

func (k TokenKind) IsCast() bool

IsCast reports whether k is a cast token.

func (TokenKind) IsKeyword

func (k TokenKind) IsKeyword() bool

IsKeyword reports whether k is a reserved word (usable as identifier in member-name positions).

func (TokenKind) IsModifier

func (k TokenKind) IsModifier() bool

IsModifier reports whether k is a member/class modifier keyword.

func (TokenKind) IsTrivia

func (k TokenKind) IsTrivia() bool

IsTrivia reports whether k is whitespace or a comment.

func (TokenKind) String

func (k TokenKind) String() string

type TokenRef

type TokenRef struct {
	Kind TokenKind
	Span Span
}

TokenRef is a token kept by the AST (operators, modifiers, keywords).

type TraitAdaptation

type TraitAdaptation struct {
	Trait     *Name // may be nil for `m as ...`
	Method    *Identifier
	Insteadof []*Name
	Modifier  *TokenRef
	Alias     *Identifier
	// contains filtered or unexported fields
}

TraitAdaptation is `A::m insteadof B;` or `m as [visibility] [alias];`.

func (*TraitAdaptation) Kind

func (*TraitAdaptation) Kind() NodeKind

type TraitUse

type TraitUse struct {
	Traits      []*Name
	Adaptations []*TraitAdaptation
	// contains filtered or unexported fields
}

func (*TraitUse) Kind

func (*TraitUse) Kind() NodeKind

type Try

type Try struct {
	Body    *Block
	Catches []*Catch
	Finally *Finally
	// contains filtered or unexported fields
}

func (*Try) Kind

func (*Try) Kind() NodeKind

type Unary

type Unary struct {
	Op   TokenRef
	Expr Expr
	// contains filtered or unexported fields
}

Unary covers ! - + ~ @ and casts.

func (*Unary) Kind

func (*Unary) Kind() NodeKind

type UnionType

type UnionType struct {
	Types []Expr
	// contains filtered or unexported fields
}

UnionType is A|B.

func (*UnionType) Kind

func (*UnionType) Kind() NodeKind

type Unset

type Unset struct {
	Vars []Expr
	// contains filtered or unexported fields
}

func (*Unset) Kind

func (*Unset) Kind() NodeKind

type Use

type Use struct {
	Type   UseKind
	Prefix *Name
	Items  []*UseItem
	// contains filtered or unexported fields
}

Use is `use A\B as C, D;` or a group use `use A\{B, C}` (Prefix set).

func (*Use) Kind

func (*Use) Kind() NodeKind

type UseItem

type UseItem struct {
	Type  UseKind // per-item kind inside group use
	Name  *Name
	Alias *Identifier
	// contains filtered or unexported fields
}

func (*UseItem) Kind

func (*UseItem) Kind() NodeKind

type UseKind

type UseKind uint8

UseKind is the kind of a use import.

const (
	UseNormal UseKind = iota
	UseFunction
	UseConst
)

type Variable

type Variable struct {
	Name     string // without '$'; empty when NameExpr != nil
	NameExpr Expr
	// contains filtered or unexported fields
}

Variable is $name, or $$expr / ${expr} when NameExpr is set.

func (*Variable) Kind

func (*Variable) Kind() NodeKind

type VariadicPlaceholder

type VariadicPlaceholder struct {
	// contains filtered or unexported fields
}

VariadicPlaceholder is the `...` of a first-class callable `f(...)`.

func (*VariadicPlaceholder) Kind

func (*VariadicPlaceholder) Kind() NodeKind

type While

type While struct {
	Cond Expr
	Body Stmt
	Alt  bool
	// contains filtered or unexported fields
}

func (*While) Kind

func (*While) Kind() NodeKind

type Yield

type Yield struct {
	Key   Expr // may be nil
	Value Expr // may be nil
	// contains filtered or unexported fields
}

func (*Yield) Kind

func (*Yield) Kind() NodeKind

type YieldFrom

type YieldFrom struct {
	Expr Expr
	// contains filtered or unexported fields
}

func (*YieldFrom) Kind

func (*YieldFrom) Kind() NodeKind

Jump to

Keyboard shortcuts

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