How to convert Antlr parse tree to JSON

103 views
Skip to first unread message

Gervasius Ishuuwa

unread,
Aug 22, 2019, 9:34:15 AM8/22/19
to antlr-discussion

HI Guys,  I am trying to replicate the solution in Golang. I am not getting the nested map as expected, instead I am only getting the head node. Below is my code thus far:
A snapshot of my parse tree and debug output are attached herewith. 
Many thanks:

package main

import (
    "encoding/json"
    "reflect"
    "strconv"
    "strings"
    "time"

    "../parser"
    "./docker"
    "./kubernetes"
    "./orchestrator"
    "./utils"
)

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

Gervasius Ishuuwa

unread,
Aug 22, 2019, 9:52:13 AM8/22/19
to antlr-discussion


On Thursday, 22 August 2019 15:34:15 UTC+2, Gervasius Ishuuwa wrote:

HI Guys,  I am trying to replicate the solution (
https://stackoverflow.com/questions/49116223/convert-antlr-parse-tree-to-json
) in Golang. I am not getting the nested map as expected, instead I am only getting the head node. Below is my code thus far:
Reply all
Reply to author
Forward
0 new messages