Note that there are some explanatory texts on larger screens.

plurals
  1. POCompiling an AST back to source code
    primarykey
    data
    text
    <p>I'm currently in the process of building a PHP Parser written in PHP, as no existing parser came up in <a href="https://stackoverflow.com/questions/5586358/any-decent-php-parser-written-in-php">my previous question</a>. The <a href="https://github.com/nikic/PHP-Parser" rel="nofollow noreferrer">parser itself</a> works fairly well.</p> <p>Now obviously a parser by itself does little good (apart from static analysis). I would like to apply transformations to the AST and then compile it back to source code. Applying the transformations isn't much of a problem, a normal Visitor pattern should do.</p> <p>What my problem currently is, is how to compile the AST back to source. There are basically two possibilities I see:</p> <ol> <li>Compile the code using some predefined scheme</li> <li>Keep the formatting of the original code and apply 1. only on Nodes that were changed.</li> </ol> <p>For now I would like to concentrate on 1. as 2. seems pretty hard to accomplish (but if you got tips concerning that, I would like to hear them).</p> <p>But I'm not really sure which design pattern can be used to compile the code. The easiest way I see to implement this, is to add a <code>-&gt;compile</code> method to all Nodes. The drawback I see here, is that it would be pretty hard to change the formatting of the generated output. One would need to change the Nodes itself in order to do that. Thus I'm looking for a different solution.</p> <p>I have heard that the Visitor pattern can be used for this, too, but I can't really imagine how this is supposed to work. As I understand the visitor pattern you have some <code>NodeTraverser</code> that iterates recursively over all Nodes and calls a <code>-&gt;visit</code> method of a <code>Visitor</code>. This sounds pretty promising for node manipulation, where the <code>Visitor-&gt;visit</code> method could simply change the Node it was passed, but I don't know how it can be used for compilation. An obvious idea would be to iterate the node tree from leaves to root and replace the visited nodes with source code. But this somehow doesn't seem a very clean solution?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload