Add provides parameter to Starlark rule()

Rules can declare expected provider types up front so missing providers
are caught after implementation execution. Child rules inherit and
deduplicate declared providers from their parent rule.

Bug: 528225104
Change-Id: I97c73724ebf327799c855a7d848855916a6a6964
Reviewed-on: https://gn-review.googlesource.com/c/gn/+/28980
Reviewed-by: Takuto Ikuta <tikuta@google.com>
Commit-Queue: Matt Stark <msta@google.com>
diff --git a/src/gn/starlark/crates/providers/src/provider_type.rs b/src/gn/starlark/crates/providers/src/provider_type.rs
index f7b1007..25ac688 100644
--- a/src/gn/starlark/crates/providers/src/provider_type.rs
+++ b/src/gn/starlark/crates/providers/src/provider_type.rs
@@ -75,7 +75,14 @@
 
 impl Display for ProviderType {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, "<provider>")
+        write!(
+            f,
+            "{}",
+            self.data
+                .get()
+                .map(|data| data.name.as_ref().value().as_str())
+                .unwrap_or("<provider>")
+        )
     }
 }
 
@@ -145,6 +152,11 @@
 }
 
 impl ProviderType {
+    /// Returns the unique identifier for this provider type.
+    pub fn id(&self) -> ProviderId {
+        self.id
+    }
+
     /// Creates a new provider type with the provided fields.
     /// This provider is not yet configured, and is unusable until `export_as`
     /// is called.
diff --git a/src/gn/starlark/crates/providers/src/providers.rs b/src/gn/starlark/crates/providers/src/providers.rs
index 0d470fb..bf99490 100644
--- a/src/gn/starlark/crates/providers/src/providers.rs
+++ b/src/gn/starlark/crates/providers/src/providers.rs
@@ -82,6 +82,11 @@
         };
         Ok(self.providers.contains_key(key))
     }
+
+    /// Returns whether a provider instance exists for the given [`ProviderId`].
+    pub fn contains_id(&self, id: ProviderId) -> bool {
+        self.providers.contains_key(&id)
+    }
 }
 
 impl<'v> StarlarkTypeRepr for Providers<'v> {
diff --git a/src/gn/starlark/crates/rule/src/errors.rs b/src/gn/starlark/crates/rule/src/errors.rs
index 1880109..01d0d97 100644
--- a/src/gn/starlark/crates/rule/src/errors.rs
+++ b/src/gn/starlark/crates/rule/src/errors.rs
@@ -2,6 +2,9 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
+use providers::ProviderType;
+use types::Label;
+
 /// Errors returned by the GN Starlark rule system.
 #[derive(thiserror::Error, Debug)]
 pub enum Error {
@@ -24,6 +27,12 @@
         "mnemonic must be an uppercase letter followed by uppercase letters or digits. Got '{0}'"
     )]
     InvalidMnemonic(String),
+    #[error("Rule '{rule}' on target '{target}' did not return declared provider: {provider}")]
+    MissingProvider {
+        rule: String,
+        target: Label,
+        provider: ProviderType,
+    },
 }
 
 impl From<Error> for starlark::Error {
diff --git a/src/gn/starlark/crates/rule/src/globals.rs b/src/gn/starlark/crates/rule/src/globals.rs
index 7fe7fbc..872a0af 100644
--- a/src/gn/starlark/crates/rule/src/globals.rs
+++ b/src/gn/starlark/crates/rule/src/globals.rs
@@ -82,6 +82,11 @@
                 #[starlark(require = named)] attrs: Option<
                     starlark::collections::SmallMap<&str, &attr::AttrSchema>,
                 >,
+                #[starlark(require = named)] provides: Option<
+                    starlark::values::list::UnpackList<
+                        starlark::values::ValueTyped<'v, $crate::providers::ProviderType>,
+                    >,
+                >,
                 eval: &mut starlark::eval::Evaluator<'v, '_, '_>,
             ) -> starlark::Result<starlark::values::Value<'v>> {
                 // Rules can only be created while loading scl files, not in macros or rule
@@ -94,8 +99,16 @@
                     .into_iter()
                     .map(|(k, v)| (k.to_string(), v.clone()))
                     .collect();
+                let provides = provides.map(|p| p.items).unwrap_or_default();
                 let rule = eval.frozen_heap(|heap, edge| {
-                    <$crate::Rule<'v, $ctx_type>>::new(attrs, parent, implementation, &heap, edge)
+                    <$crate::Rule<'v, $ctx_type>>::new(
+                        attrs,
+                        parent,
+                        implementation,
+                        provides,
+                        &heap,
+                        edge,
+                    )
                 })?;
                 Ok(eval.heap().alloc(rule))
             }
diff --git a/src/gn/starlark/crates/rule/src/implementation.rs b/src/gn/starlark/crates/rule/src/implementation.rs
index c6d7a16..a5bbf74 100644
--- a/src/gn/starlark/crates/rule/src/implementation.rs
+++ b/src/gn/starlark/crates/rule/src/implementation.rs
@@ -96,6 +96,18 @@
             )
         };
 
+        let providers = Providers::unpack_value_err(res)?;
+        for provider in &rule.provides {
+            if !providers.contains_id(provider.id()) {
+                return Err(crate::Error::MissingProvider {
+                    rule: rule.name().to_string(),
+                    target: target.label().to_owned(),
+                    provider: provider.as_ref().clone(),
+                }
+                .into());
+            }
+        }
+
         module.set_extra_value(
             module.heap().alloc_complex(EvaluatedTarget {
                 phonies: rule_context
@@ -103,7 +115,7 @@
                     .borrow_mut()
                     .rule_impl_complete()?,
                 actions,
-                providers: providers::Providers::unpack_value_err(res)?,
+                providers,
             }),
         );
 
diff --git a/src/gn/starlark/crates/rule/src/lib.rs b/src/gn/starlark/crates/rule/src/lib.rs
index 681948b..0e594e0 100644
--- a/src/gn/starlark/crates/rule/src/lib.rs
+++ b/src/gn/starlark/crates/rule/src/lib.rs
@@ -16,5 +16,6 @@
 pub use errors::Error;
 pub use globals::{extract_builtin_rules, register_builtin_rules};
 pub use implementation::{EvaluatedTarget, run};
+pub use providers;
 pub use rule::{OutputType, Rule};
 pub use types::{self, CtxMethods};
diff --git a/src/gn/starlark/crates/rule/src/rule.rs b/src/gn/starlark/crates/rule/src/rule.rs
index 69317d5..1b63a4b 100644
--- a/src/gn/starlark/crates/rule/src/rule.rs
+++ b/src/gn/starlark/crates/rule/src/rule.rs
@@ -6,6 +6,7 @@
 
 use allocative::Allocative;
 use attr::{Attr, AttrSchema, CtxAttrSchema, traits::EvalContextAttrExt};
+use providers::ProviderType;
 use starlark::{
     any::ProvidesStaticType,
     collections::SmallMap,
@@ -17,7 +18,7 @@
 };
 use starlark_derive::{NoSerialize, starlark_value};
 pub use types::OutputType;
-use types::{EvaluatorContextExt as _, Scope as _};
+use types::{EvaluatorContextExt as _, Scope as _, util::uniquify_small_vec};
 
 /// Representation of a Starlark rule object.
 ///
@@ -41,6 +42,7 @@
     pub(crate) output_type: Option<OutputType>,
     pub(crate) implementation: Value<'v>,
     pub(crate) parent: Option<ValueTyped<'v, Self>>,
+    pub(crate) provides: Vec<ValueTyped<'v, ProviderType>>,
     pub(crate) _phantom: PhantomData<C>,
 }
 
@@ -101,6 +103,7 @@
         attrs: SmallMap<String, AttrSchema>,
         parent: Option<ValueTyped<'v, Self>>,
         implementation: Value<'v>,
+        mut provides: Vec<ValueTyped<'v, ProviderType>>,
         frozen_heap: &FrozenHeap<'fh>,
         edge: HeapEdge<'v, 'fh>,
     ) -> Result<Self, starlark::Error> {
@@ -111,12 +114,16 @@
         }
 
         let (output_type, attrs) = match parent {
-            Some(p) => (
-                p.as_ref().output_type,
-                merge_attrs(p.as_ref().schema.attrs(), attrs)?,
-            ),
+            Some(p) => {
+                provides.extend_from_slice(&p.as_ref().provides);
+                (
+                    p.as_ref().output_type,
+                    merge_attrs(p.as_ref().schema.attrs(), attrs)?,
+                )
+            },
             None => (None, attrs),
         };
+        uniquify_small_vec(&mut provides);
 
         let schema = edge.rebrand(CtxAttrSchema::new(attrs, output_type, frozen_heap));
         Ok(Self {
@@ -125,6 +132,7 @@
             output_type,
             implementation,
             parent,
+            provides,
             _phantom: PhantomData,
         })
     }
@@ -146,6 +154,7 @@
             output_type: Some(builtin),
             implementation,
             parent: None,
+            provides: Vec::new(),
             _phantom: PhantomData,
         }
     }
@@ -159,6 +168,15 @@
     pub fn output_type(&self) -> Option<OutputType> {
         self.output_type
     }
+
+    /// Returns the name of the rule. Can only be called if it has been named already
+    pub fn name(&self) -> &str {
+        &self
+            .once_named
+            .get()
+            .expect("calling rule.name() on an unnamed rule")
+            .0
+    }
 }
 
 pub(crate) fn build_signature(
@@ -284,6 +302,7 @@
             output_type: self.output_type,
             implementation: self.implementation.freeze(freezer)?,
             parent: self.parent.freeze(freezer)?,
+            provides: self.provides.freeze(freezer)?,
             _phantom: PhantomData,
         })
     }
diff --git a/src/gn/starlark/crates/rule/tests/providers.rs b/src/gn/starlark/crates/rule/tests/providers.rs
new file mode 100644
index 0000000..4bae4f3
--- /dev/null
+++ b/src/gn/starlark/crates/rule/tests/providers.rs
@@ -0,0 +1,93 @@
+// Copyright 2026 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+use rule::run;
+use testutils::{Assert, FakeEvalContext};
+use types::{LabelRef, PackageRef, Session as _};
+
+#[test]
+fn test_provides() {
+    let mut assert = Assert::new_rule_assert();
+    let module = assert.module(
+        "//pkg:rules.scl",
+        r#"
+ParentInfo = provider(fields = [])
+ChildInfo = provider(fields = [])
+
+def _impl(ctx):
+    providers = {
+        "ParentInfo": ParentInfo(),
+        "ChildInfo": ChildInfo(),
+    }
+    return [providers[name] for name in ctx.attr.providers]
+
+parent = rule(
+    implementation = _impl,
+    provides = [ParentInfo],
+)
+
+child = rule(
+    implementation = _impl,
+    parent = parent,
+    attrs = {
+        "providers": attr.string_list(mandatory = True),
+    },
+    provides = [ChildInfo],
+)
+"#,
+    );
+    assert.module_add(module);
+    assert.pass(
+        r#"
+load("//pkg:rules.scl", "child")
+
+child(
+    name = "all",
+    providers = ["ParentInfo", "ChildInfo"],
+)
+
+child(
+    name = "missing_parent",
+    providers = ["ChildInfo"],
+)
+
+child(
+    name = "missing_child",
+    providers = ["ParentInfo"],
+)
+"#,
+    );
+
+    let context = assert.context();
+    for (name, expected_err) in [
+        ("all", None),
+        (
+            "missing_parent",
+            Some(
+                "Rule 'child' on target '//:missing_parent' did not return declared provider: ParentInfo",
+            ),
+        ),
+        (
+            "missing_child",
+            Some(
+                "Rule 'child' on target '//:missing_child' did not return declared provider: ChildInfo",
+            ),
+        ),
+    ] {
+        let target = context.session.get_target(
+            LabelRef::new(PackageRef::root(), name),
+            context.session.default_toolchain.as_ref(),
+        );
+        let session = assert.session();
+        let res = run(&target, move |t: &testutils::FakeTargetRef| {
+            FakeEvalContext::rule_impl(session.clone(), t.clone())
+        });
+        match expected_err {
+            None => {
+                res.unwrap();
+            },
+            Some(expected) => assert_eq!(res.unwrap_err().to_string(), expected),
+        }
+    }
+}