Generate hybrid (tagged/type) union types.
$ dotnet add package RhoMicro.CodeAnalysis.JanusThis is a source generator for generating union types. Read about union types here: https://en.wikipedia.org/wiki/Union_type
This source code generator is licensed to you under the MPL-2.0.
myUnion.IsResult or MyUnion.CreateFromResult(result)myUnion.IsNumberSystem.Text.Json serializationPackage Reference:
<ItemGroup>
<PackageReference Include="RhoMicro.CodeAnalysis.Janus" Version="*"/>
</ItemGroup>
CLI:
dotnet add package RhoMicro.CodeAnalysis.Janus
Annotate your union type with the UnionType attribute:
[UnionType<String, Double>]
readonly partial struct Union;
Use your union type:
Union u = "Hello, World!"; //implicitly converted
u = 32; //implicitly converted
u = false; //CS0029 Cannot implicitly convert type 'bool' to 'Union'
UnionTypeAttribute<T0> and UnionTypeAttributeUse UnionTypeAttribute<T0> to add T0 to the list of variants:
[UnionType<Int32>]
[UnionType<String>]
partial struct IntOrString;
Usage:
IntOrString u = "Hello, World!"; //implicitly converted
u = 32; //implicitly converted
Use UnionTypeAttribute on type parameters to add the targeted type parameter to the list of variants:
partial struct GenericUnion<[UnionType] T0, [UnionType] T1>;
Usage:
var u = GenericUnion<Int32, String>.CreateFromT1("Hello, World!");
u = GenericUnion<Int32, String>.CreateFromT0(32);
Note: due to compiler restrictions no conversions from or to generic type parameters are generated. Using factory methods is an alternative way of creating union instances.
NameDefine names for generated members using Name:
[UnionType<List<String>>(Name = "MultipleNames")]
[UnionType<String>(Name = "SingleName")]
partial struct Names;
Usage:
Names n = "John";
if(n.IsSingleName)
{
var singleName = n.AsSingleName;
} else if(n.IsMultipleNames)
{
var multipleNames = n.AsMultipleNames;
}
DescriptionProvide a description for the variant:
[UnionType<int>(Description = "This variant is used for integer values.")]
partial struct Result
IsNullableSpecify the nullability of a reference type variant:
NullableStringUnion foo1 = "value";
string value1 = foo1.CastToString; // CS8600 Converting null literal or possible null value to non-nullable type.
NonNullableStringUnion foo2 = "value";
string value2 = foo2.CastToString; // no nullability warning
[UnionType<string>(IsNullable = true)]
partial struct NullableStringUnion;
[UnionType<string>] // implicitly non-nullable
partial struct NonNullableStringUnion;
GroupsGroup variants into categories by assigning Groups:
[UnionType<Int32, Single>(Groups = ["Number"])]
[UnionType<String, Char>(Groups = ["Text"])]
partial struct GroupedUnion;
Usage:
GroupedUnion u = "Hello, World!";
if(u.Variant.Groups.ContainsNumber)
{
Assert.Fail("Expected union to be text.");
}
if(!u.Variant.Groups.ContainsText)
{
Assert.Fail("Expected union to be text.");
}
u = 32f;
if(!u.Variant.Groups.ContainsNumber)
{
Assert.Fail("Expected union to be number.");
}
if(u.Variant.Groups.ContainsText)
{
Assert.Fail("Expected union to be number.");
}
UnionTypeAttribute<T0..Tn>The generic UnionTypeAttribute types allow to define multiple variants inline:
[UnionType<int, double, byte>]
partial struct Union;
UnionTypeSettingsAttributeUse the UnionTypeSettingsAttribute to supply additional instructions to the generator.
The attribute may be applied to either an assembly or a union type.
When targeting a union type, it defines settings specific to that type.
If, however, the attribute is annotating an assembly, it supplies the default settings for every union type in that
assembly.
Settings inheritance is therefore ordered like so:
ToStringSettingDefine how implementations of ToString should be generated:
InheritInherits the setting. This is the default value.
- If the target is a type, it will inherit the setting from its containing assembly.
- If the target is an assembly, the
Detailedsetting will be used.
DetailedThe generator will emit an implementation that returns detailed information, including:
- the name of the union type
- the set of variants
- an indication of which variant is being represented by the instance
- the value currently being represented by the instance
NoneThe generator will not generate an implementation of
ToString.
SimpleThe generator will generate an implementation that returns the result of calling
ToStringon the currently represented value.
EqualityOperatorsSettingDefine if equality operators should be generated:
InheritInherits the setting. This is the default value.
- If the target is a type, it will inherit the setting from its containing assembly.
- If the target is an assembly, the
EmitOperatorsIfValueTypesetting will be used.
EmitOperatorsIfValueTypeEquality operators will be emitted only if the target union type is a value type.
EmitOperatorsEquality operators will be emitted.
OmitOperatorsEquality operators will be omitted.
JsonConverterSettingDefine how JSON support should be generated:
InheritInherits the setting. This is the default value.
- If the target is a type, it will inherit the setting from its containing assembly.
- If the target is an assembly, the
OmitJsonConvertersetting will be used.
OmitJsonConverterNo JSON converter implementation is emitted.
EmitJsonConverterA JSON converter implementation is emitted.
In our imaginary usecase, a user shall be retrieved from the infrastructure via a name query. The following types will be found throughout the example:
sealed record User(String Name);
enum ErrorCode
{
NotFound,
Unauthorized
}
readonly record struct MultipleUsersError(Int32 Count);
The User type represents a user. The ErrorCode represents an error that does not contain additional information,
like MultipleUsersError does. It represents multiple users having been found while only one was requested.
We define a union type to represent our imaginary query:
[UnionType<ErrorCode, MultipleUsersError>(Groups = ["Error"])]
[UnionType<User>(Groups = ["Success"])]
readonly partial struct GetUserResult;
Instances of GetUserResult can represent either an instance of ErrorCode, MultipleUsersError or User.
It will be used in a service façade like so:
interface IUserService
{
GetUserResult GetUserByName(String name);
}
A repository abstracts over the underlying infrastructure:
interface IUserRepository
{
IQueryable<User> UsersByName(String name);
}
Access violations would be communicated through the repository using the following exception type:
sealed class UnauthorizedDatabaseAccessException : Exception;
An implementation of the IUserService is provided as follows:
sealed class UserService : IUserService
{
public UserService(IUserRepository repository) => _repository = repository;
private readonly IUserRepository _repository;
public GetUserResult GetUserByName(String name)
{
IQueryable<User> users;
try
{
users = _repository.UsersByName(name);
} catch(UnauthorizedDatabaseAccessException)
{
return ErrorCode.Unauthorized;
}
var reifiedUsers = users.ToArray();
if(reifiedUsers.Length == 0)
{
return ErrorCode.NotFound;
} else if(reifiedUsers.Length > 1)
{
return new MultipleUsersError(reifiedUsers.Length);
}
return reifiedUsers[0];
}
}
As you can see, possible representations of GetUserResult are implicitly converted and returned by the service. Users
of OneOf will be familiar with this.
On the consumer side of this api, a generated Match function helps with transforming the union instance to another
type:
sealed class UserModel
{
public UserModel(IUserService service) => _service = service;
private readonly IUserService _service;
public String ErrorMessage { get; private set; } = String.Empty;
public User? User { get; private set; }
public void SetUser(String name)
{
var getUserResult = _service.GetUserByName(name);
User = getUserResult.Switch(
onErrorCode: HandleErrorCode,
onMultipleUsersError: HandleMultipleResult,
onUser: user => user);
}
private User? HandleErrorCode(ErrorCode code)
{
ErrorMessage = code switch
{
ErrorCode.NotFound => "The user could not be located.",
ErrorCode.Unauthorized => "You are not authorized to access users.",
_ => throw new NotImplementedException()
};
return null;
}
private User? HandleMultipleResult(MultipleUsersError result)
{
ErrorMessage = $"{result.Count} users have been located. The name was not precise enough.";
return null;
}
}