buildtools icon indicating copy to clipboard operation
buildtools copied to clipboard

Warn for existing_rules

Open laurentlb opened this issue 5 years ago • 3 comments

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

laurentlb avatar Apr 04 '19 15:04 laurentlb

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.

alandonovan avatar Apr 04 '19 15:04 alandonovan

Also native.existing_rules()[x] can be simplified as native.existing_rule(x)

laurentlb avatar Apr 08 '20 18:04 laurentlb

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).

tetromino avatar Sep 07 '21 19:09 tetromino