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

The following examples show how to use com.google.common.collect.ImmutableList#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: TableScanNode.java    From Quicksql with MIT License 6 votes vote down vote up
private static TableScanNode createFilterable(Compiler compiler,
    TableScan rel, ImmutableList<RexNode> filters, ImmutableIntList projects,
    FilterableTable filterableTable) {
  final DataContext root = compiler.getDataContext();
  final List<RexNode> mutableFilters = Lists.newArrayList(filters);
  final Enumerable<Object[]> enumerable =
      filterableTable.scan(root, mutableFilters);
  for (RexNode filter : mutableFilters) {
    if (!filters.contains(filter)) {
      throw RESOURCE.filterableTableInventedFilter(filter.toString()).ex();
    }
  }
  final Enumerable<Row> rowEnumerable = Enumerables.toRow(enumerable);
  return createEnumerable(compiler, rel, rowEnumerable, null,
      mutableFilters, projects);
}
 
Example 2
Source File: CharsetSelector.java    From ldp4j with Apache License 2.0 6 votes vote down vote up
private double filterPreferences() {
	ImmutableList<String> supportedCharsets = getCharsetNames();
	ImmutableList<String> charsetPreferences = getCharsetPreferences();

	double wildcardWeight=-1.0D;
	for(String candidate:charsetPreferences) {
		CharsetPreference preference = CharsetPreference.valueOf(candidate);
		if(preference!=null) {
			if(preference.isWildcard()) {
				wildcardWeight=Math.max(wildcardWeight, preference.weight());
			} else if(supportedCharsets.contains(preference.charset())) {
				this.preferences.add(preference);
			} else {
				this.failed.add(candidate);
			}
		} else {
			this.failed.add(candidate);
		}
	}
	return  wildcardWeight;
}
 
Example 3
Source File: TableScanNode.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static TableScanNode createFilterable(Compiler compiler,
    TableScan rel, ImmutableList<RexNode> filters, ImmutableIntList projects,
    FilterableTable filterableTable) {
  final DataContext root = compiler.getDataContext();
  final List<RexNode> mutableFilters = Lists.newArrayList(filters);
  final Enumerable<Object[]> enumerable =
      filterableTable.scan(root, mutableFilters);
  for (RexNode filter : mutableFilters) {
    if (!filters.contains(filter)) {
      throw RESOURCE.filterableTableInventedFilter(filter.toString()).ex();
    }
  }
  final Enumerable<Row> rowEnumerable = Enumerables.toRow(enumerable);
  return createEnumerable(compiler, rel, rowEnumerable, null,
      mutableFilters, projects);
}
 
Example 4
Source File: CoordSystemBuilder.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Does this axis "fit" this variable. True if all of the dimensions in the axis also appear in
 * the variable. If char variable, last dimension is left out.
 *
 * @param axis check if this axis is ok for the given variable
 * @param vp the given variable
 * @return true if all of the dimensions in the axis also appear in the variable.
 */
protected boolean isCoordinateAxisForVariable(CoordinateAxis.Builder<?> axis, VarProcess vp) {
  ImmutableList<Dimension> varDims = vp.vb.getDimensions();
  ImmutableList<Dimension> axisDims = axis.getDimensions();

  // a CHAR variable must really be a STRING, so leave out the last (string length) dimension
  int checkDims = axisDims.size();
  if (axis.dataType == DataType.CHAR)
    checkDims--;

  for (int i = 0; i < checkDims; i++) {
    Dimension axisDim = axisDims.get(i);
    if (!varDims.contains(axisDim)) {
      return false;
    }
  }
  return true;
}
 
Example 5
Source File: AppleSdkDiscovery.java    From buck with Apache License 2.0 6 votes vote down vote up
private static ImmutableList<String> validArchitecturesForPlatform(
    ApplePlatform platform, Path sdkDir) throws IOException {
  ImmutableList<String> architectures = platform.getArchitectures();
  try (DirectoryStream<Path> sdkFiles = Files.newDirectoryStream(sdkDir)) {
    ImmutableList.Builder<String> architectureSubdirsBuilder = ImmutableList.builder();
    for (Path path : sdkFiles) {
      if (Files.isDirectory(path)) {
        String directoryName = path.getFileName().toString();
        // Default Apple SDKs contain fat binaries and have no architecture subdirectories,
        // but custom SDKs might.
        if (architectures.contains(directoryName)) {
          architectureSubdirsBuilder.add(directoryName);
        }
      }
    }

    ImmutableList<String> architectureSubdirs = architectureSubdirsBuilder.build();
    if (!architectureSubdirs.isEmpty()) {
      architectures = architectureSubdirs;
    }
  }
  return architectures;
}
 
Example 6
Source File: EclipseHack.java    From SimpleWeibo with Apache License 2.0 5 votes vote down vote up
private void reorderProperties(TypeElement type, List<RetroWeiboProcessor.Property> properties) {
  PropertyOrderer propertyOrderer = getPropertyOrderer(type);
  if (propertyOrderer == null) {
    return;
  }
  final ImmutableList<String> order;
  try {
    order = propertyOrderer.determinePropertyOrder();
  } catch (IOException e) {
    processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, e.toString());
    return;
  }
  // We expect that all the properties will be found, but if not then we won't try reordering.
  boolean allFound = true;
  for (RetroWeiboProcessor.Property property : properties) {
    allFound &= order.contains(property.getGetter());
  }
  if (allFound) {
    // We successfully found the abstract methods corresponding to all the properties, so now
    // reorder the List<Property> to reflect the order of the methods.
    Comparator<RetroWeiboProcessor.Property> comparator = new Comparator<RetroWeiboProcessor.Property>() {
      @Override
      public int compare(RetroWeiboProcessor.Property a, RetroWeiboProcessor.Property b) {
        String aName = a.getGetter();
        String bName = b.getGetter();
        return order.indexOf(aName) - order.indexOf(bName);
      }
    };
    Collections.sort(properties, comparator);
  }
}
 
Example 7
Source File: SpawnAction.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an ActionSpawn with the given environment variables.
 *
 * <p>Subclasses of ActionSpawn may subclass in order to provide action-specific values for
 * environment variables or action inputs.
 */
private ActionSpawn(
    ImmutableList<String> arguments,
    Map<String, String> clientEnv,
    NestedSet<Artifact> inputs,
    Iterable<? extends ActionInput> additionalInputs,
    Map<Artifact, ImmutableList<FilesetOutputSymlink>> filesetMappings) {
  super(
      arguments,
      ImmutableMap.<String, String>of(),
      executionInfo,
      SpawnAction.this.getRunfilesSupplier(),
      SpawnAction.this,
      resourceSet);
  NestedSetBuilder<ActionInput> inputsBuilder = NestedSetBuilder.stableOrder();
  ImmutableList<Artifact> manifests = getRunfilesSupplier().getManifests();
  for (Artifact input : inputs.toList()) {
    if (!input.isFileset() && !manifests.contains(input)) {
      inputsBuilder.add(input);
    }
  }
  inputsBuilder.addAll(additionalInputs);
  this.inputs = inputsBuilder.build();
  this.filesetMappings = filesetMappings;
  LinkedHashMap<String, String> env = new LinkedHashMap<>(SpawnAction.this.env.size());
  SpawnAction.this.env.resolve(env, clientEnv);
  effectiveEnvironment = ImmutableMap.copyOf(env);
}
 
Example 8
Source File: OptionProcessor.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Check that the option lists at least one effect, and that no nonsensical combinations are
 * listed, such as having a known effect listed with UNKNOWN.
 */
private void checkEffectTagRationality(VariableElement optionField)
    throws OptionProcessorException {
  Option annotation = optionField.getAnnotation(Option.class);
  OptionEffectTag[] effectTags = annotation.effectTags();
  // Check that there is at least one OptionEffectTag listed.
  if (effectTags.length < 1) {
    throw new OptionProcessorException(
        optionField,
        "Option does not list at least one OptionEffectTag. If the option has no effect, "
            + "please be explicit and add NO_OP. Otherwise, add a tag representing its effect.");
  } else if (effectTags.length > 1) {
    // If there are more than 1 tag, make sure that NO_OP and UNKNOWN is not one of them.
    // These don't make sense if other effects are listed.
    ImmutableList<OptionEffectTag> tags = ImmutableList.copyOf(effectTags);
    if (tags.contains(OptionEffectTag.UNKNOWN)) {
      throw new OptionProcessorException(
          optionField,
          "Option includes UNKNOWN with other, known, effects. Please remove UNKNOWN from "
              + "the list.");
    }
    if (tags.contains(OptionEffectTag.NO_OP)) {
      throw new OptionProcessorException(
          optionField,
          "Option includes NO_OP with other effects. This doesn't make much sense. Please "
              + "remove NO_OP or the actual effects from the list, whichever is correct.");
    }
  }
}
 
Example 9
Source File: EclipseHack.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
private void reorderProperties(TypeElement type, List<RetroFacebookProcessor.Property> properties) {
  PropertyOrderer propertyOrderer = getPropertyOrderer(type);
  if (propertyOrderer == null) {
    return;
  }
  final ImmutableList<String> order;
  try {
    order = propertyOrderer.determinePropertyOrder();
  } catch (IOException e) {
    processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, e.toString());
    return;
  }
  // We expect that all the properties will be found, but if not then we won't try reordering.
  boolean allFound = true;
  for (RetroFacebookProcessor.Property property : properties) {
    allFound &= order.contains(property.getGetter());
  }
  if (allFound) {
    // We successfully found the abstract methods corresponding to all the properties, so now
    // reorder the List<Property> to reflect the order of the methods.
    Comparator<RetroFacebookProcessor.Property> comparator = new Comparator<RetroFacebookProcessor.Property>() {
      @Override
      public int compare(RetroFacebookProcessor.Property a, RetroFacebookProcessor.Property b) {
        String aName = a.getGetter();
        String bName = b.getGetter();
        return order.indexOf(aName) - order.indexOf(bName);
      }
    };
    Collections.sort(properties, comparator);
  }
}
 
Example 10
Source File: ErrorProcessor.java    From Moxy with MIT License 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
	for (Element element : roundEnv.getRootElements()) {
		if (element.getSimpleName().toString().equals("InjectPresenterTypeBehaviorView")) {
			for (Element element1 : element.getEnclosedElements()) {
				System.out.println("EnclosedElements: " + element1.getSimpleName());
				ImmutableList<String> of = ImmutableList.of("mPresenterIdLocalPresenter", "mTagLocalPresenter", "mFactoryLocalPresenter", "mFactoryTagPresenter");
				if (of.contains(element1.getSimpleName().toString())) {
					messager.printMessage(Diagnostic.Kind.ERROR, "expected error!", element1);
				}
			}
		}
	}
	return true;
}
 
Example 11
Source File: SimpleMetaDataManager.java    From science-journal with Apache License 2.0 5 votes vote down vote up
@Override
public void moveAllExperimentsToAnotherAccount(AppAccount targetAccount) throws IOException {
  // This method should not be called if canMoveAllExperimentsToAnotherAccount returns false.
  if (!canMoveAllExperimentsToAnotherAccount(targetAccount)) {
    throw new IllegalStateException("moveAllExperimentsToAnotherAccount now allowed now");
  }

  getFileMetadataManager().beforeMovingAllExperimentsToAnotherAccount();

  // Move experiment root directory.
  File sourceExperimentsRoot =
      FileMetadataUtil.getInstance().getExperimentsRootDirectory(appAccount);
  File targetExperimentsRoot =
      FileMetadataUtil.getInstance().getExperimentsRootDirectory(targetAccount);
  Files.move(sourceExperimentsRoot, targetExperimentsRoot);

  // Move user_metadata.proto.
  File sourceUserMetadataFile = FileMetadataUtil.getInstance().getUserMetadataFile(appAccount);
  File targetUserMetadataFile = FileMetadataUtil.getInstance().getUserMetadataFile(targetAccount);
  Files.move(sourceUserMetadataFile, targetUserMetadataFile);

  // Move experiment and sensor databases.
  ImmutableList<String> filesToMove =
      ImmutableList.of("main.db", "main.db-journal", "sensors.db", "sensors.db-journal");
  String[] sourceNames = context.databaseList();
  for (String sourceName : sourceNames) {
    if (filesToMove.contains(sourceName)) {
      File sourceFile = context.getDatabasePath(sourceName);
      String targetName = targetAccount.getDatabaseFileName(sourceName);
      File targetFile = new File(sourceFile.getParentFile(), targetName);
      Files.move(sourceFile, targetFile);
    }
  }
}
 
Example 12
Source File: MycatLogicTable.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private Statistic createStatistic(ImmutableList<ImmutableBitSet> immutableBitSets) {
  return new Statistic() {
        public Double getRowCount() {
            return StatisticCenter.INSTANCE.getLogicTableRow(table.getSchemaName(),table.getTableName());
        }

        public boolean isKey(ImmutableBitSet columns) {
            return immutableBitSets.contains(columns);
        }

        public List<ImmutableBitSet> getKeys() {
            return immutableBitSets;
        }

        public List<RelReferentialConstraint> getReferentialConstraints() {
            return ImmutableList.of();
        }

        public List<RelCollation> getCollations() {
            return ImmutableList.of();
        }

        public RelDistribution getDistribution() {
            return RelDistributionTraitDef.INSTANCE.getDefault();
        }
    };
}
 
Example 13
Source File: AaScriptHelper.java    From startup-os with Apache License 2.0 5 votes vote down vote up
private String getBashCompletions(String previousWord, String currentWord) throws IOException {
  ImmutableList<String> commands = aaTool.getCommands();
  // TODO: Get flags from commands. Perhaps AaTool can provide a get method for it.
  ImmutableList<String> initOptions =
      ImmutableList.of("--base_path", "--startupos_repo", "--user");
  ImmutableList<String> addRepoOptions = ImmutableList.of("--url", "--name");
  ImmutableList<String> diffOptions =
      ImmutableList.of("--reviewers", "--description", "--buglink");

  if (previousWord.equals("aa")) {
    return getMatches(commands, currentWord);
  } else if (previousWord.equals("workspace") || previousWord.equals("aaw")) {
    return getMatches(fileUtils.listSubfolders(workspacesPath), currentWord);
  } else if (commands.contains(previousWord)) {
    // Complete flags
    switch (previousWord) {
      case "init":
        return getMatches(initOptions, currentWord);
      case "add_repo":
        return getMatches(addRepoOptions, currentWord);
      case "diff":
        return getMatches(diffOptions, currentWord);
      default:
        break;
    }
  }
  return "";
}
 
Example 14
Source File: LibraryEligibleForFeatureSplitSuggester.java    From size-analyzer with Apache License 2.0 5 votes vote down vote up
/**
 * Inspects if any of the modules that use a library is the base module, if any modules use the
 * library at all
 */
private static LibraryUsage getLibraryUsageStatusFromModuleList(ImmutableList<String> modules) {
  if (modules.isEmpty()) {
    return LibraryUsage.LIBRARY_NOT_USED;
  }

  return modules.contains(BundleModuleName.BASE_MODULE_NAME.getName())
      ? LibraryUsage.LIBRARY_IN_BASE
      : LibraryUsage.LIBRARY_IN_FEATURE_MODULES_ONLY;
}
 
Example 15
Source File: TableScanNode.java    From calcite with Apache License 2.0 4 votes vote down vote up
private static TableScanNode createProjectableFilterable(Compiler compiler,
    TableScan rel, ImmutableList<RexNode> filters, ImmutableIntList projects,
    ProjectableFilterableTable pfTable) {
  final DataContext root = compiler.getDataContext();
  final ImmutableIntList originalProjects = projects;
  for (;;) {
    final List<RexNode> mutableFilters = Lists.newArrayList(filters);
    final int[] projectInts;
    if (projects == null
        || projects.equals(TableScan.identity(rel.getTable()))) {
      projectInts = null;
    } else {
      projectInts = projects.toIntArray();
    }
    final Enumerable<Object[]> enumerable1 =
        pfTable.scan(root, mutableFilters, projectInts);
    for (RexNode filter : mutableFilters) {
      if (!filters.contains(filter)) {
        throw RESOURCE.filterableTableInventedFilter(filter.toString())
            .ex();
      }
    }
    final ImmutableBitSet usedFields =
        RelOptUtil.InputFinder.bits(mutableFilters, null);
    if (projects != null) {
      int changeCount = 0;
      for (int usedField : usedFields) {
        if (!projects.contains(usedField)) {
          // A field that is not projected is used in a filter that the
          // table rejected. We won't be able to apply the filter later.
          // Try again without any projects.
          projects =
              ImmutableIntList.copyOf(
                  Iterables.concat(projects, ImmutableList.of(usedField)));
          ++changeCount;
        }
      }
      if (changeCount > 0) {
        continue;
      }
    }
    final Enumerable<Row> rowEnumerable = Enumerables.toRow(enumerable1);
    final ImmutableIntList rejectedProjects;
    if (Objects.equals(projects, originalProjects)) {
      rejectedProjects = null;
    } else {
      // We projected extra columns because they were needed in filters. Now
      // project the leading columns.
      rejectedProjects = ImmutableIntList.identity(originalProjects.size());
    }
    return createEnumerable(compiler, rel, rowEnumerable, projects,
        mutableFilters, rejectedProjects);
  }
}
 
Example 16
Source File: ParsedOptionDescription.java    From bazel with Apache License 2.0 4 votes vote down vote up
public boolean isHidden() {
  ImmutableList<OptionMetadataTag> tags = metadataTags();
  return tags.contains(OptionMetadataTag.HIDDEN) || tags.contains(OptionMetadataTag.INTERNAL);
}
 
Example 17
Source File: JavacTurbine.java    From bazel with Apache License 2.0 4 votes vote down vote up
/** Creates the compilation javacopts from {@link TurbineOptions}. */
@VisibleForTesting
static ImmutableList<String> processJavacopts(TurbineOptions turbineOptions) {
  ImmutableList<String> javacopts =
      JavacOptions.removeBazelSpecificFlags(
          JavacOptions.normalizeOptionsWithNormalizers(
              turbineOptions.javacOpts(),
              new DoclintOptionNormalizer(),
              new JavacOptions.ReleaseOptionNormalizer()));

  ImmutableList.Builder<String> builder = ImmutableList.builder();
  builder.addAll(javacopts);

  // Disable compilation of implicit source files.
  // This is insurance: the sourcepath is empty, so we don't expect implicit sources.
  builder.add("-implicit:none");

  // Disable debug info
  builder.add("-g:none");

  // Enable MethodParameters
  builder.add("-parameters");

  // Compile-time jars always use Java 8
  if (javacopts.contains("--release")) {
    // javac doesn't allow mixing -source and --release, so use --release if it's already present
    // in javacopts.
    builder.add("--release");
    builder.add("8");
  } else {
    builder.add("-source");
    builder.add("8");
    builder.add("-target");
    builder.add("8");
  }

  builder.add("-Xdoclint:none");

  if (!turbineOptions.processors().isEmpty()) {
    builder.add("-processor");
    builder.add(Joiner.on(',').join(turbineOptions.processors()));
  }

  return builder.build();
}
 
Example 18
Source File: TableScanNode.java    From Quicksql with MIT License 4 votes vote down vote up
private static TableScanNode createProjectableFilterable(Compiler compiler,
    TableScan rel, ImmutableList<RexNode> filters, ImmutableIntList projects,
    ProjectableFilterableTable pfTable) {
  final DataContext root = compiler.getDataContext();
  final ImmutableIntList originalProjects = projects;
  for (;;) {
    final List<RexNode> mutableFilters = Lists.newArrayList(filters);
    final int[] projectInts;
    if (projects == null
        || projects.equals(TableScan.identity(rel.getTable()))) {
      projectInts = null;
    } else {
      projectInts = projects.toIntArray();
    }
    final Enumerable<Object[]> enumerable1 =
        pfTable.scan(root, mutableFilters, projectInts);
    for (RexNode filter : mutableFilters) {
      if (!filters.contains(filter)) {
        throw RESOURCE.filterableTableInventedFilter(filter.toString())
            .ex();
      }
    }
    final ImmutableBitSet usedFields =
        RelOptUtil.InputFinder.bits(mutableFilters, null);
    if (projects != null) {
      int changeCount = 0;
      for (int usedField : usedFields) {
        if (!projects.contains(usedField)) {
          // A field that is not projected is used in a filter that the
          // table rejected. We won't be able to apply the filter later.
          // Try again without any projects.
          projects =
              ImmutableIntList.copyOf(
                  Iterables.concat(projects, ImmutableList.of(usedField)));
          ++changeCount;
        }
      }
      if (changeCount > 0) {
        continue;
      }
    }
    final Enumerable<Row> rowEnumerable = Enumerables.toRow(enumerable1);
    final ImmutableIntList rejectedProjects;
    if (Objects.equals(projects, originalProjects)) {
      rejectedProjects = null;
    } else {
      // We projected extra columns because they were needed in filters. Now
      // project the leading columns.
      rejectedProjects = ImmutableIntList.identity(originalProjects.size());
    }
    return createEnumerable(compiler, rel, rowEnumerable, projects,
        mutableFilters, rejectedProjects);
  }
}
 
Example 19
Source File: OcamlBuildRulesGenerator.java    From buck with Apache License 2.0 4 votes vote down vote up
/** Compiles a single .ml file to a .cmx */
private void generateSingleMLNativeCompilation(
    Map<Path, ImmutableSortedSet<BuildRule>> sourceToRule,
    ImmutableList.Builder<SourcePath> cmxFiles,
    Path mlSource,
    ImmutableMap<Path, ImmutableList<Path>> sources,
    ImmutableList<Path> cycleDetector) {

  ImmutableList<Path> newCycleDetector =
      ImmutableList.<Path>builder().addAll(cycleDetector).add(mlSource).build();

  if (cycleDetector.contains(mlSource)) {
    throw new HumanReadableException(
        "Dependency cycle detected: %s", Joiner.on(" -> ").join(newCycleDetector));
  }

  if (sourceToRule.containsKey(mlSource)) {
    return;
  }

  ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder();
  if (sources.containsKey(mlSource)) {
    for (Path dep : Objects.requireNonNull(sources.get(mlSource))) {
      generateSingleMLNativeCompilation(sourceToRule, cmxFiles, dep, sources, newCycleDetector);
      depsBuilder.addAll(Objects.requireNonNull(sourceToRule.get(dep)));
    }
  }
  ImmutableSortedSet<BuildRule> deps = depsBuilder.build();

  String name = mlSource.toFile().getName();

  BuildRuleParams compileParams =
      params.withDeclaredDeps(
          Suppliers.ofInstance(
              ImmutableSortedSet.<BuildRule>naturalOrder()
                  .addAll(params.getDeclaredDeps().get())
                  .add(this.cleanRule)
                  .addAll(deps)
                  .addAll(ocamlContext.getNativeCompileDeps())
                  .addAll(BuildableSupport.getDepsCollection(cCompiler, graphBuilder))
                  .build()));

  String outputFileName = getMLNativeOutputName(name);
  Path outputPath = ocamlContext.getCompileNativeOutputDir().resolve(outputFileName);
  ImmutableList<Arg> compileFlags =
      getCompileFlags(/* isBytecode */ false, /* excludeDeps */ false);
  OcamlMLCompile compile =
      new OcamlMLCompile(
          createMLNativeCompileBuildTarget(buildTarget, name),
          projectFilesystem,
          compileParams,
          new OcamlMLCompileStep.Args(
              cCompiler.getEnvironment(pathResolver),
              cCompiler.getCommandPrefix(pathResolver),
              ocamlContext.getOcamlCompiler().get(),
              ocamlContext.getOcamlInteropIncludesDir(),
              outputPath,
              mlSource,
              compileFlags));
  graphBuilder.addToIndex(compile);
  sourceToRule.put(
      mlSource, ImmutableSortedSet.<BuildRule>naturalOrder().add(compile).addAll(deps).build());
  if (!outputFileName.endsWith(OcamlCompilables.OCAML_CMI)) {
    cmxFiles.add(compile.getSourcePathToOutput());
  }
}
 
Example 20
Source File: OcamlBuildRulesGenerator.java    From buck with Apache License 2.0 4 votes vote down vote up
/** Compiles a single .ml file to a .cmo */
private void generateSingleMLBytecodeCompilation(
    Map<Path, ImmutableSortedSet<BuildRule>> sourceToRule,
    ImmutableList.Builder<SourcePath> cmoFiles,
    Path mlSource,
    ImmutableMap<Path, ImmutableList<Path>> sources,
    ImmutableList<Path> cycleDetector) {

  ImmutableList<Path> newCycleDetector =
      ImmutableList.<Path>builder().addAll(cycleDetector).add(mlSource).build();

  if (cycleDetector.contains(mlSource)) {
    throw new HumanReadableException(
        "Dependency cycle detected: %s", Joiner.on(" -> ").join(newCycleDetector));
  }
  if (sourceToRule.containsKey(mlSource)) {
    return;
  }

  ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder();
  if (sources.containsKey(mlSource)) {
    for (Path dep : Objects.requireNonNull(sources.get(mlSource))) {
      generateSingleMLBytecodeCompilation(sourceToRule, cmoFiles, dep, sources, newCycleDetector);
      depsBuilder.addAll(Objects.requireNonNull(sourceToRule.get(dep)));
    }
  }
  ImmutableSortedSet<BuildRule> deps = depsBuilder.build();

  String name = mlSource.toFile().getName();

  BuildRuleParams compileParams =
      params.withDeclaredDeps(
          Suppliers.ofInstance(
              ImmutableSortedSet.<BuildRule>naturalOrder()
                  .add(this.cleanRule)
                  .addAll(params.getDeclaredDeps().get())
                  .addAll(deps)
                  .addAll(ocamlContext.getBytecodeCompileDeps())
                  .addAll(BuildableSupport.getDepsCollection(cCompiler, graphBuilder))
                  .build()));

  String outputFileName = getMLBytecodeOutputName(name);
  Path outputPath = ocamlContext.getCompileBytecodeOutputDir().resolve(outputFileName);
  ImmutableList<Arg> compileFlags =
      getCompileFlags(/* isBytecode */ true, /* excludeDeps */ false);
  BuildRule compileBytecode =
      new OcamlMLCompile(
          createMLBytecodeCompileBuildTarget(buildTarget, name),
          projectFilesystem,
          compileParams,
          new OcamlMLCompileStep.Args(
              cCompiler.getEnvironment(pathResolver),
              cCompiler.getCommandPrefix(pathResolver),
              ocamlContext.getOcamlBytecodeCompiler().get(),
              ocamlContext.getOcamlInteropIncludesDir(),
              outputPath,
              mlSource,
              compileFlags));
  graphBuilder.addToIndex(compileBytecode);
  sourceToRule.put(
      mlSource,
      ImmutableSortedSet.<BuildRule>naturalOrder().add(compileBytecode).addAll(deps).build());
  if (!outputFileName.endsWith(OcamlCompilables.OCAML_CMI)) {
    cmoFiles.add(compileBytecode.getSourcePathToOutput());
  }
}