v0.29.0—Sharper bug analysis, reliable resource cleanup, and stronger test and CI checks.See what's new

convert

Convert a single file between C# and Calor.

Bash
calor convert <input> [options]

Overview

The convert command performs bidirectional conversion between C# and Calor:

  • C# → Calor: Convert .cs files to Calor syntax
  • Calor → C#: Convert .calr files to generated C#

The conversion direction is automatically detected from the input file extension.


Quick Start

Bash
# Convert C# to Calor
calor convert MyService.cs

# Convert Calor to C#
calor convert MyService.calr

# Specify output path
calor convert MyService.cs --output src/MyService.calr

# Include benchmark comparison
calor convert MyService.cs --benchmark

Options

OptionShortDefaultDescription
--output-oAuto-detectedOutput file path
--benchmark-bfalseInclude benchmark metrics comparison
--verbose-vfalseEnable verbose output
--explain-efalseExplain unsupported features in detail
--no-fallback—falseFail on unsupported constructs instead of emitting fallback TODOs
--validate—falseParse generated Calor before writing and report errors
--passthrough—falseWiden the set of C# members preserved as §CSHARP interop blocks. Since 0.16 calor convert already rescues a member it cannot convert this way; see What Changed in 0.16
--lossy—falseAllow reported semantic substitutions and drops. Without it, conversion is lossless: a construct with no exact Calor form is preserved as C# or refused. The output is still compiled back to C#; if that fails, it is written but reported unverified and the command exits 2
--timeout-t0Conversion timeout in seconds; 0 disables it
--explicit-call-closers—falseEmit explicit §/C for every §C call (v0.6.0-compatible output).
--format—texttext or schema 2.0 json; there is no -f alias

Auto-Detected Output Paths

If --output is not specified:

InputOutput
MyFile.csMyFile.calr
MyFile.calrMyFile.g.cs

Supported Constructs

The converter validates generated C# before claiming a fully successful conversion. It reports semantic losses with file:line locations and exposes the same list as data.lossCount and data.losses[] in JSON. Unknown operators, patterns, compound assignments, namespace handling, and local functions no longer silently substitute a different construct.

When native conversion is impossible, the containing member is preserved as a §CSHARP interop block (for some features only the statement, as §RAW, or the expression, as §CS{...}) and counted — on the command line this happens by default, without --passthrough, which widens it further. "Conversion successful" is printed only when there are no recorded losses and requested validation passed.

In the unreleased 0.27 converter, collection expressions convert natively only for array targets without spreads or a single array-to-array spread. Other collection targets and mixed spreads stay C# to retain their runtime type and enumeration order. Declaration patterns remain native. Property and positional patterns, and other complex is checks whose lowering could change evaluation or binding, stay C# with a reported loss. See the registry entries and limits.

Which Path Preserved Each Member

Each recorded loss names the path that produced it, and the trigger that fired when a rescue or passthrough did the work:

PathMeaning
interopThe converter does not support this construct, so it kept the C#. No trigger.
rescueAutomatic rescue. The member converted, but its Calor failed to parse (parse-failure) or failed to round-trip back to compiling C# (round-trip-failure), so the original C# was kept. You did not have to ask for it.
passthroughThe C# was kept only because you asked for passthrough (--passthrough, or passthroughOnError in MCP).
lossy / droppedA substitution or removal that --lossy allowed.

enabledBy names the default or option that made a rescue possible: lossless-fidelity (parse failures are always rescued in the default lossless mode), interop-mode (the library's and MCP's interop conversion mode), rescueUnusableMembers (on by default in calor convert), or passthroughOnError. When both rescue and passthrough could have fired, the report says rescue, because the member would have been rescued without the flag. Under --lossy, C# kept only because you passed --passthrough is reported as passthrough; C# the converter keeps in every mode stays interop. So on the command line --passthrough rarely changes the report unless you also pass --lossy.

Try it on a class with a private static property that has accessor bodies (its converted C# does not compile yet, so the round trip fails):

C#
// Counter.cs
public class Counter
{
    private static int count;
    private static int Count { get { return count; } set { count = value; } }

    public int Next() { Count = Count + 1; return Count; }
}
Bash
calor convert Counter.cs -o Counter.calr
Plain Text
Conversion completed with 1 interop preservation(s), 0 lossy substitution(s), and 0 drop(s) — output is not fully native Calor:
  InteropPreserved: 1
    /home/you/demo/Counter.cs:? [post-validation-fallback] [rescue: round-trip-failure] Converted Calor for 'global::Counter' did not parse or did not survive the C# round trip; original C# preserved (#717).
  ⓘ 1 member preserved as §CSHARP interop block(s) — the output parses, but this C# still needs migrating.
  Preservation paths: 1 by automatic rescue (round-trip-failure: 1; no passthrough request needed)

The CLI prints the input's full path; /home/you/demo stands in for yours.

With --format json, every data.losses[] entry carries path, and trigger and enabledBy when they apply. data.conversionPaths summarizes the file:

Example output (not checked)
"conversionPaths": {
  "schemaVersion": 2,
  "outcome": "preserved",
  "interop": 0, "rescue": 1, "passthrough": 0, "lossy": 0, "dropped": 0,
  "triggers": { "round-trip-failure": 1 },
  "rescueUnusableMembers": true,
  "passthroughOnError": false,
  "roundTrip": "verified"
}

outcome is native, preserved, lossy, unverified, or refused. A refused conversion writes nothing, exits 1, and prints Conversion refused; no output written (automatic rescue: on, --passthrough: off).

roundTrip reports the converter's round-trip check: it compiles the generated Calor, then compiles the C# that Calor produces.

roundTripMeaning
verifiedBoth compiles succeeded.
failedA compile failed. A lossless conversion is then refused, and so is one with --select-active-preprocessor-branch-lossy. A plain --lossy conversion is written with outcome: "unverified".
deferredThe caller compiles the C# itself. calor migrate and the MCP project tools do this for the whole project at once; a failure there refuses the file.
not-runConversion stopped before the check, so the file is refused.

Schema version 2 (0.26) added roundTrip and the unverified outcome. Before 0.26, --lossy skipped the check entirely. A file whose output did not compile could then report outcome: "native", print "✓ Conversion successful", and exit 0. Before 0.25 the text said "via --passthrough fallback" for every rescue, even when you had not passed the flag.

Counts, Partial Results, and the JSON Envelope

With --format json, stdout holds exactly one schema 2.0 envelope and the text report goes to stderr, including the --verbose progress lines. Each conversion issue is a Calor1343 diagnostic whose message starts with the feature name, for example [out-var] Feature 'out-var' is partially supported…. The counts are under data:

FieldMeaning
nativeConversionCountConstructs the converter wrote as Calor. A type later replaced by a rescue still counts its constructs here
interopPreservationCount, lossySubstitutionCount, dropCountPreserved, substituted, and dropped pieces; their sum is lossCount
losses[]One entry per loss: feature, path, and trigger/enabledBy when they apply
conversionPathsThe per-file outcome and per-path counts above

So nativeConversionCount > 0 does not mean the file is native. Read conversionPaths.outcome. A conversion can be partial in these ways:

  • Preserved (outcome: "preserved", exit 0): the file is written, and some members, statements, or holes are still C#.
  • Refused (outcome: "refused", exit 1): nothing is written. This happens when --no-fallback meets a construct with no Calor form, or when no rescue applies.
  • Unverified (outcome: "unverified", exit 2, plain --lossy only): the file is written, but its C# does not compile. The report prints ✗ Round-trip check failed with the first compiler errors. Fix the output by hand, or rerun without --lossy: the default lossless mode keeps a failing type as C# where it can. The check compiles the file on its own, so a file that uses a type declared in another file of your project is also unverified. --passthrough does not change this outcome under --lossy.

A rescue keeps the original C# of the whole top-level type, not only the member that failed. The C# interoperability guide lists, per feature, which shapes convert natively in 0.25 and which stay C#, with the CLI and MCP transcripts behind each example.

C# ConstructCalor Equivalent
namespace§M{id:Name} module
class§CL{id:Name:vis} class
class method§MT{id:Name:vis} method
property§PROP{id:Name:vis:type} property
field§FLD{id:type:name} field
if/else if/else§IF{id} / §EI / §EL branches (end at dedent)
for loop§L{id:var:from:to:step}
while loop§WH{id}

Local Functions

Since 0.25 (#847), a C# local function converts natively when it is in this slice:

  • declared directly in a method body (not in a block, lambda, constructor, accessor or operator);
  • no capture of the enclosing locals, parameters or this (a static local function always qualifies);
  • no attributes, type parameters, async, unsafe or extern, no ref return, no yield, no nested local function, and plain by-value parameters without default values or attributes;
  • its name is used only as a call, a call argument, or (outside lambdas) a binding initializer, return value or simple assignment value. Other uses, such as an array element, keep the member as C#.

It becomes a nested §F in the same method, and the compiler emits it back as a C# static local function in the same place. So a call keeps naming the local function, even when the class has a method with the same name. Converted output compiles with default options; --permissive-effects is not needed for these members.

C#
public static class Probe
{
    public static int Add(int x) => x + 1000;

    public static int UseShadow()
    {
        int Add(int x) => x + 1;
        return Add(2);   // 3, not 1002
    }
}

converts to:

Calor
§M{m001:Probe}
  §CL{c001:Probe:pub:stat}
    §MT{m002:Add:pub:stat} (i32:x) -> i32
      §R (+ x 1000)

    §MT{m003:UseShadow:pub:stat} () -> i32
      §F{f001:Add} (i32:x) -> i32
        §R (+ x 1)
      §R §C{Add} 2

If a member has any local function outside the slice (capturing, generic, async, iterator, and so on), the whole member is preserved as a §CSHARP block, reported as a local-function issue and counted as a loss, exactly as before. --no-fallback refuses it by name. The language rules are in Local Functions.

Iterator Properties and Indexers

A C# property or indexer getter that uses yield return or yield break is an iterator accessor. Calor has no iterator accessors: §YIELD inside a §GET is rejected with Calor0209 (illegal yield). So the converter keeps the whole member as a §CSHARP block and reports it as an iterator-accessor loss.

This C# property:

C#
public IEnumerable<int> Steps
{
    get
    {
        for (int i = Start; i > 0; i--)
        {
            yield return i;
        }
    }
}

converts to:

Calor
§M{m001:Countdown}
  §U{System.Collections.Generic}
  §CL{c001:Countdown:pub}
    §FLD{i32:Start:pub} = 3

    §CSHARP{
    public IEnumerable<int> Steps
    {
        get
        {
            for (int i = Start; i > 0; i--)
            {
                yield return i;
            }
        }
    }
    }§/CSHARP

The C# compiler still builds the iterator, so behavior does not change: the body runs only when someone enumerates the result, a finally runs when the enumerator is disposed (for example after a break in foreach), and an exception surfaces on the MoveNext call that reaches it.

This happens in the converter itself. It is the same on calor convert (with or without --passthrough), calor migrate, the MCP calor_convert tool (with or without passthroughOnError), and the library API. With --no-fallback the conversion fails and names iterator-accessor instead.

To make the member native Calor, move the loop into an iterator method and have the getter return its result. Calling an iterator method also defers the work, so the timing is the same:

Calor
§M{m001:Countdown}
  §U{System.Collections.Generic}
  §CL{c001:Countdown:pub}
    §FLD{i32:Start:pub} = 3

    §PROP{p001:Steps:Seq<i32>:pub}
      §GET{pub}
        §R §C{CountDown}

    §MT{m002:CountDown:priv} () -> Seq<i32>
      §E{}
      §L{for1:i:Start:1:-1}
        §YIELD i

Calor has no partial members either. Every declaration of a C# 13 partial property or indexer is kept as §CSHARP, so the defining declaration ({ get; }) does not turn into a second, auto-implemented property. It is reported as partial-property, or as iterator-accessor when any part in the same file yields.

Limits.

  • Every yielding accessor is preserved; none is converted to native Calor.
  • Only the yields of the accessor itself count. A member whose yields sit in a nested local function is preserved for the local function instead.
  • When a larger declaration is already preserved for another reason, the loss names that reason. An interface whose iterator getter has a default body is kept whole as interface-property-semantics, and a record as record.
  • Iterators in ordinary methods still convert natively to §YIELD.

What Changed in 0.17

0.16 got all 364 modules to parse. 0.17 is about what happens next: a module that parses can still stop at name binding, before any of the effect checking runs. At the 0.16 branch cut, 60 of the 364 stopped there. Now 40 do, and the number of modules the effect checker reaches went from 304 to 324.

Most of that came from two fixes to how the compiler resolves calls.

Overload resolution learned the conversions C# already allows. Deciding which overload you meant was comparing parameter types too literally. Passing a PropertyEnricher to a parameter typed ILogEventEnricher — an interface the class implements — was reported as "no overload matches", and so was passing a generic parameter T to a parameter typed as one of T's own constraints.

Member lookup learned about inheritance. Looking up a method asked the receiver type for its own declarations only — nothing about base classes, base interfaces, generic constraints, or System.Object. IValidator.GetType() was "no such member" because an interface has no base type to walk; so were MethodInfo.GetParameters(), declared on MethodBase, and IList<T>.Add(item), declared on ICollection<T>. Across the same three projects, the share of call sites the compiler can resolve went from 92.8% to 95.9%.

Four converter and emitter defects are fixed alongside them. A class using §EXT emitted unqualified calls to module functions, which the C# compiler then rejected; the same function referenced as a method group rather than called had the same problem; a var bound to a method call lost its type, and with it every member access on the result; and a named argument matching no parameter crashed the binder outright.

What Changed in 0.16

Converted code is only useful if the compiler can read it back. We test that on three real open-source projects — MediatR, Serilog, and FluentValidation — which come to 364 modules.

In 0.15, 59 of those 364 modules came out of the converter as Calor the compiler could not parse. Long lambdas were written at the wrong indent, calls split across lines came out wrong, and a few other patterns tripped it. In 0.16 all 364 parse.

One more thing is fixed alongside those: when the converter could not work out a lambda parameter's type, it used to write ?, which the compiler cannot read — it gave up on the rest of that method. It now treats the parameter as untyped, and reads the type from the Func<...> or Action<...> the lambda is handed to. Between that fix and the parsing fixes above, the number of modules where the converter crashed part-way through dropped from 73 to 1 across the same three projects.

There is one change to what you get back. calor convert now often rescues a member it could not convert into working Calor, by wrapping the original C# in a §CSHARP block rather than sinking the whole file. That means converted output can contain §CSHARP blocks even when you did not pass --passthrough, and the report tells you how many. Partly converted beats nothing converted, but treat each block as work still to do.

The rescue is not a guarantee. It fires when the generated Calor fails to parse or fails to round-trip back to C#; output that parses but that Calor's own compiler then rejects still fails the conversion, with nothing written and exit 1. --passthrough does not change that outcome.

Array Expressions

An array created inside an expression, such as a return, a call argument, or a branch of ?:, converts to native Calor. The C# evaluation order is kept: each element is evaluated once, left to right, in place. The unselected branch of ?:, and the right operand of && or ||, are still not evaluated. Before 0.25, a return new T[,] { … } produced Calor whose C# did not compile, and arrays in a ?: branch did not parse. Only the post-conversion rescue (§CSHARP) hid that.

This C#:

C#
public static class Grid
{
    public static int[,] Pick(bool wide, int v)
    {
        return wide
            ? new int[,] { { v, v + 1 } }
            : new int[,] { { v } };
    }

    public static int Sum(int[] xs, int start)
    {
        int s = start;
        foreach (var x in xs)
        {
            s = s + x;
        }
        return s;
    }

    public static int Total(int v) => Sum(new int[] { v, v * 2 }, Pick(true, v)[0, 1]);
}

converts to:

Calor
§M{m001:Grids}
  §CL{c001:Grid:pub:stat}
    §MT{m002:Pick:pub:stat} (bool:wide, i32:v) -> i32[,]
      §E{alloc}
      §R §IF{tern000} wide → §ARR2D{arr2d003:arr2d003:i32} §ROW v (+ v 1) §/ARR2D{arr2d003} §EL → §ARR2D{arr2d005:arr2d005:i32} §ROW v §/ARR2D{arr2d005}

    §MT{m007:Sum:pub:stat} (i32[]:xs, i32:start) -> i32
      §B{~s:i32} start
      §EACH{each008:x:var} xs
        §ASSIGN s (+ s x)
      §R s

    §MT{m009:Total:pub:stat} (i32:v) -> i32
      §E{alloc}
      §R §C{Sum} §A §ARR{arrI32010:i32} v (* v 2) §/ARR{arrI32010} §A §IDX2D §C{Pick} §A true §A v §/C 0 1 §/C

Three forms make this work:

  • Inline §ARR2D. In expression position the array is written on one line and ends with §/ARR2D{id}, the same way §ARR already did. An object initializer used as an element stays on its §ROW line (§NEW{Cell} V = v §/NEW). The converter no longer moves it into a temporary variable ahead of the statement.
  • Rank 3 and up. §ARR2D{id:id:i32:2:1:2} followed by §ROW lines gives the shape. The rows are the innermost vectors in row-major order. A row count that does not match the shape is a C# compile error, never padded or cut.
  • Grouped element access. (§IDX2D g 0 1).V reads a member of an element. Written without the parentheses, .V attached to the last index.

Names the converter generates (_hoist000, arr2d004) skip every identifier that appears in your C# file, and in the other files of a calor migrate project. A local you named _hoist000 is never rebound.

new T[0] and an empty { } initializer convert to a fresh zero-length array. Before, they became the shared Array.Empty<T>(), so new int[0] == new int[0] changed from false to true.

Supported natively: one-dimensional, implicitly typed (new[], new[,]), jagged (also new int[,][] and new int[][,]), and rectangular arrays of rank 2 or more. This covers initializers with or without written sizes, bare { … } initializers of a declared array, and sized arrays without an initializer. They work as a return value, argument, binding, field or property initializer, member-access target, and ?: branch. Elements can be calls, object initializers, x++, and other arrays.

Effects of array members are not modeled. When the receiver is typed as an array (i32[], i32[,]), a call to an array member, such as g.GetLength(0), g.Rank or g.Clone(), is an unknown external call (Calor0411). A function that makes one and declares no matching effect reports Calor0410 (an effect is used but not declared). Declare the effect, or compile converted code with --permissive-effects. Two cases resolve through Calor's built-in effect manifests instead, as before: a receiver declared as System.Array, and an array whose element type is in a namespace the manifests give a default (for example System.Threading.Tasks.ValueTask[]).

Limits. These shapes are kept as C# and reported as a conversion loss, never moved:

  • An assignment used as an element, an index, or a size ({ x = Next() }, a[i = 0], new int[n = 3]). Inside a ?:, &&, ||, or ?? operand: a sized array whose size is anything but a name or an integer literal (flag ? new int[n + 1] : …). A ref/out/in argument whose address calls a method (F(in xs[I()], new Cell())) when a later argument must be moved. These are reported as conditional-expression-hoisting.
  • An element that Calor writes as a block: a collection initializer ({ new List<int> { 1 }, 2 }), or a multi-line element, such as an anonymous object, in a rectangular array row (object[,] a = { { new { A = 1 } } };). The statement is kept as C# and reported as array-element-block.
  • If an array still produces Calor that does not parse, the member is kept as C# by the rescue and reported as post-validation-fallback. A switch expression used as an element of a one-dimensional array is one known case.
  • stackalloc arrays are unchanged by this work.

Outside arrays, the converter can still move some subexpressions of a statement into temporaries (for example, steps of a method chain). Arrays no longer add to that, but this work does not change it.


Benchmark Comparison

Use --benchmark to see how the Calor version compares to C#:

Bash
calor convert PaymentService.cs --benchmark

This is a local source-pair comparison, not the published 217-program dashboard. Keep its metric output with the conversion report rather than assuming it reproduces the website headline.


Exit Codes

CodeMeaning
0Conversion completed; inspect the loss report to distinguish fully native from preserved interop
1Missing input, unsupported construct with --no-fallback, timeout, or a refused conversion (outcome: "refused"; no file written)
2Plain --lossy only: the file was written, but its C# failed the round-trip compile check (outcome: "unverified"). With --select-active-preprocessor-branch-lossy the same failure is a refusal (exit 1)

See Also