Skip to content

A BodyFactory that writes only blank lines emits a declaration with no body: public void M() (CS0501) #119

Description

@matt-edmondson

What's wrong

TemplateRendering.WriteBody (CodeBlocker/Templates/TemplateRendering.cs) decides between an empty body ({ }), a one-line expression body, and a braced block by counting the lines returned by SplitLines. A factory that writes only blank lines is not counted as empty.

  • One cb.NewLine() renders to "\n". SplitLines removes the trailing empty entry and returns [""]. That is lines.Length == 1, so the one-line branch writes " " + "": a declaration with no body and no ;.
  • Two NewLine() calls take the multi-line branch. That branch splices only blank lines, so again no body is written.

WriteExpressionBody in the same file already skips blank lines explicitly. WriteBody does not.

Reproduction

new MethodTemplate
{
    Name = "M", Type = "void", Keywords = { "public" },
    BodyFactory = cb => cb.NewLine(),
}.WriteTo(CodeBlocker.Create());
BodyFactory Output
cb => { } public void M() { } (correct)
cb => cb.NewLine() public void M() (no body)
cb => { cb.NewLine(); cb.NewLine(); } public void M() followed by blank lines (no body)

I confirmed this with a small console program against the net8.0 build. The generated method does not compile: CS0501, "must declare a body because it is not marked abstract, extern, or partial". Constructors and operators render through the same WriteBody path, so they are affected too.

Why it matters

Body factories are often conditional generator code, for example foreach (var x in items) cb.WriteLine(...) followed by a spacing NewLine(). When the collection is empty, the generator emits C# that does not compile. It should emit an empty body.

Suggested fix / acceptance criteria

  • In WriteBody, trim leading and trailing blank lines the same way WriteExpressionBody does. A body that is entirely blank takes the lines.Length == 0 path and writes { }.
  • Add tests: a single NewLine() and a double NewLine() in the body both produce public void M() { }. Cover a constructor template as well.
  • Keep blank lines between non-blank lines of a braced body as they are.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingreadyFully specified; implement as written

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions