Documentation
¶
Overview ¶
Package monty exposes cgo-free Go bindings for the Monty sandboxed Python interpreter.
The package provides compiled runner and REPL APIs, typed value conversion, host callback dispatch, and low-level pause/resume snapshots. It embeds the platform-specific shared library needed by the bindings and loads it with purego, so normal Go module consumers do not need a local C toolchain.
For Go-owned filesystem and environment callbacks, use the companion vfs package.
Index ¶
- Variables
- func LoadReplSnapshot(data []byte) (Progress, *Repl, error)
- type Call
- type CompileOptions
- type Complete
- type Dataclass
- type Date
- type DateTime
- type Dict
- type Exception
- type ExternalFunction
- type FeedOptions
- type FeedStartOptions
- type Frame
- type FrozenSet
- type Function
- type FutureSnapshot
- type MethodHandler
- type NameLookupSnapshot
- type NamedTuple
- type OSCall
- type OSFunction
- type OSHandler
- type Pair
- type Path
- type PrintCallback
- type Progress
- type Repl
- type ReplOptions
- type ResourceLimits
- type Result
- type RunOptions
- type Runner
- type RuntimeError
- type Set
- type Snapshot
- type StartOptions
- type StatResult
- type SyntaxError
- type TimeDelta
- type TimeZone
- type Tuple
- type TypingError
- type Value
- func BigInt(value *big.Int) Value
- func Bool(value bool) Value
- func Bytes(value []byte) Value
- func CycleValue(value string) Value
- func DataclassValue(value Dataclass) Value
- func DateTimeValue(dt DateTime) Value
- func DateValue(date Date) Value
- func DictValue(items Dict) Value
- func Ellipsis() Value
- func ExceptionValue(exception Exception) Value
- func Float(value float64) Value
- func FrozenSetValue(items FrozenSet) Value
- func FunctionValue(function Function) Value
- func Int(value int64) Value
- func List(items ...Value) Value
- func MustValueOf(value any) Value
- func NamedTupleValue(value NamedTuple) Value
- func None() Value
- func PathValue(path Path) Value
- func ReprValue(value string) Value
- func SetValue(items Set) Value
- func String(value string) Value
- func TimeDeltaValue(td TimeDelta) Value
- func TimeZoneValue(tz TimeZone) Value
- func TupleValue(items ...Value) Value
- func ValueOf(value any) (Value, error)
- func (v Value) Dataclass() (Dataclass, bool)
- func (v Value) Date() (Date, bool)
- func (v Value) DateTime() (DateTime, bool)
- func (v Value) Exception() (Exception, bool)
- func (v Value) Function() (Function, bool)
- func (v Value) Kind() ValueKind
- func (v Value) MarshalJSON() ([]byte, error)
- func (v Value) Raw() any
- func (v Value) StatResult() (StatResult, bool)
- func (v Value) String() string
- func (v Value) TimeDelta() (TimeDelta, bool)
- func (v Value) TimeZone() (TimeZone, bool)
- func (v *Value) UnmarshalJSON(data []byte) error
- type ValueKind
- type Waiter
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrClosed reports that a handle-backed object no longer owns a native handle. ErrClosed = errors.New("monty handle is closed") // ErrConcurrentUse reports that the same handle-backed object is already being used. ErrConcurrentUse = errors.New("monty handle is already in use") )
Functions ¶
Types ¶
type CompileOptions ¶
type CompileOptions struct {
ScriptName string
Inputs []string
TypeCheck bool
TypeCheckStubs string
}
CompileOptions configures runner compilation.
type Dataclass ¶
type Dataclass struct {
Name string `json:"name"`
TypeID uint64 `json:"type_id"`
FieldNames []string `json:"field_names"`
Attrs Dict `json:"attrs"`
Frozen bool `json:"frozen"`
Methods map[string]MethodHandler `json:"-"`
}
Dataclass is the explicit host-side dataclass value shape.
Methods are host-only metadata and are intentionally omitted from the wire format so Rust never stores Go function pointers or opaque Go values.
type DateTime ¶
type DateTime struct {
Year int32 `json:"year"`
Month uint8 `json:"month"`
Day uint8 `json:"day"`
Hour uint8 `json:"hour"`
Minute uint8 `json:"minute"`
Second uint8 `json:"second"`
Microsecond uint32 `json:"microsecond"`
OffsetSeconds *int32 `json:"offset_seconds,omitempty"`
TimezoneName *string `json:"timezone_name,omitempty"`
}
DateTime represents a Python datetime.datetime value.
type Exception ¶
Exception is both a first-class Monty value and the explicit exception shape returned by host callbacks.
type ExternalFunction ¶
ExternalFunction handles a host external function callback.
type FeedOptions ¶
type FeedOptions struct {
Inputs map[string]Value
Functions map[string]ExternalFunction
OS OSHandler
Print PrintCallback
}
FeedOptions configures the high-level REPL helper loop.
type FeedStartOptions ¶
FeedStartOptions configures low-level REPL snippet execution.
type Frame ¶
type Frame struct {
Filename string `json:"filename"`
Line uint32 `json:"line"`
Column uint32 `json:"column"`
EndLine uint32 `json:"end_line"`
EndColumn uint32 `json:"end_column"`
FunctionName *string `json:"function_name,omitempty"`
SourceLine *string `json:"source_line,omitempty"`
}
Frame is a structured traceback frame returned by runtime and syntax errors.
type FrozenSet ¶
type FrozenSet []Value
FrozenSet is the explicit frozenset shape used by the bindings.
type FutureSnapshot ¶
type FutureSnapshot struct {
// contains filtered or unexported fields
}
FutureSnapshot is a paused future-resolution state.
func (*FutureSnapshot) Dump ¶
func (s *FutureSnapshot) Dump() ([]byte, error)
Dump serializes the current future snapshot.
func (*FutureSnapshot) PendingCallIDs ¶
func (s *FutureSnapshot) PendingCallIDs() []uint32
PendingCallIDs returns the unresolved call IDs for the future snapshot.
func (*FutureSnapshot) ResumeResults ¶
func (s *FutureSnapshot) ResumeResults(ctx context.Context, results map[uint32]Result) (Progress, error)
ResumeResults resumes a future snapshot with zero or more resolved call IDs.
type MethodHandler ¶
type MethodHandler = ExternalFunction
MethodHandler handles a host dataclass method callback.
type NameLookupSnapshot ¶
type NameLookupSnapshot struct {
VariableName string
// contains filtered or unexported fields
}
NameLookupSnapshot is a paused unresolved-name lookup.
func (*NameLookupSnapshot) Dump ¶
func (s *NameLookupSnapshot) Dump() ([]byte, error)
Dump serializes the current name-lookup snapshot.
func (*NameLookupSnapshot) ResumeUndefined ¶
func (s *NameLookupSnapshot) ResumeUndefined(ctx context.Context) (Progress, error)
ResumeUndefined resumes a name lookup as undefined.
func (*NameLookupSnapshot) ResumeValue ¶
ResumeValue resumes a name lookup with a resolved value.
type NamedTuple ¶
type NamedTuple struct {
TypeName string `json:"type_name"`
FieldNames []string `json:"field_names"`
Values []Value `json:"values"`
}
NamedTuple carries the explicit named-tuple wire shape.
type OSCall ¶
type OSCall struct {
Function OSFunction
Args []Value
Kwargs Dict
CallID uint32
}
OSCall describes an OS-level callback requested by Monty.
type OSFunction ¶
type OSFunction string
OSFunction names a host OS callback that Monty requested.
const ( OSPathExists OSFunction = "Path.exists" OSPathIsFile OSFunction = "Path.is_file" OSPathIsDir OSFunction = "Path.is_dir" OSPathIsSymlink OSFunction = "Path.is_symlink" OSPathReadText OSFunction = "Path.read_text" OSPathReadBytes OSFunction = "Path.read_bytes" OSPathWriteText OSFunction = "Path.write_text" OSPathWriteBytes OSFunction = "Path.write_bytes" OSPathMkdir OSFunction = "Path.mkdir" OSPathUnlink OSFunction = "Path.unlink" OSPathRmdir OSFunction = "Path.rmdir" OSPathIterdir OSFunction = "Path.iterdir" OSPathStat OSFunction = "Path.stat" OSPathRename OSFunction = "Path.rename" OSPathResolve OSFunction = "Path.resolve" OSPathAbsolute OSFunction = "Path.absolute" OSGetenv OSFunction = "os.getenv" OSGetEnviron OSFunction = "os.environ" )
type PrintCallback ¶
PrintCallback receives aggregated stdout text emitted during each execution step.
func WriterPrintCallback ¶
func WriterPrintCallback(w io.Writer) PrintCallback
WriterPrintCallback writes captured stdout to an io.Writer.
type Progress ¶
type Progress interface {
// contains filtered or unexported methods
}
Progress is the low-level pause/resume execution interface.
func LoadSnapshot ¶
LoadSnapshot restores a serialized non-REPL or REPL snapshot without an owner REPL.
type Repl ¶
type Repl struct {
// contains filtered or unexported fields
}
Repl is a stateful Monty REPL session.
func NewRepl ¶
func NewRepl(opts ReplOptions) (*Repl, error)
NewRepl constructs an empty REPL session.
type ReplOptions ¶
type ReplOptions struct {
ScriptName string
Limits *ResourceLimits
}
ReplOptions configures REPL construction.
type ResourceLimits ¶
type ResourceLimits struct {
MaxAllocations int
MaxDuration time.Duration
MaxMemory int
GCInterval int
MaxRecursionDepth int
}
ResourceLimits controls Monty execution limits.
A zero field value leaves that limit unset.
type Result ¶
type Result struct {
// contains filtered or unexported fields
}
Result is the explicit host callback result union.
The zero value is treated as `Return(None())`, which keeps simple handlers ergonomic while preserving an explicit pending/exception path.
type RunOptions ¶
type RunOptions struct {
Inputs map[string]Value
Functions map[string]ExternalFunction
OS OSHandler
Print PrintCallback
Limits *ResourceLimits
}
RunOptions configures the high-level runner helper loop.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner is the compiled runner entrypoint for Monty code.
func LoadRunner ¶
LoadRunner restores a serialized runner.
func New ¶
func New(code string, opts CompileOptions) (*Runner, error)
New compiles Monty code into a reusable runner.
func (*Runner) Run ¶
Run executes the runner through the high-level host callback loop.
Example ¶
package main
import (
"context"
"fmt"
monty "github.com/ewhauser/gomonty"
)
func main() {
runner, err := monty.New("40 + 2", monty.CompileOptions{
ScriptName: "example.py",
})
if err != nil {
panic(err)
}
value, err := runner.Run(context.Background(), monty.RunOptions{})
if err != nil {
panic(err)
}
fmt.Println(value.Raw())
}
Output: 42
type RuntimeError ¶
type RuntimeError struct {
Frames []Frame
// contains filtered or unexported fields
}
RuntimeError is raised for runtime failures and exposes traceback frames.
func (*RuntimeError) TracebackString ¶
func (e *RuntimeError) TracebackString() string
type Snapshot ¶
type Snapshot struct {
FunctionName string
Args []Value
Kwargs Dict
CallID uint32
IsOSFunction bool
IsMethodCall bool
// contains filtered or unexported fields
}
Snapshot is a paused external function, method call, or OS call.
func (*Snapshot) ResumeException ¶
ResumeException resumes a function or OS snapshot by raising an exception.
func (*Snapshot) ResumePending ¶
ResumePending resumes a function or OS snapshot with a pending future.
type StartOptions ¶
type StartOptions struct {
Inputs map[string]Value
Limits *ResourceLimits
}
StartOptions configures low-level runner execution.
type StatResult ¶
type StatResult struct {
Mode int64
Ino int64
Dev int64
Nlink int64
UID int64
GID int64
Size int64
Atime float64
Mtime float64
Ctime float64
}
StatResult is the explicit host helper for `os.stat_result`-compatible values.
type SyntaxError ¶
type SyntaxError struct {
// contains filtered or unexported fields
}
SyntaxError is raised for parse or compile failures.
func (*SyntaxError) TracebackString ¶
func (e *SyntaxError) TracebackString() string
type TimeDelta ¶
type TimeDelta struct {
Days int32 `json:"days"`
Seconds int32 `json:"seconds"`
Microseconds int32 `json:"microseconds"`
}
TimeDelta represents a Python datetime.timedelta value.
type TimeZone ¶
type TimeZone struct {
OffsetSeconds int32 `json:"offset_seconds"`
Name *string `json:"name,omitempty"`
}
TimeZone represents a Python datetime.timezone fixed-offset value.
type TypingError ¶
type TypingError struct {
// contains filtered or unexported fields
}
TypingError is raised for static type-check failures and can re-render the diagnostics using the formatter strings supported by Rust.
func (*TypingError) Display ¶
func (e *TypingError) Display(format string, color bool) string
Display renders the typing diagnostics using one of Rust's formatter names: `full`, `concise`, `azure`, `json`, `jsonlines`, `rdjson`, `pylint`, `gitlab`, or `github`.
func (*TypingError) TracebackString ¶
func (e *TypingError) TracebackString() string
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value is the public tagged union used by the Go bindings.
Primitive Go values round-trip directly where safe: `nil`, `bool`, signed integers, `float64`, `string`, and `[]byte`. Non-native Monty shapes remain explicit through helper structs such as Dict, Tuple, NamedTuple, Path, Dataclass, Function, and Exception.
func CycleValue ¶
CycleValue returns an output-only cycle placeholder.
func DataclassValue ¶
DataclassValue returns a dataclass value.
func ExceptionValue ¶
ExceptionValue returns an exception value.
func FrozenSetValue ¶
FrozenSetValue returns a frozenset value.
func FunctionValue ¶
FunctionValue returns an external-function value.
func MustValueOf ¶
MustValueOf converts a Go value and panics if conversion fails.
func NamedTupleValue ¶
func NamedTupleValue(value NamedTuple) Value
NamedTupleValue returns a named-tuple value.
func TimeDeltaValue ¶
TimeDeltaValue returns a timedelta value.
func (Value) MarshalJSON ¶
func (Value) StatResult ¶
func (v Value) StatResult() (StatResult, bool)
StatResult returns a stat-result payload when the value is a compatible named tuple.
func (*Value) UnmarshalJSON ¶
UnmarshalJSON decodes the stable Rust/Go wire schema for values.