Factor out helpers for generated_file() variables

No behavior change. Removes duplicated code in preparation for adding
more generated_file() variables:
- MetadataWalker::ResolveDepLabel() resolves a label found in metadata to
  a dependency of the target that declares it. It replaces the two
  copies of the lookup (deps and validations) used for walk_keys.
- GeneratedFileTargetGenerator::FillKeys() reads a list of strings, and
  is used by data_keys and walk_keys.
- TargetDescBuilder::RenderLabels() renders a sorted list of labels, and
  is used by gen_deps and validations.

Bug: 579603584
Change-Id: I290f73af4abc37d9436c4307f4afa44d5f3e1e99
Agent-Generated: true
Reviewed-on: https://gn-review.googlesource.com/c/gn/+/28720
Commit-Queue: Andrew Grieve <agrieve@google.com>
Reviewed-by: David Turner <digit@google.com>
diff --git a/src/gn/desc_builder.cc b/src/gn/desc_builder.cc
index 4a4eebf..1627ef6 100644
--- a/src/gn/desc_builder.cc
+++ b/src/gn/desc_builder.cc
@@ -759,33 +759,23 @@
     return res;
   }
 
-  ValuePtr RenderGenDeps() {
+  ValuePtr RenderGenDeps() { return RenderLabels(target_->gen_deps()); }
+
+  // Returns the sorted list of labels in |pairs|.
+  ValuePtr RenderLabels(const LabelTargetVector& pairs) {
     auto res = std::make_unique<base::ListValue>();
     Label default_tc = target_->settings()->default_toolchain_label();
-    const auto& gen_deps_pairs = target_->gen_deps();
-    std::vector<std::string> gen_deps;
-    gen_deps.reserve(gen_deps_pairs.size());
-    for (const auto& pair : gen_deps_pairs)
-      gen_deps.push_back(pair.label.GetUserVisibleName(default_tc));
-    std::sort(gen_deps.begin(), gen_deps.end());
-    for (const auto& dep : gen_deps)
-      res->AppendString(dep);
+    std::vector<std::string> labels;
+    labels.reserve(pairs.size());
+    for (const auto& pair : pairs)
+      labels.push_back(pair.label.GetUserVisibleName(default_tc));
+    std::sort(labels.begin(), labels.end());
+    for (const auto& label : labels)
+      res->AppendString(label);
     return res;
   }
 
-  ValuePtr RenderValidations() {
-    auto res = std::make_unique<base::ListValue>();
-    Label default_tc = target_->settings()->default_toolchain_label();
-    const auto& validation_pairs = target_->validations();
-    std::vector<std::string> validations;
-    validations.reserve(validation_pairs.size());
-    for (const auto& pair : validation_pairs)
-      validations.push_back(pair.label.GetUserVisibleName(default_tc));
-    std::sort(validations.begin(), validations.end());
-    for (const auto& dep : validations)
-      res->AppendString(dep);
-    return res;
-  }
+  ValuePtr RenderValidations() { return RenderLabels(target_->validations()); }
 
   ValuePtr RenderRuntimeDeps() {
     auto res = std::make_unique<base::ListValue>();
diff --git a/src/gn/generated_file_target_generator.cc b/src/gn/generated_file_target_generator.cc
index a034562..16b705b 100644
--- a/src/gn/generated_file_target_generator.cc
+++ b/src/gn/generated_file_target_generator.cc
@@ -147,47 +147,36 @@
 }
 
 bool GeneratedFileTargetGenerator::FillDataKeys() {
-  const Value* value = scope_->GetValue(variables::kDataKeys, true);
-  if (!value)
+  if (!scope_->GetValue(variables::kDataKeys, false))
     return true;
-  if (!IsMetadataCollectionTarget(variables::kDataKeys, value->origin()))
-    return false;
-  if (!value->VerifyTypeIs(Value::LIST, err_))
-    return false;
-
-  for (const Value& v : value->list_value()) {
-    // Keys must be strings.
-    if (!v.VerifyTypeIs(Value::STRING, err_))
-      return false;
-    target_->data_keys().push_back(v.string_value());
-  }
-
   data_keys_defined_ = true;
-  return true;
+  return FillKeys(variables::kDataKeys, &target_->data_keys());
 }
 
 bool GeneratedFileTargetGenerator::FillWalkKeys() {
-  const Value* value = scope_->GetValue(variables::kWalkKeys, true);
-  // If we define this and contents, that's an error.
-  if (value &&
-      !IsMetadataCollectionTarget(variables::kWalkKeys, value->origin()))
-    return false;
-
   // If we don't define it, we want the default value which is a list
   // containing the empty string.
-  if (!value) {
+  if (!scope_->GetValue(variables::kWalkKeys, false)) {
     target_->walk_keys().push_back("");
     return true;
   }
+  return FillKeys(variables::kWalkKeys, &target_->walk_keys());
+}
 
-  // Otherwise, pull and validate the specified value.
-  if (!value->VerifyTypeIs(Value::LIST, err_))
+bool GeneratedFileTargetGenerator::FillKeys(std::string_view variable,
+                                            std::vector<std::string>* out) {
+  const Value* value = scope_->GetValue(variable, true);
+  if (!value)
+    return true;
+  // If we define this and contents, that's an error.
+  if (!IsMetadataCollectionTarget(variable, value->origin()) ||
+      !value->VerifyTypeIs(Value::LIST, err_))
     return false;
   for (const Value& v : value->list_value()) {
     // Keys must be strings.
     if (!v.VerifyTypeIs(Value::STRING, err_))
       return false;
-    target_->walk_keys().push_back(v.string_value());
+    out->push_back(v.string_value());
   }
   return true;
 }
diff --git a/src/gn/generated_file_target_generator.h b/src/gn/generated_file_target_generator.h
index ba5db34..59a7539 100644
--- a/src/gn/generated_file_target_generator.h
+++ b/src/gn/generated_file_target_generator.h
@@ -32,6 +32,9 @@
   bool FillWalkKeys();
   bool FillRebase();
 
+  // Appends the list of strings in the given variable (if set) to |out|.
+  bool FillKeys(std::string_view variable, std::vector<std::string>* out);
+
   // Returns false if `contents` is defined (i.e. if this target was provided
   // with explicit contents to write). Returns false otherwise, indicating that
   // it is okay to set metadata collection variables on this target.
diff --git a/src/gn/target.cc b/src/gn/target.cc
index 91ecb76..f1cef5f 100644
--- a/src/gn/target.cc
+++ b/src/gn/target.cc
@@ -1324,8 +1324,6 @@
 
     // Gather walk keys and find the appropriate target. Targets identified in
     // the walk key set must be deps or data_deps of the declaring target.
-    const DepsIteratorRange& all_deps = target.GetDeps(Target::DEPS_ALL);
-    SourceDir current_dir = target.label().dir();
     for (const auto& next : next_walk_labels) {
       DCHECK(next.type() == Value::STRING);
 
@@ -1334,7 +1332,7 @@
       // from each explicitly listed dep prior to this, followed by all data in
       // walk order of the remaining deps.
       if (next.string_value().empty()) {
-        for (const auto& dep : all_deps) {
+        for (const auto& dep : target.GetDeps(Target::DEPS_ALL)) {
           // If we haven't walked this dep yet, go down into it.
           if (targets_walked_.add(dep.ptr)) {
             if (!Walk(*dep.ptr, false))
@@ -1356,61 +1354,10 @@
         break;
       }
 
-      // Otherwise, look through the target's deps for the specified one.
-      // Canonicalize the label if possible.
-      const Settings* settings = target.settings();
-      const Label& toolchain_label = settings->toolchain_label();
-      Label next_label = Label::Resolve(
-          current_dir, settings->build_settings()->root_path_utf8(),
-          toolchain_label, next, &err_);
-      if (next_label.is_null()) {
-        err_ = Err(next.origin(), std::string("Failed to canonicalize ") +
-                                      next.string_value() + std::string("."));
+      // Otherwise, go down into the specified dep if we haven't walked it yet.
+      const Target* dep = ResolveDepLabel(target, next);
+      if (!dep || (targets_walked_.add(dep) && !Walk(*dep, false)))
         return false;
-      }
-
-      bool found_next = false;
-      for (const auto& dep : all_deps) {
-        // Match against the label with the toolchain.
-        if (dep.label.Matches(next_label, toolchain_label)) {
-          // If we haven't walked this dep yet, go down into it.
-          if (targets_walked_.add(dep.ptr)) {
-            if (!Walk(*dep.ptr, false))
-              return false;
-          }
-          // We found it, so we can exit this search now.
-          found_next = true;
-          break;
-        }
-      }
-      if (!found_next && collect_validations_metadata_) {
-        for (const auto& dep : target.validations()) {
-          // Match against the label with the toolchain.
-          if (dep.label.Matches(next_label, toolchain_label)) {
-            // If we haven't walked this dep yet, go down into it.
-            if (targets_walked_.add(dep.ptr)) {
-              if (!Walk(*dep.ptr, false))
-                return false;
-            }
-            // We found it, so we can exit this search now.
-            found_next = true;
-            break;
-          }
-        }
-      }
-      // If we didn't find the specified dep in the target, that's an error.
-      // Propagate it back to the user.
-      if (!found_next) {
-        err_ =
-            Err(next.origin(),
-                std::string("I was expecting ") +
-                    next_label.GetUserVisibleName(true) +
-                    std::string(" to be a dependency of ") +
-                    target.label().GetUserVisibleName(true) +
-                    ". Make sure it's included in the deps or data_deps, and "
-                    "that you've specified the appropriate toolchain.");
-        return false;
-      }
     }
     result_->insert(result_->end(),
                     std::make_move_iterator(current_result.begin()),
@@ -1419,6 +1366,42 @@
   }
 
  private:
+  // Resolves |value| as a label relative to |target|, and returns the
+  // dependency of |target| that it refers to. If there is none, sets |err_| and
+  // returns nullptr.
+  const Target* ResolveDepLabel(const Target& target, const Value& value) {
+    const Settings* settings = target.settings();
+    const Label& toolchain_label = settings->toolchain_label();
+    Label label = Label::Resolve(target.label().dir(),
+                                 settings->build_settings()->root_path_utf8(),
+                                 toolchain_label, value, &err_);
+    if (label.is_null()) {
+      err_ = Err(value.origin(),
+                 "Failed to canonicalize " + value.string_value() + ".");
+      return nullptr;
+    }
+    // Match against the label with the toolchain.
+    for (const auto& dep : target.GetDeps(Target::DEPS_ALL)) {
+      if (dep.label.Matches(label, toolchain_label))
+        return dep.ptr;
+    }
+    if (collect_validations_metadata_) {
+      for (const auto& dep : target.validations()) {
+        if (dep.label.Matches(label, toolchain_label))
+          return dep.ptr;
+      }
+    }
+    // If we didn't find the specified dep in the target, that's an error.
+    // Propagate it back to the user.
+    err_ = Err(value.origin(),
+               "I was expecting " + label.GetUserVisibleName(true) +
+                   " to be a dependency of " +
+                   target.label().GetUserVisibleName(true) +
+                   ". Make sure it's included in the deps or data_deps, and "
+                   "that you've specified the appropriate toolchain.");
+    return nullptr;
+  }
+
   const KeyList& data_keys_;
   const KeyList& walk_keys_;
   const SourceDir& rebase_dir_;