Skip to content

Transpiler: closure structs from local functions capturing byte[] arrays #226

@jonathanpeppers

Description

@jonathanpeppers

Follow-up from PR #211 (crypto.c sample port).

When local functions in top-level statements reference outer byte[] variables, the C# compiler generates closure structs. The transpiler fails with:

System.InvalidOperationException: Cannot resolve struct type for local 0 with field 'palette'

Root cause

In C# top-level statements, all defined functions are local functions of the implicit Main method. When any local function references a byte[] array from the outer scope, the compiler wraps captured variables in a display class. The transpiler encounters stfld/ldfld on this compiler-generated struct and fails.

Workaround

  1. Inline all capturing functions into the main body (eliminates closures but loses abstraction)
  2. Convert to partial class methods with byte[] parameters (works for functions with few captures)
  3. Use const values instead of byte[] where possible (consts are compile-time inlined, no closure)

Long-term fix

Either teach the transpiler to handle compiler-generated closure types, or provide guidance to users to structure code to avoid closures (e.g., use partial class Program methods with parameters).

Metadata

Metadata

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions