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

Return to the regular view of this page.

Frontends

Frontends compile source code in a programming language into a Morphir IR model.

A frontend reads source documents in one programming language and writes a Morphir IR model. A backend does the opposite: it reads a model and generates code.

LanguageFrontendStatus
C#C# frontendIn process in every offering, the Native AOT morphir included. See compile.
F#F# frontendIn process in dotnet-morphir compile, and as the MEP guest morphir-fsharp-frontend for morphir compile --extension. See compile.

1 - F# frontend

Compile a subset of F# into a Morphir IR model.

The F# frontend compiles F# source documents into a Morphir IR model. It writes IR versions 1, 2 and 3 (the classic format) and version 4. It uses the F# compiler service to parse and type-check the source, so a model has the types that F# infers.

The frontend accepts a subset of F#: immutable data and pure functions. It refuses every other construct with an error diagnostic. The coverage reference lists each refused construct, with its code and an example.

Status

The frontend has two forms:

  • In process. Morphir.Frontend.FSharp.FSharpFrontend.registration is an IFrontend from Morphir.Compilation. The dotnet-morphir tool uses it.
  • MEP extension. morphir-fsharp-frontend is a Morphir Extension Protocol (MEP) 0.2.0-draft.1 guest. Hosts that cannot load the F# compiler service, such as the AOT morphir executable, start it as a process. See Run the frontend as a MEP extension.

To compile F# from the command line, see compile.

Input

A compilation gets:

  • a package name, such as acme/car-rental;
  • the modules that the package exposes;
  • the source documents, in compilation order, as F# requires.

Each F# module, nested modules included, becomes one Morphir module. The module path is the namespace and module names without the package path.

namespace Acme.CarRental

module Pricing =
    type Car = { Plate: string; Seats: int }

    type Status =
        | Available
        | Rented of days: int

    let dailyRate (car: Car) : int = if car.Seats > 4 then 60 else 40

    let charge (car: Car) (status: Status) : int =
        match status with
        | Available -> 0
        | Rented days -> dailyRate car * days

Supported subset

AreaSupported
TypesType abbreviations, records, unions with named or positional fields, generic parameters, tuples, functions, unit, bool, int, int64, float, decimal, char, string, option, Result and list
ValuesLiterals, variables, references, constructor application, tuples, lists, record construction, field access, record update, application, lambdas, let, let rec and let rec ... and, if/then/else, and match
PatternsWildcard, variable, literal, tuple, constructor, empty list, cons, as and unit, in match and in function and let parameters
Operators and library functionsArithmetic, comparison, equality, Boolean operators, |>, <|, >> and <<, and mapped functions of List, Option, Result and String

The frontend keeps the order of fields, constructor arguments and match cases, and the currying and evaluation structure of the source. A pipe or a composition becomes a direct application, not a function in the model.

Operators and library functions map to Morphir SDK operations through an explicit table. The type of an operand selects the operation: a + b on decimal values is SDK Decimal.add. A reference with no entry in the table gives fsharp.unsupported_reference and names the F# symbol.

Names and access

F# names become Morphir names: TaxRate and taxRate are both tax rate. Two declarations in one scope with the same Morphir name give fsharp.name_collision. To give a declaration a different Morphir name, use the [<MorphirName("...")>] attribute from the Morphir.FSharp.Annotations package (namespace Morphir). The name is in canonical Morphir syntax.

A module is public when the list of exposed modules names it, or when the compilation has no such list. An empty list exposes no module. An exposed module that matches no compiled module gives compile.unknown_exposed_module. A private or internal declaration is private.

Diagnostics

Diagnostics use the MEP diagnostic shape: a severity, a stable code, a message and a location. Positions are zero-based, and characters count UTF-16 code units. An error stops the compilation, and the frontend writes no model. Warnings and information diagnostics come with a successful model.

F# compiler errors have the code fsharp.compiler. Refused constructs have the codes in the coverage reference. When the frontend cannot give the compiler its references, for example in a self-contained folder whose deps file is missing or unreadable, compilation fails with one fsharp.references_unavailable error that names the cause, and the compiler does not run.

Run the frontend as a MEP extension

Install the guest as a dotnet tool. It needs the .NET runtime.

dotnet tool install --global Morphir.Frontend.FSharp.Extension

The same guest also has a self-contained folder delivery that carries its own .NET runtime, for machines without .NET. See Compile without .NET installed. Both deliveries compile with the same references (the .NET framework, FSharp.Core and Morphir.FSharp.Annotations), so at the same .NET runtime version they give the same IR and diagnostics. The model revision names the frontend identity, which includes the runtime version, so it is equal only on the same runtime patch.

The guest speaks only MEP 0.2.0-draft.1, over stdio with Content-Length framing. It serves morphir.frontend.compileModel and claims:

ClaimValue
Claims version0.1.0-draft.2
Languagefsharp, with the file extension .fs
Several documents in one requestyes (multiDocument: true)
Legacy morphir.frontend.compileno
Incremental compilationno
Model tuplesmorphir.frontend.compileModel, profile morphir-ir, codec morphir-json, envelope 0.1.0-draft.1, IR 4.0.0 and 3.0.0

Classic IR versions 1 and 2 have no tuple. For them, the host compiles at 3.0.0, reads the classic model, and writes it at the requested version. The model does not change family. A host that agrees only 4.0.0 with a guest refuses a classic request before it sends one.

To use the guest from the morphir executable, give its path with --extension, or set it in the project configuration:

morphir compile --extension "$(which morphir-fsharp-frontend)"
[frontend.fsharp]
extension = "morphir-fsharp-frontend"

The host starts the guest with explicit arguments and no shell, and passes the guest’s stderr to its own stderr. Before it sends a request, it checks that the session admits the language, the number of documents and the IR version. It always ends the session with shutdown and exit, or stops the process after a deadline. Guest output on stdout that is not a frame fails the compile with extension.protocol_error.

The model in a successful result is a verified envelope: canonical base64 of the IR JSON, its exact length and its SHA-256. The host checks them before it reads the IR. For the same documents, the IR and the diagnostics from the guest equal the in-process results; a test compares them for every case of the conformance corpus.

Upstream qualification: the MEP guest kit of finos/morphir (generic-json-library-v1) still needs a legacy 0.1 stage and a backend, so the guest is not qualified with it yet. Its conformance comes from the pinned 0.2.0-draft.1 contract, the pinned session transcripts and the model-transport cases. See deviations.

How the frontend is checked

  • The conformance corpus has cases for IR versions 1 to 4 and three input kinds. Each refused construct has its own case. The cases do not depend on the implementation.
  • Behavior cases call the compiled values with JSON arguments and compare the results.
  • A round trip generates F# from each compiled model with the F# backend, compiles that F# again, and requires the same model.

Prior art

The frontend uses the design of two F# projects, but it does not depend on them.

ProjectWhat the frontend usesWhat it does not use, and why
Fable (MIT)Design patterns: how decision trees appear in the typed tree, a replacement table for core-library calls, how inline values and witnesses appear in the typed tree, and a resolver interface for project cracking.Fable.Transforms as a library. It carries Fable’s own syntax tree and replacements for JavaScript, Python and Rust targets.
Fantomas (Apache-2.0)The F# backend formats generated code with Fantomas.Core. The round-trip check uses that backend.Fantomas.FCS in the frontend. Its syntax tree is not binary-compatible with the F# compiler service, and the frontend needs the compiler service for type checking. A second parser would give a second set of ranges.

If code is adapted from these projects, and not only its design, the source file names its origin and the NOTICE file gives the attribution.

1.1 - F# frontend coverage

The F# constructs that the F# frontend refuses, with their diagnostic codes and examples.

The F# frontend compiles a subset of F#. Before it lowers a document, admission checks the syntax and refuses each construct outside the subset with an error diagnostic. All refusals of a run are reported together, and the frontend writes no model. The overview describes the supported subset.

This page is generated from the admission catalog of the frontend, so it lists every code that admission can report. Each rule has a minimal example that gives only its own code. The conformance corpus has one refusal case for each code. Codes are stable once released.

Codes

CodeConstruct
fsharp.unsupported_mutablemutable binding or field
fsharp.unsupported_assignmentassignment
fsharp.unsupported_looploop
fsharp.unsupported_classclass
fsharp.unsupported_interfaceinterface
fsharp.unsupported_membermember
fsharp.unsupported_object_expressionobject expression
fsharp.unsupported_sequence_expressionsequence expression
fsharp.unsupported_computation_expressioncomputation expression
fsharp.unsupported_comprehensionlist comprehension or range
fsharp.unsupported_arrayarray
fsharp.unsupported_exceptionexception
fsharp.unsupported_active_patternactive pattern
fsharp.unsupported_unit_of_measureunit of measure
fsharp.unsupported_quotationquotation
fsharp.unsupported_anonymous_recordanonymous record
fsharp.unsupported_structstruct type or struct tuple
fsharp.unsupported_inlineinline function
fsharp.unsupported_attributeattribute with an effect
fsharp.unsupported_type_testtype test
fsharp.unsupported_castcast
fsharp.unsupported_nullnull
fsharp.unsupported_useuse binding
fsharp.unsupported_sequentialsequential expression
fsharp.unsupported_literalliteral of an unsupported type
fsharp.unsupported_enumenum
fsharp.unsupported_delegatedelegate
fsharp.unsupported_pattern_guardpattern guard
fsharp.unsupported_or_patternor pattern
fsharp.unsupported_record_patternrecord pattern
fsharp.unsupported_list_patternlist pattern with elements
fsharp.unsupported_named_field_patternnamed field pattern
fsharp.unsupported_conditional_compilationconditional compilation
fsharp.unsupported_signature_filesignature file

The fallback rules below refuse any expression, pattern, type or declaration outside the supported subset that no specific rule refused.

CodeConstruct
fsharp.unsupported_expressionexpression outside the supported subset
fsharp.unsupported_patternpattern outside the supported subset
fsharp.unsupported_typetype outside the supported subset
fsharp.unsupported_declarationdeclaration outside the supported subset

Rules

fsharp.unsupported_mutable

Construct: mutable binding or field

Message: Mutable bindings and fields are not supported; Morphir values are immutable.

Suggestion: Use a new let binding, or a record update, instead of changing a value.

Example. The diagnostic is at mutable.

Example.fs:

namespace Acme.Demo
module Example =
    let mutable total = 0

fsharp.unsupported_assignment

Construct: assignment

Message: Assignment with ‘<-’ is not supported; Morphir values are immutable.

Suggestion: Return a new value instead of changing an existing one.

Example. The diagnostic is at builder.Length <- 0.

Example.fs:

namespace Acme.Demo
module Example =
    let reset (builder: System.Text.StringBuilder) = builder.Length <- 0

fsharp.unsupported_loop

Construct: loop

Message: Loops (‘for’, ‘while’) are not supported; Morphir has no statements.

Suggestion: Use recursion or a List function such as List.map or List.fold.

Example. The diagnostic is at for index in 1 .. 3 do ignore index.

Example.fs:

namespace Acme.Demo
module Example =
    let count () = for index in 1 .. 3 do ignore index

fsharp.unsupported_class

Construct: class

Message: Classes are not supported; Morphir types are records, unions and type abbreviations.

Suggestion: Use a record for the data and module functions for the behavior.

Example. The diagnostic is at this text:

Counter() =
        member _.Value = 1

Example.fs:

namespace Acme.Demo
module Example =
    type Counter() =
        member _.Value = 1

fsharp.unsupported_interface

Construct: interface

Message: Interfaces are not supported; Morphir has no subtyping.

Suggestion: Use a record of functions, or a union of the cases.

Example. The diagnostic is at this text:

IShape =
        abstract Area: float

Example.fs:

namespace Acme.Demo
module Example =
    type IShape =
        abstract Area: float

fsharp.unsupported_member

Construct: member

Message: Members and type extensions are not supported; Morphir types have no methods.

Suggestion: Define a module function that takes the value as a parameter.

Example. The diagnostic is at member this.Double = this.Seats * 2.

Example.fs:

namespace Acme.Demo
module Example =
    type Car = { Seats: int } with
        member this.Double = this.Seats * 2

fsharp.unsupported_object_expression

Construct: object expression

Message: Object expressions are not supported; Morphir has no objects.

Suggestion: Use a record of functions.

Example. The diagnostic is at { new System.Object() with member _.ToString() = "x" }.

Example.fs:

namespace Acme.Demo
module Example =
    let text = { new System.Object() with member _.ToString() = "x" }

fsharp.unsupported_sequence_expression

Construct: sequence expression

Message: Sequence expressions (‘seq { }’) are not supported; Morphir has no lazy sequences.

Suggestion: Use a list and the List functions.

Example. The diagnostic is at { yield 1 }.

Example.fs:

namespace Acme.Demo
module Example =
    let numbers = seq { yield 1 }

fsharp.unsupported_computation_expression

Construct: computation expression

Message: Computation expressions are not supported; Morphir has no effects or builders.

Suggestion: Write the steps as plain functions, for example with Result.bind.

Example. The diagnostic is at { return 1 }.

Example.fs:

namespace Acme.Demo
module Example =
    let work = async { return 1 }

fsharp.unsupported_comprehension

Construct: list comprehension or range

Message: List comprehensions and ranges (’[ for … ]’, ‘[ 1 .. 3 ]’) are not supported.

Suggestion: Use List.map, List.filter or an explicit list.

Example. The diagnostic is at [ for x in [ 1; 2 ] -> x * x ].

Example.fs:

namespace Acme.Demo
module Example =
    let squares = [ for x in [ 1; 2 ] -> x * x ]

fsharp.unsupported_array

Construct: array

Message: Arrays are not supported; Morphir collections are immutable lists.

Suggestion: Use a list.

Example. The diagnostic is at [| 1; 2 |].

Example.fs:

namespace Acme.Demo
module Example =
    let numbers = [| 1; 2 |]

fsharp.unsupported_exception

Construct: exception

Message: Exceptions (’exception’, ’try … with’, ’try … finally’) are not supported; Morphir has no effects.

Suggestion: Return a Result or an option.

Example. The diagnostic is at exception Failed of string.

Example.fs:

namespace Acme.Demo
module Example =
    exception Failed of string

fsharp.unsupported_active_pattern

Construct: active pattern

Message: Active patterns are not supported; Morphir patterns match only constructors and values.

Suggestion: Use a union and a function that returns it.

Example. The diagnostic is at let (|Even|Odd|) n = if n % 2 = 0 then Even else Odd.

Example.fs:

namespace Acme.Demo
module Example =
    let (|Even|Odd|) n = if n % 2 = 0 then Even else Odd

fsharp.unsupported_unit_of_measure

Construct: unit of measure

Message: Units of measure are not supported; Morphir numbers carry no unit.

Suggestion: Use a single-case union to name the quantity.

Example. The diagnostic is at [<Measure>] type kg.

Example.fs:

namespace Acme.Demo
module Example =
    [<Measure>] type kg

fsharp.unsupported_quotation

Construct: quotation

Message: Quotations are not supported; Morphir models values, not code.

Example. The diagnostic is at <@ 1 + 1 @>.

Example.fs:

namespace Acme.Demo
module Example =
    let expression = <@ 1 + 1 @>

fsharp.unsupported_anonymous_record

Construct: anonymous record

Message: Anonymous records are not supported; Morphir record types have names.

Suggestion: Declare a record type.

Example. The diagnostic is at {| X = 1 |}.

Example.fs:

namespace Acme.Demo
module Example =
    let point = {| X = 1 |}

fsharp.unsupported_struct

Construct: struct type or struct tuple

Message: Struct types and struct tuples are not supported; Morphir has no value-type layout.

Suggestion: Remove [] or ‘struct’.

Example. The diagnostic is at struct (1, 2).

Example.fs:

namespace Acme.Demo
module Example =
    let pair = struct (1, 2)

fsharp.unsupported_inline

Construct: inline function

Message: Inline functions are not supported; Morphir functions are not specialized at their call sites.

Suggestion: Remove ‘inline’ and give the parameters concrete types.

Example. The diagnostic is at inline.

Example.fs:

namespace Acme.Demo
module Example =
    let inline double (x: int) = x * 2

fsharp.unsupported_attribute

Construct: attribute with an effect

Message: This attribute changes the meaning of the code and is not supported.

Suggestion: Remove the attribute. Only RequireQualifiedAccess, AutoOpen, CompilationRepresentation, CompiledName and MorphirName are accepted.

Example. The diagnostic is at Literal.

Example.fs:

namespace Acme.Demo
module Example =
    [<Literal>]
    let Limit = 10

fsharp.unsupported_type_test

Construct: type test

Message: Type tests (’:?’) are not supported; Morphir has no runtime types.

Suggestion: Use a union to tell the cases apart.

Example. The diagnostic is at value :? string.

Example.fs:

namespace Acme.Demo
module Example =
    let isText (value: obj) = value :? string

fsharp.unsupported_cast

Construct: cast

Message: Casts (’:>’, ‘:?>’, ‘upcast’, ‘downcast’) are not supported; Morphir has no subtyping.

Example. The diagnostic is at 1 :> obj.

Example.fs:

namespace Acme.Demo
module Example =
    let boxed = (1 :> obj)

fsharp.unsupported_null

Construct: null

Message: ’null’ is not supported; Morphir values are never null.

Suggestion: Use an option.

Example. The diagnostic is at null.

Example.fs:

namespace Acme.Demo
module Example =
    let nothing: string = null

fsharp.unsupported_use

Construct: use binding

Message: ‘use’ bindings are not supported; Morphir has no resources to dispose.

Suggestion: Use ’let’.

Example. The diagnostic is at this text:

use stream = new System.IO.MemoryStream()
        stream.Length

Example.fs:

namespace Acme.Demo
module Example =
    let size () =
        use stream = new System.IO.MemoryStream()
        stream.Length

fsharp.unsupported_sequential

Construct: sequential expression

Message: Sequential expressions (‘a; b’) are not supported; Morphir values have no side effects.

Suggestion: Remove the expression whose value is discarded.

Example. The diagnostic is at this text:

ignore 1
        2

Example.fs:

namespace Acme.Demo
module Example =
    let both () =
        ignore 1
        2

fsharp.unsupported_literal

Construct: literal of an unsupported type

Message: This literal type is not supported; Morphir numbers are Int, Float and Decimal.

Suggestion: Use an int, int64, float or decimal literal.

Example. The diagnostic is at 1uy.

Example.fs:

namespace Acme.Demo
module Example =
    let small = 1uy

fsharp.unsupported_enum

Construct: enum

Message: Enums are not supported; Morphir custom types have no numeric values.

Suggestion: Use a union without fields.

Example. The diagnostic is at this text:

Color =
        | Red = 0
        | Blue = 1

Example.fs:

namespace Acme.Demo
module Example =
    type Color =
        | Red = 0
        | Blue = 1

fsharp.unsupported_delegate

Construct: delegate

Message: Delegates are not supported; Morphir has function types.

Suggestion: Use a function type.

Example. The diagnostic is at Handler = delegate of int -> unit.

Example.fs:

namespace Acme.Demo
module Example =
    type Handler = delegate of int -> unit

fsharp.unsupported_pattern_guard

Construct: pattern guard

Message: Pattern guards (‘when’) are not supported; a Morphir pattern has no condition.

Suggestion: Match the case, then use ‘if’ in its body.

Example. The diagnostic is at n > 3.

Example.fs:

namespace Acme.Demo
module Example =
    let size n =
        match n with
        | n when n > 3 -> "big"
        | _ -> "small"

fsharp.unsupported_or_pattern

Construct: or pattern

Message: Or patterns (‘A | B’) are not supported; a Morphir case has one pattern.

Suggestion: Write one case for each alternative.

Example. The diagnostic is at 1 | 2.

Example.fs:

namespace Acme.Demo
module Example =
    let low n =
        match n with
        | 1 | 2 -> true
        | _ -> false

fsharp.unsupported_record_pattern

Construct: record pattern

Message: Record patterns are not supported.

Suggestion: Bind the record to a variable and read its fields.

Example. The diagnostic is at { Seats = s }.

Example.fs:

namespace Acme.Demo
module Example =
    type Car = { Seats: int }
    let seats car =
        match car with
        | { Seats = s } -> s

fsharp.unsupported_list_pattern

Construct: list pattern with elements

Message: List patterns with elements (’[ a; b ]’) are not supported.

Suggestion: Use ‘::’ and ‘[]’ patterns.

Example. The diagnostic is at [ a ].

Example.fs:

namespace Acme.Demo
module Example =
    let first xs =
        match xs with
        | [ a ] -> a
        | _ -> 0

fsharp.unsupported_named_field_pattern

Construct: named field pattern

Message: Named field patterns (‘Case(field = p)’) are not supported.

Suggestion: Match the fields by position.

Example. The diagnostic is at Rented(days = d).

Example.fs:

namespace Acme.Demo
module Example =
    type Status = Rented of days: int
    let days status =
        match status with
        | Rented(days = d) -> d

fsharp.unsupported_conditional_compilation

Construct: conditional compilation

Message: Conditional compilation (’#if’) is not supported, because this frontend does not choose defines.

Suggestion: Remove the directive, or keep one branch.

Example. The diagnostic is at #if DEBUG.

Example.fs:

namespace Acme.Demo
module Example =
#if DEBUG
    let mode = "debug"
#else
    let mode = "release"
#endif

fsharp.unsupported_signature_file

Construct: signature file

Message: Signature files (’.fsi’) are not supported; access comes from F# visibility and the exposed modules.

Suggestion: Remove the signature file and use ‘private’ or ‘internal’.

Example. The diagnostic is an empty range at the start of the first document.

Example.fsi:

namespace Acme.Demo
module Example =
    val total: int

Example.fs:

namespace Acme.Demo
module Example =
    let total = 1

fsharp.unsupported_expression

Construct: expression outside the supported subset

Message: This kind of expression is not supported by the F# frontend.

Example. The diagnostic is at lazy 1.

Example.fs:

namespace Acme.Demo
module Example =
    let later = lazy 1

fsharp.unsupported_pattern

Construct: pattern outside the supported subset

Message: This kind of pattern is not supported by the F# frontend.

Example. The diagnostic is at (a, _) & (_, b).

Example.fs:

namespace Acme.Demo
module Example =
    let both pair =
        match pair with
        | (a, _) & (_, b) -> a + b

fsharp.unsupported_type

Construct: type outside the supported subset

Message: This kind of type is not supported by the F# frontend.

Example. The diagnostic is at #seq<int>.

Example.fs:

namespace Acme.Demo
module Example =
    let total (values: #seq<int>) = Seq.sum values

fsharp.unsupported_declaration

Construct: declaration outside the supported subset

Message: This kind of declaration is not supported by the F# frontend.

Example. The diagnostic is at do ignore 1.

Example.fs:

namespace Acme.Demo
module Example =
    do ignore 1

2 - 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.

2.1 - C# frontend coverage

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

The C# frontend compiles a subset of C# 15. After the C# compiler binds the documents without an error, an admission analyzer refuses each construct outside the subset with an error diagnostic. All refusals of a run are reported together, and the frontend writes no model. The overview describes the supported subset.

The same analyzer runs in the compiler, in the IDE and in morphir compile, so a refusal has one code, one message and one range everywhere. A rule cannot be turned off: #pragma warning disable, .editorconfig and NoWarn do not hide it, and a SuppressMessage attribute that names a rule is refused with MORPHIR1008. A construct that a rule refuses cannot become a model, so change the construct. The absolute IRI of a rule is the help link of its diagnostic. Codes are stable once released.

Codes

CodeRoslyn idConstruct
csharp.unsupported_loopMORPHIR1001A loop with no Morphir form is not in the Morphir subset
csharp.unsupported_mutationMORPHIR1002A change of a value is not in the Morphir subset
csharp.unsupported_dynamicMORPHIR1003dynamic is not in the Morphir subset
csharp.unsupported_mutable_propertyMORPHIR1004A property with a set accessor is not in the Morphir subset
csharp.unsupported_outside_referenceMORPHIR1005A symbol outside the fixed reference set is not in the Morphir subset
csharp.unsupported_type_kindMORPHIR1006This kind of type is not in the Morphir subset
csharp.unsupported_mutable_fieldMORPHIR1007A field that can change is not in the Morphir subset
csharp.unsupported_suppressionMORPHIR1008A suppression of a Morphir rule is not in the Morphir subset
csharp.unsupported_abstract_recordMORPHIR1009An older encoding of a sum type is not in the Morphir subset
csharp.unsupported_non_partial_equalityMORPHIR1010A type with IEEE equality must be partial

csharp.unsupported_loop

  • Roslyn id: MORPHIR1001
  • Message: The ‘…’ loop is not in the Morphir subset: it …
  • IRI: https://morphir.finos.org/rules/csharp/unsupported_loop

Example:

static class M
{
    static int F(int[] xs)
    {
        foreach (var x in xs) { }
        return 0;
    }
}

csharp.unsupported_mutation

  • Roslyn id: MORPHIR1002
  • Message: A change of ‘…’ is not in the Morphir subset
  • IRI: https://morphir.finos.org/rules/csharp/unsupported_mutation

Example:

static class M
{
    static int F(int a)
    {
        a = 1;
        return a;
    }
}

csharp.unsupported_dynamic

  • Roslyn id: MORPHIR1003
  • Message: ‘dynamic’ is not in the Morphir subset
  • IRI: https://morphir.finos.org/rules/csharp/unsupported_dynamic

Example:

static class M
{
    static int F(dynamic d) => 1;
}

csharp.unsupported_mutable_property

  • Roslyn id: MORPHIR1004
  • Message: Property ‘…’ has a ‘set’ accessor
  • IRI: https://morphir.finos.org/rules/csharp/unsupported_mutable_property

Example:

sealed record R
{
    public int X { get; set; }
}

csharp.unsupported_outside_reference

  • Roslyn id: MORPHIR1005
  • Message: ‘…’ comes from the assembly ‘…’, which is outside the fixed reference set
  • IRI: https://morphir.finos.org/rules/csharp/unsupported_outside_reference

The analyzer reports a symbol from an assembly that the fixed reference set does not have. morphir compile cannot bind such a symbol, so the C# compiler reports it first as csharp.compiler.

csharp.unsupported_type_kind

  • Roslyn id: MORPHIR1006
  • Message: The … ‘…’ is not in the Morphir subset. Use a record, a closed record, a union, an enum or a static class.
  • IRI: https://morphir.finos.org/rules/csharp/unsupported_type_kind

Example:

class C { }

csharp.unsupported_mutable_field

  • Roslyn id: MORPHIR1007
  • Message: Field ‘…’ can change
  • IRI: https://morphir.finos.org/rules/csharp/unsupported_mutable_field

Example:

static class M
{
    public static int X;
}

csharp.unsupported_suppression

  • Roslyn id: MORPHIR1008
  • Message: The attribute suppresses the Morphir rule ‘…’. A construct that a Morphir rule refuses cannot become a model; change the construct.
  • IRI: https://morphir.finos.org/rules/csharp/unsupported_suppression

Example:

[System.Diagnostics.CodeAnalysis.SuppressMessage("Morphir", "MORPHIR1001")]
static class M
{
    public static int F() => 1;
}

csharp.unsupported_abstract_record

  • Roslyn id: MORPHIR1009
  • Message: The abstract record ‘…’ is an older encoding of a sum type. Write ‘closed record …’ with ‘sealed record’ cases.
  • IRI: https://morphir.finos.org/rules/csharp/unsupported_abstract_record

Example:

public abstract record Shape
{
    private Shape() { }
    public sealed record Circle(double Radius) : Shape;
    public sealed record Rect(double W, double H) : Shape;
}

csharp.unsupported_non_partial_equality

  • Roslyn id: MORPHIR1010
  • Message: The type ‘…’ has IEEE equality from a MorphirEquality attribute and is not partial. Add ‘partial’ to the type, because the equality members are added to it.
  • IRI: https://morphir.finos.org/rules/csharp/unsupported_non_partial_equality

Example:

[Morphir.MorphirEquality(Morphir.FloatEquality.Ieee)]
public sealed record Quote(double Value);