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