Mako/types/bytecode.go
2025-05-07 08:26:49 -05:00

105 lines
2.0 KiB
Go

// bytecode.go
package types
// SourcePos represents a position in the source code
type SourcePos struct {
Line int
Column int
}
// OpCode represents a bytecode instruction
type OpCode byte
const (
OP_CONSTANT OpCode = iota
OP_NIL
OP_TRUE
OP_FALSE
OP_POP
OP_GET_LOCAL
OP_SET_LOCAL
OP_GET_GLOBAL
OP_SET_GLOBAL
OP_EQUAL
OP_GREATER
OP_LESS
OP_ADD
OP_SUBTRACT
OP_MULTIPLY
OP_DIVIDE
OP_NOT
OP_NEGATE
OP_PRINT
OP_JUMP
OP_JUMP_IF_FALSE
OP_CALL
OP_RETURN
OP_CLOSURE
OP_GET_UPVALUE
OP_SET_UPVALUE
OP_CLOSE_UPVALUE
)
// String returns the string representation of an OpCode
func (op OpCode) String() string {
names := [...]string{
"OP_CONSTANT", "OP_NIL", "OP_TRUE", "OP_FALSE",
"OP_POP", "OP_GET_LOCAL", "OP_SET_LOCAL", "OP_GET_GLOBAL",
"OP_SET_GLOBAL", "OP_EQUAL", "OP_GREATER", "OP_LESS",
"OP_ADD", "OP_SUBTRACT", "OP_MULTIPLY", "OP_DIVIDE",
"OP_NOT", "OP_NEGATE", "OP_PRINT", "OP_JUMP",
"OP_JUMP_IF_FALSE", "OP_CALL", "OP_RETURN", "OP_CLOSURE",
"OP_GET_UPVALUE", "OP_SET_UPVALUE", "OP_CLOSE_UPVALUE",
}
return names[op]
}
// Instruction represents a single bytecode instruction
type Instruction struct {
Op OpCode
Operands []byte
Pos SourcePos // Source position for debugging
}
// Chunk represents a chunk of bytecode
type Chunk struct {
Code []Instruction
Constants []Value
}
// Function represents a function in bytecode
type Function struct {
Name string
Arity int
IsVariadic bool
Chunk *Chunk
Upvalues []Upvalue
LocalCount int
UpvalueCount int
}
type Closure struct {
Function *Function
Upvalues []*Upvalue
}
// Environment represents a variable scope
type Environment struct {
Values map[string]Value
Enclosing *Environment
}
// NewEnvironment creates a new environment
func NewEnvironment(enclosing *Environment) *Environment {
return &Environment{
Values: make(map[string]Value),
Enclosing: enclosing,
}
}
// Upvalue support for closures
type Upvalue struct {
Index uint8
IsLocal bool
}