Converting Antlr parse tree to JSON in GO

289 views
Skip to first unread message

gish...@gmail.com

unread,
Aug 22, 2019, 10:54:20 AM8/22/19
to golang-dev
Hi Guys, 

I am trying to replicate the following solution (https://stackoverflow.com/questions/49116223/convert-antlr-parse-tree-to-json) in Golang.  Below is my code so far:
Following is my parse tree and output after testing the code below. I have also included the expected JSON output.  Is there something I missing in the recursion, or pass by reference vs pass by value?

Many thanks, 

func toMap(tree antlr.Tree) *linkedhashmap.Map {
    m := linkedhashmap.New()
    traverseMap(tree, m)
    return m
}

func traverseMap(tree antlr.Tree, m *linkedhashmap.Map) {
    if (reflect.TypeOf(tree) == reflect.TypeOf(&antlr.TerminalNodeImpl{})) {
        token := tree.(antlr.TerminalNode).GetSymbol()
        m.Put("type", token.GetTokenType())
        m.Put("text", token.GetText())

    } else {
        children := arraylist.New()
        s := reflect.ValueOf(tree).Type().Elem().Name()
        m.Put(s, children)
        for i := 0; i < tree.GetChildCount(); i++ {
            nested := linkedhashmap.New()
            children.Add(nested)
            traverseMap(tree.GetChild(i), nested)
        }
    }
}

func main() {
    input, _ := antlr.NewFileStream("../input/sample-mvbag-rich.toml")
    lexer := parser.NewVeloLexer(input)
    stream := antlr.NewCommonTokenStream(lexer, 0)
    p := parser.NewVeloParser(stream)
    p.RemoveErrorListeners()
    p.AddErrorListener(errorListiner)
    p.BuildParseTrees = true
    tree := p.Velo()
    j := toMap(tree)
    println(j.Size())
    strB, _ := j.ToJSON()
    print(string(strB))
    //antlr.ParseTreeWalkerDefault.Walk(NewVeloListener(), tree)
}  

Screenshot 2019-08-22 at 15.00.08.png


Screenshot 2019-08-22 at 15.03.14.png


{
"VeloContext": [
{
"AuthorContext": [
{
"...": [
{
"type": 7,
"text": "Gervasius Ishuuwa"
}
]
}
],
"OrchestrationContext":[
....
]
}
]
}

Benny Siegert

unread,
Aug 22, 2019, 11:15:05 AM8/22/19
to gish...@gmail.com, golang-dev
This should go on golang-nuts instead. This mailing list is for discussion of the development of Go itself. Thanks.

--
You received this message because you are subscribed to the Google Groups "golang-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-dev+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-dev/ab8822cf-41d6-494c-baf4-8cf7c5ef9737%40googlegroups.com.


--
Benny
Reply all
Reply to author
Forward
0 new messages