created | last updated | status | reviewers | title | authors | discussion thread | |||
---|---|---|---|---|---|---|---|---|---|
2019-11-11 |
2019-12-17 |
Implemented |
|
Exposing Target Platform Constraints |
|
Rule authors occasionally need information about the target platform in a rule
implementation. This can be achieved currently using either custom toolchains or
by using implicit attributes with a select()
call. This proposal aims to allow
rule authors the information they need in a simpler manner.
Every configured target has a target platform that the outputs are compatible with. This target platform may be set (either by default or by a command-line flag) when the build begins, or may be changed as a result of a configuration transition.
A current workaround to determine the target platform is to check
ctx.configuration.host_path_separator
,
or to add an implicit attribute that selects on a relevant platform
constraint.
However, both of these are inexact and add additional overhead for rule authors.
The target platform information, as a PlatformInfo
provider,
is currently available during rule implementation (and can be accessed by native
rules), via the
ToolchainContext
.
However, the
ToolchainContextApi
itself only exposes toolchain info providers via a map-like API, which allows
code such as:
toolchain = ctx.toolchains['//tools/cpp:toolchain_type']
We can add a method (on SkylarkRuleContextApi
) to check whether a
given constraint value is present. The value passed would need to be a valid
ConstraintValueInfo
provider, obtained by an implicit depdency on the
constraint value definition that is to be checked. This ensures both that the
constraint value is valid, and that the rule author has the correct visibility
available to use the constraint value.
def _impl(ctx):
windows_constraint = ctx.attr._windows_constraint[platform_common.ConstraintValueInfo]
if ctx.target_platform_has_constraint(windows_constraint):
platform_separator = '\\'
my_rule = rule(
implementation = _impl,
attrs = {
...
'_windows_constraint': attr.label(default = '@bazel_platforms//os:windows'),
},
)
This version requires an additional implicit attribute from rule authors to use, but the overhead is low and the correctness guarantees are worthwhile.
The implementation can check the type and then call a similar method in
ConstraintCollection
to perform the actual check.
This is a new feature being added to SkylarkRuleContextApi
, so there are no
backwards compatibility concerns.