Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
308 changes: 296 additions & 12 deletions Cortex.sln

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@
- **Cortex.Mediator.Behaviors.Transactional:** implementation of the Transactional Behaviors for Commands
[![NuGet Version](https://img.shields.io/nuget/v/Cortex.Mediator.Behaviors.Transactional?label=Cortex.Mediator.Behaviors.Transactional)](https://www.nuget.org/packages/Cortex.Mediator.Behaviors.Transactional)

- **Cortex.Mediator.SourceGenerator:** optional Roslyn source generator that eliminates runtime reflection by generating compile-time dispatch with switch-based routing and explicit DI registrations.
[![NuGet Version](https://img.shields.io/nuget/v/Cortex.Mediator.SourceGenerator?label=Cortex.Mediator.SourceGenerator)](https://www.nuget.org/packages/Cortex.Mediator.SourceGenerator)

- **Cortex.Vectors:** is a High‑performance vector types—Dense, Sparse, and Bit—for AI.
[![NuGet Version](https://img.shields.io/nuget/v/Cortex.Vectors?label=Cortex.Vectors)](https://www.nuget.org/packages/Cortex.Vectors)

Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
20 changes: 20 additions & 0 deletions src/Cortex.Mediator.SourceGenerator/Assets/license.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2026 Buildersoft

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>12</LangVersion>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<IsRoslynComponent>true</IsRoslynComponent>
<IncludeBuildOutput>false</IncludeBuildOutput>
<DevelopmentDependency>true</DevelopmentDependency>
<SuppressDependenciesWhenPacking>true</SuppressDependenciesWhenPacking>

<AssemblyVersion>1.0.0</AssemblyVersion>
<FileVersion>1.0.0</FileVersion>
<Product>Buildersoft Cortex Framework</Product>
<Company>Buildersoft</Company>
<Authors>Buildersoft,EnesHoxha</Authors>
<Copyright>Copyright © Buildersoft 2026</Copyright>

<Description>
Roslyn source generator for Cortex.Mediator that eliminates runtime reflection by generating compile-time dispatch. Produces a GeneratedMediator with switch-based routing and explicit DI registrations, enabling NativeAOT compatibility and faster cold starts.
</Description>

<RepositoryUrl>https://github.com/buildersoftio/cortex</RepositoryUrl>
<PackageTags>cortex vortex mediator eda cqrs source-generator</PackageTags>

<Version>1.0.0</Version>
<PackageLicenseFile>license.md</PackageLicenseFile>
<PackageIcon>andyX.png</PackageIcon>
<PackageId>Cortex.Mediator.SourceGenerator</PackageId>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<IsPublishable>True</IsPublishable>
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
<RepositoryType></RepositoryType>
<PackageReleaseNotes>Just as the Cortex in our brains handles complex processing efficiently, Cortex Data Framework brings brainpower to your data management!</PackageReleaseNotes>
<PackageProjectUrl>https://buildersoft.io/</PackageProjectUrl>
<Title>Cortex Mediator Source Generator</Title>
<PackageReadmeFile>README.md</PackageReadmeFile>

</PropertyGroup>

<ItemGroup>
<None Remove="README.md" />
</ItemGroup>

<ItemGroup>
<Content Include="README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<None Include="Assets\andyX.png">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
<None Include="Assets\license.md">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
</ItemGroup>

<ItemGroup>
<Folder Include="Assets\" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.3.1" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true"
PackagePath="analyzers/dotnet/cs" Visible="false" />
</ItemGroup>

</Project>
247 changes: 247 additions & 0 deletions src/Cortex.Mediator.SourceGenerator/CortexMediatorGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,247 @@
using Cortex.Mediator.SourceGenerator.Diagnostics;
using Cortex.Mediator.SourceGenerator.Discovery;
using Cortex.Mediator.SourceGenerator.Emitters;
using Cortex.Mediator.SourceGenerator.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;

namespace Cortex.Mediator.SourceGenerator
{
[Generator(LanguageNames.CSharp)]
public sealed class CortexMediatorGenerator : IIncrementalGenerator
{
private const string AttributeFullName = "Cortex.Mediator.SourceGeneration.CortexMediatorGenerationAttribute";

public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Step 1: Emit the marker attribute so consumers only need the NuGet package
context.RegisterPostInitializationOutput(static ctx =>
{
ctx.AddSource("CortexMediatorGenerationAttribute.g.cs", @"// <auto-generated/>
namespace Cortex.Mediator.SourceGeneration
{
/// <summary>
/// Apply this attribute at assembly level to enable the Cortex Mediator source generator.
/// </summary>
[System.AttributeUsage(System.AttributeTargets.Assembly, AllowMultiple = false)]
internal sealed class CortexMediatorGenerationAttribute : System.Attribute
{
}
}
");
});

// Step 2: Check if the assembly attribute is present (opt-in gate)
var hasAttribute = context.SyntaxProvider
.ForAttributeWithMetadataName(
AttributeFullName,
predicate: static (node, _) => node is CompilationUnitSyntax,
transform: static (ctx, _) => true)
.Collect()
.Select(static (items, _) => items.Length > 0);

// Step 3: Discover handlers from class declarations
var handlerRegistrations = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: static (node, _) => node is ClassDeclarationSyntax cds && cds.BaseList != null,
transform: static (ctx, ct) => GetHandlerRegistrations(ctx, ct))
.Where(static r => !r.IsEmpty)
.SelectMany(static (r, _) => r);

var collectedHandlers = handlerRegistrations.Collect();

// Step 4: Discover message types for diagnostics
var messageRegistrations = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: static (node, _) => node is ClassDeclarationSyntax cds && cds.BaseList != null,
transform: static (ctx, ct) => GetMessageRegistrations(ctx, ct))
.Where(static r => !r.IsEmpty)
.SelectMany(static (r, _) => r);

var collectedMessages = messageRegistrations.Collect();

// Step 5: Combine everything and generate
var combined = collectedHandlers.Combine(collectedMessages).Combine(hasAttribute);

context.RegisterSourceOutput(combined, static (spc, input) =>
{
var ((handlers, messages), isEnabled) = input;

if (!isEnabled)
return;

// Report diagnostics
ReportDiagnostics(spc, handlers, messages);

// Emit GeneratedMediator
var mediatorSource = GeneratedMediatorEmitter.Emit(handlers);
spc.AddSource("GeneratedMediator.g.cs", mediatorSource);

// Emit GeneratedServiceCollectionExtensions
var diSource = GeneratedDIEmitter.Emit(handlers);
spc.AddSource("GeneratedServiceCollectionExtensions.g.cs", diSource);
});
}

private static ImmutableArray<HandlerRegistration> GetHandlerRegistrations(
GeneratorSyntaxContext context,
CancellationToken cancellationToken)
{
var classDeclaration = (ClassDeclarationSyntax)context.Node;
var symbol = context.SemanticModel.GetDeclaredSymbol(classDeclaration, cancellationToken);

if (symbol is not INamedTypeSymbol namedType)
return ImmutableArray<HandlerRegistration>.Empty;

return HandlerDiscovery.FindHandlers(namedType);
}

private static ImmutableArray<MessageRegistration> GetMessageRegistrations(
GeneratorSyntaxContext context,
CancellationToken cancellationToken)
{
var classDeclaration = (ClassDeclarationSyntax)context.Node;
var symbol = context.SemanticModel.GetDeclaredSymbol(classDeclaration, cancellationToken);

if (symbol is not INamedTypeSymbol namedType)
return ImmutableArray<MessageRegistration>.Empty;

return MessageDiscovery.FindMessages(namedType);
}

private static void ReportDiagnostics(
SourceProductionContext spc,
ImmutableArray<HandlerRegistration> handlers,
ImmutableArray<MessageRegistration> messages)
{
var handledCommands = new HashSet<string>(
handlers.Where(h => h.Kind == InterfaceKind.ReturningCommand)
.Select(h => h.MessageFullyQualifiedName));

var handledVoidCommands = new HashSet<string>(
handlers.Where(h => h.Kind == InterfaceKind.VoidCommand)
.Select(h => h.MessageFullyQualifiedName));

var handledQueries = new HashSet<string>(
handlers.Where(h => h.Kind == InterfaceKind.Query)
.Select(h => h.MessageFullyQualifiedName));

var handledStreamQueries = new HashSet<string>(
handlers.Where(h => h.Kind == InterfaceKind.StreamQuery)
.Select(h => h.MessageFullyQualifiedName));

var handledNotifications = new HashSet<string>(
handlers.Where(h => h.Kind == InterfaceKind.Notification)
.Select(h => h.MessageFullyQualifiedName));

// Check for unhandled messages
foreach (var msg in messages)
{
switch (msg.Kind)
{
case InterfaceKind.ReturningCommand:
if (!handledCommands.Contains(msg.MessageFullyQualifiedName))
{
spc.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.CommandHasNoHandler,
msg.Location,
msg.MessageFullyQualifiedName));
}
break;

case InterfaceKind.VoidCommand:
if (!handledVoidCommands.Contains(msg.MessageFullyQualifiedName))
{
spc.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.CommandHasNoHandler,
msg.Location,
msg.MessageFullyQualifiedName));
}
break;

case InterfaceKind.Query:
if (!handledQueries.Contains(msg.MessageFullyQualifiedName))
{
spc.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.QueryHasNoHandler,
msg.Location,
msg.MessageFullyQualifiedName));
}
break;

case InterfaceKind.StreamQuery:
if (!handledStreamQueries.Contains(msg.MessageFullyQualifiedName))
{
spc.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.StreamQueryHasNoHandler,
msg.Location,
msg.MessageFullyQualifiedName));
}
break;

case InterfaceKind.Notification:
if (!handledNotifications.Contains(msg.MessageFullyQualifiedName))
{
spc.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.NotificationHasNoHandler,
msg.Location,
msg.MessageFullyQualifiedName));
}
break;
}
}

// Check for duplicate command handlers
var commandHandlerGroups = handlers
.Where(h => h.Kind == InterfaceKind.ReturningCommand)
.GroupBy(h => h.MessageFullyQualifiedName)
.Where(g => g.Count() > 1);

foreach (var group in commandHandlerGroups)
{
var handlerNames = string.Join(", ", group.Select(h => h.HandlerFullyQualifiedName));
spc.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.MultipleHandlersForCommand,
Location.None,
group.Key,
handlerNames));
}

// Check for duplicate void command handlers
var voidCommandHandlerGroups = handlers
.Where(h => h.Kind == InterfaceKind.VoidCommand)
.GroupBy(h => h.MessageFullyQualifiedName)
.Where(g => g.Count() > 1);

foreach (var group in voidCommandHandlerGroups)
{
var handlerNames = string.Join(", ", group.Select(h => h.HandlerFullyQualifiedName));
spc.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.MultipleHandlersForCommand,
Location.None,
group.Key,
handlerNames));
}

// Check for duplicate query handlers
var queryHandlerGroups = handlers
.Where(h => h.Kind == InterfaceKind.Query)
.GroupBy(h => h.MessageFullyQualifiedName)
.Where(g => g.Count() > 1);

foreach (var group in queryHandlerGroups)
{
var handlerNames = string.Join(", ", group.Select(h => h.HandlerFullyQualifiedName));
spc.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.MultipleHandlersForQuery,
Location.None,
group.Key,
handlerNames));
}
}
}
}
Loading