C# frontend

Compile a subset of C# 15 into a Morphir IR model, with Roslyn.

The C# frontend compiles C# source documents into a Morphir IR model. It runs on Roslyn, the C# compiler, so a model has the types that C# binds. It writes the current IR (version 4) only.

The frontend accepts a subset of C# 15: records, closed record hierarchies, unions, enums and static classes with pure methods. It refuses every other construct with an error diagnostic. The coverage reference lists each refused construct, with its code, its Roslyn id and an example.

Status

The C# frontend is a built-in of every offering: the Native AOT morphir, the self-contained and framework-dependent morphir, and dotnet-morphir. Roslyn runs under Native AOT, so nothing is downloaded or installed. See morphir extension list and compile.

This delivery has the frontend for types, sum types (closed records and unions) and simple values. The rest of the C# language support follows in the same change: loops and options, and generation in a build. The plan is the C# language support PRD.

Input

A compilation gets a package name, such as acme/trading, the exposed modules and the source documents. The frontend reads no project file: the host gives the documents. It binds them with C# 15, nullable annotations on, the implicit usings of an SDK project (System, System.Collections.Generic, System.IO, System.Linq, System.Net.Http, System.Threading and System.Threading.Tasks), and a fixed reference set: the .NET 10 reference assemblies, Morphir.SDK.CSharp and the attribute assembly. The Native AOT host embeds the references, so it needs no file of the .NET SDK.

Every document is code of the user. A // <auto-generated/> header or a .g.cs name does not stop a refusal.

A C# compiler error stops the compilation. The diagnostic keeps the code csharp.compiler and puts the C# id, for example CS0029, in its data. The frontend then reports no construct that the subset refuses, because they would repeat the same mistake.

Modules

Types directly in a namespace belong to the module of that namespace. A static class is a module below its namespace. The module path is the namespace and the class names, without the package path. A namespace that is the package path itself has no module name, so types there give csharp.module_outside_package. Put them in a namespace below it.

namespace Acme.Trading.Domain;                     // module domain: types only

public enum Side { Buy, Sell }
public closed record Order;
public sealed record Market(Side Side, decimal Quantity) : Order;
public sealed record Limit(Side Side, decimal Quantity, decimal Price) : Order;

public static class Pricing                        // module domain/pricing: values
{
    public const decimal Fee = 2.5m;

    public static decimal Notional(Order order, decimal last) => order switch
    {
        Market m => m.Quantity * last,
        Limit l => l.Quantity * l.Price,
    };
}

A static class nested in a static class is a child module. The module is public when the exposed list names it, or when the request gives no list.

Types

C#Morphir
record R(int X, string Y)a type alias of a record with the fields x and y
closed record T with sealed record casesa custom type; each case is a constructor and its fields are the arguments
union U(A, B)a custom type with the constructors A and B; each has the case type as its one argument value
enuma custom type with constructors that have no arguments
int, double, bool, string, char, decimalInt, Float, Bool, String, Char, Decimal of the SDK
(int, string)a tuple
Func<A, B>the function A -> B
IReadOnlyList<T>, Morphir.SDK.CSharp.List<T>List
Maybe<T>, Result<E, V>, Dict<K, V>, Set<T>, Order of Morphir.SDK.CSharpthe types of the same name

A C# type parameter is a type variable. A case record has the custom type as its Morphir type: a method that makes a Market has the result type Order. Two types of one module with the same Morphir name, such as TaxRate and taxRate, give csharp.name_collision. The constructors of one module also must have different Morphir names: an enum member Market and a case record Market, or two case records X of two closed records, give csharp.name_collision with the two declarations. The parts of a partial record are one type.

The frontend refuses a type that it cannot give in full, so no type or field is left out of the model:

CodeC#
csharp.unsupported_record_inheritanceA record that inherits from a record that is not closed. Its inherited fields have no place in a Morphir record.
csharp.unsupported_record_memberA record member that is not a field: a computed property, a method, a field, or a property of a positional record outside its parameters.
csharp.unsupported_static_memberA member of a static class that is not a method, a constant or a nested type, for example a static property or a static readonly field.
csharp.unsupported_union_memberA member or a base list of a union. A custom type has only its cases.
csharp.unsupported_union_caseA case of a union with no name (a type parameter, a tuple or a function), or a case record of a closed record.

Sum types

Two C# forms give a Morphir custom type. For each form, the C# compiler checks that a switch has an arm for each case.

C# formMorphir custom typeUse
closed record Price; with sealed record Quote(decimal Value) : Price;type Price = Quote DecimalA new sum type. A case exists only as a constructor, and the constructor holds the fields. This is the preferred form.
union Shape(Circle, Rect);type Shape = Circle Circle | Rect RectThe cases are types that the model also uses by themselves. A constructor wraps one such type.
namespace Acme.Trading.Domain;

public closed record Price;
public sealed record Quote(decimal Value) : Price;
public sealed record NoQuote : Price;

public sealed record Circle(double Radius);
public sealed record Rect(double W, double H);
public union Shape(Circle, Rect);

public static class Geometry
{
    public static Shape Unit() => new Circle(1.0);

    public static double Area(Shape s) => s switch
    {
        Circle c => 3.14 * c.Radius * c.Radius,
        Rect r => r.W * r.H,
    };
}

The module domain has the custom types Price, with the constructors Quote (one argument value) and NoQuote, and Shape, with the constructors Circle and Rect. The constructor of a union case has one argument value, the case value. Unit applies the constructor Circle to the record, and Area matches the constructors. The C# backend writes the same two forms (see C# generation), so the C# of a model comes back to the same model.

A union converts to a custom type when each case type is a Morphir type reference: a record, a custom type, a different union or an SDK type. The constructor has the local name of that reference: union Amount(int, string) has the constructors Int and String. The constructors of a module must have different names, so two unions of one module with the case Circle, or union Lists(List<int>, List<string>), give csharp.name_collision.

An older encoding of a sum type, an abstract record with a private constructor and sealed record cases, is not a Morphir type. The rule MORPHIR1009 (csharp.unsupported_abstract_record) reports it in the IDE, in dotnet build and in morphir compile. A closed record and a union are not reported.

namespace Acme.Trading.Domain;

public abstract record Side
{
    private Side() { }
    public sealed record Buy(decimal Quantity) : Side;
    public sealed record Sell(decimal Quantity) : Side;
}

An IDE that loads Morphir.Lang.CSharp.CodeFixes offers the code fix Change to a closed record at the report. The fix writes closed in place of abstract and removes the constructors of the record. The cases, their fields and their places do not change, so the model has the custom type Side with the constructors Buy and Sell:

namespace Acme.Trading.Domain;

public closed record Side
{
    public sealed record Buy(decimal Quantity) : Side;
    public sealed record Sell(decimal Quantity) : Side;
}

The fix never changes a union. The code fix assembly uses the Workspaces layer of Roslyn, so morphir, dotnet-morphir and morphir compile do not load it.

Value classes of type parameters

A type parameter of a method can have a value class, as a type variable of Elm core has: equality, comparable or number. The frontend finds the class from two sources. The first source that gives a class wins:

  1. The .NET constraints of the type parameter. IEquatable<T> and IEqualityOperators<T, T, bool> give equality. IComparable<T> and IComparisonOperators<T, T, bool> give comparable. INumber<T> gives number.
  2. The uses in the body on values of the type parameter. ==, !=, Equals, Basics.Equal, Basics.NotEqual and EqualityComparer<T>.Default give equality. CompareTo and Comparer<T>.Default give comparable.

The type variable keeps the name of the type parameter: TKey is key. The frontend writes the class in the extensions of the type attributes of each type variable of the signature, as {"morphir-dotnet": {"classes": ["comparable"]}}. The C# backend reads it (see Generic functions). So the C# that the backend writes for a generic function comes back with the same class.

public static TKey Max<TKey>(TKey a, TKey b) where TKey : IComparable<TKey> => Basics.Max(a, b);

The model has max : key -> key -> key, and each key has the class comparable.

On two values of a type parameter of the method, the frontend lowers the equality and the order of .NET as calls of the SDK:

C#Morphir
a == b (with IEqualityOperators<T, T, bool>), a.Equals(b), EqualityComparer<T>.Default.Equals(a, b)Basics.equal a b
a.CompareTo(b), Comparer<T>.Default.Compare(a, b)Basics.compare a b, matched to -1 for LT, 0 for EQ and 1 for GT

CompareTo in .NET gives only a sign, so -1, 0 and 1 are correct results. The order is the order of the SDK, with ordinal strings: Cmp("B", "a") is -1, but string.CompareTo in C# gives 1. A call of Equals or CompareTo on a value of another type gives csharp.unsupported_reference: double.Equals, for example, makes NaN equal to NaN, and Basics.equal does not. An explicit class on a type parameter (an attribute or a key in morphir.toml) is not available yet.

Values

A static method of a static class, and a const field, becomes a value. The frontend lowers these constructs:

  • literals, parameters and locals, and constants and methods of the package;
  • the operators + - * / %, comparisons, == and !=, &&, || and !, as calls of the SDK;
  • calls of Morphir.SDK.CSharp.Basics and Morphir.SDK.CSharp.Decimal;
  • Morphir.SDK.CSharp.List<T>.FromEnumerable of an array with its items, as a list. The C# backend writes a list value in this form;
  • new of a case record (a constructor) or of a plain record (a record value), and with (a record update);
  • property access on a record, tuples and collection expressions ([1, 2, 3]);
  • ?:, and if statements; a branch that does not return goes on with the statements after the if;
  • switch statements whose sections each end with a return;
  • local variable declarations, as let, and the deconstruction of a tuple (var (a, b) = t;), as a destructure;
  • lambdas, and calls of a Func;
  • loops and local functions (see Loops);
  • a switch expression on a closed record or a union, with an arm for each case;
  • a conversion of a case value to its union (Shape s = circle, (Shape)circle, new Shape(circle)), as the constructor of the case;
  • x is P with a pattern that binds no name, as a match that gives True or False;
  • a.Equals(b) on two values of one union, as Basics.equal.

A pattern Circle c on a union is the constructor pattern Circle with c bound to the case value, so c.Radius is a field of the record. A positional or a property pattern on a case, such as Circle(var radius), binds the case value to a variable (circle-value) and each local to a field of it. Only var, a declaration and a discard can stand in such a pattern.

A Morphir custom type has no state with no case, so the frontend refuses the C# that reaches the state of a union with no case: default and new Shape() (csharp.unsupported_union_default), a null arm (csharp.unsupported_union_null), the Value property (csharp.unsupported_union_value) and the interface IUnion (csharp.unsupported_union_interface).

A switch that misses a case is an error: Morphir has no partial match. A switch on an enum that names every member is complete, and each member is a constructor pattern. An arm of a switch binds a case record to a local, and the fields of the case are variables, so m.Quantity reads the field that the pattern bound. The variable has the words of the local and of the field (m-quantity), and a number follows when the method already has that name.

A switch statement is a pattern match. The arms keep the order of the cases, and a default section is the last arm, because C# tests it last. A switch statement with no default section continues with the statements after it, and those statements are the last arm. A section that does not end with a return, for example a section that ends with break, gives csharp.unsupported_missing_return at the section. A when guard gives csharp.unsupported_guard.

Only a tuple can be deconstructed. The deconstruction of a record gives csharp.unsupported_deconstruction: read its fields by name. A deconstruction into a local that exists, such as (a, var b) = t;, is a change of a, so the admission analyzer refuses it with csharp.unsupported_mutation.

A named argument binds to its parameter: Sub(b: 1, a: 10) is sub 10 1. A record value gets each field from the constructor argument of the same name, and an object initializer then sets the field again, as in C#. A record value that leaves out a field gives csharp.unsupported_record_initializer. Every node of a value has its source range and its inferred type. A call of a generic method has the types of that call: in Id(3), the call has the type Int, not a type variable.

A method call or a property of the .NET libraries that the SDK does not map gives csharp.unsupported_reference. A construct that the frontend cannot lower gives csharp.unsupported_<construct>. Its message names the construct with the words of the source, for example 'lock' statement. A method body that does not end with a return gives csharp.unsupported_missing_return at the end of the block.

The diagnostics of a run are in document order: the document, then the start and the end of the range. The Roslyn id and the message put two diagnostics at one range in a fixed order, so the same input gives the same list each time.

Loops

The frontend lowers a loop by its shape. One loop recognizer in Morphir.Lang.CSharp.Analyzers decides for the analyzer and for the frontend, so the IDE and morphir compile accept and refuse the same loops with the same reasons.

C# loopMorphir IR
A foreach whose body is result.Add(f(x))List.map f
A foreach whose body is if (p(x)) result.Add(x);List.filter
A foreach whose body is if (p(x)) result.Add(f(x));List.filterMap with if p x then Just (f x) else Nothing
A foreach that changes one localList.foldl
A foreach that changes two or more localsList.foldl with a tuple of the locals as its state
A while, do or for loop that changes localsLetRecursion whose parameters are the changed locals
A foreach with break, return or continueLetRecursion whose parameters are the changed locals and the rest of the list

These rules apply:

  • The list of a map, a filter or a filter map is a local List<T> that is empty before the loop: new List<T>() or []. The body can declare locals before the add.
  • The state of a loop is each local and parameter that the loop changes and that lives outside the loop, in the order of the first change. The variables of a for initializer are state too. A declaration that only the next loop reads is the initial state, so var total = 0; foreach ... gives List.foldl ... 0.
  • The end of the body of a recursion calls the function again with the new state. A return in the loop and a break are base cases: a break, and the end of a while loop, go on with the statements after the loop.
  • A change such as sum += p; gives the new value to the statements after it. When a later statement reads the changed local, the change is a let with the same name.
  • A lambda that only applies a function to its parameter is that function: the body result.Add(Notional(o)) gives List.map notional.

The frontend reads the functional forms as the same IR as the loops: Select is List.map, Where is List.filter, Aggregate(seed, (state, x) => ...) is List.foldl with the element first, and FilterMap of Morphir.SDK.CSharp.List<T> is List.filterMap. These methods of LINQ and of the SDK list are read. Where then Select is List.map over List.filter, not List.filterMap. ToList() and List<T>.FromEnumerable of a list are the list.

A local function is a LetRecursion, and local functions next to each other are one group, so they can call each other. A local function that is called before its declaration gives csharp.unsupported_local_function.

A loop with no Morphir form gives csharp.unsupported_loop (MORPHIR1001), and the message gives the reason:

  • the loop writes a field, a property or an array element;
  • the loop reads a field that can change;
  • the loop changes no local and builds no list;
  • the loop builds a list in a while, do or for loop, builds a list and changes a local, builds a list and can leave early, or adds to a list in more than one place.

For example, foreach (var o in orders) { total += o.Price; counter++; } gives “The ‘foreach’ loop is not in the Morphir subset: it writes the field ‘counter’”. A change of a local in a loop is the state of the loop, so the admission analyzer does not report it as a mutation.

To lower a loop that changes locals to a LetRecursion and not to List.foldl, put [MorphirLoop(LoopLowering.Recursion)] on the method, on its class or on the assembly, or set the key of the project:

[frontend.csharp]
loop_lowering = "recursion"

An attribute wins over the key. A loop that the frontend refuses stays refused with each value. See C# handling options.

The C# backend writes each form back by its profile. See C# generation.

Compile

Save the example of Modules as Domain.cs in a directory, for example /work/trading, and run this command in that directory:

$ morphir compile --language csharp --input Domain.cs --package-name acme/trading --ir-version 4
/work/trading/.morphir/out/compile.dest/morphir-ir.json

The command writes the IR under .morphir/out/compile.dest/morphir-ir.json, as for every language, and writes the path of the IR to stdout. The report names the frontend morphir-dotnet.csharp (in-process). A C# file in --input is read with --language csharp, and the language is also chosen from the extension .cs when --language is not set.

Diagnostics in the editor

The analyzer that refuses the constructs is a Roslyn analyzer, so the compiler and the IDE show the same refusals as morphir compile. It reports only in a Morphir model project, which has [assembly: Morphir.MorphirModel] or the MSBuild property MorphirModel set to true.

[assembly: Morphir.MorphirModel]

The analyzer refuses a symbol from an assembly outside the fixed reference set (csharp.unsupported_outside_reference). The test is by the name of the assembly, so a NuGet package with a System name, such as System.Reactive, is also refused: morphir compile cannot bind it.

When an analyzer fails with an exception (Roslyn id AD0001), morphir compile reports a csharp.compiler error with that id in its data and writes no model. A source that the analyzer did not finish is not admitted.

A rule says that a construct cannot become a model, so a rule cannot be turned off. #pragma warning disable, .editorconfig and NoWarn do not hide a MORPHIR rule in the compiler or the IDE. A SuppressMessage attribute that names a MORPHIR rule is refused with MORPHIR1008 (csharp.unsupported_suppression). Change the construct instead. morphir compile also refuses a construct that the IDE does not check, such as code in a file with an // <auto-generated/> header.

CS8509 and CS8510, a switch that misses a case or has an arm that cannot match, are compiler warnings, so a #pragma can hide them in the IDE. morphir compile still reports them as errors.


C# frontend coverage

The C# constructs that the C# frontend refuses, with their diagnostic codes, Roslyn ids and examples.