diff --git a/Docs/pages/09-diagnostics.md b/Docs/pages/09-diagnostics.md index d3d2c218..68e9d9d1 100644 --- a/Docs/pages/09-diagnostics.md +++ b/Docs/pages/09-diagnostics.md @@ -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 | @@ -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\} @@ -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]`, 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] +public static partial class BrewingModule; + +// In the library CoffeeShop.Grinding, which declares Timing.Timer too: +[Module] +[Singleton] +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 + +``` + +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. diff --git a/Source/Awaiten.SourceGenerators/AnalyzerReleases.Unshipped.md b/Source/Awaiten.SourceGenerators/AnalyzerReleases.Unshipped.md index 813efe16..e7cbdde2 100644 --- a/Source/Awaiten.SourceGenerators/AnalyzerReleases.Unshipped.md +++ b/Source/Awaiten.SourceGenerators/AnalyzerReleases.Unshipped.md @@ -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 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 diff --git a/Source/Awaiten.SourceGenerators/AwaitenGenerator.AsyncInitializers.cs b/Source/Awaiten.SourceGenerators/AwaitenGenerator.AsyncInitializers.cs index cb227866..3126a13d 100644 --- a/Source/Awaiten.SourceGenerators/AwaitenGenerator.AsyncInitializers.cs +++ b/Source/Awaiten.SourceGenerators/AwaitenGenerator.AsyncInitializers.cs @@ -333,6 +333,7 @@ private static EquatableArray BuildAsyncInitializers(Impl if (InternalsMembers(owner, ConventionWrapperName(convention)).OfType() .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, @@ -353,6 +354,7 @@ private static EquatableArray 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, @@ -431,6 +433,7 @@ private static EquatableArray HiddenAsyncInitializers(Imp if (names.Add(name) && InternalsMembers(module, name).OfType().FirstOrDefault(method => context.Compilation.IsSymbolAccessibleWithin(method, context.Compilation.Assembly)) is { } wrapper) { + context.Names.ReportOwner(module); models.Add(new AsyncInitializerModel( $"{module.ToDisplayString(FullyQualified)}.{InternalsClass}", name, diff --git a/Source/Awaiten.SourceGenerators/AwaitenGenerator.Classification.cs b/Source/Awaiten.SourceGenerators/AwaitenGenerator.Classification.cs index 2ed35b0a..e5f02e77 100644 --- a/Source/Awaiten.SourceGenerators/AwaitenGenerator.Classification.cs +++ b/Source/Awaiten.SourceGenerators/AwaitenGenerator.Classification.cs @@ -64,6 +64,8 @@ private static List ClassifyParameters( { List 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 @@ -103,6 +105,7 @@ private static List 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); @@ -559,7 +562,8 @@ private sealed record InjectionContext( List<(string ServiceType, INamedTypeSymbol Symbol)> DispatchCandidates, VarianceState Variance, List Diagnostics, - Dictionary SkippedModuleRegistrations); + Dictionary SkippedModuleRegistrations, + AmbiguousTypeNames Names); /// /// The per-property injection flags: how the member is assigned (), whether a missing @@ -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); } } } @@ -757,6 +762,7 @@ private static IEnumerable 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] 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). @@ -1594,7 +1600,7 @@ private static bool ContainerImportsServices(INamedTypeSymbol containerSymbol) /// IExternalResolver, forwarding any [FromKey] key. A typeof argument that is neither a /// closed type nor an unbound generic definition is AWT215. /// - private static ExternalServiceTypes CollectExternalServiceTypes(INamedTypeSymbol containerSymbol, List modules, Compilation compilation, List diagnostics) + private static ExternalServiceTypes CollectExternalServiceTypes(INamedTypeSymbol containerSymbol, List modules, Compilation compilation, List diagnostics, AmbiguousTypeNames? names) { ExternalServiceTypes types = new(); foreach ((AttributeData attribute, Location? fallbackLocation, bool inherited, INamedTypeSymbol? module) in AttributesOf(containerSymbol, modules)) @@ -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)); diff --git a/Source/Awaiten.SourceGenerators/AwaitenGenerator.Collection.cs b/Source/Awaiten.SourceGenerators/AwaitenGenerator.Collection.cs index 856dc9e2..9265da7c 100644 --- a/Source/Awaiten.SourceGenerators/AwaitenGenerator.Collection.cs +++ b/Source/Awaiten.SourceGenerators/AwaitenGenerator.Collection.cs @@ -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) @@ -1930,9 +1931,10 @@ private static (List Closed, List[Inject] attribute carries. The /// container-side counterpart of an [Inject] property, matched to a registration by its /// implementation type (see ). marks an entry of - /// an extended base (see ). + /// an extended base (see ). is the type the + /// spells in the generated code (see ). /// - 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); /// /// Reads the container's [InjectProperty<TImplementation>(name)] and @@ -1983,7 +1985,8 @@ private static Dictionary> CollectInjectProper NamedFlag(attribute, "Optional"), NamedFlag(attribute, "Deferred"), NamedKeyArgument(attribute), - location)); + location, + KeyType: NamedKeyType(attribute))); } return map; diff --git a/Source/Awaiten.SourceGenerators/AwaitenGenerator.DecoratorPredicates.cs b/Source/Awaiten.SourceGenerators/AwaitenGenerator.DecoratorPredicates.cs index 0428519b..4caa4602 100644 --- a/Source/Awaiten.SourceGenerators/AwaitenGenerator.DecoratorPredicates.cs +++ b/Source/Awaiten.SourceGenerators/AwaitenGenerator.DecoratorPredicates.cs @@ -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. @@ -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; } } @@ -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); @@ -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)) { diff --git a/Source/Awaiten.SourceGenerators/AwaitenGenerator.HiddenServices.cs b/Source/Awaiten.SourceGenerators/AwaitenGenerator.HiddenServices.cs index db2e53e5..1a1f9d0e 100644 --- a/Source/Awaiten.SourceGenerators/AwaitenGenerator.HiddenServices.cs +++ b/Source/Awaiten.SourceGenerators/AwaitenGenerator.HiddenServices.cs @@ -524,7 +524,7 @@ public bool MayProvide(ITypeSymbol service, string? key) { ImmutableArray attributes = entry.Key.GetAttributes(); return HasAwaitenAttribute(attributes, "ImportServicesAttribute") - || CollectExternalServiceTypes(entry.Key, new List(), _compilation, new List()).Routes(serviceType) + || CollectExternalServiceTypes(entry.Key, new List(), _compilation, new List(), 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)))); diff --git a/Source/Awaiten.SourceGenerators/AwaitenGenerator.Keys.cs b/Source/Awaiten.SourceGenerators/AwaitenGenerator.Keys.cs index 5c7d063c..34f3ae9f 100644 --- a/Source/Awaiten.SourceGenerators/AwaitenGenerator.Keys.cs +++ b/Source/Awaiten.SourceGenerators/AwaitenGenerator.Keys.cs @@ -74,6 +74,28 @@ partial class AwaitenGenerator return null; } + /// + /// The type a key constant spells in the generated code: the enum of an enum constant or the operand of a + /// typeof(...), else . + /// + private static ITypeSymbol? KeyType(TypedConstant constant) + => constant.Kind switch + { + TypedConstantKind.Enum => constant.Type, + TypedConstantKind.Type => constant.Value as ITypeSymbol, + _ => null, + }; + + /// The of the Key named argument of . + private static ITypeSymbol? NamedKeyType(AttributeData attribute) + => attribute.NamedArguments.Where(argument => argument.Key == "Key").Select(argument => KeyType(argument.Value)).FirstOrDefault(); + + /// The of the [FromKey] among . + private static ITypeSymbol? FromKeyType(ImmutableArray 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 diff --git a/Source/Awaiten.SourceGenerators/AwaitenGenerator.OpenGenerics.cs b/Source/Awaiten.SourceGenerators/AwaitenGenerator.OpenGenerics.cs index 55960580..e3856694 100644 --- a/Source/Awaiten.SourceGenerators/AwaitenGenerator.OpenGenerics.cs +++ b/Source/Awaiten.SourceGenerators/AwaitenGenerator.OpenGenerics.cs @@ -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, }); @@ -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); } /// @@ -1423,6 +1425,9 @@ private sealed record OpenRegistration(INamedTypeSymbol Service, INamedTypeSymbo public IReadOnlyList? ConsumerOwned { get; init; } + /// The type the spells in the generated code (see ). + public ITypeSymbol? KeyType { get; init; } + /// /// The live , which every closing takes, so a diagnostic about one points at the open /// registration and an analyzer can suppress it there. diff --git a/Source/Awaiten.SourceGenerators/AwaitenGenerator.Production.cs b/Source/Awaiten.SourceGenerators/AwaitenGenerator.Production.cs index 7c96064d..faa0f32f 100644 --- a/Source/Awaiten.SourceGenerators/AwaitenGenerator.Production.cs +++ b/Source/Awaiten.SourceGenerators/AwaitenGenerator.Production.cs @@ -17,6 +17,12 @@ partial class AwaitenGenerator Dictionary serviceToImpl = context.ServiceToImpl; WellKnownTypes wellKnown = context.WellKnown; List diagnostics = context.Diagnostics; + if (info.ConstructVia is not null || info.ProductionMember is not null) + { + context.Names.ReportOwner(info.Origin); + } + + context.Names.Report(info.Symbol, info.DeclaredBy ?? info.Origin ?? containerSymbol, "registers", info.Location); string? resolverType = null; if (info.ConstructVia is null @@ -266,6 +272,12 @@ private static List WithDeferredSetters(List members, } ReportWhenUnregistered(dependency, service.Type, info, context); + context.Names.ReportOwner(producer.ContainingType); + foreach (IParameterSymbol parameter in setter.Parameters.Skip(1)) + { + context.Names.ReportDependency(parameter.Type, parameter.GetAttributes(), info.Symbol, info.Location); + } + members.Add(new MemberModel(name, dependency, Deferred: true, call)); } @@ -315,11 +327,17 @@ ParameterModel Classify(IParameterSymbol parameter) return null; } - InjectionContext injection = new(context.ContainerSymbol, context.Compilation, context.ServiceToImpl, context.ConstraintRejected, context.DeferredRejections, context.ConsumedConditionals, context.External.ServiceTypes, context.DispatchCandidates, context.Variance, context.Diagnostics, context.SkippedModuleRegistrations); + InjectionContext injection = new(context.ContainerSymbol, context.Compilation, context.ServiceToImpl, context.ConstraintRejected, context.DeferredRejections, context.ConsumedConditionals, context.External.ServiceTypes, context.DispatchCandidates, context.Variance, context.Diagnostics, context.SkippedModuleRegistrations, context.Names); IEnumerable filled = producer.Parameters.Skip(FirstPropertyOrdinal(producer)).Select(parameter => parameter.Name).Concat(members.Select(member => member.MemberName)); int count = members.Count; DiscoverInjectedMembers(info, injection, entries, members, afterFactory: true, implementation, filled.ToList(), context.ReportedHandleEntries); - return members.Count > count ? $"{alias.ContainingType.ToDisplayString(FullyQualified)}.{alias.Name}" : null; + if (members.Count == count) + { + return null; + } + + context.Names.ReportOwner(alias.ContainingType); + return $"{alias.ContainingType.ToDisplayString(FullyQualified)}.{alias.Name}"; } /// @@ -395,7 +413,7 @@ private static List BuildInjectedMembers(ImplInfo info, BuildContex } List members = new(); - InjectionContext injection = new(context.ContainerSymbol, context.Compilation, context.ServiceToImpl, context.ConstraintRejected, context.DeferredRejections, context.ConsumedConditionals, context.External.ServiceTypes, context.DispatchCandidates, context.Variance, context.Diagnostics, context.SkippedModuleRegistrations); + InjectionContext injection = new(context.ContainerSymbol, context.Compilation, context.ServiceToImpl, context.ConstraintRejected, context.DeferredRejections, context.ConsumedConditionals, context.External.ServiceTypes, context.DispatchCandidates, context.Variance, context.Diagnostics, context.SkippedModuleRegistrations, context.Names); bool readFactory = info.Constructor is { MethodKind: MethodKind.Ordinary, }; List notTaken = injectProperties.Where(entry => !(entry.Inherited @@ -1017,6 +1035,7 @@ private static (string? Hook, EquatableArray Parameters, IMethod // The hook's own origin (the registration that named it), not the implementation's winning Origin: two // scan registrations with different origins can fill the two slots, and each name binds only on its owner. INamedTypeSymbol? origin = release ? info.OnReleaseOrigin : info.OnActivatedOrigin; + context.Names.ReportOwner(origin); // An implementation hidden in its module or base container keeps a hook only when its owner generated the // wrapper (see SelfCompiledRegistration, SameCompilationScanRegistration and BuildThroughBaseFactories), so the @@ -1286,6 +1305,8 @@ private static EquatableArray ClassifyHookParameterSymbols(IEnum continue; } + context.Names.ReportDependency(parameter.Type, parameter.GetAttributes(), parameter.ContainingSymbol.ContainingType ?? info.Symbol, info.Location); + // AWT189: a hook parameter cannot be a runtime [Arg]. Dropped so it contributes no (unresolvable) graph // edge and no emitted argument; the error already fails the build. if (parameterModel.Kind == DependencyKind.Arg) diff --git a/Source/Awaiten.SourceGenerators/AwaitenGenerator.Registrations.cs b/Source/Awaiten.SourceGenerators/AwaitenGenerator.Registrations.cs index 8ef14bd2..2b4e9654 100644 --- a/Source/Awaiten.SourceGenerators/AwaitenGenerator.Registrations.cs +++ b/Source/Awaiten.SourceGenerators/AwaitenGenerator.Registrations.cs @@ -36,7 +36,8 @@ namespace Awaiten.SourceGenerators; /// handle takes when it is the first registration that survives coalescing. Declarer is the container or module /// that declares a registration whose Origin became the module whose generated factory or alias it calls (see /// ShareGeneratedRegistrationFactories and ShareHandleWithRegistrations), which AWT155 and AWT167 judge -/// it by and its lifecycle hooks bind on. +/// it by and its lifecycle hooks bind on. KeyType is the type the Key spells in the generated code, an enum or the +/// operand of a typeof, which AWT260 checks. /// /// /// is the live Roslyn location (with its syntax tree), not an equatable @@ -81,7 +82,8 @@ internal sealed record RawRegistration( RawRegistration? Aliased = null, INamedTypeSymbol? Declarer = null, IReadOnlyList? ConsumerOwned = null, - DecoratorPredicate? EagerWhen = null); + DecoratorPredicate? EagerWhen = null, + ITypeSymbol? KeyType = null); /// /// An imported module: its symbol and the location of the container's [Import] attribute that @@ -127,13 +129,13 @@ internal sealed record DecorateRegistration( /// /// The When predicate of a [Decorate] or the EagerWhen predicate of a [Singleton]: the -/// fully qualified static the root reads, +/// fully qualified static the root reads, the module or container that declares it (), /// the it calls when the member is a method (whose parameters the root resolves), and the /// attribute's location. names the predicate the user declared when is /// the wrapper its owner generated for it. /// /// An intermediate type carrying live Roslyn symbols; see . -internal sealed record DecoratorPredicate(string Member, IMethodSymbol? Method, Location? Location, string? Declared = null); +internal sealed record DecoratorPredicate(string Member, INamedTypeSymbol Owner, IMethodSymbol? Method, Location? Location, string? Declared = null); /// /// The generated factory of a module or base container () that builds a decorator or composite diff --git a/Source/Awaiten.SourceGenerators/AwaitenGenerator.TypeNames.cs b/Source/Awaiten.SourceGenerators/AwaitenGenerator.TypeNames.cs new file mode 100644 index 00000000..64679bce --- /dev/null +++ b/Source/Awaiten.SourceGenerators/AwaitenGenerator.TypeNames.cs @@ -0,0 +1,259 @@ +using System.Collections.Immutable; +using Awaiten.SourceGenerators.Entities; +using Awaiten.SourceGenerators.Internals; +using Microsoft.CodeAnalysis; + +namespace Awaiten.SourceGenerators; + +partial class AwaitenGenerator +{ + /// + /// Reports AWT260 for a type the container's graph needs that its generated + /// code cannot name: another type of the same full name that the container's assembly can access, declared by another + /// referenced assembly or by the project itself, makes global:: name both (CS0433) or the project's own. Each such type + /// is reported once, where it first enters the graph. The generated code names an imported module or the extended base + /// container only to call into it, or to name a type nested in it, which reports it at its import or the Extends. + /// + /// Lives only inside one graph build and never reaches a model. + internal sealed class AmbiguousTypeNames + { + private readonly Compilation _compilation; + private readonly List _diagnostics; + private readonly INamedTypeSymbol _container; + private readonly List _modules; + private readonly Dictionary _clashes = new(SymbolEqualityComparer.Default); + private readonly HashSet _reported = new(SymbolEqualityComparer.Default); + + public AmbiguousTypeNames(Compilation compilation, List diagnostics, INamedTypeSymbol container, List modules) + { + _compilation = compilation; + _diagnostics = diagnostics; + _container = container; + _modules = modules; + } + + /// + /// Reports each type within (itself, its type arguments, element types and containing types) that + /// the generated code cannot name, as needed by , which it. A generated + /// Internals class stands for the type the user wrote it for. + /// + public void Report(ITypeSymbol type, ISymbol needer, string verb, LocationInfo? location) + => ReportWithin(type, type, needer is INamedTypeSymbol { Name: InternalsClass, ContainingType: { } owner, } ? owner : needer, verb, location); + + /// + /// Reports the imported module or extended base container that is or is nested in, whose member + /// the generated code calls, such as a handle, a factory, a hook, a predicate or a wrapper it generates. + /// + public void ReportOwner(INamedTypeSymbol? owner) + { + if (owner is not null && ImportOf(owner) is { } module) + { + ReportModule(module); + } + } + + /// The imported module or extended base container that is or is nested in, or . + private ImportedModule? ImportOf(INamedTypeSymbol type) + { + for (INamedTypeSymbol? current = type.OriginalDefinition; current is not null; current = current.ContainingType) + { + if (_modules.FirstOrDefault(module => SymbolEqualityComparer.Default.Equals(module.Symbol, current)) is { } module) + { + return module; + } + } + + return null; + } + + /// + /// Reports as imported by the container, or by the base container for a module it inherits, or + /// extended for the base itself, at that import or the Extends. + /// + private void ReportModule(ImportedModule module) + { + ISymbol needer = module is { Inherited: true, IsBase: false, } + ? _modules.FirstOrDefault(candidate => candidate.IsBase)?.Symbol ?? _container + : _container; + ReportDefinition(Outermost(module.Symbol).OriginalDefinition, module.Symbol, needer, module.IsBase ? "extends" : "imports", LocationInfo.From(module.ImportLocation)); + } + + private static INamedTypeSymbol Outermost(INamedTypeSymbol type) + { + while (type.ContainingType is { } containing) + { + type = containing; + } + + return type; + } + + /// + /// Reports each top-level type definition of spells, which global:: + /// looks up by its full name. + /// + private void ReportWithin(ITypeSymbol part, ITypeSymbol type, ISymbol needer, string verb, LocationInfo? location) + { + switch (part) + { + case IArrayTypeSymbol array: + ReportWithin(array.ElementType, type, needer, verb, location); + break; + case IPointerTypeSymbol pointer: + ReportWithin(pointer.PointedAtType, type, needer, verb, location); + break; + case INamedTypeSymbol named: + if (ImportOf(named) is { } module) + { + ReportModule(module); + } + else + { + ReportDefinition(Outermost(named).OriginalDefinition, type, needer, verb, location); + } + + for (INamedTypeSymbol? current = named; current is not null; current = current.ContainingType) + { + foreach (ITypeSymbol argument in current.TypeArguments) + { + ReportWithin(argument, type, needer, verb, location); + } + } + + break; + } + } + + private void ReportDefinition(INamedTypeSymbol definition, ITypeSymbol type, ISymbol needer, string verb, LocationInfo? location) + { + if (ClashOf(definition) is { } clash && _reported.Add(definition)) + { + _diagnostics.Add(new DiagnosticInfo( + Diagnostics.AmbiguousTypeName, + location, + new EquatableArray([ + Display(type.ToDisplayString(FullyQualified)), + Display(needer.ToDisplayString(FullyQualified)), + verb, + Enumerate(clash.Assemblies), + clash.Name, + clash.Assemblies.Contains(_compilation.AssemblyName) + ? "rename one of them" + : "keep the container in a project that references only one of them, or rename one of them", + ]))); + } + } + + /// + /// Reports the type a key spells in the generated code, an enum or the operand of a typeof(...) (see + /// ), as used by . + /// + public void ReportKey(ITypeSymbol? keyType, ISymbol needer, LocationInfo? location) + { + if (keyType is not null) + { + Report(keyType, needer, "uses as a key", location); + } + } + + /// Reports a dependency of that takes, and the key of its [FromKey]. + public void ReportDependency(ITypeSymbol type, ImmutableArray attributes, ISymbol needer, LocationInfo? location) + { + Report(type, needer, "takes", location); + ReportKey(FromKeyType(attributes), needer, location); + } + + /// + /// What keeps global:: from naming when it is not the project's own, else + /// : the full name of a namespace of it that another assembly declares an accessible type of (CS0434), + /// or its own full name when another assembly declares an accessible type of that name and arity (CS0433, or the project's + /// own wins) or a namespace of that name (CS0434), with the names of the assemblies that declare them. A type the + /// compilation's assembly cannot access is never named by the generated code and does not get in the way of the one it + /// names, but a namespace does, whatever its types. A type spelled by its keyword, such as string, always names the + /// core library's. + /// + private (string Name, string[] Assemblies)? ClashOf(INamedTypeSymbol definition) + { + if (_clashes.TryGetValue(definition, out (string Name, string[] Assemblies)? cached)) + { + return cached; + } + + (string Name, string[] Assemblies)? clash = null; + if (definition is { TypeKind: not TypeKind.Error, ContainingAssembly: { } assembly, } + && definition.ToDisplayString(FullyQualified).StartsWith("global::", StringComparison.Ordinal) + && !SymbolEqualityComparer.Default.Equals(assembly, _compilation.Assembly) + && Accessible(definition)) + { + Stack names = new(); + for (INamespaceSymbol? ns = definition.ContainingNamespace; ns is { IsGlobalNamespace: false, }; ns = ns.ContainingNamespace) + { + names.Push(ns.Name); + } + + INamespaceSymbol? resolved = _compilation.GlobalNamespace; + string? prefix = null; + while (clash is null && resolved is not null && names.Count > 0) + { + string name = names.Pop(); + prefix = prefix is null ? name : $"{prefix}.{name}"; + clash = Clash(prefix, assembly, resolved.GetTypeMembers(name, 0).Where(Accessible).Select(type => type.ContainingAssembly)); + resolved = resolved.GetMembers(name).OfType().FirstOrDefault(); + } + + if (clash is null && resolved is not null) + { + IEnumerable namespaces = definition.Arity == 0 + ? resolved.GetMembers(definition.Name).OfType().SelectMany(ns => ns.ConstituentNamespaces).Select(ns => ns.ContainingAssembly) + : []; + clash = Clash( + Display(definition.ToDisplayString(FullyQualified)), + assembly, + resolved.GetTypeMembers(definition.Name, definition.Arity) + .Where(candidate => !SymbolEqualityComparer.Default.Equals(candidate, definition) && Accessible(candidate)) + .Select(candidate => candidate.ContainingAssembly) + .Concat(namespaces)); + } + } + + _clashes[definition] = clash; + return clash; + } + + private bool Accessible(INamedTypeSymbol type) => _compilation.IsSymbolAccessibleWithin(type, _compilation.Assembly); + + /// The clash of between and , or when there are none. + private static (string Name, string[] Assemblies)? Clash(string name, IAssemblySymbol assembly, IEnumerable others) + { + string[] names = others.OfType().Select(other => other.Name).ToArray(); + return names.Length == 0 + ? null + : (name, names.Append(assembly.Name).Distinct().OrderBy(other => other, StringComparer.Ordinal).ToArray()); + } + + /// + /// Reports the service and the key of each registration in that joins the graph, which the container + /// names in its resolvers and keyed dispatch, as declared by the container or module the registration comes from. A default + /// another registration replaces never joins it. + /// + public void ReportServices(List raw, Dictionary> serviceMembers, INamedTypeSymbol containerSymbol) + { + foreach (RawRegistration registration in raw) + { + ServiceKey key = new(registration.ServiceType, registration.WhenInjectedInto is { } consumer ? ContextKey(consumer) : registration.Key); + if (registration.ServiceSymbol is { } service + && serviceMembers.TryGetValue(key, out List? members) + && members.Contains(registration.ImplementationType)) + { + ISymbol declarer = registration.Declarer ?? registration.Origin ?? containerSymbol; + LocationInfo? location = LocationInfo.From(registration.Location); + Report(service, declarer, "registers", location); + ReportKey(registration.KeyType, declarer, location); + } + } + } + + private static string Enumerate(string[] assemblies) + => $"{string.Join(", ", assemblies.Take(assemblies.Length - 1).Select(name => $"'{name}'"))} and '{assemblies[assemblies.Length - 1]}'"; + } +} diff --git a/Source/Awaiten.SourceGenerators/AwaitenGenerator.cs b/Source/Awaiten.SourceGenerators/AwaitenGenerator.cs index a5bc22ce..5fd7b486 100644 --- a/Source/Awaiten.SourceGenerators/AwaitenGenerator.cs +++ b/Source/Awaiten.SourceGenerators/AwaitenGenerator.cs @@ -928,7 +928,8 @@ private sealed record BuildContext( Dictionary ClosingFaults, HashSet ReportedHandleEntries, Dictionary SkippedModuleRegistrations, - Dictionary InheritedFaults); + Dictionary InheritedFaults, + AmbiguousTypeNames Names); /// /// The mutable coalesced graph state the decorator-chain and composite builders rewrite in place: the @@ -996,7 +997,8 @@ internal static GraphModel BuildGraph( // parameter or [Inject] property - to the external provider, while every other unresolved dependency keeps the // AWT101 check. Bundled with the blanket flag as the container's external-resolution surface, threaded through // the coalescing phase that decides constructor satisfiability. - ExternalServiceTypes externalServiceTypes = CollectExternalServiceTypes(containerSymbol, modules, compilation, diagnostics); + AmbiguousTypeNames names = new(compilation, diagnostics, containerSymbol, modules); + ExternalServiceTypes externalServiceTypes = CollectExternalServiceTypes(containerSymbol, modules, compilation, diagnostics, names); // An extending container's own registration replaces an inherited [ImportService] of that type, as it // replaces an inherited registration (the reverse is in ReplaceInherited). @@ -1068,6 +1070,7 @@ internal static GraphModel BuildGraph( (List implOrder, Dictionary serviceToImpl, Dictionary> serviceMembers, List serviceMemberOrder, List<(string ServiceType, INamedTypeSymbol Symbol)> varianceCandidates, Dictionary> keyedMembers, List keyedMemberOrder) = CoalesceByImplementation(raw, containerSymbol, compilation, duplicates, checkedHandles, diagnostics); CoalescedGraph graph = new(serviceToImpl, implOrder, serviceMembers); + names.ReportServices(raw, serviceMembers, containerSymbol); // The closed generic service symbols the coalesced graph holds (recovered from the raw registrations, // which carry each closing's symbol), so an open decorator/composite can find every closing to expand onto. @@ -1124,7 +1127,7 @@ internal static GraphModel BuildGraph( // closings of an open import are checked once the instances are built (ReportOpenExternalServices). ReportContradictingExternalServices(externalServiceTypes, serviceToImpl, containerSymbol, diagnostics); - BuildContext buildContext = new(containerSymbol, compilation, serviceToImpl, decoratorInner, compositeCollections, wellKnown, constraintRejected, deferredRejections, external, variance, consumedConditionals, injectProperties, CollectDispatchCandidates(raw, serviceToImpl), diagnostics, ServedTypesOf(raw, serviceMembers, keyedMembers), factories, new AsyncInitializerScopes(compilation), new SameCompilationModules(compilation), new HiddenInjectedProperties(compilation), new Dictionary(StringComparer.Ordinal), closingFaults, new HashSet(), skippedModuleRegistrations, inheritance?.InheritedFaults ?? new Dictionary()); + BuildContext buildContext = new(containerSymbol, compilation, serviceToImpl, decoratorInner, compositeCollections, wellKnown, constraintRejected, deferredRejections, external, variance, consumedConditionals, injectProperties, CollectDispatchCandidates(raw, serviceToImpl), diagnostics, ServedTypesOf(raw, serviceMembers, keyedMembers), factories, new AsyncInitializerScopes(compilation), new SameCompilationModules(compilation), new HiddenInjectedProperties(compilation), new Dictionary(StringComparer.Ordinal), closingFaults, new HashSet(), skippedModuleRegistrations, inheritance?.InheritedFaults ?? new Dictionary(), names); // Validate each implementation, select its constructor and build the instance. foreach (ImplInfo info in implOrder) diff --git a/Source/Awaiten.SourceGenerators/Diagnostics.cs b/Source/Awaiten.SourceGenerators/Diagnostics.cs index 8466d1a2..b3ec48a9 100644 --- a/Source/Awaiten.SourceGenerators/Diagnostics.cs +++ b/Source/Awaiten.SourceGenerators/Diagnostics.cs @@ -2863,6 +2863,24 @@ internal static class Diagnostics isEnabledByDefault: true, helpLinkUri: HelpLink("AWT259")); + /// + /// The graph needs a type the generated container cannot name, because another assembly the project references, or the + /// project itself, declares a type of the same full name that the container's assembly can access, a namespace of that + /// name, or a type named like one of its namespaces. Plain C# names such a type only through an extern alias, which + /// the generator cannot add, so the generated code would not compile (CS0433 or CS0434, or a type mismatch when the + /// project's own type wins). Reported once per type, at the import or registration that brings it into the graph. The + /// remedy suggests keeping the container in a project that references only one of the assemblies unless the project + /// itself declares the name, where only a rename helps. + /// + public static readonly DiagnosticDescriptor AmbiguousTypeName = new( + "AWT260", + "Type the container cannot name", + "The generated container cannot name '{0}', which '{1}' {2}, because the assemblies {3} each declare a type or namespace named '{4}'; {5}", + "Awaiten", + DiagnosticSeverity.Error, + isEnabledByDefault: true, + helpLinkUri: HelpLink("AWT260")); + /// /// A consumer lists a service in ConsumerOwned, but building the service leaves more on the owner than the /// instance the consumer gets: a disposable transient below it (a decorated inner instance, an injected property diff --git a/Tests/Awaiten.SourceGenerators.Tests/DiagnosticTests.Awt260AmbiguousTypeName.cs b/Tests/Awaiten.SourceGenerators.Tests/DiagnosticTests.Awt260AmbiguousTypeName.cs new file mode 100644 index 00000000..8e810659 --- /dev/null +++ b/Tests/Awaiten.SourceGenerators.Tests/DiagnosticTests.Awt260AmbiguousTypeName.cs @@ -0,0 +1,543 @@ +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Emit; + +namespace Awaiten.SourceGenerators.Tests; + +public partial class DiagnosticTests +{ + /// + /// Two libraries declare a public type of the same full name, which plain C# cannot name in a project that references + /// both, so a container there that would name it reports it instead of generating code that does not compile. + /// + public class Awt260AmbiguousTypeName + { + public enum Setup + { + ImplementationAssembly, + ReferenceAssembly, + CompilationReference, + Friend, + } + + private const string Friend = "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(\"TestAssembly\")]"; + + private const string ImportBoth = """ + using Awaiten; + + namespace MyCode; + + [Container] + [Import(typeof(First.ClockModule))] + [Import(typeof(Second.ClockModule))] + public static partial class MyContainer; + """; + + private const string ImportFirst = """ + using Awaiten; + + namespace MyCode; + + [Container] + [Import(typeof(First.ClockModule))] + public static partial class MyContainer; + """; + + private static string Library( + string name, + string clock = "public sealed class Clock { }", + string registrations = "[Singleton]", + string types = "") => $$""" + using Awaiten; + + namespace Lib + { + {{clock}} + } + + namespace {{name}} + { + {{types}} + + [Module] + {{registrations}} + public static partial class ClockModule { } + } + """; + + private static string Expected(string module, string verb = "registers", string type = "Lib.Clock", string line = "6", string column = "2", string declared = "Lib.Clock") + => $"({line},{column}): error AWT260: The generated container cannot name '{type}', which '{module}' {verb}, because the assemblies 'FirstAssembly' and 'SecondAssembly' each declare a type or namespace named '{declared}'; keep the container in a project that references only one of them, or rename one of them"; + + private static GeneratorResult Run(Setup setup, string first, string second, string consumer) + { + string grants = setup == Setup.Friend ? $"using Awaiten;\n{Friend}" : "using Awaiten;"; + (Compilation firstCompilation, _) = Generator.RunGenerator(first.Replace("using Awaiten;", grants), [], [], "FirstAssembly"); + (Compilation secondCompilation, _) = Generator.RunGenerator(second.Replace("using Awaiten;", grants), [], [], "SecondAssembly"); + return Generator.RunWithReferences(consumer, [Reference(firstCompilation), Reference(secondCompilation),]); + + MetadataReference Reference(Compilation compilation) + => setup switch + { + Setup.ReferenceAssembly => Generator.EmitToReference(compilation, new EmitOptions(metadataOnly: true, includePrivateMembers: false)), + Setup.CompilationReference => Generator.ToCompilationReference(compilation), + _ => Generator.EmitToReference(compilation), + }; + } + + [Test] + [Arguments(Setup.ImplementationAssembly)] + [Arguments(Setup.ReferenceAssembly)] + [Arguments(Setup.CompilationReference)] + [Arguments(Setup.Friend)] + public async Task ARegistrationOfEachSameNamedType_ReportsEachAtItsImport(Setup setup) + { + GeneratorResult result = Run(setup, Library("First"), Library("Second"), ImportBoth); + + await That(result.Diagnostics).HasCount(2); + await That(result.Diagnostics).Contains(Expected("First.ClockModule")) + .And.Contains(Expected("Second.ClockModule", line: "7")) + .Because("'global::Lib.Clock' is ambiguous between the two references, so the container reports each type instead of emitting CS0433"); + } + + [Test] + [Arguments(Setup.ImplementationAssembly)] + [Arguments(Setup.ReferenceAssembly)] + [Arguments(Setup.CompilationReference)] + [Arguments(Setup.Friend)] + public async Task AnInstanceHandleOfEachSameNamedType_ReportsEachAtItsImport(Setup setup) + { + static string Handled(string name) => Library(name, clock: "public sealed class Clock { internal Clock() { } }"); + + GeneratorResult result = Run(setup, Handled("First"), Handled("Second"), ImportBoth); + + await That(result.Diagnostics).HasCount(2); + await That(result.Diagnostics).Contains(Expected("First.ClockModule")) + .And.Contains(Expected("Second.ClockModule", line: "7")) + .Because("the container holds each clock in a field of its type, whether it builds it itself or through the module's handle"); + } + + [Test] + [Arguments(Setup.ImplementationAssembly)] + [Arguments(Setup.ReferenceAssembly)] + public async Task ATypeArgument_IsReportedWithTheTypeItIsPartOf(Setup setup) + { + string first = Library( + "First", + registrations: "[Singleton, IHolder>]", + types: "public interface IHolder { } public sealed class Holder : IHolder { }"); + + GeneratorResult result = Run(setup, first, Library("Second", registrations: ""), ImportFirst); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.ClockModule", type: "First.IHolder")) + .Because("the second library declares 'Lib.Clock' even though the container imports none of its modules, and the implementation is reported with the service it shares the clock with"); + } + + [Test] + [Arguments(Setup.ImplementationAssembly)] + [Arguments(Setup.ReferenceAssembly)] + public async Task ADependencyImportedFromTheHost_IsReportedForTheTypeThatTakesIt(Setup setup) + { + string first = Library( + "First", + registrations: "[Singleton]", + types: "public sealed class Service { public Service(Lib.Clock clock) { } }"); + + GeneratorResult result = Run(setup, first, Library("Second", registrations: ""), ImportFirst.Replace("[Container]", "[Container]\n[ImportServices]")); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.Service", verb: "takes", line: "7")) + .Because("the container asks its host for the clock by naming its type"); + } + + [Test] + public async Task AnEmptyCollection_IsReportedForTheTypeThatTakesIt() + { + string first = Library( + "First", + registrations: "[Singleton]", + types: "public sealed class Service { public Service(System.Collections.Generic.IEnumerable clocks) { } }"); + + GeneratorResult result = Run(Setup.ImplementationAssembly, first, Library("Second", registrations: ""), ImportFirst); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.Service", verb: "takes", type: "System.Collections.Generic.IEnumerable")) + .Because("the container builds the empty collection as an array of the clock's type"); + } + + [Test] + [Arguments("public enum Clock { Fast }", "Lib.Clock.Fast", "Lib.Clock")] + [Arguments("public sealed class Clock { }", "typeof(Lib.Clock)", "Lib.Clock")] + [Arguments("public sealed class Clock { }", "typeof(System.Collections.Generic.List)", "System.Collections.Generic.List")] + public async Task ARegistrationKey_IsReportedForTheModuleThatUsesIt(string clock, string key, string type) + { + string first = Library("First", clock, $"[Singleton(Key = {key})]", "public sealed class Service { }"); + + GeneratorResult result = Run(Setup.ImplementationAssembly, first, Library("Second", clock, registrations: ""), ImportFirst); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.ClockModule", verb: "uses as a key", type: type)) + .Because("the container's keyed dispatch spells the key, and so its type, in the generated code"); + } + + [Test] + [Arguments("public enum Clock { Fast }", "Lib.Clock.Fast")] + [Arguments("public sealed class Clock { }", "typeof(Lib.Clock)")] + public async Task AKeyOfADependencyImportedFromTheHost_IsReportedForTheTypeThatTakesIt(string clock, string key) + { + string first = Library( + "First", + clock, + "[Singleton]", + $"public sealed class Service {{ }} public sealed class Consumer {{ public Consumer([FromKey({key})] Service service) {{ }} }}"); + + GeneratorResult result = Run(Setup.ImplementationAssembly, first, Library("Second", clock, registrations: ""), ImportFirst.Replace("[Container]", "[Container]\n[ImportService]")); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.Consumer", verb: "uses as a key", line: "7")) + .Because("the container forwards the key to its host when it asks for the service"); + } + + [Test] + public async Task AKeyOfAnOpenGenericRegistration_IsReportedForTheModuleThatUsesIt() + { + string first = Library( + "First", + "public enum Clock { Fast }", + "[Singleton(typeof(Holder<>), typeof(IHolder<>), Key = Lib.Clock.Fast)]", + "public interface IHolder { } public sealed class Holder : IHolder { } public sealed class Service { public Service([FromKey(Lib.Clock.Fast)] IHolder holder) { } } [Module] [Singleton] public static partial class ServiceModule { }"); + + GeneratorResult result = Run(Setup.ImplementationAssembly, first, Library("Second", "public enum Clock { Fast }", registrations: ""), ImportFirst.Replace("[Import(typeof(First.ClockModule))]", "[Import(typeof(First.ClockModule))]\n[Import(typeof(First.ServiceModule))]")); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.ClockModule", verb: "uses as a key")) + .Because("each closing of the open registration keeps its key, which the keyed dispatch spells"); + } + + [Test] + public async Task AKeyOfAPropertyEntryOfAnExtendedContainer_IsReportedForTheTypeWhosePropertyItIs() + { + string first = Library( + "First", + "public enum Clock { Fast }", + registrations: "", + types: "public sealed class Service { } public sealed class Consumer { public Service? Service { get; set; } } [Container] [ImportService] [Singleton] [InjectProperty(nameof(Consumer.Service), Key = Lib.Clock.Fast)] public static partial class BaseShop;"); + const string consumer = """ + using Awaiten; + + namespace MyCode; + + [Container(Extends = typeof(First.BaseShop))] + public static partial class MyContainer; + """; + + GeneratorResult result = Run(Setup.ImplementationAssembly, first, Library("Second", "public enum Clock { Fast }", registrations: ""), consumer); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.Consumer", verb: "uses as a key", line: "5", column: "12")) + .Because("the container forwards the entry's key to its host when it asks for the property's service"); + } + + [Test] + [Arguments( + "public sealed class Clock : First.IService { public Clock(First.IService inner) { } }", + "[Singleton] [Decorate]", + "public interface IService { } public sealed class Service : IService { }", + "Lib.Clock", "First.ClockModule", "registers")] + [Arguments( + "public sealed class Clock : First.IService { public Clock(System.Collections.Generic.IEnumerable services) { } }", + "[Singleton] [Composite]", + "public interface IService { } public sealed class Service : IService { }", + "Lib.Clock", "First.ClockModule", "registers")] + [Arguments( + "public sealed class Clock { }", + "[Singleton(typeof(Holder<>), typeof(IHolder<>))] [Singleton]", + "public interface IHolder { } public sealed class Holder : IHolder { } public sealed class Service { public Service(IHolder holder) { } }", + "First.IHolder", "First.ClockModule", "registers")] + [Arguments( + "public sealed class Clock { }", + "[Transient]", + "public sealed class Service { public Service([Arg] Lib.Clock clock) { } }", + "Lib.Clock", "First.Service", "takes")] + [Arguments( + "public sealed class Clock { }", + "[Singleton(OnActivated = nameof(Activate))]", + "public sealed class Service { } public static partial class ClockModule { internal static void Activate(Service service, Lib.Clock clock) { } }", + "Lib.Clock", "First.ClockModule", "takes")] + [Arguments( + "public sealed class Clock { }", + "[AsyncInitializer(nameof(IWarmUp.WarmUpAsync))] [Singleton]", + "public interface IWarmUp { System.Threading.Tasks.Task WarmUpAsync(Lib.Clock clock); } public sealed class Service : IWarmUp { public System.Threading.Tasks.Task WarmUpAsync(Lib.Clock clock) => System.Threading.Tasks.Task.CompletedTask; }", + "Lib.Clock", "First.IWarmUp", "takes")] + [Arguments( + "public sealed class Clock { }", + "[Singleton] [Decorate(When = nameof(Audit))]", + "public interface IService { } public sealed class Service : IService { } public sealed class Decorator : IService { public Decorator(IService inner) { } } public static partial class ClockModule { internal static bool Audit(Lib.Clock clock) => true; }", + "Lib.Clock", "First.ClockModule", "takes")] + [Arguments( + "public sealed class Clock { }", + "[Singleton]", + "public sealed class Service { internal Service() { } [Inject(Deferred = true)] public System.Collections.Generic.IEnumerable Clock { get; set; } = null!; }", + "System.Collections.Generic.IEnumerable", "First.Service", "takes")] + public async Task AFeatureThatNamesTheType_ReportsIt(string clock, string registrations, string types, string type, string needer, string verb) + { + string first = Library("First", clock, registrations, types); + + GeneratorResult result = Run(Setup.ImplementationAssembly, first, Library("Second", registrations: ""), ImportFirst.Replace("[Container]", "[Container]\n[ImportServices]")); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected(needer, verb: verb, type: type, line: "7")) + .Because("decorators, composites, open generic closings, runtime arguments, hooks, async initializers, decorator predicates and deferred setters each make the container spell the type, here of a clock it asks its host for"); + } + + [Test] + public async Task AnExtendedContainerOfAnotherAssembly_IsReportedForTheBaseContainer() + { + string first = Library("First", registrations: "", types: "[Container] [Singleton] public static partial class BaseShop;"); + const string consumer = """ + using Awaiten; + + namespace MyCode; + + [Container(Extends = typeof(First.BaseShop))] + public static partial class MyContainer; + """; + + GeneratorResult result = Run(Setup.ImplementationAssembly, first, Library("Second", registrations: ""), consumer); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.BaseShop", line: "5", column: "12")) + .Because("the extending container builds the base container's registrations itself"); + } + + [Test] + public async Task AServiceAModuleImportsFromTheHost_IsReportedForTheModule() + { + string first = Library("First", registrations: "[ImportService]"); + + GeneratorResult result = Run(Setup.ImplementationAssembly, first, Library("Second", registrations: ""), ImportFirst); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.ClockModule", verb: "imports")) + .Because("the container's by-type dispatch asks the host for the imported clock by its type"); + } + + [Test] + public async Task TheTypeOfAnAsyncInitializer_IsReportedForTheModuleThatDeclaresIt() + { + string first = Library( + "First", + "public interface IWarmUp { System.Threading.Tasks.Task WarmUpAsync(); }", + "[AsyncInitializer(nameof(Lib.IWarmUp.WarmUpAsync))] [Singleton]", + "public sealed class Service : Lib.IWarmUp { public System.Threading.Tasks.Task WarmUpAsync() => System.Threading.Tasks.Task.CompletedTask; }"); + + GeneratorResult result = Run(Setup.ImplementationAssembly, first, Library("Second", "public interface IWarmUp { }", registrations: ""), ImportFirst); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.ClockModule", verb: "declares as an async initializer", type: "Lib.IWarmUp", declared: "Lib.IWarmUp")) + .Because("the container casts the instance to the initializer's type to run it"); + } + + private const string HandledModule = "[Module] [Singleton] public static partial class Mod { }"; + + private const string Kettle = "public sealed class Kettle { internal Kettle() { } }"; + + private const string Extending = """ + using Awaiten; + + namespace MyCode; + + [Container(Extends = typeof(First.BaseShop))] + public static partial class MyContainer; + """; + + private static string BaseShop(string kettle, string module = HandledModule) + => Library("First", module, registrations: "", types: $"{kettle} [Container] [Import(typeof(Lib.Mod))] public static partial class BaseShop;"); + + [Test] + [Arguments(Kettle, HandledModule)] + [Arguments("public sealed class Kettle { }", "[Module] [Singleton(OnActivated = nameof(Activate))] public static partial class Mod { public static void Activate(First.Kettle kettle) { } }")] + [Arguments("public sealed class Kettle { }", "[Module] [Singleton(Factory = nameof(Create))] public static partial class Mod { public static First.Kettle Create() => new(); }")] + [Arguments("public sealed class Kettle { }", "[Module] [Singleton(EagerWhen = nameof(Eager))] public static partial class Mod { public static bool Eager() => true; }")] + public async Task AModuleOfAnExtendedContainer_IsReportedForTheBaseContainerThatImportsIt(string kettle, string module) + { + GeneratorResult result = Run(Setup.ImplementationAssembly, BaseShop(kettle, module), Library("Second", "public static class Mod { }", registrations: ""), Extending); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.BaseShop", verb: "imports", type: "Lib.Mod", line: "5", column: "12", declared: "Lib.Mod")) + .Because("a handle, a hook, a factory or a predicate the module declares makes the container name the module's type"); + } + + [Test] + public async Task AModuleTheContainerNeverNames_IsNotReported() + { + GeneratorResult result = Run(Setup.ImplementationAssembly, BaseShop("public sealed class Kettle { }"), Library("Second", "public static class Mod { }", registrations: ""), Extending); + + await That(result.Diagnostics).IsEmpty() + .Because("the container constructs the public kettle itself, so its generated code never names the module"); + } + + [Test] + public async Task AGenericTypeThatSharesTheNameOfAModuleTheContainerNeverNames_IsNotReported() + { + const string module = "[Module] [Singleton] [Singleton>] public static partial class Mod { } public sealed class Mod { }"; + + GeneratorResult result = Run(Setup.ImplementationAssembly, BaseShop("public sealed class Kettle { }", module), Library("Second", "public static class Mod { }", registrations: ""), Extending); + + await That(result.Diagnostics).IsEmpty() + .Because("'global::Lib.Mod' names the generic type of another arity, and the container never calls into the module 'Lib.Mod'"); + } + + [Test] + public async Task AModuleOfAnExtendedContainerOfTheSameAssembly_IsReportedOnceForTheBaseContainer() + { + (Compilation first, _) = Generator.RunGenerator(Library("First", HandledModule, registrations: "", types: Kettle), [], [], "FirstAssembly"); + (Compilation second, _) = Generator.RunGenerator(Library("Second", "public static class Mod { }", registrations: ""), [], [], "SecondAssembly"); + const string consumer = """ + extern alias Other; + using Awaiten; + + namespace MyCode; + + [Container] + [Import(typeof(Other::Lib.Mod))] + public static partial class BaseShop; + + [Container(Extends = typeof(BaseShop))] + public static partial class MyContainer; + """; + + GeneratorResult result = Generator.RunWithReferences(consumer, [Generator.EmitToReference(first).WithAliases(["Other",]), Generator.EmitToReference(second),]); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("MyCode.BaseShop", verb: "imports", type: "Lib.Mod", line: "7", declared: "Lib.Mod")) + .Because("the base container reports the module it imports itself, so the extending container does not report it again"); + } + + [Test] + public async Task AModuleTheContainerImportsThroughAnAlias_IsReportedForTheContainer() + { + (Compilation first, _) = Generator.RunGenerator(Library("First", HandledModule, registrations: "", types: Kettle), [], [], "FirstAssembly"); + (Compilation second, _) = Generator.RunGenerator(Library("Second", "public static class Mod { }", registrations: ""), [], [], "SecondAssembly"); + const string consumer = """ + extern alias Other; + using Awaiten; + + namespace MyCode; + + [Container] + [Import(typeof(Other::Lib.Mod))] + public static partial class MyContainer; + """; + + GeneratorResult result = Generator.RunWithReferences(consumer, [Generator.EmitToReference(first).WithAliases(["Other",]), Generator.EmitToReference(second),]); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("MyCode.MyContainer", verb: "imports", type: "Lib.Mod", line: "7", declared: "Lib.Mod")) + .Because("'global::Lib.Mod' names the second library's type, so the container cannot name the module it imports through the alias"); + } + + [Test] + public async Task ASameNamedTypeOfAnAliasedReference_IsNotReported() + { + (Compilation first, _) = Generator.RunGenerator(Library("First"), [], [], "FirstAssembly"); + (Compilation second, _) = Generator.RunGenerator(Library("Second", registrations: ""), [], [], "SecondAssembly"); + + GeneratorResult result = Generator.RunWithReferences(ImportFirst, [Generator.EmitToReference(first), Generator.EmitToReference(second).WithAliases(["Other",]),]); + + await That(result.Diagnostics).IsEmpty() + .Because("the second library's clock is reachable only through its alias, so 'global::Lib.Clock' names only the first one"); + } + + [Test] + public async Task ADefaultTheContainerReplaces_IsNotReported() + { + string first = Library( + "First", + registrations: "[Singleton(Fallback = Fallback.Silent)]", + clock: "public sealed class Clock : First.IClock { }", + types: "public interface IClock { }"); + string consumer = ImportFirst.Replace("[Container]", "[Container]\n[Singleton]") + "\npublic sealed class MyClock : First.IClock { }"; + + GeneratorResult result = Run(Setup.ImplementationAssembly, first, Library("Second", registrations: ""), consumer); + + await That(result.Diagnostics).IsEmpty() + .Because("the container's own registration replaces the module's default, so its clock never joins the graph"); + } + + [Test] + public async Task ASameNamedTypeTheContainerNeverNames_IsNotReported() + { + string first = Library("First", registrations: "[Singleton]", types: "public sealed class Kettle { }"); + + GeneratorResult result = Run(Setup.ImplementationAssembly, first, Library("Second", registrations: ""), ImportFirst); + + await That(result.Diagnostics).IsEmpty() + .Because("both libraries declare 'Lib.Clock', but nothing in the container's graph needs it"); + } + + [Test] + [Arguments("public")] + [Arguments("internal")] + public async Task ANamespaceOfTheSameFullName_IsReported(string accessibility) + { + GeneratorResult result = Run( + Setup.ImplementationAssembly, + Library("First"), + Library("Second", clock: $"namespace Clock {{ {accessibility} sealed class Tick {{ }} }}", registrations: ""), + ImportFirst); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.ClockModule")) + .Because("'global::Lib.Clock' conflicts with the namespace 'Lib.Clock' of the second library (CS0434), whatever the accessibility of the types in it"); + } + + [Test] + public async Task ATypeNamedLikeANamespaceOfTheType_IsReported() + { + GeneratorResult result = Run(Setup.ImplementationAssembly, Library("First"), "public class Lib { }", ImportFirst); + + await That(result.Diagnostics).HasSingle().Which.IsEqualTo(Expected("First.ClockModule", declared: "Lib")) + .Because("'global::Lib' conflicts with the type 'Lib' of the second library (CS0434), so 'global::Lib.Clock' cannot name the clock"); + } + + [Test] + public async Task ATypeNamedLikeANamespaceOfTheTypeInternalToTheOtherAssembly_IsNotReported() + { + GeneratorResult result = Run(Setup.ImplementationAssembly, Library("First"), "internal class Lib { }", ImportFirst); + + await That(result.Diagnostics).IsEmpty() + .Because("the container cannot see the second library's internal type 'Lib', so 'global::Lib' names only the namespace"); + } + + [Test] + public async Task ASameNamedTypeInternalToTheOtherAssembly_IsNotReported() + { + GeneratorResult result = Run( + Setup.ImplementationAssembly, + Library("First"), + Library("Second", clock: "internal sealed class Clock { }", registrations: ""), + ImportFirst); + + await That(result.Diagnostics).IsEmpty() + .Because("the container cannot see the second library's internal clock, so 'global::Lib.Clock' names only the first one"); + } + + private static GeneratorResult RunInFirstAssembly(string imports) + { + (Compilation second, _) = Generator.RunGenerator(Library("Second"), [], [], "SecondAssembly"); + string first = Library("First").Replace("public static partial class ClockModule { }", $$""" + public static partial class ClockModule { } + + [Container] + {{imports}} + public static partial class MyContainer; + """); + return Generator.RunWithReferences(first, [Generator.EmitToReference(second),], "FirstAssembly"); + } + + [Test] + public async Task AContainerInTheAssemblyOfOneType_ReportsOnlyTheOtherOne() + { + GeneratorResult result = RunInFirstAssembly("[Import(typeof(ClockModule))]\n[Import(typeof(Second.ClockModule))]"); + + await That(result.Diagnostics.Where(diagnostic => !diagnostic.Contains("warning CS0436"))).HasSingle().Which.IsEqualTo( + "(18,2): error AWT260: The generated container cannot name 'Lib.Clock', which 'Second.ClockModule' registers, because the assemblies 'FirstAssembly' and 'SecondAssembly' each declare a type or namespace named 'Lib.Clock'; rename one of them") + .Because("'global::Lib.Clock' names the clock of the container's own assembly, as in the module's own attribute, so only the other library's clock cannot be named, and no choice of references helps while the project declares the clock itself"); + } + + [Test] + public async Task AContainerInTheAssemblyOfOneType_NamesItsOwnType() + { + GeneratorResult result = RunInFirstAssembly("[Import(typeof(ClockModule))]"); + + await That(result.Diagnostics).IsNotEmpty().And.All().Satisfy(diagnostic => diagnostic.Contains("warning CS0436")) + .Because("'global::Lib.Clock' names the clock of the container's own assembly, with the warning the module's own attribute gets too"); + } + } +} diff --git a/Tests/Awaiten.SourceGenerators.Tests/TestHelpers/Analyzer.cs b/Tests/Awaiten.SourceGenerators.Tests/TestHelpers/Analyzer.cs index 6b586071..96a83fda 100644 --- a/Tests/Awaiten.SourceGenerators.Tests/TestHelpers/Analyzer.cs +++ b/Tests/Awaiten.SourceGenerators.Tests/TestHelpers/Analyzer.cs @@ -45,7 +45,7 @@ public static Task RunWithCompilationReference( where TAnalyzer : DiagnosticAnalyzer, new() { (Compilation referenced, _) = Generator.RunGenerator(referencedSource, [], [], "ReferencedAssembly"); - return Run(source, [referenced.ToMetadataReference(),], []); + return Run(source, [Generator.ToCompilationReference(referenced),], []); } /// diff --git a/Tests/Awaiten.SourceGenerators.Tests/TestHelpers/Generator.cs b/Tests/Awaiten.SourceGenerators.Tests/TestHelpers/Generator.cs index 7a28e93a..ee168154 100644 --- a/Tests/Awaiten.SourceGenerators.Tests/TestHelpers/Generator.cs +++ b/Tests/Awaiten.SourceGenerators.Tests/TestHelpers/Generator.cs @@ -135,7 +135,7 @@ public static GeneratorResult RunWithGeneratedCompilationReference( [StringSyntax("c#-test")] string source) { (Compilation referencedOutput, _) = RunGenerator(referencedSource, [], [], "ReferencedAssembly"); - return Run(source, [referencedOutput.ToMetadataReference(),]); + return Run(source, [ToCompilationReference(referencedOutput),]); } /// @@ -152,6 +152,16 @@ public static GeneratorResult RunWithGeneratedReferencedAssemblies( return Run(source, [EmitToReference(first), EmitToReference(second),]); } + /// + /// Like , but compiles as against + /// , which the test built itself. + /// + public static GeneratorResult RunWithReferences( + [StringSyntax("c#-test")] string source, + MetadataReference[] references, + string assemblyName = "TestAssembly") + => Collect(RunGenerator(source, references, [], assemblyName)); + /// /// Like , but with a chain of generated referenced assemblies: /// each of is compiled with the generator against the ones before it, so a @@ -220,7 +230,7 @@ public static GeneratorResult RunWithModuleAndBase( else { (Compilation @base, _) = RunGenerator(baseSource, [moduleReference,], [], "BaseAssembly"); - baseReference = build == BaseBuild.CompilationReference ? @base.ToMetadataReference() : EmitToReference(@base); + baseReference = build == BaseBuild.CompilationReference ? ToCompilationReference(@base) : EmitToReference(@base); } return Run(source, [moduleReference, baseReference,]); @@ -327,6 +337,23 @@ internal static MetadataReference EmitToReference(Compilation compilation, EmitO return MetadataReference.CreateFromImage(stream.ToArray()); } + /// + /// Returns a compilation reference to , failing loudly (with the offending diagnostics) when it + /// does not compile, as does. + /// + internal static MetadataReference ToCompilationReference(Compilation compilation) + { + Diagnostic[] errors = compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ToArray(); + if (errors.Length > 0) + { + throw new InvalidOperationException( + "The referenced assembly does not compile: " + + string.Join(Environment.NewLine, errors.Select(d => d.ToString()))); + } + + return compilation.ToMetadataReference(); + } + /// The severities of an .editorconfig, which the compiler reads per syntax tree. internal sealed class EditorConfigOptions(AnalyzerConfigSet configs) : SyntaxTreeOptionsProvider {