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 (a string type of its own; never decoded)
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")
a 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 instance, since the program declares it: the Example_call test builds a Point that way. 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"
"os"
"github.com/ant-src/ant"
"github.com/ant-src/ant/value"
)
func main() {
store := map[string]string{}
kv := ant.Namespace{
Name: "Kv",
Signatures: `
func Kv.get(key: string): string | null
func Kv.set(key: string, v: string): void
`,
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
},
},
}
src := `
Kv.set("greeting", "hi")
println(Kv.get("greeting") ?? "missing")
println(Kv.get("other") ?? "missing")
`
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
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 ¶
- Variables
- func ExitStatus(err error) int
- func Incomplete(src string) bool
- func IsTestFile(path string) bool
- func TestPattern(s string) ([]*regexp.Regexp, error)
- type Completion
- type Diagnostic
- type ExitError
- type Frame
- type Func
- type HostFunc
- type Instance
- type LoadError
- type Namespace
- type Option
- func WithArgs(args []string) Option
- func WithEnv(lookup func(name string) (string, bool)) Option
- func WithEnvironment(vars map[string]string) Option
- func WithFS(fsys fs.FS) Option
- func WithForeground(hold func() (release func(ended os.Signal) (interrupt bool))) Option
- func WithInterrupts(c <-chan struct{}) Option
- func WithNamespace(ns Namespace) Option
- func WithSource(path, src string) Option
- func WithStderr(w io.Writer) Option
- func WithStdin(r io.Reader) Option
- func WithStdout(w io.Writer) Option
- func WithoutNamespaces(names ...string) Option
- type PanicError
- type Position
- type Program
- type ResultError
- type Runtime
- type Session
- func (s *Session) Close()
- func (s *Session) Complete(src string, off int) []Completion
- func (s *Session) Eval(src string) (value.Value, error)
- func (s *Session) EvalFile(path string) (value.Value, error)
- func (s *Session) TypeOf(expr string) (string, error)
- func (s *Session) Value(name string) (value.Value, bool)
- type TestConfig
- type TestEvent
- type TestEventKind
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 ¶
IsTestFile reports whether path names a test file, whose name ends in _test.ant.
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 ¶
Diagnostic is one error found while loading or checking a program.
func (Diagnostic) Error ¶
func (d Diagnostic) Error() string
type ExitError ¶
type ExitError struct {
Status int
}
ExitError is returned by Run when the program called Os.exit.
type Func ¶
type Func struct {
// contains filtered or unexported fields
}
A Func is an Ant function callable from Go.
type HostFunc ¶
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.
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.
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.
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.
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 WithEnv ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithNamespace adds a host namespace to a program.
func WithSource ¶
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 ¶
WithStderr sets where panic reports are written. The default is os.Stderr.
func WithStdout ¶
WithStdout sets where print, println and Os.stdout write. The default is os.Stdout.
func WithoutNamespaces ¶
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 ¶
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 ¶
Position is a location in a source file. Line and Col are 1-based; Col counts bytes.
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 ¶
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 ¶
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.
func (*Program) Start ¶
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.
func (*Program) Test ¶
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 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. An Ant panic raised inside
// unwinds through the host function as a Go panic, so use defer for any cleanup.
Call(fn value.Value, args ...value.Value) value.Value
// Context is the run's context; blocking host functions should observe it.
Context() context.Context
}
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 ¶
NewSession creates a session. The options are those of Load and Run.
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 (spec/lsp.md section 4): 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 ¶
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 ¶
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.
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"
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. |
|
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). |
|
dap
Package dap is ant dap, the debug adapter (spec/dap.md): 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 (spec/dap.md): 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 (spec/lsp.md and spec/dap.md, section 1).
|
Package frame reads and writes messages framed by a Content-Length header, as the Language Server Protocol and the Debug Adapter Protocol frame them (spec/lsp.md and spec/dap.md, section 1). |
|
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 (spec/lsp.md): 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 (spec/lsp.md): 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). |
|
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. |