com.google.common.collect.ImmutableSet#contains ( )源码实例Demo

下面列出了com.google.common.collect.ImmutableSet#contains ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: bistoury   文件: AdminAppServiceImpl.java
@Override
public List<String> searchApps(String keyInput, int size) {
	final String key = Strings.nullToEmpty(keyInput).toLowerCase();
	ImmutableSet<String> adminApps = this.adminApps;
	if (Strings.isNullOrEmpty(key)) {
		return adminApps.asList().subList(0, size);
	}

	int needAddSize = size;
	List<String> matchApps = new ArrayList<>(size);
	if (adminApps.contains(key)) {
		matchApps.add(key);
		needAddSize--;
	}

	adminApps.stream()
			.filter((app) -> app.contains(key) && !app.equals(key))
			.limit(needAddSize)
			.forEach(matchApps::add);
	return matchApps;
}
 
源代码2 项目: CombatLogX   文件: HookBSkyBlock.java
@Override
public boolean doesTeamMatch(Player player1, Player player2) {
    if(player1 == null || player2 == null) return false;

    World world1 = player1.getWorld();
    World world2 = player2.getWorld();
    UUID worldId1 = world1.getUID();
    UUID worldId2 = world2.getUID();
    if(!worldId1.equals(worldId2)) return false;

    UUID uuid1 = player1.getUniqueId();
    UUID uuid2 = player2.getUniqueId();
    if(uuid1.equals(uuid2)) return true;

    Island island = getIslandFor(player1);
    ImmutableSet<UUID> memberSet = island.getMemberSet();
    return memberSet.contains(uuid2);
}
 
源代码3 项目: intellij   文件: QueryResultLineProcessorTest.java
@Test
public void testFilterRuleTypes() {
  ImmutableSet<String> acceptedRuleTypes =
      ImmutableSet.of("java_library", "custom_type", "sh_test");
  BlazeQueryLabelKindParser processor =
      new BlazeQueryLabelKindParser(t -> acceptedRuleTypes.contains(t.ruleType));

  processor.processLine("css_library rule //java/com/google/foo/styles:global");
  processor.processLine("java_library rule //java/com/google/bar/console:runtime_deps");
  processor.processLine("java_test rule //java/com/google/bar/console:test1");
  processor.processLine("test_suite rule //java/com/google/bar/console:all_tests");
  processor.processLine("custom_type rule //java/com/google/bar/console:custom");
  processor.processLine("sh_test rule //java/com/google/bar/console:sh_test");

  ImmutableList<TargetInfo> targets = processor.getTargets();
  assertThat(targets)
      .containsExactly(
          TargetInfo.builder(
                  Label.create("//java/com/google/bar/console:runtime_deps"), "java_library")
              .build(),
          TargetInfo.builder(Label.create("//java/com/google/bar/console:custom"), "custom_type")
              .build(),
          TargetInfo.builder(Label.create("//java/com/google/bar/console:sh_test"), "sh_test")
              .build());
}
 
源代码4 项目: buck   文件: MacroFinder.java
public static ImmutableList<MacroMatchResult> findAll(ImmutableSet<String> macros, String blob)
    throws MacroException {

  ImmutableList.Builder<MacroMatchResult> results = ImmutableList.builder();
  MacroFinderAutomaton matcher = new MacroFinderAutomaton(blob);
  while (matcher.hasNext()) {
    MacroMatchResult matchResult = matcher.next();
    if (matchResult.isEscaped()) {
      continue;
    }
    if (!macros.contains(matchResult.getMacroType())) {
      throw new MacroException(String.format("no such macro \"%s\"", matchResult.getMacroType()));
    }
    results.add(matchResult);
  }

  return results.build();
}
 
源代码5 项目: n4js   文件: TokenTypeRewriter.java
private static void rewriteIdentifiers(N4JSGrammarAccess ga,
		ImmutableMap.Builder<AbstractElement, Integer> builder) {
	ImmutableSet<AbstractRule> identifierRules = ImmutableSet.of(
			ga.getBindingIdentifierRule(),
			ga.getIdentifierNameRule(),
			ga.getIDENTIFIERRule());
	for (ParserRule rule : GrammarUtil.allParserRules(ga.getGrammar())) {
		for (EObject obj : EcoreUtil2.eAllContents(rule.getAlternatives())) {
			if (obj instanceof Assignment) {
				Assignment assignment = (Assignment) obj;
				AbstractElement terminal = assignment.getTerminal();
				int type = InternalN4JSParser.RULE_IDENTIFIER;
				if (terminal instanceof CrossReference) {
					terminal = ((CrossReference) terminal).getTerminal();
					type = IDENTIFIER_REF_TOKEN;
				}
				if (terminal instanceof RuleCall) {
					AbstractRule calledRule = ((RuleCall) terminal).getRule();
					if (identifierRules.contains(calledRule)) {
						builder.put(assignment, type);
					}
				}
			}
		}
	}
}
 
源代码6 项目: turbine   文件: DisambiguateTypeAnnotations.java
/**
 * Moves type annotations in {@code annotations} to {@code type}, and adds any declaration
 * annotations on {@code type} to {@code declarationAnnotations}.
 */
private static Type disambiguate(
    Env<ClassSymbol, TypeBoundClass> env,
    TurbineElementType declarationTarget,
    Type type,
    ImmutableList<AnnoInfo> annotations,
    ImmutableList.Builder<AnnoInfo> declarationAnnotations) {
  // desugar @Repeatable annotations before disambiguating: annotation containers may target
  // a subset of the types targeted by their element annotation
  annotations = groupRepeated(env, annotations);
  ImmutableList.Builder<AnnoInfo> typeAnnotations = ImmutableList.builder();
  for (AnnoInfo anno : annotations) {
    ImmutableSet<TurbineElementType> target = getTarget(env, anno);
    if (target.contains(TurbineElementType.TYPE_USE)) {
      typeAnnotations.add(anno);
    }
    if (target.contains(declarationTarget)) {
      declarationAnnotations.add(anno);
    }
  }
  return addAnnotationsToType(type, typeAnnotations.build());
}
 
源代码7 项目: guava-probably   文件: CuckooFilterTest.java
@Test
public void createAndCheckBealDupras32CuckooFilterWithKnownUtf8FalsePositives() {
  int numInsertions = 1000000;
  CuckooFilter<String> cf = CuckooFilter.create(
      Funnels.stringFunnel(UTF_8), numInsertions, 0.03,
      CuckooStrategies.MURMUR128_BEALDUPRAS_32.strategy());

  // Insert "numInsertions" even numbers into the CF.
  for (int i = 0; i < numInsertions * 2; i += 2) {
    cf.add(Integer.toString(i));
  }

  // Assert that the CF "might" have all of the even numbers.
  for (int i = 0; i < numInsertions * 2; i += 2) {
    assertTrue(cf.contains(Integer.toString(i)));
  }

  // Now we check for known false positives using a set of known false positives.
  // (These are all of the false positives under 900.)
  ImmutableSet<Integer> falsePositives =
      ImmutableSet.of(5, 315, 389, 443, 445, 615, 621, 703, 789, 861, 899);
  for (int i = 1; i < 900; i += 2) {
    if (!falsePositives.contains(i)) {
      assertFalse("CF should not contain " + i, cf.contains(Integer.toString(i)));
    }
  }

  // Check that there are exactly 26610 false positives for this CF.
  int expectedNumFpp = 26610;
  int actualNumFpp = 0;
  for (int i = 1; i < numInsertions * 2; i += 2) {
    if (cf.contains(Integer.toString(i))) {
      actualNumFpp++;
    }
  }
  assertEquals(expectedNumFpp, actualNumFpp);
  // The normal order of (expected, actual) is reversed here on purpose.
  assertEquals((double) expectedNumFpp / numInsertions, cf.currentFpp(), 0.0004);
}
 
private List<Root> checkValidDirectoryAndGetRoots(
    RepositoryName repository,
    PathFragment directory,
    ImmutableSet<PathFragment> ignoredSubdirectories,
    ImmutableSet<PathFragment> excludedSubdirectories)
    throws InterruptedException {
  if (ignoredSubdirectories.contains(directory) || excludedSubdirectories.contains(directory)) {
    return ImmutableList.of();
  }

  // Check that this package is covered by at least one of our universe patterns.
  boolean inUniverse = false;
  for (TargetPattern pattern : universeTargetPatterns) {
    boolean isTBD = pattern.getType().equals(TargetPattern.Type.TARGETS_BELOW_DIRECTORY);
    PackageIdentifier packageIdentifier = PackageIdentifier.create(repository, directory);
    if (isTBD && pattern.containsAllTransitiveSubdirectoriesForTBD(packageIdentifier)) {
      inUniverse = true;
      break;
    }
  }

  if (!inUniverse) {
    return ImmutableList.of();
  }

  List<Root> roots = new ArrayList<>();
  if (repository.isMain()) {
    roots.addAll(pkgRoots);
  } else {
    RepositoryDirectoryValue repositoryValue =
        (RepositoryDirectoryValue) graph.getValue(RepositoryDirectoryValue.key(repository));
    if (repositoryValue == null || !repositoryValue.repositoryExists()) {
      // If this key doesn't exist, the repository is outside the universe, so we return
      // "nothing".
      return ImmutableList.of();
    }
    roots.add(Root.fromPath(repositoryValue.getPath()));
  }
  return roots;
}
 
源代码9 项目: sawmill   文件: FieldTypeCondition.java
public FieldTypeCondition(String path, String type) {
    if (path == null) {
        throw new ProcessorConfigurationException("failed to parse fieldType condition, could not resolve field path");
    }

    if (type == null) {
        throw new ProcessorConfigurationException("failed to parse fieldType condition, could not resolve field type");
    }

    ImmutableSet<String> supportedTypes = typeEvaluators.keySet();
    if (!supportedTypes.contains(type.toLowerCase())) throw new ProcessorConfigurationException("type ["+type+"] must be one of " + supportedTypes);

    this.path = path;
    this.typePredicate = typeEvaluators.get(type.toLowerCase());
}
 
源代码10 项目: bundletool   文件: ExtractApksCommand.java
static ImmutableSet<String> resolveRequestedModules(
    ImmutableSet<String> requestedModules, BuildApksResult toc) {
  return requestedModules.contains(ALL_MODULES_SHORTCUT)
      ? Stream.concat(
              toc.getVariantList().stream()
                  .flatMap(variant -> variant.getApkSetList().stream())
                  .map(apkSet -> apkSet.getModuleMetadata().getName()),
              toc.getAssetSliceSetList().stream()
                  .map(AssetSliceSet::getAssetModuleMetadata)
                  .map(AssetModuleMetadata::getName))
          .collect(toImmutableSet())
      : requestedModules;
}
 
源代码11 项目: nomulus   文件: HostCheckFlow.java
@Override
public final EppResponse run() throws EppException {
  extensionManager.validate();  // There are no legal extensions for this flow.
  validateClientIsLoggedIn(clientId);
  ImmutableList<String> hostnames = ((Check) resourceCommand).getTargetIds();
  verifyTargetIdCount(hostnames, maxChecks);
  ImmutableSet<String> existingIds =
      checkResourcesExist(HostResource.class, hostnames, clock.nowUtc());
  ImmutableList.Builder<HostCheck> checks = new ImmutableList.Builder<>();
  for (String hostname : hostnames) {
    boolean unused = !existingIds.contains(hostname);
    checks.add(HostCheck.create(unused, hostname, unused ? null : "In use"));
  }
  return responseBuilder.setResData(HostCheckData.create(checks.build())).build();
}
 
源代码12 项目: markdown-doclet   文件: OptionProcessor.java
static OptionProcessor verifyName(Collection<String> names, OptionProcessor processor) {
    ImmutableSet<String> immutableNames = ImmutableSet.copyOf(names);
    return (name, arguments) -> {
        if (!immutableNames.contains(name)) {
            throw new InvalidOptionArgumentsException("Unexpected option name: '" + name + "'");
        }
        processor.process(name, arguments);
    };
}
 
源代码13 项目: bazel   文件: BazelTestSuiteBuilder.java
@Override
public boolean apply(Class<?> testClass) {
  ImmutableSet<OS> supportedOs = ImmutableSet.copyOf(Suite.getSupportedOs(testClass));
  return supportedOs.isEmpty() || supportedOs.contains(OS.getCurrent());
}
 
源代码14 项目: bazel   文件: ObjcVariablesExtension.java
public ObjcVariablesExtension build() {

      ImmutableSet<VariableCategory> activeVariableCategories =
          activeVariableCategoriesBuilder.build();

      Preconditions.checkNotNull(ruleContext, "missing RuleContext");
      Preconditions.checkNotNull(buildConfiguration, "missing BuildConfiguration");
      Preconditions.checkNotNull(intermediateArtifacts, "missing IntermediateArtifacts");
      if (activeVariableCategories.contains(VariableCategory.ARCHIVE_VARIABLES)) {
        Preconditions.checkNotNull(compilationArtifacts, "missing CompilationArtifacts");
      }
      if (activeVariableCategories.contains(VariableCategory.FULLY_LINK_VARIABLES)) {
        Preconditions.checkNotNull(objcProvider, "missing ObjcProvider");
        Preconditions.checkNotNull(fullyLinkArchive, "missing fully-link archive");
      }
      if (activeVariableCategories.contains(VariableCategory.EXECUTABLE_LINKING_VARIABLES)) {
        Preconditions.checkNotNull(objcProvider, "missing ObjcProvider");
        Preconditions.checkNotNull(frameworkSearchPaths, "missing FrameworkSearchPaths");
        Preconditions.checkNotNull(frameworkNames, "missing framework names");
        Preconditions.checkNotNull(libraryNames, "missing library names");
        Preconditions.checkNotNull(forceLoadArtifacts, "missing force-load artifacts");
        Preconditions.checkNotNull(attributeLinkopts, "missing attribute linkopts");
      }
      if (activeVariableCategories.contains(VariableCategory.DSYM_VARIABLES)) {
        Preconditions.checkNotNull(dsymSymbol, "missing dsym symbol artifact");
      }
      if (activeVariableCategories.contains(VariableCategory.LINKMAP_VARIABLES)) {
        Preconditions.checkNotNull(linkmap, "missing linkmap artifact");
      }
      if (activeVariableCategories.contains(VariableCategory.BITCODE_VARIABLES)) {
        Preconditions.checkNotNull(bitcodeSymbolMap, "missing bitcode symbol map artifact");
      }

      return new ObjcVariablesExtension(
          ruleContext,
          objcProvider,
          compilationArtifacts,
          fullyLinkArchive,
          intermediateArtifacts,
          buildConfiguration,
          frameworkSearchPaths,
          frameworkNames,
          libraryNames,
          forceLoadArtifacts,
          attributeLinkopts,
          activeVariableCategories,
          dsymSymbol,
          linkmap,
          bitcodeSymbolMap,
          arcEnabled);
    }
 
源代码15 项目: buck   文件: HalideLibraryDescription.java
@Override
public BuildRule createBuildRule(
    BuildRuleCreationContextWithTargetGraph context,
    BuildTarget buildTarget,
    BuildRuleParams params,
    HalideLibraryDescriptionArg args) {
  CxxPlatformsProvider cxxPlatformsProvider =
      getCxxPlatformsProvider(buildTarget.getTargetConfiguration());
  FlavorDomain<UnresolvedCxxPlatform> cxxPlatforms =
      cxxPlatformsProvider.getUnresolvedCxxPlatforms();

  ActionGraphBuilder graphBuilder = context.getActionGraphBuilder();
  args.checkDuplicateSources(graphBuilder.getSourcePathResolver());
  ImmutableSet<Flavor> flavors = ImmutableSet.copyOf(buildTarget.getFlavors().getSet());
  // TODO(cjhopman): This description doesn't handle parse time deps correctly.
  CxxPlatform cxxPlatform =
      cxxPlatforms
          .getValue(flavors)
          .orElse(cxxPlatformsProvider.getDefaultUnresolvedCxxPlatform())
          .resolve(graphBuilder, buildTarget.getTargetConfiguration());
  ProjectFilesystem projectFilesystem = context.getProjectFilesystem();

  if (flavors.contains(CxxDescriptionEnhancer.EXPORTED_HEADER_SYMLINK_TREE_FLAVOR)) {
    ImmutableMap.Builder<Path, SourcePath> headersBuilder = ImmutableMap.builder();
    BuildTarget compileTarget =
        graphBuilder
            .requireRule(buildTarget.withFlavors(HALIDE_COMPILE_FLAVOR, cxxPlatform.getFlavor()))
            .getBuildTarget();
    Path outputPath =
        HalideCompile.headerOutputPath(compileTarget, projectFilesystem, args.getFunctionName());
    headersBuilder.put(
        outputPath.getFileName(), ExplicitBuildTargetSourcePath.of(compileTarget, outputPath));
    return CxxDescriptionEnhancer.createHeaderSymlinkTree(
        buildTarget,
        projectFilesystem,
        graphBuilder,
        cxxPlatform,
        headersBuilder.build(),
        HeaderVisibility.PUBLIC,
        true);
  } else if (flavors.contains(HALIDE_COMPILER_FLAVOR)) {
    // We always want to build the halide "compiler" for the host platform, so
    // we use the host flavor here, regardless of the flavors on the build
    // target.
    CxxPlatform hostCxxPlatform =
        cxxPlatforms
            .getValue(CxxPlatforms.getHostFlavor())
            .resolve(graphBuilder, buildTarget.getTargetConfiguration());
    ImmutableSortedSet<BuildTarget> compilerDeps = args.getCompilerDeps();
    return createHalideCompiler(
        buildTarget,
        projectFilesystem,
        params.withDeclaredDeps(graphBuilder.getAllRules(compilerDeps)).withoutExtraDeps(),
        graphBuilder,
        context.getCellPathResolver(),
        cxxPlatformsProvider,
        hostCxxPlatform,
        args.getSrcs(),
        args.getCompilerFlags(),
        args.getPlatformCompilerFlags(),
        args.getLangCompilerFlags(),
        args.getLinkerFlags(),
        args.getPlatformLinkerFlags(),
        args.getRawHeaders(),
        args.getIncludeDirectories());
  } else if (flavors.contains(CxxDescriptionEnhancer.STATIC_FLAVOR)
      || flavors.contains(CxxDescriptionEnhancer.STATIC_PIC_FLAVOR)) {
    // Halide always output PIC, so it's output can be used for both cases.
    // See: https://github.com/halide/Halide/blob/e3c301f3/src/LLVM_Output.cpp#L152
    return createHalideStaticLibrary(
        buildTarget, projectFilesystem, params, graphBuilder, cxxPlatform, args);
  } else if (flavors.contains(CxxDescriptionEnhancer.SHARED_FLAVOR)) {
    throw new HumanReadableException(
        "halide_library '%s' does not support shared libraries as output", buildTarget);
  } else if (flavors.contains(HALIDE_COMPILE_FLAVOR)) {
    return createHalideCompile(
        buildTarget,
        projectFilesystem,
        params.withoutDeclaredDeps().withoutExtraDeps(),
        graphBuilder,
        cxxPlatform,
        Optional.of(args.getCompilerInvocationFlags()),
        args.getFunctionName());
  }

  return new HalideLibrary(
      buildTarget, projectFilesystem, params, graphBuilder, args.getSupportedPlatformsRegex());
}
 
源代码16 项目: bundletool   文件: ModuleTitleValidator.java
private static void checkModuleTitles(ImmutableList<BundleModule> modules) {
  if (BundleValidationUtils.isAssetOnlyBundle(modules)) {
    return;
  }

  BundleModule baseModule = modules.stream().filter(BundleModule::isBaseModule).findFirst().get();

  // For bundles built using older versions we haven't strictly enforced module Title Validation.
  Version bundleVersion =
      BundleToolVersion.getVersionFromBundleConfig(baseModule.getBundleConfig());
  if (!MODULE_TITLE_VALIDATION_ENFORCED.enabledForVersion(bundleVersion)) {
    return;
  }
  ResourceTable table = baseModule.getResourceTable().orElse(ResourceTable.getDefaultInstance());

  ImmutableSet<Integer> stringResourceIds =
      entries(table)
          .filter(entry -> entry.getType().getName().equals("string"))
          .map(entry -> entry.getResourceId().getFullResourceId())
          .collect(toImmutableSet());

  for (BundleModule module : modules) {
    if (module.getModuleType().equals(ModuleType.ASSET_MODULE)) {
      if (module.getAndroidManifest().getTitleRefId().isPresent()) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "Module titles not supported in asset packs, but found in '%s'.",
                module.getName())
            .build();
      }
    } else if (!module.getDeliveryType().equals(ModuleDeliveryType.ALWAYS_INITIAL_INSTALL)) {
      Optional<Integer> titleRefId = module.getAndroidManifest().getTitleRefId();

      if (!titleRefId.isPresent()) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "Mandatory title is missing in manifest for module '%s'.", module.getName())
            .build();
      }
      if (!stringResourceIds.contains(titleRefId.get())) {
        throw InvalidBundleException.builder()
            .withUserMessage(
                "Title for module '%s' is missing in the base resource table.", module.getName())
            .build();
      }
    }
  }
}
 
源代码17 项目: james-project   文件: GetMessagesMethod.java
private PropertyFilter buildHeadersPropertyFilter(ImmutableSet<HeaderProperty> headerProperties) {
    return new FieldNamePropertyFilter((fieldName) -> headerProperties.contains(HeaderProperty.fromFieldName(fieldName)));
}
 
/**
 * This class relies heavily on the behavior of segmented scans with respect to which hash keys are scanned by each segment.
 * Here's a rough ASCII example to help illustrate:
 *  ___________________________
 * |hk:A         |hk:B         |
 * ----------------------------
 * ^segment 1        ^segment 2
 *
 * Because we are scanning in segments across the entire hash key space, it is possible for the same hash key to appear in two different segments.
 * We are also running all of the scan segments in parallel, so we have no control over which segment returns first.
 *
 * In the example, if segment 2 was the first segment to post a result, we would store hk:B as a "boundary" key. That way when
 * segment 1 eventually reaches hk:B in its scan, we know that another segment has already returned this hash key and we can safely skip returning it.
 *
 * By doing this, we avoid returning a RecordIterator for the same hash key twice and we only need to store at most 2 hash keys per segment.
 *
 */
@Override
public List<SingleKeyRecordIterator> buildRecordIterators(final ScanContext scanContext) {
    final ScanResult dynamoDbResult = scanContext.getScanResult();
    final int segment = scanContext.getScanRequest().getSegment();
    final List<Map<String, AttributeValue>> items = dynamoDbResult.getItems();
    // If the scan returned no results, we need to shortcut and just throw back an empty result set
    if (items.isEmpty()) {
        return Collections.emptyList();
    }

    final List<SingleKeyRecordIterator> recordIterators = Lists.newLinkedList();

    final Iterator<Map<String, AttributeValue>> itemIterator = items.iterator();
    final Map<String, AttributeValue> firstItem = itemIterator.next();
    final StaticBuffer firstKey = new KeyBuilder(firstItem).build(Constants.JANUSGRAPH_HASH_KEY);

    // Computes the full set of boundary keys up to this point. This includes the previous end key for this segment.
    final ImmutableSet<StaticBuffer> boundaryKeys = aggregateBoundaryKeys();

    // The first key in this scan segment might already have been returned by a previous scan segment
    if (!boundaryKeys.contains(firstKey)) {
        recordIterators.add(buildRecordIteratorForHashKey(firstKey));
    }

    StaticBuffer hashKey = firstKey;
    while (itemIterator.hasNext()) {
        final Optional<StaticBuffer> nextKey = findNextHashKey(itemIterator, hashKey);
        if (nextKey.isPresent()) {
            // Found a new hash key. Make a record iterator and look for the next unique hash key
            hashKey = nextKey.get();
            recordIterators.add(buildRecordIteratorForHashKey(hashKey));
        }
    }

    // If we've already seen the final hashKey in a previous scan segment result, we want to avoid returning it again.
    if (!hashKey.equals(firstKey) && boundaryKeys.contains(hashKey)) {
        recordIterators.remove(recordIterators.size() - 1);
    }

    // Update the boundary keys for this segment
    if (scanContext.isFirstResult()) {
        setInitialBoundaryKeys(segment, firstKey, hashKey);
    } else {
        updateLastKey(segment, hashKey);
    }
    return recordIterators;
}
 
源代码19 项目: NullAway   文件: AccessPathNullnessPropagation.java
private NullnessStore lambdaInitialStore(
    UnderlyingAST.CFGLambda underlyingAST, List<LocalVariableNode> parameters) {
  // include nullness info for locals from enclosing environment
  EnclosingEnvironmentNullness environmentNullness =
      EnclosingEnvironmentNullness.instance(context);
  NullnessStore environmentMapping =
      Objects.requireNonNull(
          environmentNullness.getEnvironmentMapping(underlyingAST.getLambdaTree()),
          "no environment stored for lambda");
  NullnessStore.Builder result = environmentMapping.toBuilder();
  LambdaExpressionTree code = underlyingAST.getLambdaTree();
  // need to check annotation for i'th parameter of functional interface declaration
  Symbol.MethodSymbol fiMethodSymbol = NullabilityUtil.getFunctionalInterfaceMethod(code, types);
  com.sun.tools.javac.util.List<Symbol.VarSymbol> fiMethodParameters =
      fiMethodSymbol.getParameters();
  ImmutableSet<Integer> nullableParamsFromHandler =
      handler.onUnannotatedInvocationGetExplicitlyNullablePositions(
          context, fiMethodSymbol, ImmutableSet.of());

  for (int i = 0; i < parameters.size(); i++) {
    LocalVariableNode param = parameters.get(i);
    VariableTree variableTree = code.getParameters().get(i);
    Element element = param.getElement();
    Nullness assumed;
    // we treat lambda parameters differently; they "inherit" the nullability of the
    // corresponding functional interface parameter, unless they are explicitly annotated
    if (Nullness.hasNullableAnnotation((Symbol) element, config)) {
      assumed = NULLABLE;
    } else if (!NullabilityUtil.lambdaParamIsImplicitlyTyped(variableTree)) {
      // the parameter has a declared type with no @Nullable annotation
      // treat as non-null
      assumed = NONNULL;
    } else {
      if (NullabilityUtil.isUnannotated(fiMethodSymbol, config)) {
        // assume parameter is non-null unless handler tells us otherwise
        assumed = nullableParamsFromHandler.contains(i) ? NULLABLE : NONNULL;
      } else {
        assumed =
            Nullness.hasNullableAnnotation(fiMethodParameters.get(i), config)
                ? NULLABLE
                : NONNULL;
      }
    }
    result.setInformation(AccessPath.fromLocal(param), assumed);
  }
  result = handler.onDataflowInitialStore(underlyingAST, parameters, result);
  return result.build();
}
 
源代码20 项目: tac-kbp-eal   文件: AbstractLinkingStrategy.java
@Override
public LinkingStore wrap(final Iterable<Symbol> docIDs) {
  final ImmutableSet<Symbol> docIdSet = ImmutableSet.copyOf(docIDs);

  return new LinkingStore() {
    @Override
    public ImmutableSet<Symbol> docIDs() throws IOException {
      return docIdSet;
    }

    @Override
    public Optional<ResponseLinking> read(final ArgumentOutput argumentOutput) throws IOException {
      if (docIdSet.contains(argumentOutput.docId())) {
        return Optional.of(linkResponses(argumentOutput));
      } else {
        return Optional.absent();
      }
    }

    @Override
    public Optional<ResponseLinking> read(final AnswerKey answerKey) throws IOException {

      if (docIdSet.contains(answerKey.docId())) {
        return Optional.of(linkResponses(answerKey));
      } else {
        return Optional.absent();
      }
    }

    @Override
    public void write(final ResponseLinking toWrite) throws IOException {
      throw new UnsupportedOperationException();
    }

    @Override
    public void close() throws IOException {
      // do nothing, assume underlying argumentStore will be closed separately
    }

    @Override
    public Optional<ResponseLinking> readTransformingIDs(final Symbol docID,
        final Set<Response> responses,
        final Optional<ImmutableMap<String, String>> foreignResponseIDToLocal,
        final Optional<ImmutableMap.Builder<String, String>> foreignLinkingIDToLocal)
        throws IOException {
      throw new UnsupportedOperationException();
    }
  };
}