From 4df97fc21d495b34420838218ebabfa75cbe4776 Mon Sep 17 00:00:00 2001 From: surdeus Date: Thu, 6 Jun 2024 17:00:39 +0500 Subject: [PATCH] feat: implemented basic log package. --- logx/main.go | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ tests/cjson.xgo | 8 ++++-- xtool/main.go | 2 ++ 3 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 logx/main.go diff --git a/logx/main.go b/logx/main.go new file mode 100644 index 0000000..0aac329 --- /dev/null +++ b/logx/main.go @@ -0,0 +1,65 @@ +package logx + +import "github.com/d5/tengo/v2" +import "log" + +var Module = map[string]tengo.Object{ + "printf": &tengo.BuiltinFunction{ + Name: "printf", + Value: func( + args ...tengo.Object, + ) (tengo.Object, error) { + if len(args) < 1 { + return nil, tengo.ErrWrongNumArguments + } + + formatObject := args[0] + format, hasFormat := tengo.ToString( + formatObject, + ) + if !hasFormat { + return nil, tengo.ErrInvalidArgumentType{ + Name: "first", + Expected: "string", + Found: formatObject.TypeName(), + } + } + + v := make([]any, len(args[1:])) + for i, o := range args[1:] { + v[i] = tengo.ToInterface(o) + } + + log.Printf(format, v...) + + return nil, nil + }, + }, + "print": &tengo.BuiltinFunction{ + Name: "print", + Value: func( + args ...tengo.Object, + ) (tengo.Object, error){ + v := make([]any, len(args)) + for i, o := range args { + v[i] = tengo.ToInterface(o) + } + log.Print(v...) + return nil, nil + }, + }, + "println": &tengo.BuiltinFunction{ + Name: "println", + Value: func( + args ...tengo.Object, + ) (tengo.Object, error){ + v := make([]any, len(args)) + for i, o := range args { + v[i] = tengo.ToInterface(o) + } + log.Println(v...) + return nil, nil + }, + }, +} + diff --git a/tests/cjson.xgo b/tests/cjson.xgo index 0af89fa..28f8a6b 100644 --- a/tests/cjson.xgo +++ b/tests/cjson.xgo @@ -1,9 +1,12 @@ cjson := import("cjson") fmt := import("fmt") -fmt.println(cjson.__check()) - +log := import("log") dec := cjson.new_decoder("tests/data.cjson") +log.print("cock") +log.print("die") + +log.println("some log") for { v := dec.decode() if is_error(v) { @@ -12,5 +15,6 @@ for { if !v { break } + log.println("got one more value") fmt.println(v) } diff --git a/xtool/main.go b/xtool/main.go index 498f404..83a3195 100644 --- a/xtool/main.go +++ b/xtool/main.go @@ -20,6 +20,7 @@ import ( import "surdeus.su/core/cli/mtool" import "surdeus.su/core/xgo/cjson" +import "surdeus.su/core/xgo/logx" const ( sourceFileExt = ".xgo" @@ -54,6 +55,7 @@ func Run(flags *mtool.Flags) { } modules := stdlib.GetModuleMap(stdlib.AllModuleNames()...) modules.AddBuiltinModule("cjson", cjson.Module) + modules.AddBuiltinModule("log", logx.Module) if len(iargs) == 0 { // REPL RunREPL(modules, os.Stdin, os.Stdout)