This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

C# generation

The C# backend writes a Morphir library model as C# 15 source. It is part of Morphir.Lang.CSharp: the frontend that reads C#, the passes that run before the backend, and the backend share one package, and all three use Roslyn. The backend builds each file as a Roslyn syntax tree with SyntaxFactory, and a layout step writes the text. It uses no Roslyn Workspaces assembly, and it is a pure function of the model and the options: it reads no file and starts no process.

The backend is the csharp target of morphir generate and of morphir compile --target csharp. In code, call CSharpBackend.Generate(model, options, cancellationToken) of Morphir.Lang.CSharp.Emit. To generate C# when a C# project builds, use the source generator or the MSBuild target of the package: see C# generation in a build.

Breaking change. The package Morphir.CodeGeneration.CSharp and its text backend are gone. The package Morphir.Lang.CSharp replaces it, and the API of the backend is CSharpBackend in Morphir.Lang.CSharp.Emit. Generation in a user build (the MSBuild target and the source generator) is not in the package yet. The new backend writes C# 15 only: a request for language-version=14 fails with the code unsupported-language, and the diagnostic names 15. The shape of the output changed: modules are namespaces and static classes (no ...Module class), a custom type is a closed record or a union (no abstract class with nested cases), and records have the equality of plain C# (no IMorphirValue members unless you ask for them). The consumer needs .NET SDK 11 and LangVersion 15, or a LangVersion that the compiler accepts for closed and union.

The output

A model with a custom type Shape and a function size that matches on it gives one file:

namespace Acme.Geo;
public static class Shapes
{
    public closed record Shape;
    public sealed record Circle(double Radius) : global::Acme.Geo.Shapes.Shape;
    public sealed record Rect(double W, double H) : global::Acme.Geo.Shapes.Shape;
    public sealed record Square(double Edge) : global::Acme.Geo.Shapes.Shape;
    public static double Size(global::Acme.Geo.Shapes.Shape s) => s switch
    {
        global::Acme.Geo.Shapes.Circle(var r) => r,
        global::Acme.Geo.Shapes.Square(var e) => e,
        global::Acme.Geo.Shapes.Rect(var w, var h) => w
    };
}

The rules that give this shape:

MorphirC#
A module that has only types, with no module above it that has valuesA namespace. Its types stand in the namespace.
A module that has valuesA static class named after the module, in the namespace of the modules above it. Its types are nested in it.
A module below a module that has valuesA nested static class, also when it has only types. A class between the two that has no module of its own is public when a public module is below it.
A record aliassealed record Name(Type Field, ...), with where T : notnull for each type parameter.
A custom type with public constructors, in which each constructor has one argument that is a reference with the local name of the constructor, and no two constructors hold the same C# typeunion Name(Case1, Case2)
Any other custom typeclosed record Name with one sealed record Case(...) : Name for each constructor
A pattern matchA switch expression, with each arm and the closing brace on a line of their own. An arm that cannot match is not written.
A value that takes parametersA static method. A saturated call is a direct call. A partial application is a Func.
A tail-recursive LetRecursionA local function with a while loop. Functions of one LetRecursion that call each other only as their last step are one local function with a while loop and a state for each function; no stack grows. Any other LetRecursion is a local function.

A custom type that mixes wrapper constructors with other constructors takes the closed form. A wrapper custom type with private constructors also takes the closed form, with internal cases: a C# union has public creation members, so it cannot keep a constructor private. Two wrapper constructors that hold the same C# type, for example two record aliases with the same fields, also take the closed form.

C# does not allow a member with the name of its enclosing type, so a type, a case or a value that has the name of its module class gets a trailing underscore. Other names must be different in each namespace and static class: a case of the closed form, a type, a value and the class or namespace of a module below. When two of them have the same name, or when a module has the name of the class that holds it, generation fails with name-collision, and the diagnostic names both. A generic type can have the name of a static class or a namespace, because C# allows it. A value can have a name that ends in Module: the module classes have no such suffix.

The polyfill file

C# 15 output needs runtime types that an older target framework does not have. Each generated output has the file Morphir.Polyfill.g.cs with internal copies of these types, each group behind its guard:

TypeGuard
IsExternalInit#if !NET5_0_OR_GREATER
CompilerFeatureRequiredAttribute#if !NET7_0_OR_GREATER
UnionAttribute, IUnion, IsClosedTypeAttribute#if !NET11_0_OR_GREATER

The file is the same for every model and every target framework. It is also the text that morphir compile adds to the compilation of a C# model.

Equality

A record and a union have the equality of plain C# by default. A record with a NaN field is equal to its copy. This differs from Elm, where NaN is not equal to NaN. The IEEE option writes the Morphir members (MorphirEquals, MorphirHashCode, Equals, GetHashCode, and == and != for a union) for a type, so NaN is not equal to NaN there. Select it with --option float-equality=ieee, with float_equality = "ieee" in [codegen.csharp], or with the attribute [MorphirEquality(FloatEquality.Ieee)] in the C# of the model (see Handling options). In code, CSharpBackend.GenerateWith also takes the types that get it. Morphir.SDK.CSharp accepts both: its Basics.Equal and its collections compare a plain record or union with its own equality. A double in an SDK list, dictionary, Maybe, Result or tuple compares as a double.

The SDK uses no reflection for equality and hashing, so Basics.Equal works under Native AOT. It knows scalars, tuples, its own values and IMorphirValue; any other value uses its own Equals and GetHashCode. The SDK has no function check at run time. The backend refuses an equality on a type that holds a function with unsupported-equality when it generates the code (see Generic functions). In C# that people write, a delegate compares by reference, as in .NET.

Generic functions

A type variable of a function can have a value class, as in Elm core. The backend finds the class from one of two sources. The first source that gives a class wins:

  1. The carrier in the IR: the extensions of the type attributes of the type variable in the signature, as {"morphir-dotnet": {"classes": ["comparable"]}}. The class words are equality, comparable, number, appendable and compappend. The C# frontend writes this carrier.
  2. The first word of the Morphir name of the type variable. comparable, comparable-1 and comparable-key have the class comparable, and number has the class number.

A model with no carrier still generates: then only the name gives a class.

ClassGenerated C#The type at each call
comparablewhere T : global::System.IComparable<T>Int, Float, Char, String, or a list or a 2- or 3-tuple of comparable types. Any other type gives unsupported-comparable.
numberwhere T : global::System.Numerics.INumber<T>Int or Float. Any other type gives unsupported-numeric.
equalitywhere T : notnull, no other constraintA type that holds no function.
appendable, compappendNone: the function is refused with unsupported-appendable. Use String or List.
// maximum : comparable -> comparable -> comparable
public static TComparable Maximum<TComparable>(TComparable a, TComparable b)
    where TComparable : global::System.IComparable<TComparable> => global::Morphir.SDK.CSharp.Basics.Max(a, b);

// twice : number -> number
public static TNumber Twice<TNumber>(TNumber x)
    where TNumber : global::System.Numerics.INumber<TNumber> => global::Morphir.SDK.CSharp.Basics.Add(x, x);

The SDK has overloads of Basics for T : INumber<T> (Add, Subtract, Multiply, Negate, Abs, Clamp and Power) with checked arithmetic, so Int keeps its overflow failure. The order of a comparable type stays the order of the SDK, with ordinal strings. An SDK list implements IComparable<List<T>> with the same order. A dictionary or a set with a key of a type variable is refused with unsupported-comparable: the SDK has no comparer for it.

A type variable with no class takes no ordering and no arithmetic: they give unsupported-comparable and unsupported-numeric.

Equality through a type variable

The backend finds the type variables that reach an equality: in the body of the function, or through a call of another function of the package. At each call, it checks the type that the call gives to each of these type variables. A type that holds a function, also in a field of a record, a field of a case or the record of a union case, gives unsupported-equality at the call. The message gives the path to the function type, for example:

Functions have no admitted Morphir equality: Same compares the values of its type variable TA, and the compared type holds a function type at Callback.

The check gives diagnostics only. It does not change the generated code. A type variable that does not reach an equality takes a function type.

Options

Give an option with --option KEY=VALUE on morphir generate or morphir compile --target csharp, or as a key of [codegen.csharp] in morphir.toml. A key of the table has _ where the option has -.

Option[codegen.csharp] keyValuesDefault
language-versionlanguage_version1515
namespacenamespaceA dotted C# namespaceThe package path
profileprofileimperative, functionalimperative
traversaltraversalloop, functionalloop for imperative, functional for functional
tail-recursiontail_recursionloop, local-functionloop
float-equalityfloat_equalityclr, ieeeclr
[codegen.csharp]
profile = "functional"
float_equality = "ieee"

profile, traversal, tail-recursion and float-equality are handling options. They also have C# attributes, and the model keeps the attribute values. See Handling options for the attributes and the order in which the carriers apply. In short: --option wins over an attribute, and an attribute wins over a [codegen.csharp] key. For language-version and namespace, --option wins over the key.

profile and traversal select the C# form of the list functions, and tail-recursion selects the form of a tail call. See Profiles.

A repeated option uses its last occurrence. An unknown option, a value of the wrong JSON type, a word that is not a value of the option, or a namespace with source syntax fails the invocation with the code invalid-backend-option (exit code 2) before any file is written. [codegen.csharp] is a closed table: an unknown key or a word that is not a value fails when the configuration loads, with exit code 2, before any file is written.

Profiles

The profile selects the C# form of the list functions and of the local recursion of the model. The IR is the same in each profile: the C# frontend reads the C# of each profile back to the same IR, with source locations left out.

Morphir IRimperative (the default)functional
List.mapA foreach that adds each value to a List<T>Select
List.filterA foreach with an if that adds the elementWhere
List.filterMapA foreach with an if that adds a valueFilterMap
List.foldlA foreach that sets accumulator localsAggregate
LetRecursion, tail callA while loop with state localsA while loop with state locals
LetRecursion, otherA local recursive functionA local recursive function

These rules apply:

  • Select, Where, FilterMap and Aggregate are methods of Morphir.SDK.CSharp.List<T>, so each result is an SDK list or the state of the fold. List.filterMap has its own form, because Where then Select is the form of List.map over List.filter.
  • A fold with two or more state values has a tuple state. The imperative profile writes one tuple assignment, such as (sum, count) = (sum + x, count + 1);, so all new values come from the old values.
  • The imperative profile has no loop form for a List.filterMap whose function is not if c then Just e else Nothing, or for a fold with a tuple state whose initial value or new value is not a tuple. It writes the functional form for them.
  • The option traversal changes the form of the list functions of one value or of all values, and the profile gives its default: loop for imperative and functional for functional.
  • A tail-recursive LetRecursion that the code after it calls once is a while loop with no function: the parameters are the state locals, and one tuple assignment gives them their new values. The name of the function does not stay in the C#, so the frontend names the function loop when it reads the loop. Any other tail-recursive function is a local function with a while (true) loop in it. With tail-recursion=local-function, a tail call is a call of a local recursive function, as for a call that is not a tail call.

Example

With this morphir.toml in the project directory:

[project]
name = "acme/demo"

[frontend]
language = "csharp"

and this source src/Totals.cs:

namespace Acme.Demo;

public static class Totals
{
    public static IReadOnlyList<int> Doubled(IReadOnlyList<int> amounts)
    {
        var result = new List<int>();
        foreach (var amount in amounts) { result.Add(amount * 2); }
        return result;
    }

    public static int Sum(IReadOnlyList<int> amounts)
    {
        var total = 0;
        foreach (var amount in amounts) { total += amount; }
        return total;
    }

    public static int Factorial(int n)
    {
        var acc = 1;
        while (n > 1) { acc *= n; n--; }
        return acc;
    }
}

compile the project, then generate C# with the functional profile. Run both commands in the project directory. The compile writes the path of the published IR to stdout, and generate writes the generated files:

$ morphir compile
/work/demo/.morphir/out/compile.dest/morphir-ir.json
$ morphir generate --target csharp --output gen --option profile=functional
Morphir.Polyfill.g.cs
p_Acme.Demo/m_TotalsModule.g.cs

The file p_Acme.Demo/m_TotalsModule.g.cs has the functional forms:

namespace Acme.Demo;
public static class Totals
{
    public static global::Morphir.SDK.CSharp.List<int> Doubled(global::Morphir.SDK.CSharp.List<int> amounts) => amounts.Select<int>(amount => global::Morphir.SDK.CSharp.Basics.Multiply(amount, 2));
    public static int Factorial(int n)
    {
        int acc = 1;
        int n_2 = n;
        while (global::Morphir.SDK.CSharp.Basics.GreaterThan(n_2, 1))
        {
            (acc, n_2) = (global::Morphir.SDK.CSharp.Basics.Multiply(acc, n_2), global::Morphir.SDK.CSharp.Basics.Subtract(n_2, 1));
        }

        return acc;
    }

    public static int Sum(global::Morphir.SDK.CSharp.List<int> amounts) => amounts.Aggregate<int>(0, (total, amount) => global::Morphir.SDK.CSharp.Basics.Add(total, amount));
}

With no profile option, the imperative profile writes loops:

namespace Acme.Demo;
public static class Totals
{
    public static global::Morphir.SDK.CSharp.List<int> Doubled(global::Morphir.SDK.CSharp.List<int> amounts)
    {
        global::System.Collections.Generic.List<int> result = new global::System.Collections.Generic.List<int>();
        foreach (var amount in amounts)
        {
            result.Add(global::Morphir.SDK.CSharp.Basics.Multiply(amount, 2));
        }

        return global::Morphir.SDK.CSharp.List<int>.FromEnumerable(result);
    }

    public static int Factorial(int n)
    {
        int acc = 1;
        int n_2 = n;
        while (global::Morphir.SDK.CSharp.Basics.GreaterThan(n_2, 1))
        {
            (acc, n_2) = (global::Morphir.SDK.CSharp.Basics.Multiply(acc, n_2), global::Morphir.SDK.CSharp.Basics.Subtract(n_2, 1));
        }

        return acc;
    }

    public static int Sum(global::Morphir.SDK.CSharp.List<int> amounts)
    {
        int total = 0;
        foreach (var amount in amounts)
        {
            total = global::Morphir.SDK.CSharp.Basics.Add(total, amount);
        }

        return total;
    }
}

In the C# that the frontend reads, amount => Multiply(amount, 2) and the loop that adds amount * 2 give the same IR. A method parameter that a loop changes, such as n, is also a parameter of the loop, so the backend gives the state local the name n_2.

Checks before the backend

The checks of the backend run first, as the target-side pass morphir-dotnet.csharp.admission (see the middle end): the type catalog, the lowering and type check of the values, and the name collisions. A refusal has the code, the message and the location of the check, for example name-collision, unbound-variable or document-literal, and no file is written. The result reports the pass under passes.

Names, literals and functions

Package paths and module paths become namespaces and class names in Pascal case. Source paths use safe prefixes, such as p_Example/m_FunctionsModule.g.cs, including on Windows. Portable comparisons ignore case. A collision diagnostic identifies both owners. Generated local identities are unique within each method. Names that collide with a required protocol, generic parameter or inherited CLR member fail with a located name-collision. Malformed names fail with invalid-name.

Literals use culture-independent numeric text. Char requires one non-surrogate BMP scalar. Int literals must fit checked Int32. A v4 decimal lexeme must hold exactly in Decimal96; rounded or out-of-range values fail with representation-loss. Signed-zero Float bits are preserved, and classic nonfinite Float literals map to the corresponding double constants. Invalid UTF-16 strings fail explicitly.

Type checking runs before a successful source set is returned. Unknown variables and references, inconsistent applications, infinite types and unsupported numeric constraints produce located diagnostics. A recursive binding with no parameter fails with local-recursion.

Cancellation returns Cancelled, the original typed family and source version, and no sources.

SDK bindings

Generated code calls the public Morphir.SDK.CSharp API. The declared output requirement is net10.0 or newer plus Morphir.SDK.CSharp.

Source moduleAdmitted runtime calls
BasicsChecked Int32/IEEE Float arithmetic (also generic for INumber<T>), conversion and rounding, comparisons, min, max, clamp, Order cases and structural equality
Listsingleton, cons, map, filter, filterMap and foldl (in the form of the profile), append, head, tail and length
MaybeJust and Nothing constructors and patterns, map and andThen
ResultOk and Err constructors and patterns, map and andThen; the error type first, the value type second
Dictempty, singleton, fromList, get, insert, update, remove, toList and union
Setempty, singleton, fromList, insert, remove, toList and union
DecimalExact add, sub, mul, div, compare and toString

Map and andThen use the instance combinators. Nothing and Err bypass callbacks, and callback exceptions propagate. Dictionary and set factories select MorphirComparers.Int, Float, Char or String, composing list and tuple comparers as needed. Ordering requires concrete admitted comparable shapes, with finite Float values. A factory whose key comparer cannot be resolved fails with unsupported-comparable. Unmapped SDK references fail with unmapped-sdk; dependencies without an implementation fail with unresolved-reference or unresolved-type.

Value-dependent SDK failures, such as checked overflow or a nonfinite Float-to-Int conversion, remain the execution errors of the SDK.

1 - C# handling options

Select how Morphir handles a C# model with attributes in the C# source or with keys in morphir.toml, and the order in which they apply.

A handling option selects one of the handlings that the C# subset supports: the equality of a double, the form of a list traversal, the form of a tail call, and the lowering of a loop. Each option has two carriers with the same values: a C# attribute and a key. Use the carrier that you prefer. A project that has only attributes needs no morphir.toml.

The options

OptionKindAttribute--optionmorphir.toml keyValuesDefault
Float equalityBackend[MorphirEquality(FloatEquality.X)]float-equality[codegen.csharp] float_equalityClr, Ieee (clr, ieee)Clr
Traversal formBackend[MorphirEmit(Traversal = TraversalForm.X)]traversal[codegen.csharp] traversalLoop, Functional (loop, functional)The profile
Tail recursion formBackend[MorphirEmit(TailRecursion = TailRecursionForm.X)]tail-recursion[codegen.csharp] tail_recursionLoop, LocalFunction (loop, local-function)Loop
ProfileBackendNoneprofile[codegen.csharp] profileimperative, functionalimperative
Loop loweringFrontend[MorphirLoop(LoopLowering.X)]None[frontend.csharp] loop_loweringTraversal, Recursion (traversal, recursion)Traversal
Class of a type parameterFrontend[MorphirValueClass(ValueClass.X)]NoneNoneEquality, Comparable, Number, Appendable, CompAppendThe constraints and the uses
Model projectAnalyzer[assembly: MorphirModel]NoneThe MSBuild property MorphirModeltrueNot a model project

The attributes are in the namespace Morphir, in the attribute assembly of the package Morphir.Lang.CSharp, which targets netstandard2.0. morphir compile has the assembly in its fixed references.

  • A backend option changes only the C# text that the backend writes. The IR stays the same.

  • A frontend option changes the IR that the frontend gives. A loop that the frontend refuses stays refused with each value of an option: an option selects between supported handlings, and it does not make refused code accepted.

  • The profile gives the default traversal form: imperative writes loops, and functional writes Select, Where, Aggregate and FilterMap. A tail call is a while loop in each profile, and tail-recursion=local-function makes it a call of a local recursive function. See Profiles.

  • [MorphirLoop(LoopLowering.Recursion)] and loop_lowering = "recursion" lower a foreach that changes locals to a LetRecursion over the list, not to List.foldl. A loop that fills a list stays List.map, List.filter or List.filterMap, and a loop that is already a recursion does not change. See Loops.

  • The model project switch is an option of the analyzer in the IDE and in dotnet build, which do not read morphir.toml. Its key is the MSBuild property <MorphirModel>true</MorphirModel> in the project file. morphir compile takes each C# source that it compiles as code of a model project.

The nearest carrier wins

command line  >  attribute on the member  >  on the type  >  on the assembly  >  morphir.toml  >  profile default
  • An attribute on a member is on a method, a property or a positional parameter of a record.
  • An attribute on a type is on a record, a union or a static class. For a case record of a closed record, the case comes first, then the closed record, then each type that holds it.
  • An attribute on the assembly has the form [assembly: MorphirEquality(FloatEquality.Ieee)].

For example, the type has IEEE equality, and one field has plain equality:

[MorphirEquality(FloatEquality.Ieee)]
public partial record Quote([MorphirEquality(FloatEquality.Clr)] double Bid, double Ask);

Bid compares as plain C# does (NaN is equal to NaN), and Ask has IEEE equality (NaN is not equal to NaN).

Equality needs partial

An attribute cannot change how compiled C# compares two records. A record or a union with IEEE equality from an attribute (on the type, a closed base, a type that holds it, the assembly or one of its members) must be partial, because the equality members are added to it. A type that is not partial gets the error MORPHIR1009 (csharp.unsupported_non_partial_equality) in the IDE, in dotnet build and in morphir compile.

Backend options travel with the model

morphir generate reads an IR file and has no C# source. So the frontend writes each backend option of the attributes into the model: in the extensions of the type attributes, as {"morphir-dotnet": {"options": {"traversal": "functional"}}}. A function has it on its output type. Float equality is on the type of each field. The backend reads the options from the model, applies them, and writes the attribute back. An option that comes only from --option or from [codegen.csharp] writes no attribute.

Example

Make a directory with one file, Quote.cs, and no morphir.toml:

using Morphir;

[assembly: MorphirModel]

namespace Acme.Trading.Quotes;

[MorphirEquality(FloatEquality.Ieee)]
public partial record Quote([MorphirEquality(FloatEquality.Clr)] double Bid, double Ask);

public static class Pricing
{
    [MorphirEmit(Traversal = TraversalForm.Functional)]
    public static double Spread(Quote quote) => quote.Ask - quote.Bid;
}

Compile it and generate C# from the model in one command:

morphir compile --language csharp --input Quote.cs --package-name acme/trading --ir-version 4 --target csharp --generate-output gen

The generated Quote has the attributes again and the members of IEEE equality, and Spread has [global::Morphir.MorphirEmit(Traversal = global::Morphir.TraversalForm.Functional)]. Generate again from the IR file, with plain equality from the command line:

morphir generate --input .morphir/out/compile.dest/morphir-ir.json --target csharp --output gen-plain --option float-equality=clr

The command line wins over the attributes, so this Quote has no equality members. Without the option, the same command gives the files of gen again: the model kept the attribute values.

To set an option for a project without attributes, add the key to morphir.toml. An attribute wins over the key:

[codegen.csharp]
float_equality = "ieee"
traversal = "functional"

A malformed value fails before any file is written, with exit code 2: --option float-equality=maybe fails with invalid-backend-option, and float_equality = "maybe" fails when the configuration loads.

Frontend options in morphir.toml

A frontend option changes the IR, so its key is in [frontend.csharp], not in [codegen.csharp]. morphir compile gives the key to the C# frontend in the compile request. An attribute on the member, the type or the assembly wins over the key. Make a directory with this Totals.cs:

using System.Collections.Generic;

namespace Acme.Demo;

public static class Totals
{
    public static int Sum(IReadOnlyList<int> amounts)
    {
        var total = 0;
        foreach (var amount in amounts) { total += amount; }
        return total;
    }
}

and this morphir.toml:

[frontend.csharp]
loop_lowering = "recursion"

Then compile it:

morphir compile --language csharp --input Totals.cs --package-name acme/demo --ir-version 4

The Sum function of the IR is a LetRecursion over the list. Without the key, it is List.foldl. The attribute [assembly: MorphirLoop(LoopLowering.Recursion)] in Totals.cs, with no key, gives the same IR.

[frontend.csharp] has the keys extension, project_file and loop_lowering, and no other key. A malformed key fails when the configuration loads, before the frontend runs, with exit code 2: loop_lowering = "sideways" and traversal = "functional" (a backend key in the frontend table) both fail.

Not yet

  • A morphir.toml key for the class of a type parameter. A key must name one type parameter of one declaration, and the address of such a node is not agreed upstream. Use the attribute [MorphirValueClass].

2 - C# generation in a build

Generate C# from a Morphir model when a C# project builds: the source generator and the MSBuild target of the package Morphir.Lang.CSharp, their settings, their diagnostics and the support matrix.

The package Morphir.Lang.CSharp generates C# from the Morphir models of a C# project when the project builds. A model is an AdditionalFiles item with a file name that ends in .morphir.json. The package has two entry points:

  • The source generator (the default). It adds the generated code to the compilation. The code is not a file of the project.
  • The MSBuild target (opt-in). It writes the generated files into the intermediate output folder before the compilation, and the project compiles them.

Both entry points call one pipeline function, CSharpPipeline.Generate. It upgrades a classic model to the current IR, runs the C# passes and the backend, and has no file or process access. morphir generate --target csharp runs the same stages, so one model gives the same paths and bytes through the CLI, the target and the generator.

Requirements

  • The .NET SDK 11.0.100 or later. The generated code is C# 15, and the package sets LangVersion to 15. A build with an older SDK stops with the error MORPHIR2010, which names the SDK that it needs.
  • The project can target a lower framework, for example net10.0. Below net11.0 the output has one polyfill file, Morphir.Polyfill.g.cs, with the internal runtime types that C# 15 needs (see C# generation).
  • The generated code calls Morphir.SDK.CSharp. Add that package too.

Generate in a build

Make a console project, and add the two packages:

$ dotnet new console --output RentalApp
$ cd RentalApp
$ dotnet add package Morphir.Lang.CSharp --prerelease
$ dotnet add package Morphir.SDK.CSharp --prerelease

Put the model in the project folder as car-rental.morphir.json, and add it to RentalApp.csproj as an additional file:

<ItemGroup>
  <AdditionalFiles Include="car-rental.morphir.json" />
</ItemGroup>

The model of this example is the package car/rental with the module inventory and the value daily-rate. Its code is the static class Car.Rental.Inventory. Replace the text of Program.cs:

System.Console.WriteLine($"daily rate: {Car.Rental.Inventory.DailyRate()}");

Build and run the project:

$ dotnet run
daily rate: 5000

To see the generated files, set EmitCompilerGeneratedFiles to true. The compiler then writes them below obj/<configuration>/<framework>/generated/Morphir.Lang.CSharp.Generator/.

Write the generated files with the MSBuild target

Set MorphirGenerateCSharpFiles to true. The target MorphirGenerateCSharpFiles then writes the files into obj/<configuration>/<framework>/morphir/csharp/ before the compilation and adds them to the Compile items, and the source generator does nothing:

$ dotnet run -p:MorphirGenerateCSharpFiles=true
daily rate: 5000

In the project file:

<PropertyGroup>
  <MorphirGenerateCSharpFiles>true</MorphirGenerateCSharpFiles>
</PropertyGroup>

The target writes a file only when its bytes change, and it deletes the C# files of its folder that no model writes now. dotnet clean removes the folder.

Settings

MSBuild propertyValueEffect
MorphirGenerateCSharpFilestrueThe MSBuild target writes the files, and the source generator does nothing.
MorphirCSharpNamespaceA dotted C# namespaceThe namespace of all generated files. Empty: the namespace of the package of each model.
MorphirModeltrueThe project is a model project: the admission analyzers (MORPHIR1001 and the others) report its C# outside the Morphir subset.

Diagnostics

IdSeverityReason
MORPHIR2001ErrorThe generation of a model failed. The message has the model file, the code (for example invalid-json or unsupported-version) and the reason. The project gets no file of that model.
MORPHIR2002WarningA warning of the pipeline, with the model file and the code.
MORPHIR2003ErrorTwo models write a file with the same path and different text. One polyfill file for two models is not an error.
MORPHIR2010ErrorThe .NET SDK is older than 11.0.100.

The package

FolderContents
lib/net11.0, lib/net10.0The frontend, the passes and the backend, with the analyzer and attribute assemblies.
lib/netstandard2.0The pipeline function only, with the attribute assembly.
analyzers/dotnet/csThe source generator, the admission analyzers and their closure: Morphir.Lang.CSharp, Morphir.Models, Morphir.Compilation and Morphir.MiddleEnd for netstandard2.0, FSharp.Core, and System.Text.Json with its dependencies. It has no compiler assembly (Microsoft.CodeAnalysis*).
tasks/netstandard2.0The MSBuild task Morphir.Lang.CSharp.Build and its closure, with Microsoft.CodeAnalysis and Microsoft.CodeAnalysis.CSharp 5.12.0.
buildMorphir.Lang.CSharp.props and Morphir.Lang.CSharp.targets.

The source generator compiles against Roslyn 5.12.0, the compiler of .NET SDK 11.0.100, so it loads in that compiler and in later compilers. The compiler of SDK 10 does not load it (CS9057), and the package stops the build before the compiler with MORPHIR2010.

Support matrix

A claim names the host, the runtime and the closure that a test ran. A host with no test is not tested, and this page makes no claim that it works.

HostStatusTest
dotnet build and dotnet run, .NET SDK 11.0.100, with the closure of the table aboveTested: the source generator and the MSBuild target generate, a net10.0 program runstests/Morphir.BlackBox.Tests/EndToEnd/CSharpBuildGeneration.feature (packages lane) and scripts/csharp-sdk-matrix.sh
dotnet build, .NET SDK 10.0.100 and 10.0.403Not supported: the build stops with MORPHIR2010scripts/csharp-sdk-matrix.sh
Generated code on the .NET 10 runtimeTested: a net10.0 library and a net10.0 application, each with its own polyfill file, 0 warningsCSharpBuildGeneration.feature
Generated code on the .NET 11 runtimeTested: no polyfill fileThe commands of this page
Generated code on a net8.0 runtimeNot testedNone
Visual StudioNot tested. FSharp.Core is beside the generator, and it can conflict in the .NET Framework process of Visual Studio. The MSBuild task is netstandard2.0, but it did not run in the MSBuild of Visual Studio.None
JetBrains RiderNot testedNone
Visual Studio Code with the C# Dev KitNot testedNone

The packages lane runs on each operating system of the CI matrix. The SDK matrix check runs on Linux. The commands of this page ran on macOS arm64.

3 - C# generation API and diagnostics

CSharpBackend.Generate(VersionedModel, GenerationOptions, CancellationToken) of Morphir.Lang.CSharp.Emit is synchronous and has no file, process, configuration or compiler dependency. GenerationOptions.LanguageVersion accepts numeric 15, the only language version that the backend writes, and 15 is the default. Another value returns unsupported-language and names 15. Compiler release channel is chosen by the caller independently.

The existing GenerationOptions record and three-argument entry point are unchanged. To choose an emitted namespace, call NamespaceOverride.TryCreate(string). It returns Result<NamespaceOverride, GenerationDiagnostic>; a successful immutable value exposes Value. Pass it to CSharpBackend.Generate(model, options, namespaceOverride, cancellationToken). Both overloads use the same core implementation. An override applies to the input Library package and all its qualified type, value and constructor references. Package-derived source paths and the original typed IR remain unchanged. Separate or concurrent requests never share naming state.

The namespace accepts dotted literal BMP C# identifiers in Unicode Normalization Form C, including @-escaped reserved words. It admits the identifier character categories defined by the C# lexical specification. Formatting characters retain their literal spelling and have the compiler’s identifier-equivalence behavior. Source \u/\U escape syntax and surrogate characters are outside this literal-name boundary. Values are validated rather than normalized or interpreted as source text. Null, empty, malformed and injection-like input returns invalid-namespace at $options/namespace. An explicit null/default namespace value from a C# caller to the four-argument overload returns that same located refusal and no sources. An already cancelled caller still receives Cancelled first.

GenerationResult returns Status, Family, exact SourceVersion, selected LanguageVersion, Sources, Diagnostics and Runtime. Each source has RelativePath and Text. The runtime requirement is net10.0 plus the public Morphir.SDK.CSharp package. The core package itself does not reference that runtime. Consumers must resolve a runtime implementing the frozen SDK contract.

Success returns the complete source set and no diagnostics. Failure returns the first located refusal and no sources. Cancelled returns no sources or diagnostics, retaining input family/version and the selected profile. A caller that needs exception-based cancellation can translate this status at its edge. Cancellation checks cover traversal and emission, with a final token check before success. Invalid later modules also discard all earlier generated text.

Diagnostics carry stable Rule, structural Location and human-readable Message fields. Locations identify the version/options/distribution or the package/module/type/value/pattern/expression being checked. Callers should branch on Rule, not parse messages. The CLI successor can map these categories without loading a compiler or changing core semantics.

Diagnostic identities use explicit structural spellings, for example Name["car","rental"], ModulePath[Name["inventory"]] and FQName(PackagePath[Name["example"]],ModulePath[Name["data"]],Name["person"]). Raw words and path segments remain distinguishable. Strings are quoted, quotes and backslashes are escaped, null strings are written null, and control or surrogate characters use \u followed by four hexadecimal digits. Type mismatch messages describe Parameter(Name[...]), Named(FQName(...),[...]), Product([...]), Fields[Name[...]:...,Name[...]:...], Arrow(...,...) or Unit. These diagnostic-only spellings avoid structural reflection in NativeAOT. Module validation locations now use $modules/ModulePath[...]. This intentionally changes diagnostic text and that location spelling while retaining rule IDs, refusal and cancellation behavior, generated source bytes and paths. Callers should continue branching on Rule rather than parsing human messages.

CategoryRules
Input/profile boundaryunsupported-language, unsupported-version, unsupported-distribution, invalid-namespace
Target names and portable pathsinvalid-name, name-collision, path-collision, path-length
Type identity and closureunresolved-type, unmapped-sdk-type, unbound-type, type-arity, tuple-arity, recursive-alias, ambiguous-type, anonymous-record, private-type-exposure
Type/representation constraintstype-mismatch, open-record, unsupported-constraints, unsupported-numeric, unsupported-comparable, unsupported-equality, unsupported-appendable, representation-loss, document-literal
Value and constructor resolutionunbound-variable, unresolved-reference, unresolved-constructor, ambiguous-constructor, constructor-arity, unmapped-sdk
Unsupported source semanticsunsupported-body, unsupported-expression, local-recursion
Patterns and recordsduplicate-pattern-binding, empty-match, unknown-field

Unknown dependencies and SDK operations fail explicitly. No object-erased value, runtime stub or success-shaped partial artifact substitutes for a refusal. Admitted value-dependent SDK failures, such as checked overflow, remain execution errors. An admitted non-exhaustive source pattern raises pattern failure when no branch matches; every branch is still checked during generation.

Generated records/cases have get-only payloads and explicitly implement the SDK structural equality/hash protocol. That protocol alone does not establish the physical immutability of arbitrary externally supplied CLR generic payloads. The tested Morphir inputs use the admitted typed representations and immutable SDK collections. No arbitrary CLR IEquatable or reflection fallback is emitted.

See usage, host matrix and fixture scope and the generate command. The production AdditionalFiles/config/incremental adapter remains deferred.