Ferrous API Reference
API reference generated by dotnet fe doc — 93 public type(s).
Ferrous.Annotations
| Type | Kind | Summary |
|---|---|---|
MustUseAnalyzer | class | Roslyn 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. |
MustUseCodeFixProvider | class | Roslyn code fix provider for MustUseAnalyzer.DiagnosticId (FE0001) that inserts an explicit discard (_ = ...). |
Ferrous.AspNetCore
| Type | Kind | Summary |
|---|---|---|
FerrousEndpointBuilderExtensions | class | Extension methods for registering FerrousResultEndpointFilter on Minimal API endpoints and route groups. |
FerrousResultEndpointFilter | class | Minimal 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). |
ResultHttpExtensions | class | Extension methods that map Result<T, TError> and Option<T> values to ASP.NET Core Minimal API IResult responses (including RFC 7807 ProblemDetails). |
Ferrous
| Type | Kind | Summary |
|---|---|---|
BorrowAttribute | class | Marks a parameter as taking a shared (read-only) borrow of the passed argument. Enforced by Ferrous.Ownership (FE0202 exclusivity and FE0203 escape checks). |
BorrowMutAttribute | class | Marks a parameter as taking an exclusive mutable borrow of the passed argument. Enforced by Ferrous.Ownership (FE0202 aliasing-XOR-mutability and FE0203 escape checks). |
CheckedAttribute | class | Marks a method, constructor, property, or type as requiring explicit checked or saturating integer arithmetic (enforced by Ferrous.Pedantic FE0414). |
ClosedAttribute | class | Marks 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). |
ConsumesSelfAttribute | class | Marks an instance method as consuming this (the receiver) during a state transition. Used by Ferrous.Ownership and Ferrous.States to enforce linear typestate protocols. |
ConsumingAttribute | class | Marks 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. |
DiscriminatedUnionAttribute | class | Marks 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. |
ErrorMessageAttribute | class | Annotates 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. |
ExhaustiveAttribute | class | Marks 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). |
ImmutableAttribute | class | Marks 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). |
InstrumentAttribute | class | Marks 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. |
MustUseAttribute | class | Indicates that a return value or an instance of the annotated type should not be silently ignored. Equivalent to Rust's #[must_use] attribute. |
NewtypeAttribute | class | Marks 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. |
NoAllocAttribute | class | Marks 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. |
NoDefaultAttribute | class | Marks a struct as forbidding default/uninitialized construction via default, parameterless new(), or uninitialized fields/arrays (enforced by Ferrous.Pedantic FE0404). |
NoThrowAttribute | class | Marks a method, constructor, or property as non-throwing (enforced by Ferrous.Pedantic FE0402). |
ThreadConfinedAttribute | class | Marks 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). |
TypestateAttribute | class | Marks a type as a state in a linear typestate protocol enforced by Ferrous.States and Ferrous.Ownership. |
Ferrous.CodeFixes
| Type | Kind | Summary |
|---|---|---|
FerrousMigrationRefactoringProvider | class | On-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 |
SafetyCodeFixProvider | class | Roslyn IDE quick-fix provider for Ferrous safety and concurrency rules (FE0407, FE0409, FE0414, FE0415, FE0417, FE0420, FE0501). |
Ferrous.Concurrency.Analyzers
| Type | Kind | Summary |
|---|---|---|
ConcurrencyAnalyzer | class | Roslyn analyzer enforcing Rust-inspired concurrency safety: FE0500: Thread-confined (!Send) value captured across a thread boundary. FE0501: Unsynchronized mutable static field (static mut). |
DetachedTaskAnalyzer | class | Roslyn diagnostic analyzer (FE0503) that flags detached Task.Run(...) calls inside methods that already have a TaskScope in scope, encouraging structured concurrency via scope.Spawn(...). |
LockAcrossAwaitAnalyzer | class | CFG-based Roslyn analyzer (FE0502) flagging SemaphoreSlim, ReaderWriterLockSlim, or Monitor locks held across await points (clippy::await_holding_lock). |
Ferrous.Concurrency
| Type | Kind | Summary |
|---|---|---|
AsyncMutex<T> | class | An 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] | struct | A RAII guard providing exclusive access to the value owned by an AsyncMutex<T>. |
AsyncReadGuard<T> [MustUse] | struct | Async shared read guard for AsyncRwLock<T>. |
AsyncRwLock<T> | class | An 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] | struct | Async exclusive write guard for AsyncRwLock<T>. |
ChannelReceiver<T> | class | Receive-only handle for a TypedChannel. |
ChannelSender<T> | class | Send-only handle for a TypedChannel. Calling Complete consumes the sender handle ([ConsumesSelf]) so Ferrous.Ownership prevents sending after close. |
LazyLock<T> | class | A 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> | class | A 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] | struct | A 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> | class | A 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] | struct | Stack-allocated shared read guard for RwLock<T>. |
RwLock<T> | class | A 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] | class | A 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. |
TypedChannel | class | Factory for Rust-style split-capability typed channels (ChannelSender<T> and ChannelReceiver<T>) backed by Channel<T>. |
WriteGuard<T> [MustUse] | struct | Stack-allocated exclusive write guard for RwLock<T>. |
Ferrous.EntityFrameworkCore
| Type | Kind | Summary |
|---|---|---|
FerrousModelConfigurationExtensions | class | Extension methods for registering Ferrous value converters in EF Core DbContext models. |
FerrousQueryableExtensions | class | Result<T, TError>- and Option<T>-returning async EF Core query helpers that eliminate null returns and InvalidOperationException throws. |
NewtypeValueConverter<TNewtype, TUnderlying> | class | Reflection-free EF Core ValueConverter<TModel, TProvider> for Ferrous [Newtype] wrapper structs. |
NonEmptyStringConverter | class | EF Core ValueConverter<TModel, TProvider> that persists NonEmptyString as a database string column and re-validates on materialization. |
NonZeroConverter<T> | class | EF Core ValueConverter<TModel, TProvider> that persists NonZero<T> as its underlying numeric column and re-validates on materialization. |
Ferrous.Guard
| Type | Kind | Summary |
|---|---|---|
ScopeGuard [MustUse] | struct | A 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] | struct | A stack-allocated scope guard carrying explicit TState to avoid closure allocations. |
Ferrous.Ownership
| Type | Kind | Summary |
|---|---|---|
BorrowAnalyzer | class | Roslyn diagnostic analyzer enforcing Rust-inspired borrowing exclusivity (FE0202) and lexical borrow escape prevention (FE0203) for [Borrow], [BorrowMut], and ref/in parameters. |
OwnershipAnalyzer | class | Flow-sensitive Roslyn diagnostic analyzer built on Roslyn's ControlFlowGraph that enforces affine move semantics for [Consuming] parameters and [ConsumesSelf] methods. |
Ferrous.Pedantic
| Type | Kind | Summary |
|---|---|---|
ClippyParityAnalyzer | class | Clippy-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. |
ImmutabilityAnalyzer | class | Roslyn diagnostic analyzer (FE0418) enforcing deep immutability on parameters, fields, and properties annotated with [Immutable] (approximating Rust's &T). |
IndexingSafetyAnalyzer | class | Roslyn 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. |
InterproceduralContractAnalyzer | class | Inter-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. |
PedanticAnalyzer | class | Clippy-style pedantic Roslyn diagnostic analyzer enforcing Rust-inspired safety and zero-allocation lints (FE0400–FE0409). |
PedanticCodeFixProvider | class | Roslyn 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 => ...). |
PedanticSafetyAnalyzer | class | Roslyn diagnostic analyzer enforcing Rust-inspired panic-free, zero-allocation, numeric, equality, and unsafe safety rules (FE0410–FE0417). |
ResourceLeakAnalyzer | class | CFG-based Roslyn analyzer (FE0419) detecting un-disposed ScopeGuard or locally created IDisposable handles that leak on normal exit or early-return paths. |
Ferrous.Results
| Type | Kind | Summary |
|---|---|---|
CheckedMath | class | Zero-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. |
ContextError | class | A chained, anyhow-style error carrying a human-readable context message and an optional inner cause chain for structured error propagation across layers. |
ErrorContextExtensions | class | anyhow::Context-inspired extension methods for attaching contextual error messages to Result<T, TError> values with zero allocation on the Ok path. |
IOptionValue | interface | Non-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. |
IResultValue | interface | Non-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> | class | An immutable, read-only list guaranteed to contain at least one element (Head). |
NonEmptyString [NoDefault] | struct | A zero-allocation wrapper guaranteeing a non-null, non-whitespace string. |
NonZero<T> [NoDefault] | struct | A zero-allocation wrapper guaranteeing a non-zero numeric value (Rust's std::num::NonZero<T>). |
Option | class | Convenience factory methods for creating Option<T> instances with type inference. |
Option<T> [MustUse] | struct | Represents 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> | class | NativeAOT-compatible JsonConverter<T> for Option<T>. Serializes Some(v) directly as v and None as JSON null. |
Result | class | Convenience factory methods for creating Result<T, TError> instances. |
Result<T, TError> [MustUse] | struct | Represents either success (Ok) or failure (Err) without heap allocations or exceptions. Equivalent to Rust's Result<T, E>. |
ResultExtensions | class | Async and LINQ query comprehension combinators for Result<T, TError> and Option<T>. |
ResultJsonConverter<T, TError> | class | NativeAOT-compatible JsonConverter<T> for Result<T, TError>. Serializes Ok(v) as {"ok":v} and Err(e) as {"err":e} (Rust serde externally tagged format). |
SafeCollectionExtensions | class | Rust-inspired bounds-safe .Get(...) indexing extensions returning Option<T> instead of throwing IndexOutOfRangeException or KeyNotFoundException. |
Ferrous.States
| Type | Kind | Summary |
|---|---|---|
TypestateAnalyzer | class | Roslyn diagnostic analyzer that enforces linear typestate protocols declared with [Typestate] and [ConsumesSelf]. |
TypestateCodeFixProvider | class | Roslyn code fix provider for TypestateAnalyzer.MissingConsumesSelfDiagnosticId (FE0301) that annotates the typestate transition method with [ConsumesSelf]. |
Ferrous.Testing
| Type | Kind | Summary |
|---|---|---|
AllocAssert | class | Runtime zero-allocation and allocation-budget assertions backed by GC.GetAllocatedBytesForCurrentThread. Acts as a unit-test companion to compile-time [NoAlloc] enforcement. |
CompileAssert | class | In-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. |
CompileAssertOptions | class | Configuration options for CompileAssert in-memory compilations. |
CompileResult | class | Captures the diagnostics and generated source texts produced by CompileAssert. |
FerrousAssertionException | class | Exception thrown when a Ferrous test assertion fails. Framework-agnostic so it works seamlessly with xUnit, NUnit, MSTest, and TUnit. |
Gen | class | Built-in Gen<T> factories for primitives, collections, and Ferrous types (NonEmptyString, NonZero<T>, Option<T>, Result<T, TError>). |
Gen<T> | class | A composable, deterministic value generator with optional shrinking for property-based testing with PropAssert (inspired by Rust's proptest). |
PropAssert | class | Framework-agnostic property-based testing assertions with deterministic seeds and automatic counterexample shrinking (inspired by Rust's proptest). |
ResultAssertions | class | Framework-agnostic assertion extensions for Result<T, TError> and Option<T>. Compatible with xUnit, NUnit, MSTest, and TUnit. |
Ferrous.Tool.Commands
| Type | Kind | Summary |
|---|---|---|
MigrateCommand | class | Implements 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
| Type | Kind | Summary |
|---|---|---|
FerrousCli | class | Entrypoint and command dispatcher for the dotnet fe CLI tool. |
Ferrous.Unions
| Type | Kind | Summary |
|---|---|---|
DiscriminatedUnionGenerator | class | Incremental 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. |
InstrumentGenerator | class | Incremental Roslyn source generator for [Instrument] partial methods, emitting zero-reflection System.Diagnostics.ActivitySource spans inspired by Rust's #[tracing::instrument]. |
NewtypeGenerator | class | Incremental 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. |