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