List of usage examples for com.google.common.collect ImmutableMap values
public ImmutableCollection<V> values()
From source file:com.facebook.buck.thrift.ThriftLibraryDescription.java
@Override public <A extends ThriftConstructorArg> BuildRule createBuildRule(TargetGraph targetGraph, BuildRuleParams params, BuildRuleResolver resolver, A args) throws NoSuchBuildTargetException { BuildTarget target = params.getBuildTarget(); // Extract the thrift language we're using from our build target. Optional<Map.Entry<Flavor, ThriftLanguageSpecificEnhancer>> enhancerFlavor = enhancers .getFlavorAndValue(target);/*from w w w . ja va 2s . c o m*/ SourcePathResolver pathResolver = new SourcePathResolver(new SourcePathRuleFinder(resolver)); ImmutableMap<String, SourcePath> namedSources = pathResolver.getSourcePathNames(target, "srcs", args.srcs.keySet()); // The dependencies listed in "deps", which should all be of type "ThriftLibrary". ImmutableSortedSet<ThriftLibrary> thriftDeps = resolveThriftDeps(target, resolver.getAllRules(args.deps)); // The unflavored version of this rule is responsible for setting up the the various // build rules to facilitate dependents including it's thrift sources. if (!enhancerFlavor.isPresent()) { // Namespace the thrift files using our target's base path. ImmutableMap.Builder<Path, SourcePath> includesBuilder = ImmutableMap.builder(); for (ImmutableMap.Entry<String, SourcePath> entry : namedSources.entrySet()) { includesBuilder.put(target.getBasePath().resolve(entry.getKey()), entry.getValue()); } ImmutableMap<Path, SourcePath> includes = includesBuilder.build(); // Create the symlink tree build rule and add it to the resolver. Path includeRoot = getIncludeRoot(target, params.getProjectFilesystem()); BuildTarget symlinkTreeTarget = createThriftIncludeSymlinkTreeTarget(target); HeaderSymlinkTree symlinkTree = new HeaderSymlinkTree(params.copyWithChanges(symlinkTreeTarget, Suppliers.ofInstance(ImmutableSortedSet.of()), Suppliers.ofInstance(ImmutableSortedSet.of())), pathResolver, includeRoot, includes); resolver.addToIndex(symlinkTree); // Create a dummy rule that dependents can use to grab the information they need // about this rule from the action graph. return new ThriftLibrary(params, pathResolver, thriftDeps, symlinkTree, includes); } ThriftLanguageSpecificEnhancer enhancer = enhancerFlavor.get().getValue(); String language = enhancer.getLanguage(); ImmutableSet<String> options = enhancer.getOptions(target, args); ImmutableSet<BuildTarget> implicitDeps = enhancer.getImplicitDepsForTargetFromConstructorArg(target, args); // Lookup the thrift library corresponding to this rule. We add an implicit dep onto // this rule in the findImplicitDepsFromParams method, so this should always exist by // the time we get here. ThriftLibrary thriftLibrary = (ThriftLibrary) resolver .getRule(BuildTarget.of(target.getUnflavoredBuildTarget())); // We implicitly pass the language-specific flavors of your thrift lib dependencies as // language specific deps to the language specific enhancer. ImmutableSortedSet<BuildRule> languageSpecificDeps = BuildRules.toBuildRulesFor(target, resolver, Iterables.concat( BuildTargets.propagateFlavorDomains(target, ImmutableList.of(enhancers), FluentIterable.from(thriftDeps).transform(HasBuildTarget::getBuildTarget)), implicitDeps)); // Form the set of generated sources, so that compiler rules know what output paths to record. ImmutableMap.Builder<String, ImmutableSortedSet<String>> generatedSourcesBuilder = ImmutableMap.builder(); for (ImmutableMap.Entry<String, SourcePath> ent : namedSources.entrySet()) { String thriftName = ent.getKey(); ImmutableList<String> services = Preconditions.checkNotNull(args.srcs.get(ent.getValue())); generatedSourcesBuilder.put(thriftName, enhancer.getGeneratedSources(target, args, thriftName, services)); } ImmutableMap<String, ImmutableSortedSet<String>> generatedSources = generatedSourcesBuilder.build(); // Create a a build rule for thrift source file, to compile the language specific sources. // They keys in this map are the logical names of the thrift files (e.g as specific in a BUCK // file, such as "test.thrift"). ImmutableMap<String, ThriftCompiler> compilerRules = createThriftCompilerBuildRules(params, resolver, enhancer.getCompilerType(), args.flags, language, options, namedSources, ImmutableSortedSet.<ThriftLibrary>naturalOrder().add(thriftLibrary) .addAll(getTransitiveThriftLibraryDeps(thriftDeps)).build(), generatedSources); resolver.addAllToIndex(compilerRules.values()); // Build up the map of {@link ThriftSource} objects to pass the language specific enhancer. // They keys in this map are the logical names of the thrift files (e.g as specific in a BUCK // file, such as "test.thrift"). ImmutableMap.Builder<String, ThriftSource> thriftSourceBuilder = ImmutableMap.builder(); for (ImmutableMap.Entry<String, SourcePath> ent : namedSources.entrySet()) { ImmutableList<String> services = Preconditions.checkNotNull(args.srcs.get(ent.getValue())); ThriftCompiler compilerRule = Preconditions.checkNotNull(compilerRules.get(ent.getKey())); thriftSourceBuilder.put(ent.getKey(), new ThriftSource(compilerRule, services, getThriftCompilerOutputDir(params.getProjectFilesystem(), target, ent.getKey()))); } ImmutableMap<String, ThriftSource> thriftSources = thriftSourceBuilder.build(); // Generate language specific rules. return enhancer.createBuildRule(targetGraph, params, resolver, args, thriftSources, languageSpecificDeps); }
From source file:com.facebook.buck.skylark.parser.SkylarkProjectBuildFileParser.java
/** @return The parsed build rules defined in {@code buildFile}. */ private ParseResult parseBuildRules(Path buildFile) throws IOException, BuildFileParseException, InterruptedException { com.google.devtools.build.lib.vfs.Path buildFilePath = fileSystem.getPath(buildFile.toString()); String basePath = getBasePath(buildFile); Label containingLabel = createContainingLabel(basePath); ImplicitlyLoadedExtension implicitLoad = loadImplicitExtension(basePath, containingLabel); BuildFileAST buildFileAst = parseBuildFile(buildFilePath, containingLabel); CachingGlobber globber = newGlobber(buildFile); PackageContext packageContext = createPackageContext(basePath, globber, implicitLoad.getLoadedSymbols()); ParseContext parseContext = new ParseContext(packageContext); try (Mutability mutability = Mutability.create("parsing " + buildFile)) { EnvironmentData envData = createBuildFileEvaluationEnvironment(buildFilePath, containingLabel, buildFileAst, mutability, parseContext, implicitLoad.getExtensionData()); boolean exec = buildFileAst.exec(envData.getEnvironment(), eventHandler); if (!exec) { throw BuildFileParseException.createForUnknownParseError("Cannot evaluate build file " + buildFile); }/*from w w w . jav a 2 s . c o m*/ ImmutableMap<String, ImmutableMap<String, Object>> rules = parseContext.getRecordedRules(); if (LOG.isVerboseEnabled()) { LOG.verbose("Got rules: %s", rules.values()); } LOG.verbose("Parsed %d rules from %s", rules.size(), buildFile); ImmutableList.Builder<String> loadedPaths = ImmutableList .builderWithExpectedSize(envData.getLoadedPaths().size() + 1); loadedPaths.add(buildFilePath.toString()); loadedPaths.addAll(envData.getLoadedPaths()); return ParseResult.of(rules, loadedPaths.build(), parseContext.getAccessedConfigurationOptions(), globber.createGlobManifest()); } }
From source file:com.google.devtools.build.lib.skyframe.SkylarkImportLookupFunction.java
private SkyValue computeInternal(Label fileLabel, boolean inWorkspace, Environment env, @Nullable LinkedHashMap<Label, SkylarkImportLookupValue> alreadyVisited) throws InconsistentFilesystemException, SkylarkImportFailedException, InterruptedException { PathFragment filePath = fileLabel.toPathFragment(); // Load the AST corresponding to this file. ASTFileLookupValue astLookupValue;//from w w w.ja va 2 s . c o m try { SkyKey astLookupKey = ASTFileLookupValue.key(fileLabel); astLookupValue = (ASTFileLookupValue) env.getValueOrThrow(astLookupKey, ErrorReadingSkylarkExtensionException.class, InconsistentFilesystemException.class); } catch (ErrorReadingSkylarkExtensionException e) { throw SkylarkImportFailedException.errorReadingFile(filePath, e.getMessage()); } if (astLookupValue == null) { return null; } if (!astLookupValue.lookupSuccessful()) { // Skylark import files have to exist. throw SkylarkImportFailedException.noFile(astLookupValue.getErrorMsg()); } BuildFileAST ast = astLookupValue.getAST(); if (ast.containsErrors()) { throw SkylarkImportFailedException.skylarkErrors(filePath); } // Process the load statements in the file. ImmutableList<SkylarkImport> imports = ast.getImports(); Map<String, Extension> extensionsForImports = Maps.newHashMapWithExpectedSize(imports.size()); ImmutableList.Builder<SkylarkFileDependency> fileDependencies = ImmutableList.builder(); ImmutableMap<String, Label> labelsForImports; // Find the labels corresponding to the load statements. labelsForImports = findLabelsForLoadStatements(imports, fileLabel, env); if (labelsForImports == null) { return null; } // Look up and load the imports. ImmutableCollection<Label> importLabels = labelsForImports.values(); List<SkyKey> importLookupKeys = Lists.newArrayListWithExpectedSize(importLabels.size()); for (Label importLabel : importLabels) { importLookupKeys.add(SkylarkImportLookupValue.key(importLabel, inWorkspace)); } Map<SkyKey, SkyValue> skylarkImportMap; boolean valuesMissing = false; if (alreadyVisited == null) { // Not inlining. skylarkImportMap = env.getValues(importLookupKeys); valuesMissing = env.valuesMissing(); } else { // Inlining calls to SkylarkImportLookupFunction. if (alreadyVisited.containsKey(fileLabel)) { ImmutableList<Label> cycle = CycleUtils.splitIntoPathAndChain(Predicates.equalTo(fileLabel), alreadyVisited.keySet()).second; throw new SkylarkImportFailedException("Skylark import cycle: " + cycle); } alreadyVisited.put(fileLabel, null); skylarkImportMap = Maps.newHashMapWithExpectedSize(imports.size()); for (SkyKey importLookupKey : importLookupKeys) { SkyValue skyValue = this.computeWithInlineCallsInternal(importLookupKey, env, alreadyVisited); if (skyValue == null) { Preconditions.checkState(env.valuesMissing(), "no skylark import value for %s", importLookupKey); // We continue making inline calls even if some requested values are missing, to maximize // the number of dependent (non-inlined) SkyFunctions that are requested, thus avoiding a // quadratic number of restarts. valuesMissing = true; } else { skylarkImportMap.put(importLookupKey, skyValue); } } // All imports traversed, this key can no longer be part of a cycle. Preconditions.checkState(alreadyVisited.remove(fileLabel) == null, fileLabel); } if (valuesMissing) { // This means some imports are unavailable. return null; } // Process the loaded imports. for (Entry<String, Label> importEntry : labelsForImports.entrySet()) { String importString = importEntry.getKey(); Label importLabel = importEntry.getValue(); SkyKey keyForLabel = SkylarkImportLookupValue.key(importLabel, inWorkspace); SkylarkImportLookupValue importLookupValue = (SkylarkImportLookupValue) skylarkImportMap .get(keyForLabel); extensionsForImports.put(importString, importLookupValue.getEnvironmentExtension()); fileDependencies.add(importLookupValue.getDependency()); } // Skylark UserDefinedFunction-s in that file will share this function definition Environment, // which will be frozen by the time it is returned by createExtension. Extension extension = createExtension(ast, fileLabel, extensionsForImports, env, inWorkspace); SkylarkImportLookupValue result = new SkylarkImportLookupValue(extension, new SkylarkFileDependency(fileLabel, fileDependencies.build())); if (alreadyVisited != null) { alreadyVisited.put(fileLabel, result); } return result; }
From source file:uk.submergedcode.SubmergedCore.serialization.AchievementSerializer.java
public AchievementSerializer() { ImmutableMap<String, Achievement> specialCases = ImmutableMap.<String, Achievement>builder() .put("achievement.buildWorkBench", Achievement.BUILD_WORKBENCH) .put("achievement.diamonds", Achievement.GET_DIAMONDS) .put("achievement.portal", Achievement.NETHER_PORTAL) .put("achievement.ghast", Achievement.GHAST_RETURN) .put("achievement.theEnd", Achievement.END_PORTAL).put("achievement.theEnd2", Achievement.THE_END) .put("achievement.blazeRod", Achievement.GET_BLAZE_ROD) .put("achievement.potion", Achievement.BREW_POTION).build(); ImmutableBiMap.Builder<String, Achievement> builder = ImmutableBiMap.<String, Achievement>builder(); for (Achievement achievement : Achievement.values()) { if (specialCases.values().contains(achievement)) { continue; }//from w ww .j a va2 s . c o m builder.put("achievement." + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, achievement.name()), achievement); } builder.putAll(specialCases); achievements = builder.build(); }
From source file:dagger.internal.codegen.ProducerFactoryGenerator.java
@Override Optional<TypeSpec.Builder> write(ClassName generatedTypeName, ProductionBinding binding) { checkArgument(binding.bindingElement().isPresent()); TypeName providedTypeName = TypeName.get(binding.contributedType()); TypeName futureTypeName = listenableFutureOf(providedTypeName); TypeSpec.Builder factoryBuilder = classBuilder(generatedTypeName).addModifiers(PUBLIC, FINAL) .superclass(abstractProducerOf(providedTypeName)); UniqueNameSet uniqueFieldNames = new UniqueNameSet(); ImmutableMap.Builder<BindingKey, FieldSpec> fieldsBuilder = ImmutableMap.builder(); MethodSpec.Builder constructorBuilder = constructorBuilder().addModifiers(PUBLIC); Optional<FieldSpec> moduleField = binding.requiresModuleInstance() ? Optional.of(addFieldAndConstructorParameter(factoryBuilder, constructorBuilder, uniqueFieldNames.getUniqueName("module"), TypeName.get(binding.bindingTypeElement().get().asType()))) : Optional.empty();// ww w . ja v a 2s. c o m for (Map.Entry<BindingKey, FrameworkField> entry : generateBindingFieldsForDependencies(binding) .entrySet()) { BindingKey bindingKey = entry.getKey(); FrameworkField bindingField = entry.getValue(); FieldSpec field = addFieldAndConstructorParameter(factoryBuilder, constructorBuilder, uniqueFieldNames.getUniqueName(bindingField.name()), bindingField.type()); fieldsBuilder.put(bindingKey, field); } ImmutableMap<BindingKey, FieldSpec> fields = fieldsBuilder.build(); constructorBuilder.addStatement("super($N, $L)", fields.get(binding.monitorRequest().get().bindingKey()), producerTokenConstruction(generatedTypeName, binding)); if (binding.requiresModuleInstance()) { assignField(constructorBuilder, moduleField.get()); } for (FieldSpec field : fields.values()) { assignField(constructorBuilder, field); } MethodSpec.Builder computeMethodBuilder = methodBuilder("compute").returns(futureTypeName) .addAnnotation(Override.class).addModifiers(PROTECTED); ImmutableList<DependencyRequest> asyncDependencies = asyncDependencies(binding); for (DependencyRequest dependency : asyncDependencies) { TypeName futureType = listenableFutureOf(asyncDependencyType(dependency)); CodeBlock futureAccess = CodeBlock.of("$N.get()", fields.get(dependency.bindingKey())); computeMethodBuilder.addStatement("$T $L = $L", futureType, dependencyFutureName(dependency), dependency.kind().equals(DependencyRequest.Kind.PRODUCED) ? CodeBlock.of("$T.createFutureProduced($L)", PRODUCERS, futureAccess) : futureAccess); } FutureTransform futureTransform = FutureTransform.create(fields, binding, asyncDependencies); computeMethodBuilder.addStatement("return $T.transformAsync($L, this, this)", FUTURES, futureTransform.futureCodeBlock()); factoryBuilder .addSuperinterface( ParameterizedTypeName.get(ASYNC_FUNCTION, futureTransform.applyArgType(), providedTypeName)) .addSuperinterface(EXECUTOR); MethodSpec.Builder applyMethodBuilder = methodBuilder("apply").returns(futureTypeName) .addJavadoc("@deprecated this may only be called from the internal {@link #compute()}") .addAnnotation(Deprecated.class).addAnnotation(Override.class).addModifiers(PUBLIC) .addParameter(futureTransform.applyArgType(), futureTransform.applyArgName()) .addExceptions(getThrownTypeNames(binding.thrownTypes())) .addStatement("assert monitor != null : $S", "apply() may only be called internally from compute(); " + "if it's called explicitly, the monitor might be null") .addCode(getInvocationCodeBlock(generatedTypeName, binding, providedTypeName, futureTransform.parameterCodeBlocks())); if (futureTransform.hasUncheckedCast()) { applyMethodBuilder.addAnnotation(AnnotationSpecs.suppressWarnings(UNCHECKED)); } MethodSpec.Builder executeMethodBuilder = methodBuilder("execute").addModifiers(PUBLIC) .addJavadoc("@deprecated this may only be called from the internal {@link #compute()}") .addAnnotation(Deprecated.class).addAnnotation(Override.class).addParameter(RUNNABLE, "runnable") .addStatement("assert monitor != null : $S", "execute() may only be called internally from compute(); " + "if it's called explicitly, the monitor might be null") .addStatement("monitor.ready()").addStatement("executorProvider.get().execute(runnable)"); factoryBuilder.addMethod(constructorBuilder.build()); factoryBuilder.addMethod(computeMethodBuilder.build()); factoryBuilder.addMethod(applyMethodBuilder.build()); factoryBuilder.addMethod(executeMethodBuilder.build()); gwtIncompatibleAnnotation(binding).ifPresent(factoryBuilder::addAnnotation); // TODO(gak): write a sensible toString return Optional.of(factoryBuilder); }
From source file:org.elasticsearch.index.store.Store.java
public void writeChecksums() throws IOException { ensureOpen();//from w w w.j a va 2 s . com ImmutableMap<String, StoreFileMetaData> files = list(); String checksumName = CHECKSUMS_PREFIX + System.currentTimeMillis(); synchronized (mutex) { Map<String, String> checksums = new HashMap<>(); for (StoreFileMetaData metaData : files.values()) { if (metaData.checksum() != null) { checksums.put(metaData.name(), metaData.checksum()); } } while (directory.fileExists(checksumName)) { checksumName = CHECKSUMS_PREFIX + System.currentTimeMillis(); } try (IndexOutput output = directory.createOutput(checksumName, IOContext.DEFAULT, true)) { output.writeInt(0); // version output.writeStringStringMap(checksums); } } for (StoreFileMetaData metaData : files.values()) { if (metaData.name().startsWith(CHECKSUMS_PREFIX) && !checksumName.equals(metaData.name())) { try { directory.deleteFileChecksum(metaData.name()); } catch (Throwable e) { // ignore } } } }
From source file:com.facebook.buck.apple.AppleTestDescription.java
private TestHostInfo createTestHostInfo(BuildRuleParams params, BuildRuleResolver resolver, BuildTarget testHostAppBuildTarget, AppleDebugFormat debugFormat, Iterable<Flavor> additionalFlavors, ImmutableList<CxxPlatform> cxxPlatforms) throws NoSuchBuildTargetException { BuildRule rule = resolver.requireRule(BuildTarget.builder(testHostAppBuildTarget) .addAllFlavors(additionalFlavors).addFlavors(debugFormat.getFlavor()) .addFlavors(StripStyle.NON_GLOBAL_SYMBOLS.getFlavor()).build()); if (!(rule instanceof AppleBundle)) { throw new HumanReadableException("Apple test rule '%s' has test_host_app '%s' not of type '%s'.", params.getBuildTarget(), testHostAppBuildTarget, Description.getBuildRuleType(AppleBundleDescription.class)); }/*from www.j a v a2 s . c o m*/ AppleBundle testHostApp = (AppleBundle) rule; SourcePath testHostAppBinarySourcePath = new BuildTargetSourcePath( testHostApp.getBinaryBuildRule().getBuildTarget()); ImmutableMap<BuildTarget, NativeLinkable> roots = NativeLinkables .getNativeLinkableRoots(testHostApp.getBinary().get().getDeps(), x -> true); // Union the blacklist of all the platforms. This should give a superset for each particular // platform, which should be acceptable as items in the blacklist thare are unmatched are simply // ignored. ImmutableSet.Builder<BuildTarget> blacklistBuilder = ImmutableSet.builder(); for (CxxPlatform platform : cxxPlatforms) { blacklistBuilder .addAll(NativeLinkables.getTransitiveNativeLinkables(platform, roots.values()).keySet()); } return TestHostInfo.of(testHostApp, testHostAppBinarySourcePath, blacklistBuilder.build()); }
From source file:org.terasology.assets.module.ModuleAwareAssetTypeManager.java
/** * Switches the module environment. This triggers: * <ul>/* w w w . j av a 2s.c o m*/ * <li>Removal of all extension types, producers and formats</li> * <li>Disposal of all assets not present in the new environment</li> * <li>Reload of all assets present in the new environment</li> * <li>Scan for and install extension asset types, producers and formats</li> * <li>Makes available loading assets from the new environment</li> * </ul> * * @param newEnvironment The new module environment */ public synchronized void switchEnvironment(ModuleEnvironment newEnvironment) { Preconditions.checkNotNull(newEnvironment); if (watcher != null) { try { watcher.shutdown(); } catch (IOException e) { logger.error("Failed to shut down watch service", e); } } try { watcher = new ModuleWatcher(newEnvironment); } catch (IOException e) { logger.warn("Failed to establish watch service, will not auto-reload changed assets", e); } for (AssetType<?, ?> assetType : assetTypes.values()) { assetType.clearProducers(); } ListMultimap<Class<? extends AssetData>, AssetFileFormat<?>> extensionFileFormats = scanForExtensionFormats( newEnvironment); ListMultimap<Class<? extends AssetData>, AssetAlterationFileFormat<?>> extensionSupplementalFormats = scanForExtensionSupplementalFormats( newEnvironment); ListMultimap<Class<? extends AssetData>, AssetAlterationFileFormat<?>> extensionDeltaFormats = scanForExtensionDeltaFormats( newEnvironment); ResolutionStrategy resolutionStrategy = new ModuleDependencyResolutionStrategy(newEnvironment); Map<Class<? extends Asset>, AssetType<?, ?>> newAssetTypes = Maps.newHashMap(); setupCoreAssetTypes(newEnvironment, extensionFileFormats, extensionSupplementalFormats, extensionDeltaFormats, resolutionStrategy, newAssetTypes); setupExtensionAssetTypes(newEnvironment, extensionFileFormats, extensionSupplementalFormats, extensionDeltaFormats, resolutionStrategy, newAssetTypes); scanForExtensionProducers(newEnvironment, newAssetTypes); ImmutableMap<Class<? extends Asset>, AssetType<?, ?>> oldAssetTypes = assetTypes; assetTypes = ImmutableMap.copyOf(newAssetTypes); for (AssetType<?, ?> assetType : assetTypes.values()) { if (reloadOnSwitchAssetTypes.contains(assetType.getAssetClass())) { assetType.refresh(); } else { assetType.disposeAll(); } } oldAssetTypes.values().stream().filter(assetType -> !coreAssetTypes.contains(assetType)) .forEach(assetType -> assetType.close()); updateSubtypesMap(); }
From source file:org.elasticsearch.repositories.blobstore.BlobStoreRepository.java
/** * {@inheritDoc}/*from w w w .j a v a 2 s .c o m*/ */ @Override public ImmutableList<SnapshotId> snapshots() { try { List<SnapshotId> snapshots = newArrayList(); ImmutableMap<String, BlobMetaData> blobs; try { blobs = snapshotsBlobContainer.listBlobsByPrefix(SNAPSHOT_PREFIX); } catch (UnsupportedOperationException ex) { // Fall back in case listBlobsByPrefix isn't supported by the blob store return readSnapshotList(); } int prefixLength = SNAPSHOT_PREFIX.length(); for (BlobMetaData md : blobs.values()) { String name = md.name().substring(prefixLength); snapshots.add(new SnapshotId(repositoryName, name)); } return ImmutableList.copyOf(snapshots); } catch (IOException ex) { throw new RepositoryException(repositoryName, "failed to list snapshots in repository", ex); } }
From source file:dagger2.internal.codegen.BindingGraphValidator.java
/** * Validates that the scope (if any) of this component are compatible with the scopes of the * bindings available in this component//from www .j a v a 2 s .co m */ void validateComponentScope(final BindingGraph subject, final ValidationReport.Builder<BindingGraph> reportBuilder, ImmutableMap<BindingKey, ResolvedBindings> resolvedBindings) { Optional<Equivalence.Wrapper<AnnotationMirror>> componentScope = subject.componentDescriptor() .wrappedScope(); ImmutableSet.Builder<String> incompatiblyScopedMethodsBuilder = ImmutableSet.builder(); for (ResolvedBindings bindings : resolvedBindings.values()) { if (bindings.bindingKey().kind().equals(BindingKey.Kind.CONTRIBUTION)) { for (ContributionBinding contributionBinding : bindings.ownedContributionBindings()) { if (contributionBinding instanceof ProvisionBinding) { ProvisionBinding provisionBinding = (ProvisionBinding) contributionBinding; if (provisionBinding.scope().isPresent() && !componentScope.equals(provisionBinding.wrappedScope())) { // Scoped components cannot reference bindings to @Provides methods or @Inject // types decorated by a different scope annotation. Unscoped components cannot // reference to scoped @Provides methods or @Inject types decorated by any // scope annotation. switch (provisionBinding.bindingKind()) { case PROVISION: ExecutableElement provisionMethod = MoreElements .asExecutable(provisionBinding.bindingElement()); incompatiblyScopedMethodsBuilder .add(methodSignatureFormatter.format(provisionMethod)); break; case INJECTION: incompatiblyScopedMethodsBuilder .add(stripCommonTypePrefixes(provisionBinding.scope().get().toString()) + " class " + provisionBinding.bindingTypeElement().getQualifiedName()); break; default: throw new IllegalStateException(); } } } } } } ImmutableSet<String> incompatiblyScopedMethods = incompatiblyScopedMethodsBuilder.build(); if (!incompatiblyScopedMethods.isEmpty()) { TypeElement componentType = subject.componentDescriptor().componentDefinitionType(); StringBuilder message = new StringBuilder(componentType.getQualifiedName()); if (componentScope.isPresent()) { message.append(" scoped with "); message.append(stripCommonTypePrefixes(ErrorMessages.format(componentScope.get().get()))); message.append(" may not reference bindings with different scopes:\n"); } else { message.append(" (unscoped) may not reference scoped bindings:\n"); } for (String method : incompatiblyScopedMethods) { message.append(ErrorMessages.INDENT).append(method).append("\n"); } reportBuilder.addItem(message.toString(), componentType, subject.componentDescriptor().componentAnnotation()); } }