0

I'm working on a JS Analizer, but I found a library called Esprima.NET and I started to analize the code but there is lot of code to read and It will take me months to get its algorithm. Well, I have finished the Lexical Analyzer but right now I am struggling on the Syntax Analyzer and I noticed that the parse method returns a node of nodes forming an abstract tree. I don't know how to print the nodes like a tree.

This is my code:

main.cs

static StreamReader file = new StreamReader(@"prueba.js");
    static void Main(string[] args)
    {
        var esprima = new Esprima.NET.Esprima();
        var code = file.ReadToEnd();
        //var tokenize = esprima.tokenize(code, new Options());
        var node = esprima.parse(code, new Options());

        Console.WriteLine(node);
        Console.ReadLine();


    }

Esprima.cs (I will just show the parser method and its references)

public Node parse(string code, Options options)
    {
       //Here goes the logic of parsing options, but I deleted it
       //just for simplify large code

        var program = parseProgram();
        return program;
    }        

//here goes the node
public Node parseProgram()
    {
        List<Node> body;
        Node node;

        peek();
        node = new Node();

        body = parseScriptBody();

        return node.finishProgram(body, state.sourceType);
    }

This is what my main.cs prints: what it prints

Reyneer Leon
  • 356
  • 2
  • 14

1 Answers1

0

You're going to have to write something that loops through all the Node objects in the body list too. I'd expect, if it's a tree, that each of those Nodes might have a body with a list of Nodes.. and each of those Nodes will also have a body of Nodes.. and each of..

You get the idea.

So you'll have to decide, do you want to print it out depth first or breadth first - do you go all the way to the deepest first node of every body, print it, come up, move to the next node, go down again... or do you get the first node, print all the Nodes in its body, then visit the first body node, print all that Node's body Nodes, then the second..

All a lot easier to explain with diagrams, and fortunately someone else has done an awesome job of laying it out in this SO accepted answer:

Breadth First Vs Depth First

So now you need to implement a BF or DF traversal of your tree and print every node, not just the head one

Caius Jard
  • 72,509
  • 5
  • 49
  • 80