ast

package
v1.0.0-rc8 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 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.

View Source
const (
	MixinInclude = "include"
	MixinExtend  = "extend"
)

Mixin directive kinds.

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
	// Lambda marks a stabby lambda literal (`->(x) { ... }`). A lambda is a
	// first-class expression that evaluates to a callable value with strict
	// arity and method-like (local) return/break semantics, unlike a plain
	// block literal, which only ever appears attached to a call.
	Lambda   bool
	Position Position
}

BlockLiteral represents an inline block (closure) expression.

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
	// 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
	// BlockArg holds a Ruby-style ampersand block argument (`f(&blk)`,
	// `f(&:name)`): the expression after `&`, evaluated at call time and
	// converted into the call's block. It is mutually exclusive with Block —
	// the parser rejects a call that supplies both — and must be the last
	// argument.
	BlockArg Expression
	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
	Mixin      *MixinDecl
}

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, instance-style methods land in Methods (mixed into classes via include), `def self.` module functions land in ClassMethods, and nested module declarations are collected in Modules.

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
}

DestructureTarget represents a comma-separated assignment target list.

func (*DestructureTarget) Pos added in v0.60.0

func (e *DestructureTarget) Pos() Position

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 MixinDecl

type MixinDecl struct {
	Kind     string // MixinInclude or MixinExtend
	Modules  []MixinRef
	Position Position
}

MixinDecl represents an `include` or `extend` directive in a class or module body. Include mixes a module's instance-style methods into the declaring class's instance methods; extend mixes them into its class methods.

type MixinRef

type MixinRef struct {
	Name     string
	Position Position
}

MixinRef names one module in an include/extend directive. Name preserves any scope qualification as written (`Support::Naming`).

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.

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
	ParamBlock
)

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 string

TokenType identifies the lexical category of a token.

const (
	TokenIllegal TokenType = "ILLEGAL"
	TokenEOF     TokenType = "EOF"

	TokenIdent              TokenType = "IDENT"
	TokenInt                TokenType = "INT"
	TokenFloat              TokenType = "FLOAT"
	TokenString             TokenType = "STRING"
	TokenInterpolatedString TokenType = "INTERPOLATED_STRING"
	TokenSymbol             TokenType = "SYMBOL"
	TokenWords              TokenType = "WORDS"
	TokenSymbols            TokenType = "SYMBOLS"
	TokenInterpWords        TokenType = "INTERP_WORDS"
	TokenInterpSymbols      TokenType = "INTERP_SYMBOLS"
	TokenRegex              TokenType = "REGEX"

	TokenAssign         TokenType = "="
	TokenPlusAssign     TokenType = "+="
	TokenMinusAssign    TokenType = "-="
	TokenAsteriskAssign TokenType = "*="
	TokenPowerAssign    TokenType = "**="
	TokenSlashAssign    TokenType = "/="
	TokenPercentAssign  TokenType = "%="
	TokenAndAssign      TokenType = "&&="
	TokenOrAssign       TokenType = "||="
	TokenPlus           TokenType = "+"
	TokenMinus          TokenType = "-"
	TokenBang           TokenType = "!"
	TokenAsterisk       TokenType = "*"
	TokenPower          TokenType = "**"
	TokenSlash          TokenType = "/"
	TokenPercent        TokenType = "%"
	TokenLT             TokenType = "<"
	TokenShovel         TokenType = "<<"
	TokenGT             TokenType = ">"
	TokenLTE            TokenType = "<="
	TokenGTE            TokenType = ">="
	TokenSpaceship      TokenType = "<=>"
	TokenEQ             TokenType = "=="
	TokenCaseEQ         TokenType = "==="
	TokenNotEQ          TokenType = "!="
	TokenMatch          TokenType = "=~"
	TokenNotMatch       TokenType = "!~"
	TokenAnd            TokenType = "&&"
	TokenOr             TokenType = "||"
	TokenAmpersand      TokenType = "&"
	TokenQuestion       TokenType = "?"

	TokenComma     TokenType = ","
	TokenSemicolon TokenType = ";"
	TokenColon     TokenType = ":"
	TokenScope     TokenType = "::"
	TokenDot       TokenType = "."
	TokenSafeNav   TokenType = "&."
	TokenRange     TokenType = ".."
	TokenRangeExcl TokenType = "..."
	TokenLParen    TokenType = "("
	TokenRParen    TokenType = ")"
	TokenLBrace    TokenType = "{"
	TokenRBrace    TokenType = "}"
	TokenLBracket  TokenType = "["
	TokenRBracket  TokenType = "]"
	TokenPipe      TokenType = "|"
	TokenArrow     TokenType = "=>"
	TokenThinArrow TokenType = "->"
	TokenIvar      TokenType = "IVAR"
	TokenClassVar  TokenType = "CLASSVAR"

	TokenDef      TokenType = "DEF"
	TokenClass    TokenType = "CLASS"
	TokenEnum     TokenType = "ENUM"
	TokenExport   TokenType = "EXPORT"
	TokenSelf     TokenType = "SELF"
	TokenPrivate  TokenType = "PRIVATE"
	TokenProperty TokenType = "PROPERTY"
	TokenGetter   TokenType = "GETTER"
	TokenSetter   TokenType = "SETTER"
	TokenBegin    TokenType = "BEGIN"
	TokenRescue   TokenType = "RESCUE"
	TokenEnsure   TokenType = "ENSURE"
	TokenRaise    TokenType = "RAISE"
	TokenEnd      TokenType = "END"
	TokenReturn   TokenType = "RETURN"
	TokenYield    TokenType = "YIELD"
	TokenDo       TokenType = "DO"
	TokenThen     TokenType = "THEN"
	TokenFor      TokenType = "FOR"
	TokenWhile    TokenType = "WHILE"
	TokenUntil    TokenType = "UNTIL"
	TokenBreak    TokenType = "BREAK"
	TokenNext     TokenType = "NEXT"
	TokenRetry    TokenType = "RETRY"
	TokenIn       TokenType = "IN"
	TokenIf       TokenType = "IF"
	TokenUnless   TokenType = "UNLESS"
	TokenCase     TokenType = "CASE"
	TokenWhen     TokenType = "WHEN"
	TokenElsif    TokenType = "ELSIF"
	TokenElse     TokenType = "ELSE"
	TokenTrue     TokenType = "TRUE"
	TokenFalse    TokenType = "FALSE"
	TokenNil      TokenType = "NIL"
)

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.

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.

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