1. 4
  1. 2

    Looks like the example given bring no value comparing to a standard program. More realistic examples should behave better. See also cog program generator.

    1. 1

      This looks interesting, thanks for posting it!

      If I’m understanding the problem correctly, you want to decouple the indentation of the code generator from the generated code? I have felt that annoyance before in writing Python that generates Python or C++.

      Here’s one example. It’s not horrible, but it’s not ideal either:


      This one is a little more messy:


      However I don’t quite understand why this indentation problem leads to “tiles”, in particular the + operator displayed in “worked example 1” here.


      Ican’t think of any example where you need to align text side by side in tiles like this when generating code. All programming languages work top-to-bottom, they don’t really have any horizontal structure.

      The only case I could think of is when generating text in HTML <pre> tags, e.g. for the ASCII art table. But that’s very different than generating code.

      I was thinking of a design using Python context managers. Here’s an example, untested:

      f = IndentedOutput()  # context manager
      f.write('for x in items:')
      with f.indent():
        f.write('x = 1')
        for var_name in ['a', 'b', c']:
          f.write('%s = 2'  % var_name)
        f.write('if x:')
        with f.indent():
          # leading space stripped here; indentation in the context manager is respected instead
        f.write('print "done one loop iteration"')
      f.write('print "done program"')

      Would something like that solve your problems? I believe it’s significantly simpler than tiles and addresses the code generation use case.

      I’m sure someone has done something like this before, but I haven’t seen it. I have seen context managers used to manage opening/closing ANSI escape sequences, so using them to manage indentation is natural.