values

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package values implements all Scheme runtime value types.

The package provides the complete R7RS value system:

Numeric Tower (R7RS 6.2.1)

All numeric types implement the Number interface for uniform arithmetic.

Core Types

I/O Ports (R7RS 6.13)

Port types implement Port, InputPort, OutputPort, and related interfaces:

Concurrency (SRFI-18+)

Singletons

Use Void for the absence of a value and EOFObject for end-of-file. EmptyList is the empty list sentinel.

Package values provides Scheme runtime value types.

Index

Constants

View Source
const (
	PrefixCharacter    = `#\`
	PrefixSyntax       = `#'`
	PrefixDirective    = `#!`
	PrefixBox          = `#&`
	PrefixPrimitive    = `#%`
	PrefixBlockComment = `#|`
	PrefixLineComment  = `;`

	SpecialEOF  = PrefixDirective + `eof`
	SpecialVoid = PrefixDirective + `void`
)

Prefix constants for Scheme value representations.

View Source
const DefaultBigFloatPrecision = 256

DefaultBigFloatPrecision is the default precision for BigFloat values.

Variables

View Source
var (

	// FalseValue is the singleton false boolean.
	FalseValue = NewBoolean(false)
	// TrueValue is the singleton true boolean.
	TrueValue = NewBoolean(true)
)
View Source
var (
	ErrNotABoolean                 = NewStaticError("not a boolean")
	ErrNotAnInputPort              = NewStaticError("not an input port")
	ErrNotAnOutputPort             = NewStaticError("not an output port")
	ErrNotABox                     = NewStaticError("not a box")
	ErrNotAByte                    = NewStaticError("not a byte")
	ErrNotAByteInputPort           = NewStaticError("not a byte input port")
	ErrNotAByteOutputPort          = NewStaticError("not a byte output port")
	ErrNotAnEnvironmentFrame       = NewStaticError("not an environment frame")
	ErrNotAClosureEnvironmentFrame = NewStaticError("not a closure environment frame")
	ErrNotAContinuation            = NewStaticError("not a continuation")
	ErrNotAFunctionTemplate        = NewStaticError("not a function template")
	ErrNotAModule                  = NewStaticError("not a module")
	ErrStopIteration               = NewStaticError("stop iteration")
	ErrNotAPrimitive               = NewStaticError("not a primitive")
	ErrNoSuchBinding               = NewStaticError("no such binding")
	ErrNotAGlobalIndex             = NewStaticError("not a global index")
	ErrNotANumber                  = NewStaticError("not a number")
	ErrCannotCompare               = NewStaticError("cannot compare values")
	ErrNotAFixnum                  = NewStaticError("not a fixnum")
	ErrNotARational                = NewStaticError("not a rational number")
	ErrNotAReal                    = NewStaticError("not a real number")
	ErrNotAComplex                 = NewStaticError("not a complex number")
	ErrNotAFloatingPoint           = NewStaticError("not a floating-point number")
	ErrNotAExactInteger            = NewStaticError("not a C-exact integer")
	ErrDivisionByZero              = NewStaticError("division by zero")
	ErrNotAList                    = NewStaticError("not a list")
	ErrNotACloseParen              = NewStaticError("not a close parenthesis")
	ErrWrongNumberOfArguments      = NewStaticError("wrong number of arguments")
	ErrNotAMachineContinuation     = NewStaticError("not a machine continuation")
	ErrNotAPair                    = NewStaticError("not a pair")
	ErrNotACons                    = NewStaticError("not a cons")
	ErrNotANativeTemplate          = NewStaticError("not a native template")
	ErrNotACharacter               = NewStaticError("not a character")
	ErrNotACharacterInputPort      = NewStaticError("not a character input port")
	ErrNotACharacterOutputPort     = NewStaticError("not a character output port")
	ErrStackUnderflow              = NewStaticError("stack underflow")
	ErrNotASyntaxValue             = NewStaticError("not a syntax value")
	ErrNotASyntaxPair              = NewStaticError("not a syntax pair")
	ErrNotASyntaxSymbol            = NewStaticError("not a syntax symbol")
	ErrNotASyntaxList              = NewStaticError("not a syntax list")
	ErrNotASyntaxObject            = NewStaticError("not a syntax object")
	ErrNotASymbol                  = NewStaticError("not a symbol")
	ErrInvalidSyntax               = NewStaticError("invalid syntax")
	ErrInvalidArgument             = NewStaticError("invalid argument")
	ErrDuplicateBinding            = NewStaticError("duplicate binding")
	ErrNotAClosure                 = NewStaticError("not a closure")
	ErrUnknownCharacterMnemonic    = NewStaticError("unknown character mnemonic")
	ErrNotAnInteger                = NewStaticError("not an integer")
	ErrNotALocalEnvironmentFrame   = NewStaticError("not a local environment frame")
	ErrNotAMachineTemplate         = NewStaticError("not a machine template")
	ErrUnexpectedNil               = NewStaticError("unexpected nil value")
	ErrUnexpectedTransformer       = NewStaticError("unexpected transformer")
	ErrNotAString                  = NewStaticError("not a string")
	ErrNotAVector                  = NewStaticError("not a vector")
	ErrNotAByteVector              = NewStaticError("not a bytevector")
	ErrNotAProcedure               = NewStaticError("not a procedure")
	ErrNotAStringOutputPort        = NewStaticError("not a string output port")
	ErrNotABytevectorOutputPort    = NewStaticError("not a bytevector output port")
	ErrNotANativeError             = NewStaticError("not an error object")
	ErrNotARecord                  = NewStaticError("not a record")
	ErrNotARecordType              = NewStaticError("not a record type")
	ErrFileNotFound                = NewStaticError("file not found")
	ErrLibraryNotFound             = NewStaticError("library not found")
	ErrCircularDependency          = NewStaticError("circular library dependency")
	ErrDuplicateExport             = NewStaticError("duplicate export")
	ErrDuplicateImport             = NewStaticError("duplicate import")
	ErrUnexportedIdentifier        = NewStaticError("identifier not exported")

	// Threading errors
	ErrNotAThread            = NewStaticError("not a thread")
	ErrNotAMutex             = NewStaticError("not a mutex")
	ErrNotAConditionVariable = NewStaticError("not a condition variable")
	ErrNotATime              = NewStaticError("not a time")
	ErrNotAChannel           = NewStaticError("not a channel")
	ErrNotAWaitGroup         = NewStaticError("not a wait-group")
	ErrNotARWMutex           = NewStaticError("not a rw-mutex")
	ErrNotAOnce              = NewStaticError("not a once")
	ErrNotAnAtomic           = NewStaticError("not an atomic")
	ErrPortClosed            = NewStaticError("port is closed")
	ErrNotAHashtable         = NewStaticError("not a hashtable")
	ErrNoCaptureContext      = NewStaticError("no capture context for expansion")
	ErrExactnessConversion   = NewStaticError("exactness conversion failed")
	ErrInvalidFormat         = NewStaticError("invalid number format")
	ErrUnknownOpCode         = NewStaticError("unknown op code")
	ErrNotAMatch             = NewStaticError("not a match")
	ErrNotAPromptTag         = NewStaticError("not a prompt tag")
	ErrTypeConversion        = NewStaticError("type conversion failed")
	ErrIndexOutOfRange       = NewStaticError("index out of range")
	ErrImmutableString       = NewStaticError("cannot mutate immutable string")

	// FFI errors
	ErrFFICallbackError         = NewStaticError("FFI callback error")
	ErrCallbackResultConversion = NewStaticError("callback result conversion failed")
	ErrHashtableInsertionFailed = NewStaticError("hashtable insertion failed")

	// Environment errors (keep as panics but use sentinels)
	ErrMissingTopLevelEnvironment = NewStaticError("missing TopLevelEnvironment")
	ErrMissingPhaseRegistry       = NewStaticError("missing PhaseRegistry")
	ErrNilParentEnvironment       = NewStaticError("nil parent environment")

	// Panic recovery errors
	ErrThreadPanic   = NewStaticError("thread panic")
	ErrPanicRecovery = NewStaticError("panic recovery")

	// Syntax errors
	ErrCannotDoubleSyntaxWrap  = NewStaticError("cannot wrap syntax value in SyntaxObject")
	ErrNoMatchingClause        = NewStaticError("no matching clause")
	ErrUnsupportedTransformer  = NewStaticError("unsupported transformer")
	ErrLibraryConfiguration    = NewStaticError("library configuration error")
	ErrLibraryFormMalformed    = NewStaticError("malformed library form")
	ErrLibraryNameMismatch     = NewStaticError("library name mismatch")
	ErrHashtableKeyNotFound    = NewStaticError("hashtable key not found")
	ErrAllocationLimitExceeded = NewStaticError("allocation limit exceeded")
	ErrNonContinuableException = NewStaticError("non-continuable exception")

	// Recursion depth
	ErrCallDepthExceeded = NewStaticError("call depth exceeded")

	// Escape continuations
	ErrExpiredEscape       = NewStaticError("expired escape procedure")
	ErrContinuationBarrier = NewStaticError("continuation barrier violation")

	// Utility errors (keep as panic)
	ErrRandomGenerationFailed = NewStaticError("random generation failed")
	ErrInvalidLoadPath        = NewStaticError("invalid load path")
)

Standard error values for type checking and runtime errors.

View Source
var (
	SymbolMutexNotOwned  = NewSymbol("not-owned")
	SymbolMutexAbandoned = NewSymbol("abandoned")
)

Mutex state symbol singletons.

StateValue() returns these instead of allocating fresh symbols on each call. Same process-global vs per-VM identity subtlety as the thread state symbols — see the doc comment on SymbolThreadNew in thread.go for details.

View Source
var (
	SymbolThreadNew        = NewSymbol("new")
	SymbolThreadRunnable   = NewSymbol("runnable")
	SymbolThreadBlocked    = NewSymbol("blocked")
	SymbolThreadTerminated = NewSymbol("terminated")
	SymbolThreadUnknown    = NewSymbol("unknown")
	SymbolPrimordial       = NewSymbol("primordial")
)

Thread state symbol singletons.

StateSymbol() and PrimCurrentThread return these package-level singletons instead of allocating fresh symbols on each call. This guarantees self-consistency: (eq? (thread-state t) (thread-state t)) → #t.

However, these are process-global pointers, not per-VM interned symbols. Reader-interned 'new (created via the parser gate) lives in the per-VM TopLevelEnvironment intern table and is a different pointer. Therefore:

(eq? (thread-state t) (thread-state t))  → #t  (same singleton)
(eq? (thread-state t) 'new)              → #f  (singleton ≠ interned)
(equal? (thread-state t) 'new)           → #t  (string comparison)

SRFI-18 defines thread states as symbols but does not mandate eq? identity against reader-interned symbols, so this is conformant. The equal? path works because Symbol.EqualTo compares .Key strings.

To make eq? work against reader-interned symbols, these singletons would need to participate in the per-VM intern table. That requires either:

  • Lazily interning on first use (needs access to an environment)
  • Registering these symbols during Engine initialization

The values/ package cannot import environment/ (it's lower in the dependency graph), so this would need to be driven from engine.go or registry/. This is deferred until there is a concrete need.

View Source
var (

	// ErrJoinTimeout is returned when thread-join! times out
	ErrJoinTimeout = NewStaticError("thread-join!: timeout")

	// ErrThreadAlreadyStarted is returned when starting an already-started thread
	ErrThreadAlreadyStarted = NewStaticError("thread-start!: thread already started")

	// ErrCrossThreadContinuation is returned when invoking continuation from different thread
	ErrCrossThreadContinuation = NewStaticError("cannot invoke continuation from different thread")
)
View Source
var (

	// ArrayListEmptyList is the canonical empty ArrayList encoding: [EmptyList].
	ArrayListEmptyList = NewArrayList(EmptyList)
)
View Source
var (

	// ErrChannelClosed is returned when operating on a closed channel
	ErrChannelClosed = NewStaticError("channel is closed")
)

Functions

func BigIntegerEqualsFloat added in v1.3.0

func BigIntegerEqualsFloat(bi *BigInteger, f *Float) bool

BigIntegerEqualsFloat compares a BigInteger to a Float. Returns true only if the float exactly represents the BigInteger value.

func BooleanToBool added in v1.4.0

func BooleanToBool(b *Boolean) bool

BooleanToBool converts a Scheme *Boolean to a Go bool value.

func DisplayValueToString

func DisplayValueToString(v Value) string

DisplayValueToString writes a Scheme value to a string for display with cycle detection. Unlike WriteValueToString, strings are printed without quotes and characters without #\.

func EqualTo

func EqualTo(a, b Value) bool

EqualTo compares two values for structural equality. Handles nil and void values specially: nil equals nil, void equals void. For compound types (Pair, Vector, ArrayList), uses optimistic bisimilarity with a visited set to terminate on circular structures per R7RS §6.1. This is the same technique used by Chez Scheme and Racket: when a (pointer-a, pointer-b) pair is re-encountered during recursion, return true.

func ExactInteger

func ExactInteger(v Value) (int64, bool)

ExactInteger extracts an exact integer from a Scheme value. Returns the int64 value and true if the value is an exact integer that fits in int64. Returns 0 and false otherwise.

Accepts:

  • *Integer: direct int64 value
  • *BigInteger: if it fits in int64
  • *Rational: if denominator is 1 and numerator fits in int64

R7RS defines exact integers to include rationals like 2/1 that are mathematically integers. Call sites should check for non-negativity if required (e.g., for indexes).

func IntegerEqualsFloat added in v1.3.0

func IntegerEqualsFloat(i *Integer, f *Float) bool

IntegerEqualsFloat compares an exact integer to an inexact float. Returns true only if the float exactly represents the integer value.

R7RS §6.2.5: Numeric equality must not lose precision. An exact integer and an inexact float are equal only if the float exactly represents the integer's value.

func IsEmptyList

func IsEmptyList(v Value) bool

IsEmptyList returns true if the value is the empty list. Returns false for nil values. For Tuple types, delegates to their IsEmptyList method.

func IsList

func IsList(v Value) bool

IsList returns true if the value is a proper list. A proper list is either EmptyList or a chain of pairs ending with EmptyList. Returns false for nil, improper lists (dotted pairs), and non-list values.

func IsVoid

func IsVoid(v Value) bool

IsVoid returns true if the value represents the absence of a meaningful result.

Void, EmptyList, and nil Semantics

The value system distinguishes three "absence/empty" concepts:

  • Void (voidType{} singleton): no meaningful result (e.g., set!, display). Canonical check: values.IsVoid(v) — handles both nil and the Void singleton.

  • EmptyList (emptyListType{} singleton): the empty list () — a valid first-class Scheme value. Implements Tuple but not *Pair. Canonical check: values.IsEmptyList(v) — handles nil safely (returns false).

  • Go nil (nil interface): uninitialized / absent in Go — not a Scheme value. IsVoid(nil) returns true; IsEmptyList(nil) returns false.

Anti-patterns to avoid:

  • v == values.EmptyList or v != values.EmptyList → use values.IsEmptyList(v)
  • v == values.Void → use values.IsVoid(v)
  • v == nil || values.IsVoid(v) → redundant; values.IsVoid(v) handles nil

Note: typed nil pointers (e.g., var p *Pair = nil) are handled by the type's IsVoid() method, which checks for nil receiver.

func Must added in v1.1.0

func Must(v Value, err error)

Must panics if err is non-nil or v is not EmptyList. Designed for use with ForEach on lists guaranteed to be proper:

Must(p.ForEach(ctx, func(...) error { ... }))

func ValidateByteValue added in v1.3.0

func ValidateByteValue(v *Integer, name string, desc string) error

ValidateByteValue checks that an integer is in the byte range [0, 255]. Returns a wrapped ErrNotAByte error if the value is out of range.

func ValueToBool added in v1.4.0

func ValueToBool(b Value) bool

ValueToBool converts a value into a Go bool using Scheme semantics. In Scheme, only #f is false; everything else (including 0, "", '()) is true.

func WriteSharedValueToString

func WriteSharedValueToString(v Value) string

WriteSharedValueToString writes a Scheme value to a string with shared structure detection. Uses WriteModeWriteShared: datum labels for all multiply-referenced objects. R7RS §6.13.3: write-shared outputs datum labels for all shared structure.

func WriteValueToString

func WriteValueToString(v Value) string

WriteValueToString writes a Scheme value to a string with cycle detection. Uses WriteModeWrite: datum labels only for circular references. R7RS §6.13.3: write outputs datum labels only for objects that are part of a cycle.

Types

type AbandonedMutexException

type AbandonedMutexException struct {
	Mutex Value // *Mutex, but avoid circular import
}

AbandonedMutexException is raised when a mutex owner terminates

func (*AbandonedMutexException) Error

func (p *AbandonedMutexException) Error() string

type ArrayList

type ArrayList []Value

ArrayList is an array-backed representation of Scheme lists. It stores list elements and a terminator in a contiguous []Value slice, providing O(1) element access and better cache locality than the equivalent Pair chain.

Internal layout — the last element is the terminator (CDR of the final cons cell in the equivalent Pair chain):

Proper list (1 2 3):      [1, 2, 3, EmptyList]
                           ^^^elements^^^  ^^^terminator
Improper list (1 2 . 3):  [1, 2, 3]
                           ^^elems^^  ^^last=cdr
Empty list ():             [EmptyList]
Void (no value):           nil  |  []  |  [Void]

Length() returns len(slice)-1 for proper lists (element count, excluding the terminator).

ArrayList implements Value and Tuple. It is interconvertible with Pair chains via AsList() and with Vectors via AsVector().

R7RS §6.4: Pairs and lists.

func NewArrayList

func NewArrayList(vs ...Value) *ArrayList

NewArrayList creates a new ArrayList from the given values. The caller is responsible for including the terminator: pass EmptyList as the final element for a proper list, or omit it for an improper list.

NewArrayList(Int(1), Int(2), EmptyList)  →  (1 2)
NewArrayList(Int(1), Int(2), Int(3))     →  (1 2 . 3)
NewArrayList(EmptyList)                  →  ()

func (*ArrayList) Append

func (p *ArrayList) Append(vs Value) Value

Append inserts a value before the terminator, extending the list by one element. Returns a new ArrayList; does not mutate the receiver. Panics if the receiver is void (not a list).

func (*ArrayList) AppendList

func (p *ArrayList) AppendList(o Value) *ArrayList

AppendList concatenates another list (ArrayList or Pair chain) onto this list. Returns a new ArrayList; does not mutate either operand. Panics with ErrNotAList if the receiver is void, or if the operand is not a recognized list type and the receiver is not the empty list. When the receiver is the empty list and the operand is not a list, returns a new (improper) ArrayList containing the operand.

func (*ArrayList) AsList

func (p *ArrayList) AsList() Value

AsList converts this ArrayList to a Pair (cons cell) chain. Returns nil if void. The terminator element becomes the CDR of the final Pair — EmptyList for proper lists, any other value for improper lists.

Implementation note: Must return *Pair (not Tuple) because callers expect a linked-list representation where each node can be mutated independently.

func (*ArrayList) AsVector

func (p *ArrayList) AsVector() *Vector

AsVector converts the ArrayList to a Vector containing all elements including the terminator. Returns nil if the receiver is void.

func (*ArrayList) Car

func (p *ArrayList) Car() Value

Car returns the first element. Panics if the receiver is nil or the slice is empty.

func (*ArrayList) Cdr

func (p *ArrayList) Cdr() Value

Cdr returns a new ArrayList sharing the underlying storage from index 1 onward (sub-slice, no copy). The terminator is preserved. For single-element results, returns the element directly to match Pair behavior for improper lists.

func (*ArrayList) Copy

func (p *ArrayList) Copy() *ArrayList

Copy returns a shallow copy of this ArrayList.

func (*ArrayList) Datum

func (p *ArrayList) Datum() []Value

Datum returns the raw underlying slice, including the terminator element.

func (*ArrayList) EqualTo

func (p *ArrayList) EqualTo(o Value) bool

EqualTo returns true if the other value is an *ArrayList with the same length and element-wise structural equality (via Value.EqualTo). Void elements are compared by void-ness, not identity.

Implementation note: This method requires type assertion to *ArrayList (not Tuple) because R7RS equal? distinguishes between different list representations. An ArrayList and a Pair with identical elements are not equal?.

func (*ArrayList) ForEach

func (p *ArrayList) ForEach(ctx context.Context, fn ForEachFunc) (Value, error)

ForEach iterates over elements in the list (all except the terminator). The callback receives the index, whether there are more elements after this one, and the element value. Returns the tail (the terminator) — EmptyList for proper lists, any other value for improper lists.

This matches Pair.ForEach semantics: the final cdr is returned, not visited.

func (*ArrayList) IsEmptyList

func (p *ArrayList) IsEmptyList() bool

IsEmptyList returns true if this ArrayList encodes the empty list (): a single-element slice containing the EmptyList sentinel.

func (*ArrayList) IsList

func (p *ArrayList) IsList() bool

IsList returns true if the last element is EmptyList (proper list). Returns false for nil, empty slices, and improper lists.

func (*ArrayList) IsVoid

func (p *ArrayList) IsVoid() bool

IsVoid returns true if this ArrayList represents the absence of a value. Three representations are recognized: nil receiver, empty slice, and single-element Void.

func (*ArrayList) Length

func (p *ArrayList) Length() int

Length returns the number of list elements, excluding the terminator. Panics with ErrNotAList if the receiver is not a proper list.

func (*ArrayList) SchemeString

func (p *ArrayList) SchemeString() string

SchemeString returns the Scheme external representation. Proper lists print as (a b c), improper lists as (a b . c), empty lists as (), and void values as #<void>. Single-element lists without a terminator print as the element's SchemeString directly (unwrapped).

type AtomicBox

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

AtomicBox provides atomic operations on a Value This uses atomic.Value from the standard library

func NewAtomicBox

func NewAtomicBox(initial Value) *AtomicBox

NewAtomicBox creates a new AtomicBox with the given initial value

func (*AtomicBox) CompareAndSwap

func (p *AtomicBox) CompareAndSwap(ol, nw Value) bool

CompareAndSwap atomically compares and swaps if current equals old Returns true if the swap was performed

func (*AtomicBox) EqualTo

func (p *AtomicBox) EqualTo(v Value) bool

EqualTo returns true if the atomics are the same object.

func (*AtomicBox) ID

func (p *AtomicBox) ID() uint64

ID returns the AtomicBox's unique identifier

func (*AtomicBox) IsVoid

func (p *AtomicBox) IsVoid() bool

IsVoid returns true if the atomic is nil.

func (*AtomicBox) Load

func (p *AtomicBox) Load() Value

Load atomically loads and returns the value

func (*AtomicBox) SchemeString

func (p *AtomicBox) SchemeString() string

SchemeString returns the Scheme representation of the atomic.

func (*AtomicBox) Store

func (p *AtomicBox) Store(v Value)

Store atomically stores the value

func (*AtomicBox) Swap

func (p *AtomicBox) Swap(v Value) Value

Swap atomically stores new and returns the old value

type AtomicInt64

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

AtomicInt64 provides atomic operations on int64 values This is more efficient than AtomicBox for integer operations

func NewAtomicInt64

func NewAtomicInt64(initial int64) *AtomicInt64

NewAtomicInt64 creates a new AtomicInt64 with the given initial value

func (*AtomicInt64) Add

func (p *AtomicInt64) Add(delta int64) int64

Add atomically adds delta and returns the new value

func (*AtomicInt64) CompareAndSwap

func (p *AtomicInt64) CompareAndSwap(ol, nw int64) bool

CompareAndSwap atomically compares and swaps Returns true if the swap was performed

func (*AtomicInt64) EqualTo

func (p *AtomicInt64) EqualTo(v Value) bool

EqualTo returns true if the atomics are the same object.

func (*AtomicInt64) ID

func (p *AtomicInt64) ID() uint64

ID returns the AtomicInt64's unique identifier

func (*AtomicInt64) IsVoid

func (p *AtomicInt64) IsVoid() bool

IsVoid returns true if the atomic int64 is nil.

func (*AtomicInt64) Load

func (p *AtomicInt64) Load() int64

Load atomically loads and returns the value

func (*AtomicInt64) SchemeString

func (p *AtomicInt64) SchemeString() string

SchemeString returns the Scheme representation of the atomic int64.

func (*AtomicInt64) Store

func (p *AtomicInt64) Store(v int64)

Store atomically stores the value

func (*AtomicInt64) Swap

func (p *AtomicInt64) Swap(nw int64) int64

Swap atomically stores new and returns the old value

type BigComplex

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

BigComplex represents an arbitrary-precision complex number. The real and imaginary parts can be *BigInteger, *Rational (exact), or *BigFloat (inexact).

R7RS §6.2.1: Complex numbers are part of the numeric tower hierarchy:

number ⊃ complex ⊃ real ⊃ rational ⊃ integer

R7RS §6.2.2: BigComplex is exact if both parts are BigInteger or Rational, inexact if either part is BigFloat. Operations follow exactness contagion rules.

func NewBigComplex

func NewBigComplex(rel, iam Number) *BigComplex

NewBigComplex creates a new BigComplex from real and imaginary parts. Parts must be *BigInteger, *Rational, or *BigFloat. Other types will panic.

func NewBigComplexFromBigFloats

func NewBigComplexFromBigFloats(rel, iam *BigFloat) *BigComplex

NewBigComplexFromBigFloats creates an inexact BigComplex from BigFloat parts.

func NewBigComplexFromBigIntegers

func NewBigComplexFromBigIntegers(rel, iam *BigInteger) *BigComplex

NewBigComplexFromBigIntegers creates an exact BigComplex from BigInteger parts.

func (*BigComplex) Abs added in v1.1.0

func (p *BigComplex) Abs() Number

Abs returns the magnitude of this BigComplex as a Number.

R7RS §6.2.6: For complex numbers, abs returns the magnitude.

func (*BigComplex) Add

func (p *BigComplex) Add(o Number) Number

Add returns the sum of this BigComplex and another number.

R7RS §6.2.6: The + procedure returns the sum of its arguments. R7RS §6.2.2 Exactness: exact + exact = exact, exact + inexact = inexact.

func (*BigComplex) Compare

func (p *BigComplex) Compare(o Number) int

Compare compares this BigComplex with another number by real parts.

R7RS §6.2.6: Numeric comparisons use mathematical value. For complex numbers, we compare real parts only (matching Complex behavior).

func (*BigComplex) Conjugate

func (p *BigComplex) Conjugate() *BigComplex

Conjugate returns the complex conjugate (a-bi for a+bi).

func (*BigComplex) Divide

func (p *BigComplex) Divide(o Number) Number

Divide returns the quotient of this BigComplex and another number. Complex division: (a+bi)/(c+di) = ((ac+bd) + (bc-ad)i) / (c²+d²)

R7RS §6.2.6: The / procedure returns the quotient of its arguments. R7RS §6.2.2 Exactness: exact / exact = exact, exact / inexact = inexact.

func (*BigComplex) EqualTo

func (p *BigComplex) EqualTo(o Value) bool

EqualTo returns true if both complex numbers have equal real and imaginary parts.

R7RS §6.2.6: The = procedure compares numerical values for equality.

func (*BigComplex) Imag

func (p *BigComplex) Imag() Number

Imag returns the imaginary part of the complex number.

func (*BigComplex) ImagAsBigFloat

func (p *BigComplex) ImagAsBigFloat() *BigFloat

ImagAsBigFloat returns the imaginary part converted to BigFloat for calculations.

func (*BigComplex) ImagPart added in v1.1.0

func (p *BigComplex) ImagPart() Number

ImagPart returns the imaginary part of this complex number as a Number.

R7RS §6.2.6: imag-part returns the imaginary part of a complex number.

func (*BigComplex) IsExact

func (p *BigComplex) IsExact() bool

IsExact returns true if both parts are exact (BigInteger or Rational).

R7RS §6.2.2: A complex number is exact if both real and imaginary parts are exact.

func (*BigComplex) IsFinite added in v1.1.0

func (p *BigComplex) IsFinite() bool

IsFinite returns true since BigComplex parts are always finite.

R7RS §6.2.6: BigComplex uses BigInteger, Rational, or BigFloat parts, none of which support Inf or NaN.

func (*BigComplex) IsInteger added in v1.1.0

func (p *BigComplex) IsInteger() bool

IsInteger returns true if the imaginary part is zero and the real part is an integer.

R7RS §6.2.6: integer? returns #t for complex numbers with zero imaginary part whose real part is an integer.

func (*BigComplex) IsNaN added in v1.1.0

func (p *BigComplex) IsNaN() bool

IsNaN returns false since BigComplex parts cannot represent NaN.

R7RS §6.2.6: BigComplex uses BigInteger, Rational, or BigFloat parts, none of which support NaN.

func (*BigComplex) IsRational added in v1.1.0

func (p *BigComplex) IsRational() bool

IsRational returns true if this BigComplex is a real number.

R7RS §6.2.6: rational? returns #t for real BigComplex values since BigInteger, Rational, and BigFloat parts are all finite.

func (*BigComplex) IsReal

func (p *BigComplex) IsReal() bool

IsReal returns true if the imaginary part is zero.

func (*BigComplex) IsVoid

func (p *BigComplex) IsVoid() bool

IsVoid returns true if this BigComplex is nil.

func (*BigComplex) IsZero

func (p *BigComplex) IsZero() bool

IsZero returns true if both real and imaginary parts are zero.

func (*BigComplex) LessThan

func (p *BigComplex) LessThan(o Number) bool

LessThan compares the real parts of complex numbers. Following R7RS, < is not mathematically defined for complex numbers, but we follow the existing Complex.LessThan pattern of comparing real parts.

func (*BigComplex) Magnitude

func (p *BigComplex) Magnitude() *BigFloat

Magnitude returns the absolute value (modulus) of the complex number. |a+bi| = sqrt(a² + b²)

func (*BigComplex) Multiply

func (p *BigComplex) Multiply(o Number) Number

Multiply returns the product of this BigComplex and another number. Complex multiplication: (a+bi)(c+di) = (ac-bd) + (ad+bc)i

R7RS §6.2.6: The * procedure returns the product of its arguments. R7RS §6.2.2 Exactness: exact * exact = exact, exact * inexact = inexact.

func (*BigComplex) Negate

func (p *BigComplex) Negate() Number

Negate returns the negation of this BigComplex.

func (*BigComplex) Phase

func (p *BigComplex) Phase() *BigFloat

Phase returns the phase (argument) of the complex number in radians. Uses atan2(imag, real).

func (*BigComplex) Real

func (p *BigComplex) Real() Number

Real returns the real part of the complex number.

func (*BigComplex) RealAsBigFloat

func (p *BigComplex) RealAsBigFloat() *BigFloat

RealAsBigFloat returns the real part converted to BigFloat for calculations.

func (*BigComplex) RealPart added in v1.1.0

func (p *BigComplex) RealPart() Number

RealPart returns the real part of this complex number as a Number.

R7RS §6.2.6: real-part returns the real part of a complex number.

func (*BigComplex) SchemeString

func (p *BigComplex) SchemeString() string

SchemeString returns the Scheme representation of this BigComplex.

func (*BigComplex) Subtract

func (p *BigComplex) Subtract(o Number) Number

Subtract returns the difference of this BigComplex and another number.

R7RS §6.2.6: The - procedure returns the difference of its arguments. R7RS §6.2.2 Exactness: exact - exact = exact, exact - inexact = inexact.

func (*BigComplex) ToExact

func (p *BigComplex) ToExact() Number

ToExact converts this BigComplex to an exact representation.

R7RS §6.2.6: exact returns an exact representation of its argument. If already exact, returns itself. Otherwise converts BigFloat parts to BigInteger by truncating (may lose precision).

func (*BigComplex) ToInexact

func (p *BigComplex) ToInexact() Number

ToInexact converts this BigComplex to an inexact representation.

R7RS §6.2.6: inexact returns an inexact representation of its argument. Converts BigInteger parts to BigFloat.

type BigFloat

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

BigFloat represents an arbitrary-precision floating-point number. Created with the #m prefix in Scheme (e.g., #m3.14159265358979323846).

func NewBigFloat

func NewBigFloat(v *big.Float) *BigFloat

NewBigFloat creates a new BigFloat from a big.Float.

func NewBigFloatFromFloat64

func NewBigFloatFromFloat64(v float64) *BigFloat

NewBigFloatFromFloat64 creates a new BigFloat from a float64.

func NewBigFloatFromString

func NewBigFloatFromString(s string) *BigFloat

NewBigFloatFromString creates a new BigFloat from a string. Returns nil if the string is not a valid number.

func (*BigFloat) Abs

func (p *BigFloat) Abs() Number

Abs returns the absolute value of this BigFloat.

func (*BigFloat) Add

func (p *BigFloat) Add(o Number) Number

Add returns the sum of this BigFloat and another number.

R7RS §6.2.6: The + procedure returns the sum of its arguments. R7RS §6.2.2 Exactness: inexact + inexact = inexact, exact + inexact = inexact.

func (*BigFloat) BigFloatValue

func (p *BigFloat) BigFloatValue() *big.Float

BigFloatValue returns the underlying big.Float value.

func (*BigFloat) Compare

func (p *BigFloat) Compare(o Number) int

Compare compares this BigFloat with another number.

func (*BigFloat) Divide

func (p *BigFloat) Divide(o Number) Number

Divide returns the quotient of this BigFloat and another number.

func (*BigFloat) EqualTo

func (p *BigFloat) EqualTo(o Value) bool

EqualTo returns true if this BigFloat equals another value.

func (*BigFloat) Float64

func (p *BigFloat) Float64() float64

Float64 returns the value as float64 (may lose precision).

func (*BigFloat) HashCode added in v1.3.0

func (p *BigFloat) HashCode() uint64

HashCode returns a hash code for this BigFloat. Uses the canonical inexact-family hash so that Float and BigFloat produce identical hashes for equal values.

func (*BigFloat) IsExact

func (p *BigFloat) IsExact() bool

IsExact returns false since BigFloat is always inexact.

func (*BigFloat) IsFinite added in v1.1.0

func (p *BigFloat) IsFinite() bool

IsFinite returns true since big.Float has no Inf or NaN representation.

R7RS §6.2.6: finite? returns #t for finite numbers.

func (*BigFloat) IsInteger added in v1.1.0

func (p *BigFloat) IsInteger() bool

IsInteger returns true if this BigFloat represents an integer value.

R7RS §6.2.6: integer? returns #t for inexact integers.

func (*BigFloat) IsNaN added in v1.1.0

func (p *BigFloat) IsNaN() bool

IsNaN returns false since big.Float has no NaN representation.

R7RS §6.2.6: nan? returns #f for big.Float values.

func (*BigFloat) IsNegative

func (p *BigFloat) IsNegative() bool

IsNegative returns true if this BigFloat is negative.

func (*BigFloat) IsPositive

func (p *BigFloat) IsPositive() bool

IsPositive returns true if this BigFloat is positive.

func (*BigFloat) IsRational added in v1.1.0

func (p *BigFloat) IsRational() bool

IsRational returns true since BigFloat is always finite (big.Float has no Inf/NaN).

R7RS §6.2.6: rational? returns #t for all finite real numbers.

func (*BigFloat) IsVoid

func (p *BigFloat) IsVoid() bool

IsVoid returns true if this BigFloat is nil.

func (*BigFloat) IsZero

func (p *BigFloat) IsZero() bool

IsZero returns true if this BigFloat is zero.

func (*BigFloat) LessThan

func (p *BigFloat) LessThan(o Number) bool

LessThan returns true if this BigFloat is less than another number.

func (*BigFloat) Multiply

func (p *BigFloat) Multiply(o Number) Number

Multiply returns the product of this BigFloat and another number.

func (*BigFloat) Negate

func (p *BigFloat) Negate() Number

Negate returns the negation of this BigFloat.

func (*BigFloat) SchemeString

func (p *BigFloat) SchemeString() string

SchemeString returns the Scheme representation of this BigFloat.

func (*BigFloat) Sign added in v1.1.0

func (p *BigFloat) Sign() int

Sign returns -1 if negative, 0 if zero, or 1 if positive.

func (*BigFloat) Subtract

func (p *BigFloat) Subtract(o Number) Number

Subtract returns the difference of this BigFloat and another number.

R7RS §6.2.6: The - procedure returns the difference of its arguments. R7RS §6.2.2 Exactness: inexact - inexact = inexact, exact - inexact = inexact.

func (*BigFloat) ToExact

func (p *BigFloat) ToExact() Number

ToExact converts this BigFloat to an exact Rational.

func (*BigFloat) ToInexact

func (p *BigFloat) ToInexact() Number

ToInexact returns this BigFloat unchanged since it's already inexact.

type BigInteger

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

BigInteger represents an arbitrary-precision integer. Created with the #z prefix in Scheme (e.g., #z12345678901234567890).

R7RS §6.2.1: Integers are exact numbers in the numeric tower hierarchy:

number ⊃ complex ⊃ real ⊃ rational ⊃ integer

R7RS §6.2.2: BigInteger is always exact. Operations on exact numbers produce exact results when mathematically well-defined.

R7RS §6.2.3: Implementations may support arbitrarily large exact integers. BigInteger provides this capability using Go's math/big.Int.

Precision Preservation

BigInteger operations with Float preserve precision by promoting to BigFloat for comparison and arithmetic. This avoids precision loss from converting large BigIntegers to float64 (which has only 53 bits of mantissa precision).

Prior to M5 fix, BigIntegers with >53 significant bits would be truncated when compared with Float, causing incorrect comparison results. For example, comparing 2^53+1 with 2^53.0 would incorrectly report equality after both were converted to the same float64 value.

The fix promotes both operands to BigFloat (arbitrary precision), ensuring correct comparisons and arithmetic while preserving R7RS exactness contagion (exact + inexact → inexact).

func NewBigInteger

func NewBigInteger(v *big.Int) *BigInteger

NewBigInteger creates a new BigInteger from a big.Int.

func NewBigIntegerFromInt64

func NewBigIntegerFromInt64(v int64) *BigInteger

NewBigIntegerFromInt64 creates a new BigInteger from an int64.

func NewBigIntegerFromString

func NewBigIntegerFromString(s string, base int) *BigInteger

NewBigIntegerFromString creates a new BigInteger from a string. Returns nil if the string is not a valid integer.

func (*BigInteger) Abs

func (p *BigInteger) Abs() Number

Abs returns the absolute value of this BigInteger.

func (*BigInteger) Add

func (p *BigInteger) Add(o Number) Number

Add returns the sum of this BigInteger and another number.

R7RS §6.2.6: The + procedure returns the sum of its arguments. R7RS §6.2.2 Exactness: exact + exact = exact (BigInteger), exact + inexact = inexact (Float/Complex).

func (*BigInteger) BigInt

func (p *BigInteger) BigInt() *big.Int

BigInt returns the underlying big.Int value.

func (*BigInteger) Compare

func (p *BigInteger) Compare(o Number) int

Compare compares this BigInteger with another number.

R7RS §6.2.6: Numeric comparisons use mathematical value regardless of exactness. Returns -1, 0, or 1 for less than, equal, or greater than.

func (*BigInteger) Divide

func (p *BigInteger) Divide(o Number) Number

Divide returns the quotient of this BigInteger and another number.

R7RS §6.2.6: The / procedure returns the quotient of its arguments. For exact arguments, / may return a non-integer (Rational) when the mathematical result is not an integer. Returns BigInteger only when the division is exact (remainder is zero).

R7RS §6.2.2 Exactness: exact / exact = exact (BigInteger or Rational), exact / inexact = inexact (Float or Complex).

func (*BigInteger) EqualTo

func (p *BigInteger) EqualTo(o Value) bool

EqualTo returns true if this BigInteger equals another value.

R7RS §6.2.6: The = procedure compares numerical values for equality. BigInteger also compares equal to Integer when values match.

func (*BigInteger) HashCode

func (p *BigInteger) HashCode() uint64

HashCode returns a hash of the big integer value. Uses the canonical exact-family hash so that Integer, BigInteger, and Rational produce identical hashes for equal values.

func (*BigInteger) Int64

func (p *BigInteger) Int64() int64

Int64 returns the value as int64 (may overflow for large values).

func (*BigInteger) IsExact

func (p *BigInteger) IsExact() bool

IsExact returns true as BigInteger is always exact.

R7RS §6.2.2: Integers (including BigInteger) are always exact.

func (*BigInteger) IsFinite added in v1.1.0

func (p *BigInteger) IsFinite() bool

IsFinite returns true since integers are always finite.

R7RS §6.2.6: finite? returns #t for all exact numbers.

func (*BigInteger) IsInteger added in v1.1.0

func (p *BigInteger) IsInteger() bool

IsInteger returns true since BigInteger is always an integer.

R7RS §6.2.6: integer? returns #t for exact integers.

func (*BigInteger) IsNaN added in v1.1.0

func (p *BigInteger) IsNaN() bool

IsNaN returns false since integers are never NaN.

R7RS §6.2.6: nan? returns #f for exact numbers.

func (*BigInteger) IsNegative

func (p *BigInteger) IsNegative() bool

IsNegative returns true if this BigInteger is negative.

func (*BigInteger) IsPositive

func (p *BigInteger) IsPositive() bool

IsPositive returns true if this BigInteger is positive.

func (*BigInteger) IsRational added in v1.1.0

func (p *BigInteger) IsRational() bool

IsRational returns true since integers are a subset of rationals.

R7RS §6.2.6: rational? returns #t for all real finite numbers.

func (*BigInteger) IsVoid

func (p *BigInteger) IsVoid() bool

IsVoid returns true if this BigInteger is nil.

func (*BigInteger) IsZero

func (p *BigInteger) IsZero() bool

IsZero returns true if this BigInteger is zero.

func (*BigInteger) LessThan

func (p *BigInteger) LessThan(o Number) bool

LessThan returns true if this BigInteger is less than another number.

R7RS §6.2.6: The < procedure returns #t if its arguments are monotonically increasing. Comparison across numeric types uses mathematical value.

func (*BigInteger) Multiply

func (p *BigInteger) Multiply(o Number) Number

Multiply returns the product of this BigInteger and another number.

R7RS §6.2.6: The * procedure returns the product of its arguments. R7RS §6.2.2 Exactness: exact * exact = exact, exact * inexact = inexact. Exception: Exact zero dominates—(* 0 x) may return exact 0 even when x is inexact. Zero is an exact value when the result is mathematically unambiguous. This implementation follows Chez Scheme's behavior.

func (*BigInteger) Negate

func (p *BigInteger) Negate() Number

Negate returns the negation of this BigInteger.

func (*BigInteger) SchemeString

func (p *BigInteger) SchemeString() string

SchemeString returns the Scheme representation of this BigInteger.

func (*BigInteger) Sign added in v1.1.0

func (p *BigInteger) Sign() int

Sign returns -1 if negative, 0 if zero, or 1 if positive.

func (*BigInteger) Subtract

func (p *BigInteger) Subtract(o Number) Number

Subtract returns the difference of this BigInteger and another number.

R7RS §6.2.6: The - procedure returns the difference of its arguments. R7RS §6.2.2 Exactness: exact - exact = exact, exact - inexact = inexact.

func (*BigInteger) ToExact

func (p *BigInteger) ToExact() Number

ToExact returns this BigInteger as an exact number.

R7RS §6.2.6: exact returns an exact representation of its argument. Since BigInteger is already exact, it returns itself.

func (*BigInteger) ToInexact

func (p *BigInteger) ToInexact() Number

ToInexact returns this BigInteger converted to an inexact float.

R7RS §6.2.6: inexact returns an inexact representation of its argument. Converts to Float (float64), which may lose precision for large values.

R7RS §6.2.3: The inexact representation may have limited precision, but the conversion should be as close as practical.

PRECISION NOTE: For BigIntegers with more than 53 significant bits, precision is lost when converting to float64 (IEEE 754 binary64 has only 53 bits of mantissa precision). This is compliant with R7RS which allows inexact to be approximate.

type BinaryInputPort

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

BinaryInputPort represents a Scheme binary input port.

func NewBinaryInputPort

func NewBinaryInputPort(rdr *bufio.Reader) *BinaryInputPort

NewBinaryInputPort creates a new binary input port wrapping the given rdr.

func NewBinaryInputPortFromReader

func NewBinaryInputPortFromReader(reader io.Reader) *BinaryInputPort

NewBinaryInputPortFromReader creates a new input port reading from the given byte slice.

func (*BinaryInputPort) Close

func (b *BinaryInputPort) Close() error

Close marks the port as closed and, if a closer was provided, closes the underlying stream. Close is idempotent.

func (*BinaryInputPort) Datum

func (p *BinaryInputPort) Datum() io.Reader

Datum returns the underlying io.Reader.

func (*BinaryInputPort) EqualTo

func (p *BinaryInputPort) EqualTo(v Value) bool

EqualTo returns true if both ports wrap the same rdr.

func (*BinaryInputPort) IsClosed

func (b *BinaryInputPort) IsClosed() bool

IsClosed returns true if the port has been closed.

func (*BinaryInputPort) IsVoid

func (p *BinaryInputPort) IsVoid() bool

IsVoid returns true if the port is nil.

func (*BinaryInputPort) Read

func (p *BinaryInputPort) Read(bs []byte) (int, error)

func (*BinaryInputPort) ReadByte

func (p *BinaryInputPort) ReadByte() (byte, error)

func (*BinaryInputPort) SchemeString

func (p *BinaryInputPort) SchemeString() string

SchemeString returns the Scheme representation of the port.

func (*BinaryInputPort) UnreadByte

func (p *BinaryInputPort) UnreadByte() error

type BinaryOutputPort

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

BinaryOutputPort represents a Scheme binary output port.

func NewBinaryOutputPort

func NewBinaryOutputPort(wrt *bufio.Writer) *BinaryOutputPort

NewBinaryOutputPort creates a new binary output port wrapping the given buf.

func NewBinaryOutputPortFromWriter

func NewBinaryOutputPortFromWriter(writer io.Writer) *BinaryOutputPort

NewBinaryOutputPortFromWriter creates a new input port reading from the given byte slice.

func (*BinaryOutputPort) Close

func (p *BinaryOutputPort) Close() error

Close flushes buffered data and closes the underlying stream.

func (*BinaryOutputPort) Datum

func (p *BinaryOutputPort) Datum() io.Writer

Datum returns the underlying io.Writer.

func (*BinaryOutputPort) EqualTo

func (p *BinaryOutputPort) EqualTo(v Value) bool

EqualTo returns true if both ports wrap the same buf.

func (*BinaryOutputPort) Flush

func (p *BinaryOutputPort) Flush() error

Flush flushes the port's buffer.

func (*BinaryOutputPort) IsClosed

func (b *BinaryOutputPort) IsClosed() bool

IsClosed returns true if the port has been closed.

func (*BinaryOutputPort) IsVoid

func (p *BinaryOutputPort) IsVoid() bool

IsVoid returns true if the port is nil.

func (*BinaryOutputPort) SchemeString

func (p *BinaryOutputPort) SchemeString() string

SchemeString returns the Scheme representation of the port.

func (*BinaryOutputPort) Write

func (p *BinaryOutputPort) Write(bs []byte) (int, error)

Write writes bytes to the port.

func (*BinaryOutputPort) WriteByte

func (p *BinaryOutputPort) WriteByte(b byte) error

WriteByte writes a single byte to the port.

type BinaryReader

type BinaryReader interface {
	InputPort
	ReadByte() (byte, error)
	UnreadByte() error
}

BinaryReader represents a binary input port capable of byte-level I/O.

R7RS §6.13.3: Binary input ports support read-u8, peek-u8, read-bytevector, etc.

type BinaryWriter

type BinaryWriter interface {
	OutputPort
	WriteByte(byte) error
}

BinaryWriter represents a binary output port capable of byte-level I/O.

R7RS §6.13.3: Binary output ports support write-u8, write-bytevector, etc.

type Boolean

type Boolean struct {
	Value bool
}

Boolean represents a Scheme boolean value.

func BoolToBoolean added in v1.4.0

func BoolToBoolean(b bool) *Boolean

BoolToBoolean converts a Go bool to a Scheme boolean value.

func NewBoolean

func NewBoolean(v bool) *Boolean

NewBoolean creates a new boolean value.

func ValueToBoolean added in v1.4.0

func ValueToBoolean(b Value) *Boolean

ValueToBoolean converts a value into a Scheme *Boolean using Scheme semantics.

func (*Boolean) Datum

func (p *Boolean) Datum() bool

Datum returns the underlying boolean value.

func (*Boolean) EqualTo

func (p *Boolean) EqualTo(v Value) bool

EqualTo returns true if the values are equal booleans.

func (*Boolean) HashCode

func (p *Boolean) HashCode() uint64

HashCode returns a hash of the boolean value.

func (*Boolean) IsVoid

func (p *Boolean) IsVoid() bool

IsVoid returns true if the boolean is nil.

func (*Boolean) SchemeString

func (p *Boolean) SchemeString() string

SchemeString returns the Scheme representation of the boolean.

type Box

type Box struct {
	Value Value
}

Box represents a mutable Scheme box (container).

func NewBox

func NewBox(v Value) *Box

NewBox creates a new box containing the given value.

func (*Box) Datum

func (p *Box) Datum() Value

Datum returns the boxed value.

func (*Box) EqualTo

func (p *Box) EqualTo(v Value) bool

EqualTo returns true if the boxes contain equal values.

func (*Box) IsVoid

func (p *Box) IsVoid() bool

IsVoid returns true if the box is nil.

func (*Box) SchemeString

func (p *Box) SchemeString() string

SchemeString returns the Scheme representation of the box.

func (*Box) Unbox

func (p *Box) Unbox() Value

Unbox returns the boxed value.

type Byte

type Byte struct {
	Value uint8
}

Byte represents a Scheme byte value (0-255).

func NewByte

func NewByte(v uint8) *Byte

NewByte creates a new byte value.

func (*Byte) Datum

func (p *Byte) Datum() uint8

Datum returns the underlying byte value.

func (*Byte) EqualTo

func (p *Byte) EqualTo(v Value) bool

EqualTo returns true if the bytes have equal values.

func (*Byte) HashCode

func (p *Byte) HashCode() uint64

HashCode returns a hash of the byte value.

func (*Byte) IsVoid

func (p *Byte) IsVoid() bool

IsVoid returns true if the byte is nil.

func (*Byte) SchemeString

func (p *Byte) SchemeString() string

SchemeString returns the Scheme representation of the byte.

type ByteVector

type ByteVector []*Byte

ByteVector represents a Scheme bytevector.

func NewByteVector

func NewByteVector(vs ...*Byte) *ByteVector

NewByteVector creates a new bytevector from byte values.

func NewByteVectorFromBytes

func NewByteVectorFromBytes(vs ...byte) *ByteVector

func NewByteVectorFromIntegers

func NewByteVectorFromIntegers(vs ...*Integer) (*ByteVector, error)

NewByteVectorFromIntegers creates a new bytevector from integer values. Each integer must be in the range [0, 255] per R7RS §6.4.

func (*ByteVector) AsBytes

func (p *ByteVector) AsBytes(is ...int) []byte

AsBytes converts the bytevector to a Go byte slice. The starti and endi parameters specify the range of bytes to include. If starti is negative, it is treated as 0. If endi is greater than the length of the bytevector or non-positive, it is treated as the length of the bytevector. If starti is greater than endi, it is treated as equal to endi.

func (*ByteVector) AsList

func (p *ByteVector) AsList() Tuple

AsList converts the vector to a proper list (linked list of pairs). Returns void (nil Pair) if the vector is void. Returns EmptyList if the vector is empty. Otherwise returns a newly constructed list containing the vector's elements.

func (*ByteVector) Datum

func (p *ByteVector) Datum() []*Byte

Datum returns the underlying byte slice.

func (*ByteVector) EqualTo

func (p *ByteVector) EqualTo(v Value) bool

EqualTo returns true if the bytevectors have equal contents.

func (*ByteVector) Get

func (p *ByteVector) Get(i int) Value

func (*ByteVector) IsVoid

func (p *ByteVector) IsVoid() bool

IsVoid returns true if the bytevector is nil.

func (*ByteVector) Length

func (p *ByteVector) Length() int

func (*ByteVector) SchemeString

func (p *ByteVector) SchemeString() string

SchemeString returns the Scheme representation of the bytevector.

func (*ByteVector) Set

func (p *ByteVector) Set(i int, value Value) error

Set sets the element at the specified index to the given value. ByteVectors are always mutable, so this never returns an error from immutability. Returns an error if the value is not a Byte.

type ByteVectorBufferdOutputPort

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

ByteVectorBufferdOutputPort represents a Scheme output port writing to memory.

func NewByteVectorBufferdOutputPort

func NewByteVectorBufferdOutputPort() *ByteVectorBufferdOutputPort

NewByteVectorBufferdOutputPort creates a new in-memory bytevector output port.

func NewByteVectorBufferdOutputPortFromBuffer

func NewByteVectorBufferdOutputPortFromBuffer(buf *bytes.Buffer) *ByteVectorBufferdOutputPort

NewByteVectorBufferdOutputPortFromBuffer creates a new in-memory bytevector output port.

func (*ByteVectorBufferdOutputPort) Close

func (b *ByteVectorBufferdOutputPort) Close() error

Close marks the port as closed and, if a closer was provided, closes the underlying stream. Close is idempotent.

func (*ByteVectorBufferdOutputPort) Datum

Datum returns the underlying bytes.Buffer.

func (*ByteVectorBufferdOutputPort) EqualTo

func (p *ByteVectorBufferdOutputPort) EqualTo(v Value) bool

EqualTo returns true if both ports share the same buffer.

func (*ByteVectorBufferdOutputPort) Flush

func (*ByteVectorBufferdOutputPort) IsClosed

func (b *ByteVectorBufferdOutputPort) IsClosed() bool

IsClosed returns true if the port has been closed.

func (*ByteVectorBufferdOutputPort) IsVoid

func (p *ByteVectorBufferdOutputPort) IsVoid() bool

IsVoid returns true if this port is nil.

func (*ByteVectorBufferdOutputPort) ReadByteVector

func (p *ByteVectorBufferdOutputPort) ReadByteVector() (*ByteVector, error)

func (*ByteVectorBufferdOutputPort) SchemeString

func (p *ByteVectorBufferdOutputPort) SchemeString() string

SchemeString returns the Scheme representation of this port.

func (*ByteVectorBufferdOutputPort) Write

func (p *ByteVectorBufferdOutputPort) Write(bs []byte) (int, error)

func (*ByteVectorBufferdOutputPort) WriteByte

func (p *ByteVectorBufferdOutputPort) WriteByte(b byte) error

type ByteVectorExtractor

type ByteVectorExtractor interface {
	ReadByteVector() (*ByteVector, error)
}

ByteVectorExtractor represents a port that can extract its accumulated bytes.

type ByteVectorInputOutputPort

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

ByteVectorInputOutputPort represents a Scheme output port writing to memory.

func NewByteVectorInputOutputPort

func NewByteVectorInputOutputPort() *ByteVectorInputOutputPort

NewByteVectorInputOutputPort creates a new in-memory bytevector output port.

func NewByteVectorInputOutputPortFromBuffer

func NewByteVectorInputOutputPortFromBuffer(buf *bytes.Buffer) *ByteVectorInputOutputPort

NewByteVectorInputOutputPortFromBuffer creates a new in-memory bytevector output port.

func (*ByteVectorInputOutputPort) Close

func (b *ByteVectorInputOutputPort) Close() error

Close marks the port as closed and, if a closer was provided, closes the underlying stream. Close is idempotent.

func (*ByteVectorInputOutputPort) Datum

Datum returns the underlying bytes.Buffer.

func (*ByteVectorInputOutputPort) EqualTo

func (p *ByteVectorInputOutputPort) EqualTo(v Value) bool

EqualTo returns true if both ports share the same buffer.

func (*ByteVectorInputOutputPort) Flush

func (p *ByteVectorInputOutputPort) Flush() error

func (*ByteVectorInputOutputPort) IsClosed

func (b *ByteVectorInputOutputPort) IsClosed() bool

IsClosed returns true if the port has been closed.

func (*ByteVectorInputOutputPort) IsVoid

func (p *ByteVectorInputOutputPort) IsVoid() bool

IsVoid returns true if this port is nil.

func (*ByteVectorInputOutputPort) Read

func (p *ByteVectorInputOutputPort) Read(bs []byte) (int, error)

func (*ByteVectorInputOutputPort) ReadByte

func (p *ByteVectorInputOutputPort) ReadByte() (byte, error)

func (*ByteVectorInputOutputPort) ReadByteVector

func (p *ByteVectorInputOutputPort) ReadByteVector() (*ByteVector, error)

func (*ByteVectorInputOutputPort) SchemeString

func (p *ByteVectorInputOutputPort) SchemeString() string

SchemeString returns the Scheme representation of this port.

func (*ByteVectorInputOutputPort) UnreadByte

func (p *ByteVectorInputOutputPort) UnreadByte() error

UnreadByte unreads the last byte read, allowing it to be read again.

func (*ByteVectorInputOutputPort) Write

func (p *ByteVectorInputOutputPort) Write(bs []byte) (int, error)

func (*ByteVectorInputOutputPort) WriteByte

func (p *ByteVectorInputOutputPort) WriteByte(b byte) error

type ByteVectorInputPort

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

ByteVectorInputPort represents a Scheme input port reading from a byte slice.

func NewByteVectorInputPort

func NewByteVectorInputPort(reader *bufio.Reader) *ByteVectorInputPort

NewByteVectorInputPort creates a new input port reading from the given byte slice.

func NewByteVectorInputPortFromReader

func NewByteVectorInputPortFromReader(reader io.Reader) *ByteVectorInputPort

NewByteVectorInputPortFromReader creates a new input port reading from the given byte slice.

func (*ByteVectorInputPort) Close

func (b *ByteVectorInputPort) Close() error

Close marks the port as closed and, if a closer was provided, closes the underlying stream. Close is idempotent.

func (*ByteVectorInputPort) Datum

func (p *ByteVectorInputPort) Datum() *bufio.Reader

Datum returns the underlying bytes.Reader.

func (*ByteVectorInputPort) EqualTo

func (p *ByteVectorInputPort) EqualTo(v Value) bool

EqualTo returns true if both ports share the same rdr.

func (*ByteVectorInputPort) IsClosed

func (b *ByteVectorInputPort) IsClosed() bool

IsClosed returns true if the port has been closed.

func (*ByteVectorInputPort) IsVoid

func (p *ByteVectorInputPort) IsVoid() bool

IsVoid returns true if this port is nil.

func (*ByteVectorInputPort) Read

func (p *ByteVectorInputPort) Read(bs []byte) (int, error)

func (*ByteVectorInputPort) ReadByte

func (p *ByteVectorInputPort) ReadByte() (byte, error)

ReadByte reads and returns the next byte from the port.

func (*ByteVectorInputPort) SchemeString

func (p *ByteVectorInputPort) SchemeString() string

SchemeString returns the Scheme representation of this port.

func (*ByteVectorInputPort) UnreadByte

func (p *ByteVectorInputPort) UnreadByte() error

UnreadByte unreads the last byte read, allowing it to be read again.

type ByteVectorOutputPort

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

ByteVectorOutputPort represents a Scheme output port writing to memory.

func NewByteVectorOutputPort

func NewByteVectorOutputPort(wrt *bufio.Writer) *ByteVectorOutputPort

NewByteVectorOutputPort creates a new in-memory bytevector output port.

func NewByteVectorOutputPortFromWriter

func NewByteVectorOutputPortFromWriter(wrt io.Writer) *ByteVectorOutputPort

NewByteVectorOutputPortFromWriter creates a new in-memory bytevector output port.

func (*ByteVectorOutputPort) Close

func (p *ByteVectorOutputPort) Close() error

Close flushes buffered data and closes the underlying stream.

func (*ByteVectorOutputPort) Datum

func (p *ByteVectorOutputPort) Datum() *bufio.Writer

Datum returns the underlying bytes.Buffer.

func (*ByteVectorOutputPort) EqualTo

func (p *ByteVectorOutputPort) EqualTo(v Value) bool

EqualTo returns true if both ports share the same buffer.

func (*ByteVectorOutputPort) Flush

func (p *ByteVectorOutputPort) Flush() error

func (*ByteVectorOutputPort) IsClosed

func (b *ByteVectorOutputPort) IsClosed() bool

IsClosed returns true if the port has been closed.

func (*ByteVectorOutputPort) IsVoid

func (p *ByteVectorOutputPort) IsVoid() bool

IsVoid returns true if this port is nil.

func (*ByteVectorOutputPort) SchemeString

func (p *ByteVectorOutputPort) SchemeString() string

SchemeString returns the Scheme representation of this port.

func (*ByteVectorOutputPort) Write

func (p *ByteVectorOutputPort) Write(bs []byte) (int, error)

func (*ByteVectorOutputPort) WriteByte

func (p *ByteVectorOutputPort) WriteByte(b byte) error

type Channel

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

Channel represents a Go channel exposed to Scheme

func NewChannel

func NewChannel(bufferSize int) *Channel

NewChannel creates a new channel with the given buffer size bufferSize of 0 creates an unbuffered channel

func (*Channel) BufferSize

func (p *Channel) BufferSize() int

BufferSize returns the channel's buffer size

func (*Channel) Cap

func (p *Channel) Cap() int

Cap returns the channel's capacity

func (*Channel) Chan

func (p *Channel) Chan() chan Value

Chan returns the underlying Go channel for use in select statements

func (*Channel) Close

func (p *Channel) Close() error

Close closes the channel

func (*Channel) EqualTo

func (p *Channel) EqualTo(v Value) bool

EqualTo returns true if both channels are the same object.

func (*Channel) ID

func (p *Channel) ID() uint64

ID returns the channel's unique identifier

func (*Channel) IsClosed

func (p *Channel) IsClosed() bool

IsClosed returns true if the channel is closed

func (*Channel) IsVoid

func (p *Channel) IsVoid() bool

IsVoid returns true if this channel is nil.

func (*Channel) Len

func (p *Channel) Len() int

Len returns the number of elements queued in the channel

func (*Channel) Receive

func (p *Channel) Receive() (Value, bool)

Receive receives a value from the channel (blocking) Returns the value and true, or nil and false if channel is closed

func (*Channel) SchemeString

func (p *Channel) SchemeString() string

SchemeString returns the Scheme representation of this channel.

func (*Channel) Send

func (p *Channel) Send(v Value) error

Send sends a value on the channel (blocking)

func (*Channel) TryReceive

func (p *Channel) TryReceive() (Value, bool, bool)

TryReceive attempts to receive a value without blocking Returns (value, true, true) if received Returns (nil, false, true) if would block Returns (nil, false, false) if channel is closed

func (*Channel) TrySend

func (p *Channel) TrySend(v Value) (bool, error)

TrySend attempts to send a value without blocking Returns true if sent, false if would block

type Character

type Character struct {
	Value rune
}

Character represents a Scheme character value.

func NewCharacter

func NewCharacter(v rune) *Character

NewCharacter creates a new character from a rune.

func (*Character) Datum

func (p *Character) Datum() rune

Datum returns the underlying rune value.

func (*Character) EqualTo

func (p *Character) EqualTo(v Value) bool

EqualTo returns true if both characters have the same rune value.

func (*Character) HashCode

func (p *Character) HashCode() uint64

HashCode returns a hash of the character value.

func (*Character) IsVoid

func (p *Character) IsVoid() bool

IsVoid returns true if the character is nil.

func (*Character) SchemeString

func (p *Character) SchemeString() string

SchemeString returns the Scheme representation of the character.

func (*Character) String

func (p *Character) String() string

type CharacterInputPort

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

CharacterInputPort represents a Scheme textual input port.

func NewCharacterInputPort

func NewCharacterInputPort(rdr *bufio.Reader) *CharacterInputPort

NewCharacterInputPort creates a new character input port from an io.RuneReader.

func NewCharacterInputPortFromReader

func NewCharacterInputPortFromReader(rdr io.Reader) *CharacterInputPort

NewCharacterInputPortFromReader creates a new character input port from an io.Reader.

func (*CharacterInputPort) Close

func (b *CharacterInputPort) Close() error

Close marks the port as closed and, if a closer was provided, closes the underlying stream. Close is idempotent.

func (*CharacterInputPort) Datum

func (p *CharacterInputPort) Datum() io.RuneReader

Datum returns the underlying io.RuneReader.

func (*CharacterInputPort) EqualTo

func (p *CharacterInputPort) EqualTo(v Value) bool

EqualTo returns true if both ports wrap the same rdr.

func (*CharacterInputPort) IsClosed

func (b *CharacterInputPort) IsClosed() bool

IsClosed returns true if the port has been closed.

func (*CharacterInputPort) IsVoid

func (p *CharacterInputPort) IsVoid() bool

IsVoid returns true if the port is nil.

func (*CharacterInputPort) Read

func (p *CharacterInputPort) Read(bs []byte) (int, error)

func (*CharacterInputPort) ReadRune

func (p *CharacterInputPort) ReadRune() (rune, int, error)

func (*CharacterInputPort) SchemeString

func (p *CharacterInputPort) SchemeString() string

SchemeString returns the Scheme representation of the port.

func (*CharacterInputPort) UnreadRune

func (p *CharacterInputPort) UnreadRune() error

type CharacterOutputPort

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

CharacterOutputPort represents a Scheme textual output port.

func NewCharacterOutputPort

func NewCharacterOutputPort(wrt *bufio.Writer) *CharacterOutputPort

NewCharacterOutputPort creates a new character input port from an io.Reader.

func NewCharacterOutputPortFromWriter

func NewCharacterOutputPortFromWriter(wrt io.Writer) *CharacterOutputPort

NewCharacterOutputPortFromWriter creates a new character output port wrapping the given buf.

func (*CharacterOutputPort) Close

func (p *CharacterOutputPort) Close() error

Close flushes buffered data and closes the underlying stream.

func (*CharacterOutputPort) Datum

func (p *CharacterOutputPort) Datum() io.Writer

Datum returns the underlying data of the CharacterOutputPort as an io.Writer. there is no RunWriter interface in the standard library, so we just use io.Writer here.

func (*CharacterOutputPort) EqualTo

func (p *CharacterOutputPort) EqualTo(v Value) bool

EqualTo returns true if both ports wrap the same buf.

func (*CharacterOutputPort) Flush

func (p *CharacterOutputPort) Flush() error

func (*CharacterOutputPort) IsClosed

func (b *CharacterOutputPort) IsClosed() bool

IsClosed returns true if the port has been closed.

func (*CharacterOutputPort) IsVoid

func (p *CharacterOutputPort) IsVoid() bool

IsVoid returns true if the port is nil.

func (*CharacterOutputPort) SchemeString

func (p *CharacterOutputPort) SchemeString() string

SchemeString returns the Scheme representation of the port.

func (*CharacterOutputPort) Write

func (p *CharacterOutputPort) Write(bs []byte) (int, error)

func (*CharacterOutputPort) WriteRune

func (p *CharacterOutputPort) WriteRune(rn rune) (int, error)

WriteRune writes a single rune to the port's buf.

func (*CharacterOutputPort) WriteString

func (p *CharacterOutputPort) WriteString(s string) (int, error)

type CompileTimeValue

type CompileTimeValue struct {
	Value Value
}

CompileTimeValue wraps a value that is stored in the expand phase but accessible during macro expansion. This enables compile-time computation via define-for-syntax and begin-for-syntax.

func NewCompileTimeValue

func NewCompileTimeValue(v Value) *CompileTimeValue

NewCompileTimeValue creates a new compile-time value.

func (*CompileTimeValue) EqualTo

func (p *CompileTimeValue) EqualTo(v Value) bool

EqualTo returns true if the compile-time values are equal.

func (*CompileTimeValue) IsVoid

func (p *CompileTimeValue) IsVoid() bool

IsVoid returns true if the compile-time value is nil.

func (*CompileTimeValue) SchemeString

func (p *CompileTimeValue) SchemeString() string

SchemeString returns the Scheme representation of the compile-time value.

func (*CompileTimeValue) Unwrap

func (p *CompileTimeValue) Unwrap() Value

type Complex

type Complex struct {
	Value complex128
}

Complex represents a Scheme complex number.

func NewComplex

func NewComplex(v complex128) *Complex

NewComplex creates a new complex number from a complex128 value.

func NewComplexFromParts

func NewComplexFromParts(realPart, imagPart float64) *Complex

NewComplexFromParts creates a new complex number from real and imaginary parts.

func (*Complex) Abs added in v1.1.0

func (p *Complex) Abs() Number

Abs returns the magnitude of this complex number.

R7RS §6.2.6: For complex numbers, abs returns the magnitude.

func (*Complex) Add

func (p *Complex) Add(o Number) Number

Add returns the sum of this complex number and another number.

func (*Complex) Compare

func (p *Complex) Compare(o Number) int

Compare compares this complex number with another number by real parts.

R7RS §6.2.6: Complex comparison compares real parts only. Returns -1 if p < o, 0 if p == o, 1 if p > o.

func (*Complex) Datum

func (p *Complex) Datum() complex128

Datum returns the underlying complex128 value.

func (*Complex) Divide

func (p *Complex) Divide(o Number) Number

Divide returns the quotient of this complex number and another number.

func (*Complex) EqualTo

func (p *Complex) EqualTo(v Value) bool

EqualTo returns true if both complex numbers have the same value.

func (*Complex) Imag

func (p *Complex) Imag() float64

Imag returns the imaginary part of the complex number.

func (*Complex) ImagPart added in v1.1.0

func (p *Complex) ImagPart() Number

ImagPart returns the imaginary part of this complex number as a Number.

R7RS §6.2.6: imag-part returns the imaginary part of a complex number.

func (*Complex) IsExact

func (p *Complex) IsExact() bool

IsExact returns false since Complex is always inexact.

R7RS §6.2.2: Complex numbers with floating-point components are inexact.

func (*Complex) IsFinite added in v1.1.0

func (p *Complex) IsFinite() bool

IsFinite returns true if both real and imaginary parts are finite.

R7RS §6.2.6: finite? returns #t if neither part is Inf or NaN.

func (*Complex) IsInteger added in v1.1.0

func (p *Complex) IsInteger() bool

IsInteger returns true if this complex has zero imaginary part and an integer real part.

R7RS §6.2.6: integer? returns #t for complex numbers with zero imaginary part whose real part is an integer.

func (*Complex) IsNaN added in v1.1.0

func (p *Complex) IsNaN() bool

IsNaN returns true if either the real or imaginary part is NaN.

R7RS §6.2.6: nan? returns #t if any component is NaN.

func (*Complex) IsRational added in v1.1.0

func (p *Complex) IsRational() bool

IsRational returns true if the imaginary part is zero and the real part is finite.

R7RS §6.2.6: A complex number with zero imaginary part is rational if its real part is a finite real number.

func (*Complex) IsReal

func (p *Complex) IsReal() bool

IsReal returns true if the imaginary part is zero.

func (*Complex) IsVoid

func (p *Complex) IsVoid() bool

IsVoid returns true if this complex number is nil.

func (*Complex) IsZero

func (p *Complex) IsZero() bool

IsZero returns true if this complex number is zero.

func (*Complex) LessThan

func (p *Complex) LessThan(o Number) bool

LessThan compares the real parts of the complex numbers.

func (*Complex) Magnitude

func (p *Complex) Magnitude() float64

Magnitude returns the absolute value (modulus) of the complex number.

func (*Complex) Multiply

func (p *Complex) Multiply(o Number) Number

Multiply returns the product of this complex number and another number.

func (*Complex) Negate

func (p *Complex) Negate() Number

Negate returns the negation of this complex number.

R7RS §6.2.6: The - procedure with one argument returns the additive inverse.

func (*Complex) Phase

func (p *Complex) Phase() float64

Phase returns the phase (argument) of the complex number in radians.

func (*Complex) Real

func (p *Complex) Real() float64

Real returns the real part of the complex number.

func (*Complex) RealPart added in v1.1.0

func (p *Complex) RealPart() Number

RealPart returns the real part of this complex number as a Number.

R7RS §6.2.6: real-part returns the real part of a complex number.

func (*Complex) SchemeString

func (p *Complex) SchemeString() string

SchemeString returns the Scheme representation of this complex number. R7RS §6.2.6: Ensures decimal point for inexact values, lowercase inf/nan.

func (*Complex) Subtract

func (p *Complex) Subtract(o Number) Number

Subtract returns the difference of this complex number and another number.

func (*Complex) ToExact added in v1.1.0

func (p *Complex) ToExact() Number

ToExact converts this Complex to an exact representation.

R7RS §6.2.6: exact returns an exact representation of its argument. Both real and imaginary parts are converted to exact numbers.

func (*Complex) ToInexact added in v1.1.0

func (p *Complex) ToInexact() Number

ToInexact returns this Complex unchanged since it is already inexact.

R7RS §6.2.6: inexact returns an inexact representation of its argument.

type ComplexNumber added in v1.1.0

type ComplexNumber interface {
	Number
	RealPart() Number
	ImagPart() Number
	IsReal() bool
}

ComplexNumber represents a complex-valued number with accessible parts.

R7RS §6.2.6: Complex numbers have real and imaginary parts accessible via real-part and imag-part.

type ConditionVariable

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

ConditionVariable represents a Scheme condition variable (SRFI-18)

func NewConditionVariable

func NewConditionVariable(name string) *ConditionVariable

NewConditionVariable creates a new condition variable

func (*ConditionVariable) Broadcast

func (p *ConditionVariable) Broadcast()

Broadcast wakes all waiting threads

func (*ConditionVariable) EqualTo

func (p *ConditionVariable) EqualTo(v Value) bool

EqualTo returns true if the condition variables are the same object.

func (*ConditionVariable) ID

func (p *ConditionVariable) ID() uint64

ID returns the condition variable's unique identifier

func (*ConditionVariable) IsVoid

func (p *ConditionVariable) IsVoid() bool

IsVoid returns true if the condition variable is nil.

func (*ConditionVariable) Name

func (p *ConditionVariable) Name() string

Name returns the condition variable's name

func (*ConditionVariable) SchemeString

func (p *ConditionVariable) SchemeString() string

SchemeString returns the Scheme representation of this condition variable.

func (*ConditionVariable) SetSpecific

func (p *ConditionVariable) SetSpecific(v Value)

SetSpecific sets the condition variable's specific field

func (*ConditionVariable) Signal

func (p *ConditionVariable) Signal()

Signal wakes one waiting thread

func (*ConditionVariable) Specific

func (p *ConditionVariable) Specific() Value

Specific returns the condition variable's specific field

func (*ConditionVariable) Wait

func (p *ConditionVariable) Wait(_ *Mutex, timeout *time.Duration) bool

Wait waits on the condition variable The mutex must be held when calling Wait Returns true if signaled, false if timeout

func (*ConditionVariable) WaiterCount

func (p *ConditionVariable) WaiterCount() int

WaiterCount returns the number of threads waiting on this condition variable

type Exactness

type Exactness int

Exactness represents whether a number is exact or inexact.

R7RS §6.2.2: Numbers are either exact or inexact. A number is exact if it was written as an exact constant or derived from exact numbers using only exact operations. Otherwise, it is inexact.

const (
	Exact Exactness = iota
	Inexact
)

Exactness constants for R7RS exact/inexact classification.

func ExactnessOf

func ExactnessOf(n Number) Exactness

ExactnessOf returns the exactness of a number.

R7RS §6.2.2: - Integer, BigInteger, Rational are exact - Float, BigFloat, Complex are inexact - BigComplex depends on its components

type Float

type Float struct {
	Value float64
}

Float represents a Scheme floating-point number.

func NewFloat

func NewFloat(v float64) *Float

NewFloat creates a new float value.

func (*Float) Abs

func (p *Float) Abs() Number

Abs returns the absolute value of this float.

func (*Float) Add

func (p *Float) Add(o Number) Number

Add returns the sum of two numbers.

R7RS §6.2.6: The + procedure returns the sum of its arguments. R7RS §6.2.2 Exactness: inexact + inexact = inexact, exact + inexact = inexact.

func (*Float) Compare

func (p *Float) Compare(o Number) int

Compare compares this float with another number.

R7RS §6.2.6: Numeric comparisons use mathematical value regardless of exactness. Returns -1 if p < o, 0 if p == o, 1 if p > o.

func (*Float) Datum

func (p *Float) Datum() float64

Datum returns the underlying float64 value.

func (*Float) Divide

func (p *Float) Divide(o Number) Number

Divide returns the quotient of this float and another number.

func (*Float) EqualTo

func (p *Float) EqualTo(v Value) bool

EqualTo returns true if both floats have the same value. Handles comparison with both Float and BigFloat types for symmetry.

func (*Float) HashCode

func (p *Float) HashCode() uint64

HashCode returns a hash of the float value. Uses the canonical inexact-family hash so that Float and BigFloat produce identical hashes for equal values. NaN and Inf use bitwise hashing as a fallback since BigFloat has no Inf/NaN, making cross-type equality impossible for those values.

func (*Float) IsExact

func (p *Float) IsExact() bool

IsExact returns false since Float is always inexact.

R7RS §6.2.2: Floating-point numbers are inexact.

func (*Float) IsFinite added in v1.1.0

func (p *Float) IsFinite() bool

IsFinite returns true if this float is finite (not Inf or NaN).

R7RS §6.2.6: finite? returns #t for finite numbers.

func (*Float) IsInteger added in v1.1.0

func (p *Float) IsInteger() bool

IsInteger returns true if this float represents an integer value.

R7RS §6.2.6: integer? returns #t for inexact integers (e.g., 3.0). Uses math.Trunc to correctly handle large floats outside int64 range.

func (*Float) IsNaN added in v1.1.0

func (p *Float) IsNaN() bool

IsNaN returns true if this float is NaN.

R7RS §6.2.6: nan? returns #t for NaN values.

func (*Float) IsNegative added in v1.1.0

func (p *Float) IsNegative() bool

IsNegative returns true if this float is negative.

func (*Float) IsPositive added in v1.1.0

func (p *Float) IsPositive() bool

IsPositive returns true if this float is positive.

func (*Float) IsRational added in v1.1.0

func (p *Float) IsRational() bool

IsRational returns true if this float is finite (not NaN or Inf).

R7RS §6.2.6: rational? returns #t for finite inexact reals.

func (*Float) IsVoid

func (p *Float) IsVoid() bool

IsVoid returns true if the float is nil.

func (*Float) IsZero

func (p *Float) IsZero() bool

IsZero returns true if this float is zero.

func (*Float) LessThan

func (p *Float) LessThan(o Number) bool

LessThan returns true if this float is less than another number.

func (*Float) Multiply

func (p *Float) Multiply(o Number) Number

Multiply returns the product of two numbers.

R7RS §6.2.6: The * procedure returns the product of its arguments. R7RS §6.2.2: Exact zero dominates—(* 0 x) may return exact 0 even when x is inexact. Zero is an exact value when the result is mathematically unambiguous. This implementation follows Chez Scheme's behavior.

func (*Float) Negate

func (p *Float) Negate() Number

Negate returns the negation of this float.

R7RS §6.2.6: The - procedure with one argument returns the additive inverse.

func (*Float) SchemeString

func (p *Float) SchemeString() string

SchemeString returns the Scheme representation of the float.

R7RS §6.2.5: +inf.0, -inf.0, and +nan.0 are the written representations for positive infinity, negative infinity, and NaN. R7RS §7.1.1: Inexact real numbers must contain a decimal point to distinguish them from exact integers.

func (*Float) Sign added in v1.1.0

func (p *Float) Sign() int

Sign returns -1 if negative, 0 if zero, or 1 if positive. NaN returns 0.

func (*Float) String

func (p *Float) String() string

func (*Float) Subtract

func (p *Float) Subtract(o Number) Number

Subtract returns the difference of two numbers.

R7RS §6.2.6: The - procedure returns the difference of its arguments. R7RS §6.2.2 Exactness: inexact - inexact = inexact, exact - inexact = inexact.

func (*Float) ToExact added in v1.1.0

func (p *Float) ToExact() Number

ToExact converts this Float to an exact Number.

R7RS §6.2.6: exact returns an exact representation of its argument. Returns Integer if the float is integral, Rational otherwise.

func (*Float) ToInexact added in v1.1.0

func (p *Float) ToInexact() Number

ToInexact returns this Float unchanged since it is already inexact.

R7RS §6.2.6: inexact returns an inexact representation of its argument.

type ForEachFunc

type ForEachFunc func(ctx context.Context, i int, hasNext bool, v Value) error

ForEachFunc is the callback signature for iterating over a Tuple.

Parameters:

  • ctx: context for cancellation
  • i: zero-based element index
  • hasNext: true if more elements follow
  • v: the current element value

Return a non-nil error to stop iteration early.

type ForeignError

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

ForeignError is an error type for Go primitive implementations (functions foreign to Scheme). It wraps an optional underlying error with a message and captures a stack trace at the point of creation.

func NewForeignErrorf

func NewForeignErrorf(msg string, vs ...any) *ForeignError

NewForeignErrorf creates a new foreign error with a formatted message.

func WrapForeignErrorWithCause added in v1.3.0

func WrapForeignErrorWithCause(sentinel, cause error, msg string, vs ...any) *ForeignError

WrapForeignErrorWithCause wraps a sentinel and a root cause into a single ForeignError. The sentinel is matched by errors.Is for programmatic dispatch; the cause preserves the underlying failure for diagnostics.

func WrapForeignErrorf

func WrapForeignErrorf(err error, msg string, vs ...any) *ForeignError

WrapForeignErrorf wraps an existing error with a formatted message.

func (*ForeignError) As added in v1.3.0

func (p *ForeignError) As(target any) bool

As checks whether the sentinel or cause can be assigned to target.

func (*ForeignError) Cause added in v1.3.0

func (p *ForeignError) Cause() error

Cause returns the root cause error, if any. Useful for debugging/logging when you need the underlying failure directly.

func (*ForeignError) Error

func (p *ForeignError) Error() string

func (*ForeignError) Is added in v1.3.0

func (p *ForeignError) Is(target error) bool

Is reports whether target matches the sentinel or the cause. This replaces Unwrap and gives ForeignError precise two-chain semantics: the sentinel identifies the error category, the cause preserves the root failure from the underlying operation.

type ForeignFileError

type ForeignFileError struct {
	*ForeignError
	Filename string // the file path that caused the error
	Op       string // the operation (e.g., "open-input-file", "delete-file")
}

ForeignFileError represents an error from a file system operation. R7RS §6.11: detected by file-error? predicate.

func WrapForeignFileError

func WrapForeignFileError(err error, op string, filename string) *ForeignFileError

WrapForeignFileError wraps an OS error with file context.

type ForeignReadError

type ForeignReadError struct {
	*ForeignError
}

ForeignReadError represents an error from a read or parse operation. R7RS §6.11: detected by read-error? predicate.

func WrapForeignReadErrorf

func WrapForeignReadErrorf(err error, msg string, vs ...any) *ForeignReadError

WrapForeignReadErrorf wraps an error as a read error.

type Hashable

type Hashable interface {
	Value
	HashCode() uint64
}

Hashable represents a Value that can be used as a hashtable key.

R7RS §6.10: Hashtables map keys to values. Keys are compared using equal?, and the hash function must be consistent with the equality predicate: if a.EqualTo(b) then a.HashCode() == b.HashCode().

Implemented by: Integer, BigInteger, Float, BigFloat, Rational, Boolean, Character, Symbol, Byte, String.

type Hashtable

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

Hashtable represents a Scheme hash table mapping hashable values to values.

Separate chaining (Cormen et al., CLRS Ch. 11): collisions are resolved by storing all entries with the same hash in a linked list (here, a Go slice). O(1) amortized with a good hash function. See BIBLIOGRAPHY.md "Separate Chaining Hash Table".

Keys must implement the Hashable interface (Value + HashCode()). Uses bucket chaining with FNV-1a hashing for O(1) amortized operations and EqualTo() for key comparison within buckets.

func NewEmptyHashtable

func NewEmptyHashtable() *Hashtable

NewEmptyHashtable creates a new empty hash table.

func (*Hashtable) Clear

func (p *Hashtable) Clear()

Clear removes all entries from the hash table.

func (*Hashtable) Copy

func (p *Hashtable) Copy() *Hashtable

Copy returns a shallow copy of the hash table.

func (*Hashtable) Delete

func (p *Hashtable) Delete(key Value) error

Delete removes the entry for key from the hash table. Returns ErrInvalidArgument if the key does not implement Hashable.

func (*Hashtable) Entries added in v1.1.0

func (p *Hashtable) Entries(fn func(key Hashable, value Value) error) error

Entries iterates over all entries in the hash table, calling fn for each key-value pair. Iteration stops early if fn returns a non-nil error. This is more efficient than Keys()+Get() as it avoids intermediate allocations.

func (*Hashtable) EqualTo

func (p *Hashtable) EqualTo(o Value) bool

EqualTo returns true if both hash tables have equal contents. Uses structural equality (EqualTo) for both keys and values.

func (*Hashtable) Get

func (p *Hashtable) Get(key Value) (Value, bool, error)

Get retrieves the value associated with key. Returns the value and whether the key was found. Returns ErrInvalidArgument if the key does not implement Hashable.

func (*Hashtable) HasKey

func (p *Hashtable) HasKey(key Value) (bool, error)

HasKey returns whether the key exists in the hash table. Returns ErrInvalidArgument if the key does not implement Hashable.

func (*Hashtable) IsVoid

func (p *Hashtable) IsVoid() bool

IsVoid returns true if this hash table is nil.

func (*Hashtable) Keys

func (p *Hashtable) Keys() Tuple

Keys returns a list of all keys in the hash table.

func (*Hashtable) SchemeString

func (p *Hashtable) SchemeString() string

SchemeString returns the Scheme representation of this hash table.

func (*Hashtable) Set

func (p *Hashtable) Set(key Value, val Value) error

Set associates key with val in the hash table. Returns ErrInvalidArgument if the key does not implement Hashable.

func (*Hashtable) Size

func (p *Hashtable) Size() int

Size returns the number of entries in the hash table.

func (*Hashtable) Values

func (p *Hashtable) Values() Tuple

Values returns a list of all values in the hash table.

type Indexable

type Indexable interface {
	Value
	Length() int
	Get(int) Value
	Set(int, Value) error
}

Indexable represents a fixed-size, random-access container of values.

R7RS §6.3.6 (vectors), §6.3.7 (strings as character sequences), §6.4 (bytevectors): these types support O(1) element access by integer index.

This interface is used for compile-time documentation and type grouping. No runtime type assertions against Indexable exist in the codebase; dispatch uses concrete types (*Vector, *ByteVector) directly.

Implemented by: Vector, ByteVector.

type InputOutputPort

type InputOutputPort interface {
	InputPort
	OutputPort
}

InputOutputPort represents a bidirectional Scheme port.

type InputPort

type InputPort interface {
	Port
	Read([]byte) (int, error)
}

InputPort represents a Scheme input port.

type Integer

type Integer struct {
	Value int64
}

Integer represents a Scheme integer value.

R7RS §6.2.1: Integers are exact numbers in the numeric tower hierarchy:

number ⊃ complex ⊃ real ⊃ rational ⊃ integer

R7RS §6.2.2: Integer is always exact. Operations on exact numbers produce exact results when mathematically well-defined.

func NewInteger

func NewInteger(v int64) *Integer

NewInteger returns an Integer value. Small integers in the range -32768 to 32767 are cached and return the same pointer for the same value.

func (*Integer) Abs

func (p *Integer) Abs() Number

func (*Integer) Add

func (p *Integer) Add(o Number) Number

Add returns the sum of this integer and another number.

R7RS §6.2.6: The + procedure returns the sum of its arguments. R7RS §6.2.2 Exactness: exact + exact = exact, exact + inexact = inexact. When adding Integer + BigInteger, result is BigInteger (exact). When adding Integer + Float/Complex, result is Float/Complex (inexact).

func (*Integer) Compare

func (p *Integer) Compare(o Number) int

Compare compares this integer with another number.

R7RS §6.2.6: Numeric comparisons use mathematical value regardless of exactness. Returns -1 if p < o, 0 if p == o, 1 if p > o.

func (*Integer) Datum

func (p *Integer) Datum() int64

Datum returns the underlying int64 value.

func (*Integer) Divide

func (p *Integer) Divide(o Number) Number

Divide returns the quotient of this integer and another number.

R7RS §6.2.6: The / procedure returns the quotient of its arguments. For exact arguments, / may return a non-integer (Rational) when the mathematical result is not an integer. Returns Integer only when the division is exact.

R7RS §6.2.2 Exactness: exact / exact = exact (Integer or Rational), exact / inexact = inexact (Float or Complex).

func (*Integer) EqualTo

func (p *Integer) EqualTo(v Value) bool

EqualTo returns true if both integers have the same value.

R7RS §6.2.6: The = procedure compares numerical values for equality. This implements structural equality for the Integer type specifically. Handles comparison with Integer, BigInteger, and Rational types for symmetry.

func (*Integer) HashCode

func (p *Integer) HashCode() uint64

HashCode returns a hash of the integer value. Uses the canonical exact-family hash so that Integer, BigInteger, and Rational produce identical hashes for equal values.

func (*Integer) IsExact

func (p *Integer) IsExact() bool

IsExact returns true since Integer is always exact.

R7RS §6.2.2: Integers are always exact numbers.

func (*Integer) IsFinite added in v1.1.0

func (p *Integer) IsFinite() bool

IsFinite returns true since integers are always finite.

R7RS §6.2.6: finite? returns #t for all exact numbers.

func (*Integer) IsInteger added in v1.1.0

func (p *Integer) IsInteger() bool

IsInteger returns true since Integer is always an integer.

R7RS §6.2.6: integer? returns #t for exact integers.

func (*Integer) IsNaN added in v1.1.0

func (p *Integer) IsNaN() bool

IsNaN returns false since integers are never NaN.

R7RS §6.2.6: nan? returns #f for exact numbers.

func (*Integer) IsNegative added in v1.1.0

func (p *Integer) IsNegative() bool

IsNegative returns true if this integer is negative.

R7RS §6.2.6: negative? returns #t if the real number is negative.

func (*Integer) IsPositive added in v1.1.0

func (p *Integer) IsPositive() bool

IsPositive returns true if this integer is positive.

R7RS §6.2.6: positive? returns #t if the real number is positive.

func (*Integer) IsRational added in v1.1.0

func (p *Integer) IsRational() bool

IsRational returns true since integers are a subset of rationals.

R7RS §6.2.6: rational? returns #t for all real finite numbers.

func (*Integer) IsVoid

func (p *Integer) IsVoid() bool

IsVoid returns true if this integer is nil.

func (*Integer) IsZero

func (p *Integer) IsZero() bool

IsZero returns true if this integer is zero.

func (*Integer) LessThan

func (p *Integer) LessThan(o Number) bool

LessThan returns true if this integer is less than another number.

R7RS §6.2.6: The < procedure returns #t if its arguments are monotonically increasing. Comparison across numeric types uses mathematical value.

func (*Integer) Multiply

func (p *Integer) Multiply(o Number) Number

Multiply returns the product of this integer and another number.

R7RS §6.2.6: The * procedure returns the product of its arguments. R7RS §6.2.2 Exactness: exact * exact = exact, exact * inexact = inexact. Exception: Exact zero dominates—(* 0 x) may return exact 0 even when x is inexact. Zero is an exact value when the result is mathematically unambiguous. This implementation follows Chez Scheme's behavior.

func (*Integer) Negate

func (p *Integer) Negate() Number

Negate returns the negation of this integer.

R7RS §6.2.6: The - procedure with one argument returns the additive inverse.

func (*Integer) SchemeString

func (p *Integer) SchemeString() string

SchemeString returns the Scheme representation of this integer.

func (*Integer) Sign added in v1.1.0

func (p *Integer) Sign() int

Sign returns -1 if negative, 0 if zero, or 1 if positive.

func (*Integer) Subtract

func (p *Integer) Subtract(o Number) Number

Subtract returns the difference of this integer and another number.

R7RS §6.2.6: The - procedure returns the difference of its arguments. R7RS §6.2.2 Exactness: exact - exact = exact, exact - inexact = inexact.

func (*Integer) ToExact added in v1.1.0

func (p *Integer) ToExact() Number

ToExact returns this Integer unchanged since it is already exact.

R7RS §6.2.6: exact returns an exact representation of its argument.

func (*Integer) ToInexact added in v1.1.0

func (p *Integer) ToInexact() Number

ToInexact converts this Integer to an inexact Float.

R7RS §6.2.6: inexact returns an inexact representation of its argument.

type JoinTimeoutException

type JoinTimeoutException struct{}

JoinTimeoutException is raised when thread-join! times out

func (*JoinTimeoutException) Error

func (p *JoinTimeoutException) Error() string

type KeyValue

type KeyValue struct {
	Key   string
	Value Value
}

KeyValue represents a key-value pair.

func NewKeyValue

func NewKeyValue(key string, value Value) *KeyValue

NewKeyValue creates a new key-value pair.

func (*KeyValue) Datum

func (p *KeyValue) Datum() map[string]Value

Datum returns the key-value as a map.

type Mutex

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

Mutex represents a Scheme mutex (SRFI-18)

func NewMutex

func NewMutex(name string) *Mutex

NewMutex creates a new unlocked mutex

func (*Mutex) EqualTo

func (p *Mutex) EqualTo(v Value) bool

EqualTo returns true if the mutexes are the same object.

func (*Mutex) ID

func (p *Mutex) ID() uint64

ID returns the mutex's unique identifier

func (*Mutex) IsVoid

func (p *Mutex) IsVoid() bool

IsVoid returns true if the mutex is nil.

func (*Mutex) Lock

func (p *Mutex) Lock(timeout *time.Duration, owner *Thread) (bool, error)

Lock acquires the mutex with optional timeout and owner Returns true if acquired, false if timeout

func (*Mutex) MarkAbandoned

func (p *Mutex) MarkAbandoned()

MarkAbandoned marks the mutex as abandoned (called when owner thread terminates)

func (*Mutex) Name

func (p *Mutex) Name() string

Name returns the mutex's name

func (*Mutex) Owner

func (p *Mutex) Owner() *Thread

Owner returns the current owner thread, or nil if not owned

func (*Mutex) SchemeString

func (p *Mutex) SchemeString() string

SchemeString returns the Scheme representation of the mutex.

func (*Mutex) SetSpecific

func (p *Mutex) SetSpecific(v Value)

SetSpecific sets the mutex's specific field

func (*Mutex) Specific

func (p *Mutex) Specific() Value

Specific returns the mutex's specific field

func (*Mutex) State

func (p *Mutex) State() MutexState

State returns the current state of the mutex

func (*Mutex) StateValue

func (p *Mutex) StateValue() Value

StateValue returns the state as a Scheme value. Returns package-level singletons for symbol states so that repeated calls return the same pointer: (eq? (mutex-state m) (mutex-state m)) → #t. See the doc comment on SymbolThreadNew in thread.go for eq? vs equal? caveats. Returns: 'not-owned, 'abandoned, or the owner thread.

func (*Mutex) Unlock

func (p *Mutex) Unlock(cv *ConditionVariable, timeout *time.Duration) bool

Unlock releases the mutex If cv is provided, atomically unlock and wait on condition variable

type MutexState

type MutexState int

MutexState represents the state of a mutex

const (
	MutexUnlocked       MutexState = iota // Not locked
	MutexLockedOwned                      // Locked with owner
	MutexLockedNotOwned                   // Locked without owner
	MutexAbandoned                        // Owner terminated while holding lock
)

MutexState constants.

func (MutexState) String

func (p MutexState) String() string

type NativeError

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

NativeError represents an R7RS error object created by (error ...). It contains a message string and a list of irritant objects that provide additional context about the error. It can also wrap a Go error.

func NewErrorObject

func NewErrorObject(message string, irritants ...Value) *NativeError

NewErrorObject creates a new error object with the given message and irritants.

func NewErrorObjectWithCause

func NewErrorObjectWithCause(message string, cause error, irritants ...Value) *NativeError

NewErrorObjectWithCause creates a new error object that wraps a Go error. This preserves the original error for debugging while providing R7RS-compliant exception handling. The wrapped error can be retrieved with Datum() or Unwrap().

func NewErrorObjectWithCauseAndKind

func NewErrorObjectWithCauseAndKind(message string, cause error, kind NativeErrorKind, irritants ...Value) *NativeError

NewErrorObjectWithCauseAndKind creates a new error object that wraps a Go error with a specific kind. R7RS §6.11: The kind determines which error predicate (file-error?, read-error?) matches.

func NewFileError

func NewFileError(message string, irritants ...Value) *NativeError

NewFileError creates a new file error object with the given message and irritants. R7RS §6.11: file-error? predicate checks for errors during file operations.

func NewNativeError

func NewNativeError(msg string) *NativeError

NewNativeError creates a new native error with the given message.

func NewReadError

func NewReadError(message string, irritants ...Value) *NativeError

NewReadError creates a new read error object with the given message and irritants. R7RS §6.11: read-error? predicate checks for errors during reading.

func (*NativeError) Datum

func (p *NativeError) Datum() error

Datum returns the underlying Go error, if any.

func (*NativeError) EqualTo

func (p *NativeError) EqualTo(v Value) bool

EqualTo returns true if this error object is equal to the given value.

func (*NativeError) Error

func (p *NativeError) Error() string

Error implements the error interface.

func (*NativeError) Irritants

func (p *NativeError) Irritants() Value

Irritants returns the list of irritant objects.

func (*NativeError) IsFileError

func (p *NativeError) IsFileError() bool

IsFileError returns true if this is a file error.

func (*NativeError) IsReadError

func (p *NativeError) IsReadError() bool

IsReadError returns true if this is a read error.

func (*NativeError) IsVoid

func (p *NativeError) IsVoid() bool

IsVoid returns true if this error object is nil.

func (*NativeError) Kind

func (p *NativeError) Kind() NativeErrorKind

Kind returns the error kind for R7RS error predicates.

func (*NativeError) Message

func (p *NativeError) Message() *String

Message returns the error message string.

func (*NativeError) SchemeString

func (p *NativeError) SchemeString() string

SchemeString returns the Scheme string representation of this error object.

func (*NativeError) Unwrap

func (p *NativeError) Unwrap() error

Unwrap returns the underlying Go error for errors.Unwrap compatibility.

type NativeErrorKind

type NativeErrorKind int

NativeErrorKind represents the type of an error object for R7RS error predicates.

const (
	// NativeErrorKindGeneric is a generic error (default).
	NativeErrorKindGeneric NativeErrorKind = iota
	// NativeErrorKindRead is a read error (from reading data).
	NativeErrorKindRead
	// NativeErrorKindFile is a file error (from file operations).
	NativeErrorKindFile
)

type Number

type Number interface {
	Value
	Add(Number) Number
	Subtract(Number) Number
	Multiply(Number) Number
	Divide(Number) Number
	Negate() Number
	Abs() Number
	ToExact() Number
	ToInexact() Number
	IsZero() bool
	IsExact() bool
	IsInteger() bool  // R7RS §6.2.6: is this an integer value?
	IsRational() bool // R7RS §6.2.6: is this a rational value?
	IsFinite() bool   // R7RS §6.2.6: is this a finite number?
	IsNaN() bool      // R7RS §6.2.6: is this NaN?
	LessThan(Number) bool
	Compare(Number) int
}

Number represents a numeric value in the Scheme numeric tower.

R7RS §6.2.1: Numbers form a tower: number ⊃ complex ⊃ real ⊃ rational ⊃ integer. All numeric types implement this interface for uniform arithmetic operations.

Error signaling

Arithmetic methods signal errors by panicking with a static sentinel error (e.g., ErrDivisionByZero, ErrNotANumber). This follows the same convention used by Go's math/big package, where (*big.Int).Div, (*big.Int).QuoRem, and (*big.Float).Quo all panic on division by zero, and mirrors Go's own runtime behavior for built-in integer division.

The panic convention is a deliberate design choice: arithmetic methods return Number (not (Number, error)), keeping the interface algebraic and composable. Callers that need error values should recover panics at their boundary. The VM does this in OperationForeignFunctionCall.Apply, which recovers panics and converts them to Scheme exceptions catchable by guard and with-exception-handler.

func Simplify

func Simplify(n Number) Number

Simplify attempts to reduce a number to a simpler type without losing information.

Simplification rules: - BigComplex with zero imaginary → real part - Complex with zero imaginary → Float → possibly Integer - BigFloat that is an integer → BigInteger → possibly Integer - Float that is an integer → Integer - Rational that is an integer → BigInteger → possibly Integer - BigInteger that fits int64 → Integer

type Once

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

Once wraps sync.Once for Scheme

func NewOnce

func NewOnce() *Once

NewOnce creates a new Once

func (*Once) Do

func (p *Once) Do(f func()) bool

Do calls the function only once Returns true if this call executed the function, false if it was already called

func (*Once) Done

func (p *Once) Done() bool

Done returns true if Do has been called

func (*Once) EqualTo

func (p *Once) EqualTo(v Value) bool

EqualTo returns true if the onces are the same object.

func (*Once) ID

func (p *Once) ID() uint64

ID returns the Once's unique identifier

func (*Once) IsVoid

func (p *Once) IsVoid() bool

IsVoid returns true if the once is nil.

func (*Once) SchemeString

func (p *Once) SchemeString() string

SchemeString returns the Scheme representation of the once.

type OutputPort

type OutputPort interface {
	Port
	Write([]byte) (int, error)
	Flush() error
}

OutputPort represents a Scheme output port.

type Pair

type Pair [2]Value

Pair represents a Scheme cons cell.

func NewCons

func NewCons(car, cdr Value) *Pair

NewCons creates a new Pair with the given car and cdr Values.

func (*Pair) Append

func (p *Pair) Append(vs Value) Value

Append appends the given Value vs to the end of the list represented by the Pair. It panics if the Pair does not represent a proper list.

R7RS §6.4: The resulting list is always newly allocated, except that it shares structure with the last argument. This implementation copies the spine of p and sets the last cdr to vs.

func (*Pair) AsVector

func (p *Pair) AsVector() *Vector

AsVector converts the Pair representing a proper list into a Vector. It panics if the Pair does not represent a proper list.

func (*Pair) Car

func (p *Pair) Car() Value

Car returns the car of the Pair.

func (*Pair) Cdr

func (p *Pair) Cdr() Value

Cdr returns the cdr of the Pair.

func (*Pair) Datum

func (p *Pair) Datum() [2]Value

Datum returns the underlying data of the Pair as a [2]buf array.

func (*Pair) EqualTo

func (p *Pair) EqualTo(o Value) bool

EqualTo checks if the Pair is equal to another Value o. Delegates to the cycle-aware pairEqualToDeep to handle circular lists.

func (*Pair) ForEach

func (p *Pair) ForEach(ctx context.Context, fn ForEachFunc) (Value, error)

ForEach iterates over each element in the list represented by the Pair. The provided function fn is called for each element with the index i, a boolean hasNext indicating if there are more elements, and the value v. If fn returns an error, the iteration stops and the error is returned. If the list ends with a non-empty cdr, that cdr is returned as the second return value.

func (*Pair) IsEmptyList

func (p *Pair) IsEmptyList() bool

IsEmptyList returns false. A *Pair is never the empty list; EmptyList is a separate emptyListType value.

func (*Pair) IsList

func (p *Pair) IsList() bool

IsList checks if the Pair represents a proper list. Uses Floyd's cycle detection (tortoise-and-hare) to handle circular lists. Returns false for circular lists per R7RS §6.4. See BIBLIOGRAPHY.md "Floyd's Cycle Detection".

Implementation note: This method must use *Pair (not Tuple) for cycle detection because it requires pointer identity comparison (slow == fast). Interfaces cannot be compared by pointer identity.

func (*Pair) IsVoid

func (p *Pair) IsVoid() bool

IsVoid checks if the Pair is void (nil).

func (*Pair) Length

func (p *Pair) Length() int

Length returns the length of the list represented by the Pair. It panics if the Pair does not represent a proper list.

func (*Pair) SchemeString

func (p *Pair) SchemeString() string

SchemeString returns the Scheme representation of the Pair.

func (*Pair) SetCar

func (p *Pair) SetCar(v Value)

SetCar sets the car of the Pair to the given Value v.

func (*Pair) SetCdr

func (p *Pair) SetCdr(v Value)

SetCdr sets the cdr of the Pair to the given Value v.

func (*Pair) String

func (p *Pair) String() string

String returns the string representation of the Pair.

type Port

type Port interface {
	Value
	Close() error
	IsClosed() bool
}

Port represents a Scheme I/O port.

R7RS §6.13: All port types support close and open-state queries.

type Promise

type Promise struct {
	// Thunk is the procedure to evaluate (nil if already forced)
	Thunk Value
	// Result is the cached result (valid only if Forced is true)
	Result Value
	// Forced indicates whether the promise has been evaluated
	Forced bool
}

Promise represents a delayed computation (R7RS lazy evaluation). A promise contains either an unevaluated thunk or a cached result.

R7RS §4.2.5: The first time a promise is forced, its body is evaluated and the result is memoized; on subsequent forces, the memoized result is returned.

func NewForcedPromise

func NewForcedPromise(value Value) *Promise

NewForcedPromise creates an already-forced promise with the given value. This is used by make-promise when given a non-promise value.

func NewPromise

func NewPromise(thunk Value) *Promise

NewPromise creates a new unforced promise with the given thunk. The thunk should be a procedure that takes no arguments.

func (*Promise) EqualTo

func (p *Promise) EqualTo(v Value) bool

EqualTo returns true if the promises are the same object.

func (*Promise) IsVoid

func (p *Promise) IsVoid() bool

IsVoid returns true if the promise is nil.

func (*Promise) SchemeString

func (p *Promise) SchemeString() string

SchemeString returns the Scheme representation of the promise.

type RWMutex

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

RWMutex wraps sync.RWMutex for Scheme

func NewRWMutex

func NewRWMutex(name string) *RWMutex

NewRWMutex creates a new RWMutex

func (*RWMutex) EqualTo

func (p *RWMutex) EqualTo(v Value) bool

EqualTo returns true if the RWMutexes are the same object.

func (*RWMutex) ID

func (p *RWMutex) ID() uint64

ID returns the RWMutex's unique identifier

func (*RWMutex) IsVoid

func (p *RWMutex) IsVoid() bool

IsVoid returns true if the RWMutex is nil.

func (*RWMutex) Lock

func (p *RWMutex) Lock()

Lock acquires the write lock

func (*RWMutex) Name

func (p *RWMutex) Name() string

Name returns the RWMutex's name

func (*RWMutex) RLock

func (p *RWMutex) RLock()

RLock acquires the read lock

func (*RWMutex) RUnlock

func (p *RWMutex) RUnlock()

RUnlock releases the read lock

func (*RWMutex) SchemeString

func (p *RWMutex) SchemeString() string

SchemeString returns the Scheme representation of the RWMutex.

func (*RWMutex) TryLock

func (p *RWMutex) TryLock() bool

TryLock tries to acquire the write lock without blocking

func (*RWMutex) TryRLock

func (p *RWMutex) TryRLock() bool

TryRLock tries to acquire the read lock without blocking

func (*RWMutex) Unlock

func (p *RWMutex) Unlock()

Unlock releases the write lock

type Rational

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

Rational represents a Scheme rational number (exact fraction).

func NewRational

func NewRational(num, denom int64) *Rational

NewRational creates a new Rational from numerator and denominator. The fraction is automatically normalized (reduced to lowest terms).

func NewRationalFromBigInt

func NewRationalFromBigInt(num, denom *big.Int) *Rational

NewRationalFromBigInt creates a new Rational from big.Int numerator and denominator.

func NewRationalFromRat

func NewRationalFromRat(r *big.Rat) *Rational

NewRationalFromRat creates a Rational from an existing big.Rat.

func (*Rational) Abs added in v1.1.0

func (p *Rational) Abs() Number

Abs returns the absolute value of this rational.

func (*Rational) Add

func (p *Rational) Add(o Number) Number

Add returns the sum of two numbers.

R7RS §6.2.6: The + procedure returns the sum of its arguments. R7RS §6.2.2 Exactness: exact + exact = exact, exact + inexact = inexact.

func (*Rational) Compare

func (p *Rational) Compare(o Number) int

Compare compares this rational with another number.

R7RS §6.2.6: Numeric comparisons use mathematical value regardless of exactness. Returns -1 if p < o, 0 if p == o, 1 if p > o.

func (*Rational) Denom

func (p *Rational) Denom() *big.Int

Denom returns the denominator as a big.Int.

func (*Rational) DenomInt64

func (p *Rational) DenomInt64() int64

DenomInt64 returns the denominator as int64 (may overflow for large values).

func (*Rational) Divide

func (p *Rational) Divide(o Number) Number

Divide returns the quotient of two numbers.

func (*Rational) EqualTo

func (p *Rational) EqualTo(v Value) bool

EqualTo returns true if the rationals have equal values. Handles comparison with Integer and BigInteger for symmetry with whole-valued rationals (e.g., 5/1 == 5).

func (*Rational) Float64

func (p *Rational) Float64() float64

Float64 returns the rational as a float64 approximation.

func (*Rational) HashCode

func (p *Rational) HashCode() uint64

HashCode returns a hash of the rational value. Uses the canonical exact-family hash so that Integer, BigInteger, and Rational produce identical hashes for equal values.

func (*Rational) IsExact

func (p *Rational) IsExact() bool

IsExact returns true since Rational is always exact.

R7RS §6.2.2: Rationals are always exact numbers.

func (*Rational) IsFinite added in v1.1.0

func (p *Rational) IsFinite() bool

IsFinite returns true since exact rationals are always finite.

R7RS §6.2.6: finite? returns #t for all exact numbers.

func (*Rational) IsInteger

func (p *Rational) IsInteger() bool

IsInteger returns true if the rational represents an integer (denominator is 1).

func (*Rational) IsNaN added in v1.1.0

func (p *Rational) IsNaN() bool

IsNaN returns false since exact rationals are never NaN.

R7RS §6.2.6: nan? returns #f for exact numbers.

func (*Rational) IsNegative added in v1.1.0

func (p *Rational) IsNegative() bool

IsNegative returns true if this rational is negative.

func (*Rational) IsPositive added in v1.1.0

func (p *Rational) IsPositive() bool

IsPositive returns true if this rational is positive.

func (*Rational) IsRational added in v1.1.0

func (p *Rational) IsRational() bool

IsRational returns true since Rational is always a rational number.

R7RS §6.2.6: rational? returns #t for exact rationals.

func (*Rational) IsVoid

func (p *Rational) IsVoid() bool

IsVoid returns true if the rational is nil.

func (*Rational) IsZero

func (p *Rational) IsZero() bool

IsZero returns true if the rational equals zero.

func (*Rational) LessThan

func (p *Rational) LessThan(o Number) bool

LessThan returns true if this rational is less than another number.

func (*Rational) Multiply

func (p *Rational) Multiply(o Number) Number

Multiply returns the product of two numbers.

func (*Rational) Negate

func (p *Rational) Negate() Number

Negate returns the negation of this rational.

R7RS §6.2.6: The - procedure with one argument returns the additive inverse.

func (*Rational) Num

func (p *Rational) Num() *big.Int

Num returns the numerator as a big.Int.

func (*Rational) NumInt64

func (p *Rational) NumInt64() int64

NumInt64 returns the numerator as int64 (may overflow for large values).

func (*Rational) Rat

func (p *Rational) Rat() *big.Rat

Rat returns the underlying big.Rat value.

func (*Rational) SchemeString

func (p *Rational) SchemeString() string

SchemeString returns the Scheme representation of the rational.

func (*Rational) Sign added in v1.1.0

func (p *Rational) Sign() int

Sign returns -1 if negative, 0 if zero, or 1 if positive.

func (*Rational) Subtract

func (p *Rational) Subtract(o Number) Number

Subtract returns the difference of two numbers.

R7RS §6.2.6: The - procedure returns the difference of its arguments. R7RS §6.2.2 Exactness: exact - exact = exact, exact - inexact = inexact.

func (*Rational) ToExact added in v1.1.0

func (p *Rational) ToExact() Number

ToExact returns this Rational unchanged since it is already exact.

R7RS §6.2.6: exact returns an exact representation of its argument.

func (*Rational) ToInexact added in v1.1.0

func (p *Rational) ToInexact() Number

ToInexact converts this Rational to an inexact BigFloat.

R7RS §6.2.6: inexact returns an inexact representation of its argument. L18: Use big.Float.SetRat to preserve precision for large rationals.

type RealNumber added in v1.1.0

type RealNumber interface {
	Number
	IsPositive() bool
	IsNegative() bool
	Sign() int
}

RealNumber represents a real-valued number with sign operations.

R7RS §6.2.6: The positive? and negative? predicates apply only to real numbers. Sign returns -1, 0, or 1.

type Record

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

Record represents a record instance as defined by R7RS define-record-type. Each record has a type descriptor and a slice of field values.

func NewRecord

func NewRecord(rt *RecordType, fields []Value) *Record

NewRecord creates a new Record with the given type and field values. The fields slice should have the same length as the record type's field count.

func (*Record) EqualTo

func (p *Record) EqualTo(v Value) bool

EqualTo implements structural equality for records. Two records are equal if they have the same type and all fields are equal.

func (*Record) Field

func (p *Record) Field(index int) Value

Field returns the value at the given field index.

func (*Record) FieldByName

func (p *Record) FieldByName(name *Symbol) Value

FieldByName returns the value of the field with the given name. Returns nil if the field is not found.

func (*Record) IsVoid

func (p *Record) IsVoid() bool

IsVoid returns true if the record is nil.

func (*Record) RecordType

func (p *Record) RecordType() *RecordType

RecordType returns the record's type descriptor.

func (*Record) SchemeString

func (p *Record) SchemeString() string

SchemeString returns the Scheme external representation of the record.

func (*Record) SetField

func (p *Record) SetField(index int, value Value)

SetField sets the value at the given field index.

func (*Record) SetFieldByName

func (p *Record) SetFieldByName(name *Symbol, value Value)

SetFieldByName sets the value of the field with the given name. Does nothing if the field is not found.

type RecordType

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

RecordType represents a record type descriptor as defined by R7RS define-record-type. It holds the type name and the ordered list of field names.

func NewRecordType

func NewRecordType(name *Symbol, fieldNames []*Symbol) *RecordType

NewRecordType creates a new RecordType with the given name and field names.

func (*RecordType) EqualTo

func (p *RecordType) EqualTo(v Value) bool

EqualTo implements identity-based equality for record types. Two record types are equal only if they are the same object.

func (*RecordType) FieldCount

func (p *RecordType) FieldCount() int

FieldCount returns the number of fields in this record type.

func (*RecordType) FieldIndex

func (p *RecordType) FieldIndex(name *Symbol) int

FieldIndex returns the index of the field with the given name, or -1 if not found.

func (*RecordType) FieldNames

func (p *RecordType) FieldNames() []*Symbol

FieldNames returns the ordered list of field name symbols.

func (*RecordType) IsVoid

func (p *RecordType) IsVoid() bool

IsVoid returns true if the record type is nil.

func (*RecordType) Name

func (p *RecordType) Name() *Symbol

Name returns the record type's name symbol.

func (*RecordType) SchemeString

func (p *RecordType) SchemeString() string

SchemeString returns the Scheme external representation of the record type.

type SchemeWriter

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

SchemeWriter provides cycle-aware writing of Scheme values. Two-pass datum label output (R7RS §2.4): pass 1 (findShared) traverses the value graph to identify multiply-referenced objects; pass 2 (write) emits #n= definitions on first encounter and #n# references thereafter. See BIBLIOGRAPHY.md "Two-Pass Datum Label Output".

Implementation note: Uses maps with concrete *Pair and *Vector keys (not Tuple/Indexable interfaces) because: 1. Go map keys must be comparable types - interfaces are not suitable 2. Cycle/sharing detection requires pointer identity tracking 3. Each concrete type needs separate tracking for proper label assignment

func NewSchemeWriter

func NewSchemeWriter() *SchemeWriter

NewSchemeWriter creates a new SchemeWriter for cycle-aware output. Default mode is WriteModeWrite (labels only circular references).

func (*SchemeWriter) WriteString

func (p *SchemeWriter) WriteString(v Value) string

WriteString writes a Scheme value to a string with cycle detection. Circular and shared structures are represented using datum labels.

type SelectCase

type SelectCase struct {
	Channel   *Channel
	Value     Value // for send operations
	IsSend    bool
	IsDefault bool
}

SelectCase represents a case in a channel select operation

type SourceLocation

type SourceLocation interface {
	Value
	Index() int
	Column() int
	Line() int
}

SourceLocation represents a position in source code.

type StaticError

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

StaticError is a sentinel error type for programmatic matching via errors.Is. Each sentinel carries a fixed human-readable message and serves as a stable identity that callers can match across error wrapping layers.

func NewStaticError

func NewStaticError(msg string) *StaticError

NewStaticError creates a new static error with the given message.

func (*StaticError) Error

func (p *StaticError) Error() string

type String

type String struct {
	Value string
	// contains filtered or unexported fields
}

String represents a Scheme string value. R7RS §6.7: Literal strings and strings from symbol->string are immutable.

func InternString

func InternString(str string) *String

InternString returns an interned String for the given value. Multiple calls with the same string value return the same pointer. Interned strings are immutable per R7RS §6.7.

func NewMutableString

func NewMutableString(str string) *String

NewMutableString returns a newly allocated String that is not interned. Use this for strings that may be mutated (e.g., via string-set! or string-fill!). R7RS §6.7: Procedures like string-copy return mutable strings.

func NewString

func NewString(str string) *String

NewString returns an immutable String value. Short strings (up to 64 bytes) are automatically interned and return the same pointer for the same value. R7RS §6.7: Literal strings and strings from symbol->string are immutable. Use NewMutableString for runtime-allocated strings that may be mutated.

func (*String) Datum

func (p *String) Datum() string

Datum returns the underlying string value.

func (*String) EqualTo

func (p *String) EqualTo(v Value) bool

EqualTo returns true if the strings have equal values.

func (*String) Fill

func (p *String) Fill(char rune, start, end int) error

Fill fills the string (or a portion of it) with the given character. Returns an error if the string is immutable. R7RS §6.7: (string-fill! string fill [start [end]])

func (*String) Get added in v1.1.0

func (p *String) Get(i int) Value

Get returns the character at the given rune index as a Character value.

R7RS §6.7: (string-ref string k) returns character k of string.

func (*String) HashCode

func (p *String) HashCode() uint64

HashCode returns a hash of the string value.

func (*String) IsImmutable added in v1.3.0

func (p *String) IsImmutable() bool

IsImmutable returns true if the string cannot be mutated. Interned strings and strings returned by symbol->string are immutable. R7RS §6.7: It is an error to apply mutation procedures to literal strings or strings returned by symbol->string.

func (*String) IsVoid

func (p *String) IsVoid() bool

IsVoid returns true if the string is nil.

func (*String) Len

func (p *String) Len() int

Len returns the length of the string in characters (runes).

func (*String) Length added in v1.1.0

func (p *String) Length() int

Length returns the length of the string in characters (runes).

R7RS §6.7: (string-length string) returns the number of characters.

func (*String) Runes

func (p *String) Runes() []rune

Runes returns the string as a slice of runes.

func (*String) SchemeString

func (p *String) SchemeString() string

SchemeString returns the Scheme representation of the string.

func (*String) Set added in v1.1.0

func (p *String) Set(i int, v Value) error

Set sets the character at the given rune index from a Character value. Returns an error if the string is immutable.

R7RS §6.7: (string-set! string k char) stores char in element k.

func (*String) SetChar

func (p *String) SetChar(k int, char rune) error

SetChar sets the character at index k to the given rune. Returns an error if the string is immutable.

R7RS §6.7: (string-set! string k char) R7RS §6.7: "It is an error" to mutate literal strings or strings returned by symbol->string. This implementation signals an error when mutation is attempted on immutable strings.

func (*String) SetValue

func (p *String) SetValue(s string) error

SetValue sets the entire string value. Returns an error if the string is immutable.

func (*String) String

func (p *String) String() string

type StringInputPort

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

StringInputPort represents a Scheme string output port backed by a buffer.

func NewStringInputPort

func NewStringInputPort() *StringInputPort

NewStringInputPort creates a new string output port.

func NewStringInputPortWithBuffer

func NewStringInputPortWithBuffer(buffer *bytes.Buffer) *StringInputPort

NewStringInputPortWithBuffer creates a new string output port.

func (*StringInputPort) Close

func (b *StringInputPort) Close() error

Close marks the port as closed and, if a closer was provided, closes the underlying stream. Close is idempotent.

func (*StringInputPort) Datum

func (p *StringInputPort) Datum() *bytes.Buffer

Datum returns the underlying buffer.

func (*StringInputPort) EqualTo

func (p *StringInputPort) EqualTo(v Value) bool

EqualTo returns true if both ports use the same buffer.

func (*StringInputPort) Flush

func (p *StringInputPort) Flush() error

func (*StringInputPort) IsClosed

func (b *StringInputPort) IsClosed() bool

IsClosed returns true if the port has been closed.

func (*StringInputPort) IsVoid

func (p *StringInputPort) IsVoid() bool

IsVoid returns true if the port is nil.

func (*StringInputPort) Read

func (p *StringInputPort) Read(bs []byte) (int, error)

Read reads data from the port into bs.

func (*StringInputPort) ReadRune

func (p *StringInputPort) ReadRune() (rune, int, error)

ReadRune reads a rune from the port.

func (*StringInputPort) SchemeString

func (p *StringInputPort) SchemeString() string

SchemeString returns the Scheme representation of the port.

func (*StringInputPort) String

func (p *StringInputPort) String() string

func (*StringInputPort) UnreadRune

func (p *StringInputPort) UnreadRune() error

UnreadRune unreads the last rune read from the port.

type StringOutputPort

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

StringOutputPort represents a Scheme string output port backed by a buffer.

func NewStringOutputPort

func NewStringOutputPort() *StringOutputPort

NewStringOutputPort creates a new string output port.

func NewStringOutputPortWithBuffer

func NewStringOutputPortWithBuffer(buffer *bytes.Buffer) *StringOutputPort

NewStringOutputPortWithBuffer creates a new string output port.

func (*StringOutputPort) Close

func (b *StringOutputPort) Close() error

Close marks the port as closed and, if a closer was provided, closes the underlying stream. Close is idempotent.

func (*StringOutputPort) Datum

func (p *StringOutputPort) Datum() *bytes.Buffer

Datum returns the underlying buffer.

func (*StringOutputPort) EqualTo

func (p *StringOutputPort) EqualTo(v Value) bool

EqualTo returns true if both ports use the same buffer.

func (*StringOutputPort) Flush

func (p *StringOutputPort) Flush() error

Flush is a no-op for StringOutputPort.

func (*StringOutputPort) IsClosed

func (b *StringOutputPort) IsClosed() bool

IsClosed returns true if the port has been closed.

func (*StringOutputPort) IsVoid

func (p *StringOutputPort) IsVoid() bool

IsVoid returns true if the port is nil.

func (*StringOutputPort) SchemeString

func (p *StringOutputPort) SchemeString() string

SchemeString returns the Scheme representation of the port.

func (*StringOutputPort) String

func (p *StringOutputPort) String() string

func (*StringOutputPort) Write

func (p *StringOutputPort) Write(bs []byte) (int, error)

Write writes data to the port.

func (*StringOutputPort) WriteRune

func (p *StringOutputPort) WriteRune(rn rune) (int, error)

WriteRune writes a single rune to the port's buffer.

func (*StringOutputPort) WriteString

func (p *StringOutputPort) WriteString(s string) (int, error)

WriteString writes a string to the port.

type Symbol

type Symbol struct {
	Key string
}

Symbol represents a Scheme symbol.

func NewSymbol

func NewSymbol(key string) *Symbol

NewSymbol creates a new symbol with the given key.

func NewTemporaryVariableName

func NewTemporaryVariableName() *Symbol

NewTemporaryVariableName generates a unique symbol for use as a temporary variable. The symbol name has the format "__T_<base32-encoded-random-bytes>". Uses 128 bits of cryptographic randomness to ensure uniqueness. Thread-safe: uses crypto/rand which is safe for concurrent use. Panics if random number generation fails.

func (*Symbol) Copy

func (p *Symbol) Copy() Value

Copy returns a copy of the symbol.

func (*Symbol) Datum

func (p *Symbol) Datum() string

Datum returns the symbol's key string.

func (*Symbol) EqualTo

func (p *Symbol) EqualTo(v Value) bool

EqualTo returns true if the symbols have equal keys.

func (*Symbol) HashCode

func (p *Symbol) HashCode() uint64

HashCode returns a hash of the symbol's key.

func (*Symbol) IsVoid

func (p *Symbol) IsVoid() bool

IsVoid returns true if the symbol is nil.

func (*Symbol) SchemeString

func (p *Symbol) SchemeString() string

SchemeString returns the R7RS external representation of the symbol.

R7RS §7.1.1: Identifiers that can be represented without bars are written bare. Otherwise, they are enclosed in vertical bars with only \ and | characters escaped.

type TerminatedThreadException

type TerminatedThreadException struct {
	Thread *Thread
}

TerminatedThreadException is raised when joining a terminated thread

func (*TerminatedThreadException) Error

func (p *TerminatedThreadException) Error() string

type TextualReader

type TextualReader interface {
	InputPort
	ReadRune() (rune, int, error)
	UnreadRune() error
}

TextualReader represents a textual input port capable of rune-level I/O.

R7RS §6.13.2: Textual input ports support read-char, peek-char, read-line, etc.

type TextualWriter

type TextualWriter interface {
	OutputPort
	WriteRune(rune) (int, error)
}

TextualWriter represents a textual output port capable of rune-level I/O.

R7RS §6.13.3: Textual output ports support write-char, write-string, etc.

type Thread

type Thread struct {

	// RunFunc is set by the machine package to actually run the thread
	// This avoids circular dependency between values and machine
	RunFunc func(ctx context.Context, thunk Value) (Value, error)

	// CleanupFunc is injected by the machine package to run dynamic-wind
	// after thunks (UnwindTo(0)) on thread exit. Called on both normal exit
	// and forced termination.
	CleanupFunc func()
	// contains filtered or unexported fields
}

Thread represents a Scheme thread (SRFI-18)

func NewThread

func NewThread(thunk Value, name string) *Thread

NewThread creates a new thread that will execute the given thunk

func (*Thread) AbandonOwnedMutexes added in v1.1.0

func (p *Thread) AbandonOwnedMutexes()

AbandonOwnedMutexes marks all mutexes owned by this thread as abandoned. Called during thread termination to ensure waiting threads are notified.

func (*Thread) Done

func (p *Thread) Done() <-chan struct{}

Done returns a channel that's closed when the thread terminates

func (*Thread) EqualTo

func (p *Thread) EqualTo(v Value) bool

EqualTo returns true if both threads are the same object.

func (*Thread) ID

func (p *Thread) ID() uint64

ID returns the thread's unique identifier

func (*Thread) IsVoid

func (p *Thread) IsVoid() bool

IsVoid returns true if this thread is nil.

func (*Thread) Join

func (p *Thread) Join(timeout *time.Duration) (Value, error)

Join waits for the thread to terminate with optional timeout Returns the thread's result or an error

func (*Thread) Name

func (p *Thread) Name() string

Name returns the thread's name

func (*Thread) SchemeString

func (p *Thread) SchemeString() string

SchemeString returns the Scheme representation of this thread.

func (*Thread) SetSpecific

func (p *Thread) SetSpecific(v Value)

SetSpecific sets the thread's specific field

func (*Thread) Sleep

func (p *Thread) Sleep(d time.Duration)

Sleep pauses the thread for the given duration

func (*Thread) Specific

func (p *Thread) Specific() Value

Specific returns the thread's specific field (thread-local storage)

func (*Thread) Start

func (p *Thread) Start(parentCtx context.Context) error

Start begins execution of the thread. The parentCtx is used as the parent for the thread's cancellable context, enabling cancellation propagation from the engine/caller while allowing independent termination via thread-terminate!.

func (*Thread) State

func (p *Thread) State() ThreadState

State returns the current state of the thread

func (*Thread) StateSymbol

func (p *Thread) StateSymbol() *Symbol

StateSymbol returns the state as a Scheme symbol. Returns package-level singletons so that repeated calls return the same pointer: (eq? (thread-state t) (thread-state t)) → #t. See the doc comment on SymbolThreadNew for eq? vs equal? caveats.

func (*Thread) Terminate

func (p *Thread) Terminate()

Terminate forcefully terminates the thread. Marks all owned mutexes as abandoned and cancels the thread's context. The deferred cleanup in the goroutine (dynamic-wind after thunks) will fire when the goroutine exits. However, AbandonOwnedMutexes is also called here directly because the goroutine may be blocked on a Go-level operation (e.g., sync.Cond.Wait) and won't exit immediately on context cancellation.

func (*Thread) TrackMutex added in v1.1.0

func (p *Thread) TrackMutex(m *Mutex)

TrackMutex adds a mutex to this thread's ownership tracking set. Called by mutex-lock! when a mutex is acquired with this thread as owner.

func (*Thread) UntrackMutex added in v1.1.0

func (p *Thread) UntrackMutex(m *Mutex)

UntrackMutex removes a mutex from this thread's ownership tracking set. Called by mutex-unlock! when a mutex is released.

func (*Thread) Yield

func (p *Thread) Yield()

Yield yields execution to other threads

type ThreadState

type ThreadState int

ThreadState represents the state of a thread

const (
	ThreadNew        ThreadState = iota // Created but not started
	ThreadRunnable                      // Running or ready to run
	ThreadBlocked                       // Waiting for mutex/cv/sleep
	ThreadTerminated                    // Finished execution
)

ThreadState constants.

func (ThreadState) String

func (p ThreadState) String() string

type Time

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

Time represents a point in time (SRFI-18)

func CurrentTime

func CurrentTime() *Time

CurrentTime returns the current time

func NewTime

func NewTime(t time.Time) *Time

NewTime creates a new Time from a Go time.Time

func NewTimeFromSeconds

func NewTimeFromSeconds(seconds float64) *Time

NewTimeFromSeconds creates a Time from seconds since epoch

func (*Time) Add

func (p *Time) Add(d time.Duration) *Time

Add returns a new Time that is the given duration after this time

func (*Time) After

func (p *Time) After(other *Time) bool

After returns true if this time is after another

func (*Time) Before

func (p *Time) Before(other *Time) bool

Before returns true if this time is before another

func (*Time) DurationFromNow

func (p *Time) DurationFromNow() time.Duration

DurationFromNow returns the duration from now until this time.

func (*Time) EqualTo

func (p *Time) EqualTo(v Value) bool

EqualTo returns true if both times represent the same instant.

func (*Time) GoTime

func (p *Time) GoTime() time.Time

GoTime returns the underlying Go time.Time

func (*Time) IsVoid

func (p *Time) IsVoid() bool

IsVoid returns true if the time is nil.

func (*Time) SchemeString

func (p *Time) SchemeString() string

SchemeString returns the Scheme representation of the time.

func (*Time) Seconds

func (p *Time) Seconds() float64

Seconds returns the time as seconds since the epoch

func (*Time) Sub

func (p *Time) Sub(other *Time) time.Duration

Sub returns the duration between this time and another

type Tuple

type Tuple interface {
	Value
	// Car returns the first element of the pair (R7RS §6.4).
	Car() Value
	// Cdr returns the rest of the list after the first element (R7RS §6.4).
	Cdr() Value
	// ForEach calls fn for each element in order. Returns the tail value
	// (EmptyList for proper lists, the improper cdr otherwise).
	ForEach(ctx context.Context, fn ForEachFunc) (Value, error)
	// Length returns the number of elements. For improper lists, this
	// counts only the proper prefix.
	Length() int
	// Append creates a new list with value appended (R7RS §6.4 append).
	Append(value Value) Value
	// AsVector converts the list to a Vector (R7RS §6.4 list->vector).
	AsVector() *Vector
	// IsList reports whether this is a proper list (R7RS §6.4 list?).
	// Uses Floyd's cycle detection (tortoise-and-hare).
	IsList() bool
	// IsEmptyList reports whether this is the empty list (R7RS §6.4 null?).
	IsEmptyList() bool
	// IsVoid reports whether this value is void (nil receiver handling).
	IsVoid() bool
}

Tuple represents the Scheme list protocol — any value that can be consumed as a sequence of car/cdr pairs.

R7RS §6.4: Lists are chains of pairs terminated by the empty list. Tuple captures the operations needed to traverse, measure, and convert list-shaped values without requiring a concrete *Pair type.

Implemented by: Pair, ArrayList, emptyListType (EmptyList singleton).

IsVoid is listed explicitly because Pair uses a nil-receiver convention where (*Pair)(nil) represents void, and the method must be dispatched through the interface to handle that case.

var (

	// EmptyList is the singleton empty list ().
	// It implements Tuple but is not *Pair, enforcing (pair? '()) -> #f
	// at the type level per R7RS 6.4.
	EmptyList Tuple = emptyListType{}
)

func List

func List(os ...Value) Tuple

List constructs a proper list from the given values. Returns EmptyList if no arguments are provided. The resulting list has the values in the same order as the arguments.

Implementation note: Returns Tuple interface but constructs *Pair internally. Type assertion to *Pair is required during construction for efficient iterative building of the linked structure. Callers receive the Tuple interface.

func VectorToList

func VectorToList(vs *Vector) Tuple

VectorToList converts a Vector to a proper list preserving element order. Iterates backward through the vector, prepending each element to build the list. Returns EmptyList for nil or void vectors.

type UncaughtThreadException

type UncaughtThreadException struct {
	Reason error
}

UncaughtThreadException wraps an exception that wasn't caught in a thread

func (*UncaughtThreadException) Error

func (p *UncaughtThreadException) Error() string

func (*UncaughtThreadException) Unwrap

func (p *UncaughtThreadException) Unwrap() error

type Value

type Value interface {
	SchemeString() string
	IsVoid() bool
	EqualTo(Value) bool
}

Value is the base interface for all Scheme values.

Every runtime object in Wile implements Value. The three methods correspond to fundamental Scheme operations:

  • SchemeString returns the external representation (R7RS §13.2 write).
  • IsVoid reports whether this value represents the absence of a result (e.g., the return value of set! or display). A nil receiver must return true so that missing values are treated as void.
  • EqualTo implements structural equality (R7RS §6.1 equal?).
var EOFObject Value = eofType{}

EOFObject is the singleton EOF value.

var Void Value = voidType{}

Void is the singleton void value.

func ChannelSelect

func ChannelSelect(cases []SelectCase) (idx int, val Value, ok bool)

ChannelSelect performs a select operation on multiple channels. Returns the index of the selected case and the received value (for receive cases). If a send case targets a channel that is closed concurrently, the select returns that case's index with ok=false instead of panicking.

func ForEach

func ForEach(ctx context.Context, o Value, fn ForEachFunc) (Value, error)

ForEach iterates over a Tuple value, calling fn for each element. If the value is not a Tuple, returns the value unchanged with no error. The callback receives the element index, whether more elements follow, and the element value. Returns the tail of the tuple (EmptyList for proper lists) and any error from the callback.

type Vector

type Vector []Value

Vector represents an R7RS vector, a fixed-size mutable array of values. Vectors are written as #(element ...) in Scheme syntax. Unlike lists, vectors provide O(1) access to elements by index.

func NewVector

func NewVector(vs ...Value) *Vector

NewVector creates a new Vector from the given values. Returns an empty vector if no arguments are provided.

func NewVectorWithLength

func NewVectorWithLength(length int) *Vector

NewVectorWithLength creates a new Vector of the given length, with all elements initialized to the specified fill value.

func (*Vector) AsList

func (p *Vector) AsList() Tuple

AsList converts the vector to a proper list (linked list of pairs). Returns void (nil Pair) if the vector is void. Returns EmptyList if the vector is empty. Otherwise returns a newly constructed list containing the vector's elements.

func (*Vector) Datum

func (p *Vector) Datum() []Value

Datum returns the underlying slice of values. Returns nil if the vector is void (nil pointer).

func (*Vector) EqualTo

func (p *Vector) EqualTo(v Value) bool

EqualTo implements structural equality for vectors. Two vectors are equal if they have the same length and all corresponding elements are equal (using recursive EqualTo comparison). Returns false if the other value is not a Vector.

func (*Vector) Get

func (p *Vector) Get(i int) Value

Get returns the element at the specified index.

func (*Vector) IsVoid

func (p *Vector) IsVoid() bool

IsVoid returns true if the vector is a nil pointer. A nil vector represents the absence of a value, distinct from an empty vector.

func (*Vector) Length

func (p *Vector) Length() int

Length returns the number of elements in the vector. Returns 0 if the vector is void (nil pointer).

func (*Vector) SchemeString

func (p *Vector) SchemeString() string

SchemeString returns the Scheme external representation of the vector. Format: #( element1 element2 ... ) with elements separated by spaces. Empty vectors are represented as #().

func (*Vector) Set

func (p *Vector) Set(i int, value Value) error

Set sets the element at the specified index to the given value. Vectors are always mutable, so this never returns an error.

type WaitGroup

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

WaitGroup wraps sync.WaitGroup for Scheme

func NewWaitGroup

func NewWaitGroup() *WaitGroup

NewWaitGroup creates a new WaitGroup

func (*WaitGroup) Add

func (p *WaitGroup) Add(delta int)

Add adds delta to the counter

func (*WaitGroup) Done

func (p *WaitGroup) Done()

Done decrements the counter by one

func (*WaitGroup) EqualTo

func (p *WaitGroup) EqualTo(v Value) bool

EqualTo returns true if the wait groups are the same object.

func (*WaitGroup) ID

func (p *WaitGroup) ID() uint64

ID returns the WaitGroup's unique identifier

func (*WaitGroup) IsVoid

func (p *WaitGroup) IsVoid() bool

IsVoid returns true if the wait group is nil.

func (*WaitGroup) SchemeString

func (p *WaitGroup) SchemeString() string

SchemeString returns the Scheme representation of the wait group.

func (*WaitGroup) Wait

func (p *WaitGroup) Wait()

Wait blocks until the counter is zero

type WriteMode

type WriteMode int

WriteMode controls how the SchemeWriter handles shared structure.

R7RS §6.13.3 specifies three output procedures with different sharing semantics:

  • write: datum labels only for circular references (WriteModeWrite)
  • write-shared: datum labels for all shared references (WriteModeWriteShared)
  • write-simple: no datum labels at all (handled separately via SchemeString)
const (
	// WriteModeWrite labels only circular references.
	// R7RS §6.13.3: write outputs datum labels only for objects that are part of a cycle.
	WriteModeWrite WriteMode = iota
	// WriteModeWriteShared labels all multiply-referenced objects.
	// R7RS §6.13.3: write-shared outputs datum labels for all shared structure.
	WriteModeWriteShared
)

Directories

Path Synopsis
Package valuestest provides test helpers for the values package.
Package valuestest provides test helpers for the values package.

Jump to

Keyboard shortcuts

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