Example #1
0
 /**
  * A not type safe constructor for SkylarkNestedSet. It's discouraged to use it unless type
  * generic safety is guaranteed from the caller side.
  */
 SkylarkNestedSet(SkylarkType contentType, NestedSet<?> set) {
   // This is here for the sake of FuncallExpression.
   this.contentType = Preconditions.checkNotNull(contentType, "type cannot be null");
   this.set = Preconditions.checkNotNull(set, "set cannot be null");
   this.items = null;
   this.transitiveItems = null;
 }
Example #2
0
 public CcLibraryHelper(
     RuleContext ruleContext, CppSemantics semantics, FeatureConfiguration featureConfiguration) {
   this.ruleContext = Preconditions.checkNotNull(ruleContext);
   this.configuration = ruleContext.getConfiguration();
   this.semantics = Preconditions.checkNotNull(semantics);
   this.featureConfiguration = Preconditions.checkNotNull(featureConfiguration);
 }
 IntermediateArtifacts(
     RuleContext ruleContext,
     String archiveFileNameSuffix,
     String outputPrefix,
     BuildConfiguration buildConfiguration) {
   this.ruleContext = ruleContext;
   this.buildConfiguration = buildConfiguration;
   this.archiveFileNameSuffix = Preconditions.checkNotNull(archiveFileNameSuffix);
   this.outputPrefix = Preconditions.checkNotNull(outputPrefix);
 }
Example #4
0
 public CppModel(RuleContext ruleContext, CppSemantics semantics) {
   this.ruleContext = Preconditions.checkNotNull(ruleContext);
   this.semantics = semantics;
   configuration = ruleContext.getConfiguration();
   cppConfiguration = ruleContext.getFragment(CppConfiguration.class);
   features = CppHelper.getToolchain(ruleContext).getFeatures();
 }
 private NodeEntry getEntryForValue(SkyKey key) {
   NodeEntry entry =
       Preconditions.checkNotNull(
           graph.getBatch(null, Reason.WALKABLE_GRAPH_VALUE, ImmutableList.of(key)).get(key), key);
   Preconditions.checkState(entry.isDone(), "%s %s", key, entry);
   return entry;
 }
Example #6
0
 /**
  * Create a GlobValue wrapping {@code matches}. {@code matches} must have order {@link
  * Order#STABLE_ORDER}.
  */
 public GlobValue(NestedSet<PathFragment> matches) {
   this.matches = Preconditions.checkNotNull(matches);
   Preconditions.checkState(
       matches.getOrder() == Order.STABLE_ORDER,
       "Only STABLE_ORDER is supported, but got %s",
       matches.getOrder());
 }
    /**
     * Merges the context of a dependency into this one by adding the contents of all of its
     * attributes.
     */
    public Builder mergeDependentContext(CppCompilationContext otherContext) {
      Preconditions.checkNotNull(otherContext);
      compilationPrerequisites.addAll(otherContext.getTransitiveCompilationPrerequisites());
      includeDirs.addAll(otherContext.getIncludeDirs());
      quoteIncludeDirs.addAll(otherContext.getQuoteIncludeDirs());
      systemIncludeDirs.addAll(otherContext.getSystemIncludeDirs());
      declaredIncludeDirs.addTransitive(otherContext.getDeclaredIncludeDirs());
      declaredIncludeWarnDirs.addTransitive(otherContext.getDeclaredIncludeWarnDirs());
      declaredIncludeSrcs.addTransitive(otherContext.getDeclaredIncludeSrcs());
      pregreppedHdrs.addTransitive(otherContext.getPregreppedHeaders());
      moduleInfo.addTransitive(otherContext.moduleInfo);
      picModuleInfo.addTransitive(otherContext.picModuleInfo);

      NestedSet<Artifact> othersTransitiveModuleMaps = otherContext.getTransitiveModuleMaps();
      NestedSet<Artifact> othersDirectModuleMaps = otherContext.getDirectModuleMaps();

      // Forward transitive information.
      // The other target's transitive module maps do not include its direct module maps, so we
      // add both.
      transitiveModuleMaps.addTransitive(othersTransitiveModuleMaps);
      transitiveModuleMaps.addTransitive(othersDirectModuleMaps);

      // All module maps of direct dependencies are inputs to the current compile independently of
      // the build type.
      if (otherContext.getCppModuleMap() != null) {
        directModuleMaps.add(otherContext.getCppModuleMap().getArtifact());
      }

      defines.addAll(otherContext.getDefines());
      return this;
    }
Example #8
0
  private void init() throws InterruptedException {
    EvaluationResult<SkyValue> result;
    try (AutoProfiler p = AutoProfiler.logged("evaluation and walkable graph", LOG)) {
      result =
          graphFactory.prepareAndGet(
              universeScope, parserPrefix, loadingPhaseThreads, eventHandler);
    }
    graph = result.getWalkableGraph();

    SkyKey universeKey = graphFactory.getUniverseKey(universeScope, parserPrefix);
    universeTargetPatternKeys =
        PrepareDepsOfPatternsFunction.getTargetPatternKeys(
            PrepareDepsOfPatternsFunction.getSkyKeys(universeKey, eventHandler));

    // The prepareAndGet call above evaluates a single PrepareDepsOfPatterns SkyKey.
    // We expect to see either a single successfully evaluated value or a cycle in the result.
    Collection<SkyValue> values = result.values();
    if (!values.isEmpty()) {
      Preconditions.checkState(
          values.size() == 1,
          "Universe query \"%s\" returned multiple" + " values unexpectedly (%s values in result)",
          universeScope,
          values.size());
      Preconditions.checkNotNull(result.get(universeKey), result);
    } else {
      // No values in the result, so there must be an error. We expect the error to be a cycle.
      boolean foundCycle = !Iterables.isEmpty(result.getError().getCycleInfo());
      Preconditions.checkState(
          foundCycle,
          "Universe query \"%s\" failed with non-cycle error: %s",
          universeScope,
          result.getError());
    }
  }
 private CppCompilationContext(
     CommandLineContext commandLineContext,
     ImmutableSet<Artifact> compilationPrerequisites,
     NestedSet<PathFragment> declaredIncludeDirs,
     NestedSet<PathFragment> declaredIncludeWarnDirs,
     NestedSet<Artifact> declaredIncludeSrcs,
     NestedSet<Pair<Artifact, Artifact>> pregreppedHdrs,
     ModuleInfo moduleInfo,
     ModuleInfo picModuleInfo,
     NestedSet<Artifact> transitiveModuleMaps,
     NestedSet<Artifact> directModuleMaps,
     CppModuleMap cppModuleMap,
     boolean provideTransitiveModuleMaps,
     boolean useHeaderModules) {
   Preconditions.checkNotNull(commandLineContext);
   this.commandLineContext = commandLineContext;
   this.declaredIncludeDirs = declaredIncludeDirs;
   this.declaredIncludeWarnDirs = declaredIncludeWarnDirs;
   this.declaredIncludeSrcs = declaredIncludeSrcs;
   this.directModuleMaps = directModuleMaps;
   this.pregreppedHdrs = pregreppedHdrs;
   this.moduleInfo = moduleInfo;
   this.picModuleInfo = picModuleInfo;
   this.transitiveModuleMaps = transitiveModuleMaps;
   this.cppModuleMap = cppModuleMap;
   this.provideTransitiveModuleMaps = provideTransitiveModuleMaps;
   this.useHeaderModules = useHeaderModules;
   this.compilationPrerequisites = compilationPrerequisites;
 }
 /**
  * Returns the configurable attribute conditions necessary to evaluate the given configured
  * target, or null if not all dependencies have yet been SkyFrame-evaluated.
  */
 @Nullable
 private Set<ConfigMatchingProvider> getConfigurableAttributeConditions(
     TargetAndConfiguration ctg, Environment env) {
   if (!(ctg.getTarget() instanceof Rule)) {
     return ImmutableSet.of();
   }
   Rule rule = (Rule) ctg.getTarget();
   RawAttributeMapper mapper = RawAttributeMapper.of(rule);
   Set<SkyKey> depKeys = new LinkedHashSet<>();
   for (Attribute attribute : rule.getAttributes()) {
     for (Label label : mapper.getConfigurabilityKeys(attribute.getName(), attribute.getType())) {
       if (!BuildType.Selector.isReservedLabel(label)) {
         depKeys.add(ConfiguredTargetValue.key(label, ctg.getConfiguration()));
       }
     }
   }
   Map<SkyKey, SkyValue> cts = env.getValues(depKeys);
   if (env.valuesMissing()) {
     return null;
   }
   ImmutableSet.Builder<ConfigMatchingProvider> conditions = ImmutableSet.builder();
   for (SkyValue ctValue : cts.values()) {
     ConfiguredTarget ct = ((ConfiguredTargetValue) ctValue).getConfiguredTarget();
     conditions.add(Preconditions.checkNotNull(ct.getProvider(ConfigMatchingProvider.class)));
   }
   return conditions.build();
 }
Example #11
0
 /** Exits a scope by restoring state from the current continuation */
 void exitScope() {
   Preconditions.checkNotNull(continuation);
   lexicalFrame = continuation.lexicalFrame;
   globalFrame = continuation.globalFrame;
   knownGlobalVariables = continuation.knownGlobalVariables;
   isSkylark = continuation.isSkylark;
   continuation = continuation.continuation;
 }
 /**
  * Returns just the .params file portion of the command-line as a {@link CommandLine}.
  *
  * @throws IllegalStateException if the command-line cannot be split
  */
 CommandLine paramCmdLine() {
   Preconditions.checkNotNull(paramFile);
   return new CommandLine() {
     @Override
     public Iterable<String> arguments() {
       return splitCommandline().getSecond();
     }
   };
 }
Example #13
0
  @Nullable
  private AspectValue createAspect(
      Environment env,
      AspectKey key,
      ConfiguredAspectFactory aspectFactory,
      RuleConfiguredTarget associatedTarget,
      Set<ConfigMatchingProvider> configConditions,
      ListMultimap<Attribute, ConfiguredTarget> directDeps,
      NestedSetBuilder<Package> transitivePackages)
      throws AspectFunctionException, InterruptedException {

    SkyframeBuildView view = buildViewProvider.getSkyframeBuildView();
    BuildConfiguration configuration = associatedTarget.getConfiguration();

    StoredEventHandler events = new StoredEventHandler();
    CachingAnalysisEnvironment analysisEnvironment =
        view.createAnalysisEnvironment(key, false, events, env, configuration);
    if (env.valuesMissing()) {
      return null;
    }

    ConfiguredAspect configuredAspect =
        view.getConfiguredTargetFactory()
            .createAspect(
                analysisEnvironment,
                associatedTarget,
                aspectFactory,
                key.getAspect(),
                directDeps,
                configConditions,
                view.getHostConfiguration(associatedTarget.getConfiguration()));

    events.replayOn(env.getListener());
    if (events.hasErrors()) {
      analysisEnvironment.disable(associatedTarget.getTarget());
      throw new AspectFunctionException(
          new AspectCreationException(
              "Analysis of target '" + associatedTarget.getLabel() + "' failed; build aborted"));
    }
    Preconditions.checkState(
        !analysisEnvironment.hasErrors(), "Analysis environment hasError() but no errors reported");

    if (env.valuesMissing()) {
      return null;
    }

    analysisEnvironment.disable(associatedTarget.getTarget());
    Preconditions.checkNotNull(configuredAspect);

    return new AspectValue(
        key,
        associatedTarget.getLabel(),
        associatedTarget.getTarget().getLocation(),
        configuredAspect,
        ImmutableList.copyOf(analysisEnvironment.getRegisteredActions()),
        transitivePackages.build());
  }
Example #14
0
 /**
  * Constructs an Environment. This is the main, most basic constructor.
  *
  * @param globalFrame a frame for the global Environment
  * @param dynamicFrame a frame for the dynamic Environment
  * @param eventHandler an EventHandler for warnings, errors, etc
  * @param importedExtensions Extension-s from which to import bindings with load()
  * @param isSkylark true if in Skylark context
  * @param fileContentHashCode a hash for the source file being evaluated, if any
  * @param isLoadingPhase true if in loading phase
  */
 private Environment(
     Frame globalFrame,
     Frame dynamicFrame,
     EventHandler eventHandler,
     Map<String, Extension> importedExtensions,
     boolean isSkylark,
     @Nullable String fileContentHashCode,
     boolean isLoadingPhase) {
   this.globalFrame = Preconditions.checkNotNull(globalFrame);
   this.dynamicFrame = Preconditions.checkNotNull(dynamicFrame);
   Preconditions.checkArgument(globalFrame.mutability().isMutable());
   Preconditions.checkArgument(dynamicFrame.mutability().isMutable());
   this.eventHandler = eventHandler;
   this.importedExtensions = importedExtensions;
   this.isSkylark = isSkylark;
   this.fileContentHashCode = fileContentHashCode;
   this.isLoadingPhase = isLoadingPhase;
 }
Example #15
0
 /**
  * Returns a hash code calculated from the hash code of this Environment and the transitive
  * closure of other Environments it loads.
  */
 public String getTransitiveContentHashCode() {
   // Calculate a new hash from the hash of the loaded Extension-s.
   Fingerprint fingerprint = new Fingerprint();
   fingerprint.addString(Preconditions.checkNotNull(fileContentHashCode));
   TreeSet<String> importStrings = new TreeSet<>(importedExtensions.keySet());
   for (String importString : importStrings) {
     fingerprint.addString(importedExtensions.get(importString).getTransitiveContentHashCode());
   }
   return fingerprint.hexDigestAndReset();
 }
Example #16
0
 @Override
 public void process(Iterable<Target> partialResult)
     throws QueryException, InterruptedException {
   Preconditions.checkNotNull(pending, "Reuse of the callback is not allowed");
   pending.addAll(uniquifier.unique(partialResult));
   if (pending.size() >= batchThreshold) {
     callback.process(pending);
     pending = new ArrayList<>();
   }
 }
Example #17
0
 FakeCppCompileAction(
     ActionOwner owner,
     ImmutableList<String> features,
     FeatureConfiguration featureConfiguration,
     CcToolchainFeatures.Variables variables,
     Artifact sourceFile,
     boolean shouldScanIncludes,
     Label sourceLabel,
     NestedSet<Artifact> mandatoryInputs,
     Artifact outputFile,
     PathFragment tempOutputFile,
     DotdFile dotdFile,
     BuildConfiguration configuration,
     CppConfiguration cppConfiguration,
     CppCompilationContext context,
     Class<? extends CppCompileActionContext> actionContext,
     ImmutableList<String> copts,
     Predicate<String> nocopts,
     RuleContext ruleContext) {
   super(
       owner,
       features,
       featureConfiguration,
       variables,
       sourceFile,
       shouldScanIncludes,
       sourceLabel,
       mandatoryInputs,
       outputFile,
       dotdFile,
       null,
       null,
       null,
       configuration,
       cppConfiguration,
       // We only allow inclusion of header files explicitly declared in
       // "srcs", so we only use declaredIncludeSrcs, not declaredIncludeDirs.
       // (Disallowing use of undeclared headers for cc_fake_binary is needed
       // because the header files get included in the runfiles for the
       // cc_fake_binary and for the negative compilation tests that depend on
       // the cc_fake_binary, and the runfiles must be determined at analysis
       // time, so they can't depend on the contents of the ".d" file.)
       CppCompilationContext.disallowUndeclaredHeaders(context),
       actionContext,
       copts,
       nocopts,
       VOID_SPECIAL_INPUTS_HANDLER,
       ImmutableList.<IncludeScannable>of(),
       GUID,
       ImmutableSet.<String>of(),
       CppCompileAction.CPP_COMPILE,
       ruleContext);
   this.tempOutputFile = Preconditions.checkNotNull(tempOutputFile);
 }
Example #18
0
 private XcodeProvider(Builder builder) {
   this.label = Preconditions.checkNotNull(builder.label);
   this.propagatedUserHeaderSearchPaths = builder.propagatedUserHeaderSearchPaths.build();
   this.nonPropagatedUserHeaderSearchPaths = builder.nonPropagatedUserHeaderSearchPaths.build();
   this.propagatedHeaderSearchPaths = builder.propagatedHeaderSearchPaths.build();
   this.nonPropagatedHeaderSearchPaths = builder.nonPropagatedHeaderSearchPaths.build();
   this.bundleInfoplist = builder.bundleInfoplist;
   this.propagatedDependencies = builder.propagatedDependencies.build();
   this.nonPropagatedDependencies = builder.nonPropagatedDependencies.build();
   this.jreDependencies = builder.jreDependencies.build();
   this.xcodeprojBuildSettings = builder.xcodeprojBuildSettings.build();
   this.companionTargetXcodeprojBuildSettings =
       builder.companionTargetXcodeprojBuildSettings.build();
   this.copts = builder.copts.build();
   this.compilationModeCopts = builder.compilationModeCopts.build();
   this.productType = Preconditions.checkNotNull(builder.productType);
   this.headers = builder.headers.build();
   this.compilationArtifacts = builder.compilationArtifacts;
   this.objcProvider = Preconditions.checkNotNull(builder.objcProvider);
   this.testHost = Preconditions.checkNotNull(builder.testHost);
   this.inputsToXcodegen = builder.inputsToXcodegen.build();
   this.additionalSources = builder.additionalSources.build();
   this.extensions = builder.extensions.build();
   this.architecture = Preconditions.checkNotNull(builder.architecture);
   this.generateCompanionLibTarget = builder.generateCompanionLibTarget;
   this.configurationDistinguisher =
       Preconditions.checkNotNull(builder.configurationDistinguisher);
 }
Example #19
0
 /**
  * Invokes the appropriate constructor to create a {@link ConfiguredTarget} instance.
  *
  * <p>For use in {@code ConfiguredTargetFunction}.
  *
  * <p>Returns null if Skyframe deps are missing or upon certain errors.
  */
 @Nullable
 ConfiguredTarget createConfiguredTarget(
     Target target,
     BuildConfiguration configuration,
     CachingAnalysisEnvironment analysisEnvironment,
     ListMultimap<Attribute, ConfiguredTarget> prerequisiteMap,
     Set<ConfigMatchingProvider> configConditions)
     throws InterruptedException {
   Preconditions.checkState(
       enableAnalysis, "Already in execution phase %s %s", target, configuration);
   Preconditions.checkNotNull(analysisEnvironment);
   Preconditions.checkNotNull(target);
   Preconditions.checkNotNull(prerequisiteMap);
   return factory.createConfiguredTarget(
       analysisEnvironment,
       artifactFactory,
       target,
       configuration,
       getHostConfiguration(configuration),
       prerequisiteMap,
       configConditions);
 }
Example #20
0
  /**
   * Creates and returns a rule instance.
   *
   * <p>It is the caller's responsibility to add the rule to the package (the caller may choose not
   * to do so if, for example, the rule has errors).
   */
  static Rule createRule(
      Package.Builder pkgBuilder,
      RuleClass ruleClass,
      BuildLangTypedAttributeValuesMap attributeValues,
      EventHandler eventHandler,
      @Nullable FuncallExpression ast,
      Location location,
      @Nullable Environment env)
      throws InvalidRuleException, InterruptedException {
    Preconditions.checkNotNull(ruleClass);
    String ruleClassName = ruleClass.getName();
    Object nameObject = attributeValues.getAttributeValue("name");
    if (nameObject == null) {
      throw new InvalidRuleException(ruleClassName + " rule has no 'name' attribute");
    } else if (!(nameObject instanceof String)) {
      throw new InvalidRuleException(ruleClassName + " 'name' attribute must be a string");
    }
    String name = (String) nameObject;
    Label label;
    try {
      // Test that this would form a valid label name -- in particular, this
      // catches cases where Makefile variables $(foo) appear in "name".
      label = pkgBuilder.createLabel(name);
    } catch (LabelSyntaxException e) {
      throw new InvalidRuleException("illegal rule name: " + name + ": " + e.getMessage());
    }
    boolean inWorkspaceFile = pkgBuilder.isWorkspace();
    if (ruleClass.getWorkspaceOnly() && !inWorkspaceFile) {
      throw new RuleFactory.InvalidRuleException(
          ruleClass + " must be in the WORKSPACE file " + "(used by " + label + ")");
    } else if (!ruleClass.getWorkspaceOnly() && inWorkspaceFile) {
      throw new RuleFactory.InvalidRuleException(
          ruleClass + " cannot be in the WORKSPACE file " + "(used by " + label + ")");
    }

    AttributesAndLocation generator =
        generatorAttributesForMacros(attributeValues, env, location, label);
    try {
      return ruleClass.createRule(
          pkgBuilder,
          label,
          generator.attributes,
          eventHandler,
          ast,
          generator.location,
          new AttributeContainer(ruleClass));
    } catch (LabelSyntaxException e) {
      throw new RuleFactory.InvalidRuleException(ruleClass + " " + e.getMessage());
    }
  }
  private WalkableGraph getGraphFromPatternsEvaluation(
      ImmutableList<String> patternSequence, boolean successExpected, boolean keepGoing)
      throws InterruptedException {
    SkyKey independentTarget = PrepareDepsOfPatternsValue.key(patternSequence, "");
    ImmutableList<SkyKey> singletonTargetPattern = ImmutableList.of(independentTarget);

    // When PrepareDepsOfPatternsFunction completes evaluation,
    EvaluationResult<SkyValue> evaluationResult =
        getSkyframeExecutor()
            .getDriverForTesting()
            .evaluate(singletonTargetPattern, keepGoing, LOADING_PHASE_THREADS, eventCollector);
    // The evaluation has no errors if success was expected.
    assertThat(evaluationResult.hasError()).isNotEqualTo(successExpected);
    return Preconditions.checkNotNull(evaluationResult.getWalkableGraph());
  }
Example #22
0
 /**
  * Modifies a binding in the current Frame of this Environment, as would an {@link
  * AssignmentStatement}. Does not try to modify an inherited binding. This will shadow any
  * inherited binding, which may be an error that you want to guard against before calling this
  * function.
  *
  * @param varname the name of the variable to be bound
  * @param value the value to bind to the variable
  * @return this Environment, in fluid style
  */
 public Environment update(String varname, Object value) throws EvalException {
   Preconditions.checkNotNull(value, "update(value == null)");
   // prevents clashes between static and dynamic variables.
   if (dynamicFrame.get(varname) != null) {
     throw new EvalException(
         null, String.format("Trying to update special read-only global variable '%s'", varname));
   }
   if (isKnownGlobalVariable(varname)) {
     throw new EvalException(
         null, String.format("Trying to update read-only global variable '%s'", varname));
   }
   try {
     currentFrame().put(this, varname, Preconditions.checkNotNull(value));
   } catch (MutabilityException e) {
     // Note that since at this time we don't accept the global keyword, and don't have closures,
     // end users should never be able to mutate a frozen Environment, and a MutabilityException
     // is therefore a failed assertion for Bazel. However, it is possible to shadow a binding
     // imported from a parent Environment by updating the current Environment, which will not
     // trigger a MutabilityException.
     throw new AssertionError(
         Printer.format("Can't update %s to %r in frozen environment", varname, value), e);
   }
   return this;
 }
Example #23
0
  @Override
  protected void preloadOrThrow(QueryExpression caller, Collection<String> patterns)
      throws QueryException, TargetParsingException {
    Map<String, SkyKey> keys = new HashMap<>(patterns.size());

    for (String pattern : patterns) {
      try {
        keys.put(
            pattern,
            TargetPatternValue.key(
                pattern, TargetPatternEvaluator.DEFAULT_FILTERING_POLICY, parserPrefix));
      } catch (TargetParsingException e) {
        reportBuildFileError(caller, e.getMessage());
      }
    }
    // Get all the patterns in one batch call
    Map<SkyKey, SkyValue> existingPatterns = graph.getSuccessfulValues(keys.values());

    for (String pattern : patterns) {
      SkyKey patternKey = keys.get(pattern);
      if (patternKey == null) {
        // Exception was thrown when creating key above. Skip.
        continue;
      }
      TargetParsingException targetParsingException = null;
      if (existingPatterns.containsKey(patternKey)) {
        // The graph already contains a value or exception for this target pattern, so we use it.
        TargetPatternValue value = (TargetPatternValue) existingPatterns.get(patternKey);
        if (value != null) {
          precomputedPatterns.put(pattern, value.getTargets().getTargets());
        } else {
          // Because the graph was always initialized via a keep_going build, we know that the
          // exception stored here must be a TargetParsingException. Thus the comment in
          // SkyframeTargetPatternEvaluator#parseTargetPatternKeys describing the situation in which
          // the exception acceptance must be looser does not apply here.
          targetParsingException =
              (TargetParsingException)
                  Preconditions.checkNotNull(graph.getException(patternKey), pattern);
        }
      }

      if (targetParsingException != null) {
        reportBuildFileError(caller, targetParsingException.getMessage());
      }
    }
  }
Example #24
0
  // This is safe because of the type checking
  @SuppressWarnings("unchecked")
  private SkylarkNestedSet(
      Order order,
      SkylarkType contentType,
      Object item,
      Location loc,
      List<Object> items,
      List<NestedSet<Object>> transitiveItems)
      throws EvalException {

    // Adding the item
    if (item instanceof SkylarkNestedSet) {
      SkylarkNestedSet nestedSet = (SkylarkNestedSet) item;
      if (!nestedSet.isEmpty()) {
        contentType = checkType(contentType, nestedSet.contentType, loc);
        transitiveItems.add((NestedSet<Object>) nestedSet.set);
      }
    } else if (item instanceof SkylarkList) {
      // TODO(bazel-team): we should check ImmutableList here but it screws up genrule at line 43
      for (Object object : (SkylarkList) item) {
        contentType = checkType(contentType, SkylarkType.of(object.getClass()), loc);
        checkImmutable(object, loc);
        items.add(object);
      }
    } else {
      throw new EvalException(
          loc,
          String.format("cannot add value of type '%s' to a set", EvalUtils.getDataTypeName(item)));
    }
    this.contentType = Preconditions.checkNotNull(contentType, "type cannot be null");

    // Initializing the real nested set
    NestedSetBuilder<Object> builder = new NestedSetBuilder<>(order);
    builder.addAll(items);
    try {
      for (NestedSet<Object> nestedSet : transitiveItems) {
        builder.addTransitive(nestedSet);
      }
    } catch (IllegalStateException e) {
      throw new EvalException(loc, e.getMessage());
    }
    this.set = builder.build();
    this.items = ImmutableList.copyOf(items);
    this.transitiveItems = ImmutableList.copyOf(transitiveItems);
  }
Example #25
0
 public SkyQueryEnvironment(
     boolean keepGoing,
     boolean strictScope,
     int loadingPhaseThreads,
     Predicate<Label> labelFilter,
     EventHandler eventHandler,
     Set<Setting> settings,
     Iterable<QueryFunction> extraFunctions,
     String parserPrefix,
     WalkableGraphFactory graphFactory,
     List<String> universeScope,
     PathPackageLocator pkgPath) {
   super(keepGoing, strictScope, labelFilter, eventHandler, settings, extraFunctions);
   this.loadingPhaseThreads = loadingPhaseThreads;
   this.graphFactory = graphFactory;
   this.pkgPath = pkgPath;
   this.universeScope = Preconditions.checkNotNull(universeScope);
   this.parserPrefix = parserPrefix;
   Preconditions.checkState(
       !universeScope.isEmpty(), "No queries can be performed with an empty universe");
 }
Example #26
0
 @Override
 public Target getTarget(Label label) throws TargetNotFoundException, QueryException {
   SkyKey packageKey = getPackageKeyAndValidateLabel(label);
   if (!graph.exists(packageKey)) {
     throw new QueryException(packageKey + " does not exist in graph");
   }
   try {
     PackageValue packageValue = (PackageValue) graph.getValue(packageKey);
     if (packageValue != null) {
       Package pkg = packageValue.getPackage();
       if (pkg.containsErrors()) {
         throw new BuildFileContainsErrorsException(label.getPackageIdentifier());
       }
       return packageValue.getPackage().getTarget(label.getName());
     } else {
       throw (NoSuchThingException)
           Preconditions.checkNotNull(graph.getException(packageKey), label);
     }
   } catch (NoSuchThingException e) {
     throw new TargetNotFoundException(e);
   }
 }
Example #27
0
 public HashLine(char[] buffer, PathFragment defaultPath) {
   CharSequence bufString = CharBuffer.wrap(buffer);
   Matcher m = pattern.matcher(bufString);
   List<SingleHashLine> unorderedTable = new ArrayList<>();
   Map<String, PathFragment> pathCache = new HashMap<>();
   while (m.find()) {
     String pathString = m.group(2);
     PathFragment pathFragment = pathCache.get(pathString);
     if (pathFragment == null) {
       pathFragment = defaultPath.getRelative(pathString);
       pathCache.put(pathString, pathFragment);
     }
     unorderedTable.add(
         new SingleHashLine(
             m.start(0) + 1, // offset (+1 to skip \n in pattern)
             Integer.parseInt(m.group(1)), // line number
             pathFragment)); // filename is an absolute path
   }
   this.table = hashOrdering.immutableSortedCopy(unorderedTable);
   this.bufferLength = buffer.length;
   this.defaultPath = Preconditions.checkNotNull(defaultPath);
 }
Example #28
0
  @Override
  public ConfiguredTarget create(RuleContext ruleContext)
      throws RuleErrorException, InterruptedException {
    TransitiveInfoCollection lipoContextCollector =
        ruleContext.getPrerequisite(":lipo_context_collector", Mode.DONT_CHECK);
    if (lipoContextCollector != null
        && lipoContextCollector.getProvider(LipoContextProvider.class) == null) {
      ruleContext.ruleError("--lipo_context must point to a cc_binary or a cc_test rule");
      return null;
    }

    CppConfiguration cppConfiguration =
        Preconditions.checkNotNull(ruleContext.getFragment(CppConfiguration.class));
    Path fdoZip =
        ruleContext.getConfiguration().getCompilationMode() == CompilationMode.OPT
            ? cppConfiguration.getFdoZip()
            : null;
    SkyKey fdoKey =
        FdoSupportValue.key(
            cppConfiguration.getLipoMode(), fdoZip, cppConfiguration.getFdoInstrument());

    SkyFunction.Environment skyframeEnv = ruleContext.getAnalysisEnvironment().getSkyframeEnv();
    FdoSupportValue fdoSupport;
    try {
      fdoSupport =
          (FdoSupportValue)
              skyframeEnv.getValueOrThrow(fdoKey, FdoException.class, IOException.class);
    } catch (FdoException | IOException e) {
      ruleContext.ruleError("cannot initialize FDO: " + e.getMessage());
      return null;
    }

    if (skyframeEnv.valuesMissing()) {
      return null;
    }

    final Label label = ruleContext.getLabel();
    final NestedSet<Artifact> crosstool =
        ruleContext
            .getPrerequisite("all_files", Mode.HOST)
            .getProvider(FileProvider.class)
            .getFilesToBuild();
    final NestedSet<Artifact> crosstoolMiddleman = getFiles(ruleContext, "all_files");
    final NestedSet<Artifact> compile = getFiles(ruleContext, "compiler_files");
    final NestedSet<Artifact> strip = getFiles(ruleContext, "strip_files");
    final NestedSet<Artifact> objcopy = getFiles(ruleContext, "objcopy_files");
    final NestedSet<Artifact> link = getFiles(ruleContext, "linker_files");
    final NestedSet<Artifact> dwp = getFiles(ruleContext, "dwp_files");
    final NestedSet<Artifact> libcLink = inputsForLibc(ruleContext);
    String purposePrefix = Actions.escapeLabel(label) + "_";
    String runtimeSolibDirBase = "_solib_" + "_" + Actions.escapeLabel(label);
    final PathFragment runtimeSolibDir =
        ruleContext.getConfiguration().getBinFragment().getRelative(runtimeSolibDirBase);

    // Static runtime inputs.
    TransitiveInfoCollection staticRuntimeLibDep =
        selectDep(ruleContext, "static_runtime_libs", cppConfiguration.getStaticRuntimeLibsLabel());
    final NestedSet<Artifact> staticRuntimeLinkInputs;
    final Artifact staticRuntimeLinkMiddleman;
    if (cppConfiguration.supportsEmbeddedRuntimes()) {
      staticRuntimeLinkInputs =
          staticRuntimeLibDep.getProvider(FileProvider.class).getFilesToBuild();
    } else {
      staticRuntimeLinkInputs = NestedSetBuilder.emptySet(Order.STABLE_ORDER);
    }

    if (!staticRuntimeLinkInputs.isEmpty()) {
      NestedSet<Artifact> staticRuntimeLinkMiddlemanSet =
          CompilationHelper.getAggregatingMiddleman(
              ruleContext, purposePrefix + "static_runtime_link", staticRuntimeLibDep);
      staticRuntimeLinkMiddleman =
          staticRuntimeLinkMiddlemanSet.isEmpty()
              ? null
              : Iterables.getOnlyElement(staticRuntimeLinkMiddlemanSet);
    } else {
      staticRuntimeLinkMiddleman = null;
    }

    Preconditions.checkState(
        (staticRuntimeLinkMiddleman == null) == staticRuntimeLinkInputs.isEmpty());

    // Dynamic runtime inputs.
    TransitiveInfoCollection dynamicRuntimeLibDep =
        selectDep(
            ruleContext, "dynamic_runtime_libs", cppConfiguration.getDynamicRuntimeLibsLabel());
    final NestedSet<Artifact> dynamicRuntimeLinkInputs;
    final Artifact dynamicRuntimeLinkMiddleman;
    if (cppConfiguration.supportsEmbeddedRuntimes()) {
      NestedSetBuilder<Artifact> dynamicRuntimeLinkInputsBuilder = NestedSetBuilder.stableOrder();
      for (Artifact artifact :
          dynamicRuntimeLibDep.getProvider(FileProvider.class).getFilesToBuild()) {
        if (CppHelper.SHARED_LIBRARY_FILETYPES.matches(artifact.getFilename())) {
          dynamicRuntimeLinkInputsBuilder.add(
              SolibSymlinkAction.getCppRuntimeSymlink(
                  ruleContext, artifact, runtimeSolibDirBase, ruleContext.getConfiguration()));
        } else {
          dynamicRuntimeLinkInputsBuilder.add(artifact);
        }
      }
      dynamicRuntimeLinkInputs = dynamicRuntimeLinkInputsBuilder.build();
    } else {
      dynamicRuntimeLinkInputs = NestedSetBuilder.emptySet(Order.STABLE_ORDER);
    }

    if (!dynamicRuntimeLinkInputs.isEmpty()) {
      List<Artifact> dynamicRuntimeLinkMiddlemanSet =
          CppHelper.getAggregatingMiddlemanForCppRuntimes(
              ruleContext,
              purposePrefix + "dynamic_runtime_link",
              dynamicRuntimeLibDep,
              runtimeSolibDirBase,
              ruleContext.getConfiguration());
      dynamicRuntimeLinkMiddleman =
          dynamicRuntimeLinkMiddlemanSet.isEmpty()
              ? null
              : Iterables.getOnlyElement(dynamicRuntimeLinkMiddlemanSet);
    } else {
      dynamicRuntimeLinkMiddleman = null;
    }

    Preconditions.checkState(
        (dynamicRuntimeLinkMiddleman == null) == dynamicRuntimeLinkInputs.isEmpty());

    CppCompilationContext.Builder contextBuilder = new CppCompilationContext.Builder(ruleContext);
    CppModuleMap moduleMap = createCrosstoolModuleMap(ruleContext);
    if (moduleMap != null) {
      contextBuilder.setCppModuleMap(moduleMap);
    }
    final CppCompilationContext context = contextBuilder.build();
    boolean supportsParamFiles = ruleContext.attributes().get("supports_param_files", BOOLEAN);
    boolean supportsHeaderParsing =
        ruleContext.attributes().get("supports_header_parsing", BOOLEAN);

    NestedSetBuilder<Pair<String, String>> coverageEnvironment = NestedSetBuilder.compileOrder();

    coverageEnvironment.add(
        Pair.of("COVERAGE_GCOV_PATH", cppConfiguration.getGcovExecutable().getPathString()));
    if (cppConfiguration.getFdoInstrument() != null) {
      coverageEnvironment.add(
          Pair.of("FDO_DIR", cppConfiguration.getFdoInstrument().getPathString()));
    }

    CcToolchainProvider provider =
        new CcToolchainProvider(
            cppConfiguration,
            crosstool,
            fullInputsForCrosstool(ruleContext, crosstoolMiddleman),
            compile,
            strip,
            objcopy,
            fullInputsForLink(ruleContext, link),
            dwp,
            libcLink,
            staticRuntimeLinkInputs,
            staticRuntimeLinkMiddleman,
            dynamicRuntimeLinkInputs,
            dynamicRuntimeLinkMiddleman,
            runtimeSolibDir,
            context,
            supportsParamFiles,
            supportsHeaderParsing,
            getBuildVariables(ruleContext),
            getBuiltinIncludes(ruleContext),
            coverageEnvironment.build());
    RuleConfiguredTargetBuilder builder =
        new RuleConfiguredTargetBuilder(ruleContext)
            .add(CcToolchainProvider.class, provider)
            .add(FdoSupportProvider.class, new FdoSupportProvider(fdoSupport.getFdoSupport()))
            .setFilesToBuild(new NestedSetBuilder<Artifact>(Order.STABLE_ORDER).build())
            .add(RunfilesProvider.class, RunfilesProvider.simple(Runfiles.EMPTY));

    // If output_license is specified on the cc_toolchain rule, override the transitive licenses
    // with that one. This is necessary because cc_toolchain is used in the target configuration,
    // but it is sort-of-kind-of a tool, but various parts of it are linked into the output...
    // ...so we trust the judgment of the author of the cc_toolchain rule to figure out what
    // licenses should be propagated to C++ targets.
    License outputLicense = ruleContext.getRule().getToolOutputLicense(ruleContext.attributes());
    if (outputLicense != null && outputLicense != License.NO_LICENSE) {
      final NestedSet<TargetLicense> license =
          NestedSetBuilder.create(
              Order.STABLE_ORDER, new TargetLicense(ruleContext.getLabel(), outputLicense));
      LicensesProvider licensesProvider =
          new LicensesProvider() {
            @Override
            public NestedSet<TargetLicense> getTransitiveLicenses() {
              return license;
            }
          };

      builder.add(LicensesProvider.class, licensesProvider);
    }

    return builder.build();
  }
Example #29
0
 /** Sets whether to enable compression of the output deploy archive. */
 public DeployArchiveBuilder setCompression(Compression compress) {
   this.compression = Preconditions.checkNotNull(compress);
   return this;
 }
Example #30
0
 /** Sets the artifact to create with the action. */
 public DeployArchiveBuilder setOutputJar(Artifact outputJar) {
   this.outputJar = Preconditions.checkNotNull(outputJar);
   return this;
 }