Java Code Examples for com.google.common.collect.ImmutableSet#contains()

The following examples show how to use com.google.common.collect.ImmutableSet#contains() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DisambiguateTypeAnnotations.java    From turbine with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example 2
Source File: TokenTypeRewriter.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
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);
					}
				}
			}
		}
	}
}
 
Example 3
Source File: MacroFinder.java    From buck with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 4
Source File: HookBSkyBlock.java    From CombatLogX with GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example 5
Source File: QueryResultLineProcessorTest.java    From intellij with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 6
Source File: AdminAppServiceImpl.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example 7
Source File: HostCheckFlow.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 8
Source File: OptionProcessor.java    From markdown-doclet with GNU General Public License v3.0 5 votes vote down vote up
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);
    };
}
 
Example 9
Source File: ExtractApksCommand.java    From bundletool with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 10
Source File: FieldTypeCondition.java    From sawmill with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 11
Source File: GraphBackedRecursivePackageProvider.java    From bazel with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: CuckooFilterTest.java    From guava-probably with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 13
Source File: ModuleTitleValidator.java    From bundletool with Apache License 2.0 4 votes vote down vote up
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();
      }
    }
  }
}
 
Example 14
Source File: HalideLibraryDescription.java    From buck with Apache License 2.0 4 votes vote down vote up
@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());
}
 
Example 15
Source File: ObjcVariablesExtension.java    From bazel with Apache License 2.0 4 votes vote down vote up
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);
    }
 
Example 16
Source File: GetMessagesMethod.java    From james-project with Apache License 2.0 4 votes vote down vote up
private PropertyFilter buildHeadersPropertyFilter(ImmutableSet<HeaderProperty> headerProperties) {
    return new FieldNamePropertyFilter((fieldName) -> headerProperties.contains(HeaderProperty.fromFieldName(fieldName)));
}
 
Example 17
Source File: MultiRowParallelScanInterpreter.java    From dynamodb-janusgraph-storage-backend with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 18
Source File: AccessPathNullnessPropagation.java    From NullAway with MIT License 4 votes vote down vote up
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();
}
 
Example 19
Source File: AbstractLinkingStrategy.java    From tac-kbp-eal with MIT License 4 votes vote down vote up
@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();
    }
  };
}
 
Example 20
Source File: BazelTestSuiteBuilder.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public boolean apply(Class<?> testClass) {
  ImmutableSet<OS> supportedOs = ImmutableSet.copyOf(Suite.getSupportedOs(testClass));
  return supportedOs.isEmpty() || supportedOs.contains(OS.getCurrent());
}