Search code examples
javascriptpythoncompiler-constructiontranslate

Translate JavaScript enter and exit methods into Python


I'm trying to translate The Super Tiny Compiler by James Kyle from JavaScript into Python.

But I'm having trouble understanding what the enter and exit methods from JavaScript do:

1)

// If there is an `enter` method for this node type we'll call it with the
// `node` and its `parent`.
if (methods && methods.enter) {
  methods.enter(node, parent);
}

2)

// If there is an `exit` method for this node type we'll call it with the
// `node` and its `parent`.
if (methods && methods.exit) {
  methods.exit(node, parent);
}

How can I translate these two methods in to Python? Thank you.

Here's a link to the Tiny Compiler code


Solution

  • You will find out it in the next file "4-tranformer.js". enter and exit are just methods of an object methods in visitor. Pay attention to this peace of code:

    // We start by testing for the existence of a method on the visitor with a
    // matching `type`.
    let methods = visitor[node.type];
    

    In the code you posted we just check if the methods object has a method exit or enter and call them if it does.