ast

package
v0.60.0 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package ast contains the Vibescript abstract syntax tree node types and related lexical primitives. It is an internal package: only code within the github.com/mgomes/vibescript module can import it.

Index

Constants

View Source
const (
	RuntimeErrorTypeBase      = "RuntimeError"
	RuntimeErrorTypeStandard  = "StandardError"
	RuntimeErrorTypeAssertion = "AssertionError"
	RuntimeErrorTypeLimit     = "LimitError"
	RuntimeErrorTypeType      = "TypeError"
	RuntimeErrorTypeZeroDiv   = "ZeroDivisionError"
	RuntimeErrorTypeLocalJump = "LocalJumpError"
	RuntimeErrorTypeArgument  = "ArgumentError"
)

Canonical runtime error type names recognized by both the parser (for rescue-clause validation) and the runtime (for classifying errors). Kept here so the parser does not need to depend on the runtime package.

View Source
const (
	VisibilityPublic    = "public"
	VisibilityPrivate   = "private"
	VisibilityProtected = "protected"
)

Visibility levels for class-body visibility directives.

Variables

This section is empty.

Functions

func CanonicalRuntimeErrorType

func CanonicalRuntimeErrorType(name string) (string, bool)

CanonicalRuntimeErrorType returns the canonical spelling of a recognized runtime error type name and reports whether it is known.

func FormatDestructureTarget added in v0.60.0

func FormatDestructureTarget(target Expression) string

FormatDestructureTarget returns a destructuring binding target in source form.

func FormatParamTarget added in v0.60.0

func FormatParamTarget(param Param) string

FormatParamTarget returns the parameter's binding target in source form.

func FormatTypeExpr

func FormatTypeExpr(ty *TypeExpr) string

FormatTypeExpr returns a stable textual representation of a TypeExpr suitable for use in error messages.

func IsIdentifierRune

func IsIdentifierRune(r rune) bool

IsIdentifierRune reports whether r can appear in a Vibescript identifier after the first rune.

func IsIdentifierStart

func IsIdentifierStart(r rune) bool

IsIdentifierStart reports whether r can be the first rune of a Vibescript identifier.

func Keywords added in v0.60.0

func Keywords() []string

Keywords returns the parser's reserved keyword literals in sorted order.

Types

type AliasStmt added in v0.60.0

type AliasStmt struct {
	NewName  string
	OldName  string
	Method   bool
	Position Position
}

AliasStmt represents a Ruby-style function or method alias declaration.

func (*AliasStmt) Pos added in v0.60.0

func (s *AliasStmt) Pos() Position

type ArrayLiteral

type ArrayLiteral struct {
	Elements []Expression
	Position Position
}

ArrayLiteral represents an array literal expression.

func (*ArrayLiteral) Pos

func (e *ArrayLiteral) Pos() Position

type AssignStmt

type AssignStmt struct {
	Target Expression
	Value  Expression
	// Operator is empty for plain assignment and stores the compound
	// assignment operator otherwise.
	Operator TokenType
	Position Position
}

AssignStmt represents a variable assignment.

func (*AssignStmt) Pos

func (s *AssignStmt) Pos() Position

type BinaryExpr

type BinaryExpr struct {
	Left     Expression
	Operator TokenType
	Right    Expression
	Position Position
}

BinaryExpr represents a binary operator expression (e.g. a + b).

func (*BinaryExpr) Pos

func (e *BinaryExpr) Pos() Position

type BlockLiteral

type BlockLiteral struct {
	Params         []Param
	ImplicitParams []string
	Body           []Statement
	Position       Position
}

BlockLiteral represents an inline block attached to a call. A block is syntax, not a value: it only ever appears in the block position of a call and runs synchronously for the duration of that call (ADR-006).

func (*BlockLiteral) Pos

func (b *BlockLiteral) Pos() Position

type BoolLiteral

type BoolLiteral struct {
	Value    bool
	Position Position
}

BoolLiteral represents a boolean constant (true or false).

func (*BoolLiteral) Pos

func (e *BoolLiteral) Pos() Position

type BreakStmt

type BreakStmt struct {
	Value    Expression
	Position Position
}

BreakStmt represents a break statement that exits a loop.

func (*BreakStmt) Pos

func (s *BreakStmt) Pos() Position

type CallExpr

type CallExpr struct {
	Callee Expression
	Args   []Expression
	KwArgs []KeywordArg
	// KeywordOptionsHash marks calls whose keyword arguments are eligible to
	// collapse into a trailing positional options hash when the callee has no
	// matching keyword parameter, mirroring how Ruby binds an options hash to a
	// positional parameter. It is set for parenless calls and for parenthesized
	// calls; the runtime applies the collapse only when the resolved callee
	// supports it. Parenthesized member calls additionally consult
	// Parenthesized so method and constructor calls stay strict while a
	// function value's call alias keeps direct-call parity.
	KeywordOptionsHash bool
	// Parenthesized reports whether the call used explicit parentheses. The
	// runtime keeps parenthesized method and constructor calls strict, so it
	// only collapses their keyword arguments into an options hash for the
	// parenless form.
	Parenthesized bool
	// SpacedParen reports that whitespace separated the callee from its
	// opening parenthesis (`f (x)` rather than `f(x)`). The two produce the
	// same call here, but Ruby reads the spaced form as a command whose
	// argument is the whole parenthesised expression, so `f (x).length` means
	// different things in the two languages. Nothing in the AST would
	// otherwise record which was written.
	SpacedParen bool
	// SpacedParenTakesMember reports that this spaced-paren call is the
	// receiver of a member access (`f (x).length`). That is the one shape
	// where the space changes the program's meaning rather than only its
	// spelling: Ruby binds the member access inside the argument and answers
	// f((x).length), while this language binds it to the call's result. Both
	// readings are plausible, both produce a value, and nothing else marks
	// which one was written.
	SpacedParenTakesMember bool
	// Safe reports whether the call used the safe-navigation operator
	// (`receiver&.method(...)`). When set and the receiver evaluates to nil,
	// the runtime short-circuits the call to nil instead of dispatching. It is
	// meaningful only when Callee is a *MemberExpr whose Safe flag is also set.
	Safe     bool
	Block    *BlockLiteral
	Position Position
}

CallExpr represents a function or method call.

func (*CallExpr) Pos

func (e *CallExpr) Pos() Position

type CaseExpr

type CaseExpr struct {
	// Target is nil for targetless case expressions where each when value is
	// evaluated as a predicate.
	Target   Expression
	Clauses  []CaseWhenClause
	ElseExpr Expression
	Position Position
}

CaseExpr represents a case/when expression.

func (*CaseExpr) Pos

func (e *CaseExpr) Pos() Position

type CaseWhenClause

type CaseWhenClause struct {
	Values []CaseWhenValue
	Result Expression
}

CaseWhenClause represents a single when branch in a case expression.

type CaseWhenValue added in v0.60.0

type CaseWhenValue struct {
	Expr  Expression
	Splat bool
}

CaseWhenValue represents one value in a case/when branch.

type ClassMemberDecl added in v0.60.0

type ClassMemberDecl struct {
	Function   *FunctionStmt
	Alias      *AliasStmt
	Property   *PropertyDecl
	Visibility *VisibilityDecl
}

ClassMemberDecl preserves the source order of class-level declarations.

type ClassStmt

type ClassStmt struct {
	Name         string
	IsModule     bool
	Members      []ClassMemberDecl
	Methods      []*FunctionStmt
	ClassMethods []*FunctionStmt
	Aliases      []*AliasStmt
	Properties   []PropertyDecl
	Modules      []*ClassStmt
	Body         []Statement
	Position     Position
}

ClassStmt represents a class or module definition. Module declarations (`module Name ... end`) share the class statement shape: IsModule is set, `def self.` module functions land in ClassMethods, and nested module declarations are collected in Modules. A module is a namespace, so it declares no instance-style members and Methods stays empty for one.

func (*ClassStmt) Pos

func (s *ClassStmt) Pos() Position

type ClassVarExpr

type ClassVarExpr struct {
	Name     string
	Position Position
}

ClassVarExpr represents a class variable reference (e.g. @@count).

func (*ClassVarExpr) Pos

func (e *ClassVarExpr) Pos() Position

type ConditionalExpr added in v0.60.0

type ConditionalExpr struct {
	Condition  Expression
	Consequent Expression
	Alternate  Expression
	Position   Position
}

ConditionalExpr represents a ternary conditional expression (e.g. condition ? consequent : alternate).

func (*ConditionalExpr) Pos added in v0.60.0

func (e *ConditionalExpr) Pos() Position

type DestructureElement added in v0.60.0

type DestructureElement struct {
	Target   Expression
	Type     *TypeExpr
	Rest     bool
	Position Position
}

DestructureElement represents one target in a destructuring assignment. An anonymous rest target (a bare "*") has a nil Target with Rest set true; its Position records the location of the "*" for diagnostics.

type DestructureTarget added in v0.60.0

type DestructureTarget struct {
	Elements []DestructureElement
	Position Position
	// contains filtered or unexported fields
}

DestructureTarget represents a comma-separated assignment target list.

func NewDestructureTarget added in v0.60.0

func NewDestructureTarget(elements []DestructureElement, position Position) *DestructureTarget

NewDestructureTarget builds a destructuring target with its syntactic facts settled. Every nested target is built before the target that contains it, so each node's facts follow from its own elements in one pass.

func (*DestructureTarget) BindsAnyValue added in v0.60.0

func (e *DestructureTarget) BindsAnyValue() bool

BindsAnyValue reports whether at least one element of the target binds a value out of the right-hand side.

func (*DestructureTarget) Pos added in v0.60.0

func (e *DestructureTarget) Pos() Position

func (*DestructureTarget) WriteIsReadBack added in v0.60.0

func (e *DestructureTarget) WriteIsReadBack() bool

WriteIsReadBack reports whether the target contains a leaf that assigns into an existing container followed, in left-to-right execution order, by a leaf that reads a value out of the right-hand side. Only that ordering lets a later read observe an earlier write's mutation of an aliased right-hand-side array, so it is the only case that needs a defensive snapshot.

A write whose only successors discard their window (for example "values[0], * = values", where the trailing anonymous rest reads nothing, or "values[0], (*) = values", where the nested follower destructures nothing) is safe to alias: no surviving read can observe the mutation, so snapshotting it would copy the whole backing slice for no observable effect. Plain identifiers, ivars, and class vars write to environment or instance slots that never alias the array's backing store, so they count only as reads.

func (*DestructureTarget) WritesIntoContainer added in v0.60.0

func (e *DestructureTarget) WritesIntoContainer() bool

WritesIntoContainer reports whether any leaf of the target assigns into an existing container slot.

type EnumMemberStmt

type EnumMemberStmt struct {
	Name     string
	Position Position
}

EnumMemberStmt represents a single member in an enum definition.

type EnumStmt

type EnumStmt struct {
	Name     string
	Members  []EnumMemberStmt
	Position Position
}

EnumStmt represents an enum definition.

func (*EnumStmt) Pos

func (s *EnumStmt) Pos() Position

type ExprStmt

type ExprStmt struct {
	Expr     Expression
	Position Position
}

ExprStmt wraps an expression used as a statement.

func (*ExprStmt) Pos

func (s *ExprStmt) Pos() Position

type Expression

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

Expression is the interface implemented by all expression AST nodes.

type FloatLiteral

type FloatLiteral struct {
	Value    float64
	Position Position
}

FloatLiteral represents a floating-point constant.

func (*FloatLiteral) Pos

func (e *FloatLiteral) Pos() Position

type ForStmt

type ForStmt struct {
	Target   Expression
	Iterable Expression
	Body     []Statement
	Position Position
}

ForStmt represents a for-in loop.

func (*ForStmt) Pos

func (s *ForStmt) Pos() Position

type FunctionStmt

type FunctionStmt struct {
	Name          string
	Params        []Param
	ReturnTy      *TypeExpr
	Body          []Statement
	IsClassMethod bool
	Exported      bool
	Private       bool
	// Visibility records an inline visibility modifier (`private def`,
	// `public def`, `protected def`) on a class-body definition. It is empty
	// when the definition carries no inline modifier and inherits the
	// surrounding section directive instead.
	Visibility string
	Position   Position
}

FunctionStmt represents a function or method definition.

func (*FunctionStmt) Pos

func (s *FunctionStmt) Pos() Position

type HashLiteral

type HashLiteral struct {
	Pairs     []HashPair
	ShapeType *TypeExpr
	Position  Position
}

HashLiteral represents a hash/map literal expression.

ShapeType is set when the braced group also reads cleanly as a shape under the type grammar with built-in leaf types (ADR-004 expression-position shapes, e.g. the schema argument of JSON.parse_as). The choice between the two readings is deferred to evaluation: the group is a first-class shape value unless one of its type names is shadowed by a runtime binding (a host-provided global such as `string`), in which case it keeps the pre-existing hash semantics and Pairs evaluate normally. A group that parses only as a shape (e.g. `{ note: string | nil }`) carries ShapeType with no Pairs and always evaluates as a shape.

func (*HashLiteral) Pos

func (e *HashLiteral) Pos() Position

type HashPair

type HashPair struct {
	Key   Expression
	Value Expression
}

HashPair represents a single key-value pair in a hash literal.

type Identifier

type Identifier struct {
	Name     string
	Position Position
}

Identifier represents a named reference in an expression.

func (*Identifier) Pos

func (e *Identifier) Pos() Position

type IfExpr added in v0.60.0

type IfExpr struct {
	Condition  Expression
	Consequent Expression
	ElseIf     []IfExprBranch
	Alternate  Expression
	Position   Position
}

IfExpr represents a value-producing if/elsif/else expression.

func (*IfExpr) Pos added in v0.60.0

func (e *IfExpr) Pos() Position

type IfExprBranch added in v0.60.0

type IfExprBranch struct {
	Condition Expression
	Result    Expression
}

IfExprBranch represents one elsif branch in an if expression.

type IfStmt

type IfStmt struct {
	Condition         Expression
	Consequent        []Statement
	ElseIf            []*IfStmt
	Alternate         []Statement
	AlternateFirst    bool
	ModifierBodyFirst bool
	Position          Position
}

IfStmt represents an if/elsif/else conditional statement.

func (*IfStmt) Pos

func (s *IfStmt) Pos() Position

type IndexExpr

type IndexExpr struct {
	Object   Expression
	Indices  []Expression
	Position Position
}

IndexExpr represents a bracket-index access (e.g. arr[0]). Indices holds the one or more comma-separated selectors between the brackets, supporting Ruby's single-index (arr[i]), start/length (arr[start, length]), and range (arr[range]) forms.

func (*IndexExpr) IndexPos added in v0.60.0

func (e *IndexExpr) IndexPos(i int) Position

IndexPos returns the source position of the i-th selector for diagnostics, falling back to the bracket position when i is out of range.

func (*IndexExpr) Pos

func (e *IndexExpr) Pos() Position

type IntegerLiteral

type IntegerLiteral struct {
	Value int64
	// Big carries the literal's value when it does not fit in int64 (Value is
	// then 0 and meaningless). It is immutable after parsing: consumers wrap
	// it with value.NewBigInt, which copies, and clones share the pointer.
	Big      *big.Int
	Position Position
}

IntegerLiteral represents an integer constant.

func (*IntegerLiteral) Pos

func (e *IntegerLiteral) Pos() Position

type InterpolatedString

type InterpolatedString struct {
	Parts    []StringPart
	Position Position
}

InterpolatedString represents a string containing embedded expressions.

func (*InterpolatedString) Pos

func (s *InterpolatedString) Pos() Position

type InterpolatedSymbol added in v0.60.0

type InterpolatedSymbol struct {
	Parts    []StringPart
	Position Position
}

InterpolatedSymbol represents a symbol whose name is built from an interpolating literal (e.g. an entry of a %I[...] array). The parts are evaluated like an interpolated string and the resulting text becomes the symbol's name.

func (*InterpolatedSymbol) Pos added in v0.60.0

func (s *InterpolatedSymbol) Pos() Position

type IvarExpr

type IvarExpr struct {
	Name     string
	Position Position
}

IvarExpr represents an instance variable reference (e.g. @name).

func (*IvarExpr) Pos

func (e *IvarExpr) Pos() Position

type KeywordArg

type KeywordArg struct {
	Name  string
	Value Expression
	// Splat marks a keyword splat argument (`f(**opts)`): Name is empty and
	// Value evaluates to a hash whose entries expand into the call's keyword
	// arguments in source order, later entries winning on duplicate keys.
	Splat bool
}

KeywordArg represents a named argument in a function call.

type MemberExpr

type MemberExpr struct {
	Object   Expression
	Property string
	// Safe reports whether the access used the safe-navigation operator
	// (`object&.prop`). When set and the object evaluates to nil, the runtime
	// short-circuits the access to nil instead of looking up the member.
	Safe     bool
	Position Position
}

MemberExpr represents a dot-access property lookup (e.g. obj.prop).

func (*MemberExpr) Pos

func (e *MemberExpr) Pos() Position

type NextStmt

type NextStmt struct {
	Value    Expression
	Position Position
}

NextStmt represents a next statement that skips to the next loop iteration.

func (*NextStmt) Pos

func (s *NextStmt) Pos() Position

type NilLiteral

type NilLiteral struct {
	Position Position
}

NilLiteral represents the nil literal.

func (*NilLiteral) Pos

func (e *NilLiteral) Pos() Position

type Node

type Node interface {
	Pos() Position
}

Node is the interface implemented by all AST nodes.

type Param

type Param struct {
	Name       string
	Kind       ParamKind
	Type       *TypeExpr
	DefaultVal Expression
	IsIvar     bool
	Target     Expression
	// PropertyType is the declared property contract backing an unannotated
	// ivar parameter, resolved when the owning class compiles. It shapes
	// argument and default evaluation (a callable-typed contract keeps a
	// bare zero-arity callable un-invoked) while binding validation stays
	// with the ivar write itself.
	PropertyType *TypeExpr
}

Param represents a function or block parameter.

func CloneParams

func CloneParams(params []Param) []Param

CloneParams returns a deep copy of the given parameter list.

func CloneParamsWithTypeMemo added in v0.60.0

func CloneParamsWithTypeMemo(params []Param, memo TypeExprMemo) []Param

CloneParamsWithTypeMemo deep-copies params like CloneParams, but copies each distinct type expression only once across the whole clone and reuses that copy everywhere the source reached the same node.

Two kinds of sharing make that worth doing, and neither is visible from a single param. A param's PropertyType is not its own annotation: it points at the contract the class's generated accessor declares once, so every unannotated ivar param naming that property carries the same node. And a method mixed in from a module is a shallow copy, so every class including that module reaches the module's own annotation nodes. Copying per param and per class turned a type the source spells once into O(params * type size) and O(classes * type size): host-cloning a class with a 1000-field property type and 500 `def mN(@x)` methods retained 80MB from a 38KB script. Memoizing holds that at 0.5MB while still giving the clone nodes of its own, so a caller that mutates a returned snapshot cannot reach back into the compiled script (#16).

A nil memo copies every node, which is what the plain clone entry points do: they clone one statement or expression, where nothing is shared to begin with.

type ParamKind added in v0.60.0

type ParamKind int

ParamKind identifies how a function parameter receives values.

const (
	ParamNormal ParamKind = iota
	ParamKeyword
	ParamRest
	ParamKeywordRest
)

type Position

type Position = source.Position

Position is an alias for source.Position so that AST consumers can receive positions without importing the source package directly.

type Program

type Program struct {
	Statements []Statement
}

Program represents the top-level AST node containing all statements.

func (*Program) Pos

func (p *Program) Pos() Position

type PropertyDecl

type PropertyDecl struct {
	Names []PropertyName
	Kind  string // property/getter/setter
	// Visibility records an inline visibility modifier
	// (`private property secret`); empty means the declaration inherits the
	// surrounding section directive.
	Visibility string
	Position   Position
}

PropertyDecl represents a property, getter, or setter declaration in a class.

type PropertyName added in v0.60.0

type PropertyName struct {
	Name string
	Type *TypeExpr
}

PropertyName is a single accessor name with an optional type annotation.

type RaiseStmt

type RaiseStmt struct {
	Value    Expression
	Message  Expression
	Position Position
}

RaiseStmt represents a raise statement that throws an error.

func (*RaiseStmt) Pos

func (s *RaiseStmt) Pos() Position

type RangeExpr

type RangeExpr struct {
	Start     Expression
	End       Expression
	Exclusive bool
	Position  Position
}

RangeExpr represents a range expression (e.g. 1..10).

func (*RangeExpr) Pos

func (e *RangeExpr) Pos() Position

type RegexLiteral added in v0.60.0

type RegexLiteral struct {
	Pattern  string
	Flags    string
	Position Position
}

RegexLiteral represents a Ruby-style regex literal such as /pattern/i. The pattern is the raw source between the slashes (Go RE2 syntax) and Flags holds the trailing flag letters in source order.

func (*RegexLiteral) Pos added in v0.60.0

func (e *RegexLiteral) Pos() Position

type RescueClause added in v0.60.0

type RescueClause struct {
	Ty       *TypeExpr
	Binding  string
	Body     []Statement
	Position Position
}

RescueClause is one ordered handler in a begin/rescue block. Ty narrows the error classes the clause handles (nil catches any rescuable error), Binding names the rescued error inside Body, and Position is the rescue keyword's.

type RescueExpr added in v0.60.0

type RescueExpr struct {
	Body     Expression
	Fallback Expression
	Position Position
}

RescueExpr represents a Ruby-style rescue modifier expression (e.g. risky_call rescue fallback).

func (*RescueExpr) Pos added in v0.60.0

func (e *RescueExpr) Pos() Position

type RetryStmt added in v0.60.0

type RetryStmt struct {
	Position Position
}

RetryStmt represents a retry statement inside a rescue handler.

func (*RetryStmt) Pos added in v0.60.0

func (s *RetryStmt) Pos() Position

type ReturnStmt

type ReturnStmt struct {
	Value    Expression
	Position Position
}

ReturnStmt represents a return statement.

func (*ReturnStmt) Pos

func (s *ReturnStmt) Pos() Position

type ScopeExpr

type ScopeExpr struct {
	Object   Expression
	Property string
	Position Position
}

ScopeExpr represents a scope-resolution access (e.g. Mod::Name).

func (*ScopeExpr) Pos

func (e *ScopeExpr) Pos() Position

type SplatArg added in v0.60.0

type SplatArg struct {
	Value    Expression
	Position Position
}

SplatArg represents a positional splat argument in a call (`f(*args)`). Value evaluates to an array whose elements expand into the call's positional arguments in place. It only ever appears inside CallExpr.Args.

func (*SplatArg) Pos added in v0.60.0

func (e *SplatArg) Pos() Position

type Statement

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

Statement is the interface implemented by all statement AST nodes.

func CloneStatements

func CloneStatements(statements []Statement) []Statement

CloneStatements returns a deep copy of the given statement slice.

type StringExpr

type StringExpr struct {
	Expr Expression
}

StringExpr represents an embedded expression segment in an interpolated string.

type StringLiteral

type StringLiteral struct {
	Value    string
	Position Position
}

StringLiteral represents a plain string constant.

func (*StringLiteral) Pos

func (e *StringLiteral) Pos() Position

type StringPart

type StringPart interface {
	// contains filtered or unexported methods
}

StringPart is the interface for parts of an interpolated string.

type StringText

type StringText struct {
	Text string
}

StringText represents a literal text segment in an interpolated string.

type SymbolLiteral

type SymbolLiteral struct {
	Name     string
	Position Position
}

SymbolLiteral represents a symbol literal (e.g. :foo).

func (*SymbolLiteral) Pos

func (e *SymbolLiteral) Pos() Position

type Token

type Token struct {
	Type    TokenType
	Literal string
	Pos     source.Position
	// End is the exclusive position just past the token's final rune,
	// stamped by the lexer from the source text. It is the zero
	// Position only for EOF.
	End source.Position
	// Diagnostic marks an illegal token whose Literal is a human-readable
	// lexer diagnostic (such as a malformed numeric literal) rather than the
	// raw offending source text. The parser surfaces such literals verbatim,
	// while plain illegal characters fall back to a generic message.
	Diagnostic bool
}

Token captures lexical information for the parser.

type TokenType

type TokenType int

TokenType identifies the lexical category of a token.

const (
	// TokenNone is the zero TokenType: no token. A zero-valued Token carries
	// it, and AST nodes whose operator slot is empty (a plain assignment's
	// Operator, for example) hold it where the string-typed representation
	// held "". It is never produced by the lexer.
	TokenNone TokenType = iota
	TokenIllegal
	TokenEOF

	TokenIdent
	TokenInt
	TokenFloat
	TokenString
	TokenInterpolatedString
	TokenSymbol
	TokenWords
	TokenSymbols
	TokenInterpWords
	TokenInterpSymbols
	TokenRegex

	TokenAssign
	TokenPlusAssign
	TokenMinusAssign
	TokenAsteriskAssign
	TokenPowerAssign
	TokenSlashAssign
	TokenPercentAssign
	TokenAndAssign
	TokenOrAssign
	TokenPlus
	TokenMinus
	TokenBang
	TokenAsterisk
	TokenPower
	TokenSlash
	TokenPercent
	TokenLT
	TokenShovel
	TokenGT
	TokenLTE
	TokenGTE
	TokenSpaceship
	TokenEQ
	TokenCaseEQ
	TokenNotEQ
	TokenMatch
	TokenNotMatch
	TokenAnd
	TokenOr
	TokenAmpersand
	TokenQuestion

	TokenComma
	TokenSemicolon
	TokenColon
	TokenScope
	TokenDot
	TokenSafeNav
	TokenRange
	TokenRangeExcl
	TokenLParen
	TokenRParen
	TokenLBrace
	TokenRBrace
	TokenLBracket
	TokenRBracket
	TokenPipe
	TokenArrow
	TokenThinArrow
	TokenIvar
	TokenClassVar

	TokenDef
	TokenClass
	TokenEnum
	TokenExport
	TokenSelf
	TokenPrivate
	TokenProperty
	TokenGetter
	TokenSetter
	TokenBegin
	TokenRescue
	TokenEnsure
	TokenRaise
	TokenEnd
	TokenReturn
	TokenYield
	TokenDo
	TokenThen
	TokenFor
	TokenWhile
	TokenUntil
	TokenBreak
	TokenNext
	TokenRetry
	TokenIn
	TokenIf
	TokenUnless
	TokenCase
	TokenWhen
	TokenElsif
	TokenElse
	TokenTrue
	TokenFalse
	TokenNil
)

func LookupIdent

func LookupIdent(ident string) TokenType

LookupIdent returns the TokenType for an identifier literal, falling back to TokenIdent when the input is not a reserved keyword.

func (TokenType) String added in v0.60.0

func (t TokenType) String() string

String returns the token type's source spelling for operators and punctuation, and its diagnostic name for literal classes, exactly as the previous string-typed constants read.

type TryStmt

type TryStmt struct {
	Body     []Statement
	Rescues  []RescueClause
	Else     []Statement
	Ensure   []Statement
	Position Position
}

TryStmt represents a begin/rescue/ensure error-handling block. Rescues holds the handlers in source order; at runtime the first clause whose type matches the raised error handles it, mirroring Ruby's ordered rescue dispatch.

func (*TryStmt) Pos

func (s *TryStmt) Pos() Position

type TypeExpr

type TypeExpr struct {
	Name     string
	Kind     TypeKind
	Nullable bool
	// Optional marks a shape field that may be absent from the value
	// (`age?: int`). It is set only on the field types stored in a Shape map
	// and is distinct from Nullable: an optional field validates against the
	// field type when present, while a nullable field must be present but may
	// hold nil.
	Optional bool
	// Open marks a shape that permits undeclared extra fields
	// (`{ name: string, ... }`). Declared fields keep their contracts; extra
	// fields pass validation unchecked. It is meaningful only on TypeShape
	// nodes; shapes stay exact (closed) by default.
	Open     bool
	TypeArgs []*TypeExpr
	Shape    map[string]*TypeExpr
	Union    []*TypeExpr
	Position Position
}

TypeExpr represents a type annotation in the source code.

func CloneTypeExpr

func CloneTypeExpr(ty *TypeExpr) *TypeExpr

CloneTypeExpr returns a deep copy of the given type expression.

func CloneTypeExprWithMemo added in v0.60.0

func CloneTypeExprWithMemo(ty *TypeExpr, memo TypeExprMemo) *TypeExpr

CloneTypeExprWithMemo copies one type expression through the same memo, for the nodes that hang off a function rather than off a param (its return type).

type TypeExprMemo added in v0.60.0

type TypeExprMemo map[*TypeExpr]*TypeExpr

TypeExprMemo carries the type expressions one clone operation has already copied, keyed by the node they were copied from. See CloneParamsWithTypeMemo.

func NewTypeExprMemo added in v0.60.0

func NewTypeExprMemo() TypeExprMemo

NewTypeExprMemo returns a memo for a single clone operation. A memo must not outlive the clone it belongs to, or a later clone would hand out nodes owned by an earlier one.

type TypeKind

type TypeKind int

TypeKind identifies the category of a type expression.

const (
	// TypeAny is the unconstrained type that matches any value.
	TypeAny TypeKind = iota
	TypeInt
	TypeFloat
	TypeNumber
	TypeString
	TypeBool
	TypeNil
	TypeDuration
	TypeTime
	TypeMoney
	TypeArray
	TypeHash
	TypeRange
	TypeSymbol
	TypeFunction
	TypeShape
	TypeUnion
	TypeEnum
	TypeUnknown
)

func ResolveType

func ResolveType(name string) (TypeKind, bool)

ResolveType maps a textual type name (with optional trailing "?" to mark nullability) to its TypeKind. It returns TypeUnknown when the name does not match a built-in type.

type TypeLiteral added in v0.60.0

type TypeLiteral struct {
	Type     *TypeExpr
	Fallback Expression
	Position Position
}

TypeLiteral represents a call argument that reads as a type annotation (`JSON.parse_as(raw, array<int>)`), extending ADR-004's expression-position shape literals to non-shape roots. Fallback carries the group's value reading (`int | nil` as a bitwise-or of identifiers, for example), used when a type name is shadowed by a runtime binding; a group with no value reading (`array<int>`) has a nil Fallback and always evaluates to the type value. It only ever appears inside CallExpr.Args.

func (*TypeLiteral) Pos added in v0.60.0

func (e *TypeLiteral) Pos() Position

type UnaryExpr

type UnaryExpr struct {
	Operator TokenType
	Right    Expression
	Position Position
}

UnaryExpr represents a unary operator expression (e.g. -x, !y).

func (*UnaryExpr) Pos

func (e *UnaryExpr) Pos() Position

type UntilStmt

type UntilStmt struct {
	Condition Expression
	Body      []Statement
	BodyFirst bool
	Position  Position
}

UntilStmt represents an until loop (loops while condition is false).

func (*UntilStmt) Pos

func (s *UntilStmt) Pos() Position

type VisibilityDecl added in v0.60.0

type VisibilityDecl struct {
	Level    string
	Names    []string
	Position Position
}

VisibilityDecl represents a `public`, `private`, or `protected` directive in a class body. An empty Names list is a section directive that applies to the definitions that follow it; a non-empty list (`private :hidden, :other`) retroactively sets the visibility of the named methods.

type WhileStmt

type WhileStmt struct {
	Condition Expression
	Body      []Statement
	BodyFirst bool
	Position  Position
}

WhileStmt represents a while loop.

func (*WhileStmt) Pos

func (s *WhileStmt) Pos() Position

type YieldExpr

type YieldExpr struct {
	Args     []Expression
	Position Position
}

YieldExpr represents a yield call that invokes the enclosing block.

func (*YieldExpr) Pos

func (y *YieldExpr) Pos() Position

Jump to

Keyboard shortcuts

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