Skip to content
Merged
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
39 changes: 38 additions & 1 deletion Docs/pages/09-diagnostics.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ Every reported id with its default severity.
| [AWT257](#awt257) | Error | Collection misses a registration served through a handle |
| [AWT258](#awt258) | Error | Collection imported from the external resolver |
| [AWT259](#awt259) | Error | Relationship type registered as a service |
| [AWT260](#awt260) | Error | Type the container cannot name |
| [AWT261](#awt261) | Error | Consumer cannot own what its Func builds |
| [AWT262](#awt262) | Warning | `ConsumerOwned` entry never applies |
| [AWT263](#awt263) | Error | `Eager` and `EagerWhen` on one registration |
Expand Down Expand Up @@ -6059,7 +6060,7 @@ It is reported at the `[ImportService]`, for the `typeof` form and an unbound co

## Project setup

This checks that the project can compile the code Awaiten generates.
These check that the project can compile the code Awaiten generates.

### AWT243: Language version too old for the generated code \{#awt243\}

Expand All @@ -6086,6 +6087,42 @@ A container, and a module that generates code, needs C# 9 or later; a module tha

On .NET Framework and netstandard2.0 without a polyfill, only code in the same project from C# 11 learns that the `out` instance of `TryResolve` is not null when it returns `true`. For that annotation in other assemblies or below C# 11, add a polyfill such as the `Nullable` package or PolySharp.

### AWT260: Type the container cannot name \{#awt260\}

:::danger[Error]
The container needs a type that its generated code can't name, because another assembly the project references, or the project itself, declares a type of the same full name that the project can access, a namespace of that name, or a type named like one of its namespaces.
:::

C# names such a type only through an `extern alias`, which Awaiten can't add to your project, so the generated code wouldn't compile. A namespace `Timing.Timer` gets in the way of the type `Timing.Timer` whatever types it holds, and so does a type `Timing` the project can access. A type the project declares itself wins over a referenced one of the same name, so a container in that project can name its own type but not the other one, and its generated code gets the same CS0436 warning as your own code that names it, which fails the build under `TreatWarningsAsErrors`. A key counts too: the generated code spells the enum of a key such as `Key = Timing.Speed.Fast` and the type of a `typeof` key wherever it dispatches by the key or passes it to the host. So do the type of an `[AsyncInitializer<T>]`, and an imported module or extended base container whose handle, factory, hook or predicate the generated code calls. The container reports each such type once, at the `[Import]` of the module that registers, takes, imports, uses it as a key or declares it as an async initializer, at the `Extends` of an inherited one, or at the registration, and names the assemblies that declare the type or namespace in the way. Types of the same name that the container never needs, or that are internal to another assembly the project has no `InternalsVisibleTo` for, aren't reported.

```csharp no-compile
// In the library CoffeeShop.Brewing:
namespace Timing { public sealed class Timer; }

[Module]
[Singleton<Timing.Timer>]
public static partial class BrewingModule;

// In the library CoffeeShop.Grinding, which declares Timing.Timer too:
[Module]
[Singleton<Timing.Timer>]
public static partial class GrindingModule;

// In the application, which references both libraries:
[Container]
[Import(typeof(BrewingModule))] // AWT260 for the Timer of CoffeeShop.Brewing
[Import(typeof(GrindingModule))] // AWT260 for the Timer of CoffeeShop.Grinding
public static partial class CoffeeShop;
```

**Fix:** Rename one of the types or namespaces, or keep the container in a project that references only one of the assemblies that declare it. When the project itself declares one of them, only the rename helps. When nothing the container needs lives in one of the assemblies, not even a module it imports, give that reference an alias in the project file instead, with `Aliases` on the `ProjectReference` or `PackageReference`, so the generated code names only the other assembly's type:

```xml
<ProjectReference Include="..\CoffeeShop.Grinding\CoffeeShop.Grinding.csproj" Aliases="Grinding" />
```

The alias doesn't help when the container needs a type of the aliased assembly or imports a module from it, even through the alias: the generated code names everything through `global::`, which doesn't reach the aliased assembly, so it can't name that type or module.

## Generator bugs

This reports a bug in Awaiten itself, not a mistake in your wiring.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@
AWT257 | Awaiten | Error | A collection the container builds would miss a registration that an imported module of another assembly serves only through a generated handle the container cannot read
AWT258 | Awaiten | Error | An [ImportService] names a collection shape or keyed dictionary, which the container always builds from its own registrations, so the external resolver is never asked for it
AWT259 | Awaiten | Error | A dependency is a relationship such as Func<T> whose type the container also registers or imports as a service, which injection never hands out, because it builds the relationship over T
AWT260 | Awaiten | Error | The container needs a type whose full name another referenced assembly, or the project itself, also declares as an accessible type or a namespace, or whose namespace it declares as an accessible type, so the generated code cannot name it
AWT261 | Awaiten | Error | A consumer lists a service in ConsumerOwned whose build leaves more than the instance on the owner, such as another disposable transient, a Func or Lazy over one, or a release hook, which the consumer cannot release
AWT262 | Awaiten | Warning | A ConsumerOwned entry that no Func or dispatch dictionary of the consumer over a build-on-demand service the container disposes reaches, in any closing of the registration
AWT263 | Awaiten | Error | A [Singleton] sets both Eager = true and EagerWhen, so the predicate would never decide whether it is built at startup
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ private static EquatableArray<AsyncInitializerModel> BuildAsyncInitializers(Impl
if (InternalsMembers(owner, ConventionWrapperName(convention)).OfType<IMethodSymbol>()
.FirstOrDefault(method => method.Parameters.Length > 0 && context.Compilation.IsSymbolAccessibleWithin(method, context.Compilation.Assembly)) is { } wrapper)
{
context.Names.ReportOwner(owner);
models.Add(new AsyncInitializerModel(
$"{owner.ToDisplayString(FullyQualified)}.{InternalsClass}",
wrapper.Name,
Expand All @@ -353,6 +354,7 @@ private static EquatableArray<AsyncInitializerModel> BuildAsyncInitializers(Impl
continue;
}

context.Names.Report(convention.Type, convention.Owner, "declares as an async initializer", info.Location);
models.Add(new AsyncInitializerModel(
convention.Type.ToDisplayString(FullyQualified),
convention.Name,
Expand Down Expand Up @@ -431,6 +433,7 @@ private static EquatableArray<AsyncInitializerModel> HiddenAsyncInitializers(Imp
if (names.Add(name)
&& InternalsMembers(module, name).OfType<IMethodSymbol>().FirstOrDefault(method => context.Compilation.IsSymbolAccessibleWithin(method, context.Compilation.Assembly)) is { } wrapper)
{
context.Names.ReportOwner(module);
models.Add(new AsyncInitializerModel(
$"{module.ToDisplayString(FullyQualified)}.{InternalsClass}",
name,
Expand Down
15 changes: 13 additions & 2 deletions Source/Awaiten.SourceGenerators/AwaitenGenerator.Classification.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ private static List<ParameterModel> ClassifyParameters(
{
List<ParameterModel> parameters = new();
int firstProperty = IsGeneratedOwnerFactory(producer) ? FirstPropertyOrdinal(producer) : int.MaxValue;
bool mirrorsConstructor = producer.MethodKind == MethodKind.Constructor || producer.ContainingType.Name == InternalsClass;
ISymbol needer = mirrorsConstructor ? info.Symbol : producer.ContainingType;
foreach (IParameterSymbol parameter in producer.Parameters)
{
// A [RequestingType] parameter of a Factory method is filled at each construction site with the
Expand Down Expand Up @@ -103,6 +105,7 @@ private static List<ParameterModel> ClassifyParameters(
}

ParameterModel parameterModel = ClassifyParameter(parameter, asyncFactory, context.External.ServiceTypes);
context.Names.ReportDependency(parameter.Type, parameter.GetAttributes(), needer, info.Location);

ReportUnsupportedFromKey(parameter.GetAttributes(), parameterModel.Location ?? info.Location, DisplayInstance(info.ImplementationType), context.Diagnostics);

Expand Down Expand Up @@ -559,7 +562,8 @@ private sealed record InjectionContext(
List<(string ServiceType, INamedTypeSymbol Symbol)> DispatchCandidates,
VarianceState Variance,
List<DiagnosticInfo> Diagnostics,
Dictionary<ServiceKey, (string Module, string Reason)> SkippedModuleRegistrations);
Dictionary<ServiceKey, (string Module, string Reason)> SkippedModuleRegistrations,
AmbiguousTypeNames Names);

/// <summary>
/// The per-property injection flags: how the member is assigned (<see cref="Deferred" />), whether a missing
Expand Down Expand Up @@ -654,6 +658,7 @@ private static void DiscoverInjectedMembers(
if (ClassifyInjectedMember(property, info, context, spec) is { } member)
{
members.Add(member);
context.Names.ReportKey(entry.KeyType, info.Symbol, info.Location);
}
}
}
Expand Down Expand Up @@ -757,6 +762,7 @@ private static IEnumerable<IPropertySymbol> InjectedProperties(INamedTypeSymbol

ParameterModel dependency = ClassifyDependency(
property.Type, property.GetAttributes(), asyncFactory: false, location, externalServiceTypes);
context.Names.ReportDependency(property.Type, property.GetAttributes(), info.Symbol, info.Location);

// A container-side [InjectProperty<TImpl>] entry supplies its key directly (the property is a POCO member
// with no [FromKey]); an [Inject] property's key is already read from its [FromKey] above (KeyOverride null).
Expand Down Expand Up @@ -1594,7 +1600,7 @@ private static bool ContainerImportsServices(INamedTypeSymbol containerSymbol)
/// <c>IExternalResolver</c>, forwarding any <c>[FromKey]</c> key. A <c>typeof</c> argument that is neither a
/// closed type nor an unbound generic definition is AWT215.
/// </summary>
private static ExternalServiceTypes CollectExternalServiceTypes(INamedTypeSymbol containerSymbol, List<ImportedModule> modules, Compilation compilation, List<DiagnosticInfo> diagnostics)
private static ExternalServiceTypes CollectExternalServiceTypes(INamedTypeSymbol containerSymbol, List<ImportedModule> modules, Compilation compilation, List<DiagnosticInfo> diagnostics, AmbiguousTypeNames? names)
{
ExternalServiceTypes types = new();
foreach ((AttributeData attribute, Location? fallbackLocation, bool inherited, INamedTypeSymbol? module) in AttributesOf(containerSymbol, modules))
Expand Down Expand Up @@ -1628,6 +1634,11 @@ private static ExternalServiceTypes CollectExternalServiceTypes(INamedTypeSymbol
continue;
}

if (service is not null)
{
names?.Report(service, module ?? containerSymbol, "imports", LocationInfo.From(attribute.ApplicationSyntaxReference?.GetSyntax().GetLocation() ?? fallbackLocation));
}

if (attributeClass is { IsGenericType: true, TypeArguments.Length: 1, })
{
Add(types.Closed, service!, service!.ToDisplayString(FullyQualified));
Expand Down
11 changes: 7 additions & 4 deletions Source/Awaiten.SourceGenerators/AwaitenGenerator.Collection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,8 @@ private static void CollectLifetimeRegistrations(
SuppressDisposal: NamedFlag(attribute, "SuppressDisposal"),
WhenInjectedInto: whenInjectedInto,
ConsumerOwned: NamedTypeArrayArgument(attribute, "ConsumerOwned"),
EagerWhen: eagerWhen);
EagerWhen: eagerWhen,
KeyType: NamedKeyType(attribute));

if (fromModule && !conflictingDirectives && !skipGeneratedScanRegistrations
&& ThroughHandle(registration, context.Compilation, implicitHandles, context.Imports ?? []) is { } handled)
Expand Down Expand Up @@ -1930,9 +1931,10 @@ private static (List<CompositeRegistration> Closed, List<OpenCompositeRegistrati
/// implementation to fill, plus the same per-property flags an <c>[Inject]</c> attribute carries. The
/// container-side counterpart of an <c>[Inject]</c> property, matched to a registration by its
/// implementation type (see <see cref="CollectInjectProperties" />). <see cref="Inherited" /> marks an entry of
/// an extended base (see <see cref="InheritInjectProperties" />).
/// an extended base (see <see cref="InheritInjectProperties" />). <see cref="KeyType" /> is the type the
/// <see cref="Key" /> spells in the generated code (see <see cref="AwaitenGenerator.KeyType(TypedConstant)" />).
/// </summary>
private sealed record InjectPropertyEntry(string PropertyName, bool Optional, bool Deferred, string? Key, LocationInfo? Location, bool Inherited = false);
private sealed record InjectPropertyEntry(string PropertyName, bool Optional, bool Deferred, string? Key, LocationInfo? Location, bool Inherited = false, ITypeSymbol? KeyType = null);

/// <summary>
/// Reads the container's <c>[InjectProperty&lt;TImplementation&gt;(name)]</c> and
Expand Down Expand Up @@ -1983,7 +1985,8 @@ private static Dictionary<string, List<InjectPropertyEntry>> CollectInjectProper
NamedFlag(attribute, "Optional"),
NamedFlag(attribute, "Deferred"),
NamedKeyArgument(attribute),
location));
location,
KeyType: NamedKeyType(attribute)));
}

return map;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ private static bool TryReadPredicate(
return ThroughWrapper(out predicate);
}

predicate = new DecoratorPredicate($"{owner.ToDisplayString(FullyQualified)}.{name}", usable[0] as IMethodSymbol, location);
predicate = new DecoratorPredicate($"{owner.ToDisplayString(FullyQualified)}.{name}", owner, usable[0] as IMethodSymbol, location);
return true;

// Only an owner in another assembly carries the wrapper: one in this assembly generates it in this same run.
Expand All @@ -78,7 +78,7 @@ bool ThroughWrapper(out DecoratorPredicate? wrapped)
}

string ownerName = owner.ToDisplayString(FullyQualified);
wrapped = new DecoratorPredicate($"{ownerName}.{InInternals(wrapperName)}", wrapper as IMethodSymbol, location, $"{ownerName}.{name}");
wrapped = new DecoratorPredicate($"{ownerName}.{InInternals(wrapperName)}", owner, wrapper as IMethodSymbol, location, $"{ownerName}.{name}");
return true;
}
}
Expand Down Expand Up @@ -230,6 +230,7 @@ private static string DescribePredicateOwner(INamedTypeSymbol owner)

private static PredicateModel BuildPredicate(DecoratorPredicate predicate, string service, BuildContext context)
{
context.Names.ReportOwner(predicate.Owner);
if (!context.Predicates.TryGetValue(predicate.Member, out PredicateModel? model))
{
model = ClassifyPredicateParameters(predicate, service, context);
Expand Down Expand Up @@ -260,6 +261,7 @@ private static PredicateModel ClassifyPredicateParameters(DecoratorPredicate pre
foreach (IParameterSymbol parameter in method.Parameters)
{
ParameterModel model = ClassifyParameter(parameter, asyncFactory: false, context.External.ServiceTypes);
context.Names.ReportDependency(parameter.Type, parameter.GetAttributes(), method.ContainingType, attributeLocation);
model = model with { Location = model.Location ?? attributeLocation, };
if (ReportMisplacedInherited(parameter, attributeLocation, context.Diagnostics))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ public bool MayProvide(ITypeSymbol service, string? key)
{
ImmutableArray<AttributeData> attributes = entry.Key.GetAttributes();
return HasAwaitenAttribute(attributes, "ImportServicesAttribute")
|| CollectExternalServiceTypes(entry.Key, new List<ImportedModule>(), _compilation, new List<DiagnosticInfo>()).Routes(serviceType)
|| CollectExternalServiceTypes(entry.Key, new List<ImportedModule>(), _compilation, new List<DiagnosticInfo>(), null).Routes(serviceType)
|| entry.Value.Any(registration => NamedKeyArgument(registration.Attribute) == key
&& (registration.Service.ToDisplayString(FullyQualified) == serviceType
|| (variant is not null && VarianceCompatible(registration.Service, variant, _compilation))));
Expand Down
22 changes: 22 additions & 0 deletions Source/Awaiten.SourceGenerators/AwaitenGenerator.Keys.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,28 @@ partial class AwaitenGenerator
return null;
}

/// <summary>
/// The type a key constant spells in the generated code: the enum of an enum constant or the operand of a
/// <c>typeof(...)</c>, else <see langword="null" />.
/// </summary>
private static ITypeSymbol? KeyType(TypedConstant constant)
=> constant.Kind switch
{
TypedConstantKind.Enum => constant.Type,
TypedConstantKind.Type => constant.Value as ITypeSymbol,
_ => null,
};

/// <summary>The <see cref="KeyType" /> of the <c>Key</c> named argument of <paramref name="attribute" />.</summary>
private static ITypeSymbol? NamedKeyType(AttributeData attribute)
=> attribute.NamedArguments.Where(argument => argument.Key == "Key").Select(argument => KeyType(argument.Value)).FirstOrDefault();

/// <summary>The <see cref="KeyType" /> of the <c>[FromKey]</c> among <paramref name="attributes" />.</summary>
private static ITypeSymbol? FromKeyType(ImmutableArray<AttributeData> attributes)
=> TryGetAwaitenAttribute(attributes, "FromKeyAttribute", out AttributeData? attribute) && attribute!.ConstructorArguments.Length == 1
? KeyType(attribute.ConstructorArguments[0])
: null;

// The simple member name of the enum constant with the given underlying value, or "" for a value with no named
// member (e.g. an unnamed flags combination). Included in the encoding so diagnostics and emission can render the
// user-written PaymentProvider.Stripe. Two aliased members with the same underlying value resolve to the first and
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ private static void CollectOpenRegistration(
OnRelease = NamedArgument(attribute, "OnRelease"),
SuppressDisposal = NamedFlag(attribute, "SuppressDisposal"),
ConsumerOwned = NamedTypeArrayArgument(attribute, "ConsumerOwned"),
KeyType = NamedKeyType(attribute),
Inheritance = context.Inherited ? context.Inheritance : null,
});

Expand Down Expand Up @@ -864,7 +865,8 @@ private static RawRegistration SynthesizeClosedRegistration(
OnActivatedMarkers: candidate.OnActivated is null ? null : markers,
OnReleaseMarkers: candidate.OnRelease is null ? null : markers,
GenericFactory: candidate.Factory is not null,
ConsumerOwned: candidate.ConsumerOwned);
ConsumerOwned: candidate.ConsumerOwned,
KeyType: candidate.KeyType);
}

/// <summary>
Expand Down Expand Up @@ -1423,6 +1425,9 @@ private sealed record OpenRegistration(INamedTypeSymbol Service, INamedTypeSymbo

public IReadOnlyList<string>? ConsumerOwned { get; init; }

/// <summary>The type the <see cref="Key" /> spells in the generated code (see <see cref="AwaitenGenerator.KeyType(TypedConstant)" />).</summary>
public ITypeSymbol? KeyType { get; init; }

/// <summary>
/// The live <see cref="Location" />, which every closing takes, so a diagnostic about one points at the open
/// registration and an analyzer can suppress it there.
Expand Down
Loading
Loading