interp

package
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package interp evaluates a loaded program (section 12). An Instance is one run: it owns the module records, the writers, and the cancellation flag. Each goroutine carries its own call stack. Values come from the value package; functions and environments are defined here.

Index

Constants

This section is empty.

Variables

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

ErrInterrupted is the error Run returns when an interrupt from Config.Interrupts ended the run: one the program had not asked for, or the second.

Functions

func HasDefault

func HasDefault(tag *value.Tag, i int) bool

HasDefault reports whether field i of a record tag declares a default.

func RecordTag added in v0.3.3

func RecordTag(prelude map[string]value.Value, name string) (*value.Tag, bool)

RecordTag finds the tag of a record type in a prelude table by its name, Name or Owner.Name, where the owner is a namespace or a type. It is false for a name that is not a record type: an alias, an opaque type, a named primitive, a function.

func Run

func Run(ctx context.Context, prog *loader.Program, cfg Config) error

Run executes prog: initializes the modules in order, the script last, which runs its body.

func RunTests

func RunTests(ctx context.Context, prog *loader.Program, cfg Config, tc TestConfig) error

RunTests runs a test file's program: it initializes the modules, then runs the root's tests in source order. It returns nil when the tests ran, whatever their outcomes; a *PanicError when an initializer panicked; an *ExitError when the program called Os.exit; and the context's error when ctx ended the run.

func TestPattern

func TestPattern(s string) ([]*regexp.Regexp, error)

TestPattern compiles a -run or -skip pattern (test.md section 1): one regular expression per level of a full name, split on each / that is not escaped with a backslash or inside brackets or parentheses, so a name holding a / is matched as \/ or [/].

func TypeValue

func TypeValue(d *ast.TypeDecl, env *Env) value.Value

TypeValue builds what a type declaration binds: a record tag, a constructor, or an alias tag, which keeps the declaration and env, the environment its body's names resolve in, for a type expression to resolve (section 4, Types as values): the module's root, or for a local type the environment that holds only the types of its block. A nil env resolves the names through the prelude, as a host's declarations do. A host's opaque type, declared without a body, is a sync tag, which `is` cannot test.

Types

type AntPanic

type AntPanic struct {
	Message string
	Trace   []Frame
	// contains filtered or unexported fields
}

AntPanic is the Go panic value that carries an Ant panic while it unwinds.

func (*AntPanic) Error

func (p *AntPanic) Error() string

type Breakpoint

type Breakpoint struct {
	Pos          ast.Pos
	Condition    string
	HitCondition string
	LogMessage   string
}

Breakpoint is a line breakpoint bound to a stop point, with what decides whether it stops.

type Builtin

type Builtin struct {
	Name     string
	Params   []string
	Optional int
	Fn       func(g *Goroutine, args []value.Value) value.Value
}

Builtin is a function implemented in Go. It receives its arguments positionally, exactly len(Params) of them. A call may omit the last Optional parameters, and an omitted one arrives as nil, for the builtin to replace by its default.

func (*Builtin) FuncName

func (b *Builtin) FuncName() string

FuncName returns the builtin's name.

type Config

type Config struct {
	Prelude map[string]value.Value
	Stdin   io.Reader // what Os.stdin reads; nil is an empty stream
	Stdout  io.Writer
	Stderr  io.Writer
	Args    []string
	Program string // what Os.program returns: the root module's path as the host was given it
	Env     func(name string) (string, bool)
	Environ func() []string // every variable as name=value; nil is the process's environment
	// Grace is how long Run waits, after the script ends, for the other goroutines to finish.
	// They are told to stop at once; the wait only lets reports in progress complete. Zero
	// means the default of 100 milliseconds.
	Grace time.Duration
	// Interrupts delivers the host's interrupts, one value each. The first goes to the context
	// Os.interrupt created, when the program created one and it is not done; otherwise the run
	// is cancelled, as the first is for a program that never asked. Nil delivers none.
	Interrupts <-chan struct{}
	// Foreground is called as Cmd.run starts a child in the foreground, and the function it
	// returns as the child exits, with the signal that ended the child or nil, so the host can
	// hold back its keyboard signals meanwhile; that function reports whether one it held is
	// now the program's interrupt, which Cmd.run delivers before it returns. Nil holds nothing.
	Foreground func() func(os.Signal) bool
	// Debugger, when set, stops the run at its breakpoints and steps.
	Debugger *Debugger
}

Config configures a run.

type Debugger

type Debugger struct {
	// OnStop is called once every goroutine has stopped, from the goroutine that stopped or, for
	// a pause, from one of its own.
	OnStop func(Stop)
	// OnLog is called with what a logpoint writes, or the error of a breakpoint's condition.
	OnLog func(text string)
	// OnGoroutine is called as a goroutine starts and as it ends.
	OnGoroutine func(id int, started bool)
	// StopOnEntry stops before the first statement of the root module.
	StopOnEntry bool
	// contains filtered or unexported fields
}

Debugger stops a run at its stop points, for ant dap: at breakpoints, at the end of a step, on a pause, and at a panic. When one goroutine stops, every goroutine stops.

Each goroutine is in Ant code or outside it, in a builtin or the host's code. One in Ant code is active until it parks; one outside never touches its stack, so a stop waits only for the active ones to park, and a goroutine coming back into Ant code while the run is stopped waits there. The stacks are read, under mu, only while the run is stopped.

func NewDebugger

func NewDebugger() *Debugger

NewDebugger returns a debugger that stops at uncaught panics, the default.

func (*Debugger) Continue

func (d *Debugger) Continue(ack func())

Continue resumes every goroutine from the stop OnStop reported, calling ack, when not nil, first: a stop is reported before ack or after it, never between ack and the resume. Before the report, Continue does nothing but call ack; the stop is reported, and the client resumes from it.

func (*Debugger) Evaluate

func (d *Debugger) Evaluate(sf StackFrame, src string) (value.Value, error)

Evaluate evaluates src in a frame of the stopped run.

func (*Debugger) Frames

func (d *Debugger) Frames(id int) ([]StackFrame, bool)

Frames lists the frames of goroutine id, innermost first, while the run is stopped.

func (*Debugger) Goroutines

func (d *Debugger) Goroutines() []GoroutineInfo

Goroutines lists the live goroutines by ID.

func (*Debugger) Panic

func (d *Debugger) Panic() *AntPanic

Panic returns the panic the run stopped at, or nil.

func (*Debugger) Pause

func (d *Debugger) Pause(id int)

Pause stops every goroutine. The stop names the goroutine id, or the main goroutine when that one has ended. A run that has not started or is ending does not stop.

func (*Debugger) Resume

func (d *Debugger) Resume()

Resume resumes every goroutine, also from a stop not reported yet, as the run ends.

func (*Debugger) Scopes

func (d *Debugger) Scopes(sf StackFrame) (locals, closure, module []Var)

Scopes returns the Locals, Closure and Module variables of a frame.

func (*Debugger) SetBreakpoints

func (d *Debugger) SetBreakpoints(path string, list []Breakpoint) []error

SetBreakpoints replaces the breakpoints of the module at path. It returns, for each, why it is not set, or nil.

func (*Debugger) SetFunctionBreakpoints

func (d *Debugger) SetFunctionBreakpoints(list []FunctionBreakpoint) []error

SetFunctionBreakpoints replaces every function breakpoint. It returns, for each, why it is not set, or nil.

func (*Debugger) SetPanicFilters

func (d *Debugger) SetPanicFilters(uncaught, all bool)

SetPanicFilters sets which panics stop the run.

func (*Debugger) SetVar

func (d *Debugger) SetVar(v Var, x value.Value) error

SetVar gives a variable of a stopped frame's scopes a new value.

func (*Debugger) Step

func (d *Debugger) Step(id int, kind StepKind, ack func())

Step resumes every goroutine until the goroutine id reaches the stop point the step looks for. It calls ack as Continue does.

type Env

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

Env is an environment: the slots of one block, loop iteration, or function body, with its parent. Plain slots belong to one goroutine; shared slots may be captured by a nested body and are published through value.Slot.

type ExitError

type ExitError struct {
	Status int
}

ExitError is Os.exit.

func (*ExitError) Error

func (e *ExitError) Error() string

type Frame

type Frame struct {
	Function string
	Path     string
	Pos      ast.Pos
}

Frame is one entry of a panic trace, innermost first.

type Func

type Func struct {
	Name   string
	Params []ast.Param
	Body   *ast.Block
	Scope  *ast.FuncScope
	Env    *Env
	Lambda bool
}

Func is a declared or anonymous function, or a lambda, with the environment it captured.

func (*Func) FuncName

func (f *Func) FuncName() string

FuncName returns the function's name, "func" for anonymous functions and lambdas.

type FunctionBreakpoint

type FunctionBreakpoint struct {
	Path string
	Breakpoint
}

FunctionBreakpoint is a breakpoint at the first stop point of a function's body, in the module at Path.

type Goroutine

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

Goroutine is the per-goroutine interpreter state: its call stack, whose length is the depth.

func (*Goroutine) AfterWait

func (g *Goroutine) AfterWait()

AfterWait ends the goroutine when the run's own context is done: a wait the run's end released runs nothing more, whichever path ended the run and whether or not the flag is set yet. Every blocking call calls it as it returns.

func (*Goroutine) Call

func (g *Goroutine) Call(fn value.Value, args ...value.Value) value.Value

Call calls an Ant function value from a builtin.

func (*Goroutine) Catch

func (g *Goroutine) Catch(fn value.Value, args ...value.Value) (value.Value, *AntPanic)

Catch calls fn with args and returns its value, or the Ant panic that left it once the deferred blocks inside it have run (section 8, Catching a panic). Anything else that unwinds, Os.exit or the run's end, goes on.

func (*Goroutine) CatchFor

func (g *Goroutine) CatchFor(parent *Goroutine, body func() value.Value) (v value.Value, p *AntPanic)

CatchFor runs body as CatchFunc does, on a goroutine that works for parent, as a Parallel callback works for its caller: the panic goes back to parent, so a debugger counts it as caught exactly when parent would catch it, and stops at the panic, where the callback's locals are. parent is blocked for the whole call, so its count holds still.

func (*Goroutine) CatchFunc

func (g *Goroutine) CatchFunc(body func() value.Value) (v value.Value, p *AntPanic)

CatchFunc runs body as Catch runs a function: it returns body's value, or the Ant panic that left body, which includes the panics of a builtin's own checks inside it.

func (*Goroutine) Context

func (g *Goroutine) Context() context.Context

Context returns the run's context, for blocking host functions.

func (*Goroutine) Eprint

func (g *Goroutine) Eprint(s string)

Eprint writes s to the run's standard error, or collects it for the test the goroutine belongs to; eprint and eprintln ignore an error, as Print does.

func (*Goroutine) ErrWriter

func (g *Goroutine) ErrWriter() io.Writer

ErrWriter is the run's ErrWriter, or a writer that collects for the test the goroutine belongs to.

func (*Goroutine) FillDefaults

func (g *Goroutine) FillDefaults(tag *value.Tag, vals []value.Value)

FillDefaults fills each nil slot of vals from the tag's defaults, as a record literal at the current call does; a field without a default panics. It is how Reflect.makeRecord fills the fields it was not given.

func (*Goroutine) Instance

func (g *Goroutine) Instance() *Instance

Instance returns the run this goroutine belongs to.

func (*Goroutine) Panic

func (g *Goroutine) Panic(format string, args ...any)

Panic raises an Ant panic at the current position.

func (*Goroutine) Print

func (g *Goroutine) Print(s string)

Print writes s to the run's stdout, or collects it for the test the goroutine belongs to.

func (*Goroutine) Repanic

func (g *Goroutine) Repanic(p *AntPanic)

Repanic raises a caught Ant panic again, from the call site of the builtin in progress.

func (*Goroutine) RunSeq

func (g *Goroutine) RunSeq(seq value.Value, push func(value.Value) bool)

RunSeq runs a sequence as for does, with push as the loop body: it reports whether the consumer wants more (section 12, for).

func (*Goroutine) Spawn

func (g *Goroutine) Spawn(body func(*Goroutine))

Spawn runs body on a new Ant goroutine, as a go block does: a panic in it is reported and ends it alone, and the run's grace period waits for it.

func (*Goroutine) Tag added in v0.3.3

func (g *Goroutine) Tag(name string) (*value.Tag, bool)

Tag returns the tag of the record type a prelude name names, as the running program has it.

func (*Goroutine) TestContext

func (g *Goroutine) TestContext(who string) *value.Context

TestContext returns the current test's context, done when its body ends (Test.context).

func (*Goroutine) TestName

func (g *Goroutine) TestName(who string) string

TestName returns the current test's full name (Test.name).

func (*Goroutine) TestParallel

func (g *Goroutine) TestParallel(who string)

TestParallel makes the current test a parallel one (Test.parallel): it returns once the parent's sequential tests have ended and a slot of -parallel is free.

func (*Goroutine) TestSkip

func (g *Goroutine) TestSkip(who, reason string)

TestSkip ends the current test as skipped (Test.skip).

func (*Goroutine) TestTempDir

func (g *Goroutine) TestTempDir(who string) string

TestTempDir makes a directory removed when the current test ends (Test.tempDir).

type GoroutineInfo

type GoroutineInfo struct {
	ID   int
	Name string
}

GoroutineInfo is a goroutine as a debugger lists it.

type Instance

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

Instance is one run of a program.

func New

func New(ctx context.Context, prog *loader.Program, cfg Config) *Instance

New creates an instance without running anything. Sessions use it.

func Start

func Start(ctx context.Context, prog *loader.Program, cfg Config) (*Instance, error)

Start creates an instance and initializes its modules, running a script root's body as Run does. The caller runs functions with Call and ends the instance with Close.

func (*Instance) Args

func (in *Instance) Args() []string

Args returns the program's arguments.

func (*Instance) Call

func (in *Instance) Call(fn value.Value, args ...value.Value) (v value.Value, err error)

Call calls an Ant function value with positional arguments, on the calling Go goroutine.

func (*Instance) ChildStderr

func (in *Instance) ChildStderr() io.Writer

ChildStderr returns the run's standard error as a child process is given it: the file itself when it is one, and otherwise the writer behind the lock the run's reports take.

func (*Instance) ChildStdin

func (in *Instance) ChildStdin() io.Reader

ChildStdin returns the run's standard input as a child process is given it: the file itself when it is one, so a terminal is handed over as it is; nil, the null device, when the run has none; and otherwise the reader every reader of standard input shares.

func (*Instance) ChildStdout

func (in *Instance) ChildStdout() io.Writer

ChildStdout returns the run's standard output as a child process is given it: the file itself when it is one, and otherwise the writer behind the lock print takes, so what the child writes and what the program prints never write the host's writer at once.

func (*Instance) Close

func (in *Instance) Close()

Close stops the instance: its goroutines find the flag at their next check, blocking calls see the cancelled context, and reports in progress get the grace period to finish.

func (*Instance) Context

func (in *Instance) Context() context.Context

Context returns the run's context, for blocking builtins.

func (*Instance) Environ

func (in *Instance) Environ() []string

Environ returns the run's whole environment as name=value pairs.

func (*Instance) ErrWriter

func (in *Instance) ErrWriter() io.Writer

ErrWriter returns the writer to the run's standard error that eprint, eprintln, Os.stderr and the run's reports write through.

func (*Instance) Exit

func (in *Instance) Exit(status int)

Exit ends the run with the given status, from any goroutine. Deferred blocks do not run on the way out; the run's other goroutines stop at their next check.

func (*Instance) Foreground

func (in *Instance) Foreground() func(os.Signal)

Foreground tells the host that a child is starting in the foreground, and returns what tells it the child exited and which signal ended it, nil for none, and delivers the interrupt the host held back meanwhile when the host says it is now the program's.

func (*Instance) Interrupt

func (in *Instance) Interrupt() *value.Context

Interrupt returns the context Os.interrupt gives: the same one at every call, done when the host delivers an interrupt.

func (*Instance) Keep

func (in *Instance) Keep(key string, create func() any) any

Keep returns the value stored under key for this run, creating it with create on the first call: a library's per-run state, such as the handles of the standard streams.

func (*Instance) LastResult

func (in *Instance) LastResult() (value.Value, bool)

LastResult is what _ reads in a session, and false before any result.

func (*Instance) Lookup

func (in *Instance) Lookup(name string) (value.Value, bool)

Lookup returns a top-level name of the root module.

func (*Instance) LookupEnv

func (in *Instance) LookupEnv(name string) (string, bool)

LookupEnv consults the run's environment.

func (*Instance) OnStop

func (in *Instance) OnStop(f func(aborted bool)) (remove func())

OnStop registers f to run as the run stops, before the grace period, told whether a cancellation ended the run: the host's, or an interrupt's. The returned function unregisters it.

func (*Instance) Print

func (in *Instance) Print(s string) error

Print writes s to the run's stdout.

func (*Instance) Program

func (in *Instance) Program() string

Program returns the program's path, "" in a session.

func (*Instance) Stdin

func (in *Instance) Stdin() io.Reader

Stdin returns the run's standard input, an empty stream when none was given.

func (*Instance) Stdout

func (in *Instance) Stdout() io.Writer

Stdout returns the writer print, println and Os.stdout write to: the host's standard output, written at once under a lock, so that writes from several goroutines and from children do not interleave within one write, until the run is released.

type NativeDefaults

type NativeDefaults []func() value.Value

NativeDefaults are the field defaults of a record tag the library builds, as the prelude declares them: per field, nil or a function that makes a fresh value.

type PanicError

type PanicError struct {
	Message string
	Trace   []Frame
}

PanicError is a panic that ended the main goroutine.

func (*PanicError) Error

func (e *PanicError) Error() string

type ResultError

type ResultError struct {
	Message string
}

ResultError is an Err the script returned (section 10, Scripts). Message is String.from of its error field, which the run has written to standard error.

func (*ResultError) Error

func (e *ResultError) Error() string

type Session

type Session struct {
	Fields *ast.ModuleScope
	// contains filtered or unexported fields
}

Session evaluates inputs one at a time against a persistent module: declarations accumulate, a name may be declared again, and imported modules are loaded once.

func NewSession

func NewSession(ctx context.Context, cfg Config) *Session

NewSession creates a session whose module starts empty. When ctx is done the session's goroutines stop at their next check, as a run's do.

func (*Session) Eval

func (s *Session) Eval(prog *loader.Program) (value.Value, error)

Eval takes the program of one input, which the loader resolved against the session's fields, initializes any module it imports for the first time, binds the input's new declarations, and runs its statements. It returns the value of the last expression.

func (*Session) Instance

func (s *Session) Instance() *Instance

Instance returns the session's instance, for Close.

func (*Session) Lookup

func (s *Session) Lookup(name string) (value.Value, bool)

Lookup returns a name the session's module has bound.

func (*Session) SetLast

func (s *Session) SetLast(v value.Value)

SetLast makes v what _ reads: the result of the last input that had one.

type StackFrame

type StackFrame struct {
	Function string
	Path     string
	Pos      ast.Pos
	// contains filtered or unexported fields
}

StackFrame is one frame of a stopped goroutine, innermost first.

type StepKind

type StepKind int

StepKind is a step request.

const (
	StepIn StepKind = iota
	StepOver
	StepOut
)

type Stop

type Stop struct {
	Goroutine int    // the goroutine that stopped
	Reason    string // breakpoint, step, pause, exception, or entry
	Panic     *AntPanic
}

Stop describes why the run stopped.

type StopPoint

type StopPoint struct {
	Pos ast.Pos
	// Body is the function, lambda, go block, defer block, test, or file the point is in.
	Body ast.Node
}

StopPoint is a place a run can stop.

func StopPoints

func StopPoints(f *ast.File) []StopPoint

StopPoints lists the stop points of a module, in source order.

type TestConfig

type TestConfig struct {
	// File labels the events: the test file's path as the runner found it.
	File string
	// Run and Skip are the -run and -skip patterns, one regular expression per level of a
	// full name; nil runs every test and skips none.
	Run, Skip []*regexp.Regexp
	// Parallel is the most tests that run at once after Test.parallel; zero means one.
	Parallel int
	// Stop, when set, is set by the first failure and stops tests from starting (-failfast).
	// It may be shared by the runs of several files.
	Stop *atomic.Bool
	// Report receives every event, from any goroutine, one at a time.
	Report func(TestEvent)
}

TestConfig configures RunTests.

type TestEvent

type TestEvent struct {
	Kind TestEventKind
	File string
	Name string // the full name, as "parse/0x10"
	// Parent is the full name of the test a subtest runs in, on its TestRun event; "" for a
	// top-level test. A name may hold a /, so Name alone does not say.
	Parent  string
	Output  string
	Message string
	Elapsed time.Duration
	// Counted is set on an outcome a summary counts: a test without subtests, or one with
	// subtests that failed on its own.
	Counted bool
}

TestEvent is one event of a test's run.

type TestEventKind

type TestEventKind int

TestEventKind is what a TestEvent reports.

const (
	TestRun    TestEventKind = iota // a test starts
	TestOutput                      // a test printed Output
	TestPass
	TestFail // Message holds the failures, one report each, or "" for one that failed by its subtests alone
	TestSkip // Message holds the reason
)

type Var

type Var struct {
	Name  string
	Value value.Value
	// contains filtered or unexported fields
}

Var is a named value a debugger shows.

func (Var) Settable

func (v Var) Settable() bool

Settable reports whether SetVar can give v a new value.

Jump to

Keyboard shortcuts

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