Skip to content

Option to add leading trivia to Lua compilation units #524

@alrun3

Description

@alrun3

When the output from CSharp.lua is loaded into another Lua script, it would be useful to support injecting statements around each do ... end block for preprocessors or tools to consume:

---@beginFile "Program.cs" 
---@debug
do
local System = System
System.namespace("Source", function (namespace)
  namespace.class("Program", function (namespace)
    local Main
    Main = function ()
      System.Console.WriteLine("Hello World from C#")
    end

Currently, there is no built-in way for consumers to influence the structure of these generated blocks without forking and modifying the project directly.

I’d like to propose adding support for hooking into the compilation process, allowing consumers to customize the output without changing the source code. This could follow a pattern similar to the builder model commonly used in .NET, where Action<T> delegates are registered and invoked in sequence:

public class CodeGenerationSettings
{
    private readonly List<Action<TextWriter, string, bool>> _beforeSystemLibStart = new();
    private readonly List<Action<TextWriter, LuaCompilationUnitSyntax>> _beforeCompilationUnitStart = new();

    public void ConfigureSystemLibStart(Action<TextWriter, string, bool> hook) => _beforeSystemLibStart.Add(hook);
    public void ConfigureCompilationUnitStart(Action<TextWriter, LuaCompilationUnitSyntax> hook) => _beforeCompilationUnitStart.Add(hook);
}

Consumers could then register their own behaviors like:

settings.CodeGeneration.ConfigureCompilationUnitStart((writer, unit) =>
{
    writer.WriteLine($"---@beginFile \"{Path.GetFileName(unit.FilePath)}\"");
    writer.WriteLine("---@debug");
});

As an alternative, these annotations could be represented more formally using the LuaDocumentStatement in the AST. However, the hook-based approach is more powerful and avoids structural changes to the syntax tree or emit pipeline.

I'd be happy to contribute a PR if this proposal is acceptable

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions