1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "gn/functions.h"
6
7 #include <stddef.h>
8 #include <cctype>
9 #include <memory>
10 #include <utility>
11
12 #include "base/environment.h"
13 #include "base/strings/string_util.h"
14 #include "gn/build_settings.h"
15 #include "gn/config.h"
16 #include "gn/config_values_generator.h"
17 #include "gn/err.h"
18 #include "gn/input_file.h"
19 #include "gn/parse_node_value_adapter.h"
20 #include "gn/parse_tree.h"
21 #include "gn/pool.h"
22 #include "gn/scheduler.h"
23 #include "gn/scope.h"
24 #include "gn/settings.h"
25 #include "gn/template.h"
26 #include "gn/token.h"
27 #include "gn/value.h"
28 #include "gn/value_extractors.h"
29 #include "gn/variables.h"
30
31 namespace {
32
33 // Some functions take a {} following them, and some don't. For the ones that
34 // don't, this is used to verify that the given block node is null and will
35 // set the error accordingly if it's not. Returns true if the block is null.
VerifyNoBlockForFunctionCall(const FunctionCallNode * function,const BlockNode * block,Err * err)36 bool VerifyNoBlockForFunctionCall(const FunctionCallNode* function,
37 const BlockNode* block,
38 Err* err) {
39 if (!block)
40 return true;
41
42 *err =
43 Err(block, "Unexpected '{'.",
44 "This function call doesn't take a {} block following it, and you\n"
45 "can't have a {} block that's not connected to something like an if\n"
46 "statement or a target declaration.");
47 err->AppendRange(function->function().range());
48 return false;
49 }
50
51 // This key is set as a scope property on the scope of a declare_args() block,
52 // in order to prevent reading a variable defined earlier in the same call
53 // (see `gn help declare_args` for more).
54 const void* kInDeclareArgsKey = nullptr;
55
56 } // namespace
57
EnsureNotReadingFromSameDeclareArgs(const ParseNode * node,const Scope * cur_scope,const Scope * val_scope,Err * err)58 bool EnsureNotReadingFromSameDeclareArgs(const ParseNode* node,
59 const Scope* cur_scope,
60 const Scope* val_scope,
61 Err* err) {
62 // If the value didn't come from a scope at all, we're safe.
63 if (!val_scope)
64 return true;
65
66 const Scope* val_args_scope = nullptr;
67 val_scope->GetProperty(&kInDeclareArgsKey, &val_args_scope);
68
69 const Scope* cur_args_scope = nullptr;
70 cur_scope->GetProperty(&kInDeclareArgsKey, &cur_args_scope);
71 if (!val_args_scope || !cur_args_scope || (val_args_scope != cur_args_scope))
72 return true;
73
74 *err =
75 Err(node,
76 "Reading a variable defined in the same declare_args() call.\n"
77 "\n"
78 "If you need to set the value of one arg based on another, put\n"
79 "them in two separate declare_args() calls, one after the other.\n");
80 return false;
81 }
82
EnsureNotProcessingImport(const ParseNode * node,const Scope * scope,Err * err)83 bool EnsureNotProcessingImport(const ParseNode* node,
84 const Scope* scope,
85 Err* err) {
86 if (scope->IsProcessingImport()) {
87 *err =
88 Err(node, "Not valid from an import.",
89 "Imports are for defining defaults, variables, and rules. The\n"
90 "appropriate place for this kind of thing is really in a normal\n"
91 "BUILD file.");
92 return false;
93 }
94 return true;
95 }
96
EnsureNotProcessingBuildConfig(const ParseNode * node,const Scope * scope,Err * err)97 bool EnsureNotProcessingBuildConfig(const ParseNode* node,
98 const Scope* scope,
99 Err* err) {
100 if (scope->IsProcessingBuildConfig()) {
101 *err = Err(node, "Not valid from the build config.",
102 "You can't do this kind of thing from the build config script, "
103 "silly!\nPut it in a regular BUILD file.");
104 return false;
105 }
106 return true;
107 }
108
FillTargetBlockScope(const Scope * scope,const FunctionCallNode * function,const std::string & target_type,const BlockNode * block,const std::vector<Value> & args,Scope * block_scope,Err * err)109 bool FillTargetBlockScope(const Scope* scope,
110 const FunctionCallNode* function,
111 const std::string& target_type,
112 const BlockNode* block,
113 const std::vector<Value>& args,
114 Scope* block_scope,
115 Err* err) {
116 if (!block) {
117 FillNeedsBlockError(function, err);
118 return false;
119 }
120
121 // Copy the target defaults, if any, into the scope we're going to execute
122 // the block in.
123 const Scope* default_scope = scope->GetTargetDefaults(target_type);
124 if (default_scope) {
125 Scope::MergeOptions merge_options;
126 merge_options.skip_private_vars = true;
127 if (!default_scope->NonRecursiveMergeTo(block_scope, merge_options,
128 function, "target defaults", err))
129 return false;
130 }
131
132 // The name is the single argument to the target function.
133 if (!EnsureSingleStringArg(function, args, err))
134 return false;
135
136 // Set the target name variable to the current target, and mark it used
137 // because we don't want to issue an error if the script ignores it.
138 const std::string_view target_name(variables::kTargetName);
139 block_scope->SetValue(target_name, Value(function, args[0].string_value()),
140 function);
141 block_scope->MarkUsed(target_name);
142 return true;
143 }
144
FillNeedsBlockError(const FunctionCallNode * function,Err * err)145 void FillNeedsBlockError(const FunctionCallNode* function, Err* err) {
146 *err = Err(function->function(), "This function call requires a block.",
147 "The block's \"{\" must be on the same line as the function "
148 "call's \")\".");
149 }
150
EnsureSingleStringArg(const FunctionCallNode * function,const std::vector<Value> & args,Err * err)151 bool EnsureSingleStringArg(const FunctionCallNode* function,
152 const std::vector<Value>& args,
153 Err* err) {
154 if (args.size() != 1) {
155 *err = Err(function->function(), "Incorrect arguments.",
156 "This function requires a single string argument.");
157 return false;
158 }
159 return args[0].VerifyTypeIs(Value::STRING, err);
160 }
161
ToolchainLabelForScope(const Scope * scope)162 const Label& ToolchainLabelForScope(const Scope* scope) {
163 return scope->settings()->toolchain_label();
164 }
165
MakeLabelForScope(const Scope * scope,const FunctionCallNode * function,const std::string & name)166 Label MakeLabelForScope(const Scope* scope,
167 const FunctionCallNode* function,
168 const std::string& name) {
169 const Label& toolchain_label = ToolchainLabelForScope(scope);
170 return Label(scope->GetSourceDir(), name, toolchain_label.dir(),
171 toolchain_label.name());
172 }
173
174 // static
175 const int NonNestableBlock::kKey = 0;
176
NonNestableBlock(Scope * scope,const FunctionCallNode * function,const char * type_description)177 NonNestableBlock::NonNestableBlock(Scope* scope,
178 const FunctionCallNode* function,
179 const char* type_description)
180 : scope_(scope),
181 function_(function),
182 type_description_(type_description),
183 key_added_(false) {}
184
~NonNestableBlock()185 NonNestableBlock::~NonNestableBlock() {
186 if (key_added_)
187 scope_->SetProperty(&kKey, nullptr);
188 }
189
Enter(Err * err)190 bool NonNestableBlock::Enter(Err* err) {
191 void* scope_value = scope_->GetProperty(&kKey, nullptr);
192 if (scope_value) {
193 // Existing block.
194 const NonNestableBlock* existing =
195 reinterpret_cast<const NonNestableBlock*>(scope_value);
196 *err = Err(function_, "Can't nest these things.",
197 std::string("You are trying to nest a ") + type_description_ +
198 " inside a " + existing->type_description_ + ".");
199 err->AppendSubErr(Err(existing->function_, "The enclosing block."));
200 return false;
201 }
202
203 scope_->SetProperty(&kKey, this);
204 key_added_ = true;
205 return true;
206 }
207
208 namespace functions {
209
210 // assert ----------------------------------------------------------------------
211
212 const char kAssert[] = "assert";
213 const char kAssert_HelpShort[] =
214 "assert: Assert an expression is true at generation time.";
215 const char kAssert_Help[] =
216 R"(assert: Assert an expression is true at generation time.
217
218 assert(<condition> [, <error string>])
219
220 If the condition is false, the build will fail with an error. If the
221 optional second argument is provided, that string will be printed
222 with the error message.
223
224 Examples
225
226 assert(is_win)
227 assert(defined(sources), "Sources must be defined");
228 )";
229
RunAssert(Scope * scope,const FunctionCallNode * function,const std::vector<Value> & args,Err * err)230 Value RunAssert(Scope* scope,
231 const FunctionCallNode* function,
232 const std::vector<Value>& args,
233 Err* err) {
234 // Check usage: Assert takes 1 or 2 arguments.
235 if (args.size() != 1 && args.size() != 2) {
236 *err = Err(function->function(), "Wrong number of arguments.",
237 "assert() takes one or two arguments, "
238 "were you expecting something else?");
239 return Value();
240 }
241
242 // Check usage: The first argument must be a boolean.
243 if (args[0].type() != Value::BOOLEAN) {
244 *err = Err(function->function(), "Assertion value not a bool.");
245 return Value();
246 }
247 bool assertion_passed = args[0].boolean_value();
248
249 // Check usage: The second argument, if present, must be a string.
250 if (args.size() == 2 && args[1].type() != Value::STRING) {
251 *err = Err(function->function(), "Assertion message is not a string.");
252 return Value();
253 }
254
255 // Assertion passed: there is nothing to do, so return an empty value.
256 if (assertion_passed) {
257 return Value();
258 }
259
260 // Assertion failed; try to make a useful message and report it.
261 if (args.size() == 2) {
262 *err =
263 Err(function->function(), "Assertion failed.", args[1].string_value());
264 } else {
265 *err = Err(function->function(), "Assertion failed.");
266 }
267 if (args[0].origin()) {
268 // If you do "assert(foo)" we'd ideally like to show you where foo was
269 // set, and in this case the origin of the args will tell us that.
270 // However, if you do "assert(foo && bar)" the source of the value will
271 // be the assert like, which isn't so helpful.
272 //
273 // So we try to see if the args are from the same line or not. This will
274 // break if you do "assert(\nfoo && bar)" and we may show the second line
275 // as the source, oh well. The way around this is to check to see if the
276 // origin node is inside our function call block.
277 Location origin_location = args[0].origin()->GetRange().begin();
278 if (origin_location.file() != function->function().location().file() ||
279 origin_location.line_number() !=
280 function->function().location().line_number()) {
281 err->AppendSubErr(
282 Err(args[0].origin()->GetRange(), "", "This is where it was set."));
283 }
284 }
285 return Value();
286 }
287
288 // config ----------------------------------------------------------------------
289
290 const char kConfig[] = "config";
291 const char kConfig_HelpShort[] = "config: Defines a configuration object.";
292 const char kConfig_Help[] =
293 R"(config: Defines a configuration object.
294
295 Configuration objects can be applied to targets and specify sets of compiler
296 flags, includes, defines, etc. They provide a way to conveniently group sets
297 of this configuration information.
298
299 A config is referenced by its label just like a target.
300
301 The values in a config are additive only. If you want to remove a flag you
302 need to remove the corresponding config that sets it. The final set of flags,
303 defines, etc. for a target is generated in this order:
304
305 1. The values specified directly on the target (rather than using a config.
306 2. The configs specified in the target's "configs" list, in order.
307 3. Public_configs from a breadth-first traversal of the dependency tree in
308 the order that the targets appear in "deps".
309 4. All dependent configs from a breadth-first traversal of the dependency
310 tree in the order that the targets appear in "deps".
311
312 More background
313
314 Configs solve a problem where the build system needs to have a higher-level
315 understanding of various compiler settings. For example, some compiler flags
316 have to appear in a certain order relative to each other, some settings like
317 defines and flags logically go together, and the build system needs to
318 de-duplicate flags even though raw command-line parameters can't always be
319 operated on in that way.
320
321 The config gives a name to a group of settings that can then be reasoned
322 about by GN. GN can know that configs with the same label are the same thing
323 so can be de-duplicated. It allows related settings to be grouped so they
324 are added or removed as a unit. And it allows targets to refer to settings
325 with conceptual names ("no_rtti", "enable_exceptions", etc.) rather than
326 having to hard-coding every compiler's flags each time they are referred to.
327
328 Variables valid in a config definition
329
330 )"
331
332 CONFIG_VALUES_VARS_HELP
333
334 R"( Nested configs: configs
335
336 Variables on a target used to apply configs
337
338 all_dependent_configs, configs, public_configs
339
340 Example
341
342 config("myconfig") {
343 include_dirs = [ "include/common" ]
344 defines = [ "ENABLE_DOOM_MELON" ]
345 }
346
347 executable("mything") {
348 configs = [ ":myconfig" ]
349 }
350 )";
351
RunConfig(const FunctionCallNode * function,const std::vector<Value> & args,Scope * scope,Err * err)352 Value RunConfig(const FunctionCallNode* function,
353 const std::vector<Value>& args,
354 Scope* scope,
355 Err* err) {
356 NonNestableBlock non_nestable(scope, function, "config");
357 if (!non_nestable.Enter(err))
358 return Value();
359
360 if (!EnsureSingleStringArg(function, args, err) ||
361 !EnsureNotProcessingImport(function, scope, err))
362 return Value();
363
364 Label label(MakeLabelForScope(scope, function, args[0].string_value()));
365
366 if (g_scheduler->verbose_logging())
367 g_scheduler->Log("Defining config", label.GetUserVisibleName(true));
368
369 // Create the new config.
370 std::unique_ptr<Config> config = std::make_unique<Config>(
371 scope->settings(), label, scope->build_dependency_files());
372 config->set_defined_from(function);
373 if (!Visibility::FillItemVisibility(config.get(), scope, err))
374 return Value();
375
376 // Fill the flags and such.
377 const SourceDir& input_dir = scope->GetSourceDir();
378 ConfigValuesGenerator gen(&config->own_values(), scope, input_dir, err);
379 gen.Run();
380 if (err->has_error())
381 return Value();
382
383 // Read sub-configs.
384 const Value* configs_value = scope->GetValue(variables::kConfigs, true);
385 if (configs_value) {
386 ExtractListOfUniqueLabels(scope->settings()->build_settings(),
387 *configs_value, scope->GetSourceDir(),
388 ToolchainLabelForScope(scope), &config->configs(),
389 err);
390 }
391 if (err->has_error())
392 return Value();
393
394 // Save the generated item.
395 Scope::ItemVector* collector = scope->GetItemCollector();
396 if (!collector) {
397 *err = Err(function, "Can't define a config in this context.");
398 return Value();
399 }
400 collector->push_back(std::move(config));
401
402 return Value();
403 }
404
405 // declare_args ----------------------------------------------------------------
406
407 const char kDeclareArgs[] = "declare_args";
408 const char kDeclareArgs_HelpShort[] = "declare_args: Declare build arguments.";
409 const char kDeclareArgs_Help[] =
410 R"(declare_args: Declare build arguments.
411
412 Introduces the given arguments into the current scope. If they are not
413 specified on the command line or in a toolchain's arguments, the default
414 values given in the declare_args block will be used. However, these defaults
415 will not override command-line values.
416
417 See also "gn help buildargs" for an overview.
418
419 The precise behavior of declare args is:
420
421 1. The declare_args() block executes. Any variable defined in the enclosing
422 scope is available for reading, but any variable defined earlier in
423 the current scope is not (since the overrides haven't been applied yet).
424
425 2. At the end of executing the block, any variables set within that scope
426 are saved, with the values specified in the block used as the "default value"
427 for that argument. Once saved, these variables are available for override
428 via args.gn.
429
430 3. User-defined overrides are applied. Anything set in "gn args" now
431 overrides any default values. The resulting set of variables is promoted
432 to be readable from the following code in the file.
433
434 This has some ramifications that may not be obvious:
435
436 - You should not perform difficult work inside a declare_args block since
437 this only sets a default value that may be discarded. In particular,
438 don't use the result of exec_script() to set the default value. If you
439 want to have a script-defined default, set some default "undefined" value
440 like [], "", or -1, and after the declare_args block, call exec_script if
441 the value is unset by the user.
442
443 - Because you cannot read the value of a variable defined in the same
444 block, if you need to make the default value of one arg depend
445 on the possibly-overridden value of another, write two separate
446 declare_args() blocks:
447
448 declare_args() {
449 enable_foo = true
450 }
451 declare_args() {
452 # Bar defaults to same user-overridden state as foo.
453 enable_bar = enable_foo
454 }
455
456 Example
457
458 declare_args() {
459 enable_teleporter = true
460 enable_doom_melon = false
461 }
462
463 If you want to override the (default disabled) Doom Melon:
464 gn --args="enable_doom_melon=true enable_teleporter=true"
465 This also sets the teleporter, but it's already defaulted to on so it will
466 have no effect.
467 )";
468
RunDeclareArgs(Scope * scope,const FunctionCallNode * function,const std::vector<Value> & args,BlockNode * block,Err * err)469 Value RunDeclareArgs(Scope* scope,
470 const FunctionCallNode* function,
471 const std::vector<Value>& args,
472 BlockNode* block,
473 Err* err) {
474 NonNestableBlock non_nestable(scope, function, "declare_args");
475 if (!non_nestable.Enter(err))
476 return Value();
477
478 Scope block_scope(scope);
479 block_scope.SetProperty(&kInDeclareArgsKey, &block_scope);
480 block->Execute(&block_scope, err);
481 if (err->has_error())
482 return Value();
483
484 // Pass the values from our scope into the Args object for adding to the
485 // scope with the proper values (taking into account the defaults given in
486 // the block_scope, and arguments passed into the build).
487 Scope::KeyValueMap values;
488 block_scope.GetCurrentScopeValues(&values);
489 scope->settings()->build_settings()->build_args().DeclareArgs(values, scope,
490 err);
491 return Value();
492 }
493
494 // defined ---------------------------------------------------------------------
495
496 const char kDefined[] = "defined";
497 const char kDefined_HelpShort[] =
498 "defined: Returns whether an identifier is defined.";
499 const char kDefined_Help[] =
500 R"(defined: Returns whether an identifier is defined.
501
502 Returns true if the given argument is defined. This is most useful in
503 templates to assert that the caller set things up properly.
504
505 You can pass an identifier:
506 defined(foo)
507 which will return true or false depending on whether foo is defined in the
508 current scope.
509
510 You can also check a named scope:
511 defined(foo.bar)
512 which will return true or false depending on whether bar is defined in the
513 named scope foo. It will throw an error if foo is not defined or is not a
514 scope.
515
516 Example
517
518 template("mytemplate") {
519 # To help users call this template properly...
520 assert(defined(invoker.sources), "Sources must be defined")
521
522 # If we want to accept an optional "values" argument, we don't
523 # want to dereference something that may not be defined.
524 if (defined(invoker.values)) {
525 values = invoker.values
526 } else {
527 values = "some default value"
528 }
529 }
530 )";
531
RunDefined(Scope * scope,const FunctionCallNode * function,const ListNode * args_list,Err * err)532 Value RunDefined(Scope* scope,
533 const FunctionCallNode* function,
534 const ListNode* args_list,
535 Err* err) {
536 const auto& args_vector = args_list->contents();
537 if (args_vector.size() != 1) {
538 *err = Err(function, "Wrong number of arguments to defined().",
539 "Expecting exactly one.");
540 return Value();
541 }
542
543 const IdentifierNode* identifier = args_vector[0]->AsIdentifier();
544 if (identifier) {
545 // Passed an identifier "defined(foo)".
546 if (scope->GetValue(identifier->value().value()))
547 return Value(function, true);
548 return Value(function, false);
549 }
550
551 const AccessorNode* accessor = args_vector[0]->AsAccessor();
552 if (accessor) {
553 // Passed an accessor "defined(foo.bar)".
554 if (accessor->member()) {
555 // The base of the accessor must be a scope if it's defined.
556 const Value* base = scope->GetValue(accessor->base().value());
557 if (!base) {
558 *err = Err(accessor, "Undefined identifier");
559 return Value();
560 }
561 if (!base->VerifyTypeIs(Value::SCOPE, err))
562 return Value();
563
564 // Check the member inside the scope to see if its defined.
565 if (base->scope_value()->GetValue(accessor->member()->value().value()))
566 return Value(function, true);
567 return Value(function, false);
568 }
569 }
570
571 // Argument is invalid.
572 *err = Err(function, "Bad thing passed to defined().",
573 "It should be of the form defined(foo) or defined(foo.bar).");
574 return Value();
575 }
576
577 // getenv ----------------------------------------------------------------------
578
579 const char kGetEnv[] = "getenv";
580 const char kGetEnv_HelpShort[] = "getenv: Get an environment variable.";
581 const char kGetEnv_Help[] =
582 R"(getenv: Get an environment variable.
583
584 value = getenv(env_var_name)
585
586 Returns the value of the given environment variable. If the value is not
587 found, it will try to look up the variable with the "opposite" case (based on
588 the case of the first letter of the variable), but is otherwise
589 case-sensitive.
590
591 If the environment variable is not found, the empty string will be returned.
592 Note: it might be nice to extend this if we had the concept of "none" in the
593 language to indicate lookup failure.
594
595 Example
596
597 home_dir = getenv("HOME")
598 )";
599
RunGetEnv(Scope * scope,const FunctionCallNode * function,const std::vector<Value> & args,Err * err)600 Value RunGetEnv(Scope* scope,
601 const FunctionCallNode* function,
602 const std::vector<Value>& args,
603 Err* err) {
604 if (!EnsureSingleStringArg(function, args, err))
605 return Value();
606
607 std::unique_ptr<base::Environment> env(base::Environment::Create());
608
609 std::string result;
610 if (!env->GetVar(args[0].string_value().c_str(), &result))
611 return Value(function, ""); // Not found, return empty string.
612 return Value(function, result);
613 }
614
615 // import ----------------------------------------------------------------------
616
617 const char kImport[] = "import";
618 const char kImport_HelpShort[] =
619 "import: Import a file into the current scope.";
620 const char kImport_Help[] =
621 R"(import: Import a file into the current scope.
622
623 The import command loads the rules and variables resulting from executing the
624 given file into the current scope.
625
626 By convention, imported files are named with a .gni extension.
627
628 An import is different than a C++ "include". The imported file is executed in
629 a standalone environment from the caller of the import command. The results
630 of this execution are cached for other files that import the same .gni file.
631
632 Note that you can not import a BUILD.gn file that's otherwise used in the
633 build. Files must either be imported or implicitly loaded as a result of deps
634 rules, but not both.
635
636 The imported file's scope will be merged with the scope at the point import
637 was called. If there is a conflict (both the current scope and the imported
638 file define some variable or rule with the same name but different value), a
639 runtime error will be thrown. Therefore, it's good practice to minimize the
640 stuff that an imported file defines.
641
642 Variables and templates beginning with an underscore '_' are considered
643 private and will not be imported. Imported files can use such variables for
644 internal computation without affecting other files.
645
646 Examples
647
648 import("//build/rules/idl_compilation_rule.gni")
649
650 # Looks in the current directory.
651 import("my_vars.gni")
652 )";
653
RunImport(Scope * scope,const FunctionCallNode * function,const std::vector<Value> & args,Err * err)654 Value RunImport(Scope* scope,
655 const FunctionCallNode* function,
656 const std::vector<Value>& args,
657 Err* err) {
658 if (!EnsureSingleStringArg(function, args, err))
659 return Value();
660
661 const SourceDir& input_dir = scope->GetSourceDir();
662 SourceFile import_file = input_dir.ResolveRelativeFile(
663 args[0], err, scope->settings()->build_settings()->root_path_utf8());
664 scope->AddBuildDependencyFile(import_file);
665 if (!err->has_error()) {
666 scope->settings()->import_manager().DoImport(import_file, function, scope,
667 err);
668 }
669 return Value();
670 }
671
672 // not_needed -----------------------------------------------------------------
673
674 const char kNotNeeded[] = "not_needed";
675 const char kNotNeeded_HelpShort[] =
676 "not_needed: Mark variables from scope as not needed.";
677 const char kNotNeeded_Help[] =
678 R"(not_needed: Mark variables from scope as not needed.
679
680 not_needed(variable_list_or_star, variable_to_ignore_list = [])
681 not_needed(from_scope, variable_list_or_star,
682 variable_to_ignore_list = [])
683
684 Mark the variables in the current or given scope as not needed, which means
685 you will not get an error about unused variables for these. The
686 variable_to_ignore_list allows excluding variables from "all matches" if
687 variable_list_or_star is "*".
688
689 Example
690
691 not_needed("*", [ "config" ])
692 not_needed([ "data_deps", "deps" ])
693 not_needed(invoker, "*", [ "config" ])
694 not_needed(invoker, [ "data_deps", "deps" ])
695 )";
696
697 Value RunNotNeeded(Scope* scope,
698 const FunctionCallNode* function,
699 const ListNode* args_list,
700 Err* err) {
701 const auto& args_vector = args_list->contents();
702 if (args_vector.size() < 1 || args_vector.size() > 3) {
703 *err = Err(function, "Wrong number of arguments.",
704 "Expecting one, two or three arguments.");
705 return Value();
706 }
707 auto args_cur = args_vector.begin();
708
709 Value* value = nullptr; // Value to use, may point to result_value.
710 Value result_value; // Storage for the "evaluate" case.
711 Value scope_value; // Storage for an evaluated scope.
712 const IdentifierNode* identifier = (*args_cur)->AsIdentifier();
713 if (identifier) {
714 // Optimize the common case where the input scope is an identifier. This
715 // prevents a copy of a potentially large Scope object.
716 value = scope->GetMutableValue(identifier->value().value(),
717 Scope::SEARCH_NESTED, true);
718 if (!value) {
719 *err = Err(identifier, "Undefined identifier.");
720 return Value();
721 }
722 } else {
723 // Non-optimized case, just evaluate the argument.
724 result_value = (*args_cur)->Execute(scope, err);
725 if (err->has_error())
726 return Value();
727 value = &result_value;
728 }
729 args_cur++;
730
731 // Extract the source scope if different from current one.
732 Scope* source = scope;
733 if (value->type() == Value::SCOPE) {
734 if (args_cur == args_vector.end()) {
735 *err = Err(
736 function, "Wrong number of arguments.",
737 "The first argument is a scope, expecting two or three arguments.");
738 return Value();
739 }
740 // Copy the scope value if it will be overridden.
741 if (value == &result_value) {
742 scope_value = Value(nullptr, value->scope_value()->MakeClosure());
743 source = scope_value.scope_value();
744 } else {
745 source = value->scope_value();
746 }
747 result_value = (*args_cur)->Execute(scope, err);
748 if (err->has_error())
749 return Value();
750 value = &result_value;
751 args_cur++;
752 } else if (args_vector.size() > 2) {
753 *err = Err(
754 function, "Wrong number of arguments.",
755 "The first argument is not a scope, expecting one or two arguments.");
756 return Value();
757 }
758
759 // Extract the exclusion list if defined.
760 Value exclusion_value;
761 std::set<std::string> exclusion_set;
762 if (args_cur != args_vector.end()) {
763 exclusion_value = (*args_cur)->Execute(source, err);
764 if (err->has_error())
765 return Value();
766
767 if (exclusion_value.type() != Value::LIST) {
768 *err = Err(exclusion_value, "Not a valid list of variables to exclude.",
769 "Expecting a list of strings.");
770 return Value();
771 }
772
773 for (const Value& cur : exclusion_value.list_value()) {
774 if (!cur.VerifyTypeIs(Value::STRING, err))
775 return Value();
776
777 exclusion_set.insert(cur.string_value());
778 }
779 }
780
781 if (value->type() == Value::STRING) {
782 if (value->string_value() == "*") {
783 source->MarkAllUsed(exclusion_set);
784 return Value();
785 }
786 } else if (value->type() == Value::LIST) {
787 if (exclusion_value.type() != Value::NONE) {
788 *err = Err(exclusion_value, "Not supported with a variable list.",
789 "Exclusion list can only be used with the string \"*\".");
790 return Value();
791 }
792 for (const Value& cur : value->list_value()) {
793 if (!cur.VerifyTypeIs(Value::STRING, err))
794 return Value();
795 // We don't need the return value, we invoke scope::GetValue only to mark
796 // the value as used. Note that we cannot use Scope::MarkUsed because we
797 // want to also search in the parent scope.
798 (void)source->GetValue(cur.string_value(), true);
799 }
800 return Value();
801 }
802
803 // Not the right type of argument.
804 *err = Err(*value, "Not a valid list of variables.",
805 "Expecting either the string \"*\" or a list of strings.");
806 return Value();
807 }
808
809 // set_sources_assignment_filter -----------------------------------------------
810
811 const char kSetSourcesAssignmentFilter[] = "set_sources_assignment_filter";
812 const char kSetSourcesAssignmentFilter_HelpShort[] =
813 "set_sources_assignment_filter: Set a pattern to filter source files.";
814 const char kSetSourcesAssignmentFilter_Help[] =
815 R"(set_sources_assignment_filter: Set a pattern to filter source files.
816
817 The sources assignment filter is a list of patterns that remove files from
818 the list implicitly whenever the "sources" variable is assigned to. This will
819 do nothing for non-lists.
820
821 This is intended to be used to globally filter out files with
822 platform-specific naming schemes when they don't apply, for example you may
823 want to filter out all "*_win.cc" files on non-Windows platforms.
824
825 Typically this will be called once in the master build config script to set
826 up the filter for the current platform. Subsequent calls will overwrite the
827 previous values.
828
829 If you want to bypass the filter and add a file even if it might be filtered
830 out, call set_sources_assignment_filter([]) to clear the list of filters.
831 This will apply until the current scope exits
832
833 How to use patterns
834
835 File patterns are VERY limited regular expressions. They must match the
836 entire input string to be counted as a match. In regular expression parlance,
837 there is an implicit "^...$" surrounding your input. If you want to match a
838 substring, you need to use wildcards at the beginning and end.
839
840 There are only two special tokens understood by the pattern matcher.
841 Everything else is a literal.
842
843 - "*" Matches zero or more of any character. It does not depend on the
844 preceding character (in regular expression parlance it is equivalent to
845 ".*").
846
847 - "\b" Matches a path boundary. This will match the beginning or end of a
848 string, or a slash.
849
850 Pattern examples
851
852 "*asdf*"
853 Matches a string containing "asdf" anywhere.
854
855 "asdf"
856 Matches only the exact string "asdf".
857
858 "*.cc"
859 Matches strings ending in the literal ".cc".
860
861 "\bwin/*"
862 Matches "win/foo" and "foo/win/bar.cc" but not "iwin/foo".
863
864 Sources assignment example
865
866 # Filter out all _win files.
867 set_sources_assignment_filter([ "*_win.cc", "*_win.h" ])
868 sources = [ "a.cc", "b_win.cc" ]
869 print(sources)
870 # Will print [ "a.cc" ]. b_win one was filtered out.
871 )";
872
RunSetSourcesAssignmentFilter(Scope * scope,const FunctionCallNode * function,const std::vector<Value> & args,Err * err)873 Value RunSetSourcesAssignmentFilter(Scope* scope,
874 const FunctionCallNode* function,
875 const std::vector<Value>& args,
876 Err* err) {
877 if (args.size() != 1) {
878 *err = Err(function, "set_sources_assignment_filter takes one argument.");
879 } else {
880 std::unique_ptr<PatternList> f = std::make_unique<PatternList>();
881 f->SetFromValue(args[0], err);
882 if (!err->has_error())
883 scope->set_sources_assignment_filter(std::move(f));
884 }
885 return Value();
886 }
887
888 // pool ------------------------------------------------------------------------
889
890 const char kPool[] = "pool";
891 const char kPool_HelpShort[] = "pool: Defines a pool object.";
892 const char kPool_Help[] =
893 R"*(pool: Defines a pool object.
894
895 Pool objects can be applied to a tool to limit the parallelism of the
896 build. This object has a single property "depth" corresponding to
897 the number of tasks that may run simultaneously.
898
899 As the file containing the pool definition may be executed in the
900 context of more than one toolchain it is recommended to specify an
901 explicit toolchain when defining and referencing a pool.
902
903 A pool named "console" defined in the root build file represents Ninja's
904 console pool. Targets using this pool will have access to the console's
905 stdin and stdout, and output will not be buffered. This special pool must
906 have a depth of 1. Pools not defined in the root must not be named "console".
907 The console pool can only be defined for the default toolchain.
908 Refer to the Ninja documentation on the console pool for more info.
909
910 A pool is referenced by its label just like a target.
911
912 Variables
913
914 depth*
915 * = required
916
917 Example
918
919 if (current_toolchain == default_toolchain) {
920 pool("link_pool") {
921 depth = 1
922 }
923 }
924
925 toolchain("toolchain") {
926 tool("link") {
927 command = "..."
928 pool = ":link_pool($default_toolchain)"
929 }
930 }
931 )*";
932
933 const char kDepth[] = "depth";
934
935 Value RunPool(const FunctionCallNode* function,
936 const std::vector<Value>& args,
937 Scope* scope,
938 Err* err) {
939 NonNestableBlock non_nestable(scope, function, "pool");
940 if (!non_nestable.Enter(err))
941 return Value();
942
943 if (!EnsureSingleStringArg(function, args, err) ||
944 !EnsureNotProcessingImport(function, scope, err))
945 return Value();
946
947 Label label(MakeLabelForScope(scope, function, args[0].string_value()));
948
949 if (g_scheduler->verbose_logging())
950 g_scheduler->Log("Defining pool", label.GetUserVisibleName(true));
951
952 // Get the pool depth. It is an error to define a pool without a depth,
953 // so check first for the presence of the value.
954 const Value* depth = scope->GetValue(kDepth, true);
955 if (!depth) {
956 *err = Err(function, "Can't define a pool without depth.");
957 return Value();
958 }
959
960 if (!depth->VerifyTypeIs(Value::INTEGER, err))
961 return Value();
962
963 if (depth->int_value() < 0) {
964 *err = Err(*depth, "depth must be positive or 0.");
965 return Value();
966 }
967
968 // Create the new pool.
969 std::unique_ptr<Pool> pool = std::make_unique<Pool>(
970 scope->settings(), label, scope->build_dependency_files());
971
972 if (label.name() == "console") {
973 const Settings* settings = scope->settings();
974 if (!settings->is_default()) {
975 *err = Err(
976 function,
977 "\"console\" pool must be defined only in the default toolchain.");
978 return Value();
979 }
980 if (label.dir() != settings->build_settings()->root_target_label().dir()) {
981 *err = Err(function, "\"console\" pool must be defined in the root //.");
982 return Value();
983 }
984 if (depth->int_value() != 1) {
985 *err = Err(*depth, "\"console\" pool must have depth 1.");
986 return Value();
987 }
988 }
989 pool->set_depth(depth->int_value());
990
991 // Save the generated item.
992 Scope::ItemVector* collector = scope->GetItemCollector();
993 if (!collector) {
994 *err = Err(function, "Can't define a pool in this context.");
995 return Value();
996 }
997 collector->push_back(std::move(pool));
998
999 return Value();
1000 }
1001
1002 // print -----------------------------------------------------------------------
1003
1004 const char kPrint[] = "print";
1005 const char kPrint_HelpShort[] = "print: Prints to the console.";
1006 const char kPrint_Help[] =
1007 R"(print: Prints to the console.
1008
1009 Prints all arguments to the console separated by spaces. A newline is
1010 automatically appended to the end.
1011
1012 This function is intended for debugging. Note that build files are run in
1013 parallel so you may get interleaved prints. A buildfile may also be executed
1014 more than once in parallel in the context of different toolchains so the
1015 prints from one file may be duplicated or
1016 interleaved with itself.
1017
1018 Examples
1019
1020 print("Hello world")
1021
1022 print(sources, deps)
1023 )";
1024
1025 Value RunPrint(Scope* scope,
1026 const FunctionCallNode* function,
1027 const std::vector<Value>& args,
1028 Err* err) {
1029 std::string output;
1030 for (size_t i = 0; i < args.size(); i++) {
1031 if (i != 0)
1032 output.push_back(' ');
1033 output.append(args[i].ToString(false));
1034 }
1035 output.push_back('\n');
1036
1037 const BuildSettings::PrintCallback& cb =
1038 scope->settings()->build_settings()->print_callback();
1039 if (cb) {
1040 cb(output);
1041 } else {
1042 printf("%s", output.c_str());
1043 fflush(stdout);
1044 }
1045
1046 return Value();
1047 }
1048
1049 // split_list ------------------------------------------------------------------
1050
1051 const char kSplitList[] = "split_list";
1052 const char kSplitList_HelpShort[] =
1053 "split_list: Splits a list into N different sub-lists.";
1054 const char kSplitList_Help[] =
1055 R"(split_list: Splits a list into N different sub-lists.
1056
1057 result = split_list(input, n)
1058
1059 Given a list and a number N, splits the list into N sub-lists of
1060 approximately equal size. The return value is a list of the sub-lists. The
1061 result will always be a list of size N. If N is greater than the number of
1062 elements in the input, it will be padded with empty lists.
1063
1064 The expected use is to divide source files into smaller uniform chunks.
1065
1066 Example
1067
1068 The code:
1069 mylist = [1, 2, 3, 4, 5, 6]
1070 print(split_list(mylist, 3))
1071
1072 Will print:
1073 [[1, 2], [3, 4], [5, 6]
1074 )";
1075 Value RunSplitList(Scope* scope,
1076 const FunctionCallNode* function,
1077 const ListNode* args_list,
1078 Err* err) {
1079 const auto& args_vector = args_list->contents();
1080 if (args_vector.size() != 2) {
1081 *err = Err(function, "Wrong number of arguments to split_list().",
1082 "Expecting exactly two.");
1083 return Value();
1084 }
1085
1086 ParseNodeValueAdapter list_adapter;
1087 if (!list_adapter.InitForType(scope, args_vector[0].get(), Value::LIST, err))
1088 return Value();
1089 const std::vector<Value>& input = list_adapter.get().list_value();
1090
1091 ParseNodeValueAdapter count_adapter;
1092 if (!count_adapter.InitForType(scope, args_vector[1].get(), Value::INTEGER,
1093 err))
1094 return Value();
1095 int64_t count = count_adapter.get().int_value();
1096 if (count <= 0) {
1097 *err = Err(function, "Requested result size is not positive.");
1098 return Value();
1099 }
1100
1101 Value result(function, Value::LIST);
1102 result.list_value().resize(count);
1103
1104 // Every result list gets at least this many items in it.
1105 int64_t min_items_per_list = static_cast<int64_t>(input.size()) / count;
1106
1107 // This many result lists get an extra item which is the remainder from above.
1108 int64_t extra_items = static_cast<int64_t>(input.size()) % count;
1109
1110 // Allocate all lists that have a remainder assigned to them (max items).
1111 int64_t max_items_per_list = min_items_per_list + 1;
1112 auto last_item_end = input.begin();
1113 for (int64_t i = 0; i < extra_items; i++) {
1114 result.list_value()[i] = Value(function, Value::LIST);
1115
1116 auto begin_add = last_item_end;
1117 last_item_end += max_items_per_list;
1118 result.list_value()[i].list_value().assign(begin_add, last_item_end);
1119 }
1120
1121 // Allocate all smaller items that don't have a remainder.
1122 for (int64_t i = extra_items; i < count; i++) {
1123 result.list_value()[i] = Value(function, Value::LIST);
1124
1125 auto begin_add = last_item_end;
1126 last_item_end += min_items_per_list;
1127 result.list_value()[i].list_value().assign(begin_add, last_item_end);
1128 }
1129
1130 return result;
1131 }
1132
1133 // string_join -----------------------------------------------------------------
1134
1135 const char kStringJoin[] = "string_join";
1136 const char kStringJoin_HelpShort[] =
1137 "string_join: Concatenates a list of strings with a separator.";
1138 const char kStringJoin_Help[] =
1139 R"(string_join: Concatenates a list of strings with a separator.
1140
1141 result = string_join(separator, strings)
1142
1143 Concatenate a list of strings with intervening occurrences of separator.
1144
1145 Examples
1146
1147 string_join("", ["a", "b", "c"]) --> "abc"
1148 string_join("|", ["a", "b", "c"]) --> "a|b|c"
1149 string_join(", ", ["a", "b", "c"]) --> "a, b, c"
1150 string_join("s", ["", ""]) --> "s"
1151 )";
1152
1153 Value RunStringJoin(Scope* scope,
1154 const FunctionCallNode* function,
1155 const std::vector<Value>& args,
1156 Err* err) {
1157 // Check usage: Number of arguments.
1158 if (args.size() != 2) {
1159 *err = Err(function, "Wrong number of arguments to string_join().",
1160 "Expecting exactly two. usage: string_join(separator, strings)");
1161 return Value();
1162 }
1163
1164 // Check usage: separator is a string.
1165 if (!args[0].VerifyTypeIs(Value::STRING, err)) {
1166 *err = Err(function,
1167 "separator in string_join(separator, strings) is not "
1168 "a string",
1169 "Expecting separator argument to be a string.");
1170 return Value();
1171 }
1172 const std::string separator = args[0].string_value();
1173
1174 // Check usage: strings is a list.
1175 if (!args[1].VerifyTypeIs(Value::LIST, err)) {
1176 *err = Err(function,
1177 "strings in string_join(separator, strings) "
1178 "is not a list",
1179 "Expecting strings argument to be a list.");
1180 return Value();
1181 }
1182 const std::vector<Value> strings = args[1].list_value();
1183
1184 // Arguments looks good; do the join.
1185 std::stringstream stream;
1186 for (size_t i = 0; i < strings.size(); ++i) {
1187 if (!strings[i].VerifyTypeIs(Value::STRING, err)) {
1188 return Value();
1189 }
1190 if (i != 0) {
1191 stream << separator;
1192 }
1193 stream << strings[i].string_value();
1194 }
1195 return Value(function, stream.str());
1196 }
1197
1198 // string_replace --------------------------------------------------------------
1199
1200 const char kStringReplace[] = "string_replace";
1201 const char kStringReplace_HelpShort[] =
1202 "string_replace: Replaces substring in the given string.";
1203 const char kStringReplace_Help[] =
1204 R"(string_replace: Replaces substring in the given string.
1205
1206 result = string_replace(str, old, new[, max])
1207
1208 Returns a copy of the string str in which the occurrences of old have been
1209 replaced with new, optionally restricting the number of replacements. The
1210 replacement is performed sequentially, so if new contains old, it won't be
1211 replaced.
1212
1213 Example
1214
1215 The code:
1216 mystr = "Hello, world!"
1217 print(string_replace(mystr, "world", "GN"))
1218
1219 Will print:
1220 Hello, GN!
1221 )";
1222
1223 Value RunStringReplace(Scope* scope,
1224 const FunctionCallNode* function,
1225 const std::vector<Value>& args,
1226 Err* err) {
1227 if (args.size() < 3 || args.size() > 4) {
1228 *err = Err(function, "Wrong number of arguments to string_replace().");
1229 return Value();
1230 }
1231
1232 if (!args[0].VerifyTypeIs(Value::STRING, err))
1233 return Value();
1234 const std::string str = args[0].string_value();
1235
1236 if (!args[1].VerifyTypeIs(Value::STRING, err))
1237 return Value();
1238 const std::string& old = args[1].string_value();
1239
1240 if (!args[2].VerifyTypeIs(Value::STRING, err))
1241 return Value();
1242 const std::string& new_ = args[2].string_value();
1243
1244 int64_t max = INT64_MAX;
1245 if (args.size() > 3) {
1246 if (!args[3].VerifyTypeIs(Value::INTEGER, err))
1247 return Value();
1248 max = args[3].int_value();
1249 if (max <= 0) {
1250 *err = Err(function, "Requested number of replacements is not positive.");
1251 return Value();
1252 }
1253 }
1254
1255 int64_t n = 0;
1256 std::string val(str);
1257 size_t start_pos = 0;
1258 while ((start_pos = val.find(old, start_pos)) != std::string::npos) {
1259 val.replace(start_pos, old.length(), new_);
1260 start_pos += new_.length();
1261 if (++n >= max)
1262 break;
1263 }
1264 return Value(function, std::move(val));
1265 }
1266
1267 // string_split ----------------------------------------------------------------
1268
1269 const char kStringSplit[] = "string_split";
1270 const char kStringSplit_HelpShort[] =
1271 "string_split: Split string into a list of strings.";
1272 const char kStringSplit_Help[] =
1273 R"(string_split: Split string into a list of strings.
1274
1275 result = string_split(str[, sep])
1276
1277 Split string into all substrings separated by separator and returns a list
1278 of the substrings between those separators.
1279
1280 If the separator argument is omitted, the split is by any whitespace, and
1281 any leading/trailing whitespace is ignored; similar to Python's str.split().
1282
1283 Examples without a separator (split on whitespace):
1284
1285 string_split("") --> []
1286 string_split("a") --> ["a"]
1287 string_split(" aa bb") --> ["aa", "bb"]
1288
1289 Examples with a separator (split on separators):
1290
1291 string_split("", "|") --> [""]
1292 string_split(" a b ", " ") --> ["", "", "a", "b", "", ""]
1293 string_split("aa+-bb+-c", "+-") --> ["aa", "bb", "c"]
1294 )";
1295
1296 Value RunStringSplit(Scope* scope,
1297 const FunctionCallNode* function,
1298 const std::vector<Value>& args,
1299 Err* err) {
1300 // Check usage: argument count.
1301 if (args.size() != 1 && args.size() != 2) {
1302 *err = Err(function, "Wrong number of arguments to string_split().",
1303 "Usage: string_split(str[, sep])");
1304 return Value();
1305 }
1306
1307 // Check usage: str is a string.
1308 if (!args[0].VerifyTypeIs(Value::STRING, err)) {
1309 return Value();
1310 }
1311 const std::string str = args[0].string_value();
1312
1313 // Check usage: separator is a non-empty string.
1314 std::string separator;
1315 if (args.size() == 2) {
1316 if (!args[1].VerifyTypeIs(Value::STRING, err)) {
1317 return Value();
1318 }
1319 separator = args[1].string_value();
1320 if (separator.empty()) {
1321 *err = Err(function,
1322 "Separator argument to string_split() "
1323 "cannot be empty string",
1324 "Usage: string_split(str[, sep])");
1325 return Value();
1326 }
1327 }
1328
1329 // Split the string into a std::vector.
1330 std::vector<std::string> strings;
1331 if (!separator.empty()) {
1332 // Case: Explicit separator argument.
1333 // Note: split_string("", "x") --> [""] like Python.
1334 size_t pos = 0;
1335 size_t next_pos = 0;
1336 while ((next_pos = str.find(separator, pos)) != std::string::npos) {
1337 strings.push_back(str.substr(pos, next_pos - pos));
1338 pos = next_pos + separator.length();
1339 }
1340 strings.push_back(str.substr(pos, std::string::npos));
1341 } else {
1342 // Case: Split on any whitespace and strip ends.
1343 // Note: split_string("") --> [] like Python.
1344 std::string::const_iterator pos = str.cbegin();
1345 while (pos != str.end()) {
1346 // Advance past spaces. After this, pos is pointing to non-whitespace.
1347 pos = find_if(pos, str.end(), [](char x) { return !std::isspace(x); });
1348 if (pos == str.end()) {
1349 // Tail is all whitespace, so we're done.
1350 break;
1351 }
1352 // Advance past non-whitespace to get next chunk.
1353 std::string::const_iterator next_whitespace_position =
1354 find_if(pos, str.end(), [](char x) { return std::isspace(x); });
1355 strings.push_back(std::string(pos, next_whitespace_position));
1356 pos = next_whitespace_position;
1357 }
1358 }
1359
1360 // Convert vector of std::strings to list of GN strings.
1361 Value result(function, Value::LIST);
1362 result.list_value().resize(strings.size());
1363 for (size_t i = 0; i < strings.size(); ++i) {
1364 result.list_value()[i] = Value(function, strings[i]);
1365 }
1366 return result;
1367 }
1368
1369 // -----------------------------------------------------------------------------
1370
1371 FunctionInfo::FunctionInfo()
1372 : self_evaluating_args_runner(nullptr),
1373 generic_block_runner(nullptr),
1374 executed_block_runner(nullptr),
1375 no_block_runner(nullptr),
1376 help_short(nullptr),
1377 help(nullptr),
1378 is_target(false) {}
1379
1380 FunctionInfo::FunctionInfo(SelfEvaluatingArgsFunction seaf,
1381 const char* in_help_short,
1382 const char* in_help,
1383 bool in_is_target)
1384 : self_evaluating_args_runner(seaf),
1385 generic_block_runner(nullptr),
1386 executed_block_runner(nullptr),
1387 no_block_runner(nullptr),
1388 help_short(in_help_short),
1389 help(in_help),
1390 is_target(in_is_target) {}
1391
1392 FunctionInfo::FunctionInfo(GenericBlockFunction gbf,
1393 const char* in_help_short,
1394 const char* in_help,
1395 bool in_is_target)
1396 : self_evaluating_args_runner(nullptr),
1397 generic_block_runner(gbf),
1398 executed_block_runner(nullptr),
1399 no_block_runner(nullptr),
1400 help_short(in_help_short),
1401 help(in_help),
1402 is_target(in_is_target) {}
1403
1404 FunctionInfo::FunctionInfo(ExecutedBlockFunction ebf,
1405 const char* in_help_short,
1406 const char* in_help,
1407 bool in_is_target)
1408 : self_evaluating_args_runner(nullptr),
1409 generic_block_runner(nullptr),
1410 executed_block_runner(ebf),
1411 no_block_runner(nullptr),
1412 help_short(in_help_short),
1413 help(in_help),
1414 is_target(in_is_target) {}
1415
1416 FunctionInfo::FunctionInfo(NoBlockFunction nbf,
1417 const char* in_help_short,
1418 const char* in_help,
1419 bool in_is_target)
1420 : self_evaluating_args_runner(nullptr),
1421 generic_block_runner(nullptr),
1422 executed_block_runner(nullptr),
1423 no_block_runner(nbf),
1424 help_short(in_help_short),
1425 help(in_help),
1426 is_target(in_is_target) {}
1427
1428 // Setup the function map via a static initializer. We use this because it
1429 // avoids race conditions without having to do some global setup function or
1430 // locking-heavy singleton checks at runtime. In practice, we always need this
1431 // before we can do anything interesting, so it's OK to wait for the
1432 // initializer.
1433 struct FunctionInfoInitializer {
1434 FunctionInfoMap map;
1435
1436 FunctionInfoInitializer() {
1437 #define INSERT_FUNCTION(command, is_target) \
1438 map[k##command] = FunctionInfo(&Run##command, k##command##_HelpShort, \
1439 k##command##_Help, is_target);
1440
1441 INSERT_FUNCTION(Action, true)
1442 INSERT_FUNCTION(ActionForEach, true)
1443 INSERT_FUNCTION(BundleData, true)
1444 INSERT_FUNCTION(CreateBundle, true)
1445 INSERT_FUNCTION(Copy, true)
1446 INSERT_FUNCTION(Executable, true)
1447 INSERT_FUNCTION(Group, true)
1448 INSERT_FUNCTION(LoadableModule, true)
1449 INSERT_FUNCTION(SharedLibrary, true)
1450 INSERT_FUNCTION(SourceSet, true)
1451 INSERT_FUNCTION(StaticLibrary, true)
1452 INSERT_FUNCTION(Target, true)
1453 INSERT_FUNCTION(GeneratedFile, true)
1454 INSERT_FUNCTION(RustLibrary, true)
1455 INSERT_FUNCTION(RustProcMacro, true)
1456
1457 INSERT_FUNCTION(Assert, false)
1458 INSERT_FUNCTION(Config, false)
1459 INSERT_FUNCTION(DeclareArgs, false)
1460 INSERT_FUNCTION(Defined, false)
1461 INSERT_FUNCTION(ExecScript, false)
1462 INSERT_FUNCTION(ForEach, false)
1463 INSERT_FUNCTION(ForwardVariablesFrom, false)
1464 INSERT_FUNCTION(GetEnv, false)
1465 INSERT_FUNCTION(GetLabelInfo, false)
1466 INSERT_FUNCTION(GetPathInfo, false)
1467 INSERT_FUNCTION(GetTargetOutputs, false)
1468 INSERT_FUNCTION(Import, false)
1469 INSERT_FUNCTION(NotNeeded, false)
1470 INSERT_FUNCTION(Pool, false)
1471 INSERT_FUNCTION(Print, false)
1472 INSERT_FUNCTION(ProcessFileTemplate, false)
1473 INSERT_FUNCTION(ReadFile, false)
1474 INSERT_FUNCTION(RebasePath, false)
1475 INSERT_FUNCTION(SetDefaults, false)
1476 INSERT_FUNCTION(SetDefaultToolchain, false)
1477 INSERT_FUNCTION(SetSourcesAssignmentFilter, false)
1478 INSERT_FUNCTION(SplitList, false)
1479 INSERT_FUNCTION(StringJoin, false)
1480 INSERT_FUNCTION(StringReplace, false)
1481 INSERT_FUNCTION(StringSplit, false)
1482 INSERT_FUNCTION(Template, false)
1483 INSERT_FUNCTION(Tool, false)
1484 INSERT_FUNCTION(Toolchain, false)
1485 INSERT_FUNCTION(WriteFile, false)
1486
1487 #undef INSERT_FUNCTION
1488 }
1489 };
1490 const FunctionInfoInitializer function_info;
1491
1492 const FunctionInfoMap& GetFunctions() {
1493 return function_info.map;
1494 }
1495
1496 Value RunFunction(Scope* scope,
1497 const FunctionCallNode* function,
1498 const ListNode* args_list,
1499 BlockNode* block,
1500 Err* err) {
1501 const Token& name = function->function();
1502
1503 std::string template_name(function->function().value());
1504 const Template* templ = scope->GetTemplate(template_name);
1505 if (templ) {
1506 Value args = args_list->Execute(scope, err);
1507 if (err->has_error())
1508 return Value();
1509 return templ->Invoke(scope, function, template_name, args.list_value(),
1510 block, err);
1511 }
1512
1513 // No template matching this, check for a built-in function.
1514 const FunctionInfoMap& function_map = GetFunctions();
1515 FunctionInfoMap::const_iterator found_function =
1516 function_map.find(name.value());
1517 if (found_function == function_map.end()) {
1518 *err = Err(name, "Unknown function.");
1519 return Value();
1520 }
1521
1522 if (found_function->second.self_evaluating_args_runner) {
1523 // Self evaluating args functions are special weird built-ins like foreach.
1524 // Rather than force them all to check that they have a block or no block
1525 // and risk bugs for new additions, check a whitelist here.
1526 if (found_function->second.self_evaluating_args_runner != &RunForEach) {
1527 if (!VerifyNoBlockForFunctionCall(function, block, err))
1528 return Value();
1529 }
1530 return found_function->second.self_evaluating_args_runner(scope, function,
1531 args_list, err);
1532 }
1533
1534 // All other function types take a pre-executed set of args.
1535 Value args = args_list->Execute(scope, err);
1536 if (err->has_error())
1537 return Value();
1538
1539 if (found_function->second.generic_block_runner) {
1540 if (!block) {
1541 FillNeedsBlockError(function, err);
1542 return Value();
1543 }
1544 return found_function->second.generic_block_runner(
1545 scope, function, args.list_value(), block, err);
1546 }
1547
1548 if (found_function->second.executed_block_runner) {
1549 if (!block) {
1550 FillNeedsBlockError(function, err);
1551 return Value();
1552 }
1553
1554 Scope block_scope(scope);
1555 block->Execute(&block_scope, err);
1556 if (err->has_error())
1557 return Value();
1558
1559 Value result = found_function->second.executed_block_runner(
1560 function, args.list_value(), &block_scope, err);
1561 if (err->has_error())
1562 return Value();
1563
1564 if (!block_scope.CheckForUnusedVars(err))
1565 return Value();
1566 return result;
1567 }
1568
1569 // Otherwise it's a no-block function.
1570 if (!VerifyNoBlockForFunctionCall(function, block, err))
1571 return Value();
1572 return found_function->second.no_block_runner(scope, function,
1573 args.list_value(), err);
1574 }
1575
1576 } // namespace functions
1577