parser

package
v0.9.4 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LOWEST        int
	COMMA         // , (very low precedence, but higher than LOWEST)
	ARG_SEPARATOR // Virtual precedence level for argument list parsing (between COMMA and ASSIGNMENT)
	ASSIGNMENT    // =, +=, -=, *=, /=, %=, **=, &=, |=, ^=, <<=, >>=, >>>=, &&=, ||=, ??=
	TERNARY       // ?:
	COALESCE      // ??
	LOGICAL_OR    // ||
	LOGICAL_AND   // &&
	BITWISE_OR    // |  (Lower than XOR)
	BITWISE_XOR   // ^  (Lower than AND)
	BITWISE_AND   // &  (Lower than Equality)
	EQUALS        // ==, !=, ===, !==
	LESSGREATER   // >, <, >=, <=
	SHIFT         // <<, >>, >>> (Lower than Add/Sub)
	SUM           // + or -
	PRODUCT       // * or / or %
	POWER         // ** (Right-associative handled in parseInfix)
	PREFIX        // -X or !X or ++X or --X or ~X
	POSTFIX       // X++ or X--
	ASSERTION     // value as Type
	CALL          // myFunction(X)
	INDEX         // array[index]
	MEMBER        // object.property
)

Precedence levels for VALUE operators

View Source
const (
	TYPE_LOWEST       int
	TYPE_CONDITIONAL  // extends ? : (Very low precedence - should be parsed last)
	TYPE_PREDICATE    // is (Lower precedence - should be parsed last)
	TYPE_UNION        // |
	TYPE_INTERSECTION // &  (Higher precedence than union)
	TYPE_ARRAY        // [] (Higher precedence than intersection)
	TYPE_MEMBER       // . (Highest precedence - member access)
)

--- NEW: Type Precedence ---

Variables

View Source
var DumpASTEnabled = false

DumpASTEnabled controls whether AST dumping is enabled

Functions

func DumpAST

func DumpAST(program *Program, title string)

DumpAST prints a structured representation of the AST to stderr if enabled

func GetTokenFromNode

func GetTokenFromNode(node Node) lexer.Token

GetTokenFromNode attempts to extract the primary token associated with a parser node. This is useful for getting line numbers for error reporting. Returns the zero value of lexer.Token if no specific token can be easily extracted.

Types

type ArrayDestructuringAssignment

type ArrayDestructuringAssignment struct {
	BaseExpression                         // Embed base for ComputedType
	Token          lexer.Token             // The '[' token
	Elements       []*DestructuringElement // Target variables/patterns
	Value          Expression              // RHS expression to destructure
}

ArrayDestructuringAssignment represents [a, b, c] = expr

func (*ArrayDestructuringAssignment) String

func (ada *ArrayDestructuringAssignment) String() string

func (*ArrayDestructuringAssignment) TokenLiteral

func (ada *ArrayDestructuringAssignment) TokenLiteral() string

type ArrayDestructuringDeclaration

type ArrayDestructuringDeclaration struct {
	Token          lexer.Token             // The 'let', 'const', or 'var' token
	IsConst        bool                    // true for const, false for let/var
	Elements       []*DestructuringElement // Target variables/patterns
	TypeAnnotation Expression              // Optional type annotation (e.g., : [number, string])
	Value          Expression              // RHS expression to destructure
}

ArrayDestructuringDeclaration represents let/const/var [a, b, c] = expr

func (*ArrayDestructuringDeclaration) String

func (add *ArrayDestructuringDeclaration) String() string

func (*ArrayDestructuringDeclaration) TokenLiteral

func (add *ArrayDestructuringDeclaration) TokenLiteral() string

type ArrayLiteral

type ArrayLiteral struct {
	BaseExpression             // Embed base for ComputedType (e.g., types.ArrayType)
	Token          lexer.Token // The '[' token
	Elements       []Expression
}

ArrayLiteral represents an array literal expression (e.g., [1, "two"]).

func (*ArrayLiteral) String

func (al *ArrayLiteral) String() string

func (*ArrayLiteral) TokenLiteral

func (al *ArrayLiteral) TokenLiteral() string

type ArrayParameterPattern

type ArrayParameterPattern struct {
	BaseExpression                         // Embed base for ComputedType
	Token          lexer.Token             // The '[' token
	Elements       []*DestructuringElement // Parameter elements (can have defaults and rest)
}

ArrayParameterPattern represents array destructuring in function parameters Examples: ([a, b]: [number, number]) => {}

func (*ArrayParameterPattern) String

func (app *ArrayParameterPattern) String() string

func (*ArrayParameterPattern) TokenLiteral

func (app *ArrayParameterPattern) TokenLiteral() string

type ArrayTypeExpression

type ArrayTypeExpression struct {
	BaseExpression             // Embed base for ComputedType (types.ArrayType)
	Token          lexer.Token // The '[' token
	ElementType    Expression  // The type expression for the elements
}

ArrayTypeExpression represents an array type syntax (e.g., number[]).

func (*ArrayTypeExpression) String

func (ate *ArrayTypeExpression) String() string

func (*ArrayTypeExpression) TokenLiteral

func (ate *ArrayTypeExpression) TokenLiteral() string

type ArrowFunctionLiteral

type ArrowFunctionLiteral struct {
	BaseExpression                        // Embed base for ComputedType (Function type)
	Token                lexer.Token      // The '=>' token
	IsAsync              bool             // true for async arrow functions
	TypeParameters       []*TypeParameter // Generic type parameters (e.g., <T, U>)
	Parameters           []*Parameter     // Regular parameters
	RestParameter        *RestParameter   // Optional rest parameter (...args)
	ReturnTypeAnnotation Expression       // << MODIFIED
	Body                 Node             // Can be Expression or *BlockStatement
}

ArrowFunctionLiteral represents an arrow function definition. (<Parameters>) => <BodyExpression | BodyStatements>

func (*ArrowFunctionLiteral) String

func (afl *ArrowFunctionLiteral) String() string

func (*ArrowFunctionLiteral) TokenLiteral

func (afl *ArrowFunctionLiteral) TokenLiteral() string

type AssignmentExpression

type AssignmentExpression struct {
	BaseExpression             // Embed base for ComputedType (usually type of Value)
	Token          lexer.Token // The assignment token (e.g., '=', '+=')
	Operator       string      // The operator literal (e.g., "=", "+=")
	Left           Expression  // The target of the assignment (must be Identifier for now)
	Value          Expression  // The value being assigned
}

AssignmentExpression represents assignment (e.g., x = 5). Note: For now, only assignment to identifiers is supported. <Left Expression (Identifier)> = <Value Expression>

func (*AssignmentExpression) String

func (ae *AssignmentExpression) String() string

func (*AssignmentExpression) TokenLiteral

func (ae *AssignmentExpression) TokenLiteral() string

type AwaitExpression

type AwaitExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The 'await' token
	Argument       Expression  // The expression to await (typically a Promise)
}

AwaitExpression represents an await expression (async/await). await <Argument>

func (*AwaitExpression) String

func (ae *AwaitExpression) String() string

func (*AwaitExpression) TokenLiteral

func (ae *AwaitExpression) TokenLiteral() string

type BaseExpression

type BaseExpression struct {
	ComputedType types.Type
}

--- Base struct for Expressions to hold ComputedType --- (Optional but helps)

func (*BaseExpression) GetComputedType

func (be *BaseExpression) GetComputedType() types.Type

func (*BaseExpression) SetComputedType

func (be *BaseExpression) SetComputedType(t types.Type)

type BigIntLiteral

type BigIntLiteral struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.BIGINT token
	Value          string      // Store the numeric part (without 'n' suffix)
}

BigIntLiteral represents BigInt literals (e.g., 123n).

func (*BigIntLiteral) String

func (b *BigIntLiteral) String() string

func (*BigIntLiteral) TokenLiteral

func (b *BigIntLiteral) TokenLiteral() string

type BlockStatement

type BlockStatement struct {
	Token               lexer.Token // The { token
	Statements          []Statement
	HoistedDeclarations map[string]Expression // Changed: Store hoisted Expression within this block
}

BlockStatement represents a sequence of statements enclosed in braces. { <statement1>; <statement2>; ... }

func (*BlockStatement) String

func (bs *BlockStatement) String() string

func (*BlockStatement) TokenLiteral

func (bs *BlockStatement) TokenLiteral() string

type BooleanLiteral

type BooleanLiteral struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.TRUE or lexer.FALSE token
	Value          bool
}

BooleanLiteral represents `true` or `false`.

func (*BooleanLiteral) String

func (b *BooleanLiteral) String() string

func (*BooleanLiteral) TokenLiteral

func (b *BooleanLiteral) TokenLiteral() string

type BreakStatement

type BreakStatement struct {
	Token lexer.Token // The 'break' token
	Label *Identifier // Optional label to break to
}

--- New: Break Statement ---

func (*BreakStatement) String

func (bs *BreakStatement) String() string

func (*BreakStatement) TokenLiteral

func (bs *BreakStatement) TokenLiteral() string

type CallExpression

type CallExpression struct {
	BaseExpression                   // Embed base for ComputedType (Function's return type)
	Token               lexer.Token  // The '(' token
	Function            Expression   // Identifier or FunctionLiteral being called
	TypeArguments       []Expression // Type arguments (e.g., <string, number>)
	Arguments           []Expression // List of arguments
	IsDirectEval        bool         // True if this is a direct eval call: eval(...) where callee is plain Identifier "eval"
	ResolvedReflectType types.Type   // For Paserati.reflect<T>(): the fully resolved type T
}

CallExpression represents a function call. <Function>(<Arguments>) Function can be an identifier or a function literal.

func (*CallExpression) String

func (ce *CallExpression) String() string

func (*CallExpression) TokenLiteral

func (ce *CallExpression) TokenLiteral() string

type CatchClause

type CatchClause struct {
	Token     lexer.Token     // The 'catch' token
	Parameter Expression      // Exception variable: identifier or destructuring pattern (optional in ES2019+)
	Body      *BlockStatement // The catch block
}

CatchClause represents a catch block.

func (*CatchClause) String

func (cc *CatchClause) String() string

type ClassBody

type ClassBody struct {
	Token              lexer.Token             // The '{' token
	Methods            []*MethodDefinition     // Class method implementations
	Properties         []*PropertyDefinition   // Class properties
	ConstructorSigs    []*ConstructorSignature // Constructor overload signatures
	MethodSigs         []*MethodSignature      // Method overload signatures
	StaticInitializers []*BlockStatement       // Static initializer blocks: static { ... }
}

ClassBody represents the body of a class containing methods and properties

func (*ClassBody) String

func (cb *ClassBody) String() string

func (*ClassBody) TokenLiteral

func (cb *ClassBody) TokenLiteral() string

type ClassDeclaration

type ClassDeclaration struct {
	Token          lexer.Token      // The 'class' token
	Name           *Identifier      // Class name
	TypeParameters []*TypeParameter // Generic type parameters (e.g., <T, U>)
	SuperClass     Expression       // nil for basic classes (supports generic extends)
	Implements     []*Identifier    // Interfaces this class implements
	Body           *ClassBody       // Class body containing methods and properties
	IsAbstract     bool             // true if this is an abstract class
}

ClassDeclaration represents a class declaration statement

func (*ClassDeclaration) String

func (cd *ClassDeclaration) String() string

func (*ClassDeclaration) TokenLiteral

func (cd *ClassDeclaration) TokenLiteral() string

type ClassExpression

type ClassExpression struct {
	BaseExpression
	Token          lexer.Token      // The 'class' token
	Name           *Identifier      // nil for anonymous classes
	TypeParameters []*TypeParameter // Generic type parameters (e.g., <T, U>)
	SuperClass     Expression       // nil for basic classes (supports generic extends)
	Implements     []*Identifier    // Interfaces this class implements
	Body           *ClassBody       // Class body containing methods and properties
	IsAbstract     bool             // true if this is an abstract class
}

ClassExpression represents a class expression (can be anonymous)

func (*ClassExpression) String

func (ce *ClassExpression) String() string

func (*ClassExpression) TokenLiteral

func (ce *ClassExpression) TokenLiteral() string

type ComputedPropertyName

type ComputedPropertyName struct {
	BaseExpression
	Expr Expression // The computed expression
}

ComputedPropertyName represents a computed property name [expression]

func (*ComputedPropertyName) String

func (cpn *ComputedPropertyName) String() string

func (*ComputedPropertyName) TokenLiteral

func (cpn *ComputedPropertyName) TokenLiteral() string

type ConditionalTypeExpression

type ConditionalTypeExpression struct {
	BaseExpression             // Embed base for ComputedType (types.ConditionalType)
	CheckType      Expression  // The type being checked (T in T extends U ? X : Y)
	ExtendsToken   lexer.Token // The 'extends' token
	ExtendsType    Expression  // The type being extended/checked against (U in T extends U ? X : Y)
	QuestionToken  lexer.Token // The '?' token
	TrueType       Expression  // The type when condition is true (X in T extends U ? X : Y)
	ColonToken     lexer.Token // The ':' token
	FalseType      Expression  // The type when condition is false (Y in T extends U ? X : Y)
}

ConditionalTypeExpression represents a conditional type like T extends U ? X : Y

func (*ConditionalTypeExpression) GetComputedType

func (cte *ConditionalTypeExpression) GetComputedType() types.Type

GetComputedType satisfies the Expression interface

func (*ConditionalTypeExpression) String

func (cte *ConditionalTypeExpression) String() string

func (*ConditionalTypeExpression) TokenLiteral

func (cte *ConditionalTypeExpression) TokenLiteral() string

type ConstStatement

type ConstStatement struct {
	Token        lexer.Token      // The lexer.CONST token
	Declarations []*VarDeclarator // List of variable declarations
	// Legacy fields for backward compatibility (first declaration)
	Name           *Identifier // The variable name
	TypeAnnotation Expression  // Parsed type node
	Value          Expression  // The expression being assigned
	ComputedType   types.Type  // Stores the resolved type from TypeAnnotation
}

ConstStatement represents a `const` variable declaration. const <Name> : <TypeAnnotation> = <Value>; Note: Structurally identical to LetStatement for now, but semantically different.

func (*ConstStatement) String

func (cs *ConstStatement) String() string

func (*ConstStatement) TokenLiteral

func (cs *ConstStatement) TokenLiteral() string

type ConstructorSignature

type ConstructorSignature struct {
	Token                lexer.Token      // The 'constructor' token
	TypeParameters       []*TypeParameter // Generic type parameters (e.g., <T, U>)
	Parameters           []*Parameter     // Parameter list
	RestParameter        *RestParameter   // Rest parameter (if any)
	ReturnTypeAnnotation Expression       // Optional return type
	IsStatic             bool             // Access modifiers
	IsPublic             bool
	IsPrivate            bool
	IsProtected          bool
}

ConstructorSignature represents a constructor overload signature in a class

func (*ConstructorSignature) String

func (cs *ConstructorSignature) String() string

func (*ConstructorSignature) TokenLiteral

func (cs *ConstructorSignature) TokenLiteral() string

type ConstructorTypeExpression

type ConstructorTypeExpression struct {
	BaseExpression              // Embed base for ComputedType
	Token          lexer.Token  // The 'new' token
	Parameters     []Expression // Parameter types for the constructor
	ReturnType     Expression   // The constructed type (T in `new (): T`)
}

ConstructorTypeExpression represents a constructor type signature like `new () => T`

func (*ConstructorTypeExpression) String

func (cte *ConstructorTypeExpression) String() string

func (*ConstructorTypeExpression) TokenLiteral

func (cte *ConstructorTypeExpression) TokenLiteral() string

type ContinueStatement

type ContinueStatement struct {
	Token lexer.Token // The 'continue' token
	Label *Identifier // Optional label to continue to
}

--- New: Continue Statement ---

func (*ContinueStatement) String

func (cs *ContinueStatement) String() string

func (*ContinueStatement) TokenLiteral

func (cs *ContinueStatement) TokenLiteral() string

type DebuggerStatement added in v0.9.3

type DebuggerStatement struct {
	Token lexer.Token // The 'debugger' token
}

DebuggerStatement represents a debugger statement (no-op in runtime).

func (*DebuggerStatement) String added in v0.9.3

func (ds *DebuggerStatement) String() string

func (*DebuggerStatement) TokenLiteral added in v0.9.3

func (ds *DebuggerStatement) TokenLiteral() string

type DeferredImportExpression

type DeferredImportExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.IMPORT token
	Source         Expression  // The module specifier expression
}

DeferredImportExpression represents the deferred import.defer() expression import.defer(specifier) returns a Promise that resolves to a deferred module namespace object

func (*DeferredImportExpression) String

func (die *DeferredImportExpression) String() string

func (*DeferredImportExpression) TokenLiteral

func (die *DeferredImportExpression) TokenLiteral() string

type DestructuringElement

type DestructuringElement struct {
	Target  Expression // Target variable (Identifier for now)
	Default Expression // Default value (nil if no default)
	IsRest  bool       // true if this is a rest element (...target)
}

DestructuringElement represents a single element in destructuring pattern

func (*DestructuringElement) String

func (de *DestructuringElement) String() string

String() for DestructuringElement (helpful for debugging)

type DestructuringProperty

type DestructuringProperty struct {
	Key     Expression // Property name (Identifier or ComputedPropertyName)
	Target  Expression // Target variable (can be different from key)
	Default Expression // Default value (nil if no default)
}

DestructuringProperty represents key: target in object destructuring

func (*DestructuringProperty) String

func (dp *DestructuringProperty) String() string

String() for DestructuringProperty (helpful for debugging)

type DoWhileStatement

type DoWhileStatement struct {
	Token     lexer.Token     // The 'do' token
	Body      *BlockStatement // The loop body
	Condition Expression      // The condition to check after the body
}

DoWhileStatement represents a `do { ... } while (condition);` loop.

func (*DoWhileStatement) String

func (dws *DoWhileStatement) String() string

func (*DoWhileStatement) TokenLiteral

func (dws *DoWhileStatement) TokenLiteral() string

type DynamicImportExpression

type DynamicImportExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.IMPORT token
	Source         Expression  // The module specifier expression
	Options        Expression  // Optional import options expression (for import attributes)
}

DynamicImportExpression represents the dynamic import() expression import(specifier) or import(specifier, options) returns a Promise that resolves to a module namespace object

func (*DynamicImportExpression) String

func (die *DynamicImportExpression) String() string

func (*DynamicImportExpression) TokenLiteral

func (die *DynamicImportExpression) TokenLiteral() string

type EmptyStatement

type EmptyStatement struct {
	Token lexer.Token // The ';' token
}

--- New: Empty Statement ---

func (*EmptyStatement) String

func (es *EmptyStatement) String() string

func (*EmptyStatement) TokenLiteral

func (es *EmptyStatement) TokenLiteral() string

type EnumDeclaration

type EnumDeclaration struct {
	BaseExpression
	Token   lexer.Token   // The 'enum' token
	Name    *Identifier   // Enum name
	Members []*EnumMember // Enum members
	IsConst bool          // true for const enums
}

EnumDeclaration represents an enum declaration (enum Name { ... })

func (*EnumDeclaration) String

func (ed *EnumDeclaration) String() string

func (*EnumDeclaration) TokenLiteral

func (ed *EnumDeclaration) TokenLiteral() string

type EnumMember

type EnumMember struct {
	Token lexer.Token // The member name token
	Name  *Identifier // Member name
	Value Expression  // Optional initializer (nil for auto-increment)
}

EnumMember represents a member of an enum

func (*EnumMember) String

func (em *EnumMember) String() string

func (*EnumMember) TokenLiteral

func (em *EnumMember) TokenLiteral() string

type ExportAllDeclaration

type ExportAllDeclaration struct {
	Token      lexer.Token    // The 'export' token
	Exported   *Identifier    // Optional: export * as name from "module"
	Source     *StringLiteral // The module source
	IsTypeOnly bool           // true for "export type * from" statements
}

ExportAllDeclaration represents: export * from "module" or export * as name from "module"

func (*ExportAllDeclaration) String

func (ead *ExportAllDeclaration) String() string

func (*ExportAllDeclaration) TokenLiteral

func (ead *ExportAllDeclaration) TokenLiteral() string

type ExportDeclaration

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

ExportDeclaration is the interface for different export declaration types

type ExportDefaultDeclaration

type ExportDefaultDeclaration struct {
	Token       lexer.Token // The 'export' token
	Declaration Expression  // The default export expression
}

ExportDefaultDeclaration represents: export default expression

func (*ExportDefaultDeclaration) String

func (edd *ExportDefaultDeclaration) String() string

func (*ExportDefaultDeclaration) TokenLiteral

func (edd *ExportDefaultDeclaration) TokenLiteral() string

type ExportNamedDeclaration

type ExportNamedDeclaration struct {
	Token       lexer.Token       // The 'export' token
	Declaration Statement         // Direct export: export const x = 1
	Specifiers  []ExportSpecifier // Named exports: export { x, y }
	Source      *StringLiteral    // Re-export source: export { x } from "mod"
	IsTypeOnly  bool              // true for "export type" statements
}

ExportNamedDeclaration represents various named export forms: export const x = 1; export function foo() {} export { name1, name2 }; export { name1 as alias1 }; export { name1 } from "module";

func (*ExportNamedDeclaration) String

func (end *ExportNamedDeclaration) String() string

func (*ExportNamedDeclaration) TokenLiteral

func (end *ExportNamedDeclaration) TokenLiteral() string

type ExportNamedSpecifier

type ExportNamedSpecifier struct {
	Token    lexer.Token // The exported name token
	Local    Expression  // Local name being exported (Identifier or StringLiteral)
	Exported Expression  // Export name (Identifier or StringLiteral, same as Local if no alias)
}

ExportNamedSpecifier represents: export { name } or export { name as alias } or export { name as "string" }

func (*ExportNamedSpecifier) String

func (ens *ExportNamedSpecifier) String() string

func (*ExportNamedSpecifier) TokenLiteral

func (ens *ExportNamedSpecifier) TokenLiteral() string

type ExportSpecifier

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

ExportSpecifier represents individual export specifiers in export { ... }

type Expression

type Expression interface {
	Node

	// --- NEW: Field to store resolved type ---
	GetComputedType() types.Type
	SetComputedType(t types.Type)
	// contains filtered or unexported methods
}

Expression represents an expression node in the AST.

type ExpressionStatement

type ExpressionStatement struct {
	Token      lexer.Token // The first token of the expression
	Expression Expression
}

ExpressionStatement represents a statement consisting of a single expression. <expression>;

func (*ExpressionStatement) String

func (es *ExpressionStatement) String() string

func (*ExpressionStatement) TokenLiteral

func (es *ExpressionStatement) TokenLiteral() string

type ForInStatement

type ForInStatement struct {
	Token    lexer.Token     // The 'for' token
	Variable Statement       // Can be *LetStatement or *ConstStatement or *ExpressionStatement with *Identifier
	Object   Expression      // The object being iterated over
	Body     *BlockStatement // The loop body
}

ForInStatement represents a 'for (<variable> in <object>) { body }' statement. Variable can be either a *Identifier (e.g., for (key in obj)) or a variable declaration like *LetStatement (e.g., for (let key in obj))

func (*ForInStatement) String

func (fis *ForInStatement) String() string

func (*ForInStatement) TokenLiteral

func (fis *ForInStatement) TokenLiteral() string

type ForOfStatement

type ForOfStatement struct {
	Token    lexer.Token     // The 'for' token
	Variable Statement       // Can be *LetStatement or *ConstStatement or *ExpressionStatement with *Identifier
	Iterable Expression      // The expression being iterated over (array, string, etc.)
	Body     *BlockStatement // The loop body
	IsAsync  bool            // True for 'for await...of' loops
}

ForOfStatement represents a 'for (<variable> of <iterable>) { body }' statement. Variable can be either a *Identifier (e.g., for (item of items)) or a variable declaration like *LetStatement (e.g., for (let item of items)) For async iteration, use 'for await (variable of asyncIterable)'

func (*ForOfStatement) String

func (fos *ForOfStatement) String() string

func (*ForOfStatement) TokenLiteral

func (fos *ForOfStatement) TokenLiteral() string

type ForStatement

type ForStatement struct {
	Token       lexer.Token // The 'for' token
	Initializer Statement   // Can be *LetStatement or *ExpressionStatement or nil
	Condition   Expression  // Can be nil
	Update      Expression  // Can be nil
	Body        *BlockStatement
}

ForStatement represents a C-style 'for (initializer; condition; update) { body }' statement. Initializer can be a LetStatement or an ExpressionStatement. Condition and Update are optional expressions.

func (*ForStatement) String

func (fs *ForStatement) String() string

func (*ForStatement) TokenLiteral

func (fs *ForStatement) TokenLiteral() string

type FunctionLiteral

type FunctionLiteral struct {
	BaseExpression                        // Embed base for ComputedType (Function type)
	Token                lexer.Token      // The 'function' token
	Name                 *Identifier      // Optional function name
	IsGenerator          bool             // true for function* (generator functions)
	IsAsync              bool             // true for async functions
	TypeParameters       []*TypeParameter // Generic type parameters (e.g., <T, U>)
	Parameters           []*Parameter     // Regular parameters
	RestParameter        *RestParameter   // Optional rest parameter (...args)
	ReturnTypeAnnotation Expression       // << RENAMED & TYPE CHANGED
	Body                 *BlockStatement  // Function body
}

FunctionLiteral represents a function definition. function <Name>(<Parameters>) : <ReturnTypeAnnotation> { <Body> } Or anonymous: function(<Parameters>) : <ReturnTypeAnnotation> { <Body> }

func (*FunctionLiteral) String

func (fl *FunctionLiteral) String() string

func (*FunctionLiteral) TokenLiteral

func (fl *FunctionLiteral) TokenLiteral() string

type FunctionOverloadGroup

type FunctionOverloadGroup struct {
	Token          lexer.Token          // The token of the first function declaration
	Name           *Identifier          // Function name (shared by all overloads)
	Overloads      []*FunctionSignature // The overload signatures (without bodies)
	Implementation *FunctionLiteral     // The implementation (with body)
}

FunctionOverloadGroup represents a group of function overload signatures plus an implementation

func (*FunctionOverloadGroup) String

func (fog *FunctionOverloadGroup) String() string

func (*FunctionOverloadGroup) TokenLiteral

func (fog *FunctionOverloadGroup) TokenLiteral() string

type FunctionSignature

type FunctionSignature struct {
	BaseExpression                      // Embed base for ComputedType (so it can be an Expression too)
	Token                lexer.Token    // The 'function' token
	Name                 *Identifier    // Function name (must match other overloads)
	Parameters           []*Parameter   // Regular function parameters with type annotations
	RestParameter        *RestParameter // Optional rest parameter (...args)
	ReturnTypeAnnotation Expression     // Return type annotation (required for overloads)
}

FunctionSignature represents a function signature without a body (used in overloads)

func (*FunctionSignature) String

func (fs *FunctionSignature) String() string

func (*FunctionSignature) TokenLiteral

func (fs *FunctionSignature) TokenLiteral() string

type FunctionTypeExpression

type FunctionTypeExpression struct {
	BaseExpression                  // Embed base for ComputedType (Function type)
	Token          lexer.Token      // The '(' token starting the parameter list
	TypeParameters []*TypeParameter // Generic type parameters (e.g., <T, U>)
	Parameters     []Expression     // Slice of Expression nodes representing parameter types
	RestParameter  Expression       // Optional rest parameter type (e.g., ...args: string[])
	ReturnType     Expression       // Expression node for the return type
}

FunctionTypeExpression represents a type like (number, string) => boolean

func (*FunctionTypeExpression) GetComputedType

func (fte *FunctionTypeExpression) GetComputedType() types.Type

GetComputedType satisfies the Expression interface (placeholder) The actual type is determined during type checking.

func (*FunctionTypeExpression) String

func (fte *FunctionTypeExpression) String() string

func (*FunctionTypeExpression) TokenLiteral

func (fte *FunctionTypeExpression) TokenLiteral() string

type GenericTypeRef

type GenericTypeRef struct {
	BaseExpression              // Embed base for ComputedType
	Token          lexer.Token  // The identifier token
	Name           *Identifier  // The generic type name (e.g., "Array")
	TypeArguments  []Expression // The type arguments (e.g., [string] in Array<string>)
}

GenericTypeRef represents a generic type reference (e.g., Array<string>, Promise<number>).

func (*GenericTypeRef) String

func (g *GenericTypeRef) String() string

func (*GenericTypeRef) TokenLiteral

func (g *GenericTypeRef) TokenLiteral() string

type Identifier

type Identifier struct {
	BaseExpression // Embed base for ComputedType
	Token          lexer.Token
	Value          string // The name of the identifier
	IsConstant     bool   // Populated by Type Checker
	IsFromWith     bool   // True if this identifier comes from a with object (populated by Type Checker)
}

Identifier represents an identifier in the source code.

func (*Identifier) String

func (i *Identifier) String() string

func (*Identifier) TokenLiteral

func (i *Identifier) TokenLiteral() string

type IfExpression

type IfExpression struct {
	BaseExpression             // Embed base for ComputedType (Union of consequence/alternative types?)
	Token          lexer.Token // The 'if' token
	Condition      Expression
	Consequence    *BlockStatement
	Alternative    *BlockStatement // Optional
}

IfExpression represents an if/else conditional expression. if (<Condition>) { <Consequence> } else { <Alternative> }

func (*IfExpression) String

func (ie *IfExpression) String() string

func (*IfExpression) TokenLiteral

func (ie *IfExpression) TokenLiteral() string

type IfStatement

type IfStatement struct {
	Token       lexer.Token // The 'if' token
	Condition   Expression
	Consequence *BlockStatement
	Alternative *BlockStatement // Optional
}

IfStatement represents a 'if (condition) { consequence } else { alternative }' statement.

func (*IfStatement) String

func (is *IfStatement) String() string

func (*IfStatement) TokenLiteral

func (is *IfStatement) TokenLiteral() string

type ImportDeclaration

type ImportDeclaration struct {
	Token      lexer.Token       // The 'import' token
	Specifiers []ImportSpecifier // What to import (default, named, namespace)
	Source     *StringLiteral    // From where ("./module")
	IsTypeOnly bool              // true for "import type" statements
	Attributes map[string]string // Import attributes (e.g., { type: "json" })
}

ImportDeclaration represents an import statement import defaultImport from "module" import * as name from "module" import { export1, export2 } from "module" import { export1 as alias1 } from "module" import defaultImport, { export1, export2 } from "module" import defaultImport, * as name from "module"

func (*ImportDeclaration) String

func (id *ImportDeclaration) String() string

func (*ImportDeclaration) TokenLiteral

func (id *ImportDeclaration) TokenLiteral() string

type ImportDefaultSpecifier

type ImportDefaultSpecifier struct {
	Token lexer.Token // The identifier token
	Local *Identifier // Local binding name
}

ImportDefaultSpecifier represents: import defaultName from "module"

func (*ImportDefaultSpecifier) String

func (ids *ImportDefaultSpecifier) String() string

func (*ImportDefaultSpecifier) TokenLiteral

func (ids *ImportDefaultSpecifier) TokenLiteral() string

type ImportMetaExpression

type ImportMetaExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.IMPORT token
}

ImportMetaExpression represents the import.meta meta-property

func (*ImportMetaExpression) String

func (ime *ImportMetaExpression) String() string

func (*ImportMetaExpression) TokenLiteral

func (ime *ImportMetaExpression) TokenLiteral() string

type ImportNamedSpecifier

type ImportNamedSpecifier struct {
	Token      lexer.Token // The imported name token
	Imported   *Identifier // Original export name
	Local      *Identifier // Local binding name (same as Imported if no alias)
	IsTypeOnly bool        // true for "import { type name }" syntax
}

ImportNamedSpecifier represents: import { name } or import { name as alias }

func (*ImportNamedSpecifier) String

func (ins *ImportNamedSpecifier) String() string

func (*ImportNamedSpecifier) TokenLiteral

func (ins *ImportNamedSpecifier) TokenLiteral() string

type ImportNamespaceSpecifier

type ImportNamespaceSpecifier struct {
	Token lexer.Token // The '*' token
	Local *Identifier // Local binding name
}

ImportNamespaceSpecifier represents: import * as name from "module"

func (*ImportNamespaceSpecifier) String

func (ins *ImportNamespaceSpecifier) String() string

func (*ImportNamespaceSpecifier) TokenLiteral

func (ins *ImportNamespaceSpecifier) TokenLiteral() string

type ImportSpecifier

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

ImportSpecifier is the interface for different import specifier types

type IndexExpression

type IndexExpression struct {
	BaseExpression             // Embed base for ComputedType (element type)
	Token          lexer.Token // The '[' token
	Left           Expression  // The expression evaluating to the array/object being indexed
	Index          Expression  // The expression evaluating to the index
}

IndexExpression represents accessing an element by index (e.g., myArray[i]).

func (*IndexExpression) String

func (ie *IndexExpression) String() string

func (*IndexExpression) TokenLiteral

func (ie *IndexExpression) TokenLiteral() string

type IndexedAccessTypeExpression

type IndexedAccessTypeExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The '[' token
	ObjectType     Expression  // The type being indexed into (e.g., T in T[K])
	IndexType      Expression  // The key type used for indexing (e.g., K in T[K])
}

IndexedAccessTypeExpression represents an indexed access type like T[K] Used to access properties of a type using a key type (e.g., Person["name"])

func (*IndexedAccessTypeExpression) GetComputedType

func (iate *IndexedAccessTypeExpression) GetComputedType() types.Type

GetComputedType satisfies the Expression interface (placeholder) The actual type is determined during type checking.

func (*IndexedAccessTypeExpression) String

func (iate *IndexedAccessTypeExpression) String() string

func (*IndexedAccessTypeExpression) TokenLiteral

func (iate *IndexedAccessTypeExpression) TokenLiteral() string

type InferTypeExpression

type InferTypeExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The 'infer' token
	TypeParameter  string      // The type parameter being inferred (e.g., 'R' in 'infer R')
}

InferTypeExpression represents an infer type in conditional types like infer R Used within conditional types to infer and capture types

func (*InferTypeExpression) GetComputedType

func (ite *InferTypeExpression) GetComputedType() types.Type

GetComputedType satisfies the Expression interface (placeholder) The actual type is determined during type checking.

func (*InferTypeExpression) String

func (ite *InferTypeExpression) String() string

func (*InferTypeExpression) TokenLiteral

func (ite *InferTypeExpression) TokenLiteral() string

type InfixExpression

type InfixExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The operator token, e.g. +
	Left           Expression  // The expression to the left of the operator
	Operator       string      // e.g., "+", "-", "*", "/", "==", "!=", "<", ">"
	Right          Expression  // The expression to the right of the operator
}

InfixExpression represents an infix operator expression. <Left> <operator> <Right> e.g., 5 + 5, x == y

func (*InfixExpression) String

func (ie *InfixExpression) String() string

func (*InfixExpression) TokenLiteral

func (ie *InfixExpression) TokenLiteral() string

type InterfaceDeclaration

type InterfaceDeclaration struct {
	Token          lexer.Token          // The 'interface' token
	Name           *Identifier          // Interface name
	TypeParameters []*TypeParameter     // Generic type parameters (e.g., <T, U>)
	Extends        []Expression         // Interfaces this interface extends (supports generic types)
	Properties     []*InterfaceProperty // Interface properties/methods
}

InterfaceDeclaration represents an interface declaration. interface Name { property: Type; method(): ReturnType; }

func (*InterfaceDeclaration) String

func (id *InterfaceDeclaration) String() string

func (*InterfaceDeclaration) TokenLiteral

func (id *InterfaceDeclaration) TokenLiteral() string

type InterfaceProperty

type InterfaceProperty struct {
	Name                   *Identifier // Property/method name
	ComputedName           Expression  // Computed property name for [expression]: syntax
	Type                   Expression  // Type annotation (for properties) or function type (for methods)
	IsMethod               bool        // Whether this is a method signature
	Optional               bool        // Whether the property is optional (Name?)
	IsConstructorSignature bool        // Whether this is a constructor signature (new (): T)
	IsComputedProperty     bool        // Whether this is a computed property name [expr]:

	// Index signature fields
	IsIndexSignature bool        // Whether this is an index signature like [key: string]: Type
	KeyName          *Identifier // The key parameter name (e.g., "key" in [key: string]: Type)
	KeyType          Expression  // The key type (e.g., "string" in [key: string]: Type)
	ValueType        Expression  // The value type (e.g., "Type" in [key: string]: Type)
}

InterfaceProperty represents a property or method signature in an interface.

func (*InterfaceProperty) String

func (ip *InterfaceProperty) String() string

type IntersectionTypeExpression

type IntersectionTypeExpression struct {
	BaseExpression             // Embed base for ComputedType (which will be an IntersectionType)
	Token          lexer.Token // The '&' token
	Left           Expression  // The type expression on the left
	Right          Expression  // The type expression on the right
}

IntersectionTypeExpression represents an intersection type (e.g., A & B). For now, just binary intersections (A & B). Can be nested for more types.

func (*IntersectionTypeExpression) String

func (ite *IntersectionTypeExpression) String() string

func (*IntersectionTypeExpression) TokenLiteral

func (ite *IntersectionTypeExpression) TokenLiteral() string

type JSEmitter

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

JSEmitter is responsible for transforming AST nodes into JavaScript code

func NewJSEmitter

func NewJSEmitter() *JSEmitter

NewJSEmitter creates a new JavaScript emitter

func (*JSEmitter) Emit

func (e *JSEmitter) Emit(program *Program) string

Emit converts a program AST to JavaScript code

type KeyofTypeExpression

type KeyofTypeExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The 'keyof' token
	Type           Expression  // The type to get keys from
}

KeyofTypeExpression represents a keyof type operator like keyof T

func (*KeyofTypeExpression) GetComputedType

func (kte *KeyofTypeExpression) GetComputedType() types.Type

GetComputedType satisfies the Expression interface (placeholder) The actual type is determined during type checking.

func (*KeyofTypeExpression) String

func (kte *KeyofTypeExpression) String() string

func (*KeyofTypeExpression) TokenLiteral

func (kte *KeyofTypeExpression) TokenLiteral() string

type LabeledStatement

type LabeledStatement struct {
	Token     lexer.Token // The label identifier token
	Label     *Identifier // The label name
	Statement Statement   // The statement being labeled
}

--- New: Labeled Statement ---

func (*LabeledStatement) String

func (ls *LabeledStatement) String() string

func (*LabeledStatement) TokenLiteral

func (ls *LabeledStatement) TokenLiteral() string

type LetStatement

type LetStatement struct {
	Token        lexer.Token      // The lexer.LET token
	Declarations []*VarDeclarator // List of variable declarations
	// Legacy fields for backward compatibility (first declaration)
	Name           *Identifier // The variable name
	TypeAnnotation Expression  // Parsed type node (e.g., *Identifier)
	Value          Expression  // The expression being assigned
	ComputedType   types.Type  // Stores the resolved type from TypeAnnotation
}

LetStatement represents a `let` variable declaration. let <Name> : <TypeAnnotation> = <Value>;

func (*LetStatement) String

func (ls *LetStatement) String() string

func (*LetStatement) TokenLiteral

func (ls *LetStatement) TokenLiteral() string

type MappedTypeExpression

type MappedTypeExpression struct {
	BaseExpression             // Embed base for ComputedType (types.MappedType)
	Token          lexer.Token // The '{' token
	TypeParameter  *Identifier // The iteration variable (e.g., "P" in [P in K])
	ConstraintType Expression  // The type being iterated over (e.g., K in [P in K])
	ValueType      Expression  // The resulting value type for each property

	// Modifiers for the mapped type
	ReadonlyModifier string // "+", "-", or "" (for readonly modifier)
	OptionalModifier string // "+", "-", or "" (for optional modifier)
}

MappedTypeExpression represents a mapped type like { [P in K]: T } This is used for utility types like Partial<T>, Readonly<T>, etc.

func (*MappedTypeExpression) GetComputedType

func (mte *MappedTypeExpression) GetComputedType() types.Type

GetComputedType satisfies the Expression interface (placeholder) The actual type is determined during type checking.

func (*MappedTypeExpression) String

func (mte *MappedTypeExpression) String() string

func (*MappedTypeExpression) TokenLiteral

func (mte *MappedTypeExpression) TokenLiteral() string

type MemberExpression

type MemberExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The '.' token
	Object         Expression  // The expression on the left (e.g., identifier, call result)
	Property       Expression  // The property access (identifier or computed expression)
}

MemberExpression represents accessing a property (e.g., object.property).

func (*MemberExpression) String

func (me *MemberExpression) String() string

func (*MemberExpression) TokenLiteral

func (me *MemberExpression) TokenLiteral() string

type MethodDefinition

type MethodDefinition struct {
	BaseExpression
	Token       lexer.Token      // The method name token
	Key         Expression       // Method name (Identifier or ComputedPropertyName)
	Value       *FunctionLiteral // Function implementation
	Kind        string           // "constructor", "method"
	IsStatic    bool             // For static method support
	IsPublic    bool             // For public access modifier
	IsPrivate   bool             // For private access modifier
	IsProtected bool             // For protected access modifier
	IsAbstract  bool             // For abstract methods (no implementation)
	IsOverride  bool             // For override keyword
}

MethodDefinition represents a method in a class

func (*MethodDefinition) String

func (md *MethodDefinition) String() string

func (*MethodDefinition) TokenLiteral

func (md *MethodDefinition) TokenLiteral() string

type MethodSignature

type MethodSignature struct {
	Token                lexer.Token      // The method name token
	Key                  Expression       // Method name (Identifier or ComputedPropertyName)
	TypeParameters       []*TypeParameter // Generic type parameters (e.g., <T, U>)
	Parameters           []*Parameter     // Parameter list
	RestParameter        *RestParameter   // Rest parameter (if any)
	ReturnTypeAnnotation Expression       // Optional return type
	Kind                 string           // "method", "getter", "setter"
	IsStatic             bool             // Access modifiers
	IsPublic             bool
	IsPrivate            bool
	IsProtected          bool
	IsAbstract           bool // Abstract method modifier
	IsOverride           bool // Override method modifier
}

MethodSignature represents a method overload signature in a class

func (*MethodSignature) String

func (ms *MethodSignature) String() string

func (*MethodSignature) TokenLiteral

func (ms *MethodSignature) TokenLiteral() string

type NewExpression

type NewExpression struct {
	BaseExpression              // Embed base for ComputedType (constructed object type)
	Token          lexer.Token  // The 'new' token
	Constructor    Expression   // Identifier or function being called as constructor
	TypeArguments  []Expression // Type arguments (e.g., <string, number>)
	Arguments      []Expression // List of arguments
}

NewExpression represents a constructor call with the `new` keyword. new <Constructor>(<Arguments>)

func (*NewExpression) String

func (ne *NewExpression) String() string

func (*NewExpression) TokenLiteral

func (ne *NewExpression) TokenLiteral() string

type NewTargetExpression

type NewTargetExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.NEW token
}

NewTargetExpression represents the new.target meta-property

func (*NewTargetExpression) String

func (nte *NewTargetExpression) String() string

func (*NewTargetExpression) TokenLiteral

func (nte *NewTargetExpression) TokenLiteral() string

type Node

type Node interface {
	TokenLiteral() string // Returns the literal value of the token associated with the node
	String() string       // Returns a string representation of the node (for debugging)
}

Node is the base interface for all AST nodes.

type NonNullExpression

type NonNullExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The '!' token
	Expression     Expression  // The expression being asserted as non-null
}

NonNullExpression represents a non-null assertion expression (value!) This is a TypeScript-only operator that asserts a value is not null/undefined

func (*NonNullExpression) String

func (nne *NonNullExpression) String() string

func (*NonNullExpression) TokenLiteral

func (nne *NonNullExpression) TokenLiteral() string

type NullLiteral

type NullLiteral struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.NULL token
}

NullLiteral represents the `null` keyword.

func (*NullLiteral) String

func (nl *NullLiteral) String() string

func (*NullLiteral) TokenLiteral

func (nl *NullLiteral) TokenLiteral() string

type NumberLiteral

type NumberLiteral struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.NUMBER token
	Value          float64     // Store as float64 for simplicity
}

NumberLiteral represents numeric literals (integers or floats).

func (*NumberLiteral) String

func (n *NumberLiteral) String() string

func (*NumberLiteral) TokenLiteral

func (n *NumberLiteral) TokenLiteral() string

type ObjectDestructuringAssignment

type ObjectDestructuringAssignment struct {
	BaseExpression                          // Embed base for ComputedType
	Token          lexer.Token              // The '{' token
	Properties     []*DestructuringProperty // Target properties/patterns
	RestProperty   *DestructuringElement    // Rest property (...rest) - optional
	Value          Expression               // RHS expression to destructure
}

ObjectDestructuringAssignment represents {a, b} = expr

func (*ObjectDestructuringAssignment) String

func (oda *ObjectDestructuringAssignment) String() string

func (*ObjectDestructuringAssignment) TokenLiteral

func (oda *ObjectDestructuringAssignment) TokenLiteral() string

type ObjectDestructuringDeclaration

type ObjectDestructuringDeclaration struct {
	Token          lexer.Token              // The 'let', 'const', or 'var' token
	IsConst        bool                     // true for const, false for let/var
	Properties     []*DestructuringProperty // Target properties/patterns
	RestProperty   *DestructuringElement    // Rest property (...rest) - optional
	TypeAnnotation Expression               // Optional type annotation (e.g., : {a: number, b: string})
	Value          Expression               // RHS expression to destructure
}

ObjectDestructuringDeclaration represents let/const/var {a, b} = expr

func (*ObjectDestructuringDeclaration) String

func (odd *ObjectDestructuringDeclaration) String() string

func (*ObjectDestructuringDeclaration) TokenLiteral

func (odd *ObjectDestructuringDeclaration) TokenLiteral() string

type ObjectLiteral

type ObjectLiteral struct {
	BaseExpression             // Embed base for ComputedType (e.g., types.ObjectType)
	Token          lexer.Token // The '{' token
	// --- MODIFIED: Use slice instead of map to preserve order ---
	Properties []*ObjectProperty
}

ObjectLiteral represents an object literal expression (e.g., { key: value, "str_key": 1 }).

func (*ObjectLiteral) String

func (ol *ObjectLiteral) String() string

func (*ObjectLiteral) TokenLiteral

func (ol *ObjectLiteral) TokenLiteral() string

type ObjectParameterPattern

type ObjectParameterPattern struct {
	BaseExpression                          // Embed base for ComputedType
	Token          lexer.Token              // The '{' token
	Properties     []*DestructuringProperty // Parameter properties (can have defaults)
	RestProperty   *DestructuringElement    // Rest property (...rest) - optional
}

ObjectParameterPattern represents object destructuring in function parameters Examples: ({x, y}: Point) => {}, ({name = "Unknown"}: {name?: string}) => {}

func (*ObjectParameterPattern) String

func (opp *ObjectParameterPattern) String() string

func (*ObjectParameterPattern) TokenLiteral

func (opp *ObjectParameterPattern) TokenLiteral() string

type ObjectProperty

type ObjectProperty struct {
	Key   Expression
	Value Expression
}

--- NEW: ObjectProperty (Helper for ObjectLiteral) --- Represents a single key-value pair within an object literal. For spread elements, Key will be a SpreadElement and Value will be nil.

func (*ObjectProperty) String

func (op *ObjectProperty) String() string

String() for ObjectProperty (optional, but helpful for debugging)

type ObjectTypeExpression

type ObjectTypeExpression struct {
	BaseExpression             // Embed base for ComputedType (which will be an ObjectType)
	Token          lexer.Token // The '{' token
	Properties     []*ObjectTypeProperty
}

ObjectTypeExpression represents an object type literal (e.g., { name: string; age: number }).

func (*ObjectTypeExpression) String

func (ote *ObjectTypeExpression) String() string

func (*ObjectTypeExpression) TokenLiteral

func (ote *ObjectTypeExpression) TokenLiteral() string

type ObjectTypeProperty

type ObjectTypeProperty struct {
	Name            *Identifier  // Property name (nil for call signatures and index signatures)
	Type            Expression   // Property type annotation or function type for call signatures
	Optional        bool         // Whether the property is optional (for future use)
	IsCallSignature bool         // Whether this is a call signature like (param: type): returnType
	Parameters      []Expression // Parameters for call signatures (only used when IsCallSignature is true)
	ReturnType      Expression   // Return type for call signatures (only used when IsCallSignature is true)

	// Index signature fields
	IsIndexSignature bool        // Whether this is an index signature like [key: string]: Type
	KeyName          *Identifier // The key parameter name (e.g., "key" in [key: string]: Type)
	KeyType          Expression  // The key type (e.g., "string" in [key: string]: Type)
	ValueType        Expression  // The value type (e.g., "Type" in [key: string]: Type)

	// Computed property fields
	IsComputedProperty bool       // Whether this is a computed property [expr]: Type
	ComputedName       Expression // The computed property expression
}

ObjectTypeProperty represents a property in an object type literal.

func (*ObjectTypeProperty) String

func (otp *ObjectTypeProperty) String() string

type OptionalCallExpression

type OptionalCallExpression struct {
	BaseExpression              // Embed base for ComputedType
	Token          lexer.Token  // The '?.' token
	Function       Expression   // The function expression on the left
	Arguments      []Expression // The function arguments
}

OptionalCallExpression represents optional function call (e.g., func?.()).

func (*OptionalCallExpression) String

func (oce *OptionalCallExpression) String() string

func (*OptionalCallExpression) TokenLiteral

func (oce *OptionalCallExpression) TokenLiteral() string

type OptionalChainingExpression

type OptionalChainingExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The '?.' token
	Object         Expression  // The expression on the left (e.g., identifier, call result)
	Property       Expression  // The property access (identifier or computed expression)
}

OptionalChainingExpression represents optional chaining property access (e.g., object?.property).

func (*OptionalChainingExpression) String

func (oce *OptionalChainingExpression) String() string

func (*OptionalChainingExpression) TokenLiteral

func (oce *OptionalChainingExpression) TokenLiteral() string

type OptionalIndexExpression

type OptionalIndexExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The '?.' token
	Object         Expression  // The expression on the left (e.g., identifier, call result)
	Index          Expression  // The index expression (e.g., string, number, variable)
}

OptionalIndexExpression represents optional computed property access (e.g., object?.[expression]).

func (*OptionalIndexExpression) String

func (oie *OptionalIndexExpression) String() string

func (*OptionalIndexExpression) TokenLiteral

func (oie *OptionalIndexExpression) TokenLiteral() string

type Parameter

type Parameter struct {
	Token           lexer.Token // The token of the parameter name
	Name            *Identifier // For simple parameters
	Pattern         Expression  // For destructuring patterns (ArrayParameterPattern/ObjectParameterPattern)
	TypeAnnotation  Expression  // Parsed type node (e.g., *Identifier)
	ComputedType    types.Type  // Stores the resolved type from TypeAnnotation
	Optional        bool        // Whether this parameter is optional (param?)
	DefaultValue    Expression  // Default value expression (param = defaultValue)
	IsThis          bool        // Whether this is an explicit 'this' parameter
	IsDestructuring bool        // Whether this parameter uses destructuring pattern

	// Parameter property modifiers (only valid in constructor context)
	IsPublic    bool // true if marked with 'public' (constructor parameter property)
	IsPrivate   bool // true if marked with 'private' (constructor parameter property)
	IsProtected bool // true if marked with 'protected' (constructor parameter property)
	IsReadonly  bool // true if marked with 'readonly' (constructor parameter property)
}

--- NEW: Parameter Node --- Represents a function parameter with an optional type annotation. <Name> : <TypeAnnotation> Also supports destructuring patterns: ([a, b]: [number, number]) or ({x, y}: Point)

func (*Parameter) String

func (p *Parameter) String() string

func (*Parameter) TokenLiteral

func (p *Parameter) TokenLiteral() string

type Parser

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

Parser takes a lexer and builds an AST.

func NewParser

func NewParser(l *lexer.Lexer) *Parser

NewParser creates a new Parser.

func (*Parser) Errors

func (p *Parser) Errors() []errors.PaseratiError

Errors returns the list of parsing errors.

func (*Parser) GetSource

func (p *Parser) GetSource() *source.SourceFile

GetSource returns the source file associated with this parser

func (*Parser) ParseProgram

func (p *Parser) ParseProgram() (*Program, []errors.PaseratiError)

ParseProgram parses the entire input and returns the root Program node and any errors.

func (*Parser) SetDisallowSuper added in v0.9.3

func (p *Parser) SetDisallowSuper(disallow bool)

SetDisallowSuper sets whether super expressions should be disallowed. When true, parsing super will emit a SyntaxError (used for indirect eval).

type PrefixExpression

type PrefixExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The prefix token, e.g. ! or -
	Operator       string      // "!" or "-"
	Right          Expression  // The expression to the right of the operator
}

PrefixExpression represents a prefix operator expression. <operator><Right> e.g., !true, -15

func (*PrefixExpression) String

func (pe *PrefixExpression) String() string

func (*PrefixExpression) TokenLiteral

func (pe *PrefixExpression) TokenLiteral() string

type PrivateIdentifier

type PrivateIdentifier struct {
	BaseExpression
	Token lexer.Token
	Value string // The name including the # prefix (e.g., "#field")
}

PrivateIdentifier represents a standalone private identifier (#field) for use in 'in' expressions Syntax: #field in obj - checks if private field exists on object

func (*PrivateIdentifier) String

func (pi *PrivateIdentifier) String() string

func (*PrivateIdentifier) TokenLiteral

func (pi *PrivateIdentifier) TokenLiteral() string

type Program

type Program struct {
	Statements          []Statement
	HoistedDeclarations map[string]Expression // Changed: Store hoisted Expression (e.g., FunctionLiteral)
	Source              *source.SourceFile    // Source file context for error reporting
}

Program is the root node of the AST.

func (*Program) String

func (p *Program) String() string

func (*Program) TokenLiteral

func (p *Program) TokenLiteral() string

type PropertyDefinition

type PropertyDefinition struct {
	BaseExpression
	Token          lexer.Token // The property name token
	Key            Expression  // Property name (Identifier or ComputedPropertyName)
	TypeAnnotation Expression  // Type annotation (can be nil)
	Value          Expression  // Initializer expression (can be nil)
	IsStatic       bool        // For static property support
	Optional       bool        // Whether the property is optional (prop?)
	Readonly       bool        // Whether the property is readonly
	IsPublic       bool        // For public access modifier
	IsPrivate      bool        // For private access modifier
	IsProtected    bool        // For protected access modifier
}

PropertyDefinition represents a property declaration in a class

func (*PropertyDefinition) String

func (pd *PropertyDefinition) String() string

func (*PropertyDefinition) TokenLiteral

func (pd *PropertyDefinition) TokenLiteral() string

type RegexLiteral

type RegexLiteral struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.REGEX_LITERAL token
	Pattern        string      // The pattern part (without slashes)
	Flags          string      // The flags part
}

RegexLiteral represents a regular expression literal /pattern/flags.

func (*RegexLiteral) String

func (rl *RegexLiteral) String() string

func (*RegexLiteral) TokenLiteral

func (rl *RegexLiteral) TokenLiteral() string

type RestParameter

type RestParameter struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The '...' token
	Name           *Identifier // The parameter name (e.g., 'args' in ...args)
	Pattern        Expression  // Optional destructuring pattern (e.g., ...[x, y] or ...{a, b})
	TypeAnnotation Expression  // Optional type annotation (e.g., 'string[]' in ...args: string[])
	ComputedType   types.Type  // Stores the resolved type (should be array type)
}

RestParameter represents a rest parameter (...args) in function definitions

func (*RestParameter) String

func (rp *RestParameter) String() string

func (*RestParameter) TokenLiteral

func (rp *RestParameter) TokenLiteral() string

type ReturnStatement

type ReturnStatement struct {
	Token       lexer.Token // The lexer.RETURN token
	ReturnValue Expression  // The expression to return
}

ReturnStatement represents a `return` statement. return <ReturnValue>;

func (*ReturnStatement) String

func (rs *ReturnStatement) String() string

func (*ReturnStatement) TokenLiteral

func (rs *ReturnStatement) TokenLiteral() string

type SatisfiesExpression

type SatisfiesExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The 'satisfies' token
	Expression     Expression  // The expression being validated
	TargetType     Expression  // The target type annotation
}

SatisfiesExpression represents a satisfies expression (value satisfies Type)

func (*SatisfiesExpression) String

func (se *SatisfiesExpression) String() string

func (*SatisfiesExpression) TokenLiteral

func (se *SatisfiesExpression) TokenLiteral() string

type ShorthandMethod

type ShorthandMethod struct {
	BaseExpression                       // Embed base for ComputedType (Function type)
	Token                lexer.Token     // The identifier token (method name)
	Name                 *Identifier     // Method name
	Parameters           []*Parameter    // Regular method parameters
	RestParameter        *RestParameter  // Optional rest parameter (...args)
	ReturnTypeAnnotation Expression      // Optional return type annotation
	Body                 *BlockStatement // Method body
}

ShorthandMethod represents a shorthand method in object literals like { method() { ... } }

func (*ShorthandMethod) String

func (sm *ShorthandMethod) String() string

func (*ShorthandMethod) TokenLiteral

func (sm *ShorthandMethod) TokenLiteral() string

type SpreadElement

type SpreadElement struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The '...' token
	Argument       Expression  // The expression being spread (e.g., 'arr' in ...arr)
}

SpreadElement represents spread syntax (...arr) in function calls and other contexts

func (*SpreadElement) String

func (se *SpreadElement) String() string

func (*SpreadElement) TokenLiteral

func (se *SpreadElement) TokenLiteral() string

type Statement

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

Statement represents a statement node in the AST.

type StringLiteral

type StringLiteral struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.STRING token
	Value          string
}

StringLiteral represents string literals.

func (*StringLiteral) String

func (s *StringLiteral) String() string

func (*StringLiteral) TokenLiteral

func (s *StringLiteral) TokenLiteral() string

type SuperExpression

type SuperExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.SUPER token
}

SuperExpression represents super keyword expressions (super(), super.method())

func (*SuperExpression) String

func (se *SuperExpression) String() string

func (*SuperExpression) TokenLiteral

func (se *SuperExpression) TokenLiteral() string

type SwitchCase

type SwitchCase struct {
	Token     lexer.Token     // The 'case' or 'default' token
	Condition Expression      // The expression to match (nil for default)
	Body      *BlockStatement // The block of statements to execute
}

SwitchCase represents a single case or default clause within a switch statement.

func (*SwitchCase) String

func (sc *SwitchCase) String() string

Not a full Node, but needs String() for debugging SwitchStatement.String()

type SwitchStatement

type SwitchStatement struct {
	Token      lexer.Token   // The 'switch' token
	Expression Expression    // The expression being evaluated
	Cases      []*SwitchCase // The list of case/default clauses
}

SwitchStatement represents a switch statement. switch (Expression) { Case* Default? Case* }

func (*SwitchStatement) String

func (ss *SwitchStatement) String() string

func (*SwitchStatement) TokenLiteral

func (ss *SwitchStatement) TokenLiteral() string

type TaggedTemplateExpression

type TaggedTemplateExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // token of the tag expression's first token (for position)
	Tag            Expression  // the tag function/expression
	Template       *TemplateLiteral
}

TaggedTemplateExpression represents a tagged template: tag`...`

func (*TaggedTemplateExpression) String

func (tte *TaggedTemplateExpression) String() string

func (*TaggedTemplateExpression) TokenLiteral

func (tte *TaggedTemplateExpression) TokenLiteral() string

type TemplateLiteral

type TemplateLiteral struct {
	BaseExpression             // Embed base for ComputedType (always string)
	Token          lexer.Token // The opening '`' token
	Parts          []Node      // Alternating string parts and expressions
}

TemplateLiteral represents template literals with interpolations. `hello ${name} world` becomes: ["hello ", Expression("name"), " world"]

func (*TemplateLiteral) String

func (tl *TemplateLiteral) String() string

func (*TemplateLiteral) TokenLiteral

func (tl *TemplateLiteral) TokenLiteral() string

type TemplateLiteralTypeExpression

type TemplateLiteralTypeExpression struct {
	BaseExpression             // Embed base for ComputedType (types.TemplateLiteralType)
	Token          lexer.Token // The opening '`' token
	Parts          []Node      // Alternating string parts and type expressions
}

TemplateLiteralTypeExpression represents a template literal type like `Hello ${T}!`

func (*TemplateLiteralTypeExpression) GetComputedType

func (tlte *TemplateLiteralTypeExpression) GetComputedType() types.Type

GetComputedType satisfies the Expression interface

func (*TemplateLiteralTypeExpression) String

func (tlte *TemplateLiteralTypeExpression) String() string

func (*TemplateLiteralTypeExpression) TokenLiteral

func (tlte *TemplateLiteralTypeExpression) TokenLiteral() string

type TemplateStringPart

type TemplateStringPart struct {
	Value             string // The cooked string content (escape sequences processed)
	Raw               string // The raw string content (escape sequences preserved for TRV)
	CookedIsUndefined bool   // True if cooked value should be undefined (invalid escape in tagged template)
}

--- ADDED: Helper struct for template string parts ---

func (*TemplateStringPart) String

func (tsp *TemplateStringPart) String() string

func (*TemplateStringPart) TokenLiteral

func (tsp *TemplateStringPart) TokenLiteral() string

type TernaryExpression

type TernaryExpression struct {
	BaseExpression             // Embed base for ComputedType (Union of consequence/alternative types?)
	Token          lexer.Token // The '?' token
	Condition      Expression
	Consequence    Expression
	Alternative    Expression
}

TernaryExpression represents a conditional (ternary) expression. <Condition> ? <Consequence> : <Alternative>

func (*TernaryExpression) String

func (te *TernaryExpression) String() string

func (*TernaryExpression) TokenLiteral

func (te *TernaryExpression) TokenLiteral() string

type ThisExpression

type ThisExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.THIS token
}

ThisExpression represents the `this` keyword.

func (*ThisExpression) String

func (te *ThisExpression) String() string

func (*ThisExpression) TokenLiteral

func (te *ThisExpression) TokenLiteral() string

type ThrowStatement

type ThrowStatement struct {
	Token lexer.Token // The 'throw' token
	Value Expression  // The expression to throw
}

ThrowStatement represents a throw statement.

func (*ThrowStatement) String

func (ths *ThrowStatement) String() string

func (*ThrowStatement) TokenLiteral

func (ths *ThrowStatement) TokenLiteral() string

type TryStatement

type TryStatement struct {
	Token        lexer.Token     // The 'try' token
	Body         *BlockStatement // The try block
	CatchClause  *CatchClause    // Optional catch clause
	FinallyBlock *BlockStatement // Optional finally block (Phase 3)
}

TryStatement represents a try/catch/finally block.

func (*TryStatement) String

func (ts *TryStatement) String() string

func (*TryStatement) TokenLiteral

func (ts *TryStatement) TokenLiteral() string

type TupleTypeExpression

type TupleTypeExpression struct {
	BaseExpression              // Embed base for ComputedType (types.TupleType)
	Token          lexer.Token  // The '[' token
	ElementTypes   []Expression // The type expressions for each element
	OptionalFlags  []bool       // Which elements are optional (same length as ElementTypes)
	RestElement    Expression   // Optional rest element type (...T[])
}

TupleTypeExpression represents a tuple type syntax (e.g., [string, number, boolean?]).

func (*TupleTypeExpression) String

func (tte *TupleTypeExpression) String() string

func (*TupleTypeExpression) TokenLiteral

func (tte *TupleTypeExpression) TokenLiteral() string

type TypeAliasStatement

type TypeAliasStatement struct {
	Token          lexer.Token      // The 'type' token
	Name           *Identifier      // The name of the alias
	TypeParameters []*TypeParameter // Generic type parameters (e.g., <T, U>)
	Type           Expression       // The type expression being aliased
}

TypeAliasStatement represents a `type Name = Type;` declaration.

func (*TypeAliasStatement) String

func (tas *TypeAliasStatement) String() string

func (*TypeAliasStatement) TokenLiteral

func (tas *TypeAliasStatement) TokenLiteral() string

type TypeAssertionExpression

type TypeAssertionExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The 'as' token
	Expression     Expression  // The expression being asserted
	TargetType     Expression  // The target type annotation
}

TypeAssertionExpression represents a type assertion expression (value as Type)

func (*TypeAssertionExpression) String

func (tae *TypeAssertionExpression) String() string

func (*TypeAssertionExpression) TokenLiteral

func (tae *TypeAssertionExpression) TokenLiteral() string

type TypeParameter

type TypeParameter struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The identifier token (e.g., 'T')
	Name           *Identifier // The type parameter name
	Constraint     Expression  // Optional constraint (e.g., 'string' in 'T extends string')
	DefaultType    Expression  // Optional default type (e.g., 'string' in 'T = string')
}

--- NEW: TypeParameter Node --- Represents a type parameter in generic function declarations (e.g., T, U extends string, V = DefaultType) Used in function<T, U extends string, V = DefaultType>() syntax

func (*TypeParameter) String

func (tp *TypeParameter) String() string

func (*TypeParameter) TokenLiteral

func (tp *TypeParameter) TokenLiteral() string

type TypePredicateExpression

type TypePredicateExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The 'is' token
	Parameter      *Identifier // The parameter being tested (e.g., "x" in "x is string")
	Type           Expression  // The type being tested for
}

TypePredicateExpression represents a type predicate like 'x is string' Used in function return types to indicate that the function is a type guard

func (*TypePredicateExpression) GetComputedType

func (tpe *TypePredicateExpression) GetComputedType() types.Type

GetComputedType satisfies the Expression interface (placeholder) The actual type is determined during type checking.

func (*TypePredicateExpression) String

func (tpe *TypePredicateExpression) String() string

func (*TypePredicateExpression) TokenLiteral

func (tpe *TypePredicateExpression) TokenLiteral() string

type TypeofExpression

type TypeofExpression struct {
	BaseExpression             // Embed base for ComputedType (always string)
	Token          lexer.Token // The 'typeof' token
	Operand        Expression  // The expression whose type we want to get
}

TypeofExpression represents a typeof operator expression. typeof <operand>

func (*TypeofExpression) String

func (te *TypeofExpression) String() string

func (*TypeofExpression) TokenLiteral

func (te *TypeofExpression) TokenLiteral() string

type TypeofTypeExpression

type TypeofTypeExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The 'typeof' token
	Identifier     string      // The identifier whose type we want to get
}

TypeofTypeExpression represents a typeof type operator like typeof someVariable Used in type contexts to extract the type of a value

func (*TypeofTypeExpression) GetComputedType

func (tte *TypeofTypeExpression) GetComputedType() types.Type

GetComputedType satisfies the Expression interface (placeholder) The actual type is determined during type checking.

func (*TypeofTypeExpression) String

func (tte *TypeofTypeExpression) String() string

func (*TypeofTypeExpression) TokenLiteral

func (tte *TypeofTypeExpression) TokenLiteral() string

type UndefinedLiteral

type UndefinedLiteral struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The lexer.UNDEFINED token
}

UndefinedLiteral represents the `undefined` keyword.

func (*UndefinedLiteral) String

func (ul *UndefinedLiteral) String() string

func (*UndefinedLiteral) TokenLiteral

func (ul *UndefinedLiteral) TokenLiteral() string

type UnionTypeExpression

type UnionTypeExpression struct {
	BaseExpression             // Embed base for ComputedType (which will be a UnionType)
	Token          lexer.Token // The '|' token
	Left           Expression  // The type expression on the left
	Right          Expression  // The type expression on the right
}

UnionTypeExpression represents a union type (e.g., string | number). For now, just binary unions (A | B). Can be nested for more types.

func (*UnionTypeExpression) String

func (ute *UnionTypeExpression) String() string

func (*UnionTypeExpression) TokenLiteral

func (ute *UnionTypeExpression) TokenLiteral() string

type UpdateExpression

type UpdateExpression struct {
	BaseExpression             // Embed base for ComputedType (usually number)
	Token          lexer.Token // The '++' or '--' token
	Operator       string      // "++" or "--"
	Argument       Expression  // The expression being updated (e.g., Identifier)
	Prefix         bool        // true if operator is prefix (++x), false if postfix (x++)
}

UpdateExpression represents prefix or postfix increment/decrement (e.g., ++x, x--). Currently restricted to identifiers as arguments.

func (*UpdateExpression) String

func (ue *UpdateExpression) String() string

func (*UpdateExpression) TokenLiteral

func (ue *UpdateExpression) TokenLiteral() string

type VarDeclarator

type VarDeclarator struct {
	Name           *Identifier // The variable name
	TypeAnnotation Expression  // Parsed type node (e.g., *Identifier)
	Value          Expression  // The expression being assigned
	ComputedType   types.Type  // Stores the resolved type from TypeAnnotation or Value
}

VarDeclarator represents a single variable declaration within a var statement

type VarStatement

type VarStatement struct {
	Token        lexer.Token      // The lexer.VAR token
	Declarations []*VarDeclarator // List of variable declarations
	// Legacy fields for backward compatibility
	Name           *Identifier // The variable name (first declaration)
	TypeAnnotation Expression  // Parsed type node (first declaration)
	Value          Expression  // The expression being assigned (first declaration)
	ComputedType   types.Type  // Stores the resolved type (first declaration)
}

VarStatement represents a `var` variable declaration. var <Name> : <TypeAnnotation> = <Value>; Supports multiple declarations: var x, y = 1, z: string = "hello";

func (*VarStatement) String

func (vs *VarStatement) String() string

func (*VarStatement) TokenLiteral

func (vs *VarStatement) TokenLiteral() string

type WhileStatement

type WhileStatement struct {
	Token     lexer.Token // The 'while' token
	Condition Expression
	Body      *BlockStatement
}

WhileStatement represents a 'while (condition) { body }' statement.

func (*WhileStatement) String

func (ws *WhileStatement) String() string

func (*WhileStatement) TokenLiteral

func (ws *WhileStatement) TokenLiteral() string

type WithStatement

type WithStatement struct {
	Token      lexer.Token // The 'with' token
	Expression Expression  // The object expression to extend the scope with
	Body       Statement   // The statement to execute with the extended scope
}

WithStatement represents a 'with (expression) statement' statement.

func (*WithStatement) String

func (ws *WithStatement) String() string

func (*WithStatement) TokenLiteral

func (ws *WithStatement) TokenLiteral() string

type YieldExpression

type YieldExpression struct {
	BaseExpression             // Embed base for ComputedType
	Token          lexer.Token // The 'yield' token
	Value          Expression  // The expression to yield (optional, can be nil)
	Delegate       bool        // True for yield* delegation
}

YieldExpression represents a yield expression in generator functions. yield [expression] or yield* [expression] for delegation

func (*YieldExpression) String

func (ye *YieldExpression) String() string

func (*YieldExpression) TokenLiteral

func (ye *YieldExpression) TokenLiteral() string

Jump to

Keyboard shortcuts

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