Documentation
¶
Overview ¶
Package monty exposes cgo-free Go bindings for the Monty Python interpreter.
The package provides compiled runner and REPL APIs, typed value conversion, host callback dispatch, and low-level pause/resume snapshots. Native code is prepared explicitly with Prepare or the gomonty command, verified before every load, and then loaded with purego. Normal execution never downloads or builds code automatically.
For Go-owned filesystem and environment callbacks, use the companion vfs package.
Index ¶
- Variables
- func IsRuntimeUnavailable(err error) bool
- func LoadReplSnapshot(data []byte) (Progress, *Repl, error)
- type AssertMessageAnnotations
- type BuiltinFunction
- type Call
- type CompileOptions
- type Complete
- type Cycle
- type Dataclass
- type Date
- type DateTime
- type Dict
- type Exception
- type ExternalFunction
- type FeedOptions
- type FeedStartOptions
- type FileHandle
- type Frame
- type FrozenSet
- type Function
- type FutureSnapshot
- type HTTPDoer
- type MethodHandler
- type NameLookupSnapshot
- type NamedTuple
- type OSCall
- type OSFunction
- type OSHandler
- type Pair
- type Path
- type PrepareMode
- type PrepareOptions
- type PreparedRuntime
- type PrintCallback
- type Progress
- type Repl
- type ReplOptions
- type ResourceLimits
- type Result
- type RunOptions
- type Runner
- type RuntimeError
- type Set
- type Snapshot
- func (s *Snapshot) Dump() ([]byte, error)
- func (s *Snapshot) ResumeException(ctx context.Context, exception Exception) (Progress, error)
- func (s *Snapshot) ResumePending(ctx context.Context) (Progress, error)
- func (s *Snapshot) ResumeReturn(ctx context.Context, value Value) (Progress, error)
- func (s *Snapshot) WorkerPID() (int, bool)
- type StartOptions
- type StatResult
- type SyntaxError
- type TimeDelta
- type TimeZone
- type Tuple
- type Type
- type TypingError
- type Value
- func BigInt(value *big.Int) Value
- func Bool(value bool) Value
- func BuiltinFunctionValue(value BuiltinFunction) Value
- func Bytes(value []byte) Value
- func CycleRefValue(value Cycle) 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 FileHandleValue(value FileHandle) 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 TypeValue(value Type) Value
- func ValueOf(value any) (Value, error)
- func (v Value) BuiltinFunction() (BuiltinFunction, bool)
- func (v Value) Cycle() (Cycle, bool)
- 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) FileHandle() (FileHandle, 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) Type() (Type, bool)
- func (v *Value) UnmarshalJSON(data []byte) error
- type ValueKind
- type Waiter
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrRuntimeNotPrepared means no verified runtime exists in the local cache. ErrRuntimeNotPrepared = runtimebundle.ErrNotPrepared // ErrRuntimeIntegrity means native source, release bytes, a build receipt, // or cached runtime bytes failed verification. ErrRuntimeIntegrity = runtimebundle.ErrIntegrity // ErrRuntimeUnsupported means the current platform has no runtime asset. ErrRuntimeUnsupported = runtimebundle.ErrUnsupported // ErrRuntimeBuildPrerequisite means PrepareBuild could not prove that the // manifest-pinned Rust compiler and target are available locally. ErrRuntimeBuildPrerequisite = runtimebundle.ErrBuildPrerequisite )
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 ¶
func IsRuntimeUnavailable ¶
IsRuntimeUnavailable reports errors caused by a missing, corrupt, or unsupported native runtime.
Types ¶
type AssertMessageAnnotations ¶
type AssertMessageAnnotations uint32
AssertMessageAnnotations is Monty's per-operand UTF-8 byte cap for enhanced assertion messages. A value of zero disables annotations and restores CPython's empty message for a bare failing assert.
CompileOptions and ReplOptions use a pointer so nil retains Monty's default (currently 120 bytes), while a pointer to zero explicitly disables the feature.
type BuiltinFunction ¶
type BuiltinFunction struct {
Name string `json:"name"`
}
BuiltinFunction identifies an interpreter-native Python builtin.
type CompileOptions ¶
type CompileOptions struct {
ScriptName string
Inputs []string
TypeCheck bool
TypeCheckStubs string
AssertMessageAnnotations *AssertMessageAnnotations
}
CompileOptions configures runner compilation.
type Cycle ¶
Cycle identifies a repeated object within one converted result. ID is opaque and meaningful only for equality inside that result.
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
SkipTypeCheck bool
}
FeedOptions configures the high-level REPL helper loop.
type FeedStartOptions ¶
FeedStartOptions configures low-level REPL snippet execution.
type FileHandle ¶
type FileHandle struct {
Path Path `json:"path"`
Mode string `json:"mode"`
Position uint64 `json:"position"`
}
FileHandle is Monty's serializable virtual file state. It never contains a host file descriptor or host path.
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.
func (*FutureSnapshot) WorkerPID ¶
func (s *FutureSnapshot) WorkerPID() (int, bool)
WorkerPID returns the local worker process ID currently owning this paused execution. The value is diagnostic and may change after restore/recovery.
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.
func (*NameLookupSnapshot) WorkerPID ¶
func (s *NameLookupSnapshot) WorkerPID() (int, bool)
WorkerPID returns the local worker process ID currently owning this paused execution. The value is diagnostic and may change after restore/recovery.
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" OSPathAppendText OSFunction = "Path.append_text" OSPathWriteBytes OSFunction = "Path.write_bytes" OSPathAppendBytes OSFunction = "Path.append_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" OSOpen OSFunction = "open" OSDateToday OSFunction = "date.today" OSDateTimeNow OSFunction = "datetime.now" )
type PrepareMode ¶
type PrepareMode string
PrepareMode selects how the native runtime is explicitly acquired.
const ( // PrepareDownload downloads the exact release asset named in the committed // manifest and verifies the archive, shared library, and worker hashes. PrepareDownload PrepareMode = "download" // PrepareBuild builds the reviewed Rust source locally and accepts the // output only after recording hashes that the loader will recheck. PrepareBuild PrepareMode = "build" )
type PrepareOptions ¶
type PrepareOptions struct {
Mode PrepareMode
// SourceDir selects the GoMonty source tree for PrepareBuild. When empty,
// the source tree containing this package is used, including from a Go
// module cache.
SourceDir string
// ReleaseBaseURL is an optional HTTPS mirror for PrepareDownload. The
// committed file and archive hashes remain authoritative.
ReleaseBaseURL string
// HTTPClient optionally supplies transport policy for PrepareDownload.
// Redirects and TLS behavior are the caller's responsibility when set.
HTTPClient HTTPDoer
}
PrepareOptions configures an explicit native-runtime preparation. Normal execution never performs either operation automatically.
type PreparedRuntime ¶
type PreparedRuntime struct {
RuntimeVersion string `json:"runtime_version"`
Target string `json:"target"`
Mode PrepareMode `json:"mode"`
RustToolchain string `json:"rust_toolchain"`
}
PreparedRuntime reports the verified installation selected for this process.
func Prepare ¶
func Prepare(ctx context.Context, options PrepareOptions) (PreparedRuntime, error)
Prepare explicitly acquires, verifies, and atomically caches the current native runtime. It does not load the library or execute the worker.
func Prepared ¶
func Prepared() (PreparedRuntime, error)
Prepared verifies the cached native runtime without downloading, building, loading, or starting anything.
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.
func (*Repl) Close ¶
Close releases an idle REPL session and returns its worker to the internal pool. A REPL with an in-flight feed must be abandoned through its snapshot.
type ReplOptions ¶
type ReplOptions struct {
ScriptName string
Limits *ResourceLimits
TypeCheck bool
TypeCheckStubs string
AssertMessageAnnotations *AssertMessageAnnotations
}
ReplOptions configures REPL construction.
type ResourceLimits ¶
type ResourceLimits struct {
// MaxAllocations is retained for source compatibility. Monty v0.0.19 no
// longer exposes an allocation-count limit, so this field is not enforced.
// Deprecated: use MaxMemory and MaxDuration.
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/regularkevvv/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.
func (*Snapshot) ResumeReturn ¶
ResumeReturn resumes a function or OS snapshot with a return value.
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 Type ¶
Type is a Python type object returned by Monty. Instance is true for a sandbox-defined class; those values are output-only.
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 BuiltinFunctionValue ¶
func BuiltinFunctionValue(value BuiltinFunction) Value
BuiltinFunctionValue returns an interpreter-native builtin function value.
func CycleRefValue ¶
CycleRefValue returns an output-only cycle reference with its opaque identity.
func CycleValue ¶
CycleValue returns an output-only cycle placeholder.
func DataclassValue ¶
DataclassValue returns a dataclass value.
func ExceptionValue ¶
ExceptionValue returns an exception value.
func FileHandleValue ¶
func FileHandleValue(value FileHandle) Value
FileHandleValue returns serializable virtual file state.
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 TypeValue ¶
TypeValue returns a Python type object. Sandbox-defined instance types are output-only and will be rejected if supplied back as interpreter input.
func (Value) BuiltinFunction ¶
func (v Value) BuiltinFunction() (BuiltinFunction, bool)
BuiltinFunction returns the builtin-function payload if present.
func (Value) FileHandle ¶
func (v Value) FileHandle() (FileHandle, bool)
FileHandle returns the virtual file payload if present.
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.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
gomonty
command
Command gomonty manages explicit setup tasks for the GoMonty library.
|
Command gomonty manages explicit setup tasks for the GoMonty library. |
|
internal
|
|
|
cmd/runtime-release
command
|
|
|
Package vfs adapts Go-defined filesystems and environments into Monty OS handlers.
|
Package vfs adapts Go-defined filesystems and environments into Monty OS handlers. |