blob: c53f4590c1e62cc9350bea3008177fca24e3b8f4 [file] [log] [blame]
David Chen8fe82a32016-08-24 10:55:41 +00001---
2layout: documentation
Googler456b6ab2017-06-07 12:29:51 -04003title: Concepts and Terminology
David Chen8fe82a32016-08-24 10:55:41 +00004---
Googler55f40c82017-06-06 12:24:15 -04005<h1>Concepts and Terminology</h1>
David Chen8fe82a32016-08-24 10:55:41 +00006<p>
7 This document provides an overview of the source tree layout and the
8 terminology used in Bazel.
9</p>
10<h2>Table of Contents</h2>
11
12<ul>
13 <li><a href="#intro">Introduction</a></li>
14
15 <li><a href="#packages_targets">Workspace, Packages and Targets</a>
16 <ul>
17 <li><a href="#workspace">Workspace</a></li>
18 <li><a href="#packages">Packages</a></li>
19 <li><a href="#targets">Targets</a></li>
20 <li><a href="#labels">Labels</a></li>
21 <li><a href="#lexi">Lexical Specifications of a Label</a></li>
22 <li><a href="#rules">Rules</a></li>
23 </ul>
24 </li>
25 <li><a href="#BUILD_files">BUILD Files</a>
26 <ul>
27 <li><a href="#core_build_language">The Core Build Language</a></li>
28
29 <li><a href="#declaring_build_rules">Declaring Build Rules</a></li>
30 </ul>
31 </li>
32 <li><a href="#funcs">Types of Build Rules</a></li>
33
34 <li><a href="#dependencies">Dependencies</a>
35 <ul>
36 <li><a href="#actual_and_declared_dependencies">Actual and Declared Dependencies</a></li>
37 <li><a href="#types_of_dependencies">Types of Dependencies</a></li>
38 <li><a href="#label_directory">Using Labels to Reference Directories</a></li>
39 </ul>
40 </li>
41</ul>
42
43<h2 id="intro">Introduction</h2>
44
45<p>Bazel builds software from source code organized in a directory called
46 a workspace. Source files in the workspace are organized in a nested
47 hierarchy of packages, where each package is a directory that contains a set
48 of related source files and one BUILD file. The BUILD file specifies what
49 software outputs can be built from the source.
50</p>
51<h2 id="packages_targets">Workspace, Packages and Targets</h2>
52<h3 id="workspace">Workspace</h3>
53
54<p>A <em>workspace</em> is a directory on your filesystem that contains the
55 source files for the software you want to build, as well as symbolic links
56 to directories that contain the build outputs. Each workspace directory has
57 a text file named <code>WORKSPACE</code> which may be empty, or may contain
dzc205125b2017-06-26 11:01:47 +020058 references to <a href="external.html">external dependencies</a>
David Chen8fe82a32016-08-24 10:55:41 +000059 required to build the outputs. See also the <a
dzc205125b2017-06-26 11:01:47 +020060 href="be/workspace.html">Workspace Rules</a> section in the Build
David Chen8fe82a32016-08-24 10:55:41 +000061 Encyclopedia.
62</p>
63<h3 id="packages">Packages</h3>
64<p>
65 The primary unit of code organization in a workspace is
66 the <i>package</i>. A package is collection of related files and a
67 specification of the dependencies among them.
68</p>
69<p>
70 A package is defined as a directory containing a file
71 named <code>BUILD</code>, residing beneath the top-level directory in the
72 workspace. A package includes all files in its directory, plus all
73 subdirectories beneath it, except those which themselves contain a BUILD
74 file.
75</p>
76<p>
77 For example, in the following directory tree
78 there are two packages, <code>my/app</code>,
79 and the subpackage <code>my/app/tests</code>.
80 Note that <code>my/app/data</code> is not a package, but a directory
81 belonging to package <code>my/app</code>.
82</p>
83
84<pre>
85src/my/app/BUILD
86src/my/app/app.cc
87src/my/app/data/input.txt
88src/my/app/tests/BUILD
89src/my/app/tests/test.cc
90</pre>
91<h3 id="targets">Targets</h3>
92
93<p>
94 A package is a container. The elements of a package are called
95 <i>targets</i>. Most targets are one of two principal kinds, <i>files</i>
96 and <i>rules</i>. Additionally, there is another kind of target,
97 <a href="be/functions.html#package_group">package groups</a>,
98 but they are far less numerous.
99</p>
100
David Chen8fe82a32016-08-24 10:55:41 +0000101<p>
102 Files are further divided into two kinds.
103 <i>Source files</i> are usually written by the efforts of people,
104 and checked in to the repository.
105 <i>Generated files</i>, sometimes called derived files,
106 are not checked in, but are generated by the build tool from source
107 files according to specific rules.
108</p>
109
110<p>
111 The second kind of target is the <i>rule</i>. A rule specifies the
112 relationship between a set of input and a set of output files,
113 including the necessary steps to derive the outputs from the inputs.
114 The outputs of a rule are always generated files. The inputs to a
115 rule may be source files, but they may be generated files also;
116 consequently, outputs of one rule may be the inputs to another,
117 allowing long chains of rules to be constructed.
118</p>
119
120<p>
121 Whether the input to a rule is a source file or a generated file is
122 in most cases immaterial; what matters is only the contents of that
123 file. This fact makes it easy to replace a complex source file with
124 a generated file produced by a rule, such as happens when the burden
125 of manually maintaining a highly structured file becomes too
126 tiresome, and someone writes a program to derive it. No change is
127 required to the consumers of that file. Conversely, a generated
128 file may easily be replaced by a source file with only local
129 changes.
130</p>
131
132<p>
133 The inputs to a rule may also include <i>other rules</i>. The
134 precise meaning of such relationships is often quite complex and
135 language- or rule-dependent, but intuitively it is simple: a C++
136 library rule A might have another C++ library rule B for an input.
137 The effect of this dependency is that the B's header files are
138 available to A during compilation, B's symbols are available to A
139 during linking, and B's runtime data is available to A during
140 execution.
141</p>
142
143<p>
144 An invariant of all rules is that the files generated by a rule
145 always belong to the same package as the rule itself; it is not
146 possible to generate files into another package. It is not uncommon
147 for a rule's inputs to come from another package, though.
148</p>
149
150<p>
151 Package groups are sets of packages whose purpose is to limit accessibility
152 of certain rules. Package groups are defined by the
153 <code>package_group</code> function. They have two properties: the list of
154 packages they contain and their name. The only allowed ways to refer to them
155 are from the <code>visibility</code> attribute of rules or from the
156 <code>default_visibility</code> attribute of the <code>package</code>
157 function; they do not generate or consume files. For more information, refer
158 to the appropriate section of the <a
159 href='be/functions.html#package_group'>Build Encyclopedia</a>.
160</p>
161
162
163<h3 id="labels">Labels</h3>
164
165<p>
166 All targets belong to exactly one package. The name of a target is
167 called its <em>label</em>, and a typical label in canonical form
168 looks like this:
169</p>
170
171<pre>
172//my/app/main:app_binary
173</pre>
174
175<p>
176
177 Each label has two parts, a package name (<code>my/app/main</code>)
178 and a target name (<code>app_binary</code>). Every label uniquely
179 identifies a target. Labels sometimes appear in other forms; when
180 the colon is omitted, the target name is assumed to be the same as
181 the last component of the package name, so these two labels are
182 equivalent:
183</p>
184
185<pre>
186//my/app
187//my/app:app
188</pre>
189
190<p>
191 Short-form labels such as <code>//my/app</code> are not to
192 be confused with package names. Labels start with <code>//</code>,
193 but package names never do, thus <code>my/app</code> is the
194 package containing <code>//my/app</code>.
195
196 (A common misconception is that <code>//my/app</code> refers
197 to a package, or to <em>all</em> the targets in a package; neither
198 is true.)
199</p>
200
201<p>
202 Within a BUILD file, the package-name part of label may be omitted,
203 and optionally the colon too. So within the BUILD file for package
204 <code>my/app</code> (i.e. <code>//my/app:BUILD</code>),
205 the following "relative" labels are all equivalent:
206</p>
207
208<pre>
209//my/app:app
210//my/app
211:app
212app
213</pre>
214
215<p>
216 (It is a matter of convention that the colon is omitted for files,
217 but retained for rules, but it is not otherwise significant.)
218</p>
219
220<p>
221 Similarly, within a BUILD file, files belonging to the package may
222 be referenced by their unadorned name relative to the package
223 directory:
224</p>
225
226
227<pre>
228generate.cc
229testdata/input.txt
230</pre>
231
232<p>
233 But from other packages, or from the command-line, these file
234 targets must always be referred to by their complete label, e.g.
235 <code>//my/app:generate.cc</code>.
236</p>
237
238<p>
239 Relative labels cannot be used to refer to targets in other
240 packages; the complete package name must always be specified in this
241 case. For example, if the source tree contains both the package
242 <code>my/app</code> and the package
243 <code>my/app/testdata</code> (i.e., each of these two
244 packages has its own BUILD file). The latter package contains a
245 file named <code>testdepot.zip</code>. Here are two ways (one
246 wrong, one correct) to refer to this file within
247 <code>//my/app:BUILD</code>:
248</p>
249
250<pre>
251<span class="discouraged">testdata/testdepot.zip</span> # Wrong: testdata is a different package.
252//my/app/testdata:testdepot.zip # Right.
253</pre>
254
255<p>
256 If, by mistake, you refer to <code>testdepot.zip</code> by the wrong
257 label, such as <code>//my/app:testdata/testdepot.zip</code>
258 or <code>//my:app/testdata/testdepot.zip</code>, you will get an
259 error from the build tool saying that the label "crosses a package
260 boundary". You should correct the label by putting the colon after
261 the directory containing the innermost enclosing BUILD file, i.e.,
262 <code>//my/app/testdata:testdepot.zip</code>.
263</p>
264
265<h3 id="lexi">Lexical specification of a label</h3>
266
267<p>
268 The syntax of labels is intentionally strict, so as to
269 forbid metacharacters that have special meaning to the shell. This
270 helps to avoid inadvertent quoting problems, and makes it easier to
271 construct tools and scripts that manipulate labels, such as the
272
273 <a href="query.html">Bazel Query Language</a>.
274 All of the following are forbidden in labels: any sort of white
275 space, braces, brackets, or parentheses; wildcards such
276 as <code>*</code>; shell metacharacters such
277 as <code>&gt;</code>, <code>&amp;</code> and <code>|</code>; etc.
278 This list is not comprehensive; the precise details are below.
279</p>
280
281<h4 id="name">Target names, <code>//...:<b>target-name</b></code></h4>
282
283<p><code>target-name</code> is the name of the target within the package.
284 The name of a rule is the value of the <code>name</code>
285 parameter in the rule's declaration in a BUILD file; the name
286 of a file is its pathname relative to the directory containing
287 the BUILD file.
288 Target names must be composed entirely of
289 characters drawn from the set <code>a</code>–<code>z</code>,
290 <code>A</code>–<code>Z</code>, <code>0</code>–<code>9</code>,
291 and the punctuation symbols <code>_/.+-=,@~</code>.
292 Do not use <code>..</code> to refer to files in other packages; use
293 <code>//<var>packagename</var>:<var>filename</var></code> instead.
294 Filenames must be relative pathnames in normal form, which means
295 they must neither start nor end with a slash
296 (e.g. <code>/foo</code> and <code>foo/</code> are forbidden) nor
297 contain multiple consecutive slashes as path separators
298 (e.g. <code>foo//bar</code>). Similarly, up-level references
299 (<code>..</code>) and current-directory references
300 (<code>./</code>) are forbidden. The sole exception to this
301 rule is that a target name may consist of exactly
302 '<code>.</code>'.
303</p>
304
305<p>While it is common to use <code>/</code> in the name of a file
306 target, we recommend that you avoid the use of <code>/</code> in the
307 names of rules. Especially when the shorthand form of a label is
308 used, it may confuse the reader. The
309 label <code>//foo/bar/wiz</code> is always a shorthand
310 for <code>//foo/bar/wiz:wiz</code>, even if there is no such package
311 <code>foo/bar/wiz</code>; it never refers to <code>//foo:bar/wiz</code>,
312 even if that target exists.</p>
313
314<p>However, there are some situations where use of a slash is
315 convenient, or sometimes even necessary. For example, the name of
316 certain rules must match their principal source file, which may
317 reside in a subdirectory of the package.</p>
318
319<h4>Package names, <code>//<b>package-name</b>:...</code></h4>
320<p>
321 The name of a package is the name of the directory containing its
322
323 BUILD file, relative to the top-level directory of the source tree.
324 For example: <code>my/app</code>.
David Chen8fe82a32016-08-24 10:55:41 +0000325
Googler0bcc9842016-09-15 14:06:13 +0000326 Package names must be composed entirely of characters drawn from
327 the set <code>A</code>-<code>Z</code>, <code>a</code>–<code>z</code>,
328 <code>0</code>–<code>9</code>, '<code>/</code>', '<code>-</code>',
329 '<code>.</code>', and '<code>_</code>', and cannot start with
330 a slash.
David Chen8fe82a32016-08-24 10:55:41 +0000331<p>
332 For a language with a directory structure that is significant
333 to its module system (e.g. Java), it is important to choose directory names
334 that are valid identifiers in the language.
335</p>
336
337<p>
338 Although Bazel allows a package at the build root (e.g. <code>//:foo</code>), this
339 is not advised and projects should attempt to use more descriptively named
340 packages.
341</p>
342<p>
343 Package names may not contain the substring <code>//</code>, nor
344 end with a slash.
345</p>
346
347<h3 id="rules">Rules</h3>
348
349<p>
350 A rule specifies the relationship between inputs and outputs, and the
351 steps to build the outputs. Rules can be of one of many different
352 kinds or <i>classes</i>, which produce compiled
353 executables and libraries, test executables and other supported
354 outputs as described in the
355 <a href="be/overview.html">Build Encyclopedia</a>.
356</p>
357
358<p>
359 Every rule has a name, specified by the <code>name</code> attribute,
360 of type string. The name must be a syntactically valid target name,
361 as specified <a href='#name'>above</a>. In some cases, the name is
362 somewhat arbitrary, and more interesting are the names of the files
363 generated by the rule; this is true of genrules. In other
364 cases, the name is significant: for <code>*_binary</code>
365 and <code>*_test</code> rules, for example, the rule name determines
366 the name of the executable produced by the build.
367</p>
368
369<p>
370 Every rule has a set of <i>attributes</i>; the applicable attributes
371 for a given rule, and the significance and semantics of each
372 attribute are a function of the rule's class; see
373 the <a href='be/overview.html'>Build
374 Encyclopedia</a> for the full list of supported rules and their
375 corresponding attributes. Each attribute has a name and a
376 type. The full set of types that an attribute can have is: integer,
377 label, list of labels, string, list of strings, output label,
378 list of output labels. Not all attributes need to be specified in
379 every rule. Attributes thus form a dictionary from keys (names) to
380 optional, typed values.
381</p>
382
383<p>
384 The <code>srcs</code> attribute present in many rules has type "list
385 of label"; its value, if present, is a list of labels, each being
386 the name of a target that is an input to this rule.
387</p>
388
389<p>
390 The <code>outs</code> attribute present in many rules has type "list
391 of output labels"; this is similar to the type of
392 the <code>srcs</code> attribute, but differs in two significant
393 ways. Firstly, due to the invariant that the outputs of a rule
394 belong to the same package as the rule itself, output labels cannot
395 include a package component; they must be in one of the "relative"
396 forms shown above. Secondly, the relationship implied by an
397 (ordinary) label attribute is inverse to that implied by an output
398 label: a rule <i>depends on</i> its <code>srcs</code>, whereas a rule <i>is
399 depended on by</i> its <code>outs</code>. The two types of label attributes
400 thus assign direction to the edges between targets, giving rise to a
401 dependency graph.
402</p>
403
404<p>
David Chen8fe82a32016-08-24 10:55:41 +0000405 This directed acyclic graph over targets is called the
406 "target graph" or "build dependency graph", and is the domain over
407 which the
408
409 <a href="query.html">Bazel Query tool</a></li>
410 operates.
411</p>
412
413
414<h2 id="BUILD_files">BUILD Files</h2>
415
416<p>
417 The previous section described packages, targets and labels, and the
418 build dependency graph abstractly. In this section, we'll look at
419 the concrete syntax used to define a package.
420</p>
421
422<p>
423 By definition, every package contains a BUILD file, which is a short
424 program written in the Build Language. Most BUILD files
425 appear to be little more than a series of declarations of build
426 rules; indeed, the declarative style is strongly encouraged when
427 writing BUILD files.
428</p>
429
430<p>
431 However, the build language is in fact an imperative language, and
432 BUILD files are interpreted as a sequential list of statements.
433 Build rule functions, such as <code>cc_library</code>, are procedures whose
434 side-effect is to create an abstract build rule inside the build tool.
435</p>
436
437<p>
438 The concrete syntax of BUILD files is a subset of Python.
439 Originally, the syntax <i>was</i> that of Python, but experience
440 showed that users rarely used more than a tiny subset of Python's
441 features, and when they did, it often resulted in complex and
442 fragile BUILD files. In many cases, the use of such features was
443 unnecessary, and the same result could be achieved by using an
444 external program, e.g. via a <code>genrule</code> build rule.
445</p>
446
447<p>
448 Crucially, programs in the build language are unable to perform
449 arbitrary I/O (though many users try!). This invariant makes the
450 interpretation of BUILD files hermetic, i.e. dependent only on a
451 known set of inputs, which is essential for ensuring that builds are
452 reproducible.
453</p>
454
455<h3 id="core_build_language">The Core Build Language</h3>
456
457<p>
458 <b>Lexemes</b>: the lexical syntax of the core language is a strict
459 subset of Python 2.6, and we refer the reader to the <a
460 href='http://docs.python.org/reference/lexical_analysis.html'>Python
461 specification</a> for details.
462 Lexical features of Python that are not
463 supported include: floating-point literals, hexadecimal and Unicode
464 escapes within string literals.
465</p>
466
467<p>
468 BUILD files should be written using only ASCII characters,
469 although technically they are interpreted using the Latin-1
470 character set. The use
471 of <a href='http://www.python.org/dev/peps/pep-0263/'><code>coding:</code></a>
472 declarations is forbidden.
473</p>
474
475<p>
476 <b>Grammar</b>: the grammar of the core language is shown below,
477 using EBNF notation. Ambiguity is resolved using precedence, which
478 is defined as for Python.
479</p>
480
481<pre>
482file_input ::= (simple_stmt? '\n')*
483
484simple_stmt ::= small_stmt (';' small_stmt)* ';'?
485
486small_stmt ::= expr
487 | assign_stmt
488
fzaiser26c69e92017-08-14 19:15:46 +0200489assign_stmt ::= IDENTIFIER assign_op expr
490
491assign_op ::= '=' | '+=' | '-=' | '*=' | '/=' | '%='
David Chen8fe82a32016-08-24 10:55:41 +0000492
493expr ::= INTEGER
494 | STRING+
495 | IDENTIFIER
fzaiser26c69e92017-08-14 19:15:46 +0200496 | expr '(' arg_list? ')'
David Chen8fe82a32016-08-24 10:55:41 +0000497 | expr '.' IDENTIFIER
David Chen8fe82a32016-08-24 10:55:41 +0000498 | '[' expr_list? ']'
fzaiser26c69e92017-08-14 19:15:46 +0200499 | '[' expr ('for' IDENTIFIER 'in' expr | 'if' expr)+ ']'
David Chen8fe82a32016-08-24 10:55:41 +0000500 | '(' expr_list? ')'
501 | '{' dict_entry_list? '}'
fzaiser26c69e92017-08-14 19:15:46 +0200502 | '{' dict_entry ('for' IDENTIFIER 'in' expr | 'if' expr)+ '}'
503 | expr bin_op expr
David Chen8fe82a32016-08-24 10:55:41 +0000504 | '-' expr
fzaiser26c69e92017-08-14 19:15:46 +0200505 | 'not' expr
506 | expr '[' expr? ':' expr? ':' expr? ']'
David Chen8fe82a32016-08-24 10:55:41 +0000507 | expr '[' expr? ':' expr? ']'
508 | expr '[' expr ']'
509
fzaiser26c69e92017-08-14 19:15:46 +0200510bin_op ::= '+' | '-' | '*' | '/' | '//' | '%' | '|'
511 | 'and' | 'or' | '==' | '!=' | '&lt;' | '&lt;=' | '&gt;' | '&gt;=' | 'in' | 'not' 'in'
512
David Chen8fe82a32016-08-24 10:55:41 +0000513expr_list ::= (expr ',')* expr ','?
514
515dict_entry_list ::= (dict_entry ',')* dict_entry ','?
516
517dict_entry ::= expr ':' expr
518
519arg_list ::= (arg ',')* arg ','?
520
521arg ::= IDENTIFIER '=' expr
522 | expr
523</pre>
524
525<p>
526 For each expression of the core language, the semantics are
527 identical to the corresponding Python semantics, except in the
528 following cases:
529</p>
530<ul>
531 <li>certain overloads of the binary <code>%</code> operator are not
532 supported. Only the <code>int % int</code> and <code>str %
533 tuple</code> forms are supported. Only the <code>%s</code>
534 and <code>%d</code> format specifiers may be
535 used; <code>%(var)s</code> is illegal.</li>
536
537</ul>
538
539<p>
540 Many Python features are missing: control-flow constructs (loops,
541 conditionals, exceptions), basic datatypes (floating-point numbers, big
542 integers), <code>import</code> and the module system, support for
543 definition of classes, some Python's built-in functions. Function
544 definitions and <code>for</code> statements are allowed only in
545 extension files (<code>.bzl</code>).
546
547 Available functions are documented in
548
549 the <a href="skylark/lib/globals.html">library section</a>.
550<h3 id="declaring_build_rules">Declaring build rules</h3>
551
552<p>
553 The build language is an imperative language, so in general, order
554 does matter: variables must be defined before they are used, for
555 example. However, most BUILD files consist only of declarations of
556 build rules, and the relative order of these statements is
557 immaterial; all that matters is <em>which</em> rules were declared,
558 and with what values, by the time package evaluation completes.
559
560 So, in simple BUILD files, rule declarations can be re-ordered
561 freely without changing the behavior.
562</p>
563
564<p>
565 BUILD file authors are encouraged to use comments liberally to
566 document the role of each build target, whether it is intended for
567 public use, and anything else that would help users and future
568 maintainers, including a <code># Description:</code> comment at the
569 top, explaining the role of the package.
570</p>
571
572<p>
573 The Python comment syntax of <code>#...</code> is supported.
574 Triple-quoted string literals may span multiple lines, and can be used
575 for multi-line comments.
576</p>
577
578<h2 id="funcs">Types of build rule</h2>
579
580<p>
581 The majority of build rules come in families, grouped together by
582 language. For
583 example, <code>cc_binary</code>, <code>cc_library</code>
584 and <code>cc_test</code> are the build rules for C++ binaries,
585 libraries, and tests, respectively. Other languages use the same
586 naming scheme, with a different prefix, e.g. <code>java_*</code> for
587 Java. These functions are all documented in the
588 <a href="be/overview.html">Build Encyclopedia</a>.
589</p>
590
591<ul>
592 <li><p><code>*_binary</code>
593 rules build executable programs in a given language. After a
594 build, the executable will reside in the build tool's binary
595 output tree at the corresponding name for the rule's label,
596 so <code>//my:program</code> would appear at
597 (e.g.) <code>$(BINDIR)/my/program</code>. </p>
598
599 <p>Such rules also create a runfiles directory
600
601 containing all the files mentioned in a <code>data</code>
602 attribute belonging to the rule, or any rule in its transitive
603 closure of dependencies; this set of files is gathered together in
604 one place for ease of deployment to production.</p>
605 </li>
606
607 <li><p><code>*_test</code>
608 rules are a specialization of a <code>*_binary</code> rule, used for automated
609 testing. Tests are simply programs that return zero on success.
610
611 </p>
612
613 <p>
614 Like binaries, tests also have runfiles trees, and the files
615 beneath it are the only files that a test may legitimately open
616 at runtime. For example, a program <code>cc_test(name='x',
617 data=['//foo:bar'])</code> may open and
618
619 read <code>$TEST_SRCDIR/workspace/foo/bar</code> during execution.
620 (Each programming language has its own utility function for
621 accessing the value of <code>$TEST_SRCDIR</code>, but they are all
622 equivalent to using the environment variable directly.)
623 Failure to observe the rule will cause the test to fail when it is
624 executed on a remote testing host.
625
626 </p>
627 </li>
628
629 <li><code>*_library</code>
630 rules specify separately-compiled modules in the given
631 programming language. Libraries can depend on other libraries,
632 and binaries and tests can depend on libraries, with the expected
633 separate-compilation behavior.
634 </li>
635</ul>
636
637<h2 id="dependencies">Dependencies</h2>
638
639<p>
640 A target <code>A</code> <i>depends upon</i> a target
641 <code>B</code> if <code>B</code> is needed by <code>A</code> at
642 build or execution time. The <i>depends upon</i> relation induces a
643 directed acyclic graph (DAG) over targets, and we call this a
644 <em>dependency graph</em>.
645
646 A target's <em>direct</em> dependencies are those other targets
647 reachable by a path of length 1 in the dependency graph. A target's
648 <em>transitive</em> dependencies are those targets upon which it
649 depends via a path of any length through the graph.
650</p>
651
652<p>
653 In fact, in the context of builds, there are two dependency graphs,
654 the graph of <em>actual dependencies</em> and the graph of
655 <em>declared dependencies</em>. Most of the time, the two graphs
656 are so similar that this distinction need not be made, but it is
657 useful for the discussion below.
658</p>
659
660<h3 id="actual_and_declared_dependencies">Actual and declared dependencies</h3>
661
662<p>
663 A target <code>X</code> is <i>actually dependent</i> on target
664 <code>Y</code> iff <code>Y</code> must be present, built and
665 up-to-date in order for <code>X</code> to be built correctly.
666 "Built" could mean generated, processed, compiled, linked,
667 archived, compressed, executed, or any of the other kinds of tasks
668 that routinely occur during a build.
669</p>
670
671<p>
672 A target <code>X</code> has a <i>declared dependency</i> on target
673 <code>Y</code> iff there is a dependency edge from <code>X</code> to
674 <code>Y</code> in the package of <code>X</code>.
675</p>
676
677<p>
678 For correct builds, the graph of actual dependencies <i>A</i> must
679 be a subgraph of the graph of declared dependencies <i>D</i>. That
680 is, every pair of directly-connected nodes <code>x --&gt; y</code>
681 in <i>A</i> must also be directly connected in <i>D</i>. We say
682 <i>D</i> is an <em>overapproximation</em> of <i>A</i>.
683</p>
684
685<p>
686 It is important that it not be too much of an overapproximation,
687 though, since redundant declared dependencies can make builds slower and
688 binaries larger.
689</p>
690
691<p>
692 What this means for BUILD file writers is that every rule must
693 explicitly declare all of its actual direct dependencies to the
694 build system, and no more.
695
696 Failure to observe this principle causes undefined behavior: the
697 build may fail, but worse, the build may depend on some prior
698 operations, or upon which transitive declared dependencies the target
699 happens to have. The build tool attempts aggressively to check for
700 missing dependencies and report errors, but it is not possible for
701 this checking to be complete in all cases.
702</p>
703
704<p>
705
706 You need not (and should not) attempt to list everything indirectly imported,
707 even if it is "needed" by A at execution time.
708</p>
709
710<p>
711 During a build of target <code>X</code>, the build tool inspects the
712 entire transitive closure of dependencies of <code>X</code> to ensure that
713 any changes in those targets are reflected in the final result,
714 rebuilding intermediates as needed.
715</p>
716
717<p>
718 The transitive nature of dependencies leads to a common mistake.
719 Through careless programming, code in one file may use code provided
720 by an <em>indirect</em> dependency, i.e. a transitive but not direct
721 edge in the declared dependency graph. Indirect dependencies do not
722 appear in the BUILD file. Since the rule doesn't
723 directly depend on the provider, there is no way to track changes,
724 as shown in the following example timeline:
725</p>
726
727<div class="greenbox">
728<p><b>1. At first, everything works</b></p>
729
730<p>The code in package <code>a</code> uses code in package <code>b</code>.
731The code in package <code>b</code> uses code in package <code>c</code>,
732and thus <code>a</code> transitively depends on <code>c</code>.</p>
733
734<div style="float:left; width: 49%; margin-top: -20px;">
735<p><code>a/BUILD</code></p>
736<pre class="code">
737<b>rule(
738 name = "a",
739 srcs = "a.in",
740 deps = "//b:b",
741)</b>
742</pre>
743<p><code>a/a.in</code></p>
744<pre class="code">
745<b>import b;
746b.foo();</b>
747</pre>
748</div>
749<div style="float:right; width: 49%; margin-top: -20px; ">
750<p><code>b/BUILD</code></p>
751<pre class="code">
752<b>rule(
753 name = "b",
754 srcs = "b.in",
755 deps = "//c:c",
756)</b>
757</pre>
758<p><code>b/b.in</code></p>
759<pre class="code">
760<b>import c;
761function foo() {
762 c.bar();
763}</b>
764</pre>
765</div>
766<pre style="clear: both;">
767Declared dependency graph: a --&gt; b --&gt; c
768
769Actual dependency graph: a --&gt; b --&gt; c
770</pre>
771The declared dependencies overapproximate the actual dependencies.
772All is well.
773</div>
774
775<div class="greenbox">
776<p><b>2. A latent hazard is introduced.</b></p>
777<p>
778 Someone carelessly adds code to <code>a</code> that creates a direct
779 actual dependency on <code>c</code>, but forgets to declare it.
780</p>
781<div style="float:left; width: 49%; margin-top: -20px; ">
782<p><code>a/a.in</code></p>
783<pre class="code">
784import b;
785<b>import c;</b>
786b.foo();
787<b>c.garply();</b>
788</pre>
789</div>
790
791<pre style="clear: both;">
792Declared dependency graph: a --&gt; b --&gt; c
793
794Actual dependency graph: a --&gt; b --&gt;_c
795 \_________/|
796</pre>
797The declared dependencies no longer overapproximate the actual
798dependencies. This may build ok, because the transitive closures of
799the two graphs are equal, but masks a problem: <code>a</code> has an
800actual but undeclared dependency on <code>c</code>.
801</div>
802
803<div class="greenbox">
804<p><b>3. The hazard is revealed</b> </p>
805<p>
806 Someone refactors <code>b</code> so that it no longer depends on
807 <code>c</code>, inadvertently breaking <code>a</code> through no
808 fault of their own.
809</p>
810<div style="float:right; width: 49%; margin-top: -20px; ">
811<p><code>b/BUILD</code></p>
812<pre class="code">
813rule(
814 name = "b",
815 srcs = "b.in",
816 <b>deps = "//d:d"</b>,
817)
818</pre>
819<p><code>b/b.in</code></p>
820<pre class="code">
821<b>import d;</b>
822function foo() {
823 <b>d.baz();</b>
824}
825</pre>
826</div>
827<pre style="clear: both;">
828Declared dependency graph: a --&gt; b c
829
830Actual dependency graph: a --&gt; b _c
831 \_________/|
832</pre>
833<p>
834 The declared dependency graph is now an underapproximation of the
835 actual dependencies, even when transitively closed; the build is
836 likely to fail.
837
838 The problem could have been averted by ensuring that the actual
839 dependency from <code>a</code> to <code>c</code> introduced in Step
840 2 was properly declared in the BUILD file.
841</div>
842
843<h3 id="types_of_dependencies">Types of dependencies</h3>
844
845<p>
846 Most build rules have three attributes for specifying different kinds
847 of generic dependencies: <code>srcs</code>, <code>deps</code> and
848 <code>data</code>. These are explained below. See also
849 <a href='be/common-definitions.html'>Attributes common
dannark27486a62017-06-26 06:36:31 +0200850 to all rules</a> in the Build Encyclopedia.
David Chen8fe82a32016-08-24 10:55:41 +0000851</p>
852
853<p>
854 Many rules also have additional attributes for rule-specific kinds
855 of dependency, e.g. <code>compiler</code>, <code>resources</code>,
856 etc. These are detailed in the Build Encyclopedia.
857</p>
858
859<h4 id="srcs"><code>srcs</code> dependencies</h4>
860<p>
861 Files consumed directly by the rule or rules that output source files.
862</p>
863
864<h4 id="deps"><code>deps</code> dependencies</h4>
865<p>
866 Rule pointing to separately-compiled modules providing header files,
867 symbols, libraries, data, etc.
868</p>
869
870<h4 id="data"><code>data</code> dependencies</h4>
871<p>A build target might need some data files to run correctly. These
872 data files aren't source code: they don't affect how the target is
873 built. For example, a unit test might compare a function's output
874 to the contents of a file. When we build the unit test, we
875 don't need the file; but we do need it when we run the test. The
876 same applies to tools that are launched during execution.
877
878<p>The build system runs tests in an isolated directory where only files
879 listed as "data" are available. Thus, if a binary/library/test
880 needs some files to run, specify them (or a build rule containing
881 them) in data. For example:
882</p>
883
884<pre>
885# I need a config file from a directory named env:
886java_binary(
887 name = "setenv",
888 ...
889 data = [":env/default_env.txt"],
890)
891
892# I need test data from another directory
893sh_test(
894 name = "regtest",
895 srcs = ["regtest.sh"],
896 data = [
897 "//data:file1.txt",
898 "//data:file2.txt",
899 ...
900 ],
901)
902</pre>
903
904<p>These files are available using the relative path
905<code>path/to/data/file</code>. In tests, it is also possible to refer to
906them by joining the paths of the test's source directory and the workspace-relative
907path, e.g.
908
909<code>${TEST_SRCDIR}/workspace/path/to/data/file</code>.
910 <h3 id="label_directory">Using Labels to Reference Directories</h3>
911
912 <p>As you look over our <code>BUILD</code> files, you might notice
913 that some <code>data</code> labels refer to directories.
914 These labels end with <code>/.</code> or <code>/</code> like so:
915
916<pre>
917<span style="text-decoration: line-through">data = ["//data/regression:unittest/."]</span> # don't use this
918</pre>
919<p>
920or like so:
921</p>
922<pre>
923<span style="text-decoration: line-through">data = ["testdata/."]</span> # don't use this
924</pre>
925
926<p>
927or like so:
928</p>
929
930<pre>
931<span style="text-decoration: line-through">data = ["testdata/"]</span> # don't use this
932</pre>
933 <p>This seems convenient, particularly for tests (since it allows a test to
934 use all the data files in the directory).
935 </p>
936
937 <p>But try not to do this. In order to ensure correct incremental rebuilds (and
938 re-execution of tests) after a change, the build system must be
939 aware of the complete set of files that are inputs to the build (or
940 test). When you specify a directory, the build system will perform
941 a rebuild only when the directory itself changes (due to addition or
942 deletion of files), but won't be able to detect edits to individual
943 files as those changes do not affect the enclosing directory.
944 Rather than specifying directories as inputs to the build system,
945 you should enumerate the set of files contained within them, either
946 explicitly or using the
947 <a href='be/functions.html#glob'><code>glob()</code></a> function.
948 (Use <code>**</code> to force the <a href='be/functions.html#glob'>
949 <code>glob()</code></a> to be recursive.)
950 </p>
951
952<pre>
953data = glob(["testdata/**"]) # use this instead
954</pre>
955
956 <p>Unfortunately, there are some scenarios where directory labels must be used.
957 For example, if the <code>testdata</code> directory contains files whose
958 names do not conform to the strict <a href='#lexi'>label syntax</a>
959 (e.g. they contain certain punctuation symbols), then explicit
960 enumeration of files, or use of the
961 <a href='be/functions.html#glob'><code>glob()</code></a> function will
962 produce an invalid labels error. You must use directory labels in this case,
963 but beware of the concomitant risk of incorrect rebuilds described above.
964 </p>
965
966 <p>If you must use directory labels, keep in mind that you can't refer to the parent
967 package with a relative "<code>../</code>" path; instead, use an absolute path like
968 "<code>//data/regression:unittest/.</code>".
969 </p>
970
971 <p>Note that directory labels are only valid for data dependencies. If you try to use
972 a directory as a label in an argument other than <code>data</code>, it
973 will fail and you will get a (probably cryptic) error message.
974 </p>
975