Skip to content

Commit

Permalink
Use a dummy toolchain context for rules that don't have one.
Browse files Browse the repository at this point in the history
Fixes bazelbuild#12610.

Closes bazelbuild#13162.

PiperOrigin-RevId: 361545255
  • Loading branch information
katre authored and copybara-github committed Mar 8, 2021
1 parent 2dea9d1 commit 52b1b74
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
import com.google.devtools.build.lib.shell.ShellUtils;
import com.google.devtools.build.lib.shell.ShellUtils.TokenizationException;
import com.google.devtools.build.lib.starlarkbuildapi.StarlarkRuleContextApi;
import com.google.devtools.build.lib.starlarkbuildapi.platform.ToolchainContextApi;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.Collection;
Expand Down Expand Up @@ -701,9 +702,24 @@ public Dict<String, String> var() throws EvalException {
}

@Override
public ResolvedToolchainContext toolchains() throws EvalException {
public ToolchainContextApi toolchains() throws EvalException {
checkMutable("toolchains");
return ruleContext.getToolchainContext();
ResolvedToolchainContext toolchainContext = ruleContext.getToolchainContext();
if (toolchainContext == null) {
// Starlark rules are easier if this cannot be null, so return a no-op value instead.
return new ToolchainContextApi() {
@Override
public Object getIndex(StarlarkSemantics semantics, Object key) {
return Starlark.NONE;
}

@Override
public boolean containsKey(StarlarkSemantics semantics, Object key) {
return false;
}
};
}
return toolchainContext;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3123,4 +3123,29 @@ public void testBuildFilePath() throws Exception {
Object result = ev.eval("ruleContext.build_file_path");
assertThat(result).isEqualTo("bar/BUILD");
}

@Test
public void testNoToolchainContext() throws Exception {
// Build setting rules do not have a toolchain context, as they are part of the configuration.
scratch.file(
"test/BUILD",
"load(':rule.bzl', 'sample_setting')",
"toolchain_type(name = 'toolchain_type')",
"sample_setting(",
" name = 'test',",
" build_setting_default = True,",
")");
scratch.file(
"test/rule.bzl",
"def _sample_impl(ctx):",
" info = ctx.toolchains['//:toolchain_type']",
" if info != None:",
" fail('Toolchain should be empty')",
"sample_setting = rule(",
" implementation = _sample_impl,",
" build_setting = config.bool(flag = True),",
")");
getConfiguredTarget("//test:test");
assertNoEvents();
}
}

0 comments on commit 52b1b74

Please sign in to comment.