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
|
package eval
import (
"fmt"
"sort"
"strconv"
"strings"
"unsafe"
"src.elv.sh/pkg/diag"
"src.elv.sh/pkg/eval/errs"
"src.elv.sh/pkg/eval/vals"
"src.elv.sh/pkg/eval/vars"
"src.elv.sh/pkg/parse"
"src.elv.sh/pkg/persistent/hash"
)
// Closure is a function defined with Elvish code. Each Closure has its unique
// identity.
type Closure struct {
ArgNames []string
// The index of the rest argument. -1 if there is no rest argument.
RestArg int
OptNames []string
OptDefaults []any
Src parse.Source
DefRange diag.Ranging
op effectOp
newLocal []staticVarInfo
captured *Ns
}
var (
_ Callable = &Closure{}
_ vals.PseudoMap = &Closure{}
)
// Kind returns "fn".
func (*Closure) Kind() string {
return "fn"
}
// Equal compares by address.
func (c *Closure) Equal(rhs any) bool {
return c == rhs
}
// Hash returns the hash of the address of the closure.
func (c *Closure) Hash() uint32 {
return hash.Pointer(unsafe.Pointer(c))
}
// Call calls a closure.
func (c *Closure) Call(fm *Frame, args []any, opts map[string]any) error {
// Check number of arguments.
if c.RestArg != -1 {
if len(args) < len(c.ArgNames)-1 {
return errs.ArityMismatch{What: "arguments",
ValidLow: len(c.ArgNames) - 1, ValidHigh: -1, Actual: len(args)}
}
} else {
if len(args) != len(c.ArgNames) {
return errs.ArityMismatch{What: "arguments",
ValidLow: len(c.ArgNames), ValidHigh: len(c.ArgNames), Actual: len(args)}
}
}
// Check whether all supplied options are supported. This map contains the
// subset of keys from opts that can be found in c.OptNames.
optSupported := make(map[string]struct{})
for _, name := range c.OptNames {
_, ok := opts[name]
if ok {
optSupported[name] = struct{}{}
}
}
if len(optSupported) < len(opts) {
// Report all the options that are not supported.
unsupported := make([]string, 0, len(opts)-len(optSupported))
for name := range opts {
_, supported := optSupported[name]
if !supported {
unsupported = append(unsupported, parse.Quote(name))
}
}
sort.Strings(unsupported)
return UnsupportedOptionsError{unsupported}
}
// This Frame is dedicated to the current form, so we can modify it in place.
// BUG(xiaq): When evaluating closures, async access to global variables
// and ports can be problematic.
// Make upvalue namespace and capture variables.
fm.up = c.captured
// Populate local scope with arguments, options, and newly created locals.
localSize := len(c.ArgNames) + len(c.OptNames) + len(c.newLocal)
local := &Ns{make([]vars.Var, localSize), make([]staticVarInfo, localSize)}
for i, name := range c.ArgNames {
local.infos[i] = staticVarInfo{name, false, false}
}
if c.RestArg == -1 {
for i := range c.ArgNames {
local.slots[i] = vars.FromInit(args[i])
}
} else {
for i := 0; i < c.RestArg; i++ {
local.slots[i] = vars.FromInit(args[i])
}
restOff := len(args) - len(c.ArgNames)
local.slots[c.RestArg] = vars.FromInit(
vals.MakeList(args[c.RestArg : c.RestArg+restOff+1]...))
for i := c.RestArg + 1; i < len(c.ArgNames); i++ {
local.slots[i] = vars.FromInit(args[i+restOff])
}
}
offset := len(c.ArgNames)
for i, name := range c.OptNames {
v, ok := opts[name]
if !ok {
v = c.OptDefaults[i]
}
local.infos[offset+i] = staticVarInfo{name, false, false}
local.slots[offset+i] = vars.FromInit(v)
}
offset += len(c.OptNames)
for i, info := range c.newLocal {
local.infos[offset+i] = info
// TODO: Take info.readOnly into account too when creating variable
local.slots[offset+i] = MakeVarFromName(info.name)
}
fm.local = local
fm.src = c.Src
fm.defers = new([]func(*Frame) Exception)
exc := c.op.exec(fm)
excDefer := fm.runDefers()
// TODO: Combine exc and excDefer if both are not nil
if excDefer != nil && exc == nil {
exc = excDefer
}
return exc
}
// MakeVarFromName creates a Var with a suitable type constraint inferred from
// the name.
func MakeVarFromName(name string) vars.Var {
switch {
case strings.HasSuffix(name, FnSuffix):
val := nopGoFn
return vars.FromPtr(&val)
case strings.HasSuffix(name, NsSuffix):
val := &Ns{}
return vars.FromPtr(&val)
default:
return vars.FromInit(nil)
}
}
// UnsupportedOptionsError is an error returned by a closure call when there are
// unsupported options.
type UnsupportedOptionsError struct {
Options []string
}
func (er UnsupportedOptionsError) Error() string {
if len(er.Options) == 1 {
return fmt.Sprintf("unsupported option: %s", er.Options[0])
}
return fmt.Sprintf("unsupported options: %s", strings.Join(er.Options, ", "))
}
func (c *Closure) Fields() vals.StructMap { return closureFields{c} }
type closureFields struct{ c *Closure }
func (closureFields) IsStructMap() {}
func (cf closureFields) ArgNames() vals.List { return vals.MakeListSlice(cf.c.ArgNames) }
func (cf closureFields) RestArg() string { return strconv.Itoa(cf.c.RestArg) }
func (cf closureFields) OptNames() vals.List { return vals.MakeListSlice(cf.c.OptNames) }
func (cf closureFields) Src() parse.Source { return cf.c.Src }
func (cf closureFields) OptDefaults() vals.List {
return vals.MakeList(cf.c.OptDefaults...)
}
func (cf closureFields) Body() string {
r := cf.c.op.(diag.Ranger).Range()
return cf.c.Src.Code[r.From:r.To]
}
func (cf closureFields) Def() string {
return cf.c.Src.Code[cf.c.DefRange.From:cf.c.DefRange.To]
}
|