Repository navigation
Expand file tree
/
Copy pathhost.go
More file actions
287 lines (266 loc) · 11 KB
/
Copy pathhost.go
File metadata and controls
287 lines (266 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package ant
import (
"context"
"fmt"
"slices"
"strings"
"ant-lang.org/ast"
"ant-lang.org/internal/check"
"ant-lang.org/internal/interp"
"ant-lang.org/internal/lib"
"ant-lang.org/parser"
"ant-lang.org/value"
)
// Runtime is what a host function sees of the running program.
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)
}
// 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 HostFunc func(rt Runtime, args []value.Value) (value.Value, error)
// Namespace is a set of host functions and types that Ant code reaches as Name.function, the
// way it reaches the standard library.
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
}
// WithNamespace adds a host namespace to a program.
func WithNamespace(ns Namespace) Option {
return func(c *config) { c.namespaces = append(c.namespaces, ns) }
}
// 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.
func WithoutNamespaces(names ...string) Option {
return func(c *config) {
for _, name := range names {
c.removed = append(c.removed, name)
c.removed = append(c.removed, goesWith[name]...)
}
}
}
// goesWith lists the prelude names a removed namespace takes with it.
var goesWith = map[string][]string{"Os": {"Cmd"}}
// build parses a namespace's signatures and binds its functions.
func (ns Namespace) build() (value.Value, *ast.File, error) {
f, err := parser.Parse("namespace "+ns.Name, ns.Signatures, parser.Declarations)
if err != nil {
return nil, nil, fmt.Errorf("namespace %s: %v", ns.Name, err)
}
var fields []string
var vals []value.Value
seen := map[string]bool{}
for _, d := range f.Decls {
switch d := d.(type) {
case *ast.FuncDecl:
if d.Owner != ns.Name {
return nil, nil, fmt.Errorf("namespace %s: func %s must be declared as %s.%s", ns.Name, d.Name, ns.Name, d.Name)
}
impl, ok := ns.Funcs[d.Name]
if !ok {
return nil, nil, fmt.Errorf("namespace %s: no implementation for %s", ns.Name, d.Name)
}
params := make([]string, len(d.Params))
for i, p := range d.Params {
params[i] = p.Name
}
optional := 0
for i := len(d.Params) - 1; i >= 0 && d.Params[i].Default != nil; i-- {
optional++
}
fields = append(fields, d.Name)
vals = append(vals, &interp.Builtin{Name: ns.Name + "." + d.Name, Params: params, Optional: optional, Fn: hostBuiltin(impl)})
seen[d.Name] = true
case *ast.TypeDecl:
if d.Owner != ns.Name {
return nil, nil, fmt.Errorf("namespace %s: type %s must be declared as %s.%s", ns.Name, d.Name, ns.Name, d.Name)
}
if rt, ok := d.Body.(*ast.RecordType); ok && slices.ContainsFunc(rt.Fields, func(f ast.FieldType) bool { return f.Default != nil }) {
// only the standard library fills field defaults natively
return nil, nil, fmt.Errorf("namespace %s: type %s.%s gives a field a default, which a host namespace cannot fill", ns.Name, ns.Name, d.Name)
}
fields = append(fields, d.Name)
vals = append(vals, interp.TypeValue(d, nil))
case *ast.VarDecl:
return nil, nil, fmt.Errorf("namespace %s: a host namespace declares no constants; declare a function that returns the value", ns.Name)
default:
return nil, nil, fmt.Errorf("namespace %s: only func and type declarations are allowed", ns.Name)
}
}
for name := range ns.Funcs {
if !seen[name] {
return nil, nil, fmt.Errorf("namespace %s: %s has no signature", ns.Name, name)
}
}
tag := value.NewTag(ns.Name, value.RecordTag, fields)
return value.NewRecord(tag, vals), f, nil
}
func hostBuiltin(impl HostFunc) func(*interp.Goroutine, []value.Value) value.Value {
return func(g *interp.Goroutine, args []value.Value) value.Value {
v, err := impl(g, args)
if err != nil {
g.Panic("%s", strings.TrimSpace(err.Error()))
}
if v == nil {
return value.Void
}
return value.TextIn(v) // text from the host is outside text (section 11, String)
}
}
// prelude builds the table of prelude names for a program: the standard library, less the
// removed namespaces, plus the host namespaces.
func (c config) prelude() (map[string]value.Value, []string, []check.HostNamespace, error) {
table := make(map[string]value.Value, len(lib.Prelude())+len(c.namespaces))
for k, v := range lib.Prelude() {
table[k] = v
}
for _, name := range c.removed {
delete(table, name)
}
var extra []string
var decls []check.HostNamespace
for _, ns := range c.namespaces {
v, f, err := ns.build()
if err != nil {
return nil, nil, nil, err
}
table[ns.Name] = v
extra = append(extra, ns.Name)
decls = append(decls, check.HostNamespace{Name: ns.Name, Decls: f})
}
return table, extra, decls, nil
}
// 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 (p *Program) Tag(name string) (*value.Tag, bool) { return interp.RecordTag(p.prelude, name) }
// An Instance is a started program: its modules are initialized and its functions can be
// called from Go until Close.
type Instance struct {
in *interp.Instance
}
// 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 (p *Program) Start(ctx context.Context, opts ...Option) (*Instance, error) {
if err := p.runnable(); err != nil {
return nil, err
}
in, err := interp.Start(ctx, p.prog, p.cfg.with(opts).run(p.prelude))
if err != nil {
return nil, convertRunError(err)
}
return &Instance{in: in}, nil
}
// Func returns a top-level function of the root module, or false when there is none.
func (in *Instance) Func(name string) (*Func, bool) {
v, ok := in.in.Lookup(name)
if !ok {
return nil, false
}
if _, ok := v.(value.Callable); !ok {
return nil, false
}
return &Func{in: in.in, v: v, name: name}, true
}
// Value returns a top-level value of the root module, such as a var or a type's tag.
func (in *Instance) Value(name string) (value.Value, bool) { return in.in.Lookup(name) }
// Close stops the instance's goroutines.
func (in *Instance) Close() { in.in.Close() }
// A Func is an Ant function callable from Go.
type Func struct {
in *interp.Instance
v value.Value
name string
}
// 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 (f *Func) Call(args ...value.Value) (value.Value, error) {
for i, a := range args {
args[i] = value.TextIn(a) // text from the host is outside text (section 11, String)
}
v, err := f.in.Call(f.v, args...)
if err != nil {
return nil, convertRunError(err)
}
return v, nil
}
// Value returns the function as an Ant value, for passing to other calls.
func (f *Func) Value() value.Value { return f.v }
func convertRunError(err error) error {
switch e := err.(type) {
case nil:
return nil
case *interp.PanicError:
trace := make([]Frame, len(e.Trace))
for i, f := range e.Trace {
trace[i] = Frame{Function: f.Function, Pos: Position{Path: f.Path, Line: f.Pos.Line, Col: f.Pos.Col}}
}
return &PanicError{Message: e.Message, Trace: trace}
case *interp.ExitError:
return &ExitError{Status: e.Status}
case *interp.ResultError:
return &ResultError{Message: e.Message}
}
return err
}