Skip to content

Commit 18cfcb3

Browse files
committed
make sure shebang is always emitted first
1 parent 2439c81 commit 18cfcb3

3 files changed

Lines changed: 51 additions & 1 deletion

File tree

nattlua/emitter/base.lua

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,18 @@ return function()
508508
end
509509

510510
function META:BuildCode(block)
511+
local statements = block.statements
512+
local first_statement = statements and statements[1]
513+
local has_leading_shebang = first_statement and first_statement.Type == "statement_shebang"
514+
515+
if has_leading_shebang then
516+
self:EmitStatement(first_statement)
517+
518+
if statements[2] or (block.imports and not self.config.skip_import) then
519+
self:Whitespace("\n")
520+
end
521+
end
522+
511523
if block.imports and not self.config.skip_import then
512524
self.done = {}
513525
self:EmitNonSpace("_G.IMPORTS = _G.IMPORTS or {}\n")
@@ -564,7 +576,18 @@ return function()
564576
end
565577
end
566578

567-
self:EmitStatements(block.statements)
579+
if has_leading_shebang then
580+
local remaining = {}
581+
582+
for i = 2, #statements do
583+
remaining[#remaining + 1] = statements[i]
584+
end
585+
586+
self:EmitStatements(remaining)
587+
else
588+
self:EmitStatements(statements)
589+
end
590+
568591
local str = self:Concat()
569592

570593
if self.config.trailing_newline and str:find("\n", nil, true) then

test/tests/nattlua/emitter.lua

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,30 @@ local function identical(str)
2121
check({pretty_print = true}, str)
2222
end
2323

24+
do
25+
local output = assert(
26+
nl.Compiler(
27+
[[#!/usr/bin/env lua
28+
local dep = import("./shebang_import_dep.nlua")]],
29+
nil,
30+
{
31+
parser = {
32+
working_directory = "test/tests/nattlua/",
33+
emit_environment = false,
34+
},
35+
emitter = {
36+
pretty_print = true,
37+
force_parenthesis = true,
38+
string_quote = "\"",
39+
},
40+
}
41+
):Emit()
42+
)
43+
44+
assert(output:find("^#!/usr/bin/env lua\n_G%.IMPORTS = _G%.IMPORTS or %{%}\n") ~= nil)
45+
assert(select(2, output:gsub("#!", "")) == 1)
46+
end
47+
2448
check(
2549
{pretty_print = true, force_parenthesis = true, string_quote = "\""},
2650
[[local foo = aaa 'aaa'-- dawdwa
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
return {
2+
ok = true,
3+
}

0 commit comments

Comments
 (0)