buildtools
buildtools copied to clipboard
Warn for existing_rules
We've found this pattern in user code in Bazel:
if foo in native.existing_rules():
It should be replaced with the much more efficient:
if native.existing_rule(foo):
(also with not in
instead of in
)
cc @alandonovan
existing_rule is much more efficient than existing_rules, but still much less efficient than necessary: most users compute 'x in existing_rules()', which can be simplified to bool(existing_rule(x)), but this could be further simplified to 'rule_exists(x)', or alternatively a variant of existing_rule that doesn't materialize the fields until you ask for them. (For example, it could return a struct whose field names are attributes, analogous to ctx.attrs.)
It would be nice to introduce that feature before advising everyone change their code, only to change it again.
Also native.existing_rules()[x]
can be simplified as native.existing_rule(x)
Note that once https://github.com/bazelbuild/proposals/blob/main/designs/2021-06-15-improving-native.existing_rules.md is implemented, if foo in native.existing_rules()
would be nearly as efficient as if native.existing_rule(foo)
.