21

Go 语言实现的小型、动态、快速、安全的脚本语言

 4 years ago
source link: https://mp.weixin.qq.com/s/unqFqCMHfDL2DOZzk4Cc6w
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

关注公众号 “ OpenSourceDaily ” ,每天推荐给你优秀开源项目

大家好,我是欧盆索思(opensource),每天为你带来优秀的开源项目!

今天为 Go 语言爱好者推荐一个脚本语言:Tengo,这是用 Go 语言实现的小型,动态,快速,安全的脚本语言。项目地址:https://github.com/d5/tengo,目前 Star 数:1.7k+。

Tengo 既快速又安全,因为它是用 native Go 编写的基于堆栈的 VM 上作为字节码编译/执行的。

该语言的特性如下:

  • 简单易读的语法

    • 带类型强制的动态输入

    • 高阶函数和闭包

    • 不变值

  • 可安全嵌入和扩展

  • 用 native Go 编写的编译器/运行时(无外部 deps 或 cgo)

  • 可执行为独立语言或 REPL

  • 案例:规则引擎,状态机,数据管道,翻译器(如 tengo 到 lua)

性能如何呢?

yQbMfuz.png!web

Tengo 支持几种使用方式。

1)作为 Go 包,嵌入 Go 中使用,比如:

package main

import (
 "context"
 "fmt"

 "github.com/d5/tengo/v2"
)

func main() {
 // Tengo script code
 src := `
each := func(seq, fn) {
    for x in seq { fn(x) }
}

sum := 0
mul := 1
each([a, b, c, d], func(x) {
 sum += x
 mul *= x
})`

 // create a new Script instance
 script := tengo.NewScript([]byte(src))

 // set values
 _ = script.Add("a", 1)
 _ = script.Add("b", 9)
 _ = script.Add("c", 8)
 _ = script.Add("d", 4)

 // run the script
 compiled, err := script.RunContext(context.Background())
 if err != nil {
  panic(err)
 }

 // retrieve values
 sum := compiled.Get("sum")
 mul := compiled.Get("mul")
 fmt.Println(sum, mul) // "22 288"
}

编译运行使用 Go 来处理。需要按照 Tengo:

go get github.com/d5/tengo/v2

2)作为独立脚本使用

先安装 Tengo CLI:

go get github.com/d5/tengo/cmd/tengo

写下如下脚本:

fmt := import("fmt")
// 注意 p 是小写的
fmt.println("Hello Tengo!")

保存为:hello.tengo,之后执行如下命令:

tengo hello.tengo

输出:

Hello Tengo!

3)类似 Python,REPL 方式运行

很简单,输入 tengo 回车,然后交互式输入:

>> fmt := import("fmt")
{printf: <user-function>, println: <user-function>, sprintf: <user-function>, print: <user-function>, __module_name__: "fmt"}
>> fmt.println("Hello Tengo!")
Hello Tengo!
<undefined>
>>

相关文档

目前官方提供了如下文档,通过这些文档可以看到该脚本语言支持的功能。

  • 语言语法:https://github.com/d5/tengo/blob/master/docs/tutorial.md

  • 对象类型:https://github.com/d5/tengo/blob/master/docs/objects.md

  • 运行时类型:https://github.com/d5/tengo/blob/master/docs/runtime-types.md

  • 操作符:https://github.com/d5/tengo/blob/master/docs/operators.md

  • 内置函数:https://github.com/d5/tengo/blob/master/docs/builtins.md

  • 互通性:https://github.com/d5/tengo/blob/master/docs/interoperability.md

  • Tengo 命令行:https://github.com/d5/tengo/blob/master/docs/tengo-cli.md

  • 标准库:https://github.com/d5/tengo/blob/master/docs/stdlib.md

另外还提供了 VSCode 和 Atom 的语法高亮插件。

目前标准库不多,只有如下几个:

fABNnez.png!web

在线 Playground

官方还提供了在线试验的 Playground:https://tengolang.com,有兴趣的可以试试!

文末 「阅读原文」 可直达项目首页。

今天的项目大家觉得怎么样吗?如果你喜欢,请在文章底部留言、点赞或关注转发,你的支持就是我持续更新的最大动力!

推荐阅读

OpenSourceDaily - 送给爱开源的你

jyQjyay.jpg!web

Git · GitHub · GitLab · Gitee


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK