Remove GN attributes from reserved attributes.

Instead, they only apply when inheriting from a builtin rule.
This means that you can now define a custom rule with the attribute
"deps", for example.

Bug: 528225104
Change-Id: I28de38628c66cf82c4c4e773aba630b56a6a6964
Reviewed-on: https://gn-review.googlesource.com/c/gn/+/29280
Reviewed-by: Takuto Ikuta <tikuta@google.com>
Commit-Queue: Matt Stark <msta@google.com>
diff --git a/src/gn/starlark/crates/attr/src/ctx.rs b/src/gn/starlark/crates/attr/src/ctx.rs
index fc38fcd..006c265 100644
--- a/src/gn/starlark/crates/attr/src/ctx.rs
+++ b/src/gn/starlark/crates/attr/src/ctx.rs
@@ -63,19 +63,20 @@
         builtin: Option<OutputType>,
         heap: &FrozenHeap<'v>,
     ) -> Self {
-        let (builtin_files, builtin_attrs) = builtin.map(|b| b.attrs()).unwrap_or_default();
-        let mut attrs_fields =
-            SmallMap::with_capacity(attrs.len() + builtin_files.len() + builtin_attrs.len());
+        let builtin_fields = builtin.map(OutputType::attrs).unwrap_or_default();
+        let mut attrs_fields = SmallMap::with_capacity(
+            attrs.len() + builtin_fields.file_and_attr.len() + builtin_fields.attr_only.len(),
+        );
         let mut file_fields = SmallMap::new();
         let mut files_fields = SmallMap::new();
 
         let any = || Field::new(starlark::values::typing::TypeCompiled::any(), None);
 
-        for name in builtin_files {
+        for name in builtin_fields.file_and_attr {
             attrs_fields.insert(name.to_string(), any());
             files_fields.insert(name.to_string(), any());
         }
-        for name in builtin_attrs {
+        for name in builtin_fields.attr_only {
             attrs_fields.insert(name.to_string(), any());
         }
 
@@ -129,11 +130,13 @@
         mut ctx_attr: Vec<Value<'v>>,
         heap: &Heap<'v>,
     ) -> starlark::Result<CtxAttr<'v>> {
-        let (builtin_files, builtin_attrs) = output_type.map(|b| b.attrs()).unwrap_or_default();
-        debug_assert!(builtin_files.len() + builtin_attrs.len() == ctx_attr.len());
+        let builtin_fields = output_type.map(OutputType::attrs).unwrap_or_default();
+        debug_assert!(
+            builtin_fields.file_and_attr.len() + builtin_fields.attr_only.len() == ctx_attr.len()
+        );
         ctx_attr.reserve_exact(self.attr.len() - ctx_attr.len());
         let mut ctx_files = Vec::with_capacity(self.files.len());
-        for &attr_val in ctx_attr.iter().take(builtin_files.len()) {
+        for &attr_val in ctx_attr.iter().take(builtin_fields.file_and_attr.len()) {
             ctx_files.push(attr_val);
         }
         let mut ctx_file = Vec::with_capacity(self.file.len());
diff --git a/src/gn/starlark/crates/rule/src/globals.rs b/src/gn/starlark/crates/rule/src/globals.rs
index 872a0af..f07649c 100644
--- a/src/gn/starlark/crates/rule/src/globals.rs
+++ b/src/gn/starlark/crates/rule/src/globals.rs
@@ -169,4 +169,45 @@
             "Attribute 'name' is reserved",
         );
     }
+
+    #[test]
+    fn test_reserved_attributes() {
+        let mut a = new_assert();
+
+        a.pass(
+            r#"
+my_rule = rule(
+    implementation = lambda ctx: [],
+    attrs = {
+        "deps": attr.label_list(),
+        "sources": attr.label_list(),
+    },
+)
+"#,
+        );
+
+        a.fail(
+            r#"
+load("//builtins:rules.scl", "static_library")
+rule(
+    implementation = lambda ctx: [],
+    parent = static_library,
+    attrs = {"deps": attr.label_list()},
+)
+"#,
+            "Attribute 'deps' is reserved",
+        );
+
+        a.fail(
+            r#"
+load("//builtins:rules.scl", "copy")
+rule(
+    implementation = lambda ctx: [],
+    parent = copy,
+    attrs = {"outputs": attr.string_list()},
+)
+"#,
+            "Attribute 'outputs' is reserved",
+        );
+    }
 }
diff --git a/src/gn/starlark/crates/rule/src/rule.rs b/src/gn/starlark/crates/rule/src/rule.rs
index 1b63a4b..99c8798 100644
--- a/src/gn/starlark/crates/rule/src/rule.rs
+++ b/src/gn/starlark/crates/rule/src/rule.rs
@@ -60,15 +60,7 @@
 /// Some reserved attributes are currently in use (eg. name).
 /// Others are reserved for future use, so we disallow them in case we want to
 /// support them in the future.
-const RESERVED_ATTRS: &[&str] = &[
-    "deps",
-    "name",
-    "public",
-    "public_deps",
-    "sources",
-    "testonly",
-    "visibility",
-];
+const RESERVED_ATTRS: &[&str] = &["name", "testonly", "visibility"];
 
 fn merge_attrs(
     parent_attrs: &SmallMap<String, AttrSchema>,
@@ -115,11 +107,17 @@
 
         let (output_type, attrs) = match parent {
             Some(p) => {
+                let output_type = p.as_ref().output_type;
+                if let Some(output_type) = output_type {
+                    let field_names = output_type.attrs();
+                    for name in attrs.keys() {
+                        if field_names.is_reserved(name) {
+                            return Err(crate::Error::ReservedAttribute(name.clone()).into());
+                        }
+                    }
+                }
                 provides.extend_from_slice(&p.as_ref().provides);
-                (
-                    p.as_ref().output_type,
-                    merge_attrs(p.as_ref().schema.attrs(), attrs)?,
-                )
+                (output_type, merge_attrs(p.as_ref().schema.attrs(), attrs)?)
             },
             None => (None, attrs),
         };
diff --git a/src/gn/starlark/crates/testutils/src/target.rs b/src/gn/starlark/crates/testutils/src/target.rs
index 20c1c79..3957238 100644
--- a/src/gn/starlark/crates/testutils/src/target.rs
+++ b/src/gn/starlark/crates/testutils/src/target.rs
@@ -167,8 +167,8 @@
         self.get()
             .output_type
             .map(|ot| {
-                let (file_fields, target_fields) = ot.attrs();
-                vec![Value::new_none(); file_fields.len() + target_fields.len()]
+                let fields = ot.attrs();
+                vec![Value::new_none(); fields.file_and_attr.len() + fields.attr_only.len()]
             })
             .unwrap_or_default()
     }
diff --git a/src/gn/starlark/crates/types/src/lib.rs b/src/gn/starlark/crates/types/src/lib.rs
index c86a0a7..8f9c404 100644
--- a/src/gn/starlark/crates/types/src/lib.rs
+++ b/src/gn/starlark/crates/types/src/lib.rs
@@ -25,7 +25,7 @@
 pub use file::{File, intern_string};
 pub use label::Label;
 pub use label_ref::LabelRef;
-pub use output_type::OutputType;
+pub use output_type::{BuiltinFieldNames, OutputType};
 pub use package::Package;
 pub use package_ref::PackageRef;
 pub use path_resolver::PathResolver;
diff --git a/src/gn/starlark/crates/types/src/output_type.rs b/src/gn/starlark/crates/types/src/output_type.rs
index 24c6e65..f4d481e 100644
--- a/src/gn/starlark/crates/types/src/output_type.rs
+++ b/src/gn/starlark/crates/types/src/output_type.rs
@@ -42,7 +42,7 @@
 }
 
 /// Compile-time check if slice contains a string.
-const fn contains(slice: &[&'static str], needle: &'static str) -> bool {
+const fn contains(slice: &[&'static str], needle: &str) -> bool {
     let mut i = 0;
     while i < slice.len() {
         if str_eq(slice[i], needle) {
@@ -53,6 +53,117 @@
     false
 }
 
+/// Field names associated with a built-in GN target type.
+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
+pub struct BuiltinFieldNames {
+    /// Built-in attributes populated only in `ctx.attr`.
+    pub attr_only: &'static [&'static str],
+    /// Built-in attributes populated in both `ctx.attr` and `ctx.files`.
+    pub file_and_attr: &'static [&'static str],
+    /// Native GN attributes forwarded as kwargs rather than exposed on `ctx`,
+    /// reserved so Starlark rules cannot shadow them.
+    pub reserved_fields: &'static [&'static str],
+}
+
+impl BuiltinFieldNames {
+    /// Returns `true` if `name` is handled or reserved by this built-in target type.
+    pub const fn is_reserved(&self, name: &str) -> bool {
+        contains(self.attr_only, name)
+            || contains(self.file_and_attr, name)
+            || contains(self.reserved_fields, name)
+    }
+}
+
+/// All native GN target attributes across all target types (excluding
+/// `testonly` and `visibility`, which are reserved for all rules).
+const RESERVED_FIELDS: &[&str] = &[
+    "aliased_deps",
+    "all_dependent_configs",
+    "allow_circular_includes_from",
+    "arflags",
+    "args",
+    "asmflags",
+    "assert_no_deps",
+    "bridge_header",
+    "bundle_contents_dir",
+    "bundle_deps_filter",
+    "bundle_executable_dir",
+    "bundle_resources_dir",
+    "bundle_root_dir",
+    "c_additional_outputs",
+    "cflags",
+    "cflags_c",
+    "cflags_cc",
+    "cflags_objc",
+    "cflags_objcc",
+    "check_includes",
+    "check_includes_strict",
+    "collect_validations_metadata",
+    "complete_static_lib",
+    "configs",
+    "contents",
+    "crate_name",
+    "crate_root",
+    "crate_type",
+    "data",
+    "data_deps",
+    "data_keys",
+    "datadeps",
+    "defines",
+    "depfile",
+    "deps",
+    "externs",
+    "framework_dirs",
+    "frameworks",
+    "friend",
+    "gen_deps",
+    "generate_modulemap",
+    "include_dirs",
+    "inputs",
+    "ldflags",
+    "lib_dirs",
+    "libs",
+    "metadata",
+    "mnemonic",
+    "module_name",
+    "output_conversion",
+    "output_dir",
+    "output_extension",
+    "output_name",
+    "output_prefix_override",
+    "outputs",
+    "partial_info_plist",
+    "pool",
+    "post_processing_args",
+    "post_processing_manifest",
+    "post_processing_outputs",
+    "post_processing_script",
+    "post_processing_sources",
+    "precompiled_header",
+    "precompiled_source",
+    "product_type",
+    "public",
+    "public_configs",
+    "public_deps",
+    "public_inputs",
+    "rebase",
+    "response_file_contents",
+    "rustenv",
+    "rustflags",
+    "script",
+    "sources",
+    "swiftflags",
+    "transparent",
+    "validations",
+    "walk_keys",
+    "weak_frameworks",
+    "weak_libraries",
+    "write_runtime_deps",
+    "xcasset_compiler_flags",
+    "xcode_extra_attributes",
+    "xcode_test_application_name",
+];
+
 impl OutputType {
     const MAX: u8 = Self::RustProcMacro as u8;
     const NOOP: u8 = 15;
@@ -68,35 +179,44 @@
         }
     }
 
-    /// Returns (attr-and-files attributes, attr-only attributes).
+    /// Returns the built-in and reserved field names for this target type.
     ///
-    /// Any attributes that should fill ctx.files.* should go in the former.
-    /// Other attributes should go in the latter.
-    pub const fn attrs(self) -> (&'static [&'static str], &'static [&'static str]) {
+    /// Any attributes that should fill `ctx.files.*` go in `file_and_attr`;
+    /// other attributes exposed on `ctx.attr.*` go in `attr_only`; remaining
+    /// native GN attributes go in `reserved_fields`.
+    pub const fn attrs(self) -> BuiltinFieldNames {
         match self {
             Self::Executable
             | Self::SharedLibrary
             | Self::LoadableModule
             | Self::StaticLibrary
-            | Self::SourceSet => (&["sources", "public"], &["deps", "public_deps"]),
-            _ => (&[], &[]),
+            | Self::SourceSet => BuiltinFieldNames {
+                file_and_attr: &["sources", "public"],
+                attr_only: &["deps", "public_deps"],
+                reserved_fields: RESERVED_FIELDS,
+            },
+            _ => BuiltinFieldNames {
+                file_and_attr: &[],
+                attr_only: &[],
+                reserved_fields: RESERVED_FIELDS,
+            },
         }
     }
 
     pub const fn has_sources(self) -> bool {
-        contains(self.attrs().0, "sources")
+        contains(self.attrs().file_and_attr, "sources")
     }
 
     pub const fn has_public(self) -> bool {
-        contains(self.attrs().0, "public")
+        contains(self.attrs().file_and_attr, "public")
     }
 
     pub const fn has_deps(self) -> bool {
-        contains(self.attrs().1, "deps")
+        contains(self.attrs().attr_only, "deps")
     }
 
     pub const fn has_public_deps(self) -> bool {
-        contains(self.attrs().1, "public_deps")
+        contains(self.attrs().attr_only, "public_deps")
     }
 }
 
@@ -115,4 +235,22 @@
         assert!(OutputType::Executable.has_deps());
         assert!(!OutputType::Copy.has_deps());
     }
+
+    #[test]
+    fn test_is_reserved() {
+        assert!(OutputType::Executable.attrs().is_reserved("deps"));
+        assert!(OutputType::Executable.attrs().is_reserved("sources"));
+        assert!(OutputType::Executable.attrs().is_reserved("cflags"));
+        assert!(!OutputType::Executable.attrs().is_reserved("custom_attr"));
+
+        assert!(OutputType::Group.attrs().is_reserved("deps"));
+        assert!(OutputType::Group.attrs().is_reserved("public_inputs"));
+        assert!(!OutputType::Group.attrs().is_reserved("custom_attr"));
+
+        assert!(OutputType::Copy.attrs().is_reserved("sources"));
+        assert!(OutputType::Copy.attrs().is_reserved("outputs"));
+
+        assert!(OutputType::RustLibrary.attrs().is_reserved("sources"));
+        assert!(OutputType::RustLibrary.attrs().is_reserved("crate_root"));
+    }
 }