2 ms·
You don't have to know the level of nesting; you can add indents afterward just as easily as you can wrap a subexpression in parentheses afterward. def indent(
by abecedarius 18y ago
You don't have to know the level of nesting; you can add indents afterward just as easily as you can wrap a subexpression in parentheses afterward.
def indent(code): return code.replace('\n', '\n ')
- scott_s 18y agoIn my current project, I've implemented a source-to-source compiler. In the places where I emit C code, I usually don't have a handle to the scopes above me. I could get one, but it would take more work. The code I generate has no indents and no newlines. Not having to keep track of these makes life simpler. To make my generated code more legible, I just run indent on it.
- abecedarius 18y agoI've written C code emitters too. FWIW, I've found nicely-indented output templates help to keep the source code of the emitter clear (and with no need to get at the enclosing scopes). But the question you raised was whether indentation-only was harder to generate, and I'd say no, because code.replace('\n', '\n ') is as simple as '{' + code + '}', if slightly slower.
- scott_s 18y agoAnd my point was that with the transformations I generate, I don't just say '{' + code + '}'. I'm applying transformations to existing code, not generating all of my own code from scratch. Again, I see no point in making efforts to generate clean looking code when utilities like indent exist.