Parse and Execute another code.. from a go program


(Ravi Raju) #1

Hi,
I am trying to write a program that will take in a text formatted code and parse it and execute it.

The program parsed does not have to be very complex (in that case i need a full fledged compiler) - but instead
a simpler programming language (very very simple is ok). I am thinking of using “go/parser” package to parse the code into an AST and i don’t know if someone has experimented with executing the AST…

Thanks!
Ravi


(Giulio Iotti) #2

Basically you want to create an interpreted language. Not sure the go AST is any use: it is made for Go and Go might not be simple enough for your needs.

What are your needs? What do you need an interpreter for?

Obviously there exist several written in Go: Javascript, Lisp, declarative configuration syntaxes…


(Ravi Raju) #3

Is there a way to execute a AST ? Or AST can be converted into some form to be executed ?

Certain parts (logic) of my program i want to be adaptive, so don’t want to hard-code it into my program (binary). Putting this logic into a go-plugin is one option. But that still requires developer to build and provide the plugin. Instead the logic (to start with is simple) can be coded in this limited syntax language and can be uploaded to the program. Program converts the logic into a format that it can execute in a fast manner (not as fast a fully compiled and optimized code)…

One parallel i can think of is how regular expression is first compiled into a FSM and that FSM can be executed over an input string to find if there is a match or not (https://golang.org/pkg/regexp/#Compile)

i know there are safety considerations since it can be point of attack… but i am looking at the capability first and then will secure it.

Thanks!


(Giulio Iotti) #4

Yes, I see what you mean. But no, the AST is not executable. The Go Compiler does a bunch of other things before emitting an executable. In fact, “go run”, which gives the impression of interpreting a Go file, actually compiles and writes to a temporary file that it executes (basically, it does a “go build && ./binary-file”.)

Simple solution: make the Go Compiler (the “go” command) a dependency of your program and compile on demand. It is still quite a suspicious solution, but there are use cases.

For normal plugins, better than dynamic loading, you can just run other binaries and communicate via standard input and output with them. Check out “pie”: https://github.com/natefinch/pie


(Kristoffer Berdal) #5

What you are looking for here is essentially a embedded programming language, as far as I understand it. Lua is a great language for this, and there are several implementations in Go! I’m on my phone right now, but just search for Lua and Go. I’ll try to find a link once I’m back at a computer.


(system) #6

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.