From 53b05b5ba6f8128f3b39c9f8db5a8f8106cf9782 Mon Sep 17 00:00:00 2001 From: Leon Mika Date: Mon, 19 May 2025 22:04:09 +1000 Subject: [PATCH] Added 'error' and 'assert' builtins --- ucl/builtins.go | 25 +++++++++++++++++++++++++ ucl/inst.go | 3 +++ ucl/objs.go | 8 ++++++++ 3 files changed, 36 insertions(+) diff --git a/ucl/builtins.go b/ucl/builtins.go index 88a796d..9a1ac62 100644 --- a/ucl/builtins.go +++ b/ucl/builtins.go @@ -1103,6 +1103,31 @@ func returnBuiltin(ctx context.Context, args invocationArgs) (Object, error) { return nil, errReturn{ret: args.args[0]} } +// TODO - add tests + +func errorBuiltin(ctx context.Context, args invocationArgs) (Object, error) { + if len(args.args) < 1 { + return nil, errors.New("need at least one arguments") + } + return nil, ErrRuntime{args.args[0].String()} +} + +func assertBuiltin(ctx context.Context, args invocationArgs) (Object, error) { + if len(args.args) < 1 { + return nil, errors.New("need at least one arguments") + } + + if isTruthy(args.args[0]) { + return nil, nil + } + + if len(args.args) > 1 { + return nil, ErrRuntime{args.args[1].String()} + } + + return nil, ErrRuntime{"assertion failed"} +} + func procBuiltin(ctx context.Context, args macroArgs) (Object, error) { if args.nargs() < 1 { return nil, errors.New("need at least one arguments") diff --git a/ucl/inst.go b/ucl/inst.go index e47873f..94c0353 100644 --- a/ucl/inst.go +++ b/ucl/inst.go @@ -96,6 +96,9 @@ func New(opts ...InstOption) *Inst { rootEC.addCmd("continue", invokableFunc(continueBuiltin)) rootEC.addCmd("return", invokableFunc(returnBuiltin)) + rootEC.addCmd("error", invokableFunc(errorBuiltin)) + rootEC.addCmd("assert", invokableFunc(assertBuiltin)) + rootEC.addMacro("if", macroFunc(ifBuiltin)) rootEC.addMacro("foreach", macroFunc(foreachBuiltin)) rootEC.addMacro("for", macroFunc(foreachBuiltin)) diff --git a/ucl/objs.go b/ucl/objs.go index 827260e..8ca798d 100644 --- a/ucl/objs.go +++ b/ucl/objs.go @@ -643,6 +643,14 @@ func (p OpaqueObject) Truthy() bool { return p.v != nil } +type ErrRuntime struct { + errStr string +} + +func (e ErrRuntime) Error() string { + return e.errStr +} + type errBreak struct { isCont bool ret Object