<commit_before>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.facebook.buck.apple;

import com.facebook.buck.apple.toolchain.AppleCxxPlatform;
import com.facebook.buck.core.cell.CellPathResolver;
import com.facebook.buck.core.filesystems.RelPath;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.cxx.CxxLibraryGroup;
import com.facebook.buck.cxx.CxxPreprocessorInput;
import com.facebook.buck.cxx.HeaderSymlinkTreeWithHeaderMap;
import com.facebook.buck.cxx.PreprocessorFlags;
import com.facebook.buck.cxx.TransitiveCxxPreprocessorInputCache;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.HeaderVisibility;
import com.facebook.buck.cxx.toolchain.Preprocessor;
import com.facebook.buck.downwardapi.config.DownwardApiConfig;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.swift.SwiftBuckConfig;
import com.facebook.buck.swift.SwiftCompile;
import com.facebook.buck.swift.SwiftDescriptions;
import com.facebook.buck.swift.SwiftLibraryDescription;
import com.facebook.buck.swift.SwiftLibraryDescriptionArg;
import com.facebook.buck.swift.toolchain.SwiftPlatform;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.Optional;

public class AppleLibraryDescriptionSwiftEnhancer {
  public static BuildRule createSwiftCompileRule(
      BuildTarget target,
      CellPathResolver cellRoots,
      ActionGraphBuilder graphBuilder,
      AppleNativeTargetDescriptionArg args,
      ProjectFilesystem filesystem,
      CxxPlatform platform,
      AppleCxxPlatform applePlatform,
      SwiftBuckConfig swiftBuckConfig,
      DownwardApiConfig downwardApiConfig,
      ImmutableSet<CxxPreprocessorInput> inputs) {

    SwiftLibraryDescriptionArg.Builder delegateArgsBuilder = SwiftLibraryDescriptionArg.builder();
    SwiftDescriptions.populateSwiftLibraryDescriptionArg(
        swiftBuckConfig, graphBuilder.getSourcePathResolver(), delegateArgsBuilder, args, target);
    delegateArgsBuilder.setTargetSdkVersion(args.getTargetSdkVersion());
    SwiftLibraryDescriptionArg swiftArgs = delegateArgsBuilder.build();

    Preprocessor preprocessor =
        platform.getCpp().resolve(graphBuilder, target.getTargetConfiguration());

    PreprocessorFlags.Builder flagsBuilder = PreprocessorFlags.builder();
    inputs.forEach(input -> flagsBuilder.addAllIncludes(input.getIncludes()));
    inputs.forEach(input -> flagsBuilder.addAllFrameworkPaths(input.getFrameworks()));
    PreprocessorFlags preprocessorFlags = flagsBuilder.build();

    Optional<CxxPreprocessorInput> underlyingModule =
        AppleLibraryDescription.underlyingModuleCxxPreprocessorInput(
            target, graphBuilder, platform);

    SwiftPlatform swiftPlatform = applePlatform.getSwiftPlatform().get();

    return SwiftLibraryDescription.createSwiftCompileRule(
        platform,
        swiftPlatform,
        swiftBuckConfig,
        downwardApiConfig,
        target,
        graphBuilder,
        cellRoots,
        filesystem,
        swiftArgs,
        preprocessor,
        preprocessorFlags,
        underlyingModule.isPresent(),
        args.getTargetSdkVersion()
            .map(version -> swiftPlatform.getSwiftTarget().withTargetSdkVersion(version)));
  }

  /**
   * Returns transitive preprocessor inputs excluding those from the swift delegate of the given
   * CxxLibrary.
   */
  public static ImmutableSet<CxxPreprocessorInput> getPreprocessorInputsForAppleLibrary(
      BuildTarget target,
      ActionGraphBuilder graphBuilder,
      CxxPlatform platform,
      AppleNativeTargetDescriptionArg arg) {
    CxxLibraryGroup lib = (CxxLibraryGroup) graphBuilder.requireRule(target.withFlavors());
    ImmutableMap<BuildTarget, CxxPreprocessorInput> transitiveMap =
        TransitiveCxxPreprocessorInputCache.computeTransitiveCxxToPreprocessorInputMap(
            platform, lib, false, graphBuilder);

    ImmutableSet.Builder<CxxPreprocessorInput> builder = ImmutableSet.builder();
    builder.addAll(transitiveMap.values());
    if (arg.isModular()) {
      Optional<CxxPreprocessorInput> underlyingModule =
          AppleLibraryDescription.underlyingModuleCxxPreprocessorInput(
              target, graphBuilder, platform);
      underlyingModule.ifPresent(builder::add);
    } else {
      builder.add(lib.getPublicCxxPreprocessorInputExcludingDelegate(platform, graphBuilder));
    }

    return builder.build();
  }

  public static BuildRule createObjCGeneratedHeaderBuildRule(
      BuildTarget buildTarget,
      ProjectFilesystem projectFilesystem,
      ActionGraphBuilder graphBuilder,
      CxxPlatform cxxPlatform,
      HeaderVisibility headerVisibility) {
    ImmutableMap<Path, SourcePath> headers =<commit_msg>Extract Swift rule creation code to be re-used<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.facebook.buck.apple;

import com.facebook.buck.apple.toolchain.AppleCxxPlatform;
import com.facebook.buck.core.cell.CellPathResolver;
import com.facebook.buck.core.filesystems.RelPath;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.cxx.CxxLibraryGroup;
import com.facebook.buck.cxx.CxxPreprocessorInput;
import com.facebook.buck.cxx.HeaderSymlinkTreeWithHeaderMap;
import com.facebook.buck.cxx.PreprocessorFlags;
import com.facebook.buck.cxx.TransitiveCxxPreprocessorInputCache;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.HeaderVisibility;
import com.facebook.buck.cxx.toolchain.Preprocessor;
import com.facebook.buck.downwardapi.config.DownwardApiConfig;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.swift.SwiftBuckConfig;
import com.facebook.buck.swift.SwiftCompile;
import com.facebook.buck.swift.SwiftDescriptions;
import com.facebook.buck.swift.SwiftLibraryDescription;
import com.facebook.buck.swift.SwiftLibraryDescriptionArg;
import com.facebook.buck.swift.toolchain.SwiftPlatform;
import com.facebook.buck.swift.toolchain.SwiftTargetTriple;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.Optional;

public class AppleLibraryDescriptionSwiftEnhancer {
  public static BuildRule createSwiftCompileRule(
      BuildTarget target,
      CellPathResolver cellRoots,
      ActionGraphBuilder graphBuilder,
      AppleNativeTargetDescriptionArg args,
      ProjectFilesystem filesystem,
      CxxPlatform platform,
      AppleCxxPlatform applePlatform,
      SwiftBuckConfig swiftBuckConfig,
      DownwardApiConfig downwardApiConfig,
      ImmutableSet<CxxPreprocessorInput> inputs) {

    SwiftLibraryDescriptionArg swiftArgs =
        getSwiftArgs(target, graphBuilder, args, swiftBuckConfig);

    Preprocessor preprocessor = getPreprocessor(target, graphBuilder, platform);

    PreprocessorFlags preprocessorFlags = getPreprocessorFlags(inputs);

    Optional<CxxPreprocessorInput> underlyingModule =
        getUnderlyingModulePreprocessorInput(target, graphBuilder, platform);

    SwiftPlatform swiftPlatform = applePlatform.getSwiftPlatform().get();

    return SwiftLibraryDescription.createSwiftCompileRule(
        platform,
        swiftPlatform,
        swiftBuckConfig,
        downwardApiConfig,
        target,
        graphBuilder,
        cellRoots,
        filesystem,
        swiftArgs,
        preprocessor,
        preprocessorFlags,
        underlyingModule.isPresent(),
        getSwiftTargetTruple(args, swiftPlatform));
  }

  private static Optional<SwiftTargetTriple> getSwiftTargetTruple(
      AppleNativeTargetDescriptionArg args, SwiftPlatform swiftPlatform) {
    return args.getTargetSdkVersion()
        .map(version -> swiftPlatform.getSwiftTarget().withTargetSdkVersion(version));
  }

  private static SwiftLibraryDescriptionArg getSwiftArgs(
      BuildTarget target,
      ActionGraphBuilder graphBuilder,
      AppleNativeTargetDescriptionArg args,
      SwiftBuckConfig swiftBuckConfig) {
    SwiftLibraryDescriptionArg.Builder delegateArgsBuilder = SwiftLibraryDescriptionArg.builder();
    SwiftDescriptions.populateSwiftLibraryDescriptionArg(
        swiftBuckConfig, graphBuilder.getSourcePathResolver(), delegateArgsBuilder, args, target);
    delegateArgsBuilder.setTargetSdkVersion(args.getTargetSdkVersion());
    return delegateArgsBuilder.build();
  }

  private static Preprocessor getPreprocessor(
      BuildTarget target, ActionGraphBuilder graphBuilder, CxxPlatform platform) {
    return platform.getCpp().resolve(graphBuilder, target.getTargetConfiguration());
  }

  private static PreprocessorFlags getPreprocessorFlags(ImmutableSet<CxxPreprocessorInput> inputs) {
    PreprocessorFlags.Builder flagsBuilder = PreprocessorFlags.builder();
    inputs.forEach(input -> flagsBuilder.addAllIncludes(input.getIncludes()));
    inputs.forEach(input -> flagsBuilder.addAllFrameworkPaths(input.getFrameworks()));
    return flagsBuilder.build();
  }

  private static Optional<CxxPreprocessorInput> getUnderlyingModulePreprocessorInput(
      BuildTarget target, ActionGraphBuilder graphBuilder, CxxPlatform platform) {
    return AppleLibraryDescription.underlyingModuleCxxPreprocessorInput(
        target, graphBuilder, platform);
  }

  /**
   * Returns transitive preprocessor inputs excluding those from the swift delegate of the given
   * CxxLibrary.
   */
  public static ImmutableSet<CxxPreprocessorInput> getPreprocessorInputsForAppleLibrary(
      BuildTarget target,
      ActionGraphBuilder graphBuilder,
      CxxPlatform platform,
      AppleNativeTargetDescriptionArg arg) {
    CxxLibraryGroup lib = (CxxLibraryGroup) graphBuilder.requireRule(target.withFlavors());
    ImmutableMap<BuildTarget, CxxPreprocessorInput> transitiveMap =
        TransitiveCxxPreprocessorInputCache.computeTransitiveCxxToPreprocessorInputMap(
            platform, lib, false, graphBuilder);

    ImmutableSet.Builder<CxxPreprocessorInput> builder = ImmutableSet.builder();
    builder.addAll(transitiveMap.values());
    if (arg.isModular()) {
      Optional<CxxPreprocessorInput> underlyingModule =
          getUnderlyingModulePreprocessorInput(target, graphBuilder, platform);
      underlyingModule.ifPresent(builder::add);
    } else {
      builder.add(lib.getPublicCxxPreprocessorInputExcludingDelegate(platform, graphBuilder));
    }

    return builder.build();
  }

  public static BuildRule createObjCGeneratedHeaderBuildRule(
      BuildTarget buildTarget,
      ProjectFilesystem projectFilesystem,
      ActionGraphBuilder graphBuilder,
      CxxPlatform cxxPlatform,
      HeaderVisibility headerVisibility) {
    ImmutableMap<Path, SourcePath> headers =
{'fraction_non_alphanumeric': 0.07801076564634048, 'fraction_numerical': 0.0006427251546557404, 'mean_word_length': 4.77365491651206, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3403811', 'n_tokens_mistral': 3370, 'n_tokens_neox': 3200, 'n_words': 673}