Is there an interpreter that returns an extended AST?

2

I'm using an interpreter that returns an AST that I do not know how I'm going to read.

{
    clauses: [
        {
            body: [/* ...*/],
            condition: {/* ...*/},
            type: "IfClause"
        }
    ],
    type: "IfStatement"
}

I have to do a single loop to deal with this tree and a lot of conditions to memorize the property I passed inside, etc. I'm sure I'm doing it the wrong way, so I'd like another kind of tree.

{
    type: "IfClause"
},
{
    type: "Literal",
    value: false
},
{
    type: "BlockStatement"
},
{
    type: "Endif"
}

Or is there another solution?

    
asked by anonymous 16.04.2016 / 12:22

1 answer

2

Basically what you are wanting will hardly be supported natively since the very concept of a tree is hierarchical in nature.

What is your goal? Is it just to "look" and get to see what you want more easily? Or would it be to process the generated tree code?

A list is simpler for you to see, but it is much more complicated to process, since you will have to recreate all the contexts of each block.

If you have difficulties with these blocks, you might just need to get a little more accustomed with recursive algorithms, for example.

Transforming the list

If you really need it, a flat list can be generated by processing AST.

Suppose you have the following dummy tree:

var astTree = {
    type: "IfClause",
    base:
    {
        type: "Boolean",
        value: false
    },
    body: [
        { type: "Var" },
        { 
            type: "ForClause",
            body: [
                { type: "VarIncrement" }
            ]
        },
        { type: "Return" },
    ]
};

So you can rely on a recursive function that traverses all subelements that have a body and add to an array. Example:

var flatten = function(node) {
    var list = [];
    function consume(node) {
        list.push(node);
        if ('body' in node) {
            var endNode = { type: node.type + 'End' }
            node.type += "Start";
            node.body.forEach(consume);
            list.push(endNode);
            delete node.body;
        }
    }
    consume(node);
    return list;
}

And the result is:

[
  {
    "type": "IfClauseStart",
    "base": {
      "type": "Boolean",
      "value": false
    }
  },
  {
    "type": "Var"
  },
  {
    "type": "ForClauseStart"
  },
  {
    "type": "VarIncrement"
  },
  {
    "type": "ForClauseEnd"
  },
  {
    "type": "Return"
  },
  {
    "type": "IfClauseEnd"
  }
]

See the functional example

    
19.04.2016 / 05:02