Revert of Revert of Add a WorkerScheduler and a WebThreadImplForWorker (patchset...
[chromium-blink-merge.git] / tools / gn / command_refs.cc
blob832f53a7f29a957f11d0b6b121f308ef0b7578c8
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.
5 #include <map>
6 #include <set>
8 #include "base/command_line.h"
9 #include "tools/gn/commands.h"
10 #include "tools/gn/deps_iterator.h"
11 #include "tools/gn/filesystem_utils.h"
12 #include "tools/gn/input_file.h"
13 #include "tools/gn/item.h"
14 #include "tools/gn/setup.h"
15 #include "tools/gn/standard_out.h"
16 #include "tools/gn/target.h"
18 namespace commands {
20 namespace {
22 typedef std::set<const Target*> TargetSet;
23 typedef std::vector<const Target*> TargetVector;
25 // Maps targets to the list of targets that depend on them.
26 typedef std::multimap<const Target*, const Target*> DepMap;
28 // Populates the reverse dependency map for the targets in the Setup.
29 void FillDepMap(Setup* setup, DepMap* dep_map) {
30 for (const auto& target : setup->builder()->GetAllResolvedTargets()) {
31 for (const auto& dep_pair : target->GetDeps(Target::DEPS_ALL))
32 dep_map->insert(std::make_pair(dep_pair.ptr, target));
36 // Forward declaration for function below.
37 size_t RecursivePrintTargetDeps(const DepMap& dep_map,
38 const Target* target,
39 TargetSet* seen_targets,
40 int indent_level);
42 // Prints the target and its dependencies in tree form. If the set is non-null,
43 // new targets encountered will be added to the set, and if a ref is in the set
44 // already, it will not be recused into. When the set is null, all refs will be
45 // printed.
47 // Returns the number of items printed.
48 size_t RecursivePrintTarget(const DepMap& dep_map,
49 const Target* target,
50 TargetSet* seen_targets,
51 int indent_level) {
52 std::string indent(indent_level * 2, ' ');
53 size_t count = 1;
55 // Only print the toolchain for non-default-toolchain targets.
56 OutputString(indent + target->label().GetUserVisibleName(
57 !target->settings()->is_default()));
59 bool print_children = true;
60 if (seen_targets) {
61 if (seen_targets->find(target) == seen_targets->end()) {
62 // New target, mark it visited.
63 seen_targets->insert(target);
64 } else {
65 // Already seen.
66 print_children = false;
67 // Only print "..." if something is actually elided, which means that
68 // the current target has children.
69 if (dep_map.lower_bound(target) != dep_map.upper_bound(target))
70 OutputString("...");
74 OutputString("\n");
75 if (print_children) {
76 count += RecursivePrintTargetDeps(dep_map, target, seen_targets,
77 indent_level + 1);
79 return count;
82 // Prints refs of the given target (not the target itself). See
83 // RecursivePrintTarget.
84 size_t RecursivePrintTargetDeps(const DepMap& dep_map,
85 const Target* target,
86 TargetSet* seen_targets,
87 int indent_level) {
88 DepMap::const_iterator dep_begin = dep_map.lower_bound(target);
89 DepMap::const_iterator dep_end = dep_map.upper_bound(target);
90 size_t count = 0;
91 for (DepMap::const_iterator cur_dep = dep_begin;
92 cur_dep != dep_end; cur_dep++) {
93 count += RecursivePrintTarget(dep_map, cur_dep->second, seen_targets,
94 indent_level);
96 return count;
99 void RecursiveCollectChildRefs(const DepMap& dep_map,
100 const Target* target,
101 TargetSet* results);
103 // Recursively finds all targets that reference the given one, and additionally
104 // adds the current one to the list.
105 void RecursiveCollectRefs(const DepMap& dep_map,
106 const Target* target,
107 TargetSet* results) {
108 if (results->find(target) != results->end())
109 return; // Already found this target.
110 results->insert(target);
111 RecursiveCollectChildRefs(dep_map, target, results);
114 // Recursively finds all targets that reference the given one.
115 void RecursiveCollectChildRefs(const DepMap& dep_map,
116 const Target* target,
117 TargetSet* results) {
118 DepMap::const_iterator dep_begin = dep_map.lower_bound(target);
119 DepMap::const_iterator dep_end = dep_map.upper_bound(target);
120 for (DepMap::const_iterator cur_dep = dep_begin;
121 cur_dep != dep_end; cur_dep++)
122 RecursiveCollectRefs(dep_map, cur_dep->second, results);
125 bool TargetContainsFile(const Target* target, const SourceFile& file) {
126 for (const auto& cur_file : target->sources()) {
127 if (cur_file == file)
128 return true;
130 for (const auto& cur_file : target->public_headers()) {
131 if (cur_file == file)
132 return true;
134 for (const auto& cur_file : target->inputs()) {
135 if (cur_file == file)
136 return true;
138 for (const auto& cur_file : target->data()) {
139 if (cur_file == file)
140 return true;
142 return false;
145 void GetTargetsContainingFile(Setup* setup,
146 const std::vector<const Target*>& all_targets,
147 const SourceFile& file,
148 bool all_toolchains,
149 UniqueVector<const Target*>* matches) {
150 Label default_toolchain = setup->loader()->default_toolchain_label();
151 for (const auto& target : all_targets) {
152 if (!all_toolchains) {
153 // Only check targets in the default toolchain.
154 if (target->label().GetToolchainLabel() != default_toolchain)
155 continue;
157 if (TargetContainsFile(target, file))
158 matches->push_back(target);
162 bool TargetReferencesConfig(const Target* target, const Config* config) {
163 for (const LabelConfigPair& cur : target->configs()) {
164 if (cur.ptr == config)
165 return true;
167 for (const LabelConfigPair& cur : target->public_configs()) {
168 if (cur.ptr == config)
169 return true;
171 return false;
174 void GetTargetsReferencingConfig(Setup* setup,
175 const std::vector<const Target*>& all_targets,
176 const Config* config,
177 bool all_toolchains,
178 UniqueVector<const Target*>* matches) {
179 Label default_toolchain = setup->loader()->default_toolchain_label();
180 for (const auto& target : all_targets) {
181 if (!all_toolchains) {
182 // Only check targets in the default toolchain.
183 if (target->label().GetToolchainLabel() != default_toolchain)
184 continue;
186 if (TargetReferencesConfig(target, config))
187 matches->push_back(target);
191 // Returns the number of matches printed.
192 size_t DoTreeOutput(const DepMap& dep_map,
193 const UniqueVector<const Target*>& implicit_target_matches,
194 const UniqueVector<const Target*>& explicit_target_matches,
195 bool all) {
196 TargetSet seen_targets;
197 size_t count = 0;
199 // Implicit targets don't get printed themselves.
200 for (const Target* target : implicit_target_matches) {
201 if (all)
202 count += RecursivePrintTargetDeps(dep_map, target, nullptr, 0);
203 else
204 count += RecursivePrintTargetDeps(dep_map, target, &seen_targets, 0);
207 // Explicit targets appear in the output.
208 for (const Target* target : implicit_target_matches) {
209 if (all)
210 count += RecursivePrintTarget(dep_map, target, nullptr, 0);
211 else
212 count += RecursivePrintTarget(dep_map, target, &seen_targets, 0);
215 return count;
218 // Returns the number of matches printed.
219 size_t DoAllListOutput(
220 const DepMap& dep_map,
221 const UniqueVector<const Target*>& implicit_target_matches,
222 const UniqueVector<const Target*>& explicit_target_matches) {
223 // Output recursive dependencies, uniquified and flattened.
224 TargetSet results;
226 for (const Target* target : implicit_target_matches)
227 RecursiveCollectChildRefs(dep_map, target, &results);
228 for (const Target* target : explicit_target_matches) {
229 // Explicit targets also get added to the output themselves.
230 results.insert(target);
231 RecursiveCollectChildRefs(dep_map, target, &results);
234 FilterAndPrintTargetSet(false, results);
235 return results.size();
238 // Returns the number of matches printed.
239 size_t DoDirectListOutput(
240 const DepMap& dep_map,
241 const UniqueVector<const Target*>& implicit_target_matches,
242 const UniqueVector<const Target*>& explicit_target_matches) {
243 TargetSet results;
245 // Output everything that refers to the implicit ones.
246 for (const Target* target : implicit_target_matches) {
247 DepMap::const_iterator dep_begin = dep_map.lower_bound(target);
248 DepMap::const_iterator dep_end = dep_map.upper_bound(target);
249 for (DepMap::const_iterator cur_dep = dep_begin;
250 cur_dep != dep_end; cur_dep++)
251 results.insert(cur_dep->second);
254 // And just output the explicit ones directly (these are the target matches
255 // when referring to what references a file or config).
256 for (const Target* target : explicit_target_matches)
257 results.insert(target);
259 FilterAndPrintTargetSet(false, results);
260 return results.size();
263 } // namespace
265 const char kRefs[] = "refs";
266 const char kRefs_HelpShort[] =
267 "refs: Find stuff referencing a target or file.";
268 const char kRefs_Help[] =
269 "gn refs <out_dir> (<label_pattern>|<label>|<file>)* [--all]\n"
270 " [--all-toolchains] [--as=...] [--testonly=...] [--type=...]\n"
271 "\n"
272 " Finds reverse dependencies (which targets reference something). The\n"
273 " input is a list containing:\n"
274 "\n"
275 " - Target label: The result will be which targets depend on it.\n"
276 "\n"
277 " - Config label: The result will be which targets list the given\n"
278 " config in its \"configs\" or \"public_configs\" list.\n"
279 "\n"
280 " - Label pattern: The result will be which targets depend on any\n"
281 " target matching the given pattern. Patterns will not match\n"
282 " configs. These are not general regular expressions, see\n"
283 " \"gn help label_pattern\" for details.\n"
284 "\n"
285 " - File name: The result will be which targets list the given file in\n"
286 " its \"inputs\", \"sources\", \"public\", or \"data\". Any input\n"
287 " that does not contain wildcards and does not match a target or a\n"
288 " config will be treated as a file.\n"
289 "\n"
290 "Options\n"
291 "\n"
292 " --all\n"
293 " When used without --tree, will recurse and display all unique\n"
294 " dependencies of the given targets. For example, if the input is\n"
295 " a target, this will output all targets that depend directly or\n"
296 " indirectly on the input. If the input is a file, this will output\n"
297 " all targets that depend directly or indirectly on that file.\n"
298 "\n"
299 " When used with --tree, turns off eliding to show a complete tree.\n"
300 "\n"
301 " --all-toolchains\n"
302 " Normally only inputs in the default toolchain will be included.\n"
303 " This switch will turn on matching all toolchains.\n"
304 "\n"
305 " For example, a file is in a target might be compiled twice:\n"
306 " once in the default toolchain and once in a secondary one. Without\n"
307 " this flag, only the default toolchain one will be matched and\n"
308 " printed (potentially with its recursive dependencies, depending on\n"
309 " the other options). With this flag, both will be printed\n"
310 " (potentially with both of their recursive dependencies).\n"
311 "\n"
312 TARGET_PRINTING_MODE_COMMAND_LINE_HELP
313 "\n"
314 " -q\n"
315 " Quiet. If nothing matches, don't print any output. Without this\n"
316 " option, if there are no matches there will be an informational\n"
317 " message printed which might interfere with scripts processing the\n"
318 " output.\n"
319 "\n"
320 TARGET_TESTONLY_FILTER_COMMAND_LINE_HELP
321 "\n"
322 " --tree\n"
323 " Outputs a reverse dependency tree from the given target.\n"
324 " Duplicates will be elided. Combine with --all to see a full\n"
325 " dependency tree.\n"
326 "\n"
327 " Tree output can not be used with the filtering or output flags:\n"
328 " --as, --type, --testonly.\n"
329 "\n"
330 TARGET_TYPE_FILTER_COMMAND_LINE_HELP
331 "\n"
332 "Examples (target input)\n"
333 "\n"
334 " gn refs out/Debug //tools/gn:gn\n"
335 " Find all targets depending on the given exact target name.\n"
336 "\n"
337 " gn refs out/Debug //base:i18n --as=buildfiles | xargs gvim\n"
338 " Edit all .gn files containing references to //base:i18n\n"
339 "\n"
340 " gn refs out/Debug //base --all\n"
341 " List all targets depending directly or indirectly on //base:base.\n"
342 "\n"
343 " gn refs out/Debug \"//base/*\"\n"
344 " List all targets depending directly on any target in //base or\n"
345 " its subdirectories.\n"
346 "\n"
347 " gn refs out/Debug \"//base:*\"\n"
348 " List all targets depending directly on any target in\n"
349 " //base/BUILD.gn.\n"
350 "\n"
351 " gn refs out/Debug //base --tree\n"
352 " Print a reverse dependency tree of //base:base\n"
353 "\n"
354 "Examples (file input)\n"
355 "\n"
356 " gn refs out/Debug //base/macros.h\n"
357 " Print target(s) listing //base/macros.h as a source.\n"
358 "\n"
359 " gn refs out/Debug //base/macros.h --tree\n"
360 " Display a reverse dependency tree to get to the given file. This\n"
361 " will show how dependencies will reference that file.\n"
362 "\n"
363 " gn refs out/Debug //base/macros.h //base/basictypes.h --all\n"
364 " Display all unique targets with some dependency path to a target\n"
365 " containing either of the given files as a source.\n"
366 "\n"
367 " gn refs out/Debug //base/macros.h --testonly=true --type=executable\n"
368 " --all --as=output\n"
369 " Display the executable file names of all test executables\n"
370 " potentially affected by a change to the given file.\n";
372 int RunRefs(const std::vector<std::string>& args) {
373 if (args.size() <= 1) {
374 Err(Location(), "You're holding it wrong.",
375 "Usage: \"gn refs <out_dir> (<label_pattern>|<file>)*\"")
376 .PrintToStdout();
377 return 1;
380 const base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
381 bool tree = cmdline->HasSwitch("tree");
382 bool all = cmdline->HasSwitch("all");
383 bool all_toolchains = cmdline->HasSwitch("all-toolchains");
385 Setup* setup = new Setup;
386 setup->set_check_for_bad_items(false);
387 if (!setup->DoSetup(args[0], false) || !setup->Run())
388 return 1;
390 // The inputs are everything but the first arg (which is the build dir).
391 std::vector<std::string> inputs(args.begin() + 1, args.end());
393 // Get the matches for the command-line input.
394 UniqueVector<const Target*> target_matches;
395 UniqueVector<const Config*> config_matches;
396 UniqueVector<const Toolchain*> toolchain_matches;
397 UniqueVector<SourceFile> file_matches;
398 if (!ResolveFromCommandLineInput(setup, inputs, all_toolchains,
399 &target_matches, &config_matches,
400 &toolchain_matches, &file_matches))
401 return 1;
403 // When you give a file or config as an input, you want the targets that are
404 // associated with it. We don't want to just append this to the
405 // target_matches, however, since these targets should actually be listed in
406 // the output, while for normal targets you don't want to see the inputs,
407 // only what refers to them.
408 std::vector<const Target*> all_targets =
409 setup->builder()->GetAllResolvedTargets();
410 UniqueVector<const Target*> explicit_target_matches;
411 for (const auto& file : file_matches) {
412 GetTargetsContainingFile(setup, all_targets, file, all_toolchains,
413 &explicit_target_matches);
415 for (const auto& config : config_matches) {
416 GetTargetsReferencingConfig(setup, all_targets, config, all_toolchains,
417 &explicit_target_matches);
420 // Tell the user if their input matches no files or labels. We need to check
421 // both that it matched no targets and no configs. File input will already
422 // have been converted to targets at this point. Configs will have been
423 // converted to targets also, but there could be no targets referencing the
424 // config, which is different than no config with that name.
425 bool quiet = cmdline->HasSwitch("q");
426 if (!quiet && config_matches.empty() &&
427 explicit_target_matches.empty() && target_matches.empty()) {
428 OutputString("The input matches no targets, configs, or files.\n",
429 DECORATION_YELLOW);
430 return 1;
433 // Construct the reverse dependency tree.
434 DepMap dep_map;
435 FillDepMap(setup, &dep_map);
437 size_t cnt = 0;
438 if (tree)
439 cnt = DoTreeOutput(dep_map, target_matches, explicit_target_matches, all);
440 else if (all)
441 cnt = DoAllListOutput(dep_map, target_matches, explicit_target_matches);
442 else
443 cnt = DoDirectListOutput(dep_map, target_matches, explicit_target_matches);
445 // If you ask for the references of a valid target, but that target has
446 // nothing referencing it, we'll get here without having printed anything.
447 if (!quiet && cnt == 0)
448 OutputString("Nothing references this.\n", DECORATION_YELLOW);
450 return 0;
453 } // namespace commands