Add providers parameter to Starlark label attributes

Label attributes can declare required provider combinations (matching bazel) so missing dependency providers fail before running rule implementations.

Bug: 528225104
Change-Id: I10e685196bd4465dcaf681bdba2b610b6a6a6964
Reviewed-on: https://gn-review.googlesource.com/c/gn/+/29000
Commit-Queue: Matt Stark <msta@google.com>
Reviewed-by: Takuto Ikuta <tikuta@google.com>
diff --git a/src/gn/starlark/Cargo.lock b/src/gn/starlark/Cargo.lock
index 8f803f6..c9708b0 100644
--- a/src/gn/starlark/Cargo.lock
+++ b/src/gn/starlark/Cargo.lock
@@ -158,6 +158,7 @@
 dependencies = [
  "allocative",
  "either",
+ "providers",
  "starlark",
  "starlark_derive",
  "testutils",
diff --git a/src/gn/starlark/crates/attr/Cargo.toml b/src/gn/starlark/crates/attr/Cargo.toml
index 970dbe2..09a6ce7 100644
--- a/src/gn/starlark/crates/attr/Cargo.toml
+++ b/src/gn/starlark/crates/attr/Cargo.toml
@@ -12,6 +12,7 @@
 [dependencies]
 allocative = { workspace = true }
 either = { workspace = true }
+providers = { path = "../providers" }
 starlark = { workspace = true }
 starlark_derive = { workspace = true }
 thiserror = { workspace = true }
diff --git a/src/gn/starlark/crates/attr/src/allow_files.rs b/src/gn/starlark/crates/attr/src/allow_files.rs
index 63bc6a7..6b6fedf 100644
--- a/src/gn/starlark/crates/attr/src/allow_files.rs
+++ b/src/gn/starlark/crates/attr/src/allow_files.rs
@@ -117,6 +117,7 @@
                     disallow_empty: false,
                     allow_files: AllowFilesSchema::Many(AllowFiles::Some(vec![pattern.to_owned()])),
                     cfg: AttrCfg::CurrentToolchain,
+                    providers: Default::default(),
                     doc: String::new(),
                 };
                 Attr::create(
diff --git a/src/gn/starlark/crates/attr/src/attr.rs b/src/gn/starlark/crates/attr/src/attr.rs
index 884b5d3..c1fa74a 100644
--- a/src/gn/starlark/crates/attr/src/attr.rs
+++ b/src/gn/starlark/crates/attr/src/attr.rs
@@ -311,6 +311,7 @@
             disallow_empty: false,
             allow_files: AllowFilesSchema::None,
             cfg: AttrCfg::CurrentToolchain,
+            providers: Default::default(),
             doc: String::new(),
         };
 
@@ -343,6 +344,7 @@
             disallow_empty: false,
             allow_files: AllowFilesSchema::None,
             cfg: AttrCfg::CurrentToolchain,
+            providers: Default::default(),
             doc: String::new(),
         };
 
@@ -377,6 +379,7 @@
             disallow_empty: false,
             allow_files: AllowFilesSchema::Many(AllowFiles::Some(vec![".cc".to_owned()])),
             cfg: AttrCfg::CurrentToolchain,
+            providers: Default::default(),
             doc: String::new(),
         };
 
@@ -423,6 +426,7 @@
                 disallow_empty: false,
                 allow_files: AllowFilesSchema::None,
                 cfg: AttrCfg::CurrentToolchain,
+                providers: Default::default(),
                 doc: String::new(),
             };
 
@@ -468,6 +472,7 @@
                 disallow_empty: false,
                 allow_files: AllowFilesSchema::None,
                 cfg: AttrCfg::CurrentToolchain,
+                providers: Default::default(),
                 doc: String::new(),
             };
 
diff --git a/src/gn/starlark/crates/attr/src/errors.rs b/src/gn/starlark/crates/attr/src/errors.rs
index 2bbcd22..cc69620 100644
--- a/src/gn/starlark/crates/attr/src/errors.rs
+++ b/src/gn/starlark/crates/attr/src/errors.rs
@@ -42,10 +42,14 @@
         "target `{target}` does not produce any outputs matching allowed extensions: {allowed:?}"
     )]
     NoMatchingOutputs { target: Label, allowed: Vec<String> },
+    #[error("target `{target}` does not have mandatory providers: {missing}")]
+    MissingRequiredProviders { target: Label, missing: String },
     #[error("attribute {0}: only attr.label and attr.label_list types may be overridden")]
     OnlyLabelTypesMayBeOverridden(String),
     #[error("attribute {0}: types of parent and child's attributes mismatch")]
     AttributeTypeMismatch(String),
+    #[error("provider group cannot be empty")]
+    EmptyProviderGroup,
 }
 
 impl From<Error> for starlark::Error {
diff --git a/src/gn/starlark/crates/attr/src/globals.rs b/src/gn/starlark/crates/attr/src/globals.rs
index 406a08c..28738ba 100644
--- a/src/gn/starlark/crates/attr/src/globals.rs
+++ b/src/gn/starlark/crates/attr/src/globals.rs
@@ -5,6 +5,8 @@
 use std::fmt::{self, Display, Formatter};
 
 use allocative::Allocative;
+use either::Either;
+use providers::ProviderType;
 use starlark::{
     environment::{Methods, MethodsBuilder},
     eval::Evaluator,
@@ -14,6 +16,9 @@
 
 use crate::{AttrKind, allow_files::AllowFiles, cfg::AttrCfg};
 
+pub(crate) type ProvidersArg<'v> =
+    Either<UnpackList<UnpackList<&'v ProviderType>>, UnpackList<&'v ProviderType>>;
+
 /// The type that all parameters of attr.* get converted to.
 /// Mostly used because rust doesn't have default parameters,
 /// so we just ..Default::default() the fields that aren't used.
@@ -26,6 +31,7 @@
     pub(crate) allow_single_file: Option<AllowFiles>,
     pub(crate) cfg: Option<AttrCfg>,
     pub(crate) doc: Option<NoneOr<String>>,
+    pub(crate) providers: Option<ProvidersArg<'v>>,
 }
 
 /// The Starlark `attr` module containing functions to declare rule attributes.
@@ -127,6 +133,7 @@
         allow_files: Option<AllowFiles>,
         allow_single_file: Option<AllowFiles>,
         cfg: Option<AttrCfg>,
+        providers: Option<ProvidersArg<'v>>,
         eval: &mut Evaluator<'v, '_, '_>,
     ) -> starlark::Result<Value<'v>> {
         (this.make_attr_schema)(
@@ -138,6 +145,7 @@
                 allow_files,
                 allow_single_file,
                 cfg,
+                providers,
                 ..Default::default()
             },
             eval,
@@ -151,6 +159,7 @@
         mandatory: Option<bool>,
         allow_empty: Option<bool>,
         allow_files: Option<AllowFiles>,
+        providers: Option<ProvidersArg<'v>>,
         eval: &mut Evaluator<'v, '_, '_>,
     ) -> starlark::Result<Value<'v>> {
         (this.make_attr_schema)(
@@ -161,6 +170,7 @@
                 mandatory,
                 allow_empty,
                 allow_files,
+                providers,
                 ..Default::default()
             },
             eval,
@@ -175,6 +185,7 @@
         allow_empty: Option<bool>,
         allow_files: Option<AllowFiles>,
         cfg: Option<AttrCfg>,
+        providers: Option<ProvidersArg<'v>>,
         eval: &mut Evaluator<'v, '_, '_>,
     ) -> starlark::Result<Value<'v>> {
         (this.make_attr_schema)(
@@ -186,6 +197,7 @@
                 allow_empty,
                 allow_files,
                 cfg,
+                providers,
                 ..Default::default()
             },
             eval,
@@ -200,6 +212,7 @@
         allow_empty: Option<bool>,
         allow_files: Option<AllowFiles>,
         cfg: Option<AttrCfg>,
+        providers: Option<ProvidersArg<'v>>,
         eval: &mut Evaluator<'v, '_, '_>,
     ) -> starlark::Result<Value<'v>> {
         (this.make_attr_schema)(
@@ -211,6 +224,7 @@
                 allow_empty,
                 allow_files,
                 cfg,
+                providers,
                 ..Default::default()
             },
             eval,
@@ -268,6 +282,7 @@
         allow_empty: Option<bool>,
         allow_files: Option<AllowFiles>,
         cfg: Option<AttrCfg>,
+        providers: Option<ProvidersArg<'v>>,
         eval: &mut Evaluator<'v, '_, '_>,
     ) -> starlark::Result<Value<'v>> {
         (this.make_attr_schema)(
@@ -279,6 +294,7 @@
                 allow_empty,
                 allow_files,
                 cfg,
+                providers,
                 ..Default::default()
             },
             eval,
@@ -335,7 +351,7 @@
     use super::*;
     use crate::AttrSchema;
 
-    fn make_attr_schema<'v>(
+    pub(crate) fn make_attr_schema<'v>(
         kind: crate::AttrKind,
         args: AttrSpecArgs<'v>,
         eval: &mut Evaluator<'v, '_, '_>,
@@ -354,6 +370,7 @@
         let mut assert = Assert::new();
         assert.globals_add(|builder| {
             builder.set("attr", super::AttrModule { make_attr_schema });
+            providers::register_providers(builder);
         });
         assert
     }
diff --git a/src/gn/starlark/crates/attr/src/schema.rs b/src/gn/starlark/crates/attr/src/schema.rs
index 2edfb00..53e6ded 100644
--- a/src/gn/starlark/crates/attr/src/schema.rs
+++ b/src/gn/starlark/crates/attr/src/schema.rs
@@ -8,6 +8,8 @@
 };
 
 use allocative::Allocative;
+use either::Either;
+use providers::ProviderType;
 use starlark::{
     eval::ParametersSpecParam,
     starlark_simple_value,
@@ -58,6 +60,8 @@
     pub(crate) disallow_empty: bool,
     pub(crate) allow_files: AllowFilesSchema,
     pub(crate) cfg: AttrCfg,
+    // The outer layer represents ANY while the inner layer represents ALL.
+    pub(crate) providers: Vec<Vec<ProviderType>>,
     pub(crate) doc: String,
 }
 
@@ -106,6 +110,22 @@
                 _ => return Err(crate::Error::AllowFilesMutuallyExclusive.into()),
             },
             cfg: args.cfg.unwrap_or(AttrCfg::CurrentToolchain),
+            providers: match args.providers {
+                None => Vec::new(),
+                // `Left` precedes `Right` in `ProvidersArg` so `providers = []`
+                // unpacks here as zero groups rather than `vec![vec![]]`.
+                Some(Either::Left(lists)) => {
+                    if lists.items.iter().any(|ps| ps.items.is_empty()) {
+                        return Err(crate::Error::EmptyProviderGroup.into());
+                    }
+                    lists
+                        .items
+                        .into_iter()
+                        .map(|ps| ps.items.into_iter().cloned().collect())
+                        .collect()
+                },
+                Some(Either::Right(ps)) => vec![ps.items.into_iter().cloned().collect()],
+            },
             doc: match args.doc {
                 None | Some(NoneOr::None) => String::new(),
                 Some(NoneOr::Other(s)) => s,
@@ -179,6 +199,7 @@
             || self.disallow_empty != child.disallow_empty
             || self.allow_files != child.allow_files
             || self.cfg != child.cfg
+            || self.providers != child.providers
         {
             return Err(crate::Error::AttributeTypeMismatch(name.to_owned()).into());
         }
@@ -241,6 +262,7 @@
                 disallow_empty: false,
                 allow_files: AllowFilesSchema::None,
                 cfg: AttrCfg::CurrentToolchain,
+                providers: Vec::new(),
                 doc: String::new(),
             },
         );
@@ -261,6 +283,7 @@
                 disallow_empty: false,
                 allow_files: AllowFilesSchema::None,
                 cfg: AttrCfg::CurrentToolchain,
+                providers: Vec::new(),
                 doc: "An integer".to_string(),
             },
         );
@@ -286,6 +309,7 @@
                 disallow_empty: false,
                 allow_files: AllowFilesSchema::None,
                 cfg: AttrCfg::CurrentToolchain,
+                providers: Vec::new(),
                 doc: String::new(),
             },
         );
@@ -314,6 +338,7 @@
                 disallow_empty: false,
                 allow_files: AllowFilesSchema::Many(AllowFiles::All),
                 cfg: AttrCfg::CurrentToolchain,
+                providers: Vec::new(),
                 doc: String::new(),
             },
         );
@@ -327,6 +352,7 @@
                 disallow_empty: false,
                 allow_files: AllowFilesSchema::None,
                 cfg: AttrCfg::CurrentToolchain,
+                providers: Vec::new(),
                 doc: String::new(),
             },
         );
@@ -345,6 +371,7 @@
                 disallow_empty: true,
                 allow_files: AllowFilesSchema::None,
                 cfg: AttrCfg::CurrentToolchain,
+                providers: Vec::new(),
                 doc: String::new(),
             },
         );
@@ -372,6 +399,7 @@
                 disallow_empty: false,
                 allow_files: AllowFilesSchema::None,
                 cfg: AttrCfg::CurrentToolchain,
+                providers: Vec::new(),
                 doc: String::new(),
             },
         );
@@ -420,6 +448,7 @@
                 disallow_empty: false,
                 allow_files: AllowFilesSchema::Many(AllowFiles::All),
                 cfg: AttrCfg::CurrentToolchain,
+                providers: Vec::new(),
                 doc: String::new(),
             },
         );
diff --git a/src/gn/starlark/crates/attr/src/value.rs b/src/gn/starlark/crates/attr/src/value.rs
index 2dc9fa0..abca267 100644
--- a/src/gn/starlark/crates/attr/src/value.rs
+++ b/src/gn/starlark/crates/attr/src/value.rs
@@ -3,11 +3,12 @@
 // found in the LICENSE file.
 
 use allocative::Allocative;
+use providers::ProviderType;
 use starlark::{
     collections::{SmallMap, SmallSet},
     values::{Heap, Value, dict::Dict},
 };
-use types::{File, LabelRef, TargetRef as _};
+use types::{File, LabelRef, TargetRef};
 
 use crate::{Attr, Session, schema::AttrSchema};
 
@@ -202,6 +203,7 @@
         match lf {
             crate::LabelOrFile::Label(lbl) => {
                 let target = session.get_target(lbl.as_ref(), *current_toolchain);
+                verify_providers(&target, &schema.providers)?;
                 if let Some(matcher) = schema.file_matcher()
                     && let crate::allow_files::AllowFiles::Some(exts) = matcher
                     && !target.outputs().iter().any(|f| matcher.matches(f.as_str()))
@@ -229,6 +231,37 @@
     }
 }
 
+fn verify_providers(dep: &impl TargetRef, required: &[Vec<ProviderType>]) -> starlark::Result<()> {
+    if required.is_empty()
+        || required
+            .iter()
+            .any(|group| group.iter().all(|p| dep.has_provider(p.id())))
+    {
+        return Ok(());
+    }
+    let missing = required
+        .iter()
+        .map(|group| {
+            let mut names: Vec<_> = group
+                .iter()
+                .filter(|p| !dep.has_provider(p.id()))
+                .map(|p| format!("'{p}'"))
+                .collect();
+            if names.len() == 1 {
+                names.pop().unwrap()
+            } else {
+                format!("({})", names.join(" and "))
+            }
+        })
+        .collect::<Vec<_>>()
+        .join(" or ");
+    Err(crate::Error::MissingRequiredProviders {
+        target: dep.label().to_owned(),
+        missing,
+    }
+    .into())
+}
+
 #[cfg(test)]
 mod tests {
     use starlark::{
@@ -254,6 +287,7 @@
             disallow_empty: false,
             allow_files: AllowFilesSchema::None,
             cfg: AttrCfg::CurrentToolchain,
+            providers: Vec::new(),
             doc: String::new(),
         };
 
@@ -291,6 +325,7 @@
             disallow_empty: false,
             allow_files: AllowFilesSchema::None,
             cfg: AttrCfg::CurrentToolchain,
+            providers: Vec::new(),
             doc: String::new(),
         };
 
@@ -363,6 +398,7 @@
             disallow_empty: false,
             allow_files: AllowFilesSchema::Many(AllowFiles::All),
             cfg: AttrCfg::CurrentToolchain,
+            providers: Vec::new(),
             doc: String::new(),
         };
 
@@ -426,6 +462,7 @@
             disallow_empty: false,
             allow_files: AllowFilesSchema::Single(AllowFiles::All),
             cfg: AttrCfg::CurrentToolchain,
+            providers: Vec::new(),
             doc: String::new(),
         };
 
@@ -545,6 +582,7 @@
             disallow_empty: false,
             allow_files: AllowFilesSchema::None,
             cfg: AttrCfg::CurrentToolchain,
+            providers: Vec::new(),
             doc: String::new(),
         };
 
@@ -598,6 +636,7 @@
             disallow_empty: false,
             allow_files: AllowFilesSchema::Many(AllowFiles::Some(vec![".cc".to_owned()])),
             cfg: AttrCfg::CurrentToolchain,
+            providers: Vec::new(),
             doc: String::new(),
         };
 
diff --git a/src/gn/starlark/crates/ffi/src/target_ref.rs b/src/gn/starlark/crates/ffi/src/target_ref.rs
index 3f0c043..fef7852 100644
--- a/src/gn/starlark/crates/ffi/src/target_ref.rs
+++ b/src/gn/starlark/crates/ffi/src/target_ref.rs
@@ -188,6 +188,13 @@
         }
         attrs
     }
+
+    fn has_provider(&self, id: types::ProviderId) -> bool {
+        self.0
+            .evaluated
+            .get()
+            .is_some_and(|evaluated| evaluated.by_ref(|e| e.providers.contains_id(id)))
+    }
 }
 
 impl attr::TargetAttrExt for TargetRef {
diff --git a/src/gn/starlark/crates/providers/src/lib.rs b/src/gn/starlark/crates/providers/src/lib.rs
index cb2eeb3..0e6d0ab 100644
--- a/src/gn/starlark/crates/providers/src/lib.rs
+++ b/src/gn/starlark/crates/providers/src/lib.rs
@@ -13,5 +13,6 @@
 pub(crate) use errors::Error;
 pub use globals::register_providers;
 pub use provider_instance::ProviderInstance;
-pub use provider_type::{ProviderId, ProviderType};
+pub use provider_type::ProviderType;
 pub use providers::Providers;
+pub use types::ProviderId;
diff --git a/src/gn/starlark/crates/providers/src/provider_type.rs b/src/gn/starlark/crates/providers/src/provider_type.rs
index 25ac688..bbfd002 100644
--- a/src/gn/starlark/crates/providers/src/provider_type.rs
+++ b/src/gn/starlark/crates/providers/src/provider_type.rs
@@ -5,10 +5,7 @@
 use std::{
     fmt,
     fmt::{Debug, Display},
-    sync::{
-        OnceLock,
-        atomic::{AtomicU64, Ordering},
-    },
+    sync::OnceLock,
 };
 
 use allocative::Allocative;
@@ -23,31 +20,10 @@
     },
 };
 use starlark_derive::{NoSerialize, Trace, starlark_value};
+use types::ProviderId;
 
 use crate::{Error, ProviderInstance};
 
-/// A unique identifier for a provider type within a GN build session.
-#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Allocative, Freeze, Trace)]
-pub struct ProviderId(pub(crate) u64);
-
-impl ProviderId {
-    /// Generates a new unique `ProviderId`.
-    ///
-    /// A process-wide counter is fine here because all we care about is that these type IDs are
-    /// distinct Provider IDs are also not persisted anywhere so we don't have nondeterminism
-    /// concerns.
-    pub fn next() -> Self {
-        // Built-in provider IDs are u8s, so starting at 256 is safe
-        static NEXT_ID: AtomicU64 = AtomicU64::new(256);
-        Self(NEXT_ID.fetch_add(1, Ordering::Relaxed))
-    }
-
-    /// Constant constructor for built-in providers.
-    pub const fn builtin(id: u8) -> Self {
-        Self(id as u64)
-    }
-}
-
 #[derive(Allocative, Clone, Debug, Trace)]
 // Contains all the information we cannot know about a provider type until we
 // actually know the name of it.
@@ -73,6 +49,14 @@
 
 starlark_simple_value!(ProviderType);
 
+impl PartialEq for ProviderType {
+    fn eq(&self, other: &Self) -> bool {
+        self.id == other.id
+    }
+}
+
+impl Eq for ProviderType {}
+
 impl Display for ProviderType {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(
diff --git a/src/gn/starlark/crates/rule/src/errors.rs b/src/gn/starlark/crates/rule/src/errors.rs
index 01d0d97..ab26f72 100644
--- a/src/gn/starlark/crates/rule/src/errors.rs
+++ b/src/gn/starlark/crates/rule/src/errors.rs
@@ -2,7 +2,6 @@
 // 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.
@@ -31,7 +30,7 @@
     MissingProvider {
         rule: String,
         target: Label,
-        provider: ProviderType,
+        provider: providers::ProviderType,
     },
 }
 
diff --git a/src/gn/starlark/crates/rule/src/implementation.rs b/src/gn/starlark/crates/rule/src/implementation.rs
index a5bbf74..1f6e70d 100644
--- a/src/gn/starlark/crates/rule/src/implementation.rs
+++ b/src/gn/starlark/crates/rule/src/implementation.rs
@@ -77,15 +77,16 @@
             let actions = eval
                 .heap()
                 .alloc_typed(crate::actions::Actions::<C>::default());
+            let ctx_fields = rule.schema.create_ctx_fields(
+                target.attrs(),
+                rule_context.session(),
+                &rule_context.current_toolchain(),
+                rule.output_type,
+                target.builtin_attrs(rule_context.session(), &eval.heap()),
+                &eval.heap(),
+            )?;
             let ctx = eval.heap().alloc(Ctx::<C>::new(
-                rule.schema.create_ctx_fields(
-                    target.attrs(),
-                    rule_context.session(),
-                    &rule_context.current_toolchain(),
-                    rule.output_type,
-                    target.builtin_attrs(rule_context.session(), &eval.heap()),
-                    &eval.heap(),
-                )?,
+                ctx_fields,
                 rule,
                 eval.heap().alloc(target.label().to_owned()),
                 actions.to_value(),
diff --git a/src/gn/starlark/crates/rule/tests/frozen_rule.rs b/src/gn/starlark/crates/rule/tests/frozen_rule.rs
index 1306b71..d9efea8 100644
--- a/src/gn/starlark/crates/rule/tests/frozen_rule.rs
+++ b/src/gn/starlark/crates/rule/tests/frozen_rule.rs
@@ -99,6 +99,7 @@
             rule: rule(&native, "custom_shared_library"),
             cxx_attrs: unknown_attrs.clone(),
             dependencies: HashSet::new(),
+            evaluated: Default::default(),
         }
     );
 
@@ -113,6 +114,7 @@
             rule: rule(&native, "static_library"),
             cxx_attrs: unknown_attrs.clone(),
             dependencies: HashSet::new(),
+            evaluated: Default::default(),
         }
     );
 
@@ -141,6 +143,7 @@
                 Label::new(PackageRef::root().to_owned(), "parent".to_owned()),
                 toolchain.clone(),
             )]),
+            evaluated: Default::default(),
         }
     );
 
@@ -165,6 +168,7 @@
                 Label::new(PackageRef::root().to_owned(), "child".to_owned()),
                 toolchain.clone(),
             )]),
+            evaluated: Default::default(),
         }
     );
 
@@ -189,6 +193,7 @@
                 Label::new(PackageRef::root().to_owned(), "custom_val".to_owned()),
                 toolchain.clone(),
             )]),
+            evaluated: Default::default(),
         }
     );
 }
diff --git a/src/gn/starlark/crates/rule/tests/providers.rs b/src/gn/starlark/crates/rule/tests/providers.rs
index 4bae4f3..e35ce62 100644
--- a/src/gn/starlark/crates/rule/tests/providers.rs
+++ b/src/gn/starlark/crates/rule/tests/providers.rs
@@ -91,3 +91,159 @@
         }
     }
 }
+
+#[test]
+fn test_required_providers() {
+    let mut assert = Assert::new_rule_assert();
+    let module = assert.module(
+        "//pkg:req_rules.scl",
+        r#"
+FooInfo = provider(fields = ["x"])
+BarInfo = provider(fields = ["y"])
+BazInfo = provider(fields = ["z"])
+
+def _impl(ctx):
+    providers = {
+        "FooInfo": FooInfo(),
+        "BarInfo": BarInfo(),
+        "BazInfo": BazInfo(),
+    }
+    return [providers[name] for name in ctx.attr.providers]
+
+provides = rule(
+    implementation = _impl,
+    attrs = {"providers": attr.string_list()},
+)
+
+def _impl(ctx):
+    return []
+
+req_rule = rule(
+    implementation = _impl,
+    attrs = {
+        "dep": attr.label(allow_files = True, providers = [FooInfo, BarInfo]),
+        "or_dep": attr.label(providers = [[FooInfo], [BarInfo, BazInfo]]),
+        "label_list": attr.label_list(providers = [FooInfo]),
+        "label_keyed_dict": attr.label_keyed_string_dict(providers = [FooInfo]),
+        "label_list_dict": attr.label_list_dict(providers = [FooInfo]),
+        "string_keyed_dict": attr.string_keyed_label_dict(providers = [FooInfo]),
+    },
+)
+"#,
+    );
+    assert.module_add(module);
+    assert.pass(
+        r#"
+load("//pkg:req_rules.scl", "provides", "req_rule")
+
+provides(name = "none")
+provides(name = "foo", providers = ["FooInfo"])
+provides(name = "bar", providers = ["BarInfo"])
+provides(name = "baz", providers = ["BazInfo"])
+provides(name = "foo_bar", providers = ["FooInfo", "BarInfo"])
+provides(name = "bar_baz", providers = ["BarInfo", "BazInfo"])
+
+req_rule(
+    name = "all_ok",
+    dep = ":foo_bar",
+    or_dep = ":foo",
+    label_list = [":foo"],
+    label_keyed_dict = {":foo": "k"},
+    label_list_dict = {"k": [":foo"]},
+    string_keyed_dict = {"k": ":foo"},
+)
+req_rule(name = "defaults_ok")
+req_rule(name = "file_ok", dep = "foo/file.cc")
+req_rule(name = "or_bar_baz_ok", or_dep = ":bar_baz")
+
+req_rule(name = "single_missing", dep = ":foo")
+req_rule(name = "single_missing_both", dep = ":none")
+req_rule(name = "or_missing", or_dep = ":none")
+req_rule(name = "or_partial_missing", or_dep = ":bar")
+req_rule(name = "list_missing", label_list = [":none"])
+req_rule(name = "keyed_missing", label_keyed_dict = {":none": "k"})
+req_rule(name = "list_dict_missing", label_list_dict = {"k": [":none"]})
+req_rule(name = "string_keyed_missing", string_keyed_dict = {"k": ":none"})
+"#,
+    );
+
+    let context = assert.context();
+    for (name, expected_err) in [
+        ("none", None),
+        ("foo", None),
+        ("bar", None),
+        ("baz", None),
+        ("foo_bar", None),
+        ("bar_baz", None),
+        ("all_ok", None),
+        ("defaults_ok", None),
+        ("file_ok", None),
+        ("or_bar_baz_ok", None),
+        (
+            "single_missing",
+            Some(
+                "for attribute `dep`: target `//:foo` does not have mandatory providers: 'BarInfo'",
+            ),
+        ),
+        (
+            "single_missing_both",
+            Some(
+                "for attribute `dep`: target `//:none` does not have mandatory providers: ('FooInfo' and 'BarInfo')",
+            ),
+        ),
+        (
+            "or_missing",
+            Some(
+                "for attribute `or_dep`: target `//:none` does not have mandatory providers: 'FooInfo' or ('BarInfo' and 'BazInfo')",
+            ),
+        ),
+        (
+            "or_partial_missing",
+            Some(
+                "for attribute `or_dep`: target `//:bar` does not have mandatory providers: 'FooInfo' or 'BazInfo'",
+            ),
+        ),
+        (
+            "list_missing",
+            Some(
+                "for attribute `label_list`: target `//:none` does not have mandatory providers: 'FooInfo'",
+            ),
+        ),
+        (
+            "keyed_missing",
+            Some(
+                "for attribute `label_keyed_dict`: target `//:none` does not have mandatory providers: 'FooInfo'",
+            ),
+        ),
+        (
+            "list_dict_missing",
+            Some(
+                "for attribute `label_list_dict`: target `//:none` does not have mandatory providers: 'FooInfo'",
+            ),
+        ),
+        (
+            "string_keyed_missing",
+            Some(
+                "for attribute `string_keyed_dict`: target `//:none` does not have mandatory providers: 'FooInfo'",
+            ),
+        ),
+    ] {
+        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 => {
+                target
+                    .evaluated
+                    .set(res.unwrap())
+                    .expect("target evaluated twice");
+            },
+            Some(expected) => assert_eq!(format!("{:#}", res.unwrap_err()), expected),
+        }
+    }
+}
diff --git a/src/gn/starlark/crates/testutils/src/eval_context.rs b/src/gn/starlark/crates/testutils/src/eval_context.rs
index 900f3ed..251f8b1 100644
--- a/src/gn/starlark/crates/testutils/src/eval_context.rs
+++ b/src/gn/starlark/crates/testutils/src/eval_context.rs
@@ -159,6 +159,7 @@
             cxx_attrs: scope.0.clone(),
             outputs: vec![],
             attrs: vec![],
+            evaluated: Default::default(),
         };
         let mut targets = self.session.targets_under_construction.borrow_mut();
         targets.push(Box::new(target));
diff --git a/src/gn/starlark/crates/testutils/src/session.rs b/src/gn/starlark/crates/testutils/src/session.rs
index afa4b42..4304831 100644
--- a/src/gn/starlark/crates/testutils/src/session.rs
+++ b/src/gn/starlark/crates/testutils/src/session.rs
@@ -85,6 +85,7 @@
             rule: self.default_rule(),
             cxx_attrs: Default::default(),
             dependencies: Default::default(),
+            evaluated: Default::default(),
         }
     }
 
diff --git a/src/gn/starlark/crates/testutils/src/target.rs b/src/gn/starlark/crates/testutils/src/target.rs
index 8b8b005..20c1c79 100644
--- a/src/gn/starlark/crates/testutils/src/target.rs
+++ b/src/gn/starlark/crates/testutils/src/target.rs
@@ -5,14 +5,14 @@
 use std::{
     collections::{HashMap, HashSet},
     ops::Deref,
-    sync::Arc,
+    sync::{Arc, OnceLock},
 };
 
 use allocative::Allocative;
 use attr::Attr;
 use starlark::{
     starlark_simple_value,
-    values::{Heap, ProvidesStaticType, StarlarkValue, Value},
+    values::{Heap, OwnedFrozen, ProvidesStaticType, StarlarkValue, Value, ValueTyped},
 };
 use starlark_derive::{NoSerialize, starlark_value};
 use types::{File, IPromiseToImplementStarlarkEqAndHash, Label, LabelRef, OutputType, TargetRef};
@@ -35,6 +35,9 @@
     /// Registered target dependencies.
     #[allocative(skip)]
     pub dependencies: HashSet<(Label, Label)>,
+    /// Cached rule evaluation result containing returned providers.
+    #[allocative(skip)]
+    pub evaluated: OnceLock<OwnedFrozen<ValueTyped<'static, rule::EvaluatedTarget<'static>>>>,
 }
 
 impl PartialEq for FakeTarget {
@@ -169,6 +172,13 @@
             })
             .unwrap_or_default()
     }
+
+    fn has_provider(&self, id: types::ProviderId) -> bool {
+        self.get()
+            .evaluated
+            .get()
+            .is_some_and(|evaluated| evaluated.by_ref(|e| e.providers.contains_id(id)))
+    }
 }
 
 impl types::TargetMut for FakeTarget {
diff --git a/src/gn/starlark/crates/types/src/lib.rs b/src/gn/starlark/crates/types/src/lib.rs
index 2419311..c86a0a7 100644
--- a/src/gn/starlark/crates/types/src/lib.rs
+++ b/src/gn/starlark/crates/types/src/lib.rs
@@ -12,6 +12,7 @@
 pub mod package;
 pub mod package_ref;
 pub mod path_resolver;
+pub mod provider_id;
 pub mod scope;
 pub mod session;
 pub mod target_ref;
@@ -28,6 +29,7 @@
 pub use package::Package;
 pub use package_ref::PackageRef;
 pub use path_resolver::PathResolver;
+pub use provider_id::ProviderId;
 pub use scope::Scope;
 pub use session::Session;
 pub use target_ref::{IPromiseToImplementStarlarkEqAndHash, TargetMut, TargetRef};
diff --git a/src/gn/starlark/crates/types/src/provider_id.rs b/src/gn/starlark/crates/types/src/provider_id.rs
new file mode 100644
index 0000000..855f36f
--- /dev/null
+++ b/src/gn/starlark/crates/types/src/provider_id.rs
@@ -0,0 +1,30 @@
+// 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 std::sync::atomic::{AtomicU64, Ordering};
+
+use allocative::Allocative;
+use starlark::values::{Freeze, Trace};
+
+/// A unique identifier for a provider type within a GN build session.
+#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Allocative, Freeze, Trace)]
+pub struct ProviderId(u64);
+
+impl ProviderId {
+    /// Generates a new unique `ProviderId`.
+    ///
+    /// A process-wide counter is fine here because all we care about is that
+    /// these type IDs are distinct. Provider IDs are also not persisted
+    /// anywhere so we don't have nondeterminism concerns.
+    pub fn next() -> Self {
+        // Built-in provider IDs are u8s, so starting at 256 is safe.
+        static NEXT_ID: AtomicU64 = AtomicU64::new(256);
+        Self(NEXT_ID.fetch_add(1, Ordering::Relaxed))
+    }
+
+    /// Constant constructor for built-in providers.
+    pub const fn builtin(id: u8) -> Self {
+        Self(id as u64)
+    }
+}
diff --git a/src/gn/starlark/crates/types/src/target_ref.rs b/src/gn/starlark/crates/types/src/target_ref.rs
index 48ee3fc..b74b2ad 100644
--- a/src/gn/starlark/crates/types/src/target_ref.rs
+++ b/src/gn/starlark/crates/types/src/target_ref.rs
@@ -4,7 +4,7 @@
 
 use starlark::values::{AllocValue, Heap, StarlarkValue, Value};
 
-use crate::{File, LabelRef, OutputType, Session};
+use crate::{File, LabelRef, OutputType, ProviderId, Session};
 
 /// Unfortunately while we could specify that Eq and Hash are implemented, there
 /// is no way to delegate starlark's equality and hash function to it
@@ -40,6 +40,9 @@
 
     /// Returns the resolved built-in attributes as Starlark values.
     fn builtin_attrs<'v>(&self, session: &Self::Session, heap: &Heap<'v>) -> Vec<Value<'v>>;
+
+    /// Returns `true` if this target provides the given provider type.
+    fn has_provider(&self, id: ProviderId) -> bool;
 }
 
 /// A trait for mutating a target before it is registered in the session.