Indentation for code generation

Often programmers write code that generates other code.

(The technical term is metaprogramming , but it's more than just cross-compilers, think of every PHP web page that generates HTML or every XSLT file.)

One area that I find difficult is coming up with methods that provide a clear imprint of both the original source file and the computer object file to help debug. It seems that the two goals are competing.

I find this particularly difficult in the combination of PHP / HTML. I think this is because:

  • sometimes more HTML code in the source file than PHP generation
  • HTML files tend to be longer than, say, SQL statements, and require better indentation
  • HTML has spatially sensitive functions (e.g. between tags)
  • the result is more readily accessible HTML than SQL statements, so there is more pressure to do reasonable work.

What methods do you use to solve this problem?

<h / "> Edit: I agree that there are at least three arguments so as not to worry about creating pretty HTML code:

  • The complexity of code generation is increasing.
  • It doesn’t matter for browser rendering; developers can use Firebug or similar to view it.
  • The performance drawback is the increase in loading time for whitespace characters.

Of course, I sometimes generated code without thinking about backtracking (especially SQL).

However, there are several arguments that speak in a different way:

  • I find, in practice, that I often read the generated code - the presence of additional steps for its access is inconvenient.
  • HTML , .

, :

<div class="foo">
    <?php
        $fooHeader();
        $fooBody();
        $fooFooter();
    ?>
</div>

, :

<div class="foo"><?php
        $fooHeader();
        $fooBody();
        $fooFooter();
?></div>

- , HTML.

+5
8

XSLT-, ++. XSLT, . , XSLT, GNU. ++, .

, , HTML PHP.

+4

, , , .

, Python, Python.

def generateWhileLoop(condition, block, indentPrefix = ""):
    print indentPrefix + "while " + condition + ":"
    generateBlock(block, indentPrefix + "    ")

, :

def generateWhileLoop(condition, block, indentLevel = 0):
    print " " * (indentLevel * spacesPerIndent) + "while " + condition + ":"
    generateBlock(block, indentLevel + 1)

, condition - , , block - . , .

, PHP HTML.

[, : , . , , , PHP-, , .]

+3

AST, , .

+3

, . , . , . .

+2

.

, . , , , . , , , .

+1

- PHP, , HTML PHP , . , , , ., , Smarty. , , , , . , , PHP-, ( ).

+1

, HTML - ?

, .. , ( ), , HTML div ..?

, Firebug ( IE IE ), HTML . , - WAY , HTML-.

0

In the PHP / HTML situation, I try to ensure that each piece of code is sequentially indented in the source code. This allows you to read code where it really matters, and usually has a side effect for getting HTML output that you can read. As others have said, firebug takes care of the rest.

0
source

All Articles