Documentation
¶
Overview ¶
Package syntax implements a lossless, error-tolerant, version-aware PHP lexer and parser (PHP 5.3 – 8.6).
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
- Variables
- func Children(n Node, fn func(Node))
- func Endless(n Node) bool
- func Escapes(loop Node) bool
- func ExitInvocation(e Expr) bool
- func ExitInvokes(n *Exit) bool
- func FirstTerminating(p Node) int
- func Inspect(n Node, fn func(Node) bool)
- func InspectFile(f *File, fn func(Node) bool)
- func IsDestructuring(n Node) bool
- func IsFuncLike(n Node) bool
- func IsNullConst(e Expr) bool
- func IsVariableScope(n Node) bool
- func Lex(src []byte, opt LexOptions) ([]Token, []LexError)
- func LiteralArrayKey(x Expr) (string, bool)
- func LiteralStringValue(literal *Literal) (string, bool)
- func LiteralStringValueForVersion(literal *Literal, version phpversion.Version) (string, bool)
- func MinVersion(n Node) phpversion.Version
- func PlainStringLiteral(raw string) (string, bool)
- func ScopeMemo[T any](scope Node, build func(scope Node) *T) *T
- func SetParents(f *File)
- func SourceVersion(node Node) phpversion.Version
- func StmtIndex(list []Stmt, s Node) int
- func StrictTypes(f *File) bool
- func StringLiteralValue(raw string) (val string, ok bool)
- func StringLiteralValueForVersion(raw string, version phpversion.Version) (val string, ok bool)
- func Superglobal(name string) bool
- func Terminates(s Stmt) bool
- func TreeDepth(stmts []Stmt) int
- type Arg
- type ArgList
- type ArgPlaceholder
- type Array
- type ArrayDimFetch
- type ArrayItem
- type ArrowFunction
- type Assign
- type Attribute
- type AttributeGroup
- type BadExpr
- type BadStmt
- type Binary
- type Block
- type Break
- type Case
- type Catch
- type ClassConst
- type ClassConstFetch
- type ClassKind
- type ClassLike
- type Clone
- type Closure
- type ClosureUse
- type ConstFetch
- type ConstItem
- type ConstStmt
- type Continue
- type Declare
- type DeclareItem
- type DecodedString
- type DoWhile
- type Echo
- type Else
- type ElseIf
- type Empty
- type EnumCase
- type Error
- type Eval
- type Exit
- type Expr
- type ExprStmt
- type File
- type Finally
- type For
- type Foreach
- type FuncCall
- type Function
- type Global
- type Goto
- type HaltCompiler
- type Identifier
- type If
- type IncDec
- type Include
- type InlineHTML
- type Instanceof
- type InterpolatedString
- type IntersectionType
- type Isset
- type Label
- type LexError
- type LexOptions
- type LineIndex
- func (l *LineIndex) LineSpan(line int) Span
- func (l *LineIndex) Lines() int
- func (l *LineIndex) OffsetUTF16(line, col int) uint32
- func (l *LineIndex) Position(offset uint32) (line, col int)
- func (l *LineIndex) RuneColumn(offset uint32) (line, col int)
- func (l *LineIndex) UTF16Column(offset uint32) (line, col int)
- type List
- type Literal
- type LiteralKind
- type MagicConst
- type Match
- type MatchArm
- type Method
- type MethodCall
- type Modifiers
- type Name
- type NameKind
- type Namespace
- type New
- type Node
- type NodeIdentity
- type NodeKind
- type Nop
- type NullableType
- type Options
- type Param
- type Paren
- type Print
- type Property
- type PropertyFetch
- type PropertyHook
- type PropertyItem
- type Return
- type Span
- type StaticCall
- type StaticPropertyFetch
- type StaticStmt
- type StaticVar
- type Stmt
- type StringPart
- type Switch
- type Tail
- type Ternary
- type Throw
- type Token
- type TokenKind
- type TokenRef
- type TraitAdaptation
- type TraitUse
- type Try
- type Unary
- type UnionType
- type Unset
- type Use
- type UseItem
- type UseKind
- type Variable
- type VariadicPlaceholder
- type While
- type Yield
- type YieldFrom
Constants ¶
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.
const MaxErrors = 1000
MaxErrors caps the syntax errors reported for one file.
const MaxFileSize = 10 << 20
MaxFileSize is the largest source analyzed (bytes); larger files get one error and an empty tree.
Variables ¶
var MirroredComparison = map[TokenKind]TokenKind{ TGreater: TLess, TLess: TGreater, TIsGreaterOrEqual: TIsSmallerOrEqual, TIsSmallerOrEqual: TIsGreaterOrEqual, }
MirroredComparison maps an ordering comparison to the one that holds with its operands swapped (`a < b` is `b > a`).
Functions ¶
func Children ¶
Children calls fn for each direct child of n, in source order. Nil children are skipped.
func Endless ¶
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 ¶
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 ¶
ExitInvocation reports a direct exit/die call, including an immediate invocation of its first-class callable. Creating a callable does not exit.
func ExitInvokes ¶
ExitInvokes reports whether evaluating exit/die calls the function rather than producing a closure (`exit(...)`, `exit(?)`).
func FirstTerminating ¶
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 ¶
Inspect walks the tree depth-first in source order. If fn returns false the node's children are skipped.
func InspectFile ¶
InspectFile walks every top-level statement of f.
func IsDestructuring ¶ added in v0.2.5
IsDestructuring reports whether n is an array pattern being assigned to: the target of `=`, the value of a foreach, or nested in such a pattern.
func IsFuncLike ¶
IsFuncLike reports whether n is a function, method, closure, arrow function or property hook.
func IsNullConst ¶
IsNullConst reports whether e is the constant null (any case, optionally `\`-qualified). Parentheses are not looked through.
func IsVariableScope ¶
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 ¶
LiteralArrayKey returns the canonical array key of a literal key expression (integer or plain string literal, optionally negated): "0", "-1", "name".
func LiteralStringValue ¶
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 lowest PHP version whose grammar or meaning supports the syntax that node n itself introduces (its children are not included). Nodes using only syntax every supported version accepts return phpversion.Min. It is metadata only: it never changes parsing.
The table is deliberately conservative: when a construct may or may not need a newer version (e.g. string keys in an array spread), the lower version is returned, so callers comparing two trees never reject code because of a guess.
func PlainStringLiteral ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Superglobal reports whether name (without '$') is one of PHP's superglobal arrays, visible in every scope without a `global` statement.
func Terminates ¶
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 ¶
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.
type ArgList ¶
type ArgList struct {
Args []Expr // *Arg, *ArgPlaceholder or *VariadicPlaceholder
// contains filtered or unexported fields
}
ArgList is a parenthesised argument list.
func (*ArgList) FirstClassCallable ¶ added in v0.2.5
FirstClassCallable reports whether a is the `(...)` of a first-class callable (`f(...)`, `$o->m(...)`, `C::m(...)`): the closure keeps the callee's whole signature. See Partial for every closure-creating list.
type ArgPlaceholder ¶ added in v0.2.6
type ArgPlaceholder struct {
Name *Identifier // named placeholder, or nil
// contains filtered or unexported fields
}
ArgPlaceholder is a `?` argument of a partial function application (`f(?, 2)`, `f(name: ?)`, 8.6).
func (*ArgPlaceholder) Kind ¶ added in v0.2.6
func (*ArgPlaceholder) 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).
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().
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 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.
type BadStmt ¶
type BadStmt struct {
// contains filtered or unexported fields
}
BadStmt marks a region that failed to parse.
type Block ¶
Block is { ... } or, for alternative syntax, the statement list between ':' and the end keyword (Alt = true).
func FuncLikeBody ¶
FuncLikeBody returns the braced body of a function-like (nil for arrow functions, expression hooks and abstract declarations).
type Case ¶
type Catch ¶
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 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 ¶
EnclosingClass returns the class-like declaration containing n (nil outside one).
type Clone ¶
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
}
type ClosureUse ¶
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
}
type ConstStmt ¶
type ConstStmt struct {
Attrs []*AttributeGroup
Consts []*ConstItem
// contains filtered or unexported fields
}
ConstStmt is a top-level `const A = 1;`.
type Declare ¶
type Declare struct {
Items []*DeclareItem
Body Stmt // nil for `declare(...);`
Alt bool
// contains filtered or unexported fields
}
type DeclareItem ¶
type DeclareItem struct {
Key *Identifier
Value Expr
// contains filtered or unexported fields
}
func (*DeclareItem) Kind ¶
func (*DeclareItem) Kind() NodeKind
type DecodedString ¶
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 Echo ¶
type EnumCase ¶
type EnumCase struct {
Attrs []*AttributeGroup
Name *Identifier
Value Expr
// contains filtered or unexported fields
}
type Error ¶
type Error struct {
Span Span
Msg string
// Compile marks an error PHP raises when it compiles code its grammar
// accepts (`f(a: 1, 2)`, `new C(...)`), rather than a parse error.
Compile bool
}
Error is a syntax error (the tree is still complete; see BadExpr/BadStmt).
type Exit ¶
type Expr ¶
type Expr interface {
Node
// contains filtered or unexported methods
}
Expr is an expression node.
func UnwrapParens ¶
UnwrapParens strips any number of enclosing parentheses from e (a Paren without an inner expression is returned as is).
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 ¶
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 ¶
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) Memo ¶
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) ParsesWorse ¶ added in v0.2.6
ParsesWorse reports whether f, a changed version of orig, parses worse: more errors, or more the parser recovered from, as when a parse error takes the place of a compile error at the same position.
func (*File) Recovered ¶ added in v0.2.6
Recovered reports whether the parser recovered from an error in f: its tree may lack or misplace code. A file with only compile errors is whole.
func (*File) RecoveryError ¶ added in v0.2.6
RecoveryError returns the first error the parser recovered from, which may have dropped or reshaped code; compile errors leave the tree whole.
func (*File) RecoveryErrorCount ¶ added in v0.2.6
RecoveryErrorCount is the number of errors the parser recovered from, compile errors aside.
type For ¶
type Foreach ¶
type FuncCall ¶
type Function ¶
type Function struct {
Attrs []*AttributeGroup
ByRef bool
Name *Identifier
Params []*Param
ReturnType Expr
Body *Block
// contains filtered or unexported fields
}
type Goto ¶
type Goto struct {
Label *Identifier
// contains filtered or unexported fields
}
func ScopeGotos ¶
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.
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 Include ¶
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 Label ¶
type Label struct {
Name *Identifier
// contains filtered or unexported fields
}
func ScopeLabels ¶
ScopeLabels returns the labels of a variable scope in source order, read with its `goto` statements and with the same ones left out.
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 ¶
NewLineIndex indexes line starts of src (\n, \r\n and \r terminate lines).
func (*LineIndex) LineSpan ¶
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) OffsetUTF16 ¶
OffsetUTF16 converts an LSP position (0-based line, UTF-16 column) to a byte offset.
func (*LineIndex) RuneColumn ¶
RuneColumn returns the 0-based column of offset counted in runes.
func (*LineIndex) UTF16Column ¶
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.
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).
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 MatchArm ¶
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
}
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.
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.
type Namespace ¶
type New ¶
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 ¶
EnclosingFuncLike returns the nearest function-like strictly enclosing n (nil in top-level code).
func EnclosingVariableScope ¶
EnclosingVariableScope returns the nearest strictly enclosing local scope.
func RequiredVersion ¶ added in v0.2.5
func RequiredVersion(f *File) (phpversion.Version, Node)
RequiredVersion returns the highest MinVersion over every node of f, and the first node (in source order) that requires it, or nil when the file only uses syntax available in phpversion.Min.
func VariableScopeBody ¶
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 KArgPlaceholder 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 )
type Nop ¶
type Nop struct {
// contains filtered or unexported fields
}
Nop is an empty statement `;` (also stray close/open tag pairs are trivia).
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 ¶
FuncLikeParams returns the parameters of a function-like.
func VariableScopeParams ¶
VariableScopeParams returns the explicit parameters of a local scope. The implicit setter parameter is not an AST parameter.
type Paren ¶
type Paren struct {
Expr Expr
// contains filtered or unexported fields
}
Paren is a parenthesised expression (kept for exact ranges).
type Property ¶
type Property struct {
Attrs []*AttributeGroup
Modifiers Modifiers
Type Expr
Props []*PropertyItem
Hooks []*PropertyHook
// contains filtered or unexported fields
}
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 ¶
func (*PropertyItem) Kind ¶
func (*PropertyItem) Kind() NodeKind
type Span ¶
Span is a byte range [Start, End) in the source.
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 Stmt ¶
type Stmt interface {
Node
// contains filtered or unexported methods
}
Stmt is a statement node.
func StmtListOf ¶
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 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 ¶
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 ¶
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 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 ¶
IsAssignOp reports whether k is a compound assignment operator.
func (TokenKind) IsKeyword ¶
IsKeyword reports whether k is a reserved word (usable as identifier in member-name positions).
func (TokenKind) IsModifier ¶
IsModifier reports whether k is a member/class modifier keyword.
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
}
type Try ¶
type UnionType ¶
type UnionType struct {
Types []Expr
// contains filtered or unexported fields
}
UnionType is A|B.
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).
type UseItem ¶
type UseItem struct {
Type UseKind // per-item kind inside group use
Name *Name
Alias *Identifier
// contains filtered or unexported fields
}
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.
type VariadicPlaceholder ¶
type VariadicPlaceholder struct {
// contains filtered or unexported fields
}
VariadicPlaceholder is the `...` of a first-class callable `f(...)`, or the trailing `...` of a partial function application `f(1, ...)` (8.6).
func (*VariadicPlaceholder) Kind ¶
func (*VariadicPlaceholder) Kind() NodeKind