Skip to content

Commit

Permalink
ArC: improve error message for unsatisfied dependency
Browse files Browse the repository at this point in the history
- in particular, the message is improved when a user attempts to inject
a bean class:
(a) that has no bean defining annotation.
(b) is vetoed
(c) is excluded in config
(d) does not declare a valid bean constructor
(e) has the matched type excluded by the Typed annotation
  • Loading branch information
mkouba authored and carlesarnal committed Dec 18, 2023
1 parent d731567 commit 2ccc518
Show file tree
Hide file tree
Showing 17 changed files with 521 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
Expand Down Expand Up @@ -49,6 +50,7 @@
import io.quarkus.arc.processor.BeanRegistrar.RegistrationContext;
import io.quarkus.arc.processor.BuildExtension.BuildContext;
import io.quarkus.arc.processor.BuildExtension.Key;
import io.quarkus.arc.processor.Types.TypeClosure;
import io.quarkus.arc.processor.bcextensions.ExtensionsEntryPoint;
import io.quarkus.gizmo.MethodCreator;
import io.quarkus.gizmo.ResultHandle;
Expand Down Expand Up @@ -79,6 +81,7 @@ public class BeanDeployment {

private final List<BeanInfo> beans;
private volatile Map<DotName, List<BeanInfo>> beansByType;
private final List<SkippedClass> skippedClasses;

private final List<InterceptorInfo> interceptors;
private final List<DecoratorInfo> decorators;
Expand Down Expand Up @@ -218,6 +221,7 @@ public class BeanDeployment {
this.interceptors = new CopyOnWriteArrayList<>();
this.decorators = new CopyOnWriteArrayList<>();
this.beans = new CopyOnWriteArrayList<>();
this.skippedClasses = new CopyOnWriteArrayList<>();
this.observers = new CopyOnWriteArrayList<>();

this.assignabilityCheck = new AssignabilityCheck(getBeanArchiveIndex(), applicationIndex);
Expand Down Expand Up @@ -271,9 +275,11 @@ void registerScopes() {

BeanRegistrar.RegistrationContext registerBeans(List<BeanRegistrar> beanRegistrars) {
List<InjectionPointInfo> injectionPoints = new ArrayList<>();
this.beans.addAll(
findBeans(initBeanDefiningAnnotations(beanDefiningAnnotations.values(), stereotypes.keySet()), observers,
injectionPoints, jtaCapabilities));
BeanDiscoveryResult beanDiscoveryResult = findBeans(
initBeanDefiningAnnotations(beanDefiningAnnotations.values(), stereotypes.keySet()), observers,
injectionPoints, jtaCapabilities);
this.beans.addAll(beanDiscoveryResult.beans);
this.skippedClasses.addAll(beanDiscoveryResult.skippedClasses);
// Note that we use unmodifiable views because the underlying collections may change in the next phase
// E.g. synthetic beans are added and unused interceptors removed
buildContext.putInternal(Key.BEANS, Collections.unmodifiableList(beans));
Expand Down Expand Up @@ -941,7 +947,23 @@ static ScopeInfo getValidScope(Set<ScopeInfo> scopes, AnnotationTarget target) {
}
}

private List<BeanInfo> findBeans(Collection<DotName> beanDefiningAnnotations, List<ObserverInfo> observers,
record BeanDiscoveryResult(List<BeanInfo> beans, List<SkippedClass> skippedClasses) {
}

/**
* A class found during discovery but skipped for a specific reason.
*/
record SkippedClass(ClassInfo clazz, SkippedReason reason) {
}

enum SkippedReason {
EXCLUDED_TYPE,
VETOED,
NO_BEAN_DEF_ANNOTATION,
NO_BEAN_CONSTRUCTOR
}

private BeanDiscoveryResult findBeans(Collection<DotName> beanDefiningAnnotations, List<ObserverInfo> observers,
List<InjectionPointInfo> injectionPoints, boolean jtaCapabilities) {

Set<ClassInfo> beanClasses = new HashSet<>();
Expand All @@ -956,6 +978,9 @@ private List<BeanInfo> findBeans(Collection<DotName> beanDefiningAnnotations, Li
.map(StereotypeInfo::getName)
.collect(Collectors.toSet());

List<SkippedClass> skipped = new ArrayList<>();
List<ClassInfo> noBeanDefiningAnnotationClasses = new ArrayList<>();

Set<DotName> seenClasses = new HashSet<>();

// If needed use the specialized immutable index to discover beans
Expand All @@ -978,6 +1003,7 @@ private List<BeanInfo> findBeans(Collection<DotName> beanDefiningAnnotations, Li
}

if (isExcluded(beanClass)) {
skipped.add(new SkippedClass(beanClass, SkippedReason.EXCLUDED_TYPE));
continue;
}

Expand All @@ -997,18 +1023,21 @@ private List<BeanInfo> findBeans(Collection<DotName> beanDefiningAnnotations, Li
// in strict compatibility mode, the bean needs to have either no args ctor or some with @Inject
// note that we perform validation (for multiple ctors for instance) later in the cycle
if (strictCompatibility && numberOfConstructorsWithInject == 0) {
skipped.add(new SkippedClass(beanClass, SkippedReason.NO_BEAN_CONSTRUCTOR));
continue;
}

// without strict compatibility, a bean without no-arg constructor needs to have either a constructor
// annotated with @Inject or a single constructor
if (numberOfConstructorsWithInject == 0 && numberOfConstructorsWithoutInject != 1) {
skipped.add(new SkippedClass(beanClass, SkippedReason.NO_BEAN_CONSTRUCTOR));
continue;
}
}

if (isVetoed(beanClass)) {
// Skip vetoed bean classes
skipped.add(new SkippedClass(beanClass, SkippedReason.VETOED));
continue;
}

Expand All @@ -1032,9 +1061,12 @@ private List<BeanInfo> findBeans(Collection<DotName> beanDefiningAnnotations, Li
if (annotationStore.hasAnyAnnotation(beanClass, beanDefiningAnnotations)) {
hasBeanDefiningAnnotation = true;
beanClasses.add(beanClass);
} else {
noBeanDefiningAnnotationClasses.add(beanClass);
}

// non-inherited methods
// non-inherited methods: producers and disposers
// Impl.note: we cannot optimize with beanClass.hasAnnotation() as the annotations can be added with a transformer
for (MethodInfo method : beanClass.methods()) {
if (method.isSynthetic()) {
continue;
Expand Down Expand Up @@ -1216,10 +1248,10 @@ private List<BeanInfo> findBeans(Collection<DotName> beanDefiningAnnotations, Li
for (MethodInfo producerMethod : producerMethods) {
BeanInfo declaringBean = beanClassToBean.get(producerMethod.declaringClass());
if (declaringBean != null) {
Set<Type> beanTypes = Types.getProducerMethodTypeClosure(producerMethod, this);
DisposerInfo disposer = findDisposer(beanTypes, declaringBean, producerMethod, disposers);
TypeClosure typeClosure = Types.getProducerMethodTypeClosure(producerMethod, this);
DisposerInfo disposer = findDisposer(typeClosure.types(), declaringBean, producerMethod, disposers);
unusedDisposers.remove(disposer);
BeanInfo producerMethodBean = Beans.createProducerMethod(beanTypes, producerMethod, declaringBean, this,
BeanInfo producerMethodBean = Beans.createProducerMethod(typeClosure, producerMethod, declaringBean, this,
disposer, injectionPointTransformer);
if (producerMethodBean != null) {
beans.add(producerMethodBean);
Expand All @@ -1231,8 +1263,8 @@ private List<BeanInfo> findBeans(Collection<DotName> beanDefiningAnnotations, Li
for (FieldInfo producerField : producerFields) {
BeanInfo declaringBean = beanClassToBean.get(producerField.declaringClass());
if (declaringBean != null) {
Set<Type> beanTypes = Types.getProducerFieldTypeClosure(producerField, this);
DisposerInfo disposer = findDisposer(beanTypes, declaringBean, producerField, disposers);
TypeClosure typeClosure = Types.getProducerFieldTypeClosure(producerField, this);
DisposerInfo disposer = findDisposer(typeClosure.types(), declaringBean, producerField, disposers);
unusedDisposers.remove(disposer);
BeanInfo producerFieldBean = Beans.createProducerField(producerField, declaringBean, this,
disposer);
Expand Down Expand Up @@ -1281,7 +1313,18 @@ private List<BeanInfo> findBeans(Collection<DotName> beanDefiningAnnotations, Li
LOGGER.logf(Level.TRACE, "Created %s", bean);
}
}
return beans;

for (Iterator<ClassInfo> it = noBeanDefiningAnnotationClasses.iterator(); it.hasNext();) {
ClassInfo clazz = it.next();
if (beanClasses.contains(clazz)) {
// Bean class is not annotated with a bean defining annotation but declares observer, producer, disposer..
continue;
}
skipped.add(new SkippedClass(clazz, SkippedReason.NO_BEAN_DEF_ANNOTATION));
}

LOGGER.debugf("Found %s beans, skipped %s classes", beans.size(), skipped.size());
return new BeanDiscoveryResult(beans, skipped);
}

private boolean isVetoed(ClassInfo beanClass) {
Expand Down Expand Up @@ -1670,6 +1713,26 @@ public Set<String> getQualifierNonbindingMembers(DotName name) {
return qualifierNonbindingMembers.getOrDefault(name, Collections.emptySet());
}

/**
* Returns the set of skipped classes that match the given required type.
*
* @param type
* @return set of skipped classes
*/
List<SkippedClass> findSkippedClassesMatching(Type type) {
List<SkippedClass> skipped = new ArrayList<>();
for (SkippedClass skippedClass : skippedClasses) {
Set<Type> types = Types.getClassUnrestrictedTypeClosure(skippedClass.clazz, this);
for (Type beanType : types) {
if (beanResolver.matches(type, beanType)) {
skipped.add(skippedClass);
break;
}
}
}
return skipped;
}

@Override
public String toString() {
return "BeanDeployment [name=" + name + "]";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.util.function.Consumer;
import java.util.stream.Collectors;

import jakarta.enterprise.inject.Typed;
import jakarta.enterprise.inject.spi.DefinitionException;
import jakarta.enterprise.inject.spi.DeploymentException;
import jakarta.enterprise.inject.spi.InterceptionType;
Expand Down Expand Up @@ -55,6 +56,7 @@ public class BeanInfo implements InjectionTargetInfo {
protected final ScopeInfo scope;

protected final Set<Type> types;
protected final Set<Type> unrestrictedTypes;

protected final Set<AnnotationInstance> qualifiers;

Expand Down Expand Up @@ -97,18 +99,19 @@ public class BeanInfo implements InjectionTargetInfo {
BeanInfo(AnnotationTarget target, BeanDeployment beanDeployment, ScopeInfo scope, Set<Type> types,
Set<AnnotationInstance> qualifiers, List<Injection> injections, BeanInfo declaringBean, DisposerInfo disposer,
boolean alternative, List<StereotypeInfo> stereotypes, String name, boolean isDefaultBean, String targetPackageName,
Integer priority) {
Integer priority, Set<Type> unrestrictedTypes) {
this(null, null, target, beanDeployment, scope, types, qualifiers, injections, declaringBean, disposer,
alternative, stereotypes, name, isDefaultBean, null, null, Collections.emptyMap(), true, false,
targetPackageName, priority, null);
targetPackageName, priority, null, unrestrictedTypes);
}

BeanInfo(ClassInfo implClazz, Type providerType, AnnotationTarget target, BeanDeployment beanDeployment, ScopeInfo scope,
Set<Type> types, Set<AnnotationInstance> qualifiers, List<Injection> injections, BeanInfo declaringBean,
DisposerInfo disposer, boolean alternative,
List<StereotypeInfo> stereotypes, String name, boolean isDefaultBean, Consumer<MethodCreator> creatorConsumer,
Consumer<MethodCreator> destroyerConsumer, Map<String, Object> params, boolean isRemovable,
boolean forceApplicationClass, String targetPackageName, Integer priority, String identifier) {
boolean forceApplicationClass, String targetPackageName, Integer priority, String identifier,
Set<Type> unrestrictedTypes) {

this.target = Optional.ofNullable(target);
if (implClazz == null && target != null) {
Expand All @@ -126,6 +129,7 @@ public class BeanInfo implements InjectionTargetInfo {
for (Type type : types) {
Beans.analyzeType(type, beanDeployment);
}
this.unrestrictedTypes = unrestrictedTypes != null ? unrestrictedTypes : types;
Beans.addImplicitQualifiers(qualifiers);
this.qualifiers = qualifiers;
this.injections = injections;
Expand Down Expand Up @@ -249,6 +253,15 @@ public Set<Type> getTypes() {
return types;
}

/**
*
* @return the unrestricted set of bean types
* @see Typed
*/
public Set<Type> getUnrestrictedTypes() {
return unrestrictedTypes;
}

public boolean hasType(DotName typeName) {
for (Type type : types) {
if (type.name().equals(typeName)) {
Expand Down Expand Up @@ -1173,7 +1186,7 @@ Builder targetPackageName(String name) {
BeanInfo build() {
return new BeanInfo(implClazz, providerType, target, beanDeployment, scope, types, qualifiers, injections,
declaringBean, disposer, alternative, stereotypes, name, isDefaultBean, creatorConsumer,
destroyerConsumer, params, removable, forceApplicationClass, targetPackageName, priority, identifier);
destroyerConsumer, params, removable, forceApplicationClass, targetPackageName, priority, identifier, null);
}

public Builder forceApplicationClass(boolean forceApplicationClass) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,22 @@ List<BeanInfo> findTypeMatching(Type type) {
return resolved.isEmpty() ? Collections.emptyList() : resolved;
}

List<BeanInfo> findUnrestrictedTypeMatching(TypeAndQualifiers typeAndQualifiers) {
List<BeanInfo> resolved = new ArrayList<>();
for (BeanInfo b : beanDeployment.getBeans()) {
if (!Beans.hasQualifiers(b, typeAndQualifiers.qualifiers)) {
continue;
}
for (Type type : b.getUnrestrictedTypes()) {
if (matches(typeAndQualifiers.type, type)) {
resolved.add(b);
break;
}
}
}
return resolved.isEmpty() ? Collections.emptyList() : resolved;
}

Collection<BeanInfo> potentialBeans(Type type) {
if ((type.kind() == CLASS || type.kind() == PARAMETERIZED_TYPE) && !type.name().equals(DotNames.OBJECT)) {
return beanDeployment.getBeansByRawType(type.name());
Expand Down
Loading

0 comments on commit 2ccc518

Please sign in to comment.