Documentation
¶
Overview ¶
Package wile provides the public API for embedding the Wile Scheme interpreter.
Basic usage:
engine, err := wile.NewEngine()
if err != nil {
log.Fatal(err)
}
result, err := engine.Eval(ctx, "(+ 1 2 3)")
fmt.Println(result) // 6
With extensions:
engine, err := wile.NewEngine(
wile.WithExtension(io.Extension),
wile.WithExtension(system.Extension),
)
Custom primitives:
engine, _ := wile.NewEngine()
engine.RegisterPrimitive(wile.PrimitiveSpec{
Name: "my-func",
ParamCount: 1,
Impl: myFuncImpl,
})
Index ¶
- Variables
- func IsBoolean(v Value) bool
- func IsList(v Value) bool
- func IsNull(v Value) bool
- func IsNumber(v Value) bool
- func IsPair(v Value) bool
- func IsProcedure(v Value) bool
- func IsString(v Value) bool
- func IsSymbol(v Value) bool
- func ToGoBool(v Value) (bool, bool)
- func ToGoFloat(v Value) (float64, bool)
- func ToGoInt(v Value) (int64, bool)
- func ToGoString(v Value) (string, bool)
- type CompilationError
- type CompiledCode
- type Engine
- func (p *Engine) Call(ctx context.Context, proc Value, args ...Value) (Value, error)
- func (p *Engine) Compile(ctx context.Context, code string) (*CompiledCode, error)
- func (p *Engine) CompileWithSource(ctx context.Context, code string, source string) (*CompiledCode, error)
- func (p *Engine) Define(name string, value Value) error
- func (p *Engine) Environment() *environment.EnvironmentFrame
- func (p *Engine) Eval(ctx context.Context, code string) (Value, error)
- func (p *Engine) EvalMultiple(ctx context.Context, code string) (Value, error)
- func (p *Engine) EvalMultipleWithSource(ctx context.Context, code string, source string) (Value, error)
- func (p *Engine) EvalWithSource(ctx context.Context, code string, source string) (Value, error)
- func (p *Engine) Get(name string) (Value, bool)
- func (p *Engine) LastCounters() machine.VMCounters
- func (p *Engine) RegisterFunc(name string, fn any) error
- func (p *Engine) RegisterPrimitive(spec PrimitiveSpec) error
- func (p *Engine) Run(ctx context.Context, cc *CompiledCode) (Value, error)
- func (p *Engine) TopLevelEnvironment() *environment.TopLevelEnvironment
- type EngineOption
- type Error
- type ForeignFunction
- type MachineContext
- type PrimitiveSpec
- type RuntimeError
- type Value
- func Car(v Value) (Value, bool)
- func Cdr(v Value) (Value, bool)
- func NewBigFloat(f *big.Float) Value
- func NewBigFloatFromFloat64(f float64) Value
- func NewBigFloatFromString(s string) Value
- func NewBigInteger(n *big.Int) Value
- func NewBigIntegerFromInt64(n int64) Value
- func NewBigIntegerFromString(s string, base int) Value
- func NewBoolean(b bool) Value
- func NewFloat(f float64) Value
- func NewInteger(n int64) Value
- func NewList(vals ...Value) Value
- func NewString(s string) Value
- func NewSymbol(s string) Value
- func ToSlice(v Value) ([]Value, bool)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var False = wrapValue(values.FalseValue)
False is the #f value.
var Null = wrapValue(values.EmptyList)
Null is the empty list.
var True = wrapValue(values.TrueValue)
True is the #t value.
var Void = wrapValue(values.Void)
Void is the void value.
Functions ¶
func IsPair ¶ added in v1.1.0
IsPair returns true if v is a non-empty pair (cons cell). EmptyList is not a *Pair (it's a separate type), so the type assertion handles the distinction without an explicit IsEmptyList check.
func IsProcedure ¶ added in v1.1.0
IsProcedure returns true if v is a callable procedure (lambda, case-lambda, or parameter).
func ToGoBool ¶ added in v1.1.0
ToGoBool extracts a Go bool from a Scheme boolean value. Returns (false, false) if v is not a boolean.
func ToGoFloat ¶ added in v1.1.0
ToGoFloat extracts a float64 from an inexact real value. Returns (0, false) if v is not a Float.
func ToGoInt ¶ added in v1.1.0
ToGoInt extracts an int64 from an exact integer value. Returns (0, false) if v is not an exact integer or does not fit in int64.
func ToGoString ¶ added in v1.1.0
ToGoString extracts the Go string from a Scheme string value. Returns ("", false) if v is not a string.
Types ¶
type CompilationError ¶ added in v1.1.0
CompilationError wraps errors from parsing, expanding, or compiling Scheme code.
func (*CompilationError) Error ¶ added in v1.1.0
func (p *CompilationError) Error() string
func (*CompilationError) Unwrap ¶ added in v1.1.0
func (p *CompilationError) Unwrap() error
type CompiledCode ¶
type CompiledCode struct {
// contains filtered or unexported fields
}
CompiledCode represents compiled Scheme code ready for execution.
func (*CompiledCode) String ¶
func (p *CompiledCode) String() string
String returns a string representation of the compiled code.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is the main entry point for embedding Wile.
func NewEngine ¶
func NewEngine(opts ...EngineOption) (*Engine, error)
NewEngine creates a new Wile engine. By default, only core primitives are included. Use WithExtension to add optional extensions.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/aalpar/wile"
)
func main() {
engine, err := wile.NewEngine()
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
result, err := engine.Eval(ctx, "(+ 1 2 3)")
if err != nil {
log.Fatal(err)
}
fmt.Println(result.SchemeString())
}
Output: 6
Example (WithExtension) ¶
package main
import (
"fmt"
"log"
"github.com/aalpar/wile"
"github.com/aalpar/wile/internal/extensions/io"
)
func main() {
_, err := wile.NewEngine(
wile.WithExtension(io.Extension),
)
if err != nil {
log.Fatal(err)
}
fmt.Println("engine created with I/O extension")
}
Output: engine created with I/O extension
func (*Engine) Call ¶
Call invokes a Scheme procedure with arguments. Supports all callable types: lambdas, case-lambdas, and parameters. Composable continuations cannot be called from Go (they require the VM winding stack) and return an error.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/aalpar/wile"
)
func main() {
engine, err := wile.NewEngine()
if err != nil {
log.Fatal(err)
}
// Define a Scheme function.
ctx := context.Background()
_, err = engine.EvalMultiple(ctx, `
(define (square x) (* x x))
`)
if err != nil {
log.Fatal(err)
}
// Retrieve and call it from Go.
proc, ok := engine.Get("square")
if !ok {
log.Fatal("square not found")
}
result, err := engine.Call(ctx, proc, wile.NewInteger(12))
if err != nil {
log.Fatal(err)
}
fmt.Println(result.SchemeString())
}
Output: 144
func (*Engine) Compile ¶
Compile parses and compiles code without executing.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/aalpar/wile"
)
func main() {
engine, err := wile.NewEngine()
if err != nil {
log.Fatal(err)
}
// Define a variable, then compile an expression that uses it.
ctx := context.Background()
_, err = engine.Eval(ctx, "(define x 0)")
if err != nil {
log.Fatal(err)
}
compiled, err := engine.Compile(context.Background(), "(* x x)")
if err != nil {
log.Fatal(err)
}
// Run the same compiled code with different values of x.
for _, n := range []int64{3, 5, 7} {
err = engine.Define("x", wile.NewInteger(n))
if err != nil {
log.Fatal(err)
}
result, err := engine.Run(ctx, compiled)
if err != nil {
log.Fatal(err)
}
fmt.Println(result.SchemeString())
}
}
Output: 9 25 49
func (*Engine) CompileWithSource ¶ added in v1.1.0
func (p *Engine) CompileWithSource(ctx context.Context, code string, source string) (*CompiledCode, error)
CompileWithSource parses and compiles code without executing. The source parameter identifies where the code came from (e.g. a filename) and appears in error messages and stack traces.
func (*Engine) Define ¶
Define binds a value to a name in the top-level environment.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/aalpar/wile"
)
func main() {
engine, err := wile.NewEngine()
if err != nil {
log.Fatal(err)
}
err = engine.Define("width", wile.NewInteger(800))
if err != nil {
log.Fatal(err)
}
err = engine.Define("height", wile.NewInteger(600))
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
result, err := engine.Eval(ctx, "(* width height)")
if err != nil {
log.Fatal(err)
}
fmt.Println(result.SchemeString())
}
Output: 480000
func (*Engine) Environment ¶
func (p *Engine) Environment() *environment.EnvironmentFrame
Environment returns the underlying environment for advanced use.
func (*Engine) EvalMultiple ¶
EvalMultiple evaluates multiple expressions, returning the last result.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/aalpar/wile"
)
func main() {
engine, err := wile.NewEngine()
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
result, err := engine.EvalMultiple(ctx, `
(define x 10)
(define y 20)
(+ x y)
`)
if err != nil {
log.Fatal(err)
}
fmt.Println(result.SchemeString())
}
Output: 30
func (*Engine) EvalMultipleWithSource ¶ added in v1.1.0
func (p *Engine) EvalMultipleWithSource(ctx context.Context, code string, source string) (Value, error)
EvalMultipleWithSource evaluates multiple expressions, returning the last result. The source parameter identifies where the code came from (e.g. a filename) and appears in error messages and stack traces.
func (*Engine) EvalWithSource ¶ added in v1.1.0
EvalWithSource parses, compiles, and executes Scheme code, returning the result. The source parameter identifies where the code came from (e.g. a filename) and appears in error messages and stack traces.
func (*Engine) LastCounters ¶ added in v1.1.0
func (p *Engine) LastCounters() machine.VMCounters
LastCounters returns the VM performance counters from the most recent Run or Eval call. Sub-context counters are not aggregated.
func (*Engine) RegisterFunc ¶ added in v1.1.0
RegisterFunc registers a Go function as a Scheme primitive using natural Go signatures. Supported parameter types: int64, int, float64, string, bool, []byte, []T (typed slices), map[K]V, structs (exported fields), func(...) (callbacks), wile.Value, and context.Context (first param only). Supported return types: int64, int, float64, string, bool, []byte, []T, map[K]V, structs, wile.Value, error (last return only), and void.
Variadic Go functions are supported. The variadic parameter receives all excess arguments from Scheme, converted element-by-element.
If the first parameter is context.Context, the VM's context is forwarded automatically and does not count toward the Scheme parameter count.
Callback parameters (func types) receive a Go closure that invokes a Scheme procedure through a VM sub-context. Callbacks must be called synchronously during the registered function's execution. Storing a callback for later invocation or calling it from another goroutine is unsafe — the closure captures VM state that is not goroutine-safe.
Returns a *wile.Error if fn is not a function or uses unsupported types.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/aalpar/wile"
)
func main() {
engine, err := wile.NewEngine()
if err != nil {
log.Fatal(err)
}
// Register a Go function with a natural signature — no MachineContext needed.
err = engine.RegisterFunc("double", func(n int64) int64 {
return n * 2
})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
result, err := engine.Eval(ctx, "(map double '(1 2 3 4 5))")
if err != nil {
log.Fatal(err)
}
fmt.Println(result.SchemeString())
}
Output: (2 4 6 8 10)
func (*Engine) RegisterPrimitive ¶
func (p *Engine) RegisterPrimitive(spec PrimitiveSpec) error
RegisterPrimitive adds a Go function as a Scheme primitive.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/aalpar/wile"
"github.com/aalpar/wile/values"
)
func main() {
engine, err := wile.NewEngine()
if err != nil {
log.Fatal(err)
}
// Register a Go function that doubles an integer.
err = engine.RegisterPrimitive(wile.PrimitiveSpec{
Name: "double",
ParamCount: 1,
Impl: func(_ context.Context, mc *wile.MachineContext) error {
n := mc.Arg(0).(*values.Integer).Value
mc.SetValue(values.NewInteger(n * 2))
return nil
},
})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
result, err := engine.Eval(ctx, "(double 21)")
if err != nil {
log.Fatal(err)
}
fmt.Println(result.SchemeString())
}
Output: 42
func (*Engine) TopLevelEnvironment ¶
func (p *Engine) TopLevelEnvironment() *environment.TopLevelEnvironment
TopLevelEnvironment returns the TopLevelEnvironment for advanced use. This provides access to per-instance symbol interning and phase management.
type EngineOption ¶
type EngineOption func(*engineConfig)
EngineOption configures an Engine.
func WithExtension ¶
func WithExtension(ext registry.Extension) EngineOption
WithExtension adds an extension to the engine.
func WithExtensions ¶
func WithExtensions(exts ...registry.Extension) EngineOption
WithExtensions adds multiple extensions to the engine.
func WithRegistry ¶
func WithRegistry(r *registry.Registry) EngineOption
WithRegistry uses a custom registry instead of the default. When set, core primitives are NOT automatically added.
type ForeignFunction ¶
type ForeignFunction = machine.ForeignFunction
ForeignFunction is the signature for primitive implementations. This is a re-export of machine.ForeignFunction for convenience.
type MachineContext ¶
type MachineContext = machine.MachineContext
MachineContext provides access to the VM during primitive execution. This is a re-export of machine.MachineContext for convenience.
type PrimitiveSpec ¶
type PrimitiveSpec = registry.PrimitiveSpec
PrimitiveSpec defines a primitive to be registered. This is a re-export of registry.PrimitiveSpec for convenience.
type RuntimeError ¶ added in v1.1.0
type RuntimeError struct {
Message string
Cause error
Condition Value // non-nil when Scheme raise produced the error
Source string // formatted source location ("file:line:col"), empty if unavailable
StackTrace string // formatted VM stack trace, empty if unavailable
}
RuntimeError wraps errors from executing Scheme code. If the error originated from a Scheme raise/raise-continuable, Condition holds the raised value. Source and StackTrace provide the source location and VM stack trace at the point of the error (populated when per-operation source tracking is available).
func (*RuntimeError) Error ¶ added in v1.1.0
func (p *RuntimeError) Error() string
func (*RuntimeError) Unwrap ¶ added in v1.1.0
func (p *RuntimeError) Unwrap() error
type Value ¶
type Value interface {
// SchemeString returns the Scheme representation.
SchemeString() string
// IsVoid returns true if this is the void value.
IsVoid() bool
// Internal returns the underlying values.Value for advanced use.
// This is exported for use by testing packages and advanced embedding scenarios.
Internal() values.Value
// contains filtered or unexported methods
}
Value represents a Scheme value in the public API.
func Car ¶ added in v1.1.0
Car returns the car of a pair or other Tuple type. Returns (value, true) on success, or (nil, false) if v is not a non-empty Tuple.
func Cdr ¶ added in v1.1.0
Cdr returns the cdr of a pair or other Tuple type. Returns (value, true) on success, or (nil, false) if v is not a non-empty Tuple.
func NewBigFloat ¶
NewBigFloat creates a big float value from a big.Float.
func NewBigFloatFromFloat64 ¶
NewBigFloatFromFloat64 creates a big float value from a float64.
func NewBigFloatFromString ¶
NewBigFloatFromString creates a big float from a string. Returns nil if the string is not a valid float.
func NewBigInteger ¶
NewBigInteger creates a big integer value from a big.Int.
func NewBigIntegerFromInt64 ¶
NewBigIntegerFromInt64 creates a big integer value from an int64.
func NewBigIntegerFromString ¶
NewBigIntegerFromString creates a big integer from a string in the given base. Returns nil if the string is not a valid integer.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package main provides the entry point for the Wile Scheme interpreter binary.
|
Package main provides the entry point for the Wile Scheme interpreter binary. |
|
Package environment provides variable binding and scoping for the Scheme compiler.
|
Package environment provides variable binding and scoping for the Scheme compiler. |
|
examples
|
|
|
embedding
command
basic demonstrates embedding the Wile Scheme interpreter in a Go program.
|
basic demonstrates embedding the Wile Scheme interpreter in a Go program. |
|
embedding/source-tracking
command
source-tracking demonstrates the WithSource API for embedding Wile with per-operation source location tracking.
|
source-tracking demonstrates the WithSource API for embedding Wile with per-operation source location tracking. |
|
internal
|
|
|
bootstrap
Package bootstrap initializes the top-level Scheme environment.
|
Package bootstrap initializes the top-level Scheme environment. |
|
extensions/all
Package all provides additional primitives for records, promises, and extended string/character operations.
|
Package all provides additional primitives for records, promises, and extended string/character operations. |
|
extensions/eval
Package eval provides evaluation and environment primitives.
|
Package eval provides evaluation and environment primitives. |
|
extensions/exceptions
Package exceptions provides R7RS exception handling primitives.
|
Package exceptions provides R7RS exception handling primitives. |
|
extensions/files
Package files provides file I/O primitives.
|
Package files provides file I/O primitives. |
|
extensions/gointerop
Package gointerop provides Go concurrency primitive wrappers.
|
Package gointerop provides Go concurrency primitive wrappers. |
|
extensions/io
Package io provides I/O primitives for reading and writing.
|
Package io provides I/O primitives for reading and writing. |
|
extensions/math
Package math provides transcendental and advanced mathematical primitives.
|
Package math provides transcendental and advanced mathematical primitives. |
|
extensions/system
Package system provides system interface primitives.
|
Package system provides system interface primitives. |
|
extensions/threads
Package threads provides SRFI-18 multithreading primitives.
|
Package threads provides SRFI-18 multithreading primitives. |
|
forms
Package forms provides a unified registry for special form handlers.
|
Package forms provides a unified registry for special form handlers. |
|
match
Package match implements the pattern matching engine for syntax-rules and syntax-case.
|
Package match implements the pattern matching engine for syntax-rules and syntax-case. |
|
parser
Package parser implements R7RS Scheme syntax parsing.
|
Package parser implements R7RS Scheme syntax parsing. |
|
repl
Package repl provides an interactive Read-Eval-Print Loop for Wile Scheme.
|
Package repl provides an interactive Read-Eval-Print Loop for Wile Scheme. |
|
schemeutil
Package schemeutil provides conversion utilities between syntax, datum, and Go types.
|
Package schemeutil provides conversion utilities between syntax, datum, and Go types. |
|
syntax
Package syntax implements Scheme syntax representation with hygiene support.
|
Package syntax implements Scheme syntax representation with hygiene support. |
|
tokenizer
Package tokenizer implements R7RS Scheme lexical analysis.
|
Package tokenizer implements R7RS Scheme lexical analysis. |
|
validate
Package validate validates Scheme syntax and produces typed expressions.
|
Package validate validates Scheme syntax and produces typed expressions. |
|
Package machine implements the Scheme virtual machine, compiler, and macro expander.
|
Package machine implements the Scheme virtual machine, compiler, and macro expander. |
|
Package registry provides a plugin architecture for registering Scheme primitives.
|
Package registry provides a plugin architecture for registering Scheme primitives. |
|
core
Package core provides the essential primitives required for Scheme to function.
|
Package core provides the essential primitives required for Scheme to function. |
|
helpers
Package helpers provides shared utility functions for primitive implementations.
|
Package helpers provides shared utility functions for primitive implementations. |
|
testhelpers
Package testhelpers provides shared test infrastructure for Scheme primitive tests.
|
Package testhelpers provides shared test infrastructure for Scheme primitive tests. |
|
Package gorules defines custom lint rules for the Wile project.
|
Package gorules defines custom lint rules for the Wile project. |
|
Package runtime provides the core API for embedding Wile Scheme in Go applications.
|
Package runtime provides the core API for embedding Wile Scheme in Go applications. |
|
Package values implements all Scheme runtime value types.
|
Package values implements all Scheme runtime value types. |