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