ant

package module
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: 26 Imported by: 1 module, 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.

README

Ant

Ant is a typed language with errors as values, pipes for data, and goroutines.

Examples

var result = [5, 2, 8, 1]
  | Array.filter({ x > 2 })
  | Array.map({ x * 10 })
  | Array.sort()
println(result) // [50, 80]
type Ready = { url: string }
type Pending = {}
func status(job: Ready | Pending): string {
  if job is Ready { job.url } else { "pending" }
}
func firstLine(path: string): Result[string | null, Error] {
  var file = try File.open(path)
  defer { File.close(file) }
  File.readLine(file)
}
var messages: Channel[string] = Channel.new()
select {
  var message = Channel.receive(messages) { println(message) }
  Time.sleep(Time.duration(seconds: 1)) { println("Timeout") }
}
var date = Time.plainDate(2024, 8, 31)
var next = Time.add(date, Time.duration(months: 1))
println(next) // 2024-09-30

Install

go install github.com/ant-src/ant/cmd/ant@latest

Type-check and run:

ant check main.ant
ant run main.ant

Try things out in the REPL, which highlights the code as it is typed, completes names, members, and arguments with Tab, and suggests the first completion after the cursor:

ant

Format, or check the layout in CI:

ant fmt .
ant fmt --check .

Read the docs of the standard library, or of a module's exports:

ant doc Array.map
ant doc Time
ant doc geometry.ant distance

Complete commands, flags, and files in the shell:

source <(ant --comp zsh)   # in ~/.zshrc, after compinit
source <(ant --comp bash)  # in ~/.bashrc
ant --comp fish | source   # in ~/.config/fish/config.fish

Editor Support

Ant provides code completion, diagnostics, and navigation through the Language Server Protocol (LSP), and debugging through the Debug Adapter Protocol (DAP).

Go API

Ant can be embedded in Go applications for executing scripts, calling Ant functions, and exposing Go functions to Ant.

Load, check, and run a program:

prog, err := ant.Load("main.ant")
diags := prog.Check()
err = prog.Run(ctx, ant.WithArgs(args))

Call Ant functions from Go:

in, err := prog.Start(ctx)
defer in.Close()

scale, _ := in.Func("scale")
result, err := scale.Call(point, 2.0)

Expose Go functions to Ant using namespaces and Ant type signatures:

prog, err := ant.Load("main.ant", ant.WithNamespace(ant.Namespace{
    Name:       "Kv",
    Signatures: "func Kv.get(key: string): string | null",
    Funcs:      map[string]ant.HostFunc{"get": get},
}), ant.WithoutNamespaces("File", "Http"))

Evaluate code interactively with persistent state, using the same API as the Ant REPL:

s, err := ant.NewSession(ctx, ant.WithStdout(os.Stdout))
v, err := s.Eval("var x = 2")
v, err = s.Eval("x * 21")

License

MIT

Documentation

Overview

Package ant loads, runs, and checks programs written in Ant.

Load parses a program and every module it imports into an immutable Program, which can be run any number of times, concurrently. Program.Run executes it with the options given and returns nil when the script ends, a *ResultError when it returns an Err, a *PanicError when the main goroutine panics, or an *ExitError when the program calls Os.exit. Program.Check runs the type checker and returns its diagnostics.

The library reads sources through an fs.FS, writes only to the writers it is given, takes its standard input, arguments and environment from options, and never exits the process. An interrupt reaches a program through WithInterrupts: the first goes to the context Os.interrupt returns when the program asked for one, and otherwise, or at the second, the run ends as it does when the context given to Run is cancelled.

Calling across the boundary

Program.Start initializes a program and returns an Instance, so a host loads a library, whose initialization runs no statements, and calls into it: its Func method finds a top-level function, which Func.Call calls with positional arguments, and its Value method reads a top-level var or a type's tag. WithNamespace gives a program a set of Go functions that Ant code reaches as Name.function, declared in Ant notation so the checker can type the calls. A Session evaluates inputs one at a time on a persistent module.

Values

Ant values cross the boundary as value.Value, which is a Go interface value holding one of these representations:

Ant                         Go
int, int64                  int64
int8 … int32, uint8 … uint64, byte   the Go integer type of that width (byte is uint8)
float32, float64            float32, float64
string                      string
Bytes                       *value.Bytes  (value.NewBytes adopts, value.CopyBytes copies; View, Snapshot)
bool                        bool
null, void                  value.Null, value.Void
Array[T]                    *value.Array  (value.NewArray, Values, Get, Set, Push)
Map[K, V]                   *value.Map    (value.NewMap, Get, Set, Keys, Entries)
Set[T]                      *value.Set    (value.NewSet, Has, Add, Remove, Values)
a record                    *value.Record (value.NewRecord with its *value.Tag, Field, SetField)
a named primitive type      *value.Tagged (Tag and Payload)
Result[T, E], Error         records built by value.Ok, value.Err, and value.ErrorValue
Entry[K, V], Indexed[T]     records built by value.Entry and value.Indexed
a function                  an opaque value.Callable: pass it back to Func.Call or Runtime.Call
a type                      *value.Tag, from Instance.Value("Name"), Runtime.Tag or Program.Tag
Time.Instant                value.Time: value.NewInstant from a time.Time, value.GoTime to one
Time.Duration               value.Time: value.NewDuration from a time.Duration, value.GoDuration to one
another time value          an opaque value.Time: its String is the RFC 9557 form; pass it back
a Regex.Pattern             *value.Regex, from value.NewRegex: its String is the literal form
a sync object, Channel, Context  an opaque value.Sync: pass it back

A record's tag comes from the program, which holds one for each record type: the instance has those the root module declares, and the Example_call test builds a Point that way; Runtime.Tag and Program.Tag have those of the prelude, a host namespace's among them, as the Example_namespace test builds a Kv.Pair. A host function receives its arguments in the order its signature lists them, already of these representations, and returns a value of them; an error it returns becomes an Ant panic with the error's message. value.Render renders any value the way String.from does.

Example (Call)

Calling an Ant function from Go.

package main

import (
	"context"
	"fmt"

	"github.com/ant-src/ant"
	"github.com/ant-src/ant/value"
)

func main() {
	src := `
type Point = { x: float64, y: float64 }

func scale(p: Point, k: float64): Point { Point{ x: p.x * k, y: p.y * k } }
`
	prog, err := ant.Load("geometry.ant", ant.WithSource("geometry.ant", src))
	if err != nil {
		fmt.Println(err)
		return
	}
	in, err := prog.Start(context.Background())
	if err != nil {
		fmt.Println(err)
		return
	}
	defer in.Close()
	pointTag, _ := in.Value("Point")
	scale, _ := in.Func("scale")
	p := value.NewRecord(pointTag.(*value.Tag), []value.Value{1.5, 2.0})
	result, err := scale.Call(p, 2.0)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(value.Render(result))
}
Output:
Point{ x: 3.0, y: 4.0 }
Example (Namespace)

Giving a program a host namespace, declared in Ant notation and implemented in Go.

package main

import (
	"context"
	"fmt"
	"maps"
	"os"
	"slices"

	"github.com/ant-src/ant"
	"github.com/ant-src/ant/value"
)

func main() {
	store := map[string]string{}
	kv := ant.Namespace{
		Name: "Kv",
		Signatures: `
type Kv.Pair = { key: string, v: string }

func Kv.get(key: string): string | null
func Kv.set(key: string, v: string): void
func Kv.pairs(): Array[Kv.Pair]
`,
		Funcs: map[string]ant.HostFunc{
			"get": func(rt ant.Runtime, args []value.Value) (value.Value, error) {
				if v, ok := store[args[0].(string)]; ok {
					return v, nil
				}
				return value.Null, nil
			},
			"set": func(rt ant.Runtime, args []value.Value) (value.Value, error) {
				store[args[0].(string)] = args[1].(string)
				return value.Void, nil
			},
			"pairs": func(rt ant.Runtime, args []value.Value) (value.Value, error) {
				// The program holds the tag of Kv.Pair; a record needs that one.
				pair, _ := rt.Tag("Kv.Pair")
				var pairs []value.Value
				for _, key := range slices.Sorted(maps.Keys(store)) {
					pairs = append(pairs, value.NewRecord(pair, []value.Value{key, store[key]}))
				}
				return value.NewArray(pairs), nil
			},
		},
	}
	src := `
Kv.set("greeting", "hi")
println(Kv.get("greeting") ?? "missing")
println(Kv.get("other") ?? "missing")
for p in Kv.pairs() { println("${p.key} = ${p.v}") }
`
	prog, err := ant.Load("main.ant", ant.WithSource("main.ant", src), ant.WithNamespace(kv), ant.WithoutNamespaces("File", "Http"))
	if err != nil {
		fmt.Println(err)
		return
	}
	if err := prog.Run(context.Background(), ant.WithStdout(os.Stdout)); err != nil {
		fmt.Println(err)
	}
}
Output:
hi
missing
greeting = hi
Example (Run)

Running a program from a string, with its output captured.

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/ant-src/ant"
)

func main() {
	src := `
for name in Os.args() { println("hello, ${name}") }
`
	prog, err := ant.Load("main.ant", ant.WithSource("main.ant", src))
	if err != nil {
		fmt.Println(err)
		return
	}
	var out strings.Builder
	err = prog.Run(context.Background(), ant.WithStdout(&out), ant.WithArgs([]string{"ada", "linus"}))
	fmt.Print(out.String())
	fmt.Println("exit status", ant.ExitStatus(err))
}
Output:
hello, ada
hello, linus
exit status 0

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInterrupted = interp.ErrInterrupted

ErrInterrupted is what Run returns when an interrupt ended the run: one the program had not asked for, or the second. ExitStatus gives it 130, as a shell gives a process a signal ended.

Functions

func ExitStatus

func ExitStatus(err error) int

ExitStatus maps the error returned by Load or Run to the exit status the ant command uses: 0 for nil, 2 for a LoadError, 1 for a PanicError or a ResultError, the status of an ExitError, and 1 for any other error.

func Incomplete

func Incomplete(src string) bool

Incomplete reports whether src ends too early to be one input, so a REPL should keep reading: an open brace, bracket, string, or raw string.

func IsTestFile

func IsTestFile(path string) bool

IsTestFile reports whether path names a test file, whose name ends in _test.ant.

func TestPattern

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

TestPattern compiles a -run or -skip pattern of ant test: one regular expression per level of a full name, split on each / that is not escaped with a backslash or inside brackets or parentheses.

Types

type Completion

type Completion struct {
	Label string // the name, as a list shows it
	// Insert is the text to write: the label, or more where the position asks for it, as a
	// named argument gets its colon and a directory its slash.
	Insert string
	// Kind says what it is: "variable", "function", "field", "type", "namespace", "module",
	// "constant", "keyword", "file", or "folder".
	Kind string
	// Detail is what hover would show beside it: a function's parameters and result, a
	// variable's type, or what a name is.
	Detail string
	// Preferred marks an item the position asks for first: a parameter the call has not been
	// given, or a field the record literal lacks.
	Preferred bool
}

A Completion is one thing that can be written at a position of an input, as Complete lists them.

type Diagnostic

type Diagnostic struct {
	Pos Position
	// End is where the expression the diagnostic is about ends, when it names one, and Pos is
	// its start; else its Line is 0.
	End     Position
	Message string
	// Code names the rule the diagnostic reports, such as "type-mismatch" (spec/check.md
	// section 3). It is empty for a failure that is not about the program, such as a prelude
	// that does not load.
	Code string
	// Severity is "error", or "warning" for code the checker accepts that is almost always a
	// mistake (spec/check.md section 4).
	Severity string
	// Help says how to fix it, when the message does not; Fixes are edits that would, and
	// Related are other places that explain it.
	Help    string
	Fixes   []Fix
	Related []Related
}

Diagnostic is one error found while loading or checking a program.

func Check added in v0.3.0

func Check(paths []string, opts ...Option) (diags []Diagnostic, loaded bool)

Check checks the programs rooted at paths together: the module at each path and every module it imports, each module once however many paths reach it. A path ending in .d.ant is a declaration file, checked on its own. A program that does not load, as Load reports, is not checked, and its load errors are returned in its place; the others are still checked. Check returns every error sorted by path and position, and whether every program loaded.

func Errors added in v0.3.0

func Errors(diags []Diagnostic) []Diagnostic

Errors is the diagnostics of diags that are errors, without the warnings.

func (Diagnostic) Error

func (d Diagnostic) Error() string

type Edit added in v0.3.0

type Edit struct {
	Start, End Position
	Text       string
}

Edit replaces the text from Start up to End, both in Start's file, with Text.

type ExitError

type ExitError struct {
	Status int
}

ExitError is returned by Run when the program called Os.exit.

func (*ExitError) Error

func (e *ExitError) Error() string

type Fix added in v0.3.0

type Fix struct {
	Title string
	Auto  bool
	Edits []Edit
}

Fix is a set of edits that removes a diagnostic. Auto marks one that is safe to apply unread (spec/check.md section 2, Help and fixes).

type Frame

type Frame struct {
	Function string
	Pos      Position
}

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

type Func

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

A Func is an Ant function callable from Go.

func (*Func) Call

func (f *Func) Call(args ...value.Value) (value.Value, error)

Call calls the function with positional arguments. An Ant panic comes back as a *PanicError, after being reported to the instance's stderr; Os.exit as an *ExitError. Strings in the arguments that are not UTF-8 are decoded as value.Text does, in place.

func (*Func) Value

func (f *Func) Value() value.Value

Value returns the function as an Ant value, for passing to other calls.

type HostFunc

type HostFunc func(rt Runtime, args []value.Value) (value.Value, error)

A HostFunc is a Go function Ant code can call. It receives its arguments positionally, in the order its signature lists them. An error it returns becomes an Ant panic with the error's message; a nil result is void. Every string in the result that is not UTF-8 is decoded as value.Text does, in place, since an Ant string holds only scalar values; binary data travels as *value.Bytes, which is kept as it is. Bytes a host function returns are the caller's, as the standard library's are: make them with value.CopyBytes, or with value.NewBytes from a slice the host gives up. Bytes it receives it only reads during the call, or copies with Snapshot.

type Instance

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

An Instance is a started program: its modules are initialized and its functions can be called from Go until Close.

func (*Instance) Close

func (in *Instance) Close()

Close stops the instance's goroutines.

func (*Instance) Func

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

Func returns a top-level function of the root module, or false when there is none.

func (*Instance) Value

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

Value returns a top-level value of the root module, such as a var or a type's tag.

type LoadError

type LoadError struct {
	Diagnostics []Diagnostic
}

LoadError reports why a program could not be loaded: a syntax error, a missing module, an import cycle, or a missing main. The ant command exits with status 2.

func (*LoadError) Error

func (e *LoadError) Error() string

type Namespace

type Namespace struct {
	// Name is the namespace's name, bound in every module like a prelude name.
	Name string
	// Signatures declares the functions and types as a declaration file does (section 10,
	// Declaration files), every name qualified by the namespace, though without constants or
	// field defaults, which only the standard library fills, for example:
	//
	//	func Db.query(sql: string, args: Array[string]): Result[Array[Db.Row], Error]
	//	type Db.Row = Map[string, string]
	//
	// The checker types calls from them; the runtime takes parameter names from them. Kept in
	// a declaration file beside the script, and embedded from it, they are also what ant check
	// and an editor read for the script with no host running; the host's own, given here, are
	// then the ones its programs use (section 10, Declaration files).
	Signatures string
	// Funcs maps each function's name, without the namespace, to its implementation.
	Funcs map[string]HostFunc
}

Namespace is a set of host functions and types that Ant code reaches as Name.function, the way it reaches the standard library.

type Option

type Option func(*config)

An Option configures Load, Run, or both. Options given to Run override those given to Load.

func WithArgs

func WithArgs(args []string) Option

WithArgs sets what Os.args returns.

func WithEnv

func WithEnv(lookup func(name string) (string, bool)) Option

WithEnv sets what Os.env consults. The default is os.LookupEnv. Os.environ and the environment a child of a Cmd inherits stay the process's; WithEnvironment replaces all three.

func WithEnvironment

func WithEnvironment(vars map[string]string) Option

WithEnvironment gives the run its whole environment: what Os.env and Os.environ see, and what a child of a Cmd inherits when it is given no env of its own.

func WithFS

func WithFS(fsys fs.FS) Option

WithFS reads sources from fsys instead of the operating system. Paths are then fs.FS paths: slash-separated and relative to the root of fsys.

func WithForeground

func WithForeground(hold func() (release func(ended os.Signal) (interrupt bool))) Option

WithForeground tells the host when Cmd.run has a child in the foreground: hold is called as the child starts, and the function it returns as the child exits, with the signal that ended it or nil. That function reports whether the run gets an interrupt for it, which Cmd.run delivers before it returns, as WithInterrupts would. The ant command holds back Ctrl-C meanwhile, which the child gets from the terminal, and passes it on only when the child died of it. Without it Cmd.run holds nothing back.

func WithInterrupts

func WithInterrupts(c <-chan struct{}) Option

WithInterrupts delivers interrupts to a run, an instance, or a session, one per value the host sends on c. The first goes to the context Os.interrupt returns, when the program has called it and the context is not done, so the program can drain and exit; otherwise, and for a program that never called it, an interrupt ends the run, and Run, the Func.Call or the Session.Eval in progress returns ErrInterrupted. The ant command sends one per Ctrl-C or SIGTERM.

func WithNamespace

func WithNamespace(ns Namespace) Option

WithNamespace adds a host namespace to a program.

func WithSource

func WithSource(path, src string) Option

WithSource supplies the text of the module at path, overriding whatever the file system holds, so a program can be loaded from a string.

func WithStderr

func WithStderr(w io.Writer) Option

WithStderr sets where panic reports are written. The default is os.Stderr.

func WithStdin

func WithStdin(r io.Reader) Option

WithStdin sets what Os.stdin reads. The default is os.Stdin.

func WithStdout

func WithStdout(w io.Writer) Option

WithStdout sets where print, println and Os.stdout write. The default is os.Stdout.

func WithoutNamespaces

func WithoutNamespaces(names ...string) Option

WithoutNamespaces removes prelude namespaces from a program, such as File or Http, so a script cannot reach them. Removing Os removes Cmd too, since a Cmd runs with the process's streams and environment.

type PanicError

type PanicError struct {
	Message string
	Trace   []Frame
}

PanicError is returned by Run when a panic ended the main goroutine. The runtime has already written the message and trace to the run's stderr writer. The ant command exits with status 1.

func (*PanicError) Error

func (e *PanicError) Error() string

type Position

type Position struct {
	Path string
	Line int
	Col  int
}

Position is a location in a source file. Line and Col are 1-based; Col counts bytes.

func (Position) String

func (p Position) String() string

type Program

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

A Program is a loaded, parsed, and resolved module graph. It is immutable.

func Load

func Load(path string, opts ...Option) (*Program, error)

Load parses the module at path and every module it imports. It returns a *LoadError when a module has a syntax error, cannot be found, takes part in an import cycle, or is a script that another module imports. A path ending in .d.ant is a declaration file (section 10, Declaration files), which Check checks and Run refuses.

func (*Program) Check

func (p *Program) Check() []Diagnostic

Check type-checks every module of the program, including code nothing calls, and returns the errors sorted by position. A program with no diagnostics is well typed.

func (*Program) Run

func (p *Program) Run(ctx context.Context, opts ...Option) error

Run executes the program: it initializes every module in dependency order, the root last, which for a script runs its body. It returns nil when the script ends, a *ResultError when it returns an Err, a *PanicError when the main goroutine panics, an *ExitError when the program calls Os.exit, and ctx.Err() when the context is cancelled first.

It returns a *LoadError, and runs nothing, for a program that cannot run: one whose root is a test file or a declaration file, or which reads a name that only a host's declaration file declares (section 10, Declaration files). Load accepts such a program because Check checks it.

A panic and a returned Err are the program's own output, and the run writes them to its standard error. Any other error is returned and not written: a host that wants it shown prints it.

func (*Program) Start

func (p *Program) Start(ctx context.Context, opts ...Option) (*Instance, error)

Start initializes the program's modules, the root last, and returns an Instance to call into. A root that is a script runs its body here, as Run would; a library runs only its initializers. The options given to Load apply, and options given here override them. It returns a *LoadError for a program that cannot run, as Run does.

func (*Program) Tag added in v0.3.3

func (p *Program) Tag(name string) (*value.Tag, bool)

Tag returns the tag of a record type of the program's prelude, as Runtime.Tag does, for a host that builds the arguments of a Func.Call outside any host function. The tags of a namespace's types are made anew by each Load, so two programs given the same Namespace do not share them.

func (*Program) Test

func (p *Program) Test(ctx context.Context, cfg TestConfig, opts ...Option) error

Test runs the tests of a program whose root is a test file (section 10, Tests): it initializes the modules, then runs each test, reporting events to cfg.Report. 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 ctx.Err() when the context ended first.

type Related struct {
	Pos     Position
	Message string
}

Related is another place that explains a diagnostic.

type ResultError

type ResultError struct {
	Message string
}

ResultError is returned by Run when the script returned an Err, through try or return (section 10). Message is the Err's error field, an Error as its message alone and any other error as String.from renders it, which the runtime has already written to the run's stderr writer, with a newline. The ant command exits with status 1.

func (*ResultError) Error

func (e *ResultError) Error() string

type Runtime

type Runtime interface {
	// Call calls an Ant function value with positional arguments.
	//
	// Whatever ends the call early unwinds through the host function as a Go panic: an Ant
	// panic, Os.exit, and the end of a run that was cancelled or interrupted. Use defer for
	// cleanup, and let the panic go on: the run ends as it would have without the host function.
	// When a library stands between the call and the host function and recovers panics, as an
	// event loop does to restore a terminal, it would keep the unwinding from the run. Recover
	// first, in the callback the library calls, keep the value, have the library return, and
	// panic with the value again in the host function:
	//
	//	var unwound any
	//	loop.OnEvent(func(e Event) {
	//		defer func() {
	//			if r := recover(); r != nil {
	//				unwound = r
	//				loop.Stop()
	//			}
	//		}()
	//		rt.Call(handler, toValue(e))
	//	})
	//	loop.Run()
	//	if unwound != nil {
	//		panic(unwound)
	//	}
	//
	// Call is for one caller at a time, while the host function that was given the Runtime has
	// not returned. It may be called from another Go goroutine that the host function waits
	// for, and what unwinds does so on that goroutine, to be carried back the same way. Two
	// calls at once on one Runtime are a data race.
	Call(fn value.Value, args ...value.Value) value.Value
	// Context is the run's context; blocking host functions should observe it.
	Context() context.Context
	// Tag returns the tag of a record type of the prelude, for value.NewRecord: a type one of
	// the program's namespaces declares, as "Db.Row", or one of the standard library's, as
	// "Cmd.Output". A record takes part in is and in field access only under the tag the
	// program holds, so one made with value.NewTag is of no type the program knows. It is false
	// for a name that is not a record type.
	Tag(name string) (*value.Tag, bool)
}

Runtime is what a host function sees of the running program.

type Session

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

A Session evaluates one input at a time on a persistent module, which is what the REPL is built on. Each input may hold declarations and statements; declarations accumulate, a name may be declared again, imports stay in force, and goroutines keep running between inputs.

func NewSession

func NewSession(ctx context.Context, opts ...Option) (*Session, error)

NewSession creates a session. The options are those of Load and Run.

func (*Session) Close

func (s *Session) Close()

Close stops the session's goroutines.

func (*Session) Complete

func (s *Session) Complete(src string, off int) []Completion

Complete lists what can be written at byte offset off of src, the input being typed, as the language server's completion does: the names the session has declared, with their types, the imports in force, the prelude, and what the position allows, as the members after a dot, the functions that take the left side after a pipe, the parameters of a call, and the keywords. After a dot it also offers the fields of the record a variable of the session holds at runtime, read through its fields, which a union's static type does not promise. The items are unsorted.

func (*Session) Eval

func (s *Session) Eval(src string) (value.Value, error)

Eval evaluates one input and returns the value of its last expression, or void, which _ reads in the inputs after it unless it is void (section 10, Scripts). The input is a script body of its own: the value it returns, by return or ?? return, is its result, and an Err it returns, as try does, comes back as a *ResultError after being reported. A syntax or scope error comes back as a *LoadError, a panic as a *PanicError after being reported.

func (*Session) EvalFile

func (s *Session) EvalFile(path string) (value.Value, error)

EvalFile evaluates the file at path as an input of the session, its relative imports resolved against its own directory, and returns what Eval returns.

func (*Session) TypeOf

func (s *Session) TypeOf(expr string) (string, error)

TypeOf returns the type the checker gives expr, an expression over what the session has declared, as the checker writes it; _ in it stands for the expression whose value it reads. A syntax error, or a type error in expr, comes back as a *LoadError, positioned in expr.

func (*Session) Value

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

Value returns a name the session has declared, or for _ the last result.

type TestConfig

type TestConfig struct {
	// File labels the events: the test file's path as the runner found it.
	File string
	// Run and Skip hold one regular expression per level of a test's full name (the -run and
	// -skip flags of ant test); 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. It may be shared
	// by the runs of several files.
	Stop *atomic.Bool
	// Report receives every event, one at a time, from any goroutine.
	Report func(TestEvent)
}

TestConfig configures Program.Test.

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 run (test.md).

type TestEventKind

type TestEventKind int

TestEventKind is what a TestEvent reports.

const (
	TestRun    TestEventKind = iota // a test starts
	TestOutput                      // a test printed Output
	TestPass                        // a test passed
	TestFail                        // a test failed; Message holds its failures, "" when only subtests failed
	TestSkip                        // a test was skipped; Message holds the reason
)

Directories

Path Synopsis
Package ast declares the syntax tree of an Ant module, as the parser builds it and the resolver annotates it.
Package ast declares the syntax tree of an Ant module, as the parser builds it and the resolver annotates it.
cmd
ant command
Command ant runs, checks, and evaluates Ant programs.
Command ant runs, checks, and evaluates Ant programs.
Package docs holds the pages of the documentation that the ant command prints itself.
Package docs holds the pages of the documentation that the ant command prints itself.
examples
host command
Command host is the example of docs/guide/embedding.md: a Go program that runs an Ant script and gives it a namespace of its own, App.
Command host is the example of docs/guide/embedding.md: a Go program that runs an Ant script and gives it a namespace of its own, App.
internal
batch
Package batch coalesces what a run writes for a host to which each write is costly, such as a debug adapter sending an event per write or a page posted a message per write.
Package batch coalesces what a run writes for a host to which each write is costly, such as a debug adapter sending an event per write or a page posted a message per write.
check
Package check is the type checker (sections 4 through 8 and 10 of the specification).
Package check is the type checker (sections 4 through 8 and 10 of the specification).
codes
Package codes names the rules a diagnostic of ant check can report (spec/check.md section 3).
Package codes names the rules a diagnostic of ant check can report (spec/check.md section 3).
dap
Package dap is ant dap, the debug adapter: it serves the Debug Adapter Protocol on a stream and runs one program under the interpreter's debugger, in its own process.
Package dap is ant dap, the debug adapter: it serves the Debug Adapter Protocol on a stream and runs one program under the interpreter's debugger, in its own process.
diag
Package diag finds what a diagnostic is about in its source, and prints it as ant check does: the position and the message, then the lines it covers with the span underlined.
Package diag finds what a diagnostic is about in its source, and prints it as ant check does: the position and the message, then the lines it covers with the span underlined.
doc
Package doc prints declarations with their doc comments, as ant doc does (spec/doc.md).
Package doc prints declarations with their doc comments, as ant doc does (spec/doc.md).
format
Package format lays out Ant source as spec/fmt.md describes: it reprints the tokens, comments, and line breaks of a module, changing only whitespace, statement semicolons, and trailing commas.
Package format lays out Ant source as spec/fmt.md describes: it reprints the tokens, comments, and line breaks of a module, changing only whitespace, statement semicolons, and trailing commas.
frame
Package frame reads and writes messages framed by a Content-Length header, as the Language Server Protocol and the Debug Adapter Protocol frame them.
Package frame reads and writes messages framed by a Content-Length header, as the Language Server Protocol and the Debug Adapter Protocol frame them.
grapheme
Package grapheme splits text into extended grapheme clusters by the rules of Unicode's UAX #29, for String.graphemes (section 11, String).
Package grapheme splits text into extended grapheme clusters by the rules of Unicode's UAX #29, for String.graphemes (section 11, String).
highlight
Package highlight classifies the bytes of Ant source for coloring, as the REPL colors its input and ant check its code snippets.
Package highlight classifies the bytes of Ant source for coloring, as the REPL colors its input and ant check its code snippets.
interp
Package interp evaluates a loaded program (section 12).
Package interp evaluates a loaded program (section 12).
lexer
Package lexer turns Ant source into tokens, applying the line-ending rule of section 2.
Package lexer turns Ant source into tokens, applying the line-ending rule of section 2.
lib
Package lib implements the standard library (section 11 and stdlib.md) as builtins, and builds the prelude table that binds every prelude name.
Package lib implements the standard library (section 11 and stdlib.md) as builtins, and builds the prelude table that binds every prelude name.
loader
Package loader reads a program's modules, parses and resolves them, and orders them for initialization (section 10).
Package loader reads a program's modules, parses and resolves them, and orders them for initialization (section 10).
lsp
Package lsp is the language server behind ant lsp: it speaks the Language Server Protocol over a stream, analyzing each open document as the root of its own program.
Package lsp is the language server behind ant lsp: it speaks the Language Server Protocol over a stream, analyzing each open document as the root of its own program.
lsp/htmldata
Package htmldata lists the elements and attributes of HTML for completion in markup (section 5, HTML expressions).
Package htmldata lists the elements and attributes of HTML for completion in markup (section 5, HTML expressions).
near
Package near finds the names close to a misspelled one, for the help of the checker and of ant doc.
Package near finds the names close to a misspelled one, for the help of the checker and of ant doc.
prelude
Package prelude lists the names the prelude binds in every module (sections 10 and 11).
Package prelude lists the names the prelude binds in every module (sections 10 and 11).
repl
Package repl is the read-eval-print loop a bare ant command runs.
Package repl is the read-eval-print loop a bare ant command runs.
resolve
Package resolve annotates a parsed module: every identifier gets a reference, every binding a slot, and every scope its size.
Package resolve annotates a parsed module: every identifier gets a reference, every binding a slot, and every scope its size.
temporal
Package temporal implements the time values of stdlib.md's Time namespace after JavaScript's Temporal: an Instant on the time line, a ZonedDateTime in a zone, the plain wall-clock types, zones, and durations, with nanosecond precision and Temporal's range of 100 million days each way from the epoch.
Package temporal implements the time values of stdlib.md's Time namespace after JavaScript's Temporal: an Instant on the time line, a ZonedDateTime in a zone, the plain wall-clock types, zones, and durations, with nanosecond precision and Temporal's range of 100 million days each way from the epoch.
temporal/gen command
Command gen writes zones_gen.go, the zone table of package temporal, from three published files: tzdata.zi, the compact form of the IANA time zone database that systems ship under zoneinfo (its Z lines are the zones and its L lines the links to them), which gives every name; CLDR's bcp47/timezone.xml, whose alias groups say which names are one zone, as Temporal's implementations canonicalize, so that Asia/Calcutta equals Asia/Kolkata while Europe/Stockholm stays apart from Europe/Berlin although the IANA database has merged their rules since 1970; and CLDR's windowsZones.xml, which maps Windows zone names to IANA names.
Command gen writes zones_gen.go, the zone table of package temporal, from three published files: tzdata.zi, the compact form of the IANA time zone database that systems ship under zoneinfo (its Z lines are the zones and its L lines the links to them), which gives every name; CLDR's bcp47/timezone.xml, whose alias groups say which names are one zone, as Temporal's implementations canonicalize, so that Asia/Calcutta equals Asia/Kolkata while Europe/Stockholm stays apart from Europe/Berlin although the IANA database has merged their rules since 1970; and CLDR's windowsZones.xml, which maps Windows zone names to IANA names.
token
Package token defines the tokens the lexer produces and the parser consumes.
Package token defines the tokens the lexer produces and the parser consumes.
types
Package types is the checker's type language (section 4): primitives, null, void, never, arrays, maps, sets, functions, anonymous records, named types, type parameters, and unions.
Package types is the checker's type language (section 4): primitives, null, void, never, arrays, maps, sets, functions, anonymous records, named types, type parameters, and unions.
Package parser builds the syntax tree of an Ant module.
Package parser builds the syntax tree of an Ant module.
Package value defines Ant's run-time values (section 12): their kinds, the tags of named types, records, tagged primitives, arrays, maps, functions, and sync objects, together with equality, hashing, rendering, arithmetic, and conversions.
Package value defines Ant's run-time values (section 12): their kinds, the tags of named types, records, tagged primitives, arrays, maps, functions, and sync objects, together with equality, hashing, rendering, arithmetic, and conversions.
Command wasm is Ant compiled to WebAssembly for JavaScript hosts, browsers and Node: the @ant-lang/wasm package loads it.
Command wasm is Ant compiled to WebAssembly for JavaScript hosts, browsers and Node: the @ant-lang/wasm package loads it.

Jump to

Keyboard shortcuts

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