Skip to content

Instantly share code, notes, and snippets.

@sangupta
Created Apr 27, 2022
Embed
What would you like to do?
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())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment