ucl/cmdlang/objs.go

80 lines
1.7 KiB
Go
Raw Normal View History

2024-04-10 10:45:58 +00:00
package cmdlang
import (
"context"
"errors"
2024-04-10 12:19:11 +00:00
"fmt"
"strconv"
)
2024-04-10 12:19:11 +00:00
type object interface {
2024-04-11 12:05:05 +00:00
String() string
2024-04-10 12:19:11 +00:00
}
type strObject string
func (s strObject) String() string {
return string(s)
}
2024-04-10 10:45:58 +00:00
2024-04-11 12:05:05 +00:00
func toGoValue(obj object) (interface{}, bool) {
switch v := obj.(type) {
case nil:
return nil, true
case strObject:
return string(v), true
}
return nil, false
}
2024-04-10 10:45:58 +00:00
type invocationArgs struct {
2024-04-11 12:05:05 +00:00
inst *Inst
ec *evalCtx
2024-04-11 10:47:59 +00:00
args []object
}
func (ia invocationArgs) expectArgn(x int) error {
if len(ia.args) < x {
return errors.New("expected at least " + strconv.Itoa(x) + " args")
}
return nil
2024-04-10 10:45:58 +00:00
}
2024-04-10 12:19:11 +00:00
func (ia invocationArgs) stringArg(i int) (string, error) {
if len(ia.args) < i {
return "", errors.New("expected at least " + strconv.Itoa(i) + " args")
}
s, ok := ia.args[i].(fmt.Stringer)
if !ok {
return "", errors.New("expected a string arg")
}
return s.String(), nil
}
// invokable is an object that can be executed as a command
2024-04-10 10:45:58 +00:00
type invokable interface {
invoke(ctx context.Context, args invocationArgs) (object, error)
2024-04-10 10:45:58 +00:00
}
2024-04-11 10:47:59 +00:00
type streamInvokable interface {
invokable
invokeWithStream(context.Context, stream, invocationArgs) (object, error)
}
type invokableFunc func(ctx context.Context, args invocationArgs) (object, error)
2024-04-10 10:45:58 +00:00
func (i invokableFunc) invoke(ctx context.Context, args invocationArgs) (object, error) {
2024-04-10 10:45:58 +00:00
return i(ctx, args)
}
2024-04-11 10:47:59 +00:00
type invokableStreamFunc func(ctx context.Context, inStream stream, args invocationArgs) (object, error)
func (i invokableStreamFunc) invoke(ctx context.Context, args invocationArgs) (object, error) {
return i(ctx, nil, args)
}
func (i invokableStreamFunc) invokeWithStream(ctx context.Context, inStream stream, args invocationArgs) (object, error) {
return i(ctx, inStream, args)
}