[go: up one dir, main page]

Skip to content

Commit

Permalink
Move Scope to the dagger.model package
Browse files Browse the repository at this point in the history
RELNOTES=n/a

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=179461777
  • Loading branch information
ronshapiro committed Dec 19, 2017
1 parent 00205c8 commit 87435d6
Show file tree
Hide file tree
Showing 26 changed files with 361 additions and 298 deletions.
3 changes: 2 additions & 1 deletion java/dagger/internal/codegen/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ java_library(
"DaggerElements.java",
"DaggerStreams.java",
"DaggerTypes.java",
"DiagnosticFormatting.java",
"Expression.java",
"FeatureStatus.java",
"ForwardingNetwork.java",
Expand All @@ -84,6 +85,7 @@ java_library(
"OptionalType.java",
"Optionals.java",
"RequestKinds.java",
"Scopes.java",
"SetType.java",
"SimpleAnnotationMirror.java",
"SimpleTypeAnnotationValue.java",
Expand Down Expand Up @@ -137,7 +139,6 @@ java_library(
"ProductionBinding.java",
"ProvisionBinding.java",
"ResolvedBindings.java",
"Scope.java",
"SourceFiles.java", # Consider splitting this up?
"SubcomponentDeclaration.java",
],
Expand Down
1 change: 1 addition & 0 deletions java/dagger/internal/codegen/Binding.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import com.google.common.collect.Sets;
import dagger.internal.codegen.BindingType.HasBindingType;
import dagger.model.Key;
import dagger.model.Scope;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import static dagger.internal.codegen.ConfigurationAnnotations.getModuleSubcomponents;
import static dagger.internal.codegen.ContributionBinding.Kind.SYNTHETIC_RELEASABLE_REFERENCE_MANAGER;
import static dagger.internal.codegen.ContributionBinding.Kind.SYNTHETIC_RELEASABLE_REFERENCE_MANAGERS;
import static dagger.internal.codegen.ErrorMessages.stripCommonTypePrefixes;
import static dagger.internal.codegen.DiagnosticFormatting.stripCommonTypePrefixes;
import static dagger.internal.codegen.MoreAnnotationMirrors.simpleName;
import static javax.lang.model.type.TypeKind.DECLARED;
import static javax.lang.model.type.TypeKind.EXECUTABLE;
Expand Down
7 changes: 3 additions & 4 deletions java/dagger/internal/codegen/BindingGraph.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import static dagger.internal.codegen.ContributionBinding.Kind.SYNTHETIC_OPTIONAL_BINDING;
import static dagger.internal.codegen.DaggerStreams.toImmutableSet;
import static dagger.internal.codegen.Keys.indexByKey;
import static dagger.internal.codegen.Scope.reusableScope;
import static dagger.internal.codegen.Util.reentrantComputeIfAbsent;
import static java.util.function.Predicate.isEqual;
import static javax.lang.model.element.Modifier.ABSTRACT;
Expand All @@ -53,6 +52,7 @@
import dagger.internal.codegen.Keys.HasKey;
import dagger.model.Key;
import dagger.model.RequestKind;
import dagger.model.Scope;
import dagger.producers.Produced;
import dagger.producers.Producer;
import dagger.releasablereferences.CanReleaseReferences;
Expand Down Expand Up @@ -794,7 +794,7 @@ private boolean isResolvedInParent(BindingKey bindingKey, ContributionBinding bi
}

private Optional<Resolver> getOwningResolver(ContributionBinding binding) {
if (binding.scope().isPresent() && binding.scope().get().equals(reusableScope(elements))) {
if (binding.scope().isPresent() && binding.scope().get().isReusable()) {
for (Resolver requestResolver : getResolverLineage().reverse()) {
// If a @Reusable binding was resolved in an ancestor, use that component.
if (requestResolver.resolvedBindings.containsKey(
Expand Down Expand Up @@ -1095,8 +1095,7 @@ boolean dependsOnLocalBindings(Binding binding) {
}

private boolean dependsOnLocalBindingsUncached(Binding binding) {
if ((!binding.scope().isPresent()
|| binding.scope().get().equals(reusableScope(elements)))
if ((!binding.scope().isPresent() || binding.scope().get().isReusable())
// TODO(beder): Figure out what happens with production subcomponents.
&& !binding.bindingType().equals(BindingType.PRODUCTION)) {
for (DependencyRequest dependency : binding.dependencies()) {
Expand Down
26 changes: 14 additions & 12 deletions java/dagger/internal/codegen/BindingGraphValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import static dagger.internal.codegen.DaggerElements.getAnnotationMirror;
import static dagger.internal.codegen.DaggerElements.isAnnotationPresent;
import static dagger.internal.codegen.DaggerStreams.toImmutableSet;
import static dagger.internal.codegen.DiagnosticFormatting.stripCommonTypePrefixes;
import static dagger.internal.codegen.ErrorMessages.CANNOT_INJECT_WILDCARD_TYPE;
import static dagger.internal.codegen.ErrorMessages.CONTAINS_DEPENDENCY_CYCLE_FORMAT;
import static dagger.internal.codegen.ErrorMessages.DEPENDS_ON_PRODUCTION_EXECUTOR_FORMAT;
Expand All @@ -59,12 +60,12 @@
import static dagger.internal.codegen.ErrorMessages.referenceReleasingScopeMetadataMissingCanReleaseReferences;
import static dagger.internal.codegen.ErrorMessages.referenceReleasingScopeNotAnnotatedWithMetadata;
import static dagger.internal.codegen.ErrorMessages.referenceReleasingScopeNotInComponentHierarchy;
import static dagger.internal.codegen.ErrorMessages.stripCommonTypePrefixes;
import static dagger.internal.codegen.Keys.isValidImplicitProvisionKey;
import static dagger.internal.codegen.Keys.isValidMembersInjectionKey;
import static dagger.internal.codegen.MoreAnnotationMirrors.getTypeValue;
import static dagger.internal.codegen.Scope.reusableScope;
import static dagger.internal.codegen.Scope.scopesOf;
import static dagger.internal.codegen.Scopes.getReadableSource;
import static dagger.internal.codegen.Scopes.scopesOf;
import static dagger.internal.codegen.Scopes.singletonScope;
import static dagger.internal.codegen.Util.componentCanMakeNewInstances;
import static dagger.internal.codegen.Util.reentrantComputeIfAbsent;
import static java.util.stream.Collectors.groupingBy;
Expand Down Expand Up @@ -98,6 +99,7 @@
import dagger.internal.codegen.ContributionType.HasContributionType;
import dagger.model.Key;
import dagger.model.RequestKind;
import dagger.model.Scope;
import dagger.releasablereferences.CanReleaseReferences;
import dagger.releasablereferences.ForReleasableReferences;
import dagger.releasablereferences.ReleasableReferenceManager;
Expand Down Expand Up @@ -292,7 +294,7 @@ private void validateDependencyScopes(BindingGraph graph) {
ImmutableSet<Scope> scopes = descriptor.scopes();
ImmutableSet<TypeElement> scopedDependencies = scopedTypesIn(descriptor.dependencies());
if (!scopes.isEmpty()) {
Scope singletonScope = Scope.singletonScope(elements);
Scope singletonScope = singletonScope(elements);
// Dagger 1.x scope compatibility requires this be suppress-able.
if (compilerOptions.scopeCycleValidationType().diagnosticKind().isPresent()
&& scopes.contains(singletonScope)) {
Expand All @@ -313,7 +315,7 @@ private void validateDependencyScopes(BindingGraph graph) {
// Scoped components may depend on at most one scoped component.
StringBuilder message = new StringBuilder();
for (Scope scope : scopes) {
message.append(scope.getReadableSource()).append(' ');
message.append(getReadableSource(scope)).append(' ');
}
message
.append(descriptor.componentDefinitionType().getQualifiedName())
Expand Down Expand Up @@ -457,7 +459,7 @@ private void validateDependencyScopeHierarchy(
TypeElement dependency,
Deque<ImmutableSet<Scope>> scopeStack,
Deque<TypeElement> scopedDependencyStack) {
ImmutableSet<Scope> scopes = Scope.scopesOf(dependency);
ImmutableSet<Scope> scopes = scopesOf(dependency);
if (stackOverlaps(scopeStack, scopes)) {
scopedDependencyStack.push(dependency);
// Current scope has already appeared in the component chain.
Expand Down Expand Up @@ -514,7 +516,7 @@ private <T> boolean stackOverlaps(Deque<ImmutableSet<T>> stack, ImmutableSet<T>
private void checkBindingScope(
ContributionBinding binding, ComponentDescriptor owningComponent) {
if (binding.scope().isPresent()
&& !binding.scope().get().equals(reusableScope(elements))
&& !binding.scope().get().isReusable()
&& !owningComponent.scopes().contains(binding.scope().get())) {
incompatiblyScopedBindings.put(owningComponent, binding);
}
Expand All @@ -534,7 +536,7 @@ private void checkScopedBindings(BindingGraph graph) {
if (!graph.componentDescriptor().scopes().isEmpty()) {
message.append(" scoped with ");
for (Scope scope : graph.componentDescriptor().scopes()) {
message.append(scope.getReadableSource()).append(' ');
message.append(getReadableSource(scope)).append(' ');
}
message.append("may not reference bindings with different scopes:\n");
} else {
Expand All @@ -554,7 +556,7 @@ private void checkScopedBindings(BindingGraph graph) {

case INJECTION:
message
.append(binding.scope().get().getReadableSource())
.append(getReadableSource(binding.scope().get()))
.append(" class ")
.append(binding.bindingTypeElement().get().getQualifiedName());
break;
Expand Down Expand Up @@ -954,7 +956,7 @@ private boolean reportMissingReleasableReferenceManager() {
}

Scope scope =
Scope.scope(MoreTypes.asTypeElement(getTypeValue(key.qualifier().get(), "value")));
Scopes.scope(MoreTypes.asTypeElement(getTypeValue(key.qualifier().get(), "value")));
String missingRequestKey = formatCurrentDependencyRequestKey();
if (!rootGraph.componentDescriptor().releasableReferencesScopes().contains(scope)) {
reportErrorAtEntryPoint(
Expand Down Expand Up @@ -1200,8 +1202,8 @@ ValidationReport<TypeElement> validate(BindingGraph graph) {
private void appendIndentedComponentsList(StringBuilder message, Iterable<TypeElement> types) {
for (TypeElement scopedComponent : types) {
message.append(INDENT);
for (Scope scope : Scope.scopesOf(scopedComponent)) {
message.append(scope.getReadableSource()).append(' ');
for (Scope scope : scopesOf(scopedComponent)) {
message.append(getReadableSource(scope)).append(' ');
}
message.append(stripCommonTypePrefixes(scopedComponent.getQualifiedName().toString()))
.append('\n');
Expand Down
7 changes: 5 additions & 2 deletions java/dagger/internal/codegen/ComponentDescriptor.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import static dagger.internal.codegen.DaggerElements.getAnnotationMirror;
import static dagger.internal.codegen.DaggerStreams.toImmutableSet;
import static dagger.internal.codegen.InjectionAnnotations.getQualifier;
import static dagger.internal.codegen.Scopes.productionScope;
import static dagger.internal.codegen.Scopes.scopesOf;
import static javax.lang.model.type.TypeKind.DECLARED;
import static javax.lang.model.type.TypeKind.VOID;

Expand All @@ -50,6 +52,7 @@
import dagger.MembersInjector;
import dagger.Module;
import dagger.Subcomponent;
import dagger.model.Scope;
import dagger.producers.ProductionComponent;
import dagger.producers.ProductionSubcomponent;
import dagger.releasablereferences.CanReleaseReferences;
Expand Down Expand Up @@ -564,9 +567,9 @@ private ComponentDescriptor create(
Optional.ofNullable(getOnlyElement(enclosedBuilders, null));
Optional<BuilderSpec> builderSpec = createBuilderSpec(builderType);

ImmutableSet<Scope> scopes = Scope.scopesOf(componentDefinitionType);
ImmutableSet<Scope> scopes = scopesOf(componentDefinitionType);
if (kind.isProducer()) {
scopes = FluentIterable.from(scopes).append(Scope.productionScope(elements)).toSet();
scopes = FluentIterable.from(scopes).append(productionScope(elements)).toSet();
}

return new AutoValue_ComponentDescriptor(
Expand Down
12 changes: 5 additions & 7 deletions java/dagger/internal/codegen/ComponentHierarchyValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@

import static com.google.common.base.Functions.constant;
import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static dagger.internal.codegen.Scopes.getReadableSource;

import com.google.auto.common.MoreTypes;
import com.google.common.base.Predicate;
Expand All @@ -31,19 +31,17 @@
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import dagger.internal.codegen.ComponentDescriptor.ComponentMethodDescriptor;
import dagger.model.Scope;
import java.util.Map;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;

/** Validates the relationships between parent components and subcomponents. */
final class ComponentHierarchyValidator {
private final CompilerOptions compilerOptions;
private final Elements elements;

ComponentHierarchyValidator(CompilerOptions compilerOptions, Elements elements) {
ComponentHierarchyValidator(CompilerOptions compilerOptions) {
this.compilerOptions = compilerOptions;
this.elements = elements;
}

ValidationReport<TypeElement> validate(ComponentDescriptor componentDescriptor) {
Expand Down Expand Up @@ -120,7 +118,7 @@ private void validateScopeHierarchy(
Predicate<Scope> subjectScopes =
subject.kind().isProducer()
// TODO(beder): validate that @ProductionScope is only applied on production components
? and(in(subject.scopes()), not(equalTo(Scope.productionScope(elements))))
? and(in(subject.scopes()), not(Scope::isProductionScope))
: in(subject.scopes());
SetMultimap<ComponentDescriptor, Scope> overlappingScopes =
Multimaps.filterValues(scopesByComponent, subjectScopes);
Expand All @@ -134,7 +132,7 @@ private void validateScopeHierarchy(
error.append("\n ")
.append(entry.getKey().componentDefinitionType().getQualifiedName())
.append(" also has ")
.append(scope.getReadableSource());
.append(getReadableSource(scope));
}
report.addItem(
error.toString(),
Expand Down
2 changes: 1 addition & 1 deletion java/dagger/internal/codegen/ComponentProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ protected Iterable<? extends ProcessingStep> initSteps() {
CanReleaseReferencesValidator canReleaseReferencesValidator =
new CanReleaseReferencesValidator();
ComponentHierarchyValidator componentHierarchyValidator =
new ComponentHierarchyValidator(compilerOptions, elements);
new ComponentHierarchyValidator(compilerOptions);
BindingGraphValidator bindingGraphValidator =
new BindingGraphValidator(
elements,
Expand Down
4 changes: 2 additions & 2 deletions java/dagger/internal/codegen/DelegateBindingExpression.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@
import static com.google.common.collect.Iterables.getOnlyElement;
import static dagger.internal.codegen.Accessibility.isTypeAccessibleFrom;
import static dagger.internal.codegen.RequestKinds.requestType;
import static dagger.internal.codegen.Scope.reusableScope;

import com.squareup.javapoet.ClassName;
import dagger.model.RequestKind;
import dagger.model.Scope;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;

Expand Down Expand Up @@ -128,7 +128,7 @@ static ScopeKind get(Binding binding, BindingGraph graph, Elements elements) {
if (graph.scopesRequiringReleasableReferenceManagers().contains(scope)) {
return RELEASABLE;
}
return scope.equals(reusableScope(elements)) ? SINGLE_CHECK : DOUBLE_CHECK;
return scope.isReusable() ? SINGLE_CHECK : DOUBLE_CHECK;
}

boolean isSimilarOrWeakerScopeThan(ScopeKind other) {
Expand Down
71 changes: 71 additions & 0 deletions java/dagger/internal/codegen/DiagnosticFormatting.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright (C) 2017 The Dagger Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package dagger.internal.codegen;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Utility methods for formatting diagnostics to the {@link javax.annotation.processing.Messager}.
*/
final class DiagnosticFormatting {

/**
* A regular expression to match a small list of specific packages deemed to be unhelpful to
* display in fully qualified types in error messages.
*
* <p>Note: This should never be applied to messages themselves.
*/
private static final Pattern COMMON_PACKAGE_PATTERN =
Pattern.compile(
"(?:^|[^.a-z_])" // What we want to match on but not capture.
+ "((?:" // Start a group with a non-capturing or part
+ "java[.]lang"
+ "|java[.]util"
+ "|javax[.]inject"
+ "|dagger"
+ "|com[.]google[.]common[.]base"
+ "|com[.]google[.]common[.]collect"
+ ")[.])" // Always end with a literal .
+ "[A-Z]"); // What we want to match on but not capture.

/**
* A method to strip out common packages and a few rare type prefixes from types' string
* representation before being used in error messages.
*
* <p>This type assumes a String value that is a valid fully qualified (and possibly
* parameterized) type, and should NOT be used with arbitrary text, especially prose error
* messages.
*
* <p>TODO(cgruber): Tighten these to take type representations (mirrors and elements) to avoid
* accidental mis-use by running errors through this method.
*/
static String stripCommonTypePrefixes(String type) {
// Do regex magic to remove common packages we care to shorten.
Matcher matcher = COMMON_PACKAGE_PATTERN.matcher(type);
StringBuilder result = new StringBuilder();
int index = 0;
while (matcher.find()) {
result.append(type.subSequence(index, matcher.start(1)));
index = matcher.end(1); // Skip the matched pattern content.
}
result.append(type.subSequence(index, type.length()));
return result.toString();
}

private DiagnosticFormatting() {}
}
Loading

0 comments on commit 87435d6

Please sign in to comment.