com.google.devtools.build.lib.syntax.StarlarkSemantics Java Examples

The following examples show how to use com.google.devtools.build.lib.syntax.StarlarkSemantics. 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: ExtremaPackageLoadingListener.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void onLoadingCompleteAndSuccessful(
    Package pkg, StarlarkSemantics starlarkSemantics, long loadTimeNanos) {
  if (currentNumPackagesToTrack == 0) {
    // Micro-optimization - no need to track.
    return;
  }

  long loadTimeMillis = TimeUnit.MILLISECONDS.convert(loadTimeNanos, TimeUnit.NANOSECONDS);
  slowestPackagesToLoad.aggregate(
      new PackageIdentifierAndLong(pkg.getPackageIdentifier(), loadTimeMillis));

  packagesWithMostComputationSteps.aggregate(
      new PackageIdentifierAndLong(pkg.getPackageIdentifier(), pkg.getComputationSteps()));

  largestPackages.aggregate(
      new PackageIdentifierAndLong(pkg.getPackageIdentifier(), pkg.getTargets().size()));

  packagesWithMostTransitiveLoads.aggregate(
      new PackageIdentifierAndLong(
          pkg.getPackageIdentifier(), pkg.getStarlarkFileDependencies().size()));
}
 
Example #2
Source File: StarlarkDebugServerTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Creates and starts a worker thread parsing, resolving, and executing the given Starlark file to
 * populate the specified module, or if none is given, in a fresh module with a default
 * environment.
 */
private static Thread execInWorkerThread(ParserInput input, @Nullable Module module) {
  Thread javaThread =
      new Thread(
          () -> {
            try (Mutability mu = Mutability.create("test")) {
              StarlarkThread thread = new StarlarkThread(mu, StarlarkSemantics.DEFAULT);
              EvalUtils.exec(
                  input, FileOptions.DEFAULT, module != null ? module : Module.create(), thread);
            } catch (SyntaxError.Exception | EvalException | InterruptedException ex) {
              throw new AssertionError(ex);
            }
          });
  javaThread.start();
  return javaThread;
}
 
Example #3
Source File: ResolvedToolchainContext.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Override
public ToolchainInfo getIndex(StarlarkSemantics semantics, Object key) throws EvalException {
  Label toolchainTypeLabel = transformKey(key, repoMapping());

  if (!containsKey(semantics, key)) {
    // TODO(bazel-configurability): The list of available toolchain types is confusing in the
    // presence of aliases, since it only contains the actual label, not the alias passed to the
    // rule definition.
    throw Starlark.errorf(
        "In %s, toolchain type %s was requested but only types [%s] are configured",
        targetDescription(),
        toolchainTypeLabel,
        requiredToolchainTypes().stream()
            .map(ToolchainTypeInfo::typeLabel)
            .map(Label::toString)
            .collect(joining(", ")));
  }
  return forToolchainType(toolchainTypeLabel);
}
 
Example #4
Source File: WorkspaceFactoryHelper.java    From bazel with Apache License 2.0 6 votes vote down vote up
static void addBindRule(
    Package.Builder pkg,
    RuleClass bindRuleClass,
    Label virtual,
    Label actual,
    StarlarkSemantics semantics,
    ImmutableList<StarlarkThread.CallStackEntry> callstack)
    throws RuleFactory.InvalidRuleException, Package.NameConflictException, InterruptedException {

  Map<String, Object> attributes = Maps.newHashMap();
  // Bound rules don't have a name field, but this works because we don't want more than one
  // with the same virtual name.
  attributes.put("name", virtual.getName());
  if (actual != null) {
    attributes.put("actual", actual);
  }
  StoredEventHandler handler = new StoredEventHandler();
  BuildLangTypedAttributeValuesMap attributeValues =
      new BuildLangTypedAttributeValuesMap(attributes);
  Rule rule =
      RuleFactory.createRule(pkg, bindRuleClass, attributeValues, handler, semantics, callstack);
  overwriteRule(pkg, rule);
  rule.setVisibility(ConstantRuleVisibility.PUBLIC);
}
 
Example #5
Source File: Label.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the execution root for the workspace, relative to the execroot (e.g., for label
 * {@code @repo//pkg:b}, it will returns {@code external/repo/pkg} and for label {@code //pkg:a},
 * it will returns an empty string.
 */
@StarlarkMethod(
    name = "workspace_root",
    structField = true,
    doc =
        "Returns the execution root for the workspace of this label, relative to the execroot. "
            + "For instance:<br>"
            + "<pre class=language-python>Label(\"@repo//pkg/foo:abc\").workspace_root =="
            + " \"external/repo\"</pre>",
    useStarlarkSemantics = true)
public String getWorkspaceRoot(StarlarkSemantics semantics) {
  if (semantics.experimentalSiblingRepositoryLayout()) {
    return packageIdentifier.getRepository().getExecPath(true).toString();
  } else {
    return packageIdentifier.getRepository().getSourceRoot().toString();
  }
}
 
Example #6
Source File: WorkspaceFactory.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * @param builder a builder for the Workspace
 * @param ruleClassProvider a provider for known rule classes
 * @param environmentExtensions the Starlark environment extensions
 * @param mutability the Mutability for the current evaluation context
 * @param installDir the install directory
 * @param workspaceDir the workspace directory
 * @param defaultSystemJavabaseDir the local JDK directory
 */
public WorkspaceFactory(
    Package.Builder builder,
    RuleClassProvider ruleClassProvider,
    ImmutableList<EnvironmentExtension> environmentExtensions,
    Mutability mutability,
    boolean allowOverride,
    @Nullable Path installDir,
    @Nullable Path workspaceDir,
    @Nullable Path defaultSystemJavabaseDir,
    StarlarkSemantics starlarkSemantics) {
  this.builder = builder;
  this.mutability = mutability;
  this.installDir = installDir;
  this.workspaceDir = workspaceDir;
  this.defaultSystemJavabaseDir = defaultSystemJavabaseDir;
  this.environmentExtensions = environmentExtensions;
  this.ruleFactory = new RuleFactory(ruleClassProvider);
  this.workspaceGlobals = new WorkspaceGlobals(allowOverride, ruleFactory);
  this.starlarkSemantics = starlarkSemantics;
  this.workspaceFunctions =
      createWorkspaceFunctions(
          allowOverride, ruleFactory, this.workspaceGlobals, starlarkSemantics);
}
 
Example #7
Source File: WorkspaceFactory.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static ImmutableMap<String, Object> createWorkspaceFunctions(
    boolean allowOverride,
    RuleFactory ruleFactory,
    WorkspaceGlobals workspaceGlobals,
    StarlarkSemantics starlarkSemantics) {
  ImmutableMap.Builder<String, Object> env = ImmutableMap.builder();
  Starlark.addMethods(env, workspaceGlobals, starlarkSemantics);

  for (String ruleClass : ruleFactory.getRuleClassNames()) {
    // There is both a "bind" WORKSPACE function and a "bind" rule. In workspace files,
    // the non-rule function takes precedence.
    // TODO(cparsons): Rule functions should not be added to WORKSPACE files.
    if (!ruleClass.equals("bind")) {
      StarlarkCallable ruleFunction = newRuleFunction(ruleFactory, ruleClass, allowOverride);
      env.put(ruleClass, ruleFunction);
    }
  }

  return env.build();
}
 
Example #8
Source File: StarlarkCallbackHelper.java    From bazel with Apache License 2.0 5 votes vote down vote up
public StarlarkCallbackHelper(
    StarlarkFunction callback,
    StarlarkSemantics starlarkSemantics,
    BazelStarlarkContext context) {
  this.callback = callback;
  this.starlarkSemantics = starlarkSemantics;
  this.context = context;
}
 
Example #9
Source File: WorkspaceFactoryTestHelper.java    From bazel with Apache License 2.0 5 votes vote down vote up
WorkspaceFactoryTestHelper(boolean allowOverride, Root root) {
  this.root = root;
  this.exception = null;
  this.events = null;
  this.allowOverride = allowOverride;
  this.starlarkSemantics = StarlarkSemantics.DEFAULT;
}
 
Example #10
Source File: StarlarkDefinedConfigTransition.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static StarlarkDefinedConfigTransition newRegularTransition(
    StarlarkCallable impl,
    List<String> inputs,
    List<String> outputs,
    StarlarkSemantics semantics,
    StarlarkThread thread) {
  return new RegularTransition(
      impl, inputs, outputs, semantics, BazelStarlarkContext.from(thread));
}
 
Example #11
Source File: WorkspaceFactory.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Returns the entries to populate the "native" module with, for WORKSPACE-loaded .bzl files. */
static ImmutableMap<String, Object> createNativeModuleBindings(
    RuleClassProvider ruleClassProvider, String version) {
  // Machinery to build the collection of workspace functions.
  RuleFactory ruleFactory = new RuleFactory(ruleClassProvider);
  WorkspaceGlobals workspaceGlobals = new WorkspaceGlobals(/*allowOverride=*/ false, ruleFactory);
  // TODO(bazel-team): StarlarkSemantics should be a parameter here, as native module can be
  // configured by flags. [brandjon: This should be possible now that we create the native module
  // in StarlarkBuiltinsFunction. We could defer creation until the StarlarkSemantics are known.
  // But mind that some code may depend on being able to enumerate all possible entries regardless
  // of the particular semantics.]
  ImmutableMap<String, Object> workspaceFunctions =
      createWorkspaceFunctions(
          /*allowOverride=*/ false, ruleFactory, workspaceGlobals, StarlarkSemantics.DEFAULT);

  // Determine the contents for native.
  ImmutableMap.Builder<String, Object> bindings = new ImmutableMap.Builder<>();
  Starlark.addMethods(bindings, new StarlarkNativeModule());
  for (Map.Entry<String, Object> entry : workspaceFunctions.entrySet()) {
    String name = entry.getKey();
    if (name.startsWith("$")) {
      // Skip "abstract" rules like "$go_rule".
      continue;
    }
    // "workspace" is explicitly omitted from the native module,
    // as it must only occur at the top of a WORKSPACE file.
    // TODO(cparsons): Clean up separation between environments.
    if (name.equals("workspace")) {
      continue;
    }
    bindings.put(entry);
  }
  bindings.put("bazel_version", version);

  return bindings.build();
}
 
Example #12
Source File: StarlarkRepositoryFunction.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean verifySemanticsMarkerData(Map<String, String> markerData, Environment env)
    throws InterruptedException {
  StarlarkSemantics starlarkSemantics = PrecomputedValue.STARLARK_SEMANTICS.get(env);
  if (starlarkSemantics == null) {
    // As it is a precomputed value, it should already be available. If not, returning
    // false is the safe thing to do.
    return false;
  }
  return describeSemantics(starlarkSemantics).equals(markerData.get(SEMANTICS));
}
 
Example #13
Source File: RuleFactoryTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testWorkspaceRuleFailsInBuildFile() throws Exception {
  Path myPkgPath = scratch.resolve("/workspace/mypkg/BUILD");
  Package.Builder pkgBuilder =
      packageFactory
          .newPackageBuilder(
              PackageIdentifier.createInMainRepo("mypkg"), "TESTING", StarlarkSemantics.DEFAULT)
          .setFilename(RootedPath.toRootedPath(root, myPkgPath));

  Map<String, Object> attributeValues = new HashMap<>();
  attributeValues.put("name", "foo");
  attributeValues.put("actual", "//bar:baz");

  RuleClass ruleClass = provider.getRuleClassMap().get("bind");
  RuleFactory.InvalidRuleException e =
      assertThrows(
          RuleFactory.InvalidRuleException.class,
          () ->
              RuleFactory.createAndAddRuleImpl(
                  pkgBuilder,
                  ruleClass,
                  new BuildLangTypedAttributeValuesMap(attributeValues),
                  new Reporter(new EventBus()),
                  StarlarkSemantics.DEFAULT,
                  DUMMY_STACK));
  assertThat(e).hasMessageThat().contains("must be in the WORKSPACE file");
}
 
Example #14
Source File: AbstractConfiguredTarget.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue(StarlarkSemantics semantics, String name) throws EvalException {
  if (semantics.incompatibleDisableTargetProviderFields()
      && !SPECIAL_FIELD_NAMES.contains(name)) {
    throw Starlark.errorf(
        "Accessing providers via the field syntax on structs is "
            + "deprecated and will be removed soon. It may be temporarily re-enabled by setting "
            + "--incompatible_disable_target_provider_fields=false. See "
            + "https://github.com/bazelbuild/bazel/issues/9014 for details.");
  }
  return getValue(name);
}
 
Example #15
Source File: SkydocTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testProviderInfo() throws Exception {
  scratch.file(
      "/test/test.bzl",
      "MyExampleInfo = provider(",
      "  doc = 'Stores information about example.',",
      "  fields = {",
      "    'name' : 'A string representing a random name.',",
      "    'city' : 'A string representing a city.',",
      "  },",
      ")",
      "pass");

  ImmutableMap.Builder<String, ProviderInfo> providerInfoMap = ImmutableMap.builder();

  skydocMain.eval(
      StarlarkSemantics.DEFAULT,
      Label.parseAbsoluteUnchecked("//test:test.bzl"),
      ImmutableMap.builder(),
      providerInfoMap,
      ImmutableMap.builder(),
      ImmutableMap.builder(),
      ImmutableMap.builder());

  Map<String, ProviderInfo> providers = providerInfoMap.build();
  assertThat(providers).hasSize(1);

  ModuleInfo moduleInfo =
      new ProtoRenderer().appendProviderInfos(providers.values()).getModuleInfo().build();
  ProviderInfo providerInfo = moduleInfo.getProviderInfo(0);
  assertThat(providerInfo.getProviderName()).isEqualTo("MyExampleInfo");
  assertThat(providerInfo.getDocString()).isEqualTo("Stores information about example.");
  assertThat(getFieldNames(providerInfo)).containsExactly("name", "city").inOrder();
  assertThat(getFieldDocString(providerInfo))
      .containsExactly("A string representing a random name.", "A string representing a city.")
      .inOrder();
}
 
Example #16
Source File: StarlarkDocumentationCollector.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Method getSelfCallConstructorMethod(Class<?> objectClass) {
  Method selfCallMethod = CallUtils.getSelfCallMethod(StarlarkSemantics.DEFAULT, objectClass);
  if (selfCallMethod != null && selfCallMethod.isAnnotationPresent(StarlarkConstructor.class)) {
    return selfCallMethod;
  }
  return null;
}
 
Example #17
Source File: AppleStarlarkCommon.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
// This method is registered statically for Starlark, and never called directly.
public ObjcProvider newObjcProvider(Boolean usesSwift, Dict<?, ?> kwargs, StarlarkThread thread)
    throws EvalException {
  StarlarkSemantics semantics = thread.getSemantics();
  ObjcProvider.StarlarkBuilder resultBuilder = new ObjcProvider.StarlarkBuilder(semantics);
  if (usesSwift) {
    resultBuilder.add(ObjcProvider.FLAG, ObjcProvider.Flag.USES_SWIFT);
  }
  for (Map.Entry<?, ?> entry : kwargs.entrySet()) {
    Key<?> key = ObjcProvider.getStarlarkKeyForString((String) entry.getKey());
    if (key != null) {
      resultBuilder.addElementsFromStarlark(key, entry.getValue());
    } else if (entry.getKey().equals("strict_include")) {
      resultBuilder.addStrictIncludeFromStarlark(entry.getValue());
    } else if (entry.getKey().equals("providers")) {
      resultBuilder.addProvidersFromStarlark(entry.getValue());
    } else if (entry.getKey().equals("direct_dep_providers")) {
      if (semantics.incompatibleObjcProviderRemoveCompileInfo()) {
        throw new EvalException(null, BAD_DIRECT_DEP_PROVIDERS_ERROR);
      }
      resultBuilder.addDirectDepProvidersFromStarlark(entry.getValue());
    } else {
      throw new EvalException(null, String.format(BAD_KEY_ERROR, entry.getKey()));
    }
  }
  return resultBuilder.build();
}
 
Example #18
Source File: ExecGroupCollection.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * This creates a new {@link ExecGroupContext} object every time this is called. This seems better
 * than pre-creating and storing all {@link ExecGroupContext}s since they're just thin wrappers
 * around {@link ResolvedToolchainContext} objects.
 */
@Override
public ExecGroupContext getIndex(StarlarkSemantics semantics, Object key) throws EvalException {
  String execGroup = castGroupName(key);
  if (!containsKey(semantics, key)) {
    throw Starlark.errorf(
        "In %s, unrecognized exec group '%s' requested. Available exec groups: [%s]",
        toolchainCollection().getDefaultToolchainContext().targetDescription(),
        execGroup,
        String.join(", ", getScrubbedExecGroups()));
  }
  return new ExecGroupContext(toolchainCollection().getToolchainContext(execGroup));
}
 
Example #19
Source File: RuleFactoryTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildRuleFailsInWorkspaceFile() throws Exception {
  Path myPkgPath = scratch.resolve("/workspace/WORKSPACE");
  Package.Builder pkgBuilder =
      packageFactory
          .newPackageBuilder(
              LabelConstants.EXTERNAL_PACKAGE_IDENTIFIER, "TESTING", StarlarkSemantics.DEFAULT)
          .setFilename(RootedPath.toRootedPath(root, myPkgPath));

  Map<String, Object> attributeValues = new HashMap<>();
  attributeValues.put("name", "foo");
  attributeValues.put("alwayslink", true);

  RuleClass ruleClass = provider.getRuleClassMap().get("cc_library");
  RuleFactory.InvalidRuleException e =
      assertThrows(
          RuleFactory.InvalidRuleException.class,
          () ->
              RuleFactory.createAndAddRuleImpl(
                  pkgBuilder,
                  ruleClass,
                  new BuildLangTypedAttributeValuesMap(attributeValues),
                  new Reporter(new EventBus()),
                  StarlarkSemantics.DEFAULT,
                  DUMMY_STACK));
  assertThat(e).hasMessageThat().contains("cannot be in the WORKSPACE file");
}
 
Example #20
Source File: ExtremaPackageLoadingListenerTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecordsTopLargestPackagesPerBuild() {
  underTest.setNumPackagesToTrack(2);

  underTest.onLoadingCompleteAndSuccessful(
      mockPackage(
          "my/pkg1",
          ImmutableMap.of("target1", mock(Target.class)),
          /*starlarkDependencies=*/ ImmutableList.of()),
      StarlarkSemantics.DEFAULT,
      /*loadTimeNanos=*/ 100);

  underTest.onLoadingCompleteAndSuccessful(
      mockPackage(
          "my/pkg2",
          ImmutableMap.of("target1", mock(Target.class), "target2", mock(Target.class)),
          /*starlarkDependencies=*/ ImmutableList.of()),
      StarlarkSemantics.DEFAULT,
      /*loadTimeNanos=*/ 100);

  underTest.onLoadingCompleteAndSuccessful(
      mockPackage(
          "my/pkg3",
          ImmutableMap.of(
              "target1",
              mock(Target.class),
              "target2",
              mock(Target.class),
              "target3",
              mock(Target.class)),
          /*starlarkDependencies=*/ ImmutableList.of()),
      StarlarkSemantics.DEFAULT,
      /*loadTimeNanos=*/ 100);

  assertThat(toStrings(underTest.getAndResetTopPackages().getLargestPackages()))
      .containsExactly("my/pkg3 (3)", "my/pkg2 (2)")
      .inOrder();

  assertAllTopPackagesEmpty(underTest.getAndResetTopPackages());
}
 
Example #21
Source File: SkydocTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testSkydocCrashesOnCycle() throws Exception {
  scratch.file(
      "/dep/dep.bzl",
      "load('//test:main.bzl', 'some_var')",
      "def rule_impl(ctx):",
      "  return []");

  scratch.file(
      "/test/main.bzl",
      "load('//dep:dep.bzl', 'rule_impl')",
      "",
      "some_var = 1",
      "",
      "main_rule = rule(",
      "    doc = 'Main rule',",
      "    implementation = rule_impl,",
      ")");

  StarlarkEvaluationException expected =
      assertThrows(
          StarlarkEvaluationException.class,
          () ->
              skydocMain.eval(
                  StarlarkSemantics.DEFAULT,
                  Label.parseAbsoluteUnchecked("//test:main.bzl"),
                  ImmutableMap.builder(),
                  ImmutableMap.builder(),
                  ImmutableMap.builder(),
                  ImmutableMap.builder(),
                  ImmutableMap.builder()));

  assertThat(expected).hasMessageThat().contains("cycle with test/main.bzl");
}
 
Example #22
Source File: OutputGroupInfo.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public Object getIndex(StarlarkSemantics semantics, Object key) throws EvalException {
  if (!(key instanceof String)) {
    throw Starlark.errorf(
        "Output group names must be strings, got %s instead", Starlark.type(key));
  }

  NestedSet<Artifact> result = outputGroups.get(key);
  if (result != null) {
    return Depset.of(Artifact.TYPE, result);
  } else {
    throw Starlark.errorf("Output group %s not present", key);
  }
}
 
Example #23
Source File: StarlarkSemanticsConsistencyTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that a randomly generated {@link StarlarkSemanticsOptions} object can be converted to a
 * {@link StarlarkSemantics} object with the same field values.
 */
@Test
public void optionsToSemantics() throws Exception {
  for (int i = 0; i < NUM_RANDOM_TRIALS; i++) {
    long seed = i;
    StarlarkSemanticsOptions options = buildRandomOptions(new Random(seed));
    StarlarkSemantics semantics = buildRandomSemantics(new Random(seed));
    StarlarkSemantics semanticsFromOptions = options.toStarlarkSemantics();
    assertThat(semanticsFromOptions).isEqualTo(semantics);
  }
}
 
Example #24
Source File: StarlarkSemanticsInfoItem.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] get(Supplier<BuildConfiguration> configurationSupplier, CommandEnvironment env) {
  StarlarkSemanticsOptions starlarkSemanticsOptions =
      commandOptions.getOptions(StarlarkSemanticsOptions.class);
  SkyframeExecutor skyframeExecutor = env.getBlazeWorkspace().getSkyframeExecutor();
  StarlarkSemantics effectiveStarlarkSemantics =
      skyframeExecutor.getEffectiveStarlarkSemantics(starlarkSemanticsOptions);
  return print(effectiveStarlarkSemantics.toDeterministicString());
}
 
Example #25
Source File: BzlLoadFunction.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Executes the .bzl file defining the module to be loaded. */
private void executeBzlFile(
    StarlarkFile file,
    Label label,
    Module module,
    Map<String, Module> loadedModules,
    StarlarkSemantics starlarkSemantics,
    ExtendedEventHandler skyframeEventHandler,
    ImmutableMap<RepositoryName, RepositoryName> repositoryMapping)
    throws BzlLoadFailedException, InterruptedException {
  try (Mutability mu = Mutability.create("loading", label)) {
    StarlarkThread thread = new StarlarkThread(mu, starlarkSemantics);
    thread.setLoader(loadedModules::get);
    StoredEventHandler starlarkEventHandler = new StoredEventHandler();
    thread.setPrintHandler(Event.makeDebugPrintHandler(starlarkEventHandler));
    ruleClassProvider.setStarlarkThreadContext(thread, label, repositoryMapping);
    execAndExport(file, label, starlarkEventHandler, module, thread);

    Event.replayEventsOn(skyframeEventHandler, starlarkEventHandler.getEvents());
    for (Postable post : starlarkEventHandler.getPosts()) {
      skyframeEventHandler.post(post);
    }
    if (starlarkEventHandler.hasErrors()) {
      throw BzlLoadFailedException.errors(label.toPathFragment());
    }
  }
}
 
Example #26
Source File: StarlarkProviderTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Instantiates a {@link StarlarkInfo} with fields a=1, b=2, c=3 (and nothing else). */
private static StarlarkInfo instantiateWithA1B2C3(StarlarkProvider provider) throws Exception {
  try (Mutability mu = Mutability.create()) {
    StarlarkThread thread = new StarlarkThread(mu, StarlarkSemantics.DEFAULT);
    Object result =
        Starlark.call(
            thread,
            provider,
            /*args=*/ ImmutableList.of(),
            /*kwargs=*/ ImmutableMap.of("a", 1, "b", 2, "c", 3));
    assertThat(result).isInstanceOf(StarlarkInfo.class);
    return (StarlarkInfo) result;
  }
}
 
Example #27
Source File: JavaHelper.java    From bazel with Apache License 2.0 5 votes vote down vote up
public static PathFragment getJavaResourcePath(
    JavaSemantics semantics, RuleContext ruleContext, Artifact resource)
    throws InterruptedException {
  PathFragment rootRelativePath = resource.getRootRelativePath();
  StarlarkSemantics starlarkSemantics =
      ruleContext.getAnalysisEnvironment().getStarlarkSemantics();

  if (!ruleContext.getLabel().getWorkspaceRoot(starlarkSemantics).isEmpty()) {
    PathFragment workspace =
        PathFragment.create(ruleContext.getLabel().getWorkspaceRoot(starlarkSemantics));
    rootRelativePath = rootRelativePath.relativeTo(workspace);
  }

  if (!ruleContext.attributes().has("resource_strip_prefix", Type.STRING)
      || !ruleContext.attributes().isAttributeValueExplicitlySpecified("resource_strip_prefix")) {
    return semantics.getDefaultJavaResourcePath(rootRelativePath);
  }

  PathFragment prefix =
      PathFragment.create(ruleContext.attributes().get("resource_strip_prefix", Type.STRING));

  if (!rootRelativePath.startsWith(prefix)) {
    ruleContext.attributeError(
        "resource_strip_prefix",
        String.format(
            "Resource file '%s' is not under the specified prefix to strip", rootRelativePath));
    return rootRelativePath;
  }

  return rootRelativePath.relativeTo(prefix);
}
 
Example #28
Source File: SelectTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static Object eval(String expr)
    throws SyntaxError.Exception, EvalException, InterruptedException {
  ParserInput input = ParserInput.fromLines(expr);
  Module module =
      Module.withPredeclared(StarlarkSemantics.DEFAULT, /*predeclared=*/ StarlarkLibrary.COMMON);
  try (Mutability mu = Mutability.create()) {
    StarlarkThread thread = new StarlarkThread(mu, StarlarkSemantics.DEFAULT);
    return EvalUtils.eval(input, FileOptions.DEFAULT, module, thread);
  }
}
 
Example #29
Source File: ObjcProvider.java    From bazel with Apache License 2.0 5 votes vote down vote up
private ObjcProvider(
    StarlarkSemantics semantics,
    ImmutableMap<Key<?>, NestedSet<?>> items,
    ImmutableList<PathFragment> strictDependencyIncludes,
    ImmutableListMultimap<Key<?>, ?> directItems,
    CcCompilationContext ccCompilationContext) {
  this.semantics = semantics;
  this.items = Preconditions.checkNotNull(items);
  this.strictDependencyIncludes = Preconditions.checkNotNull(strictDependencyIncludes);
  this.directItems = Preconditions.checkNotNull(directItems);
  this.ccCompilationContext = ccCompilationContext;
}
 
Example #30
Source File: StarlarkRepositoryContextTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testAttr() throws Exception {
  setUpContextForRule(
      ImmutableMap.of("name", "test", "foo", "bar"),
      ImmutableSet.of(),
      StarlarkSemantics.DEFAULT,
      /* repoRemoteExecutor= */ null,
      Attribute.attr("foo", Type.STRING).build());

  assertThat(context.getAttr().getFieldNames()).contains("foo");
  assertThat(context.getAttr().getValue("foo")).isEqualTo("bar");
}