Merge pull request #964 from nicolasdespres/sighup
[platform/upstream/ninja.git] / doc / manual.asciidoc
1 Ninja
2 =====
3
4
5 Introduction
6 ------------
7
8 Ninja is yet another build system.  It takes as input the
9 interdependencies of files (typically source code and output
10 executables) and orchestrates building them, _quickly_.
11
12 Ninja joins a sea of other build systems.  Its distinguishing goal is
13 to be fast.  It is born from
14 http://neugierig.org/software/chromium/notes/2011/02/ninja.html[my
15 work on the Chromium browser project], which has over 30,000 source
16 files and whose other build systems (including one built from custom
17 non-recursive Makefiles) would take ten seconds to start building
18 after changing one file.  Ninja is under a second.
19
20 Philosophical overview
21 ~~~~~~~~~~~~~~~~~~~~~~
22
23 Where other build systems are high-level languages, Ninja aims to be
24 an assembler.
25
26 Build systems get slow when they need to make decisions.  When you are
27 in a edit-compile cycle you want it to be as fast as possible -- you
28 want the build system to do the minimum work necessary to figure out
29 what needs to be built immediately.
30
31 Ninja contains the barest functionality necessary to describe
32 arbitrary dependency graphs.  Its lack of syntax makes it impossible
33 to express complex decisions.
34
35 Instead, Ninja is intended to be used with a separate program
36 generating its input files.  The generator program (like the
37 `./configure` found in autotools projects) can analyze system
38 dependencies and make as many decisions as possible up front so that
39 incremental builds stay fast.  Going beyond autotools, even build-time
40 decisions like "which compiler flags should I use?"  or "should I
41 build a debug or release-mode binary?"  belong in the `.ninja` file
42 generator.
43
44 Design goals
45 ~~~~~~~~~~~~
46
47 Here are the design goals of Ninja:
48
49 * very fast (i.e., instant) incremental builds, even for very large
50   projects.
51
52 * very little policy about how code is built.  Different projects and
53   higher-level build systems have different opinions about how code
54   should be built; for example, should built objects live alongside
55   the sources or should all build output go into a separate directory?
56   Is there a "package" rule that builds a distributable package of
57   the project?  Sidestep these decisions by trying to allow either to
58   be implemented, rather than choosing, even if that results in
59   more verbosity.
60
61 * get dependencies correct, and in particular situations that are
62   difficult to get right with Makefiles (e.g. outputs need an implicit
63   dependency on the command line used to generate them; to build C
64   source code you need to use gcc's `-M` flags for header
65   dependencies).
66
67 * when convenience and speed are in conflict, prefer speed.
68
69 Some explicit _non-goals_:
70
71 * convenient syntax for writing build files by hand.  _You should
72   generate your ninja files using another program_.  This is how we
73   can sidestep many policy decisions.
74
75 * built-in rules. _Out of the box, Ninja has no rules for
76   e.g. compiling C code._
77
78 * build-time customization of the build. _Options belong in
79   the program that generates the ninja files_.
80
81 * build-time decision-making ability such as conditionals or search
82   paths. _Making decisions is slow._
83
84 To restate, Ninja is faster than other build systems because it is
85 painfully simple.  You must tell Ninja exactly what to do when you
86 create your project's `.ninja` files.
87
88 Comparison to Make
89 ~~~~~~~~~~~~~~~~~~
90
91 Ninja is closest in spirit and functionality to Make, relying on
92 simple dependencies between file timestamps.
93
94 But fundamentally, make has a lot of _features_: suffix rules,
95 functions, built-in rules that e.g. search for RCS files when building
96 source.  Make's language was designed to be written by humans.  Many
97 projects find make alone adequate for their build problems.
98
99 In contrast, Ninja has almost no features; just those necessary to get
100 builds correct while punting most complexity to generation of the
101 ninja input files.  Ninja by itself is unlikely to be useful for most
102 projects.
103
104 Here are some of the features Ninja adds to Make.  (These sorts of
105 features can often be implemented using more complicated Makefiles,
106 but they are not part of make itself.)
107
108 * Ninja has special support for discovering extra dependencies at build
109   time, making it easy to get <<ref_headers,header dependencies>>
110   correct for C/C++ code.
111
112 * A build edge may have multiple outputs.
113
114 * Outputs implicitly depend on the command line that was used to generate
115   them, which means that changing e.g. compilation flags will cause
116   the outputs to rebuild.
117
118 * Output directories are always implicitly created before running the
119   command that relies on them.
120
121 * Rules can provide shorter descriptions of the command being run, so
122   you can print e.g. `CC foo.o` instead of a long command line while
123   building.
124
125 * Builds are always run in parallel, based by default on the number of
126   CPUs your system has.  Underspecified build dependencies will result
127   in incorrect builds.
128
129 * Command output is always buffered.  This means commands running in
130   parallel don't interleave their output, and when a command fails we
131   can print its failure output next to the full command line that
132   produced the failure.
133
134
135 Using Ninja for your project
136 ----------------------------
137
138 Ninja currently works on Unix-like systems and Windows. It's seen the
139 most testing on Linux (and has the best performance there) but it runs
140 fine on Mac OS X and FreeBSD.
141
142 If your project is small, Ninja's speed impact is likely unnoticeable.
143 (However, even for small projects it sometimes turns out that Ninja's
144 limited syntax forces simpler build rules that result in faster
145 builds.)  Another way to say this is that if you're happy with the
146 edit-compile cycle time of your project already then Ninja won't help.
147
148 There are many other build systems that are more user-friendly or
149 featureful than Ninja itself.  For some recommendations: the Ninja
150 author found http://gittup.org/tup/[the tup build system] influential
151 in Ninja's design, and thinks https://github.com/apenwarr/redo[redo]'s
152 design is quite clever.
153
154 Ninja's benefit comes from using it in conjunction with a smarter
155 meta-build system.
156
157 http://code.google.com/p/gyp/[gyp]:: The meta-build system used to
158 generate build files for Google Chrome and related projects (v8,
159 node.js).  gyp can generate Ninja files for all platforms supported by
160 Chrome. See the
161 http://code.google.com/p/chromium/wiki/NinjaBuild[Chromium Ninja
162 documentation for more details].
163
164 http://www.cmake.org/[CMake]:: A widely used meta-build system that
165 can generate Ninja files on Linux as of CMake version 2.8.8.  (There
166 is some Mac and Windows support -- http://www.reactos.org[ReactOS]
167 uses Ninja on Windows for their buildbots, but those platforms are not
168 yet officially supported by CMake as the full test suite doesn't
169 pass.)
170
171 others:: Ninja ought to fit perfectly into other meta-build software
172 like http://industriousone.com/premake[premake].  If you do this work,
173 please let us know!
174
175 Running Ninja
176 ~~~~~~~~~~~~~
177
178 Run `ninja`.  By default, it looks for a file named `build.ninja` in
179 the current directory and builds all out-of-date targets.  You can
180 specify which targets (files) to build as command line arguments.
181
182 There is also a special syntax `target^` for specifying a target
183 as the first output of some rule containing the source you put in
184 the command line, if one exists. For example, if you specify target as
185 `foo.c^` then `foo.o` will get built (assuming you have those targets
186 in your build files).
187
188 `ninja -h` prints help output.  Many of Ninja's flags intentionally
189 match those of Make; e.g `ninja -C build -j 20` changes into the
190 `build` directory and runs 20 build commands in parallel.  (Note that
191 Ninja defaults to running commands in parallel anyway, so typically
192 you don't need to pass `-j`.)
193
194
195 Environment variables
196 ~~~~~~~~~~~~~~~~~~~~~
197
198 Ninja supports one environment variable to control its behavior:
199 `NINJA_STATUS`, the progress status printed before the rule being run.
200
201 Several placeholders are available:
202
203 `%s`:: The number of started edges.
204 `%t`:: The total number of edges that must be run to complete the build.
205 `%p`:: The percentage of started edges.
206 `%r`:: The number of currently running edges.
207 `%u`:: The number of remaining edges to start.
208 `%f`:: The number of finished edges.
209 `%o`:: Overall rate of finished edges per second
210 `%c`:: Current rate of finished edges per second (average over builds
211 specified by `-j` or its default)
212 `%e`:: Elapsed time in seconds.  _(Available since Ninja 1.2.)_
213 `%%`:: A plain `%` character.
214
215 The default progress status is `"[%s/%t] "` (note the trailing space
216 to separate from the build rule). Another example of possible progress status
217 could be `"[%u/%r/%f] "`.
218
219 Extra tools
220 ~~~~~~~~~~~
221
222 The `-t` flag on the Ninja command line runs some tools that we have
223 found useful during Ninja's development.  The current tools are:
224
225 [horizontal]
226 `query`:: dump the inputs and outputs of a given target.
227
228 `browse`:: browse the dependency graph in a web browser.  Clicking a
229 file focuses the view on that file, showing inputs and outputs.  This
230 feature requires a Python installation.
231
232 `graph`:: output a file in the syntax used by `graphviz`, a automatic
233 graph layout tool.  Use it like:
234 +
235 ----
236 ninja -t graph mytarget | dot -Tpng -ograph.png
237 ----
238 +
239 In the Ninja source tree, `ninja graph.png`
240 generates an image for Ninja itself.  If no target is given generate a
241 graph for all root targets.
242
243 `targets`:: output a list of targets either by rule or by depth.  If used
244 like +ninja -t targets rule _name_+ it prints the list of targets
245 using the given rule to be built.  If no rule is given, it prints the source
246 files (the leaves of the graph).  If used like
247 +ninja -t targets depth _digit_+ it
248 prints the list of targets in a depth-first manner starting by the root
249 targets (the ones with no outputs). Indentation is used to mark dependencies.
250 If the depth is zero it prints all targets. If no arguments are provided
251 +ninja -t targets depth 1+ is assumed. In this mode targets may be listed
252 several times. If used like this +ninja -t targets all+ it
253 prints all the targets available without indentation and it is faster
254 than the _depth_ mode.
255
256 `commands`:: given a list of targets, print a list of commands which, if
257 executed in order, may be used to rebuild those targets, assuming that all
258 output files are out of date.
259
260 `clean`:: remove built files. By default it removes all built files
261 except for those created by the generator.  Adding the `-g` flag also
262 removes built files created by the generator (see <<ref_rule,the rule
263 reference for the +generator+ attribute>>).  Additional arguments are
264 targets, which removes the given targets and recursively all files
265 built for them.
266 +
267 If used like +ninja -t clean -r _rules_+ it removes all files built using
268 the given rules.
269 +
270 Files created but not referenced in the graph are not removed. This
271 tool takes in account the +-v+ and the +-n+ options (note that +-n+
272 implies +-v+).
273
274 `compdb`:: given a list of rules, each of which is expected to be a
275 C family language compiler rule whose first input is the name of the
276 source file, prints on standard output a compilation database in the
277 http://clang.llvm.org/docs/JSONCompilationDatabase.html[JSON format] expected
278 by the Clang tooling interface.
279 _Available since Ninja 1.2._
280
281
282 Writing your own Ninja files
283 ----------------------------
284
285 The remainder of this manual is only useful if you are constructing
286 Ninja files yourself: for example, if you're writing a meta-build
287 system or supporting a new language.
288
289 Conceptual overview
290 ~~~~~~~~~~~~~~~~~~~
291
292 Ninja evaluates a graph of dependencies between files, and runs
293 whichever commands are necessary to make your build target up to date
294 as determined by file modification times.  If you are familiar with
295 Make, Ninja is very similar.
296
297 A build file (default name: `build.ninja`) provides a list of _rules_
298 -- short names for longer commands, like how to run the compiler --
299 along with a list of _build_ statements saying how to build files
300 using the rules -- which rule to apply to which inputs to produce
301 which outputs.
302
303 Conceptually, `build` statements describe the dependency graph of your
304 project, while `rule` statements describe how to generate the files
305 along a given edge of the graph.
306
307 Syntax example
308 ~~~~~~~~~~~~~~
309
310 Here's a basic `.ninja` file that demonstrates most of the syntax.
311 It will be used as an example for the following sections.
312
313 ---------------------------------
314 cflags = -Wall
315
316 rule cc
317   command = gcc $cflags -c $in -o $out
318
319 build foo.o: cc foo.c
320 ---------------------------------
321
322 Variables
323 ~~~~~~~~~
324 Despite the non-goal of being convenient to write by hand, to keep
325 build files readable (debuggable), Ninja supports declaring shorter
326 reusable names for strings.  A declaration like the following
327
328 ----------------
329 cflags = -g
330 ----------------
331
332 can be used on the right side of an equals sign, dereferencing it with
333 a dollar sign, like this:
334
335 ----------------
336 rule cc
337   command = gcc $cflags -c $in -o $out
338 ----------------
339
340 Variables can also be referenced using curly braces like `${in}`.
341
342 Variables might better be called "bindings", in that a given variable
343 cannot be changed, only shadowed.  There is more on how shadowing works
344 later in this document.
345
346 Rules
347 ~~~~~
348
349 Rules declare a short name for a command line.  They begin with a line
350 consisting of the `rule` keyword and a name for the rule.  Then
351 follows an indented set of `variable = value` lines.
352
353 The basic example above declares a new rule named `cc`, along with the
354 command to run.  In the context of a rule, the `command` variable
355 defines the command to run, `$in` expands to the list of
356 input files (`foo.c`), and `$out` to the output files (`foo.o`) for the
357 command.  A full list of special variables is provided in
358 <<ref_rule,the reference>>.
359
360 Build statements
361 ~~~~~~~~~~~~~~~~
362
363 Build statements declare a relationship between input and output
364 files.  They begin with the `build` keyword, and have the format
365 +build _outputs_: _rulename_ _inputs_+.  Such a declaration says that
366 all of the output files are derived from the input files.  When the
367 output files are missing or when the inputs change, Ninja will run the
368 rule to regenerate the outputs.
369
370 The basic example above describes how to build `foo.o`, using the `cc`
371 rule.
372
373 In the scope of a `build` block (including in the evaluation of its
374 associated `rule`), the variable `$in` is the list of inputs and the
375 variable `$out` is the list of outputs.
376
377 A build statement may be followed by an indented set of `key = value`
378 pairs, much like a rule.  These variables will shadow any variables
379 when evaluating the variables in the command.  For example:
380
381 ----------------
382 cflags = -Wall -Werror
383 rule cc
384   command = gcc $cflags -c $in -o $out
385
386 # If left unspecified, builds get the outer $cflags.
387 build foo.o: cc foo.c
388
389 # But you can shadow variables like cflags for a particular build.
390 build special.o: cc special.c
391   cflags = -Wall
392
393 # The variable was only shadowed for the scope of special.o;
394 # Subsequent build lines get the outer (original) cflags.
395 build bar.o: cc bar.c
396
397 ----------------
398
399 For more discussion of how scoping works, consult <<ref_scope,the
400 reference>>.
401
402 If you need more complicated information passed from the build
403 statement to the rule (for example, if the rule needs "the file
404 extension of the first input"), pass that through as an extra
405 variable, like how `cflags` is passed above.
406
407 If the top-level Ninja file is specified as an output of any build
408 statement and it is out of date, Ninja will rebuild and reload it
409 before building the targets requested by the user.
410
411 Generating Ninja files from code
412 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
413
414 `misc/ninja_syntax.py` in the Ninja distribution is a tiny Python
415 module to facilitate generating Ninja files.  It allows you to make
416 Python calls like `ninja.rule(name='foo', command='bar',
417 depfile='$out.d')` and it will generate the appropriate syntax.  Feel
418 free to just inline it into your project's build system if it's
419 useful.
420
421
422 More details
423 ------------
424
425 The `phony` rule
426 ~~~~~~~~~~~~~~~~
427
428 The special rule name `phony` can be used to create aliases for other
429 targets.  For example:
430
431 ----------------
432 build foo: phony some/file/in/a/faraway/subdir/foo
433 ----------------
434
435 This makes `ninja foo` build the longer path.  Semantically, the
436 `phony` rule is equivalent to a plain rule where the `command` does
437 nothing, but phony rules are handled specially in that they aren't
438 printed when run, logged (see below), nor do they contribute to the
439 command count printed as part of the build process.
440
441 `phony` can also be used to create dummy targets for files which
442 may not exist at build time.  If a phony build statement is written
443 without any dependencies, the target will be considered out of date if
444 it does not exist.  Without a phony build statement, Ninja will report
445 an error if the file does not exist and is required by the build.
446
447
448 Default target statements
449 ~~~~~~~~~~~~~~~~~~~~~~~~~
450
451 By default, if no targets are specified on the command line, Ninja
452 will build every output that is not named as an input elsewhere.
453 You can override this behavior using a default target statement.
454 A default target statement causes Ninja to build only a given subset
455 of output files if none are specified on the command line.
456
457 Default target statements begin with the `default` keyword, and have
458 the format +default _targets_+.  A default target statement must appear
459 after the build statement that declares the target as an output file.
460 They are cumulative, so multiple statements may be used to extend
461 the list of default targets.  For example:
462
463 ----------------
464 default foo bar
465 default baz
466 ----------------
467
468 This causes Ninja to build the `foo`, `bar` and `baz` targets by
469 default.
470
471
472 [[ref_log]]
473 The Ninja log
474 ~~~~~~~~~~~~~
475
476 For each built file, Ninja keeps a log of the command used to build
477 it.  Using this log Ninja can know when an existing output was built
478 with a different command line than the build files specify (i.e., the
479 command line changed) and knows to rebuild the file.
480
481 The log file is kept in the build root in a file called `.ninja_log`.
482 If you provide a variable named `builddir` in the outermost scope,
483 `.ninja_log` will be kept in that directory instead.
484
485
486 [[ref_versioning]]
487 Version compatibility
488 ~~~~~~~~~~~~~~~~~~~~~
489
490 _Available since Ninja 1.2._
491
492 Ninja version labels follow the standard major.minor.patch format,
493 where the major version is increased on backwards-incompatible
494 syntax/behavioral changes and the minor version is increased on new
495 behaviors.  Your `build.ninja` may declare a variable named
496 `ninja_required_version` that asserts the minimum Ninja version
497 required to use the generated file.  For example,
498
499 -----
500 ninja_required_version = 1.1
501 -----
502
503 declares that the build file relies on some feature that was
504 introduced in Ninja 1.1 (perhaps the `pool` syntax), and that
505 Ninja 1.1 or greater must be used to build.  Unlike other Ninja
506 variables, this version requirement is checked immediately when
507 the variable is encountered in parsing, so it's best to put it
508 at the top of the build file.
509
510 Ninja always warns if the major versions of Ninja and the
511 `ninja_required_version` don't match; a major version change hasn't
512 come up yet so it's difficult to predict what behavior might be
513 required.
514
515 [[ref_headers]]
516 C/C++ header dependencies
517 ~~~~~~~~~~~~~~~~~~~~~~~~~
518
519 To get C/C++ header dependencies (or any other build dependency that
520 works in a similar way) correct Ninja has some extra functionality.
521
522 The problem with headers is that the full list of files that a given
523 source file depends on can only be discovered by the compiler:
524 different preprocessor defines and include paths cause different files
525 to be used.  Some compilers can emit this information while building,
526 and Ninja can use that to get its dependencies perfect.
527
528 Consider: if the file has never been compiled, it must be built anyway,
529 generating the header dependencies as a side effect.  If any file is
530 later modified (even in a way that changes which headers it depends
531 on) the modification will cause a rebuild as well, keeping the
532 dependencies up to date.
533
534 When loading these special dependencies, Ninja implicitly adds extra
535 build edges such that it is not an error if the listed dependency is
536 missing.  This allows you to delete a header file and rebuild without
537 the build aborting due to a missing input.
538
539 depfile
540 ^^^^^^^
541
542 `gcc` (and other compilers like `clang`) support emitting dependency
543 information in the syntax of a Makefile.  (Any command that can write
544 dependencies in this form can be used, not just `gcc`.)
545
546 To bring this information into Ninja requires cooperation.  On the
547 Ninja side, the `depfile` attribute on the `build` must point to a
548 path where this data is written.  (Ninja only supports the limited
549 subset of the Makefile syntax emitted by compilers.)  Then the command
550 must know to write dependencies into the `depfile` path.
551 Use it like in the following example:
552
553 ----
554 rule cc
555   depfile = $out.d
556   command = gcc -MMD -MF $out.d [other gcc flags here]
557 ----
558
559 The `-MMD` flag to `gcc` tells it to output header dependencies, and
560 the `-MF` flag tells it where to write them.
561
562 deps
563 ^^^^
564
565 _(Available since Ninja 1.3.)_
566
567 It turns out that for large projects (and particularly on Windows,
568 where the file system is slow) loading these dependency files on
569 startup is slow.
570
571 Ninja 1.3 can instead process dependencies just after they're generated
572 and save a compacted form of the same information in a Ninja-internal
573 database.
574
575 Ninja supports this processing in two forms.
576
577 1. `deps = gcc` specifies that the tool outputs `gcc`-style dependencies
578    in the form of Makefiles.  Adding this to the above example will
579    cause Ninja to process the `depfile` immediately after the
580    compilation finishes, then delete the `.d` file (which is only used
581    as a temporary).
582
583 2. `deps = msvc` specifies that the tool outputs header dependencies
584    in the form produced by Visual Studio's compiler's
585    http://msdn.microsoft.com/en-us/library/hdkef6tk(v=vs.90).aspx[`/showIncludes`
586    flag].  Briefly, this means the tool outputs specially-formatted lines
587    to its stdout.  Ninja then filters these lines from the displayed
588    output.  No `depfile` attribute is necessary, but the localized string
589    in front of the the header file path. For instance
590    `msvc_deps_prefix = Note: including file: `
591    for a English Visual Studio (the default). Should be globally defined.
592 +
593 ----
594 msvc_deps_prefix = Note: including file:
595 rule cc
596   deps = msvc
597   command = cl /showIncludes -c $in /Fo$out
598 ----
599
600 If the include directory directives are using absolute paths, your depfile
601 may result in a mixture of relative and absolute paths. Paths used by other
602 build rules need to match exactly. Therefore, it is recommended to use
603 relative paths in these cases.
604
605 [[ref_pool]]
606 Pools
607 ~~~~~
608
609 _Available since Ninja 1.1._
610
611 Pools allow you to allocate one or more rules or edges a finite number
612 of concurrent jobs which is more tightly restricted than the default
613 parallelism.
614
615 This can be useful, for example, to restrict a particular expensive rule
616 (like link steps for huge executables), or to restrict particular build
617 statements which you know perform poorly when run concurrently.
618
619 Each pool has a `depth` variable which is specified in the build file.
620 The pool is then referred to with the `pool` variable on either a rule
621 or a build statement.
622
623 No matter what pools you specify, ninja will never run more concurrent jobs
624 than the default parallelism, or the number of jobs specified on the command
625 line (with `-j`).
626
627 ----------------
628 # No more than 4 links at a time.
629 pool link_pool
630   depth = 4
631
632 # No more than 1 heavy object at a time.
633 pool heavy_object_pool
634   depth = 1
635
636 rule link
637   ...
638   pool = link_pool
639
640 rule cc
641   ...
642
643 # The link_pool is used here. Only 4 links will run concurrently.
644 build foo.exe: link input.obj
645
646 # A build statement can be exempted from its rule's pool by setting an
647 # empty pool. This effectively puts the build statement back into the default
648 # pool, which has infinite depth.
649 build other.exe: link input.obj
650   pool =
651
652 # A build statement can specify a pool directly.
653 # Only one of these builds will run at a time.
654 build heavy_object1.obj: cc heavy_obj1.cc
655   pool = heavy_object_pool
656 build heavy_object2.obj: cc heavy_obj2.cc
657   pool = heavy_object_pool
658
659 ----------------
660
661 The `console` pool
662 ^^^^^^^^^^^^^^^^^^
663
664 _Available since Ninja 1.5._
665
666 There exists a pre-defined pool named `console` with a depth of 1. It has
667 the special property that any task in the pool has direct access to the
668 standard input, output and error streams provided to Ninja, which are
669 normally connected to the user's console (hence the name) but could be
670 redirected. This can be useful for interactive tasks or long-running tasks
671 which produce status updates on the console (such as test suites).
672
673 While a task in the `console` pool is running, Ninja's regular output (such
674 as progress status and output from concurrent tasks) is buffered until
675 it completes.
676
677 Ninja file reference
678 --------------------
679
680 A file is a series of declarations.  A declaration can be one of:
681
682 1. A rule declaration, which begins with +rule _rulename_+, and
683    then has a series of indented lines defining variables.
684
685 2. A build edge, which looks like +build _output1_ _output2_:
686    _rulename_ _input1_ _input2_+. +
687    Implicit dependencies may be tacked on the end with +|
688    _dependency1_ _dependency2_+. +
689    Order-only dependencies may be tacked on the end with +||
690    _dependency1_ _dependency2_+.  (See <<ref_dependencies,the reference on
691    dependency types>>.)
692
693 3. Variable declarations, which look like +_variable_ = _value_+.
694
695 4. Default target statements, which look like +default _target1_ _target2_+.
696
697 5. References to more files, which look like +subninja _path_+ or
698    +include _path_+.  The difference between these is explained below
699    <<ref_scope,in the discussion about scoping>>.
700
701 6. A pool declaration, which looks like +pool _poolname_+. Pools are explained
702    <<ref_pool, in the section on pools>>.
703
704 Lexical syntax
705 ~~~~~~~~~~~~~~
706
707 Ninja is mostly encoding agnostic, as long as the bytes Ninja cares
708 about (like slashes in paths) are ASCII.  This means e.g. UTF-8 or
709 ISO-8859-1 input files ought to work.
710
711 Comments begin with `#` and extend to the end of the line.
712
713 Newlines are significant.  Statements like `build foo bar` are a set
714 of space-separated tokens that end at the newline.  Newlines and
715 spaces within a token must be escaped.
716
717 There is only one escape character, `$`, and it has the following
718 behaviors:
719
720 [horizontal]
721 `$` followed by a newline:: escape the newline (continue the current line
722 across a line break).
723
724 `$` followed by text:: a variable reference.
725
726 `${varname}`:: alternate syntax for `$varname`.
727
728 `$` followed by space:: a space.  (This is only necessary in lists of
729 paths, where a space would otherwise separate filenames.  See below.)
730
731 `$:` :: a colon.  (This is only necessary in `build` lines, where a colon
732 would otherwise terminate the list of outputs.)
733
734 `$$`:: a literal `$`.
735
736 A `build` or `default` statement is first parsed as a space-separated
737 list of filenames and then each name is expanded.  This means that
738 spaces within a variable will result in spaces in the expanded
739 filename.
740
741 ----
742 spaced = foo bar
743 build $spaced/baz other$ file: ...
744 # The above build line has two outputs: "foo bar/baz" and "other file".
745 ----
746
747 In a `name = value` statement, whitespace at the beginning of a value
748 is always stripped.  Whitespace at the beginning of a line after a
749 line continuation is also stripped.
750
751 ----
752 two_words_with_one_space = foo $
753     bar
754 one_word_with_no_space = foo$
755     bar
756 ----
757
758 Other whitespace is only significant if it's at the beginning of a
759 line.  If a line is indented more than the previous one, it's
760 considered part of its parent's scope; if it is indented less than the
761 previous one, it closes the previous scope.
762
763 [[ref_toplevel]]
764 Top-level variables
765 ~~~~~~~~~~~~~~~~~~~
766
767 Two variables are significant when declared in the outermost file scope.
768
769 `builddir`:: a directory for some Ninja output files.  See <<ref_log,the
770   discussion of the build log>>.  (You can also store other build output
771   in this directory.)
772
773 `ninja_required_version`:: the minimum version of Ninja required to process
774   the build correctly.  See <<ref_versioning,the discussion of versioning>>.
775
776
777 [[ref_rule]]
778 Rule variables
779 ~~~~~~~~~~~~~~
780
781 A `rule` block contains a list of `key = value` declarations that
782 affect the processing of the rule.  Here is a full list of special
783 keys.
784
785 `command` (_required_):: the command line to run.  This string (after
786   $variables are expanded) is passed directly to `sh -c` without
787   interpretation by Ninja. Each `rule` may have only one `command`
788   declaration. To specify multiple commands use `&&` (or similar) to
789   concatenate operations.
790
791 `depfile`:: path to an optional `Makefile` that contains extra
792   _implicit dependencies_ (see <<ref_dependencies,the reference on
793   dependency types>>).  This is explicitly to support C/C++ header
794   dependencies; see <<ref_headers,the full discussion>>.
795
796 `deps`:: _(Available since Ninja 1.3.)_ if present, must be one of
797   `gcc` or `msvc` to specify special dependency processing.  See
798    <<ref_headers,the full discussion>>.  The generated database is
799    stored as `.ninja_deps` in the `builddir`, see <<ref_toplevel,the
800    discussion of `builddir`>>.
801
802 `msvc_deps_prefix`:: _(Available since Ninja 1.5.)_ defines the string
803   which should be stripped from msvc's /showIncludes output. Only
804   needed when `deps = msvc` and no English Visual Studio version is used.
805
806 `description`:: a short description of the command, used to pretty-print
807   the command as it's running.  The `-v` flag controls whether to print
808   the full command or its description; if a command fails, the full command
809   line will always be printed before the command's output.
810
811 `generator`:: if present, specifies that this rule is used to
812   re-invoke the generator program.  Files built using `generator`
813   rules are treated specially in two ways: firstly, they will not be
814   rebuilt if the command line changes; and secondly, they are not
815   cleaned by default.
816
817 `in`:: the space-separated list of files provided as inputs to the build line
818   referencing this `rule`, shell-quoted if it appears in commands.  (`$in` is
819   provided solely for convenience; if you need some subset or variant of this
820   list of files, just construct a new variable with that list and use
821   that instead.)
822
823 `in_newline`:: the same as `$in` except that multiple inputs are
824   separated by newlines rather than spaces.  (For use with
825   `$rspfile_content`; this works around a bug in the MSVC linker where
826   it uses a fixed-size buffer for processing input.)
827
828 `out`:: the space-separated list of files provided as outputs to the build line
829   referencing this `rule`, shell-quoted if it appears in commands.
830
831 `restat`:: if present, causes Ninja to re-stat the command's outputs
832   after execution of the command.  Each output whose modification time
833   the command did not change will be treated as though it had never
834   needed to be built.  This may cause the output's reverse
835   dependencies to be removed from the list of pending build actions.
836
837 `rspfile`, `rspfile_content`:: if present (both), Ninja will use a
838   response file for the given command, i.e. write the selected string
839   (`rspfile_content`) to the given file (`rspfile`) before calling the
840   command and delete the file after successful execution of the
841   command.
842 +
843 This is particularly useful on Windows OS, where the maximal length of
844 a command line is limited and response files must be used instead.
845 +
846 Use it like in the following example:
847 +
848 ----
849 rule link
850   command = link.exe /OUT$out [usual link flags here] @$out.rsp
851   rspfile = $out.rsp
852   rspfile_content = $in
853
854 build myapp.exe: link a.obj b.obj [possibly many other .obj files]
855 ----
856
857 [[ref_dependencies]]
858 Build dependencies
859 ~~~~~~~~~~~~~~~~~~
860
861 There are three types of build dependencies which are subtly different.
862
863 1. _Explicit dependencies_, as listed in a build line.  These are
864    available as the `$in` variable in the rule.  Changes in these files
865    cause the output to be rebuilt; if these file are missing and
866    Ninja doesn't know how to build them, the build is aborted.
867 +
868 This is the standard form of dependency to be used for e.g. the
869 source file of a compile command.
870
871 2. _Implicit dependencies_, either as picked up from
872    a `depfile` attribute on a rule or from the syntax +| _dep1_
873    _dep2_+ on the end of a build line.  The semantics are identical to
874    explicit dependencies, the only difference is that implicit dependencies
875    don't show up in the `$in` variable.
876 +
877 This is for expressing dependencies that don't show up on the
878 command line of the command; for example, for a rule that runs a
879 script, the script itself should be an implicit dependency, as
880 changes to the script should cause the output to rebuild.
881 +
882 Note that dependencies as loaded through depfiles have slightly different
883 semantics, as described in the <<ref_rule,rule reference>>.
884
885 3. _Order-only dependencies_, expressed with the syntax +|| _dep1_
886    _dep2_+ on the end of a build line.  When these are out of date, the
887    output is not rebuilt until they are built, but changes in order-only
888    dependencies alone do not cause the output to be rebuilt.
889 +
890 Order-only dependencies can be useful for bootstrapping dependencies
891 that are only discovered during build time: for example, to generate a
892 header file before starting a subsequent compilation step.  (Once the
893 header is used in compilation, a generated dependency file will then
894 express the implicit dependency.)
895
896 File paths are compared as is, which means that an absolute path and a
897 relative path, pointing to the same file, are considered different by Ninja.
898
899 Variable expansion
900 ~~~~~~~~~~~~~~~~~~
901
902 Variables are expanded in paths (in a `build` or `default` statement)
903 and on the right side of a `name = value` statement.
904
905 When a `name = value` statement is evaluated, its right-hand side is
906 expanded immediately (according to the below scoping rules), and
907 from then on `$name` expands to the static string as the result of the
908 expansion.  It is never the case that you'll need to "double-escape" a
909 value to prevent it from getting expanded twice.
910
911 All variables are expanded immediately as they're encountered in parsing,
912 with one important exception: variables in `rule` blocks are expanded
913 when the rule is _used_, not when it is declared.  In the following
914 example, the `demo` rule prints "this is a demo of bar".
915
916 ----
917 rule demo
918   command = echo "this is a demo of $foo"
919
920 build out: demo
921   foo = bar
922 ----
923
924 [[ref_scope]]
925 Evaluation and scoping
926 ~~~~~~~~~~~~~~~~~~~~~~
927
928 Top-level variable declarations are scoped to the file they occur in.
929
930 Rule declarations are also scoped to the file they occur in.
931 _(Available since Ninja 1.6)_
932
933 The `subninja` keyword, used to include another `.ninja` file,
934 introduces a new scope.  The included `subninja` file may use the
935 variables and rules from the parent file, and shadow their values for the file's
936 scope, but it won't affect values of the variables in the parent.
937
938 To include another `.ninja` file in the current scope, much like a C
939 `#include` statement, use `include` instead of `subninja`.
940
941 Variable declarations indented in a `build` block are scoped to the
942 `build` block.  The full lookup order for a variable expanded in a
943 `build` block (or the `rule` is uses) is:
944
945 1. Special built-in variables (`$in`, `$out`).
946
947 2. Build-level variables from the `build` block.
948
949 3. Rule-level variables from the `rule` block (i.e. `$command`).
950    (Note from the above discussion on expansion that these are
951    expanded "late", and may make use of in-scope bindings like `$in`.)
952
953 4. File-level variables from the file that the `build` line was in.
954
955 5. Variables from the file that included that file using the
956    `subninja` keyword.
957