Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ public void Generate(

var contextOnlyTypes = syntaxInfos.OfType<ContextOnlyMessageInfo>().OrderBy(c => c.OrderByKey).ToList();

if (handlers.Count == 0 && sagas.Count == 0 && contextOnlyTypes.Count == 0)
if (handlers.Count == 0
&& sagas.Count == 0
&& contextOnlyTypes.Count == 0
&& !syntaxInfos.Any(static info => info is MessageDeclarationsInfo { Declarations.Count: > 0 }))
{
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public bool TryHandle(
// Capture declaration metadata (doc + span) cross-file from the resolved symbol. Metadata-only types
// (declared in another assembly) carry no source declaration, so there is nothing to contribute. This
// is stale only in the IDE's incremental cache; every real compiler invocation runs fresh.
var declaredMessageType = messageType.ToDeclaredTypeInfo(cancellationToken);
var declaredMessageType = messageType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken);
if (declaredMessageType is null)
{
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,8 @@
namespace Mocha.Analyzers.Inspectors;

/// <summary>
/// Inspects dispatch call sites (<c>SendAsync</c>, <c>PublishAsync</c>, <c>RequestAsync</c>,
/// <c>QueryAsync</c>, etc.) on <c>IMessageBus</c>, <c>ISender</c>, and <c>IPublisher</c>
/// to extract the compile-time message and response types being dispatched.
/// Extracts message and response types from message bus and mediator dispatch calls.
/// </summary>
/// <remarks>
/// <para>
/// The extracted types feed downstream generators and analyzers that verify serializer
/// registrations (MO0018) and handler existence (MO0020).
/// </para>
/// <para>
/// Type extraction varies by method shape: for most generic methods the message type comes
/// from the type argument <c>T</c>, but for <c>RequestAsync&lt;TResponse&gt;</c> the type
/// argument is the <em>response</em> type - the message type is inferred from the first
/// argument's compile-time type instead. Non-generic overloads (e.g.
/// <c>RequestAsync(object, …)</c>) also fall back to argument-expression analysis.
/// </para>
/// </remarks>
public sealed class CallSiteMessageTypeInspector : ISyntaxInspector
{
/// <inheritdoc />
Expand Down Expand Up @@ -62,7 +47,6 @@ public bool TryHandle(
return false;
}

// Try IMessageBus
if (knownSymbols.IMessageBus is not null
&& SymbolEqualityComparer.Default.Equals(receiverType, knownSymbols.IMessageBus))
{
Expand All @@ -80,7 +64,7 @@ public bool TryHandle(
if (knownSymbols.IPublisher is not null
&& SymbolEqualityComparer.Default.Equals(receiverType, knownSymbols.IPublisher))
{
return TryHandlePublisher(methodSymbol, invocation, cancellationToken, out syntaxInfo);
return TryHandlePublisher(methodSymbol, invocation, semanticModel, cancellationToken, out syntaxInfo);
}

return false;
Expand Down Expand Up @@ -134,14 +118,13 @@ private static bool TryHandleMessageBus(
argTypeName,
kind,
argLocation,
DeclaredMessageType: argType.ToDeclaredTypeInfo(cancellationToken));
DeclaredMessageType: argType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken));
return true;
}

return false;
}

// All other IMessageBus methods are generic - extract T from type arguments.
if (methodSymbol.TypeArguments.Length == 0)
{
return false;
Expand Down Expand Up @@ -172,15 +155,17 @@ private static bool TryHandleMessageBus(
responseTypeName = methodSymbol
.TypeArguments[0]
.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
declaredResponseType = methodSymbol.TypeArguments[0].ToDeclaredTypeInfo(cancellationToken);
declaredResponseType = methodSymbol.TypeArguments[0].ToDeclaredTypeInfo(
semanticModel.Compilation,
cancellationToken);
}

syntaxInfo = new CallSiteMessageTypeInfo(
requestTypeName,
kind,
location,
responseTypeName,
firstArgType.ToDeclaredTypeInfo(cancellationToken),
firstArgType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken),
declaredResponseType);
return true;
}
Expand All @@ -199,7 +184,7 @@ private static bool TryHandleMessageBus(
typeName,
kind,
locationInfo,
DeclaredMessageType: messageType.ToDeclaredTypeInfo(cancellationToken));
DeclaredMessageType: messageType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken));
return true;
}

Expand Down Expand Up @@ -254,13 +239,14 @@ private static bool TryHandleSender(
typeName,
kind,
locationInfo,
DeclaredMessageType: messageType.ToDeclaredTypeInfo(cancellationToken));
DeclaredMessageType: messageType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken));
return true;
}

private static bool TryHandlePublisher(
IMethodSymbol methodSymbol,
InvocationExpressionSyntax invocation,
SemanticModel semanticModel,
CancellationToken cancellationToken,
out SyntaxInfo? syntaxInfo)
{
Expand Down Expand Up @@ -289,7 +275,7 @@ private static bool TryHandlePublisher(
typeName,
CallSiteKind.MediatorPublish,
locationInfo,
DeclaredMessageType: messageType.ToDeclaredTypeInfo(cancellationToken));
DeclaredMessageType: messageType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken));
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ public bool TryHandle(
// their resolved symbols, so this handler is one of several discovery sources merged by type name.
// Metadata-only types (declared in another assembly) yield null. This is stale only in the IDE's
// incremental cache; every real compiler invocation runs fresh.
var declaredMessageType = messageSymbol.ToDeclaredTypeInfo(cancellationToken);
var declaredResponseType = responseType.ToDeclaredTypeInfo(cancellationToken);
var declaredMessageType = messageSymbol.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken);
var declaredResponseType = responseType.ToDeclaredTypeInfo(semanticModel.Compilation, cancellationToken);

syntaxInfo = new MessagingHandlerInfo(
handlerFullName,
Expand Down
24 changes: 16 additions & 8 deletions src/Mocha/src/Mocha.Analyzers/MessagingGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ private static bool IsJsonSerializableAttributeCandidate(SyntaxNode node)
CreateJsonSerializableTypeInfo(
serializableType,
attribute.GetLocation().ToDeclarationLocationInfo(),
semanticModel.Compilation,
cancellationToken));
}

Expand Down Expand Up @@ -458,9 +459,14 @@ private static MessageDeclarationsInfo BuildMessageDeclarations(
// Sources B and C: dispatch call sites and explicit AddMessage registrations.
foreach (var info in callSiteInfos)
{
if (info is CallSiteMessageTypeInfo callSite)
if (info is CallSiteMessageTypeInfo callSite && !IsMediatorCallSite(callSite.Kind))
{
AddDeclaration(byTypeName, callSite.DeclaredMessageType);
// A message is dispatched as its runtime type, which is never an interface or an abstract class.
if (callSite.DeclaredMessageType is { IsAbstract: false })
{
AddDeclaration(byTypeName, callSite.DeclaredMessageType);
}

AddDeclaration(byTypeName, callSite.DeclaredResponseType);
}
else if (info is AddMessageDeclarationInfo addMessage)
Expand Down Expand Up @@ -516,12 +522,13 @@ private static DeclaredTypeInfo MergeDeclarations(DeclaredTypeInfo first, Declar
// Prefer the entry with the ordinally smallest location; a null location always loses.
var location = LocationInfo.Min(first.Location, second.Location);

return new DeclaredTypeInfo(first.TypeName, xmlDocumentation, location);
return new DeclaredTypeInfo(first.TypeName, xmlDocumentation, location, first.IsAbstract);
}

private static JsonSerializableTypeInfo CreateJsonSerializableTypeInfo(
INamedTypeSymbol serializableType,
LocationInfo? location,
Compilation compilation,
CancellationToken cancellationToken)
{
var typeName = serializableType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
Expand All @@ -545,7 +552,7 @@ private static JsonSerializableTypeInfo CreateJsonSerializableTypeInfo(
// Capture the declaration metadata (doc + location) cross-file from the resolved symbol so
// context-only types (serializable types with no handler) still carry their own declaration.
// This is stale only in the IDE's incremental cache; every real compiler invocation runs fresh.
var declaration = serializableType.ToDeclaredTypeInfo(cancellationToken);
var declaration = serializableType.ToDeclaredTypeInfo(compilation, cancellationToken);

return new JsonSerializableTypeInfo(
typeName,
Expand Down Expand Up @@ -741,8 +748,7 @@ private static void AddRequiredCallSiteTypes(
{
foreach (var info in callSiteInfos)
{
if (info is CallSiteMessageTypeInfo callSite
&& callSite.Kind is not (CallSiteKind.MediatorSend or CallSiteKind.MediatorQuery or CallSiteKind.MediatorPublish))
if (info is CallSiteMessageTypeInfo callSite && !IsMediatorCallSite(callSite.Kind))
{
requiredTypes.Add(callSite.MessageTypeName);

Expand Down Expand Up @@ -800,8 +806,7 @@ private static void ValidateCallSiteJsonContext(
// dispatch is in-process and does not require JSON serialization.
foreach (var info in callSiteInfos)
{
if (info is CallSiteMessageTypeInfo callSite
&& callSite.Kind is not (CallSiteKind.MediatorSend or CallSiteKind.MediatorQuery or CallSiteKind.MediatorPublish))
if (info is CallSiteMessageTypeInfo callSite && !IsMediatorCallSite(callSite.Kind))
{
if (!coveredTypes.Contains(callSite.MessageTypeName))
{
Expand Down Expand Up @@ -831,6 +836,9 @@ private static void ValidateCallSiteJsonContext(
}
}

private static bool IsMediatorCallSite(CallSiteKind kind)
=> kind is CallSiteKind.MediatorSend or CallSiteKind.MediatorQuery or CallSiteKind.MediatorPublish;

private static ImmutableArray<SyntaxInfo> ExtractContextOnlyTypes(
ImmutableArray<SyntaxInfo> syntaxInfos,
JsonContextInfo jsonContextInfo)
Expand Down
6 changes: 5 additions & 1 deletion src/Mocha/src/Mocha.Analyzers/Models/DeclaredTypeInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ namespace Mocha.Analyzers;
/// <param name="Location">
/// The full source location of the type declaration, or <see langword="null"/> if unavailable.
/// </param>
/// <param name="IsAbstract">
/// <see langword="true"/> when the declared type is an interface or an abstract class.
/// </param>
public sealed record DeclaredTypeInfo(
string TypeName,
string? XmlDocumentation,
LocationInfo? Location);
LocationInfo? Location,
bool IsAbstract);
4 changes: 2 additions & 2 deletions src/Mocha/src/Mocha.Analyzers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ Classes (not records) that inherit from `Saga<TState>` are discovered. The inspe

## Call-Site Discovery

Invocations on `IMessageBus`, `ISender`, and `IPublisher` are inspected to discover message types used at call sites. These are used for validation only (no code generation).
Invocations on `IMessageBus`, `ISender`, and `IPublisher` are inspected to discover message types used at call sites. Message types found at `IMessageBus` call sites are validated and, when they are declared in the same assembly, registered with `AddMessage<T>` in the generated module. A type that the generated code cannot reference, such as a private nested type, a file-local type, an anonymous type, or a type that contains a type parameter, is not registered. An interface or an abstract class at a call site is not registered either. Mediator call sites are used for validation only.

### IMessageBus Methods

Expand Down Expand Up @@ -264,7 +264,7 @@ For each message type registration, the generator computes an "enclosed types" a

**Fires when (AOT mode):** A message type used in a dispatch call (`PublishAsync`, `SendAsync`, etc.) is not found in the local `JsonSerializerContext` or imported module types.

**Scope:** Only messaging dispatch calls - mediator dispatch (`ISender.SendAsync`, `ISender.QueryAsync`, `IPublisher.PublishAsync`) is excluded because it's in-process.
**Scope:** Dispatch calls on `IMessageBus`. Mediator dispatch is excluded.

> **Note:** MO0017 is reserved and not currently used.

Expand Down
52 changes: 48 additions & 4 deletions src/Mocha/src/Mocha.Analyzers/Utils/RoslynExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,11 +168,13 @@ public static bool ImplementsInterface(this INamedTypeSymbol type, INamedTypeSym
/// </summary>
/// <returns>
/// A <see cref="DeclaredTypeInfo"/> for a source declaration; <see langword="null"/> for a
/// metadata-only type that has no source declaration in the current compilation, or a non-named
/// type that cannot carry source declaration metadata.
/// metadata-only type that has no source declaration in the current compilation, a non-named
/// type that cannot carry source declaration metadata, or a type that code generated into
/// <paramref name="compilation"/> cannot reference.
/// </returns>
public static DeclaredTypeInfo? ToDeclaredTypeInfo(
this ITypeSymbol? type,
Compilation compilation,
CancellationToken cancellationToken)
{
if (type is not INamedTypeSymbol namedType)
Expand All @@ -182,14 +184,56 @@ public static bool ImplementsInterface(this INamedTypeSymbol type, INamedTypeSym

var location = namedType.GetDeclarationLocationInfo(cancellationToken);

if (location is null)
if (location is null || !IsReferenceableFromGeneratedCode(namedType, compilation))
{
return null;
}

return new DeclaredTypeInfo(
namedType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
namedType.GetXmlDocumentation(cancellationToken),
location);
location,
namedType.IsAbstract);
}

private static bool IsReferenceableFromGeneratedCode(ITypeSymbol type, Compilation compilation)
=> compilation.IsSymbolAccessibleWithin(type, compilation.Assembly) && !ContainsUnnameableType(type);

// A type is unnameable when, at any depth, it contains a type that a fully qualified name in a separate,
// safe-context file cannot denote: a file-local, anonymous, error, pointer or function pointer type, or a
// type parameter.
private static bool ContainsUnnameableType(ITypeSymbol type)
{
switch (type)
{
case IArrayTypeSymbol array:
return ContainsUnnameableType(array.ElementType);

case INamedTypeSymbol { TypeKind: not TypeKind.Error } named:
for (var current = named; current is not null; current = current.ContainingType)
{
if (current.IsFileLocal || current.IsAnonymousType)
{
return true;
}

foreach (var typeArgument in current.TypeArguments)
{
if (ContainsUnnameableType(typeArgument))
{
return true;
}
}
}

return false;

default:
return type.TypeKind
is TypeKind.TypeParameter
or TypeKind.Error
or TypeKind.Pointer
or TypeKind.FunctionPointer;
}
}
}
3 changes: 3 additions & 0 deletions src/Mocha/test/Mocha.Analyzers.Tests/MessagingTestHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,9 @@ private static CSharpCompilation CreateCompilation(
// Mocha (IConsumer, IBatchEventHandler, Saga, SagaStateBase)
MetadataReference.CreateFromFile(typeof(IConsumer).Assembly.Location),

// Mocha.Mediator (IPublisher and ISender)
MetadataReference.CreateFromFile(typeof(Mediator.IPublisher).Assembly.Location),

// Mocha.Utilities (FeatureCollectionExtensions)
MetadataReference.CreateFromFile(typeof(Features.FeatureCollectionExtensions).Assembly.Location),

Expand Down
Loading