2024-04-10 10:45:58 +00:00
|
|
|
package cmdlang
|
|
|
|
|
2024-04-10 11:58:06 +00:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
2024-04-10 12:19:11 +00:00
|
|
|
"fmt"
|
2024-04-10 11:58:06 +00:00
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
2024-04-10 12:19:11 +00:00
|
|
|
type object interface {
|
|
|
|
}
|
|
|
|
|
|
|
|
type strObject string
|
|
|
|
|
|
|
|
func (s strObject) String() string {
|
|
|
|
return string(s)
|
|
|
|
}
|
2024-04-10 10:45:58 +00:00
|
|
|
|
|
|
|
type invocationArgs struct {
|
2024-04-10 12:19:11 +00:00
|
|
|
args []object
|
2024-04-10 11:58:06 +00:00
|
|
|
inStream stream
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2024-04-10 11:58:06 +00:00
|
|
|
// invokable is an object that can be executed as a command
|
2024-04-10 10:45:58 +00:00
|
|
|
type invokable interface {
|
2024-04-10 11:58:06 +00:00
|
|
|
invoke(ctx context.Context, args invocationArgs) (object, error)
|
2024-04-10 10:45:58 +00:00
|
|
|
}
|
|
|
|
|
2024-04-10 11:58:06 +00:00
|
|
|
type invokableFunc func(ctx context.Context, args invocationArgs) (object, error)
|
2024-04-10 10:45:58 +00:00
|
|
|
|
2024-04-10 11:58:06 +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)
|
|
|
|
}
|