| 1 |
// Copyright 2017 The Bazel Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package starlark |
| 6 |
|
| 7 |
import ( |
| 8 |
"fmt" |
| 9 |
"io" |
| 10 |
"log" |
| 11 |
"math/big" |
| 12 |
"math/bits" |
| 13 |
"sort" |
| 14 |
"strings" |
| 15 |
"sync/atomic" |
| 16 |
"time" |
| 17 |
"unicode" |
| 18 |
"unicode/utf8" |
| 19 |
|
| 20 |
"go.starlark.net/internal/compile" |
| 21 |
"go.starlark.net/internal/spell" |
| 22 |
"go.starlark.net/resolve" |
| 23 |
"go.starlark.net/syntax" |
| 24 |
) |
| 25 |
|
| 26 |
// A Thread contains the state of a Starlark thread, |
| 27 |
// such as its call stack and thread-local storage. |
| 28 |
// The Thread is threaded throughout the evaluator. |
| 29 |
type Thread struct { |
| 30 |
// Name is an optional name that describes the thread, for debugging. |
| 31 |
Name string |
| 32 |
|
| 33 |
// stack is the stack of (internal) call frames. |
| 34 |
stack []*frame |
| 35 |
|
| 36 |
// Print is the client-supplied implementation of the Starlark |
| 37 |
// 'print' function. If nil, fmt.Fprintln(os.Stderr, msg) is |
| 38 |
// used instead. |
| 39 |
Print func(thread *Thread, msg string) |
| 40 |
|
| 41 |
// Load is the client-supplied implementation of module loading. |
| 42 |
// Repeated calls with the same module name must return the same |
| 43 |
// module environment or error. |
| 44 |
// The error message need not include the module name. |
| 45 |
// |
| 46 |
// See example_test.go for some example implementations of Load. |
| 47 |
Load func(thread *Thread, module string) (StringDict, error) |
| 48 |
|
| 49 |
// OnMaxSteps is called when the thread reaches the limit set by SetMaxExecutionSteps. |
| 50 |
// The default behavior is to call thread.Cancel("too many steps"). |
| 51 |
OnMaxSteps func(thread *Thread) |
| 52 |
|
| 53 |
// Steps a count of abstract computation steps executed |
| 54 |
// by this thread. It is incremented by the interpreter. It may be used |
| 55 |
// as a measure of the approximate cost of Starlark execution, by |
| 56 |
// computing the difference in its value before and after a computation. |
| 57 |
// |
| 58 |
// The precise meaning of "step" is not specified and may change. |
| 59 |
Steps, maxSteps uint64 |
| 60 |
|
| 61 |
// cancelReason records the reason from the first call to Cancel. |
| 62 |
cancelReason atomic.Pointer[string] |
| 63 |
|
| 64 |
// locals holds arbitrary "thread-local" Go values belonging to the client. |
| 65 |
// They are accessible to the client but not to any Starlark program. |
| 66 |
locals map[string]any |
| 67 |
|
| 68 |
// proftime holds the accumulated execution time since the last profile event. |
| 69 |
proftime time.Duration |
| 70 |
} |
| 71 |
|
| 72 |
// ExecutionSteps returns the current value of Steps. |
| 73 |
func (thread *Thread) ExecutionSteps() uint64 { |
| 74 |
return thread.Steps |
| 75 |
} |
| 76 |
|
| 77 |
// SetMaxExecutionSteps sets a limit on the number of Starlark |
| 78 |
// computation steps that may be executed by this thread. If the |
| 79 |
// thread's step counter exceeds this limit, the interpreter calls |
| 80 |
// the optional OnMaxSteps function or the default behavior |
| 81 |
// of calling thread.Cancel("too many steps"). |
| 82 |
func (thread *Thread) SetMaxExecutionSteps(max uint64) { |
| 83 |
thread.maxSteps = max |
| 84 |
} |
| 85 |
|
| 86 |
// Uncancel resets the cancellation state. |
| 87 |
// |
| 88 |
// Unlike most methods of Thread, it is safe to call Uncancel from any |
| 89 |
// goroutine, even if the thread is actively executing. |
| 90 |
func (thread *Thread) Uncancel() { |
| 91 |
thread.cancelReason.Store(nil) |
| 92 |
} |
| 93 |
|
| 94 |
// Cancel causes execution of Starlark code in the specified thread to |
| 95 |
// promptly fail with an EvalError that includes the specified reason. |
| 96 |
// There may be a delay before the interpreter observes the cancellation |
| 97 |
// if the thread is currently in a call to a built-in function. |
| 98 |
// |
| 99 |
// Call [Uncancel] to reset the cancellation state. |
| 100 |
// |
| 101 |
// Unlike most methods of Thread, it is safe to call Cancel from any |
| 102 |
// goroutine, even if the thread is actively executing. |
| 103 |
func (thread *Thread) Cancel(reason string) { |
| 104 |
// Atomically set cancelReason, preserving earlier reason if any. |
| 105 |
thread.cancelReason.CompareAndSwap(nil, &reason) |
| 106 |
} |
| 107 |
|
| 108 |
// SetLocal sets the thread-local value associated with the specified key. |
| 109 |
// It must not be called after execution begins. |
| 110 |
func (thread *Thread) SetLocal(key string, value any) { |
| 111 |
if thread.locals == nil { |
| 112 |
thread.locals = make(map[string]any) |
| 113 |
} |
| 114 |
thread.locals[key] = value |
| 115 |
} |
| 116 |
|
| 117 |
// Local returns the thread-local value associated with the specified key. |
| 118 |
func (thread *Thread) Local(key string) any { |
| 119 |
return thread.locals[key] |
| 120 |
} |
| 121 |
|
| 122 |
// CallFrame returns a copy of the specified frame of the callstack. |
| 123 |
// It should only be used in built-ins called from Starlark code. |
| 124 |
// Depth 0 means the frame of the built-in itself, 1 is its caller, and so on. |
| 125 |
// |
| 126 |
// It is equivalent to CallStack().At(depth), but more efficient. |
| 127 |
func (thread *Thread) CallFrame(depth int) CallFrame { |
| 128 |
return thread.frameAt(depth).asCallFrame() |
| 129 |
} |
| 130 |
|
| 131 |
func (thread *Thread) frameAt(depth int) *frame { |
| 132 |
return thread.stack[len(thread.stack)-1-depth] |
| 133 |
} |
| 134 |
|
| 135 |
// CallStack returns a new slice containing the thread's stack of call frames. |
| 136 |
func (thread *Thread) CallStack() CallStack { |
| 137 |
frames := make([]CallFrame, len(thread.stack)) |
| 138 |
for i, fr := range thread.stack { |
| 139 |
frames[i] = fr.asCallFrame() |
| 140 |
} |
| 141 |
return frames |
| 142 |
} |
| 143 |
|
| 144 |
// CallStackDepth returns the number of frames in the current call stack. |
| 145 |
func (thread *Thread) CallStackDepth() int { return len(thread.stack) } |
| 146 |
|
| 147 |
// A StringDict is a mapping from names to values, and represents |
| 148 |
// an environment such as the global variables of a module. |
| 149 |
// It is not a true starlark.Value. |
| 150 |
type StringDict map[string]Value |
| 151 |
|
| 152 |
// Keys returns a new sorted slice of d's keys. |
| 153 |
func (d StringDict) Keys() []string { |
| 154 |
names := make([]string, 0, len(d)) |
| 155 |
for name := range d { |
| 156 |
names = append(names, name) |
| 157 |
} |
| 158 |
sort.Strings(names) |
| 159 |
return names |
| 160 |
} |
| 161 |
|
| 162 |
func (d StringDict) String() string { |
| 163 |
buf := new(strings.Builder) |
| 164 |
buf.WriteByte('{') |
| 165 |
sep := "" |
| 166 |
for _, name := range d.Keys() { |
| 167 |
buf.WriteString(sep) |
| 168 |
buf.WriteString(name) |
| 169 |
buf.WriteString(": ") |
| 170 |
writeValue(buf, d[name], nil) |
| 171 |
sep = ", " |
| 172 |
} |
| 173 |
buf.WriteByte('}') |
| 174 |
return buf.String() |
| 175 |
} |
| 176 |
|
| 177 |
func (d StringDict) Freeze() { |
| 178 |
for _, v := range d { |
| 179 |
v.Freeze() |
| 180 |
} |
| 181 |
} |
| 182 |
|
| 183 |
// Has reports whether the dictionary contains the specified key. |
| 184 |
func (d StringDict) Has(key string) bool { _, ok := d[key]; return ok } |
| 185 |
|
| 186 |
// A frame records a call to a Starlark function (including module toplevel) |
| 187 |
// or a built-in function or method. |
| 188 |
type frame struct { |
| 189 |
callable Callable // current function (or toplevel) or built-in |
| 190 |
pc uint32 // program counter (Starlark frames only) |
| 191 |
locals []Value // local variables (Starlark frames only) |
| 192 |
spanStart int64 // start time of current profiler span |
| 193 |
} |
| 194 |
|
| 195 |
// Position returns the source position of the current point of execution in this frame. |
| 196 |
func (fr *frame) Position() syntax.Position { |
| 197 |
switch c := fr.callable.(type) { |
| 198 |
case *Function: |
| 199 |
// Starlark function |
| 200 |
return c.funcode.Position(fr.pc) |
| 201 |
case callableWithPosition: |
| 202 |
// If a built-in Callable defines |
| 203 |
// a Position method, use it. |
| 204 |
return c.Position() |
| 205 |
} |
| 206 |
return syntax.MakePosition(&builtinFilename, 0, 0) |
| 207 |
} |
| 208 |
|
| 209 |
var builtinFilename = "<builtin>" |
| 210 |
|
| 211 |
// Function returns the frame's function or built-in. |
| 212 |
func (fr *frame) Callable() Callable { return fr.callable } |
| 213 |
|
| 214 |
// A CallStack is a stack of call frames, outermost first. |
| 215 |
type CallStack []CallFrame |
| 216 |
|
| 217 |
// At returns a copy of the frame at depth i. |
| 218 |
// At(0) returns the topmost frame. |
| 219 |
func (stack CallStack) At(i int) CallFrame { return stack[len(stack)-1-i] } |
| 220 |
|
| 221 |
// Pop removes and returns the topmost frame. |
| 222 |
func (stack *CallStack) Pop() CallFrame { |
| 223 |
last := len(*stack) - 1 |
| 224 |
top := (*stack)[last] |
| 225 |
*stack = (*stack)[:last] |
| 226 |
return top |
| 227 |
} |
| 228 |
|
| 229 |
// String returns a user-friendly description of the stack. |
| 230 |
func (stack CallStack) String() string { |
| 231 |
out := new(strings.Builder) |
| 232 |
if len(stack) > 0 { |
| 233 |
fmt.Fprintf(out, "Traceback (most recent call last):\n") |
| 234 |
} |
| 235 |
for _, fr := range stack { |
| 236 |
fmt.Fprintf(out, " %s: in %s\n", fr.Pos, fr.Name) |
| 237 |
} |
| 238 |
return out.String() |
| 239 |
} |
| 240 |
|
| 241 |
// An EvalError is a Starlark evaluation error and |
| 242 |
// a copy of the thread's stack at the moment of the error. |
| 243 |
type EvalError struct { |
| 244 |
Msg string |
| 245 |
CallStack CallStack |
| 246 |
cause error |
| 247 |
} |
| 248 |
|
| 249 |
// A CallFrame represents the function name and current |
| 250 |
// position of execution of an enclosing call frame. |
| 251 |
type CallFrame struct { |
| 252 |
Name string |
| 253 |
Pos syntax.Position |
| 254 |
} |
| 255 |
|
| 256 |
func (fr *frame) asCallFrame() CallFrame { |
| 257 |
return CallFrame{ |
| 258 |
Name: fr.Callable().Name(), |
| 259 |
Pos: fr.Position(), |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
func (thread *Thread) evalError(err error) *EvalError { |
| 264 |
return &EvalError{ |
| 265 |
Msg: err.Error(), |
| 266 |
CallStack: thread.CallStack(), |
| 267 |
cause: err, |
| 268 |
} |
| 269 |
} |
| 270 |
|
| 271 |
func (e *EvalError) Error() string { return e.Msg } |
| 272 |
|
| 273 |
// Backtrace returns a user-friendly error message describing the stack |
| 274 |
// of calls that led to this error. |
| 275 |
func (e *EvalError) Backtrace() string { |
| 276 |
// If the topmost stack frame is a built-in function, |
| 277 |
// remove it from the stack and add print "Error in fn:". |
| 278 |
stack := e.CallStack |
| 279 |
suffix := "" |
| 280 |
if last := len(stack) - 1; last >= 0 && stack[last].Pos.Filename() == builtinFilename { |
| 281 |
suffix = " in " + stack[last].Name |
| 282 |
stack = stack[:last] |
| 283 |
} |
| 284 |
return fmt.Sprintf("%sError%s: %s", stack, suffix, e.Msg) |
| 285 |
} |
| 286 |
|
| 287 |
func (e *EvalError) Unwrap() error { return e.cause } |
| 288 |
|
| 289 |
// A Program is a compiled Starlark program. |
| 290 |
// |
| 291 |
// Programs are immutable, and contain no Values. |
| 292 |
// A Program may be created by parsing a source file (see SourceProgram) |
| 293 |
// or by loading a previously saved compiled program (see CompiledProgram). |
| 294 |
type Program struct { |
| 295 |
compiled *compile.Program |
| 296 |
} |
| 297 |
|
| 298 |
// CompilerVersion is the version number of the protocol for compiled |
| 299 |
// files. Applications must not run programs compiled by one version |
| 300 |
// with an interpreter at another version, and should thus incorporate |
| 301 |
// the compiler version into the cache key when reusing compiled code. |
| 302 |
const CompilerVersion = compile.Version |
| 303 |
|
| 304 |
// Filename returns the name of the file from which this program was loaded. |
| 305 |
func (prog *Program) Filename() string { return prog.compiled.Toplevel.Pos.Filename() } |
| 306 |
|
| 307 |
func (prog *Program) String() string { return prog.Filename() } |
| 308 |
|
| 309 |
// NumLoads returns the number of load statements in the compiled program. |
| 310 |
func (prog *Program) NumLoads() int { return len(prog.compiled.Loads) } |
| 311 |
|
| 312 |
// Load(i) returns the name and position of the i'th module directly |
| 313 |
// loaded by this one, where 0 <= i < NumLoads(). |
| 314 |
// The name is unresolved---exactly as it appears in the source. |
| 315 |
func (prog *Program) Load(i int) (string, syntax.Position) { |
| 316 |
id := prog.compiled.Loads[i] |
| 317 |
return id.Name, id.Pos |
| 318 |
} |
| 319 |
|
| 320 |
// WriteTo writes the compiled module to the specified output stream. |
| 321 |
func (prog *Program) Write(out io.Writer) error { |
| 322 |
data := prog.compiled.Encode() |
| 323 |
_, err := out.Write(data) |
| 324 |
return err |
| 325 |
} |
| 326 |
|
| 327 |
// ExecFile calls [ExecFileOptions] using [syntax.LegacyFileOptions]. |
| 328 |
// |
| 329 |
// Deprecated: use [ExecFileOptions] with [syntax.FileOptions] instead, |
| 330 |
// because this function relies on legacy global variables. |
| 331 |
func ExecFile(thread *Thread, filename string, src any, predeclared StringDict) (StringDict, error) { |
| 332 |
return ExecFileOptions(syntax.LegacyFileOptions(), thread, filename, src, predeclared) |
| 333 |
} |
| 334 |
|
| 335 |
// ExecFileOptions parses, resolves, and executes a Starlark file in the |
| 336 |
// specified global environment, which may be modified during execution. |
| 337 |
// |
| 338 |
// Thread is the state associated with the Starlark thread. |
| 339 |
// |
| 340 |
// The filename and src parameters are as for syntax.Parse: |
| 341 |
// filename is the name of the file to execute, |
| 342 |
// and the name that appears in error messages; |
| 343 |
// src is an optional source of bytes to use |
| 344 |
// instead of filename. |
| 345 |
// |
| 346 |
// predeclared defines the predeclared names specific to this module. |
| 347 |
// Execution does not modify this dictionary, though it may mutate |
| 348 |
// its values. |
| 349 |
// |
| 350 |
// If ExecFileOptions fails during evaluation, it returns an *EvalError |
| 351 |
// containing a backtrace. |
| 352 |
func ExecFileOptions(opts *syntax.FileOptions, thread *Thread, filename string, src any, predeclared StringDict) (StringDict, error) { |
| 353 |
// Parse, resolve, and compile a Starlark source file. |
| 354 |
_, mod, err := SourceProgramOptions(opts, filename, src, predeclared.Has) |
| 355 |
if err != nil { |
| 356 |
return nil, err |
| 357 |
} |
| 358 |
|
| 359 |
g, err := mod.Init(thread, predeclared) |
| 360 |
g.Freeze() |
| 361 |
return g, err |
| 362 |
} |
| 363 |
|
| 364 |
// SourceProgram calls [SourceProgramOptions] using [syntax.LegacyFileOptions]. |
| 365 |
// |
| 366 |
// Deprecated: use [SourceProgramOptions] with [syntax.FileOptions] instead, |
| 367 |
// because this function relies on legacy global variables. |
| 368 |
func SourceProgram(filename string, src any, isPredeclared func(string) bool) (*syntax.File, *Program, error) { |
| 369 |
return SourceProgramOptions(syntax.LegacyFileOptions(), filename, src, isPredeclared) |
| 370 |
} |
| 371 |
|
| 372 |
// SourceProgramOptions produces a new program by parsing, resolving, |
| 373 |
// and compiling a Starlark source file. |
| 374 |
// On success, it returns the parsed file and the compiled program. |
| 375 |
// The filename and src parameters are as for syntax.Parse. |
| 376 |
// |
| 377 |
// The isPredeclared predicate reports whether a name is |
| 378 |
// a pre-declared identifier of the current module. |
| 379 |
// Its typical value is predeclared.Has, |
| 380 |
// where predeclared is a StringDict of pre-declared values. |
| 381 |
func SourceProgramOptions(opts *syntax.FileOptions, filename string, src any, isPredeclared func(string) bool) (*syntax.File, *Program, error) { |
| 382 |
f, err := opts.Parse(filename, src, 0) |
| 383 |
if err != nil { |
| 384 |
return nil, nil, err |
| 385 |
} |
| 386 |
prog, err := FileProgram(f, isPredeclared) |
| 387 |
return f, prog, err |
| 388 |
} |
| 389 |
|
| 390 |
// FileProgram produces a new program by resolving, |
| 391 |
// and compiling the Starlark source file syntax tree. |
| 392 |
// On success, it returns the compiled program. |
| 393 |
// |
| 394 |
// Resolving a syntax tree mutates it. |
| 395 |
// Do not call FileProgram more than once on the same file. |
| 396 |
// |
| 397 |
// The isPredeclared predicate reports whether a name is |
| 398 |
// a pre-declared identifier of the current module. |
| 399 |
// Its typical value is predeclared.Has, |
| 400 |
// where predeclared is a StringDict of pre-declared values. |
| 401 |
func FileProgram(f *syntax.File, isPredeclared func(string) bool) (*Program, error) { |
| 402 |
if err := resolve.File(f, isPredeclared, Universe.Has); err != nil { |
| 403 |
return nil, err |
| 404 |
} |
| 405 |
|
| 406 |
var pos syntax.Position |
| 407 |
if len(f.Stmts) > 0 { |
| 408 |
pos = syntax.Start(f.Stmts[0]) |
| 409 |
} else { |
| 410 |
pos = syntax.MakePosition(&f.Path, 1, 1) |
| 411 |
} |
| 412 |
|
| 413 |
module := f.Module.(*resolve.Module) |
| 414 |
compiled := compile.File(f.Options, f.Stmts, pos, "<toplevel>", module.Locals, module.Globals) |
| 415 |
|
| 416 |
return &Program{compiled}, nil |
| 417 |
} |
| 418 |
|
| 419 |
// CompiledProgram produces a new program from the representation |
| 420 |
// of a compiled program previously saved by Program.Write. |
| 421 |
func CompiledProgram(in io.Reader) (*Program, error) { |
| 422 |
data, err := io.ReadAll(in) |
| 423 |
if err != nil { |
| 424 |
return nil, err |
| 425 |
} |
| 426 |
compiled, err := compile.DecodeProgram(data) |
| 427 |
if err != nil { |
| 428 |
return nil, err |
| 429 |
} |
| 430 |
return &Program{compiled}, nil |
| 431 |
} |
| 432 |
|
| 433 |
// Init creates a set of global variables for the program, |
| 434 |
// executes the toplevel code of the specified program, |
| 435 |
// and returns a new, unfrozen dictionary of the globals. |
| 436 |
func (prog *Program) Init(thread *Thread, predeclared StringDict) (StringDict, error) { |
| 437 |
toplevel := makeToplevelFunction(prog, predeclared) |
| 438 |
|
| 439 |
_, err := Call(thread, toplevel, nil, nil) |
| 440 |
|
| 441 |
// Convert the global environment to a map. |
| 442 |
// We return a (partial) map even in case of error. |
| 443 |
return toplevel.Globals(), err |
| 444 |
} |
| 445 |
|
| 446 |
// ExecREPLChunk compiles and executes file f in the specified thread |
| 447 |
// and global environment. This is a variant of ExecFile specialized to |
| 448 |
// the needs of a REPL, in which a sequence of input chunks, each |
| 449 |
// syntactically a File, manipulates the same set of module globals, |
| 450 |
// which are not frozen after execution. |
| 451 |
// |
| 452 |
// This function is intended to support only go.starlark.net/repl. |
| 453 |
// Its API stability is not guaranteed. |
| 454 |
func ExecREPLChunk(f *syntax.File, thread *Thread, globals StringDict) error { |
| 455 |
var predeclared StringDict |
| 456 |
|
| 457 |
// -- variant of FileProgram -- |
| 458 |
|
| 459 |
if err := resolve.REPLChunk(f, globals.Has, predeclared.Has, Universe.Has); err != nil { |
| 460 |
return err |
| 461 |
} |
| 462 |
|
| 463 |
var pos syntax.Position |
| 464 |
if len(f.Stmts) > 0 { |
| 465 |
pos = syntax.Start(f.Stmts[0]) |
| 466 |
} else { |
| 467 |
pos = syntax.MakePosition(&f.Path, 1, 1) |
| 468 |
} |
| 469 |
|
| 470 |
module := f.Module.(*resolve.Module) |
| 471 |
compiled := compile.File(f.Options, f.Stmts, pos, "<toplevel>", module.Locals, module.Globals) |
| 472 |
prog := &Program{compiled} |
| 473 |
|
| 474 |
// -- variant of Program.Init -- |
| 475 |
|
| 476 |
toplevel := makeToplevelFunction(prog, predeclared) |
| 477 |
|
| 478 |
// Initialize module globals from parameter. |
| 479 |
for i, id := range prog.compiled.Globals { |
| 480 |
if v := globals[id.Name]; v != nil { |
| 481 |
toplevel.module.globals[i] = v |
| 482 |
} |
| 483 |
} |
| 484 |
|
| 485 |
_, err := Call(thread, toplevel, nil, nil) |
| 486 |
|
| 487 |
// Reflect changes to globals back to parameter, even after an error. |
| 488 |
for i, id := range prog.compiled.Globals { |
| 489 |
if v := toplevel.module.globals[i]; v != nil { |
| 490 |
globals[id.Name] = v |
| 491 |
} |
| 492 |
} |
| 493 |
|
| 494 |
return err |
| 495 |
} |
| 496 |
|
| 497 |
func makeToplevelFunction(prog *Program, predeclared StringDict) *Function { |
| 498 |
// Create the Starlark value denoted by each program constant c. |
| 499 |
constants := make([]Value, len(prog.compiled.Constants)) |
| 500 |
for i, c := range prog.compiled.Constants { |
| 501 |
var v Value |
| 502 |
switch c := c.(type) { |
| 503 |
case int64: |
| 504 |
v = MakeInt64(c) |
| 505 |
case *big.Int: |
| 506 |
v = MakeBigInt(c) |
| 507 |
case string: |
| 508 |
v = String(c) |
| 509 |
case compile.Bytes: |
| 510 |
v = Bytes(c) |
| 511 |
case float64: |
| 512 |
v = Float(c) |
| 513 |
default: |
| 514 |
log.Panicf("unexpected constant %T: %v", c, c) |
| 515 |
} |
| 516 |
constants[i] = v |
| 517 |
} |
| 518 |
|
| 519 |
return &Function{ |
| 520 |
funcode: prog.compiled.Toplevel, |
| 521 |
module: &Module{ |
| 522 |
program: prog, |
| 523 |
predeclared: predeclared, |
| 524 |
globals: make([]Value, len(prog.compiled.Globals)), |
| 525 |
constants: constants, |
| 526 |
}, |
| 527 |
} |
| 528 |
} |
| 529 |
|
| 530 |
// Eval calls [EvalOptions] using [syntax.LegacyFileOptions]. |
| 531 |
// |
| 532 |
// Deprecated: use [EvalOptions] with [syntax.FileOptions] instead, |
| 533 |
// because this function relies on legacy global variables. |
| 534 |
func Eval(thread *Thread, filename string, src any, env StringDict) (Value, error) { |
| 535 |
return EvalOptions(syntax.LegacyFileOptions(), thread, filename, src, env) |
| 536 |
} |
| 537 |
|
| 538 |
// EvalOptions parses, resolves, and evaluates an expression within the |
| 539 |
// specified (predeclared) environment. |
| 540 |
// |
| 541 |
// Evaluation cannot mutate the environment dictionary itself, |
| 542 |
// though it may modify variables reachable from the dictionary. |
| 543 |
// |
| 544 |
// The filename and src parameters are as for syntax.Parse. |
| 545 |
// |
| 546 |
// If EvalOptions fails during evaluation, it returns an *EvalError |
| 547 |
// containing a backtrace. |
| 548 |
func EvalOptions(opts *syntax.FileOptions, thread *Thread, filename string, src any, env StringDict) (Value, error) { |
| 549 |
expr, err := opts.ParseExpr(filename, src, 0) |
| 550 |
if err != nil { |
| 551 |
return nil, err |
| 552 |
} |
| 553 |
f, err := makeExprFunc(opts, expr, env) |
| 554 |
if err != nil { |
| 555 |
return nil, err |
| 556 |
} |
| 557 |
return Call(thread, f, nil, nil) |
| 558 |
} |
| 559 |
|
| 560 |
// EvalExpr calls [EvalExprOptions] using [syntax.LegacyFileOptions]. |
| 561 |
// |
| 562 |
// Deprecated: use [EvalExprOptions] with [syntax.FileOptions] instead, |
| 563 |
// because this function relies on legacy global variables. |
| 564 |
func EvalExpr(thread *Thread, expr syntax.Expr, env StringDict) (Value, error) { |
| 565 |
return EvalExprOptions(syntax.LegacyFileOptions(), thread, expr, env) |
| 566 |
} |
| 567 |
|
| 568 |
// EvalExprOptions resolves and evaluates an expression within the |
| 569 |
// specified (predeclared) environment. |
| 570 |
// Evaluating a comma-separated list of expressions yields a tuple value. |
| 571 |
// |
| 572 |
// Resolving an expression mutates it. |
| 573 |
// Do not call EvalExprOptions more than once for the same expression. |
| 574 |
// |
| 575 |
// Evaluation cannot mutate the environment dictionary itself, |
| 576 |
// though it may modify variables reachable from the dictionary. |
| 577 |
// |
| 578 |
// If EvalExprOptions fails during evaluation, it returns an *EvalError |
| 579 |
// containing a backtrace. |
| 580 |
func EvalExprOptions(opts *syntax.FileOptions, thread *Thread, expr syntax.Expr, env StringDict) (Value, error) { |
| 581 |
fn, err := makeExprFunc(opts, expr, env) |
| 582 |
if err != nil { |
| 583 |
return nil, err |
| 584 |
} |
| 585 |
return Call(thread, fn, nil, nil) |
| 586 |
} |
| 587 |
|
| 588 |
// ExprFunc calls [ExprFuncOptions] using [syntax.LegacyFileOptions]. |
| 589 |
// |
| 590 |
// Deprecated: use [ExprFuncOptions] with [syntax.FileOptions] instead, |
| 591 |
// because this function relies on legacy global variables. |
| 592 |
func ExprFunc(filename string, src any, env StringDict) (*Function, error) { |
| 593 |
return ExprFuncOptions(syntax.LegacyFileOptions(), filename, src, env) |
| 594 |
} |
| 595 |
|
| 596 |
// ExprFunc returns a no-argument function |
| 597 |
// that evaluates the expression whose source is src. |
| 598 |
func ExprFuncOptions(options *syntax.FileOptions, filename string, src any, env StringDict) (*Function, error) { |
| 599 |
expr, err := options.ParseExpr(filename, src, 0) |
| 600 |
if err != nil { |
| 601 |
return nil, err |
| 602 |
} |
| 603 |
return makeExprFunc(options, expr, env) |
| 604 |
} |
| 605 |
|
| 606 |
// makeExprFunc returns a no-argument function whose body is expr. |
| 607 |
// The options must be consistent with those used when parsing expr. |
| 608 |
func makeExprFunc(opts *syntax.FileOptions, expr syntax.Expr, env StringDict) (*Function, error) { |
| 609 |
locals, err := resolve.ExprOptions(opts, expr, env.Has, Universe.Has) |
| 610 |
if err != nil { |
| 611 |
return nil, err |
| 612 |
} |
| 613 |
|
| 614 |
prog := compile.Expr(opts, expr, "<expr>", locals) |
| 615 |
return makeToplevelFunction(&Program{prog}, env), nil |
| 616 |
} |
| 617 |
|
| 618 |
// The following functions are primitive operations of the byte code interpreter. |
| 619 |
|
| 620 |
// list += iterable |
| 621 |
func listExtend(x *List, y Iterable) { |
| 622 |
if ylist, ok := y.(*List); ok { |
| 623 |
// fast path: list += list |
| 624 |
x.elems = append(x.elems, ylist.elems...) |
| 625 |
} else { |
| 626 |
iter := y.Iterate() |
| 627 |
defer iter.Done() |
| 628 |
var z Value |
| 629 |
for iter.Next(&z) { |
| 630 |
x.elems = append(x.elems, z) |
| 631 |
} |
| 632 |
} |
| 633 |
} |
| 634 |
|
| 635 |
// getAttr implements x.dot. |
| 636 |
func getAttr(x Value, name string) (Value, error) { |
| 637 |
hasAttr, ok := x.(HasAttrs) |
| 638 |
if !ok { |
| 639 |
return nil, fmt.Errorf("%s has no .%s field or method", x.Type(), name) |
| 640 |
} |
| 641 |
|
| 642 |
var errmsg string |
| 643 |
v, err := hasAttr.Attr(name) |
| 644 |
if err == nil { |
| 645 |
if v != nil { |
| 646 |
return v, nil // success |
| 647 |
} |
| 648 |
// (nil, nil) => generic error |
| 649 |
errmsg = fmt.Sprintf("%s has no .%s field or method", x.Type(), name) |
| 650 |
} else if nsa, ok := err.(NoSuchAttrError); ok { |
| 651 |
errmsg = string(nsa) |
| 652 |
} else { |
| 653 |
return nil, err // return error as is |
| 654 |
} |
| 655 |
|
| 656 |
// add spelling hint |
| 657 |
if n := spell.Nearest(name, hasAttr.AttrNames()); n != "" { |
| 658 |
errmsg = fmt.Sprintf("%s (did you mean .%s?)", errmsg, n) |
| 659 |
} |
| 660 |
|
| 661 |
return nil, fmt.Errorf("%s", errmsg) |
| 662 |
} |
| 663 |
|
| 664 |
// setField implements x.name = y. |
| 665 |
func setField(x Value, name string, y Value) error { |
| 666 |
if x, ok := x.(HasSetField); ok { |
| 667 |
err := x.SetField(name, y) |
| 668 |
if is[NoSuchAttrError](err) { |
| 669 |
// No such field: check spelling. |
| 670 |
if n := spell.Nearest(name, x.AttrNames()); n != "" { |
| 671 |
err = fmt.Errorf("%s (did you mean .%s?)", err, n) |
| 672 |
} |
| 673 |
} |
| 674 |
return err |
| 675 |
} |
| 676 |
|
| 677 |
return fmt.Errorf("can't assign to .%s field of %s", name, x.Type()) |
| 678 |
} |
| 679 |
|
| 680 |
// getIndex implements x[y]. |
| 681 |
func getIndex(x, y Value) (Value, error) { |
| 682 |
switch x := x.(type) { |
| 683 |
case Mapping: // dict |
| 684 |
z, found, err := x.Get(y) |
| 685 |
if err != nil { |
| 686 |
return nil, err |
| 687 |
} |
| 688 |
if !found { |
| 689 |
return nil, fmt.Errorf("key %v not in %s", y, x.Type()) |
| 690 |
} |
| 691 |
return z, nil |
| 692 |
|
| 693 |
case Indexable: // string, list, tuple |
| 694 |
n := x.Len() |
| 695 |
i, err := AsInt32(y) |
| 696 |
if err != nil { |
| 697 |
return nil, fmt.Errorf("%s index: %s", x.Type(), err) |
| 698 |
} |
| 699 |
origI := i |
| 700 |
if i < 0 { |
| 701 |
i += n |
| 702 |
} |
| 703 |
if i < 0 || i >= n { |
| 704 |
return nil, outOfRange(origI, n, x) |
| 705 |
} |
| 706 |
return x.Index(i), nil |
| 707 |
} |
| 708 |
return nil, fmt.Errorf("unhandled index operation %s[%s]", x.Type(), y.Type()) |
| 709 |
} |
| 710 |
|
| 711 |
func outOfRange(i, n int, x Value) error { |
| 712 |
if n == 0 { |
| 713 |
return fmt.Errorf("index %d out of range: empty %s", i, x.Type()) |
| 714 |
} else { |
| 715 |
return fmt.Errorf("%s index %d out of range [%d:%d]", x.Type(), i, -n, n-1) |
| 716 |
} |
| 717 |
} |
| 718 |
|
| 719 |
// setIndex implements x[y] = z. |
| 720 |
func setIndex(x, y, z Value) error { |
| 721 |
switch x := x.(type) { |
| 722 |
case HasSetKey: |
| 723 |
if err := x.SetKey(y, z); err != nil { |
| 724 |
return err |
| 725 |
} |
| 726 |
|
| 727 |
case HasSetIndex: |
| 728 |
n := x.Len() |
| 729 |
i, err := AsInt32(y) |
| 730 |
if err != nil { |
| 731 |
return err |
| 732 |
} |
| 733 |
origI := i |
| 734 |
if i < 0 { |
| 735 |
i += n |
| 736 |
} |
| 737 |
if i < 0 || i >= n { |
| 738 |
return outOfRange(origI, n, x) |
| 739 |
} |
| 740 |
return x.SetIndex(i, z) |
| 741 |
|
| 742 |
default: |
| 743 |
return fmt.Errorf("%s value does not support item assignment", x.Type()) |
| 744 |
} |
| 745 |
return nil |
| 746 |
} |
| 747 |
|
| 748 |
// Unary applies a unary operator (+, -, ~, not) to its operand. |
| 749 |
func Unary(op syntax.Token, x Value) (Value, error) { |
| 750 |
// The NOT operator is not customizable. |
| 751 |
if op == syntax.NOT { |
| 752 |
return !x.Truth(), nil |
| 753 |
} |
| 754 |
|
| 755 |
// Int, Float, and user-defined types |
| 756 |
if x, ok := x.(HasUnary); ok { |
| 757 |
// (nil, nil) => unhandled |
| 758 |
y, err := x.Unary(op) |
| 759 |
if y != nil || err != nil { |
| 760 |
return y, err |
| 761 |
} |
| 762 |
} |
| 763 |
|
| 764 |
return nil, fmt.Errorf("unknown unary op: %s %s", op, x.Type()) |
| 765 |
} |
| 766 |
|
| 767 |
// Binary applies a strict binary operator (not AND or OR) to its operands. |
| 768 |
// For equality tests or ordered comparisons, use Compare instead. |
| 769 |
func Binary(op syntax.Token, x, y Value) (Value, error) { |
| 770 |
switch op { |
| 771 |
case syntax.PLUS: |
| 772 |
switch x := x.(type) { |
| 773 |
case String: |
| 774 |
if y, ok := y.(String); ok { |
| 775 |
return x + y, nil |
| 776 |
} |
| 777 |
case Bytes: |
| 778 |
if y, ok := y.(Bytes); ok { |
| 779 |
return x + y, nil |
| 780 |
} |
| 781 |
case Int: |
| 782 |
switch y := y.(type) { |
| 783 |
case Int: |
| 784 |
return x.Add(y), nil |
| 785 |
case Float: |
| 786 |
xf, err := x.finiteFloat() |
| 787 |
if err != nil { |
| 788 |
return nil, err |
| 789 |
} |
| 790 |
return xf + y, nil |
| 791 |
} |
| 792 |
case Float: |
| 793 |
switch y := y.(type) { |
| 794 |
case Float: |
| 795 |
return x + y, nil |
| 796 |
case Int: |
| 797 |
yf, err := y.finiteFloat() |
| 798 |
if err != nil { |
| 799 |
return nil, err |
| 800 |
} |
| 801 |
return x + yf, nil |
| 802 |
} |
| 803 |
case *List: |
| 804 |
if y, ok := y.(*List); ok { |
| 805 |
z := make([]Value, 0, x.Len()+y.Len()) |
| 806 |
z = append(z, x.elems...) |
| 807 |
z = append(z, y.elems...) |
| 808 |
return NewList(z), nil |
| 809 |
} |
| 810 |
case Tuple: |
| 811 |
if y, ok := y.(Tuple); ok { |
| 812 |
z := make(Tuple, 0, len(x)+len(y)) |
| 813 |
z = append(z, x...) |
| 814 |
z = append(z, y...) |
| 815 |
return z, nil |
| 816 |
} |
| 817 |
} |
| 818 |
|
| 819 |
case syntax.MINUS: |
| 820 |
switch x := x.(type) { |
| 821 |
case Int: |
| 822 |
switch y := y.(type) { |
| 823 |
case Int: |
| 824 |
return x.Sub(y), nil |
| 825 |
case Float: |
| 826 |
xf, err := x.finiteFloat() |
| 827 |
if err != nil { |
| 828 |
return nil, err |
| 829 |
} |
| 830 |
return xf - y, nil |
| 831 |
} |
| 832 |
case Float: |
| 833 |
switch y := y.(type) { |
| 834 |
case Float: |
| 835 |
return x - y, nil |
| 836 |
case Int: |
| 837 |
yf, err := y.finiteFloat() |
| 838 |
if err != nil { |
| 839 |
return nil, err |
| 840 |
} |
| 841 |
return x - yf, nil |
| 842 |
} |
| 843 |
case *Set: // difference |
| 844 |
if y, ok := y.(*Set); ok { |
| 845 |
iter := y.Iterate() |
| 846 |
defer iter.Done() |
| 847 |
return x.Difference(iter) |
| 848 |
} |
| 849 |
} |
| 850 |
|
| 851 |
case syntax.STAR: |
| 852 |
switch x := x.(type) { |
| 853 |
case Int: |
| 854 |
switch y := y.(type) { |
| 855 |
case Int: |
| 856 |
return x.Mul(y), nil |
| 857 |
case Float: |
| 858 |
xf, err := x.finiteFloat() |
| 859 |
if err != nil { |
| 860 |
return nil, err |
| 861 |
} |
| 862 |
return xf * y, nil |
| 863 |
case String: |
| 864 |
return stringRepeat(y, x) |
| 865 |
case Bytes: |
| 866 |
return bytesRepeat(y, x) |
| 867 |
case *List: |
| 868 |
elems, err := tupleRepeat(Tuple(y.elems), x) |
| 869 |
if err != nil { |
| 870 |
return nil, err |
| 871 |
} |
| 872 |
return NewList(elems), nil |
| 873 |
case Tuple: |
| 874 |
return tupleRepeat(y, x) |
| 875 |
} |
| 876 |
case Float: |
| 877 |
switch y := y.(type) { |
| 878 |
case Float: |
| 879 |
return x * y, nil |
| 880 |
case Int: |
| 881 |
yf, err := y.finiteFloat() |
| 882 |
if err != nil { |
| 883 |
return nil, err |
| 884 |
} |
| 885 |
return x * yf, nil |
| 886 |
} |
| 887 |
case String: |
| 888 |
if y, ok := y.(Int); ok { |
| 889 |
return stringRepeat(x, y) |
| 890 |
} |
| 891 |
case Bytes: |
| 892 |
if y, ok := y.(Int); ok { |
| 893 |
return bytesRepeat(x, y) |
| 894 |
} |
| 895 |
case *List: |
| 896 |
if y, ok := y.(Int); ok { |
| 897 |
elems, err := tupleRepeat(Tuple(x.elems), y) |
| 898 |
if err != nil { |
| 899 |
return nil, err |
| 900 |
} |
| 901 |
return NewList(elems), nil |
| 902 |
} |
| 903 |
case Tuple: |
| 904 |
if y, ok := y.(Int); ok { |
| 905 |
return tupleRepeat(x, y) |
| 906 |
} |
| 907 |
|
| 908 |
} |
| 909 |
|
| 910 |
case syntax.SLASH: |
| 911 |
switch x := x.(type) { |
| 912 |
case Int: |
| 913 |
xf, err := x.finiteFloat() |
| 914 |
if err != nil { |
| 915 |
return nil, err |
| 916 |
} |
| 917 |
switch y := y.(type) { |
| 918 |
case Int: |
| 919 |
yf, err := y.finiteFloat() |
| 920 |
if err != nil { |
| 921 |
return nil, err |
| 922 |
} |
| 923 |
if yf == 0.0 { |
| 924 |
return nil, fmt.Errorf("floating-point division by zero") |
| 925 |
} |
| 926 |
return xf / yf, nil |
| 927 |
case Float: |
| 928 |
if y == 0.0 { |
| 929 |
return nil, fmt.Errorf("floating-point division by zero") |
| 930 |
} |
| 931 |
return xf / y, nil |
| 932 |
} |
| 933 |
case Float: |
| 934 |
switch y := y.(type) { |
| 935 |
case Float: |
| 936 |
if y == 0.0 { |
| 937 |
return nil, fmt.Errorf("floating-point division by zero") |
| 938 |
} |
| 939 |
return x / y, nil |
| 940 |
case Int: |
| 941 |
yf, err := y.finiteFloat() |
| 942 |
if err != nil { |
| 943 |
return nil, err |
| 944 |
} |
| 945 |
if yf == 0.0 { |
| 946 |
return nil, fmt.Errorf("floating-point division by zero") |
| 947 |
} |
| 948 |
return x / yf, nil |
| 949 |
} |
| 950 |
} |
| 951 |
|
| 952 |
case syntax.SLASHSLASH: |
| 953 |
switch x := x.(type) { |
| 954 |
case Int: |
| 955 |
switch y := y.(type) { |
| 956 |
case Int: |
| 957 |
if y.Sign() == 0 { |
| 958 |
return nil, fmt.Errorf("floored division by zero") |
| 959 |
} |
| 960 |
return x.Div(y), nil |
| 961 |
case Float: |
| 962 |
xf, err := x.finiteFloat() |
| 963 |
if err != nil { |
| 964 |
return nil, err |
| 965 |
} |
| 966 |
if y == 0.0 { |
| 967 |
return nil, fmt.Errorf("floored division by zero") |
| 968 |
} |
| 969 |
return floor(xf / y), nil |
| 970 |
} |
| 971 |
case Float: |
| 972 |
switch y := y.(type) { |
| 973 |
case Float: |
| 974 |
if y == 0.0 { |
| 975 |
return nil, fmt.Errorf("floored division by zero") |
| 976 |
} |
| 977 |
return floor(x / y), nil |
| 978 |
case Int: |
| 979 |
yf, err := y.finiteFloat() |
| 980 |
if err != nil { |
| 981 |
return nil, err |
| 982 |
} |
| 983 |
if yf == 0.0 { |
| 984 |
return nil, fmt.Errorf("floored division by zero") |
| 985 |
} |
| 986 |
return floor(x / yf), nil |
| 987 |
} |
| 988 |
} |
| 989 |
|
| 990 |
case syntax.PERCENT: |
| 991 |
switch x := x.(type) { |
| 992 |
case Int: |
| 993 |
switch y := y.(type) { |
| 994 |
case Int: |
| 995 |
if y.Sign() == 0 { |
| 996 |
return nil, fmt.Errorf("integer modulo by zero") |
| 997 |
} |
| 998 |
return x.Mod(y), nil |
| 999 |
case Float: |
| 1000 |
xf, err := x.finiteFloat() |
| 1001 |
if err != nil { |
| 1002 |
return nil, err |
| 1003 |
} |
| 1004 |
if y == 0 { |
| 1005 |
return nil, fmt.Errorf("floating-point modulo by zero") |
| 1006 |
} |
| 1007 |
return xf.Mod(y), nil |
| 1008 |
} |
| 1009 |
case Float: |
| 1010 |
switch y := y.(type) { |
| 1011 |
case Float: |
| 1012 |
if y == 0.0 { |
| 1013 |
return nil, fmt.Errorf("floating-point modulo by zero") |
| 1014 |
} |
| 1015 |
return x.Mod(y), nil |
| 1016 |
case Int: |
| 1017 |
if y.Sign() == 0 { |
| 1018 |
return nil, fmt.Errorf("floating-point modulo by zero") |
| 1019 |
} |
| 1020 |
yf, err := y.finiteFloat() |
| 1021 |
if err != nil { |
| 1022 |
return nil, err |
| 1023 |
} |
| 1024 |
return x.Mod(yf), nil |
| 1025 |
} |
| 1026 |
case String: |
| 1027 |
return interpolate(string(x), y) |
| 1028 |
} |
| 1029 |
|
| 1030 |
case syntax.NOT_IN: |
| 1031 |
z, err := Binary(syntax.IN, x, y) |
| 1032 |
if err != nil { |
| 1033 |
return nil, err |
| 1034 |
} |
| 1035 |
return !z.Truth(), nil |
| 1036 |
|
| 1037 |
case syntax.IN: |
| 1038 |
switch y := y.(type) { |
| 1039 |
case Container: // List, Tuple, Set, String, Bytes, rangeValue etc. |
| 1040 |
found, err := y.Has(x) |
| 1041 |
return Bool(found), err |
| 1042 |
case Mapping: // e.g. dict |
| 1043 |
// Ignore error from Get as we cannot distinguish true |
| 1044 |
// errors (value cycle, type error) from "key not found". |
| 1045 |
_, found, _ := y.Get(x) |
| 1046 |
return Bool(found), nil |
| 1047 |
} |
| 1048 |
|
| 1049 |
case syntax.PIPE: |
| 1050 |
switch x := x.(type) { |
| 1051 |
case Int: |
| 1052 |
if y, ok := y.(Int); ok { |
| 1053 |
return x.Or(y), nil |
| 1054 |
} |
| 1055 |
|
| 1056 |
case *Dict: // union |
| 1057 |
if y, ok := y.(*Dict); ok { |
| 1058 |
return x.Union(y), nil |
| 1059 |
} |
| 1060 |
|
| 1061 |
case *Set: // union |
| 1062 |
if y, ok := y.(*Set); ok { |
| 1063 |
iter := Iterate(y) |
| 1064 |
defer iter.Done() |
| 1065 |
return x.Union(iter) |
| 1066 |
} |
| 1067 |
} |
| 1068 |
|
| 1069 |
case syntax.AMP: |
| 1070 |
switch x := x.(type) { |
| 1071 |
case Int: |
| 1072 |
if y, ok := y.(Int); ok { |
| 1073 |
return x.And(y), nil |
| 1074 |
} |
| 1075 |
case *Set: // intersection |
| 1076 |
if y, ok := y.(*Set); ok { |
| 1077 |
iter := y.Iterate() |
| 1078 |
defer iter.Done() |
| 1079 |
return x.Intersection(iter) |
| 1080 |
} |
| 1081 |
} |
| 1082 |
|
| 1083 |
case syntax.CIRCUMFLEX: |
| 1084 |
switch x := x.(type) { |
| 1085 |
case Int: |
| 1086 |
if y, ok := y.(Int); ok { |
| 1087 |
return x.Xor(y), nil |
| 1088 |
} |
| 1089 |
case *Set: // symmetric difference |
| 1090 |
if y, ok := y.(*Set); ok { |
| 1091 |
iter := y.Iterate() |
| 1092 |
defer iter.Done() |
| 1093 |
return x.SymmetricDifference(iter) |
| 1094 |
} |
| 1095 |
} |
| 1096 |
|
| 1097 |
case syntax.LTLT, syntax.GTGT: |
| 1098 |
if x, ok := x.(Int); ok { |
| 1099 |
y, err := AsInt32(y) |
| 1100 |
if err != nil { |
| 1101 |
return nil, err |
| 1102 |
} |
| 1103 |
if y < 0 { |
| 1104 |
return nil, fmt.Errorf("negative shift count: %v", y) |
| 1105 |
} |
| 1106 |
if op == syntax.LTLT { |
| 1107 |
if y >= 512 { |
| 1108 |
return nil, fmt.Errorf("shift count too large: %v", y) |
| 1109 |
} |
| 1110 |
return x.Lsh(uint(y)), nil |
| 1111 |
} else { |
| 1112 |
return x.Rsh(uint(y)), nil |
| 1113 |
} |
| 1114 |
} |
| 1115 |
|
| 1116 |
default: |
| 1117 |
// unknown operator |
| 1118 |
goto unknown |
| 1119 |
} |
| 1120 |
|
| 1121 |
// user-defined types |
| 1122 |
// (nil, nil) => unhandled |
| 1123 |
if x, ok := x.(HasBinary); ok { |
| 1124 |
z, err := x.Binary(op, y, Left) |
| 1125 |
if z != nil || err != nil { |
| 1126 |
return z, err |
| 1127 |
} |
| 1128 |
} |
| 1129 |
if y, ok := y.(HasBinary); ok { |
| 1130 |
z, err := y.Binary(op, x, Right) |
| 1131 |
if z != nil || err != nil { |
| 1132 |
return z, err |
| 1133 |
} |
| 1134 |
} |
| 1135 |
|
| 1136 |
// unsupported operand types |
| 1137 |
unknown: |
| 1138 |
return nil, fmt.Errorf("unknown binary op: %s %s %s", x.Type(), op, y.Type()) |
| 1139 |
} |
| 1140 |
|
| 1141 |
// It's always possible to overeat in small bites but we'll |
| 1142 |
// try to stop someone swallowing the world in one gulp. |
| 1143 |
const maxAlloc = 1 << 30 |
| 1144 |
|
| 1145 |
func tupleRepeat(elems Tuple, n Int) (Tuple, error) { |
| 1146 |
if len(elems) == 0 { |
| 1147 |
return nil, nil |
| 1148 |
} |
| 1149 |
i, err := AsInt32(n) |
| 1150 |
if err != nil { |
| 1151 |
return nil, fmt.Errorf("repeat count %s too large", n) |
| 1152 |
} |
| 1153 |
if i < 1 { |
| 1154 |
return nil, nil |
| 1155 |
} |
| 1156 |
// Inv: i > 0, len > 0 |
| 1157 |
of, sz := bits.Mul(uint(len(elems)), uint(i)) |
| 1158 |
if of != 0 || sz >= maxAlloc { // of != 0 => overflow |
| 1159 |
// Don't print sz. |
| 1160 |
return nil, fmt.Errorf("excessive repeat (%d * %d elements)", len(elems), i) |
| 1161 |
} |
| 1162 |
res := make([]Value, sz) |
| 1163 |
// copy elems into res, doubling each time |
| 1164 |
x := copy(res, elems) |
| 1165 |
for x < len(res) { |
| 1166 |
copy(res[x:], res[:x]) |
| 1167 |
x *= 2 |
| 1168 |
} |
| 1169 |
return res, nil |
| 1170 |
} |
| 1171 |
|
| 1172 |
func bytesRepeat(b Bytes, n Int) (Bytes, error) { |
| 1173 |
res, err := stringRepeat(String(b), n) |
| 1174 |
return Bytes(res), err |
| 1175 |
} |
| 1176 |
|
| 1177 |
func stringRepeat(s String, n Int) (String, error) { |
| 1178 |
if s == "" { |
| 1179 |
return "", nil |
| 1180 |
} |
| 1181 |
i, err := AsInt32(n) |
| 1182 |
if err != nil { |
| 1183 |
return "", fmt.Errorf("repeat count %s too large", n) |
| 1184 |
} |
| 1185 |
if i < 1 { |
| 1186 |
return "", nil |
| 1187 |
} |
| 1188 |
// Inv: i > 0, len > 0 |
| 1189 |
of, sz := bits.Mul(uint(len(s)), uint(i)) |
| 1190 |
if of != 0 || sz >= maxAlloc { // of != 0 => overflow |
| 1191 |
// Don't print sz. |
| 1192 |
return "", fmt.Errorf("excessive repeat (%d * %d elements)", len(s), i) |
| 1193 |
} |
| 1194 |
return String(strings.Repeat(string(s), i)), nil |
| 1195 |
} |
| 1196 |
|
| 1197 |
// Call calls the function fn with the specified positional and keyword arguments. |
| 1198 |
func Call(thread *Thread, fn Value, args Tuple, kwargs []Tuple) (Value, error) { |
| 1199 |
c, ok := fn.(Callable) |
| 1200 |
if !ok { |
| 1201 |
return nil, fmt.Errorf("invalid call of non-function (%s)", fn.Type()) |
| 1202 |
} |
| 1203 |
|
| 1204 |
// Allocate and push a new frame. |
| 1205 |
var fr *frame |
| 1206 |
// Optimization: use slack portion of thread.stack |
| 1207 |
// slice as a freelist of empty frames. |
| 1208 |
if n := len(thread.stack); n < cap(thread.stack) { |
| 1209 |
fr = thread.stack[n : n+1][0] |
| 1210 |
} |
| 1211 |
if fr == nil { |
| 1212 |
fr = new(frame) |
| 1213 |
} |
| 1214 |
|
| 1215 |
if thread.stack == nil { |
| 1216 |
// one-time initialization of thread |
| 1217 |
if thread.maxSteps == 0 { |
| 1218 |
thread.maxSteps-- // (MaxUint64) |
| 1219 |
} |
| 1220 |
} |
| 1221 |
|
| 1222 |
thread.stack = append(thread.stack, fr) // push |
| 1223 |
|
| 1224 |
fr.callable = c |
| 1225 |
|
| 1226 |
thread.beginProfSpan() |
| 1227 |
|
| 1228 |
// Use defer to ensure that panics from built-ins |
| 1229 |
// pass through the interpreter without leaving |
| 1230 |
// it in a bad state. |
| 1231 |
defer func() { |
| 1232 |
thread.endProfSpan() |
| 1233 |
|
| 1234 |
// clear out any references |
| 1235 |
// TODO(adonovan): opt: zero fr.Locals and |
| 1236 |
// reuse it if it is large enough. |
| 1237 |
*fr = frame{} |
| 1238 |
|
| 1239 |
thread.stack = thread.stack[:len(thread.stack)-1] // pop |
| 1240 |
}() |
| 1241 |
|
| 1242 |
result, err := c.CallInternal(thread, args, kwargs) |
| 1243 |
|
| 1244 |
// Sanity check: nil is not a valid Starlark value. |
| 1245 |
if result == nil && err == nil { |
| 1246 |
err = fmt.Errorf("internal error: nil (not None) returned from %s", fn) |
| 1247 |
} |
| 1248 |
|
| 1249 |
// Always return an EvalError with an accurate frame. |
| 1250 |
if err != nil && !is[*EvalError](err) { |
| 1251 |
err = thread.evalError(err) |
| 1252 |
} |
| 1253 |
|
| 1254 |
return result, err |
| 1255 |
} |
| 1256 |
|
| 1257 |
func slice(x, lo, hi, step_ Value) (Value, error) { |
| 1258 |
sliceable, ok := x.(Sliceable) |
| 1259 |
if !ok { |
| 1260 |
return nil, fmt.Errorf("invalid slice operand %s", x.Type()) |
| 1261 |
} |
| 1262 |
|
| 1263 |
n := sliceable.Len() |
| 1264 |
step := 1 |
| 1265 |
if step_ != None { |
| 1266 |
var err error |
| 1267 |
step, err = AsInt32(step_) |
| 1268 |
if err != nil { |
| 1269 |
return nil, fmt.Errorf("invalid slice step: %s", err) |
| 1270 |
} |
| 1271 |
if step == 0 { |
| 1272 |
return nil, fmt.Errorf("zero is not a valid slice step") |
| 1273 |
} |
| 1274 |
} |
| 1275 |
|
| 1276 |
// TODO(adonovan): opt: preallocate result array. |
| 1277 |
|
| 1278 |
var start, end int |
| 1279 |
if step > 0 { |
| 1280 |
// positive stride |
| 1281 |
// default indices are [0:n]. |
| 1282 |
var err error |
| 1283 |
start, end, err = indices(lo, hi, n) |
| 1284 |
if err != nil { |
| 1285 |
return nil, err |
| 1286 |
} |
| 1287 |
|
| 1288 |
if end < start { |
| 1289 |
end = start // => empty result |
| 1290 |
} |
| 1291 |
} else { |
| 1292 |
// negative stride |
| 1293 |
// default indices are effectively [n-1:-1], though to |
| 1294 |
// get this effect using explicit indices requires |
| 1295 |
// [n-1:-1-n:-1] because of the treatment of -ve values. |
| 1296 |
start = n - 1 |
| 1297 |
if err := asIndex(lo, n, &start); err != nil { |
| 1298 |
return nil, fmt.Errorf("invalid start index: %s", err) |
| 1299 |
} |
| 1300 |
if start >= n { |
| 1301 |
start = n - 1 |
| 1302 |
} |
| 1303 |
|
| 1304 |
end = -1 |
| 1305 |
if err := asIndex(hi, n, &end); err != nil { |
| 1306 |
return nil, fmt.Errorf("invalid end index: %s", err) |
| 1307 |
} |
| 1308 |
if end < -1 { |
| 1309 |
end = -1 |
| 1310 |
} |
| 1311 |
|
| 1312 |
if start < end { |
| 1313 |
start = end // => empty result |
| 1314 |
} |
| 1315 |
} |
| 1316 |
|
| 1317 |
return sliceable.Slice(start, end, step), nil |
| 1318 |
} |
| 1319 |
|
| 1320 |
// From Hacker's Delight, section 2.8. |
| 1321 |
func signum64(x int64) int { return int(uint64(x>>63) | uint64(-x)>>63) } |
| 1322 |
func signum(x int) int { return signum64(int64(x)) } |
| 1323 |
|
| 1324 |
// indices converts start_ and end_ to indices in the range [0:len]. |
| 1325 |
// The start index defaults to 0 and the end index defaults to len. |
| 1326 |
// An index -len < i < 0 is treated like i+len. |
| 1327 |
// All other indices outside the range are clamped to the nearest value in the range. |
| 1328 |
// Beware: start may be greater than end. |
| 1329 |
// This function is suitable only for slices with positive strides. |
| 1330 |
func indices(start_, end_ Value, len int) (start, end int, err error) { |
| 1331 |
start = 0 |
| 1332 |
if err := asIndex(start_, len, &start); err != nil { |
| 1333 |
return 0, 0, fmt.Errorf("invalid start index: %s", err) |
| 1334 |
} |
| 1335 |
// Clamp to [0:len]. |
| 1336 |
if start < 0 { |
| 1337 |
start = 0 |
| 1338 |
} else if start > len { |
| 1339 |
start = len |
| 1340 |
} |
| 1341 |
|
| 1342 |
end = len |
| 1343 |
if err := asIndex(end_, len, &end); err != nil { |
| 1344 |
return 0, 0, fmt.Errorf("invalid end index: %s", err) |
| 1345 |
} |
| 1346 |
// Clamp to [0:len]. |
| 1347 |
if end < 0 { |
| 1348 |
end = 0 |
| 1349 |
} else if end > len { |
| 1350 |
end = len |
| 1351 |
} |
| 1352 |
|
| 1353 |
return start, end, nil |
| 1354 |
} |
| 1355 |
|
| 1356 |
// asIndex sets *result to the integer value of v, adding len to it |
| 1357 |
// if it is negative. If v is nil or None, *result is unchanged. |
| 1358 |
func asIndex(v Value, len int, result *int) error { |
| 1359 |
if v != nil && v != None { |
| 1360 |
var err error |
| 1361 |
*result, err = AsInt32(v) |
| 1362 |
if err != nil { |
| 1363 |
return err |
| 1364 |
} |
| 1365 |
if *result < 0 { |
| 1366 |
*result += len |
| 1367 |
} |
| 1368 |
} |
| 1369 |
return nil |
| 1370 |
} |
| 1371 |
|
| 1372 |
// setArgs sets the values of the formal parameters of function fn in |
| 1373 |
// based on the actual parameter values in args and kwargs. |
| 1374 |
func setArgs(locals []Value, fn *Function, args Tuple, kwargs []Tuple) error { |
| 1375 |
|
| 1376 |
// This is the general schema of a function: |
| 1377 |
// |
| 1378 |
// def f(p1, p2=dp2, p3=dp3, *args, k1, k2=dk2, k3, **kwargs) |
| 1379 |
// |
| 1380 |
// The p parameters are non-kwonly, and may be specified positionally. |
| 1381 |
// The k parameters are kwonly, and must be specified by name. |
| 1382 |
// The defaults tuple is (dp2, dp3, mandatory, dk2, mandatory). |
| 1383 |
// |
| 1384 |
// Arguments are processed as follows: |
| 1385 |
// - positional arguments are bound to a prefix of [p1, p2, p3]. |
| 1386 |
// - surplus positional arguments are bound to *args. |
| 1387 |
// - keyword arguments are bound to any of {p1, p2, p3, k1, k2, k3}; |
| 1388 |
// duplicate bindings are rejected. |
| 1389 |
// - surplus keyword arguments are bound to **kwargs. |
| 1390 |
// - defaults are bound to each parameter from p2 to k3 if no value was set. |
| 1391 |
// default values come from the tuple above. |
| 1392 |
// It is an error if the tuple entry for an unset parameter is 'mandatory'. |
| 1393 |
|
| 1394 |
// Nullary function? |
| 1395 |
if fn.NumParams() == 0 { |
| 1396 |
if nactual := len(args) + len(kwargs); nactual > 0 { |
| 1397 |
return fmt.Errorf("function %s accepts no arguments (%d given)", fn.Name(), nactual) |
| 1398 |
} |
| 1399 |
return nil |
| 1400 |
} |
| 1401 |
|
| 1402 |
cond := func(x bool, y, z any) any { |
| 1403 |
if x { |
| 1404 |
return y |
| 1405 |
} |
| 1406 |
return z |
| 1407 |
} |
| 1408 |
|
| 1409 |
// nparams is the number of ordinary parameters (sans *args and **kwargs). |
| 1410 |
nparams := fn.NumParams() |
| 1411 |
var kwdict *Dict |
| 1412 |
if fn.HasKwargs() { |
| 1413 |
nparams-- |
| 1414 |
kwdict = new(Dict) |
| 1415 |
locals[nparams] = kwdict |
| 1416 |
} |
| 1417 |
if fn.HasVarargs() { |
| 1418 |
nparams-- |
| 1419 |
} |
| 1420 |
|
| 1421 |
// nonkwonly is the number of non-kwonly parameters. |
| 1422 |
nonkwonly := nparams - fn.NumKwonlyParams() |
| 1423 |
|
| 1424 |
// Too many positional args? |
| 1425 |
n := len(args) |
| 1426 |
if len(args) > nonkwonly { |
| 1427 |
if !fn.HasVarargs() { |
| 1428 |
return fmt.Errorf("function %s accepts %s%d positional argument%s (%d given)", |
| 1429 |
fn.Name(), |
| 1430 |
cond(len(fn.defaults) > fn.NumKwonlyParams(), "at most ", ""), |
| 1431 |
nonkwonly, |
| 1432 |
cond(nonkwonly == 1, "", "s"), |
| 1433 |
len(args)) |
| 1434 |
} |
| 1435 |
n = nonkwonly |
| 1436 |
} |
| 1437 |
|
| 1438 |
// Bind positional arguments to non-kwonly parameters. |
| 1439 |
for i := 0; i < n; i++ { |
| 1440 |
locals[i] = args[i] |
| 1441 |
} |
| 1442 |
|
| 1443 |
// Bind surplus positional arguments to *args parameter. |
| 1444 |
if fn.HasVarargs() { |
| 1445 |
tuple := make(Tuple, len(args)-n) |
| 1446 |
for i := n; i < len(args); i++ { |
| 1447 |
tuple[i-n] = args[i] |
| 1448 |
} |
| 1449 |
locals[nparams] = tuple |
| 1450 |
} |
| 1451 |
|
| 1452 |
// Bind keyword arguments to parameters. |
| 1453 |
paramIdents := fn.funcode.Locals[:nparams] |
| 1454 |
for _, pair := range kwargs { |
| 1455 |
k, v := pair[0].(String), pair[1] |
| 1456 |
if i := findParam(paramIdents, string(k)); i >= 0 { |
| 1457 |
if locals[i] != nil { |
| 1458 |
return fmt.Errorf("function %s got multiple values for parameter %s", fn.Name(), k) |
| 1459 |
} |
| 1460 |
locals[i] = v |
| 1461 |
continue |
| 1462 |
} |
| 1463 |
if kwdict == nil { |
| 1464 |
return fmt.Errorf("function %s got an unexpected keyword argument %s", fn.Name(), k) |
| 1465 |
} |
| 1466 |
oldlen := kwdict.Len() |
| 1467 |
kwdict.SetKey(k, v) |
| 1468 |
if kwdict.Len() == oldlen { |
| 1469 |
return fmt.Errorf("function %s got multiple values for parameter %s", fn.Name(), k) |
| 1470 |
} |
| 1471 |
} |
| 1472 |
|
| 1473 |
// Are defaults required? |
| 1474 |
if n < nparams || fn.NumKwonlyParams() > 0 { |
| 1475 |
m := nparams - len(fn.defaults) // first default |
| 1476 |
|
| 1477 |
// Report errors for missing required arguments. |
| 1478 |
var missing []string |
| 1479 |
var i int |
| 1480 |
for i = n; i < m; i++ { |
| 1481 |
if locals[i] == nil { |
| 1482 |
missing = append(missing, paramIdents[i].Name) |
| 1483 |
} |
| 1484 |
} |
| 1485 |
|
| 1486 |
// Bind default values to parameters. |
| 1487 |
for ; i < nparams; i++ { |
| 1488 |
if locals[i] == nil { |
| 1489 |
dflt := fn.defaults[i-m] |
| 1490 |
if is[mandatory](dflt) { |
| 1491 |
missing = append(missing, paramIdents[i].Name) |
| 1492 |
continue |
| 1493 |
} |
| 1494 |
locals[i] = dflt |
| 1495 |
} |
| 1496 |
} |
| 1497 |
|
| 1498 |
if missing != nil { |
| 1499 |
return fmt.Errorf("function %s missing %d argument%s (%s)", |
| 1500 |
fn.Name(), len(missing), cond(len(missing) > 1, "s", ""), strings.Join(missing, ", ")) |
| 1501 |
} |
| 1502 |
} |
| 1503 |
return nil |
| 1504 |
} |
| 1505 |
|
| 1506 |
func findParam(params []compile.Binding, name string) int { |
| 1507 |
for i, param := range params { |
| 1508 |
if param.Name == name { |
| 1509 |
return i |
| 1510 |
} |
| 1511 |
} |
| 1512 |
return -1 |
| 1513 |
} |
| 1514 |
|
| 1515 |
// https://github.com/google/starlark-go/blob/master/doc/spec.md#string-interpolation |
| 1516 |
func interpolate(format string, x Value) (Value, error) { |
| 1517 |
buf := new(strings.Builder) |
| 1518 |
index := 0 |
| 1519 |
nargs := 1 |
| 1520 |
if tuple, ok := x.(Tuple); ok { |
| 1521 |
nargs = len(tuple) |
| 1522 |
} |
| 1523 |
for { |
| 1524 |
i := strings.IndexByte(format, '%') |
| 1525 |
if i < 0 { |
| 1526 |
buf.WriteString(format) |
| 1527 |
break |
| 1528 |
} |
| 1529 |
buf.WriteString(format[:i]) |
| 1530 |
format = format[i+1:] |
| 1531 |
|
| 1532 |
if format != "" && format[0] == '%' { |
| 1533 |
buf.WriteByte('%') |
| 1534 |
format = format[1:] |
| 1535 |
continue |
| 1536 |
} |
| 1537 |
|
| 1538 |
var arg Value |
| 1539 |
if format != "" && format[0] == '(' { |
| 1540 |
// keyword argument: %(name)s. |
| 1541 |
format = format[1:] |
| 1542 |
j := strings.IndexByte(format, ')') |
| 1543 |
if j < 0 { |
| 1544 |
return nil, fmt.Errorf("incomplete format key") |
| 1545 |
} |
| 1546 |
key := format[:j] |
| 1547 |
if dict, ok := x.(Mapping); !ok { |
| 1548 |
return nil, fmt.Errorf("format requires a mapping") |
| 1549 |
} else if v, found, _ := dict.Get(String(key)); found { |
| 1550 |
arg = v |
| 1551 |
} else { |
| 1552 |
return nil, fmt.Errorf("key not found: %s", key) |
| 1553 |
} |
| 1554 |
format = format[j+1:] |
| 1555 |
} else { |
| 1556 |
// positional argument: %s. |
| 1557 |
if index >= nargs { |
| 1558 |
return nil, fmt.Errorf("not enough arguments for format string") |
| 1559 |
} |
| 1560 |
if tuple, ok := x.(Tuple); ok { |
| 1561 |
arg = tuple[index] |
| 1562 |
} else { |
| 1563 |
arg = x |
| 1564 |
} |
| 1565 |
} |
| 1566 |
|
| 1567 |
// NOTE: Starlark does not support any of these optional Python features: |
| 1568 |
// - optional conversion flags: [#0- +], etc. |
| 1569 |
// - optional minimum field width (number or *). |
| 1570 |
// - optional precision (.123 or *) |
| 1571 |
// - optional length modifier |
| 1572 |
|
| 1573 |
// conversion type |
| 1574 |
if format == "" { |
| 1575 |
return nil, fmt.Errorf("incomplete format") |
| 1576 |
} |
| 1577 |
switch c := format[0]; c { |
| 1578 |
case 's', 'r': |
| 1579 |
if str, ok := AsString(arg); ok && c == 's' { |
| 1580 |
buf.WriteString(str) |
| 1581 |
} else { |
| 1582 |
writeValue(buf, arg, nil) |
| 1583 |
} |
| 1584 |
case 'd', 'i', 'o', 'x', 'X': |
| 1585 |
i, err := NumberToInt(arg) |
| 1586 |
if err != nil { |
| 1587 |
return nil, fmt.Errorf("%%%c format requires integer: %v", c, err) |
| 1588 |
} |
| 1589 |
switch c { |
| 1590 |
case 'd', 'i': |
| 1591 |
fmt.Fprintf(buf, "%d", i) |
| 1592 |
case 'o': |
| 1593 |
fmt.Fprintf(buf, "%o", i) |
| 1594 |
case 'x': |
| 1595 |
fmt.Fprintf(buf, "%x", i) |
| 1596 |
case 'X': |
| 1597 |
fmt.Fprintf(buf, "%X", i) |
| 1598 |
} |
| 1599 |
case 'e', 'f', 'g', 'E', 'F', 'G': |
| 1600 |
f, ok := AsFloat(arg) |
| 1601 |
if !ok { |
| 1602 |
return nil, fmt.Errorf("%%%c format requires float, not %s", c, arg.Type()) |
| 1603 |
} |
| 1604 |
Float(f).format(buf, c) |
| 1605 |
case 'c': |
| 1606 |
switch arg := arg.(type) { |
| 1607 |
case Int: |
| 1608 |
// chr(int) |
| 1609 |
r, err := AsInt32(arg) |
| 1610 |
if err != nil || r < 0 || r > unicode.MaxRune { |
| 1611 |
return nil, fmt.Errorf("%%c format requires a valid Unicode code point, got %s", arg) |
| 1612 |
} |
| 1613 |
buf.WriteRune(rune(r)) |
| 1614 |
case String: |
| 1615 |
r, size := utf8.DecodeRuneInString(string(arg)) |
| 1616 |
if size != len(arg) || len(arg) == 0 { |
| 1617 |
return nil, fmt.Errorf("%%c format requires a single-character string") |
| 1618 |
} |
| 1619 |
buf.WriteRune(r) |
| 1620 |
default: |
| 1621 |
return nil, fmt.Errorf("%%c format requires int or single-character string, not %s", arg.Type()) |
| 1622 |
} |
| 1623 |
case '%': |
| 1624 |
buf.WriteByte('%') |
| 1625 |
default: |
| 1626 |
return nil, fmt.Errorf("unknown conversion %%%c", c) |
| 1627 |
} |
| 1628 |
format = format[1:] |
| 1629 |
index++ |
| 1630 |
} |
| 1631 |
|
| 1632 |
if index < nargs && !is[Mapping](x) { |
| 1633 |
return nil, fmt.Errorf("too many arguments for format string") |
| 1634 |
} |
| 1635 |
|
| 1636 |
return String(buf.String()), nil |
| 1637 |
} |
| 1638 |
|
| 1639 |
func is[T any](x any) bool { |
| 1640 |
_, ok := x.(T) |
| 1641 |
return ok |
| 1642 |
} |