lunarmodules / Penlight

A set of pure Lua libraries focusing on input data handling (such as reading configuration files), functional programming (such as map, reduce, placeholder expressions,etc), and OS path management. Much of the functionality is inspired by the Python standard libraries.
https://lunarmodules.github.io/Penlight/
MIT License
1.9k stars 238 forks source link

enhance(template): Preserve line numbers #468

Closed RiskoZoSlovenska closed 5 months ago

RiskoZoSlovenska commented 7 months ago

This PR tweaks the template module to build intermediate template code where instructions have the same line numbers as in the original template.

For example, with the old behaviour, the template

# local foo = 1
a $(foo + 1) b
# bar()

would have resulted in the following intermediate code:

return function()
local __R_size, __R_table, __tostring = 0, {}, __tostring
 local foo = 1
__R_size = __R_size + 1; __R_table[__R_size] = "a "
__R_size = __R_size + 1; __R_table[__R_size] = __tostring((foo + 1) or '')
__R_size = __R_size + 1; __R_table[__R_size] = " b\
"
 bar()
return __R_table
end

If bar() were to produce an error, Lua would report it as occurring on line 8, which is completely unhelpful. However, after this PR, the above template will produce the following code:

return function() local __R_size, __R_table, __tostring = 0, {}, __tostring;  local foo = 1
 __R_size = __R_size + 1; __R_table[__R_size] = "a "; __R_size = __R_size + 1; __R_table[__R_size] = __tostring((foo + 1) or ''); __R_size = __R_size + 1; __R_table[__R_size] = " b\
"; bar()
return __R_table; end

While less readable, any errors will now be reported as occurring on the same line as in the original template, which greatly eases debugging, since it's often easy to pinpoint the source of error just by looking at the right line in the template string.

Essentially, this PR only swaps out some newlines for spaces and semicolons; the actual rendering behaviour of templates should remain unchanged. It also works when the newline option is truthy; stripped newlines aren't removed completely, just moved out of the appender statements and into the intermediate Lua code.

RiskoZoSlovenska commented 6 months ago

CI failures appear to be unrelated and transient