Skip to content

Instantly share code, notes, and snippets.

@sangupta
Created April 27, 2022 05:50
Show Gist options
  • Save sangupta/070edef1bc1aec675d47eb3b44ad1b24 to your computer and use it in GitHub Desktop.
Save sangupta/070edef1bc1aec675d47eb3b44ad1b24 to your computer and use it in GitHub Desktop.
Parse Typescript code in Go lang using v8go. The idea is to re-use the original Typescript library than rolling out a parser of our own.
package main
import (
"fmt"
"io/ioutil"
v8 "rogchap.com/v8go"
)
func main() {
// create a new VM
ctx := v8.NewContext()
// read typescript.js from file system
tsSource, err := ioutil.ReadFile("/path/to/typescript/lib/typescript.js")
if err != nil {
panic(err)
}
// load typescript
ctx.RunScript(string(tsSource), "typescript.js")
// read global object
obj := ctx.Global()
typescript, _ := obj.Get("ts")
ts, _ := typescript.AsObject()
// fmt.Println(typescript.IsObject())
moduleKindJs, _ := ts.Get("ScriptTarget")
moduleKind, _ := moduleKindJs.AsObject()
systemJs, _ := moduleKind.Get("Latest")
system := systemJs.String()
fnJs, _ := ts.Get("createSourceFile")
fn, _ := fnJs.AsFunction()
// all set
// read the source code file
jsFile, err := ioutil.ReadFile("/path/to/typescript/source/index.ts")
if err != nil {
panic(err)
}
// empty := make(map[string]interface{}, 0)
isolate := ctx.Isolate()
ctx.RunScript("const compilerOptions = { module: "+system+"};", "source-tree.js")
sourceFileName, err := v8.NewValue(isolate, "index.ts")
sourceCode, err := v8.NewValue(isolate, string(jsFile))
compilerOptions, _ := ctx.RunScript("compilerOptions", "source-tree.js")
booleanTrue, err := v8.NewValue(isolate, true)
fnValue, _ := fn.Call(ctx.Global(), sourceFileName, sourceCode, compilerOptions, booleanTrue)
if err != nil {
e := err.(*v8.JSError) // JavaScript errors will be returned as the JSError struct
fmt.Println(e.Message) // the message of the exception thrown
fmt.Println(e.Location) // the filename, line number and the column where the error occured
fmt.Println(e.StackTrace) // the full stack trace of the error, if available
fmt.Printf("javascript error: %v", e) // will format the standard error message
fmt.Printf("javascript stack trace: %+v", e) // will format the full error stack trace
return
}
// fnValue contains the parsed AST
fmt.Println(fnValue.IsObject())
// fmt.Println(fnValue.DetailString())
}
@mmaico
Copy link

mmaico commented Mar 21, 2023

Hi Sangupta, I read your article, but I think the ts and js files were missing for me to be able to make the comparison.

I need call the function default of this file js file

In Java i call using this code

But in GoLang I am not able to run. Could you help me with this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment