Laszlo Csomor | 39fc88c | 2015-03-02 16:22:29 +0000 | [diff] [blame] | 1 | Macros |
| 2 | ====== |
| 3 | |
| 4 | **Status: Stable** |
| 5 | |
| 6 | Macro creation |
| 7 | -------------- |
| 8 | |
| 9 | A macro is a function called from the BUILD file. It can instantiate native |
| 10 | or Skylark rules. By the end of the loading phase, macros don't exist |
| 11 | anymore: Bazel sees only the set of rules they created. |
| 12 | |
| 13 | Native rules can be instantiated from the `native` module, e.g. |
| 14 | |
| 15 | ```python |
| 16 | native.cc_library(name = x) |
| 17 | ``` |
| 18 | |
| 19 | If you need to know the package name (i.e. which BUILD file is calling the |
| 20 | macro), use the constant `PACKAGE_NAME`. |
| 21 | |
| 22 | Examples |
| 23 | -------- |
| 24 | |
| 25 | * [Macro creating native rules](cookbook.md#macro_native). |
| 26 | |
| 27 | * [Macro creating Skylark rules](cookbook.md#macro_skylark). |
| 28 | |
| 29 | Debugging |
| 30 | --------- |
| 31 | |
| 32 | * `bazel query --output=build ///my/path:all` will show you how the BUILD |
| 33 | file looks like after evaluation. All macros, globs, loops are expanded. |
| 34 | |
| 35 | * You can also use `print` for debugging. It displays the message as a |
| 36 | warning during the loading phase. Except in rare cases, remove your `print` |
| 37 | calls before submitting the code to the depot. |
| 38 | |
| 39 | Errors |
| 40 | ------ |
| 41 | |
| 42 | If you want to throw an error, use the `fail` function. Explain clearly to |
| 43 | the user what went wrong and how to fix their BUILD file. It is not possible |
| 44 | to catch an error. |
| 45 | |
| 46 | Conventions |
| 47 | ----------- |
| 48 | |
| 49 | * All public functions (functions that don't start with underscore) that |
| 50 | instantiate rules must have a `name` argument. This argument should not be |
| 51 | optional (don't give a default value). |
| 52 | |
| 53 | * Public functions should use a docstring following [Python |
| 54 | conventions](https://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Comments#Comments). |
| 55 | |
| 56 | * In BUILD files, the `name` argument of the macros must a be a keyword |
| 57 | argument (not a positional argument). |
| 58 | |
| 59 | * The `name` attribute of rules generated by a macro should include the name |
| 60 | argument as a prefix. For example, `macro(name = "foo")` can generate a |
| 61 | cc_library `foo` and a genrule `foo_gen`. |
| 62 | |
| 63 | * Macros should have an optional `visibility` argument. |