Ferrous API Reference

Ferrous API Reference

API reference generated by dotnet fe doc — 98 public type(s).

Ferrous.Annotations

TypeKindSummary
MustUseAnalyzerclassRoslyn diagnostic analyzer that warns when a value annotated with [MustUse] (via its method, constructor, or return type) is discarded in an expression statement. Equivalent to Rust's #[must_use] lint.
MustUseCodeFixProviderclassRoslyn code fix provider for MustUseAnalyzer.DiagnosticId (FE0001) that inserts an explicit discard (_ = ...).

Ferrous.AspNetCore

TypeKindSummary
FerrousEndpointBuilderExtensionsclassExtension methods for registering FerrousResultEndpointFilter on Minimal API endpoints and route groups.
FerrousOpenApiExtensionsclassExtension methods for registering Ferrous OpenAPI schema transformations on OpenApiOptions.
FerrousOpenApiSchemaTransformerclassOpenAPI schema transformer that unwraps Ferrous refined types (NonEmptyString, NonZero<T>) and [Newtype(typeof(T))] structs into their underlying primitive OpenAPI schemas instead of wrapper objects.
FerrousResultEndpointFilterclassMinimal API IEndpointFilter that automatically unwraps Result<T, TError> and Option<T> return values into HTTP IResult responses (200 OK, 404 Not Found, or RFC 7807 ProblemDetails).
ResultHttpExtensionsclassExtension methods that map Result<T, TError> and Option<T> values to ASP.NET Core Minimal API IResult responses (including RFC 7807 ProblemDetails).

Ferrous

TypeKindSummary
BorrowAttributeclassMarks a parameter as taking a shared (read-only) borrow of the passed argument. Enforced by Ferrous.Ownership (FE0202 exclusivity and FE0203 escape checks).
BorrowMutAttributeclassMarks a parameter as taking an exclusive mutable borrow of the passed argument. Enforced by Ferrous.Ownership (FE0202 aliasing-XOR-mutability and FE0203 escape checks).
CheckedAttributeclassMarks a method, constructor, property, or type as requiring explicit checked or saturating integer arithmetic (enforced by Ferrous.Pedantic FE0414).
ClosedAttributeclassMarks an abstract class or record hierarchy as closed so switch expressions and statements must exhaustively handle all derived types in the compilation (enforced by Ferrous.Pedantic FE0400).
ConsumesSelfAttributeclassMarks an instance method as consuming this (the receiver) during a state transition. Used by Ferrous.Ownership and Ferrous.States to enforce linear typestate protocols.
ConsumingAttributeclassMarks a parameter as consuming ownership of the passed argument. Once a local variable is passed to a ConsumingAttribute parameter, subsequent reads or mutations of that variable are flagged by Ferrous.Ownership.
DiscriminatedUnionAttributeclassMarks a partial struct or record as a discriminated union whose boilerplate (case wrappers, structural equality, exhaustive Match, and .NET 11+ [Union] protocol) is generated by Ferrous.Unions.
ErrorMessageAttributeclassAnnotates a [DiscriminatedUnion] variant factory method with a human-readable error message template (Rust thiserror #[error("...")] style). Placeholders matching parameter names (e.g., "{port}") are interpolated by the generated FormatError() and ToString() methods.
ExhaustiveAttributeclassMarks an enum type as requiring exhaustive handling in switch expressions and statements even when a discard/default arm is present (enforced by Ferrous.Pedantic FE0400).
ImmutableAttributeclassMarks a parameter, field, or property as deeply immutable (approximating Rust's &T). Property/field setters and mutating collection calls on the annotated symbol or its nested members are flagged by Ferrous.Pedantic (FE0418).
InstrumentAttributeclassMarks a partial method for compile-time System.Diagnostics.Activity span instrumentation inspired by Rust's #[tracing::instrument]. The Ferrous.Unions source generator emits a System.Diagnostics.ActivitySource span wrapping a companion {MethodName}Core(...) implementation and automatically records non-skipped parameter values as activity tags.
MustUseAttributeclassIndicates that a return value or an instance of the annotated type should not be silently ignored. Equivalent to Rust's #[must_use] attribute.
NewtypeAttributeclassMarks a readonly partial struct as a zero-overhead Rust-style newtype wrapper around UnderlyingType. Ferrous.Unions generates Value, equality, comparison, parsing, span formatting, [NoDefault], and a NativeAOT-safe System.Text.Json converter.
NoAllocAttributeclassMarks a method, constructor, or property as zero-allocation (enforced by Ferrous.Pedantic FE0413). Implicit struct boxing, reference-type allocations, closure captures, and implicit params arrays are flagged.
NoDefaultAttributeclassMarks a struct as forbidding default/uninitialized construction via default, parameterless new(), or uninitialized fields/arrays (enforced by Ferrous.Pedantic FE0404).
NoThrowAttributeclassMarks a method, constructor, or property as non-throwing (enforced by Ferrous.Pedantic FE0402).
ThreadConfinedAttributeclassMarks a type as thread-confined (!Send): instances must not be captured across thread boundaries such as Task.Run, Parallel.ForEach, or ThreadPool.QueueUserWorkItem (enforced by Ferrous.Concurrency.Analyzers FE0500).
TypestateAttributeclassMarks a type as a state in a linear typestate protocol enforced by Ferrous.States and Ferrous.Ownership.

Ferrous.CodeFixes

TypeKindSummary
FerrousMigrationRefactoringProviderclassOn-demand Roslyn IDE refactoring provider (Ctrl+. / lightbulb) for progressively migrating idiomatic C# code to Ferrous: Convert throwing method (sync or async Task<T>/ValueTask<T>) to Result<T, string> Convert nullable-returning method (T?, Task<T?>, or expression-bodied) to Option<T> Wrap primitive parameter in a [Newtype(typeof(T))] struct
FerrousStructuralMigrationRefactoringProviderclassOn-demand Roslyn IDE structural refactoring provider (Ctrl+. / lightbulb) for migrating higher-level C# patterns to Ferrous: Convert abstract record hierarchy → [DiscriminatedUnion] struct Convert lock (_gate) + protected field → Mutex<T>
SafetyCodeFixProviderclassRoslyn IDE quick-fix provider for Ferrous safety and concurrency rules (FE0407, FE0409, FE0414, FE0415, FE0417, FE0420, FE0501).

Ferrous.Concurrency.Analyzers

TypeKindSummary
ConcurrencyAnalyzerclassRoslyn analyzer enforcing Rust-inspired concurrency safety: FE0500: Thread-confined (!Send) value captured across a thread boundary. FE0501: Unsynchronized mutable static field (static mut).
DetachedTaskAnalyzerclassRoslyn diagnostic analyzer (FE0503) that flags detached Task.Run(...) calls inside methods that already have a TaskScope in scope, encouraging structured concurrency via scope.Spawn(...).
LockAcrossAwaitAnalyzerclassCFG-based Roslyn analyzer (FE0502) flagging SemaphoreSlim, ReaderWriterLockSlim, or Monitor locks held across await points (clippy::await_holding_lock).

Ferrous.Concurrency

TypeKindSummary
AsyncMutex<T>classAn async-capable data-owning mutual exclusion primitive inspired by tokio::sync::Mutex<T>. Compiled with .NET 11 runtime async (runtime-async=on) on net11.0.
AsyncMutexGuard<T> [MustUse]structA RAII guard providing exclusive access to the value owned by an AsyncMutex<T>.
AsyncReadGuard<T> [MustUse]structAsync shared read guard for AsyncRwLock<T>.
AsyncRwLock<T>classAn async-capable data-owning reader-writer lock inspired by tokio::sync::RwLock<T>. Compiled with .NET 11 runtime async (runtime-async=on) on net11.0.
AsyncWriteGuard<T> [MustUse]structAsync exclusive write guard for AsyncRwLock<T>.
ChannelReceiver<T>classReceive-only handle for a TypedChannel.
ChannelSender<T>classSend-only handle for a TypedChannel. Calling Complete consumes the sender handle ([ConsumesSelf]) so Ferrous.Ownership prevents sending after close.
LazyLock<T>classA thread-safe lazily initialized value inspired by Rust's std::sync::LazyLock<T>. Safe to store in static readonly fields without triggering FE0501.
Mutex<T>classA data-owning mutual exclusion primitive inspired by Rust's std::sync::Mutex<T>. The protected value can only be accessed while holding a stack-allocated MutexGuard<T>.
MutexGuard<T> [MustUse]structA stack-allocated RAII guard providing exclusive access to the value owned by a Mutex<T>. Because this is a ref struct, it cannot escape to the heap or be held across await.
OnceLock<T>classA thread-safe write-once synchronization cell inspired by Rust's std::sync::OnceLock<T>. Safe to store in static readonly fields without triggering FE0501.
ReadGuard<T> [MustUse]structStack-allocated shared read guard for RwLock<T>.
RwLock<T>classA data-owning reader-writer lock inspired by Rust's std::sync::RwLock<T>. Multiple readers may hold ReadGuard<T> concurrently, while writers acquire exclusive access via WriteGuard<T>.
TaskScope [MustUse]classA structured concurrency nursery inspired by Rust's std::thread::scope and tokio::task::JoinSet. Guarantees that every child task spawned inside the scope either completes or is cooperatively cancelled and awaited before leaving the await using block—preventing orphaned background tasks and unobserved exceptions. Compiled with .NET 11 runtime async (runtime-async=on) on net11.0.
TypedChannelclassFactory for Rust-style split-capability typed channels (ChannelSender<T> and ChannelReceiver<T>) backed by Channel<T>.
WriteGuard<T> [MustUse]structStack-allocated exclusive write guard for RwLock<T>.

Ferrous.EntityFrameworkCore

TypeKindSummary
AutoNewtypeValueConverter<TNewtype, TUnderlying>classParameterless EF Core ValueConverter<TModel, TProvider> used by FerrousNewtypeConventionExtensions.UseFerrousNewtypes(ModelConfigurationBuilder, Assembly[]) to automatically map [Newtype(typeof(TUnderlying))] structs to their underlying column type.
FerrousModelConfigurationExtensionsclassExtension methods for registering Ferrous value converters in EF Core DbContext models.
FerrousNewtypeConventionExtensionsclassConvention extensions for zero-boilerplate [Newtype] discovery in EF Core DbContext models.
FerrousQueryableExtensionsclassResult<T, TError>- and Option<T>-returning async EF Core query helpers that eliminate null returns and InvalidOperationException throws.
NewtypeValueConverter<TNewtype, TUnderlying>classReflection-free EF Core ValueConverter<TModel, TProvider> for Ferrous [Newtype] wrapper structs.
NonEmptyStringConverterclassEF Core ValueConverter<TModel, TProvider> that persists NonEmptyString as a database string column and re-validates on materialization.
NonZeroConverter<T>classEF Core ValueConverter<TModel, TProvider> that persists NonZero<T> as its underlying numeric column and re-validates on materialization.

Ferrous.Guard

TypeKindSummary
ScopeGuard [MustUse]structA stack-allocated scope guard that executes a callback when disposed (exiting a using scope), unless dismissed beforehand. Equivalent to Rust's Drop / defer pattern.
ScopeGuard<TState> [MustUse]structA stack-allocated scope guard carrying explicit TState to avoid closure allocations.

Ferrous.Ownership

TypeKindSummary
BorrowAnalyzerclassRoslyn diagnostic analyzer enforcing Rust-inspired borrowing exclusivity (FE0202) and lexical borrow escape prevention (FE0203) for [Borrow], [BorrowMut], and ref/in parameters.
OwnershipAnalyzerclassFlow-sensitive Roslyn diagnostic analyzer built on Roslyn's ControlFlowGraph that enforces affine move semantics for [Consuming] parameters and [ConsumesSelf] methods.

Ferrous.Pedantic

TypeKindSummary
ClippyParityAnalyzerclassClippy-parity pedantic Roslyn diagnostic analyzer (FE0423–FE0427): oversized [DiscriminatedUnion] structs, NotImplementedException stubs, needless collection materializations, stray Console.Write* in libraries, and unnecessary .Unwrap() inside IsOk/IsSome guards.
ImmutabilityAnalyzerclassRoslyn diagnostic analyzer (FE0418) enforcing deep immutability on parameters, fields, and properties annotated with [Immutable] (approximating Rust's &T).
IndexingSafetyAnalyzerclassRoslyn diagnostic analyzer (FE0420, inspired by clippy::indexing_slicing) that flags unchecked array, list, span, and string indexing inside [NoThrow] or Result-returning methods unless bounds are proven by an enclosing loop or guard.
InterproceduralContractAnalyzerclassInter-procedural Roslyn diagnostic analyzer (FE0421–FE0422) that summarizes same-compilation helper methods via operation blocks and flags transitive throws inside [NoThrow]/Result methods and transitive heap allocations inside [NoAlloc] methods.
PedanticAnalyzerclassClippy-style pedantic Roslyn diagnostic analyzer enforcing Rust-inspired safety and zero-allocation lints (FE0400–FE0409).
PedanticCodeFixProviderclassRoslyn code fix provider for Ferrous.Pedantic diagnostics: FE0400: Scaffold missing enum switch expression arms. FE0401: Replace .Unwrap()/.Expect(...) with .UnwrapOr(default). FE0403: Convert capturing ScopeGuard.Defer(() => ...) to zero-allocation ScopeGuard.Defer(state, static s => ...).
PedanticSafetyAnalyzerclassRoslyn diagnostic analyzer enforcing Rust-inspired panic-free, zero-allocation, numeric, equality, and unsafe safety rules (FE0410–FE0417).
ResourceLeakAnalyzerclassCFG-based Roslyn analyzer (FE0419) detecting un-disposed ScopeGuard or locally created IDisposable handles that leak on normal exit or early-return paths.

Ferrous.Results

TypeKindSummary
CheckedMathclassZero-allocation Rust-inspired checked and saturating integer arithmetic helpers. Checked operations return Option<T>.None on overflow or division by zero; saturating operations clamp to IMinMaxValue<TSelf>.MinValue or IMinMaxValue<TSelf>.MaxValue.
ContextErrorclassA chained, anyhow-style error carrying a human-readable context message and an optional inner cause chain for structured error propagation across layers.
ErrorContextExtensionsclassanyhow::Context-inspired extension methods for attaching contextual error messages to Result<T, TError> values with zero allocation on the Ok path.
IOptionValueinterfaceNon-generic inspection contract implemented by Option<T> so framework integrations (such as ASP.NET Core endpoint filters) can inspect boxed options without reflection or trimming warnings.
IResultValueinterfaceNon-generic inspection contract implemented by Result<T, TError> so framework integrations (such as ASP.NET Core endpoint filters) can inspect boxed results without reflection or trimming warnings.
NonEmptyList<T>classAn immutable, read-only list guaranteed to contain at least one element (Head).
NonEmptyString [NoDefault]structA zero-allocation wrapper guaranteeing a non-null, non-whitespace string.
NonZero<T> [NoDefault]structA zero-allocation wrapper guaranteeing a non-zero numeric value (Rust's std::num::NonZero<T>).
OptionclassConvenience factory methods for creating Option<T> instances with type inference.
Option<T> [MustUse]structRepresents an optional value: every Option<T> is either Some containing a value, or None containing no value. Equivalent to Rust's Option<T>.
OptionJsonConverter<T>classNativeAOT-compatible JsonConverter<T> for Option<T>. Serializes Some(v) directly as v and None as JSON null.
ResultclassConvenience factory methods for creating Result<T, TError> instances.
Result<T, TError> [MustUse]structRepresents either success (Ok) or failure (Err) without heap allocations or exceptions. Equivalent to Rust's Result<T, E>.
ResultExtensionsclassAsync and LINQ query comprehension combinators for Result<T, TError> and Option<T>.
ResultJsonConverter<T, TError>classNativeAOT-compatible JsonConverter<T> for Result<T, TError>. Serializes Ok(v) as {"ok":v} and Err(e) as {"err":e} (Rust serde externally tagged format).
SafeCollectionExtensionsclassRust-inspired bounds-safe .Get(...) indexing extensions returning Option<T> instead of throwing IndexOutOfRangeException or KeyNotFoundException.

Ferrous.States

TypeKindSummary
TypestateAnalyzerclassRoslyn diagnostic analyzer that enforces linear typestate protocols declared with [Typestate] and [ConsumesSelf].
TypestateCodeFixProviderclassRoslyn code fix provider for TypestateAnalyzer.MissingConsumesSelfDiagnosticId (FE0301) that annotates the typestate transition method with [ConsumesSelf].

Ferrous.Testing

TypeKindSummary
AllocAssertclassRuntime zero-allocation and allocation-budget assertions backed by GC.GetAllocatedBytesForCurrentThread. Acts as a unit-test companion to compile-time [NoAlloc] enforcement.
CompileAssertclassIn-memory Roslyn compile-pass and compile-fail test harness inspired by Rust's trybuild. Verifies that C# snippets targeting [Typestate], [Consuming], [BorrowMut], [NoDefault], [Closed], and other Ferrous contracts either compile cleanly or fail with specific expected diagnostic IDs.
CompileAssertOptionsclassConfiguration options for CompileAssert in-memory compilations.
CompileResultclassCaptures the diagnostics and generated source texts produced by CompileAssert.
FerrousAssertionExceptionclassException thrown when a Ferrous test assertion fails. Framework-agnostic so it works seamlessly with xUnit, NUnit, MSTest, and TUnit.
GenclassBuilt-in Gen<T> factories for primitives, collections, and Ferrous types (NonEmptyString, NonZero<T>, Option<T>, Result<T, TError>).
Gen<T>classA composable, deterministic value generator with optional shrinking for property-based testing with PropAssert (inspired by Rust's proptest).
PropAssertclassFramework-agnostic property-based testing assertions with deterministic seeds and automatic counterexample shrinking (inspired by Rust's proptest).
ResultAssertionsclassFramework-agnostic assertion extensions for Result<T, TError> and Option<T>. Compatible with xUnit, NUnit, MSTest, and TUnit.

Ferrous.Tool.Commands

TypeKindSummary
MigrateCommandclassImplements dotnet fe migrate [path] [--report | --apply] for progressive C# → Ferrous migration. Scans C# codebases for throwing methods, nullable-returning methods, raw lock blocks, mutable static fields, and async void methods, and optionally applies safe mechanical upgrades.

Ferrous.Tool

TypeKindSummary
FerrousCliclassEntrypoint and command dispatcher for the dotnet fe CLI tool.

Ferrous.Unions

TypeKindSummary
DiscriminatedUnionGeneratorclassIncremental Roslyn source generator that turns a [DiscriminatedUnion] partial struct with static partial variant factory declarations into a zero-boxing tagged union with structural equality, TryGet* accessors, exhaustive Match, and automatic System.Runtime.CompilerServices.UnionAttribute light-up when available.
InstrumentGeneratorclassIncremental Roslyn source generator for [Instrument] partial methods, emitting zero-reflection System.Diagnostics.ActivitySource spans inspired by Rust's #[tracing::instrument].
NewtypeGeneratorclassIncremental Roslyn source generator that turns a [Newtype(typeof(T))] readonly partial struct into a zero-overhead strongly typed wrapper implementing IEquatable<T>, IComparable<T>, IParsable<T>, ISpanFormattable, [NoDefault], and a NativeAOT-safe System.Text.Json converter.