1# GN Language and Operation 2 3[TOC] 4 5## Introduction 6 7This page describes many of the language details and behaviors. 8 9### Use the built-in help! 10 11GN has an extensive built-in help system which provides a reference for 12every function and built-in variable. This page is more high-level. 13 14``` 15gn help 16``` 17 18You can also see the 19[slides](https://docs.google.com/presentation/d/15Zwb53JcncHfEwHpnG_PoIbbzQ3GQi_cpujYwbpcbZo/edit?usp=sharing) 20from a March, 2016 introduction to GN. The speaker notes contain the full 21content. 22 23### Design philosophy 24 25 * Writing build files should not be a creative endeavour. Ideally two 26 people should produce the same buildfile given the same 27 requirements. There should be no flexibility unless it's absolutely 28 needed. As many things should be fatal errors as possible. 29 30 * The definition should read more like code than rules. I don't want 31 to write or debug Prolog. But everybody on our team can write and 32 debug C++ and Python. 33 34 * The build language should be opinionated as to how the build should 35 work. It should not necessarily be easy or even possible to express 36 arbitrary things. We should be changing source and tooling to make 37 the build simpler rather than making everything more complicated to 38 conform to external requirements (within reason). 39 40 * Be like Blaze when it makes sense (see "Differences and similarities 41 to Blaze" below). 42 43## Language 44 45GN uses an extremely simple, dynamically typed language. The types are: 46 47 * Boolean (`true`, `false`). 48 * 64-bit signed integers. 49 * Strings. 50 * Lists (of any other types). 51 * Scopes (sort of like a dictionary, only for built-in stuff). 52 53There are some built-in variables whose values depend on the current 54environment. See `gn help` for more. 55 56There are purposefully many omissions in the language. There are no 57user-defined function calls, for example (templates are the closest thing). As 58per the above design philosophy, if you need this kind of thing you're probably 59doing it wrong. 60 61The variable `sources` has a special rule: when assigning to it, a list 62of exclusion patterns is applied to it. This is designed to 63automatically filter out some types of files. See `gn help 64set_sources_assignment_filter` and `gn help label_pattern` for more. 65 66The full grammar for language nerds is available in `gn help grammar`. 67 68### Strings 69 70Strings are enclosed in double-quotes and use backslash as the escape 71character. The only escape sequences supported are: 72 73 * `\"` (for literal quote) 74 * `\$` (for literal dollars sign) 75 * `\\` (for literal backslash) 76 77Any other use of a backslash is treated as a literal backslash. So, for 78example, `\b` used in patterns does not need to be escaped, nor do most Windows 79paths like `"C:\foo\bar.h"`. 80 81Simple variable substitution is supported via `$`, where the word 82following the dollars sign is replaced with the value of the variable. 83You can optionally surround the name with `{}` if there is not a 84non-variable-name character to terminate the variable name. More complex 85expressions are not supported, only variable name substitution. 86 87``` 88a = "mypath" 89b = "$a/foo.cc" # b -> "mypath/foo.cc" 90c = "foo${a}bar.cc" # c -> "foomypathbar.cc" 91``` 92 93You can encode 8-bit characters using "$0xFF" syntax, so a string with newlines 94(hex 0A) would `"look$0x0Alike$0x0Athis"`. 95 96### Lists 97 98Aside from telling empty lists from non empty lists (`a == []`), there is no 99way to get the length of a list. If you find yourself wanting to do this kind 100of thing, you're trying to do too much work in the build. 101 102Lists support appending: 103 104``` 105a = [ "first" ] 106a += [ "second" ] # [ "first", "second" ] 107a += [ "third", "fourth" ] # [ "first", "second", "third", "fourth" ] 108b = a + [ "fifth" ] # [ "first", "second", "third", "fourth", "fifth" ] 109``` 110 111Appending a list to another list appends the items in the second list 112rather than appending the list as a nested member. 113 114You can remove items from a list: 115 116``` 117a = [ "first", "second", "third", "first" ] 118b = a - [ "first" ] # [ "second", "third" ] 119a -= [ "second" ] # [ "first", "third", "fourth" ] 120``` 121 122The - operator on a list searches for matches and removes all matching 123items. Subtracting a list from another list will remove each item in the 124second list. 125 126If no matching items are found, an error will be thrown, so you need to 127know in advance that the item is there before removing it. Given that 128there is no way to test for inclusion, the main use-case is to set up a 129master list of files or flags, and to remove ones that don't apply to 130the current build based on various conditions. 131 132Stylistically, prefer to only add to lists and have each source file or 133dependency appear once. This is the opposite of the advice Chrome-team used to 134give for GYP (GYP would prefer to list all files, and then remove the ones you 135didn't want in conditionals). 136 137Lists support zero-based subscripting to extract values: 138 139``` 140a = [ "first", "second", "third" ] 141b = a[1] # -> "second" 142``` 143 144The \[\] operator is read-only and can not be used to mutate the 145list. The primary use-case of this is when an external script returns 146several known values and you want to extract them. 147 148There are some cases where it's easy to overwrite a list when you mean 149to append to it instead. To help catch this case, it is an error to 150assign a nonempty list to a variable containing an existing nonempty 151list. If you want to get around this restriction, first assign the 152destination variable to the empty list. 153 154``` 155a = [ "one" ] 156a = [ "two" ] # Error: overwriting nonempty list with a nonempty list. 157a = [] # OK 158a = [ "two" ] # OK 159``` 160 161Note that execution of the build script is done without intrinsic 162knowledge of the meaning of the underlying data. This means that it 163doesn't know that `sources` is a list of file names, for example. So if 164you remove an item, it must match the literal string rather than 165specifying a different name that will resolve to the same file name. 166 167### Conditionals 168 169Conditionals look like C: 170 171``` 172 if (is_linux || (is_win && target_cpu == "x86")) { 173 sources -= [ "something.cc" ] 174 } else if (...) { 175 ... 176 } else { 177 ... 178 } 179``` 180 181You can use them in most places, even around entire targets if the 182target should only be declared in certain circumstances. 183 184### Looping 185 186You can iterate over a list with `foreach`. This is discouraged. Most things 187the build should do can normally be expressed without doing this, and if you 188find it necessary it may be an indication you're doing too much work in the 189metabuild. 190 191``` 192foreach(i, mylist) { 193 print(i) # Note: i is a copy of each element, not a reference to it. 194} 195``` 196 197### Function calls 198 199Simple function calls look like most other languages: 200 201``` 202print("hello, world") 203assert(is_win, "This should only be executed on Windows") 204``` 205 206Such functions are built-in and the user can not define new ones. 207 208Some functions take a block of code enclosed by `{ }` following them: 209 210``` 211static_library("mylibrary") { 212 sources = [ "a.cc" ] 213} 214``` 215 216Most of these define targets. The user can define new functions like this 217with the template mechanism discussed below. 218 219Precisely, this expression means that the block becomes an argument to the 220function for the function to execute. Most of the block-style functions execute 221the block and treat the resulting scope as a dictionary of variables to read. 222 223### Scoping and execution 224 225Files and function calls followed by `{ }` blocks introduce new scopes. Scopes 226are nested. When you read a variable, the containing scopes will be searched in 227reverse order until a matching name is found. Variable writes always go to the 228innermost scope. 229 230There is no way to modify any enclosing scope other than the innermost 231one. This means that when you define a target, for example, nothing you 232do inside of the block will "leak out" into the rest of the file. 233 234`if`/`else`/`foreach` statements, even though they use `{ }`, do not introduce 235a new scope so changes will persist outside of the statement. 236 237## Naming things 238 239### File and directory names 240 241File and directory names are strings and are interpreted as relative to 242the current build file's directory. There are three possible forms: 243 244Relative names: 245 246``` 247"foo.cc" 248"src/foo.cc" 249"../src/foo.cc" 250``` 251 252Source-tree absolute names: 253 254``` 255"//net/foo.cc" 256"//base/test/foo.cc" 257``` 258 259System absolute names (rare, normally used for include directories): 260 261``` 262"/usr/local/include/" 263"/C:/Program Files/Windows Kits/Include" 264``` 265 266## Build configuration 267 268## Targets 269 270A target is a node in the build graph. It usually represents some kind 271of executable or library file that will be generated. Targets depend on 272other targets. The built-in target types (see `gn help <targettype>` for 273more help) are: 274 275 * `action`: Run a script to generate a file. 276 * `action_foreach`: Run a script once for each source file. 277 * `bundle_data`: Declare data to go into a Mac/iOS bundle. 278 * `create_bundle`: Creates a Mac/iOS bundle. 279 * `executable`: Generates an executable file. 280 * `group`: A virtual dependency node that refers to one or more other 281 targets. 282 * `shared_library`: A .dll or .so. 283 * `loadable_module`: A .dll or .so loadable only at runtime. 284 * `source_set`: A lightweight virtual static library (usually 285 preferrable over a real static library since it will build faster). 286 * `static_library`: A .lib or .a file (normally you'll want a 287 `source_set` instead). 288 289You can extend this to make custom target types using templates (see below). In 290Chrome some of the more commonly-used templates are: 291 292 * `component`: Either a source set or shared library, depending on the 293 build type. 294 * `test`: A test executable. On mobile this will create the appropriate 295 native app type for tests. 296 * `app`: Executable or Mac/iOS application. 297 * `android_apk`: Make an APK. There are a _lot_ of other Android ones, see 298 `//build/config/android/rules.gni`. 299 300## Configs 301 302Configs are named objects that specify sets of flags, include 303directories, and defines. They can be applied to a target and pushed to 304dependent targets. 305 306To define a config: 307 308``` 309config("myconfig") { 310 includes = [ "src/include" ] 311 defines = [ "ENABLE_DOOM_MELON" ] 312} 313``` 314 315To apply a config to a target: 316 317``` 318executable("doom_melon") { 319 configs = [ ":myconfig" ] 320} 321``` 322 323It is common for the build config file to specify target defaults that 324set a default list of configs. Targets can add or remove to this list as 325needed. So in practice you would usually use `configs += ":myconfig"` to 326append to the list of defaults. 327 328See `gn help config` for more information about how configs are declared 329and applied. 330 331### Public configs 332 333A target can apply settings to other targets that depend on it. The most 334common example is a third party target that requires some defines or 335include directories for its headers to compile properly. You want these 336settings to apply both to the compile of the third party library itself, 337as well as all targets that use the library. 338 339To do this, you write a config with the settings you want to apply: 340 341``` 342config("my_external_library_config") { 343 includes = "." 344 defines = [ "DISABLE_JANK" ] 345} 346``` 347 348Then this config is added to the target as a "public" config. It will 349apply both to the target as well as targets that directly depend on it. 350 351``` 352shared_library("my_external_library") { 353 ... 354 # Targets that depend on this get this config applied. 355 public_configs = [ ":my_external_library_config" ] 356} 357``` 358 359Dependent targets can in turn forward this up the dependency tree 360another level by adding your target as a "public" dependency. 361 362``` 363static_library("intermediate_library") { 364 ... 365 # Targets that depend on this one also get the configs from "my external library". 366 public_deps = [ ":my_external_library" ] 367} 368``` 369 370A target can forward a config to all dependents until a link boundary is 371reached by setting it as an `all_dependent_config`. This is strongly 372discouraged as it can spray flags and defines over more of the build than 373necessary. Instead, use public_deps to control which flags apply where. 374 375In Chrome, prefer the build flag header system (`build/buildflag_header.gni`) 376for defines which prevents most screw-ups with compiler defines. 377 378## Templates 379 380Templates are GN's primary way to re-use code. Typically, a template 381would expand to one or more other target types. 382 383``` 384# Declares a script that compiles IDL files to source, and then compiles those 385# source files. 386template("idl") { 387 # Always base helper targets on target_name so they're unique. Target name 388 # will be the string passed as the name when the template is invoked. 389 idl_target_name = "${target_name}_generate" 390 action_foreach(idl_target_name) { 391 ... 392 } 393 394 # Your template should always define a target with the name target_name. 395 # When other targets depend on your template invocation, this will be the 396 # destination of that dependency. 397 source_set(target_name) { 398 ... 399 deps = [ ":$idl_target_name" ] # Require the sources to be compiled. 400 } 401} 402``` 403 404Typically your template definition would go in a `.gni` file and users 405would import that file to see the template definition: 406 407``` 408import("//tools/idl_compiler.gni") 409 410idl("my_interfaces") { 411 sources = [ "a.idl", "b.idl" ] 412} 413``` 414 415Declaring a template creates a closure around the variables in scope at 416that time. When the template is invoked, the magic variable `invoker` is 417used to read variables out of the invoking scope. The template would 418generally copy the values its interested in into its own scope: 419 420``` 421template("idl") { 422 source_set(target_name) { 423 sources = invoker.sources 424 } 425} 426``` 427 428The current directory when a template executes will be that of the 429invoking build file rather than the template source file. This is so 430files passed in from the template invoker will be correct (this 431generally accounts for most file handling in a template). However, if 432the template has files itself (perhaps it generates an action that runs 433a script), you will want to use absolute paths ("//foo/...") to refer to 434these files to account for the fact that the current directory will be 435unpredictable during invocation. See `gn help template` for more 436information and more complete examples. 437 438## Other features 439 440### Imports 441 442You can import `.gni` files into the current scope with the `import` 443function. This is _not_ an include in the C++ sense. The imported file is 444executed independently and the resulting scope is copied into the current file 445(C++ executes the included file in the current context of when the 446include directive appeared). This allows the results of the import to be 447cached, and also prevents some of the more "creative" uses of includes like 448multiply-included files. 449 450Typically, a `.gni` would define build arguments and templates. See `gn 451help import` for more. 452 453Your `.gni` file can define temporary variables that are not exported files 454that include it by using a preceding underscore in the name like `_this`. 455 456### Path processing 457 458Often you will want to make a file name or a list of file names relative 459to a different directory. This is especially common when running 460scripts, which are executed with the build output directory as the 461current directory, while build files usually refer to files relative to 462their containing directory. 463 464You can use `rebase_path` to convert directories. See `gn help 465rebase_path` for more help and examples. Typical usage to convert a file 466name relative to the current directory to be relative to the root build 467directory would be: ``` new_paths = rebase_path("myfile.c", 468root_build_dir) ``` 469 470### Patterns 471 472Patterns are used to generate the output file names for a given set of 473inputs for custom target types, and to automatically remove files from 474the `sources` variable (see `gn help set_sources_assignment_filter`). 475 476They are like simple regular expressions. See `gn help label_pattern` 477for more. 478 479### Executing scripts 480 481There are two ways to execute scripts. All external scripts in GN are in 482Python. The first way is as a build step. Such a script would take some 483input and generate some output as part of the build. Targets that invoke 484scripts are declared with the "action" target type (see `gn help 485action`). 486 487The second way to execute scripts is synchronously during build file 488execution. This is necessary in some cases to determine the set of files 489to compile, or to get certain system configurations that the build file 490might depend on. The build file can read the stdout of the script and 491act on it in different ways. 492 493Synchronous script execution is done by the `exec_script` function (see 494`gn help exec_script` for details and examples). Because synchronously 495executing a script requires that the current buildfile execution be 496suspended until a Python process completes execution, relying on 497external scripts is slow and should be minimized. 498 499To prevent abuse, files permitted to call `exec_script` can be whitelisted in 500the toplevel `.gn` file. Chrome does this to require additional code review 501for such additions. See `gn help dotfile`. 502 503You can synchronously read and write files which is discouraged but 504occasionally necessary when synchronously running scripts. The typical use-case 505would be to pass a list of file names longer than the command-line limits of 506the current platform. See `gn help read_file` and `gn help write_file` for how 507to read and write files. These functions should be avoided if at all possible. 508 509Actions that exceed command-line length limits can use response files to 510get around this limitation without synchronously writing files. See 511`gn help response_file_contents`. 512 513# Differences and similarities to Blaze 514 515Blaze is Google's internal build system, now publicly released as 516[Bazel](http://bazel.io/). It has inspired a number of other systems such as 517[Pants](http://www.pantsbuild.org/) and [Buck](http://facebook.github.io/buck/). 518 519In Google's homogeneous environment, the need for conditionals is very 520low and they can get by with a few hacks (`abi_deps`). Chrome uses 521conditionals all over the place and the need to add these is the main 522reason for the files looking different. 523 524GN also adds the concept of "configs" to manage some of the trickier 525dependency and configuration problems which likewise don't arise on the 526server. Blaze has a concept of a "configuration" which is like a GN 527toolchain, but built into the tool itself. The way that toolchains work 528in GN is a result of trying to separate this concept out into the build 529files in a clean way. 530 531GN keeps some GYP concept like "all dependent" settings which work a bit 532differently in Blaze. This is partially to make conversion from the existing 533GYP code easier, and the GYP constructs generally offer more fine-grained 534control (which is either good or bad, depending on the situation). 535 536GN also uses GYP names like "sources" instead of "srcs" since 537abbreviating this seems needlessly obscure, although it uses Blaze's 538"deps" since "dependencies" is so hard to type. Chromium also compiles 539multiple languages in one target so specifying the language type on the 540target name prefix was dropped (e.g. from `cc_library`). 541