ucl/repl/evaldisplay.go

46 lines
846 B
Go
Raw Normal View History

2024-12-11 09:47:05 +00:00
package repl
import (
"context"
"fmt"
"os"
"ucl.lmika.dev/ucl"
)
2024-12-11 10:16:08 +00:00
type NoResults struct{}
2024-12-11 09:47:05 +00:00
func (r *REPL) EvalAndDisplay(ctx context.Context, expr string) error {
res, err := r.inst.Eval(ctx, expr)
if err != nil {
return err
}
return displayResult(ctx, r.inst, res)
}
func displayResult(ctx context.Context, inst *ucl.Inst, res any) (err error) {
switch v := res.(type) {
2024-12-11 10:16:08 +00:00
case NoResults:
return nil
2024-12-11 09:47:05 +00:00
case nil:
if _, err = fmt.Fprintln(os.Stdout, "(nil)"); err != nil {
return err
}
2024-12-11 10:16:08 +00:00
case ucl.Listable:
2024-12-11 09:47:05 +00:00
for i := 0; i < v.Len(); i++ {
if err = displayResult(ctx, inst, v.Index(i)); err != nil {
return err
}
}
2024-12-11 10:16:08 +00:00
case ucl.Object:
2024-12-11 09:47:05 +00:00
if _, err = fmt.Fprintln(os.Stdout, v.String()); err != nil {
return err
}
2024-12-11 10:16:08 +00:00
default:
if _, err = fmt.Fprintln(os.Stdout, v); err != nil {
return err
}
2024-12-11 09:47:05 +00:00
}
return nil
}