Skip to content

Commit 3c4b936

Browse files
authored
handle exception instead of crashing (#18895)
Fixes: #18641 PiperOrigin-RevId: 546092727 Change-Id: I66365813a40390ec61a1a0565b06655b3ca50fcd
1 parent ffcf0fd commit 3c4b936

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

src/main/java/com/google/devtools/build/lib/analysis/starlark/StarlarkRuleClassFunctions.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -771,9 +771,15 @@ public String getName() {
771771
public Object call(StarlarkThread thread, Tuple args, Dict<String, Object> kwargs)
772772
throws EvalException, InterruptedException {
773773
if (!args.isEmpty()) {
774-
throw new EvalException("unexpected positional arguments");
774+
throw new EvalException("Unexpected positional arguments");
775+
}
776+
try {
777+
BazelStarlarkContext.from(thread).checkLoadingPhase(getName());
778+
} catch (IllegalStateException e) {
779+
throw new EvalException(
780+
"A rule can only be instantiated in a BUILD file, or a macro "
781+
+ "invoked from a BUILD file");
775782
}
776-
BazelStarlarkContext.from(thread).checkLoadingPhase(getName());
777783
if (ruleClass == null) {
778784
throw new EvalException("Invalid rule class hasn't been exported by a bzl file");
779785
}

src/test/py/bazel/bzlmod/bazel_module_test.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,37 @@ def testWorkspaceToolchainRegistrationWithPlatformsConstraint(self):
635635
with open(self.Path('bazel-bin/my_consumer'), 'r') as f:
636636
self.assertEqual(f.read().strip(), 'my_value = Hello, Bzlmod!')
637637

638+
def testModuleExtensionWithRuleError(self):
639+
self.ScratchFile(
640+
'MODULE.bazel',
641+
[
642+
'ext = use_extension("extensions.bzl", "ext")',
643+
'use_repo(ext, "ext")',
644+
],
645+
)
646+
self.ScratchFile('BUILD')
647+
self.ScratchFile(
648+
'extensions.bzl',
649+
[
650+
'def _rule_impl(ctx):',
651+
' print("RULE CALLED")',
652+
'init_rule = rule(_rule_impl)',
653+
'def ext_impl(module_ctx):',
654+
' init_rule()',
655+
'ext = module_extension(implementation = ext_impl,)',
656+
],
657+
)
658+
exit_code, _, stderr = self.RunBazel(
659+
['build', '--nobuild', '@ext//:all'],
660+
allow_failure=True,
661+
)
662+
self.AssertExitCode(exit_code, 48, stderr)
663+
self.assertIn(
664+
'Error in init_rule: A rule can only be instantiated in a BUILD file, '
665+
'or a macro invoked from a BUILD file',
666+
stderr,
667+
)
668+
638669

639670
if __name__ == '__main__':
640671
unittest.main()

0 commit comments

Comments
 (0)