Recursion and Pass by Reference vs Pass by Value


(Siuslam) #1

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:
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"
    "github.com/antlr/antlr4/runtime/Go/antlr"
    "github.com/emirpasic/gods/lists/arraylist"
    "github.com/emirpasic/gods/maps/linkedhashmap"
)

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)
}