eval

package
v0.0.0-...-4ed6c96 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2026 License: MIT Imports: 46 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CallerUser      = "user"
	CallerAssistant = "assistant"
)

Caller identities for SetCaller/RequireUser.

Variables

View Source
var ErrInterrupted = errors.New("interrupted")

ErrInterrupted is returned by Eval when the user presses ctrl+c while a form is running (the shell's SIGINT handler calls Interrupt). Callers treat it like bash treats ^C: abandon the command, keep the shell.

View Source
var ErrStreamConsumed = errors.New("stream already consumed — re-run the producer, or use the materialized result (*1)")

ErrStreamConsumed is returned by Next on a stream that already ended or was closed. Materialize a stream (assign the printed result, *1) to reuse its values.

Functions

func AsString

func AsString(v Value) (string, bool, error)

AsString returns string content: a String as-is, a line stream drained and rejoined (each line newline-terminated, matching a text file's shape). Row streams and non-strings return ok=false.

func BuiltinDoc

func BuiltinDoc(name string) string

BuiltinDoc returns a builtin's registered one-line documentation, or "" when the name is unregistered (or undocumented).

func ClearInterrupt

func ClearInterrupt()

ClearInterrupt re-arms evaluation after an interrupt has been handled; the shell calls it before dispatching each new line.

func CommandHelp

func CommandHelp(name string) (string, bool)

CommandHelp returns the text `help name` (and `name -h`) prints; ok=false for unregistered names. Exported for the handbook generator, which shares this renderer so generated docs cannot drift from -h.

func CommandWords

func CommandWords() []string

CommandWords returns the names registered as standalone command words, unsorted — the shell's tab completer merges candidate sets and sorts.

func DefaultGraph

func DefaultGraph() (*core.Graph, error)

DefaultGraph resolves the default graph (the default-graph binding, else the stock name) for callers outside eval that write registry-style nodes. Created lazily on first use.

func FindProject

func FindProject(dir string) (name, hub string, ok bool)

FindProject reports the project containing dir.

func FlagUsage

func FlagUsage(o Option) string

FlagUsage is the exported flagSpelling — one option's "-d, --dir PATH" column, for the man pages' OPTIONS section.

func FormatTable

func FormatTable(v Value) (string, bool)

FormatTable renders a list of dictionaries (or a single dictionary) as an aligned text table. Returns ok=false when the value has no tabular shape.

func FormatTableColor

func FormatTableColor(v Value) (string, bool)

FormatTableColor is FormatTable with ANSI styling for interactive display: bold headers and file names tinted by type. The plain variant remains for values that flow back into Scheme (the `table` builtin) and for tests.

func FormatTableColorWidth

func FormatTableColorWidth(v Value, width int) (string, bool)

FormatTableColorWidth is FormatTableWidth with ANSI styling — what the shell uses, passing the terminal width.

func FormatTableWidth

func FormatTableWidth(v Value, width int) (string, bool)

FormatTableWidth is FormatTable fitted to a display-width budget: the widest columns shrink and their cells wrap across continuation lines. A budget of 0 means unlimited.

func Interrupt

func Interrupt()

Interrupt requests that any running evaluation stop: the eval loop (and long-blocking builtins like sleep) poll the flag and return ErrInterrupted.

func InterruptContext

func InterruptContext(parent context.Context) (context.Context, context.CancelFunc)

InterruptContext derives a context that cancels when a pending interrupt is observed (polled every interruptPoll), so context-taking blocking calls abort on ^C. The returned stop releases the poller.

func Interrupted

func Interrupted() bool

Interrupted reports whether an interrupt is pending.

func IsUserFunction

func IsUserFunction(v Value) bool

IsUserFunction reports whether a value is a user-defined function (a closure from define/lambda), as opposed to a Go-registered builtin.

func NoteNames

func NoteNames() []string

NoteNames returns the completion source for `note <tab>`: every note's slug, sorted.

func OptBool

func OptBool(opts map[string]Value, long string) bool

func OptInt

func OptInt(opts map[string]Value, long string, def int) int

func OptNumber

func OptNumber(opts map[string]Value, long string, def float64) float64

func OptString

func OptString(opts map[string]Value, long, def string) string

OptString, OptInt, OptNumber, OptBool read one parsed option with a default — the builtin side of ParseOptions' map.

func ParseAt

func ParseAt(command, raw string, now time.Time) (time.Time, error)

ParseAt resolves --at's raw text against now: "HH:MM" is the next such clock time, "YYYY-MM-DD HH:MM" (or T-joined) an absolute local time, "YYYY- MM-DD" that day's midnight. A past time errors.

func ParseSpan

func ParseSpan(command, flag, raw string) (time.Duration, error)

ParseSpan reads a schedule span: Go durations ("30s", "10m", "1h30m") plus day/week units ("1d", "2w") and the bare unit words minute, hour, day, week — `--every day` reads as English.

func PrintValue

func PrintValue(v Value) string

PrintValue prints a Value in Scheme style

func PrintValueCapped

func PrintValueCapped(v Value, capBytes int) (string, error)

PrintValueCapped renders a value for an LLM tool result: streams drain and everything truncates at capBytes with a notice. A stream erroring mid-way returns the error, or the partial output with the error noted inline.

func ProjectNames

func ProjectNames() []string

ProjectNames returns the completion source for `project <tab>`: the registered project names, sorted. Like the projects listing, nothing is enumerated from disk — an empty registry completes nothing.

func ProjectRoot

func ProjectRoot() string

ProjectRoot returns the projects root: the project-root binding when it names a non-empty string (config-as-data, like default-graph — e.g. (define project-root "~/code") in the prelude), else ~/src.

func RankText

func RankText(op string, item Value, key string) (string, error)

RankText is rankText for builtins registered outside the package.

func RefString

func RefString(node *models.Node) string

RefString is a node's canonical reference: project:name, note:slug, task:ID, or #ID for anything else.

func Register

func Register(name, doc string, meta CommandMeta)

Register records a builtin's one-line documentation and command-mode capabilities, called beside its definition (Set/SetSpecialForm/ SetMacro).

func RegisteredWords

func RegisteredWords() []string

RegisteredWords returns every registered name — command words, stage words, and the plain Scheme library — unsorted.

func SchemeComplete

func SchemeComplete(s string) bool

SchemeComplete reports whether Scheme source is lexically complete: every (/{/[ group closed and no unterminated string, |symbol|, or block comment.

func StageWords

func StageWords() []string

StageWords returns the names registered as pipeline stage words, unsorted.

func Synopsis

func Synopsis(name string) (usage, scheme string, ok bool)

Synopsis exposes a command's two usage spellings — the command-mode line and the parenthesized Scheme call — for renderers outside the package (the man pages). Same construction as helpText.

func TreeNames

func TreeNames() []string

TreeNames returns the current project's worktree names — directory base names plus branch names where they differ, since findTree matches either — sorted.

Types

type ApprovalFunc

type ApprovalFunc func(action string) bool

ApprovalFunc decides whether a gated action (rm, mv, sh, cat, ls, ...) may proceed. The action string is the human-readable form, e.g. `rm "notes.txt"`.

type BuiltinFunc

type BuiltinFunc func(args []Value, env *Environment) (Value, error)

type Bytevector

type Bytevector []byte

Bytevector is a Scheme bytevector, reader syntax #u8(0 255). Self-evaluating.

type CaseLambda

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

CaseLambda dispatches to the first clause whose formals accept the argument count, in clause order per §4.2.9.

type Char

type Char rune

Char is a Scheme character — one Unicode code point. Reader syntax #\a, #\newline, #\x41. Self-evaluating.

type CommandMeta

type CommandMeta struct {
	// Command makes the name a standalone command word: a line starting
	// with it runs the builtin instead of a system binary.
	Command bool

	// Stage makes the name a pipeline stage word (valid after a `|`).
	Stage bool

	// MinArgs/MaxArgs bound a standalone invocation's argument count; MaxArgs -1
	// means unbounded.
	MinArgs, MaxArgs int

	// Instruction passes the text after the name (and any leading flags) as one
	// verbatim string argument: `agent summarize the Makefile` runs (agent
	// "summarize the Makefile").
	Instruction bool

	// Globs marks a builtin whose path arguments accept glob expansion: an
	// unquoted *?[] token desugars to a (glob "pattern") form, so the builtin
	// must accept a list of paths wherever it accepts one.
	Globs bool

	// Operators lists dash-words the command-mode flag reader passes through as
	// positional arguments instead of parsing as flags — where's test(1)
	// comparisons (`where size -gt 100MB`).
	Operators []string

	// Usage is the positional synopsis help prints after the name —
	// "[pattern]", "\"query\" [input]" — with [flags] appended when the
	// command declares options.
	Usage string

	// Options declares the command's optional parameters — the single source for
	// command-mode flags, the Scheme options dict, and help.
	Options []Option
}

CommandMeta describes how a builtin participates in command mode, as a command word, a pipeline stage word, or both; it is declared with Register beside the builtin and consumed by the shell's reader.

func LookupCommand

func LookupCommand(name string) (CommandMeta, bool)

LookupCommand returns a name's registered command metadata. ok reports only that the name is registered; check the Command/Stage fields for what the word may do in command mode.

type Continuation

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

Continuation is the escape procedure call/cc passes to its receiver. Callable everywhere a procedure is (compiled calls, Apply, apply builtin).

type Dictionary

type Dictionary map[string]Value

Dictionary is a map from Value to Value (for simplicity, keys are usually Keyword or Symbol)

type EOFObject

type EOFObject struct{}

EOFObject is the disjoint end-of-file type: eof-object? answers true for it and nothing else. One singleton suffices — the ports work in Phase 6 returns the same one.

type Environment

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

Environment is goroutine-confined: every read and write happens on the goroutine driving the evaluator, so lookups take no locks. New cross- goroutine paths must bring their own confinement, not a lock here.

func NewEnvironment

func NewEnvironment(parent *Environment) *Environment

func (*Environment) Lookup

func (env *Environment) Lookup(name string) (Value, error)

func (*Environment) LookupMacro

func (env *Environment) LookupMacro(name string) (MacroFunc, bool)

func (*Environment) LookupSpecialForm

func (env *Environment) LookupSpecialForm(name string) (SpecialFormFunc, bool)

func (*Environment) Set

func (env *Environment) Set(name string, val Value)

func (*Environment) SetBuiltin

func (env *Environment) SetBuiltin(name, doc string, fn BuiltinFunc)

SetBuiltin binds a builtin function and registers its documentation — the common case for builtins with no command-mode presence.

func (*Environment) SetMacro

func (env *Environment) SetMacro(name string, macro MacroFunc)

func (*Environment) SetScoped

func (env *Environment) SetScoped(name string, val Value) error

func (*Environment) SetSpecialForm

func (env *Environment) SetSpecialForm(name string, sf SpecialFormFunc)

SetSpecialForm registers a fallback special form. Registering over a natively compiled name replaces the compiler: the latest registration wins.

func (*Environment) UserFunctionNames

func (env *Environment) UserFunctionNames() []string

UserFunctionNames returns the names bound to user-defined functions (define/lambda closures) anywhere in this environment chain — the words command mode would dispatch via tryUserCommand.

type ErrorObject

type ErrorObject struct {
	Message   string
	Irritants []Value
	Kind      string
	// contains filtered or unexported fields
}

ErrorObject is the condition created by (error msg irritants...) and the wrapper for Go errors caught at an exception boundary. Kind classifies file-error? ("file") and read-error? ("read") conditions.

func (*ErrorObject) String

func (eo *ErrorObject) String() string

type Evaluator

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

Evaluator holds the global environment and evaluation settings (timeout, resource limits, etc.)

func NewEvaluator

func NewEvaluator() *Evaluator

func NewEvaluatorWithEnvironment

func NewEvaluatorWithEnvironment(db *sqlx.DB, gs *core.GraphStore) *Evaluator

func (*Evaluator) AliasNames

func (e *Evaluator) AliasNames() []string

AliasNames returns every defined command-mode alias name, unsorted — the shell's tab completer merges them with other candidate sets.

func (*Evaluator) AllowDir

func (e *Evaluator) AllowDir(dir string, write bool)

AllowDir grants standing access under dir for approval-gated operations: reads always, writes too when write is true.

func (*Evaluator) Apply

func (e *Evaluator) Apply(fn Value, args []Value, env *Environment) (Value, error)

Apply invokes any procedure value with the given arguments on this evaluator, so dynamic state riding on it (caller identity, approval gate) stays in force for the call.

func (*Evaluator) Approver

func (e *Evaluator) Approver() ApprovalFunc

Approver returns the currently installed approval function (nil when ungated).

func (*Evaluator) Caller

func (e *Evaluator) Caller() string

Caller returns the current caller identity.

func (*Evaluator) Confirmer

func (e *Evaluator) Confirmer() ApprovalFunc

Confirmer returns the currently installed confirmation function (nil when none — fail closed, never prompt-free).

func (*Evaluator) Eval

func (e *Evaluator) Eval(expr Value, env *Environment) (Value, error)

Eval compiles expr against env's scope and runs it (compile.go). The shell and the LLM tool loop enter here per form; fallback special forms enter here per subform.

func (*Evaluator) EvalAll

func (e *Evaluator) EvalAll(exprs []Value, env *Environment) (Value, error)

EvalAll evaluates a sequence of expressions, returning the result of the last one. It skips nils (which may represent comments or empty lines).

func (*Evaluator) GlobalEnv

func (e *Evaluator) GlobalEnv() *Environment

func (*Evaluator) LookupAlias

func (e *Evaluator) LookupAlias(name string) (string, bool)

LookupAlias returns the expansion for a command-mode alias.

func (*Evaluator) PathAllowed

func (e *Evaluator) PathAllowed(path string, write bool) bool

PathAllowed reports whether the standing grant covers path at the given access level — the hook for gates outside the evaluator (the native read/edit/write tools).

func (*Evaluator) RankInput

func (e *Evaluator) RankInput(op string, v Value) ([]Value, error)

RankInput is rankInput for builtins registered outside the package (llm- map/classify in llm/), sharing the ranking builtins' input convention including the read gate on file inputs.

func (*Evaluator) RecordResult

func (e *Evaluator) RecordResult(v Value)

RecordResult shifts the last-result bindings in the global environment: *1 becomes v, the previous *1 moves to *2 and *2 to *3 — so a value just printed at the REPL stays reachable, e.g.

func (*Evaluator) RequireUser

func (e *Evaluator) RequireUser(name string) error

RequireUser errors unless the current caller is the user — for interactive builtins (configure, resume, compact) that only the person at the terminal may run.

func (*Evaluator) SetApprover

func (e *Evaluator) SetApprover(fn ApprovalFunc)

SetApprover installs (or, with nil, removes) the function consulted by destructive builtins (rm, mv, sh) before they act. With no approver set, those builtins run ungated.

func (*Evaluator) SetCaller

func (e *Evaluator) SetCaller(caller string)

SetCaller records who initiated the current evaluation. The zero value means CallerUser: code typed at the prompt never has to set it.

func (*Evaluator) SetConfirmer

func (e *Evaluator) SetConfirmer(fn ApprovalFunc)

SetConfirmer installs the function irreversible builtins (delete-graph) consult for an explicit go-ahead.

func (*Evaluator) SetForegroundRunner

func (e *Evaluator) SetForegroundRunner(fn ForegroundRunner)

SetForegroundRunner installs (or, with nil, removes) the shell's foreground-child runner.

func (*Evaluator) SetInFlightHistory

func (e *Evaluator) SetInFlightHistory(id int64)

SetInFlightHistory records which history row holds the line currently executing.

func (*Evaluator) SetSessionID

func (e *Evaluator) SetSessionID(id string)

SetSessionID records the shell session's id for provenance stamps (the task builtin). The shell loop sets it once at startup, sharing the id its history and session rows carry.

type FastBuiltin

type FastBuiltin struct {
	Fn  BuiltinFunc
	Fn1 func(a Value, env *Environment) (Value, error)
	Fn2 func(a, b Value, env *Environment) (Value, error)
}

FastBuiltin wraps a builtin with allocation-free call paths for the arities that dominate real code.

type ForegroundRunner

type ForegroundRunner func(cmd *exec.Cmd, line string) (int, error)

ForegroundRunner runs a terminal-attached child as the foreground process group and returns its exit code; the shell installs one so exec joins its job control. line is the display form for job listings.

type Integer

type Integer int64

Integer is the exact integer type of the D1 numeric split (SCHEME.md): int64 exact alongside Number's float64 inexact.

func (Integer) String

func (i Integer) String() string

type Keyword

type Keyword string

type Lambda

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

Lambda represents a user-defined function (closure).

type MacroFunc

type MacroFunc func(args []Value) (Value, error)

type MultipleValues

type MultipleValues struct {
	Vals []Value
}

MultipleValues carries the results of (values a b ...) to call-with-values. Zero or ≥2 values only; never one.

type MutableString

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

MutableString is the second string representation of SCHEME.md D3: a []rune-backed mutable string, allocated only by make-string, string, and string-copy.

type Number

type Number float64

func (Number) String

func (n Number) String() string

String makes Number a fmt.Stringer so every print path agrees: exactly- representable integral values print as integers ("2178309", not "2.178309e+06"), everything else as the shortest round-tripping decimal.

type Option

type Option struct {
	Long        string     // --long flag and :long dict key
	Short       string     // one-letter -s spelling; "" = long-only
	Kind        OptionKind // value type; OptionBool takes no value
	Placeholder string     // help's display for the value (PATH, N, COL)
	Doc         string     // one-line description in help output
}

Option is one declared optional parameter. Its Long name is both the command-mode --flag and the Scheme dict key, so translation between the two surfaces is mechanical.

type OptionKind

type OptionKind int

OptionKind is the value type an option carries. Numeric kinds coerce numeric strings, matching command mode's everything-is-a-string words.

const (
	OptionBool OptionKind = iota
	OptionString
	OptionInt
	OptionNumber
)

type Pair

type Pair struct {
	Car, Cdr Value
}

Pair is a real cons cell (SCHEME.md D2 stage one): the canonical *data* list type, existing alongside rf's slice-backed lists.

type Parameter

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

Parameter is a make-parameter object: callable with no arguments to read its current value.

type Port

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

Port is a Scheme port. Direction and kind are fixed at creation; ops check both and whether the port is still open. Like the rest of the evaluator, ports assume one evaluation at a time — no locking.

type Promise

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

Promise is a delayed computation.

type Record

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

Record is an instance: values aligned with the type's field order. Fields the constructor doesn't name start nil (unspecified, per spec).

type RecordType

type RecordType struct {
	Name   string
	Fields []Symbol
}

RecordType is a record type descriptor, bound to the definition's type name. Field order is the declaration order of the field specs.

type Ref

type Ref struct {
	Kind string // "task", "note", "project", or "" for a bare "#id"
	Key  string
}

Ref names one node in the knowledge-base graph: a kind plus a key — "task:42", "note:slug", "project:name", or "#42" for any node by id.

func ExtractRefs

func ExtractRefs(text string) []Ref

ExtractRefs returns the [[...]] references in text, in order, deduplicated.

func ParseRef

func ParseRef(s string) (Ref, error)

ParseRef reads a reference string. A bare word with no prefix is a note slug — inside [[...]] the common case — and "#N" is any node by id.

func (Ref) String

func (r Ref) String() string

type RegisteredProject

type RegisteredProject struct {
	NodeID uint32
	Name   string
	Path   string // "" for a project with no backing directory
	Kind   string // "hub" (trees are siblings of .bare) or "dir" (trees in .trees/)
	Text   string // markdown notes, edited with project -e
}

RegisteredProject is one registry entry, decoded from a project node's properties.

type SpecialFormFunc

type SpecialFormFunc func(args []Value, env *Environment, e *Evaluator) (Value, error)

SpecialFormFunc receives the evaluator itself rather than an eval callback: passing the bound method allocated a closure per dispatch, and forms need e to enter tail calls anyway.

type Stream

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

Stream is a lazy, single-use sequence of Values — the value type behind cat/sh/fetch and lazy grep/take stages, so (pipe (sh "yes") (take 2)) terminates instead of buffering forever.

func StreamFromReader

func StreamFromReader(r io.Reader, closefn func() error) *Stream

StreamFromReader is the exported spelling of streamFromReader for callers outside the package that hand text to the pipeline as lines (`docs --raw`). closefn may be nil.

func (*Stream) Close

func (s *Stream) Close() error

Close marks the stream done and releases upstream resources — killing a sh child process, closing a cat file handle. Idempotent; safe to call concurrently with a blocked Next.

func (*Stream) Lines

func (s *Stream) Lines() bool

Lines reports whether this is a line stream — the lines of a text source, rejoinable into a string — as opposed to a stream of rows.

func (*Stream) Next

func (s *Stream) Next() (Value, bool, error)

Next returns the next value. ok=false with a nil error is a clean end (resources already released); a spent stream errors ErrStreamConsumed.

func (*Stream) TextReader

func (s *Stream) TextReader() io.Reader

TextReader adapts a line stream to an io.Reader yielding its text, each line newline-terminated — the shape a child process's stdin expects.

type String

type String string

type Symbol

type Symbol string

type SyntaxRules

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

SyntaxRules is a macro transformer value, produced by the syntax-rules special form and installed by define-syntax / let-syntax.

type TailCall

type TailCall struct {
	Node node
	Expr Value
	Env  *Environment
}

TailCall is the value a tail-position call returns to the run loop: Node runs in Env. A nil Node carries an uncompiled Expr — the shape fallback special forms produce through tail — compiled on arrival.

type Value

type Value interface{}

func AsList

func AsList(v Value) ([]Value, bool, error)

AsList returns a value as a list, draining a stream if given one. ok=false means the value has no list shape (coercion sites keep their own type-error messages).

func JobRows

func JobRows() []Value

JobRows lists every job started this process as rows — the cmd `jobs` builtin appends these to the shell's stopped-job rows.

func Materialize

func Materialize(v Value) (Value, error)

Materialize drains a stream into its eager equivalent — a line stream to its text (a String, each line newline-terminated), any other stream to a list — and returns non-stream values unchanged.

func Parse

func Parse(input string) (Value, error)

Parse parses a single line of Scheme code into a Value (AST)

func ParseAll

func ParseAll(input string) ([]Value, error)

ParseAll parses multiple Scheme expressions from a string.

func ParseOptions

func ParseOptions(name string, args []Value) ([]Value, map[string]Value, error)

ParseOptions splits args into positional arguments and the declared options of the named builtin. Unknown keys and kind mismatches error naming the supported set; a boolean option given #f counts as unset.

type Vector

type Vector []Value

Vector is a Scheme vector, reader syntax #(1 2 3).

Jump to

Keyboard shortcuts

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