feat(sphinxdocs): support documenting flag scope in bzl:flag (#4488)

Bazel Starlark build flags can configure a `scope` (such as `universal`
or `project`), which determines how flag values propagate across
configurations, but `{bzl:flag}` had no way to record it.

Add a `:scope:` option to `{bzl:flag}` that renders a `Scope:` field at
the top of the flag description, and document `:scope: universal` on
universal flags in `//python/config_settings`.
diff --git a/docs/api/rules_python/python/config_settings/index.md b/docs/api/rules_python/python/config_settings/index.md
index 4d9169a..b778686 100644
--- a/docs/api/rules_python/python/config_settings/index.md
+++ b/docs/api/rules_python/python/config_settings/index.md
@@ -5,7 +5,7 @@
 
 # //python/config_settings
 
-:::{bzl:flag} add_srcs_to_runfiles
+::::{bzl:flag} add_srcs_to_runfiles
 Determines if the `srcs` of targets are added to their runfiles.
 
 More specifically, the sources added to runfiles are the `.py` files in `srcs`.
@@ -17,14 +17,16 @@
   behavior is `disabled`.
 * `disabled`: Don't add `srcs` to a target's runfiles.
 * `enabled`:  Add `srcs` to a target's runfiles.
-::::{versionadded} 0.37.0
-::::
-::::{deprecated} 0.37.0
-This is a transition flag and will be removed in a subsequent release.
-::::
+:::{versionadded} 0.37.0
 :::
+:::{deprecated} 0.37.0
+This is a transition flag and will be removed in a subsequent release.
+:::
+::::
 
 ::::{bzl:flag} build_python_zip
+:scope: universal
+
 Controls if a `py_binary/py_test` output is a self-executable zipapp.
 
 When enabled, the output of `py_binary` or `py_test` targets will be a
@@ -67,6 +69,8 @@
 ::::
 
 ::::{bzl:flag} experimental_python_import_all_repositories
+:scope: universal
+
 Controls whether repository directories are added to the import path.
 
 When enabled, the top-level directories in the runfiles root directory (which
@@ -88,7 +92,10 @@
 ::::
 
 ::::{bzl:flag} python_path
-A fallback path to use for Python for particular legacy Windows-specific code paths.
+:scope: universal
+
+A fallback path to use for Python for particular legacy Windows-specific code
+paths.
 
 Deprecated, do not use. This flag is largely a no-op and was replaced by
 toolchains. It only remains for some legacy Windows code-paths that will
@@ -105,6 +112,8 @@
 ::::
 
 :::{bzl:flag} python_version
+:scope: universal
+
 Determines the default hermetic Python toolchain version. This can be set to
 one of the values that `rules_python` maintains.
 :::
@@ -114,6 +123,8 @@
 :::
 
 ::::{bzl:flag} incompatible_default_to_explicit_init_py
+:scope: universal
+
 Controls if missing `__init__.py` files are generated or not.
 
 If false, `py_binary` and `py_test` will, for every `*.py` and `*.so` file,
@@ -442,6 +453,7 @@
 ::::
 
 ::::{bzl:flag} venvs_use_declare_symlink
+:scope: universal
 
 Determines if relative symlinks are created using `declare_symlink()` at build
 time.
diff --git a/sphinxdocs/docs/sphinx-bzl.md b/sphinxdocs/docs/sphinx-bzl.md
index c96061b..68cf23d 100644
--- a/sphinxdocs/docs/sphinx-bzl.md
+++ b/sphinxdocs/docs/sphinx-bzl.md
@@ -257,10 +257,25 @@
 
 :::::
 
-:::{rst:directive} .. bzl:flag:: target
+:::::{rst:directive} .. bzl:flag:: target
 
-Documents a flag. It has the same format as `{bzl:target}`
+Documents a flag. It has the same target format as `{bzl:target}`.
+
+Directive options:
+* `:scope:` specifies the scope of the flag (e.g., `universal` or `target`)
+
+````
+:::{bzl:flag} //foo:my_flag
+:scope: universal
+
+My docs
 :::
+````
+
+:::{versionadded} VERSION_NEXT_FEATURE
+The `:scope:` directive option was added.
+:::
+:::::
 
 ::::::{rst:directive} .. bzl:typedef:: typename
 
diff --git a/sphinxdocs/sphinxdocs/src/sphinx_bzl/bzl.py b/sphinxdocs/sphinxdocs/src/sphinx_bzl/bzl.py
index 9cef0cc..0a9eb04 100644
--- a/sphinxdocs/sphinxdocs/src/sphinx_bzl/bzl.py
+++ b/sphinxdocs/sphinxdocs/src/sphinx_bzl/bzl.py
@@ -1316,10 +1316,43 @@
 # TODO: Integrate with the option directive, since flags are options, afterall.
 # https://www.sphinx-doc.org/en/master/usage/domains/standard.html#directive-option
 class _BzlFlag(_BzlTarget):
-    """Documents a flag"""
+    """Documents a flag.
+
+    Flags can optionally have their scope specified using the `:scope:` option.
+
+    ```
+    :::{bzl:flag} foo
+    :scope: universal
+    :::
+    ```
+    """
 
     _TARGET_TYPE = _TargetType.FLAG
 
+    option_spec = _BzlTarget.option_spec | {
+        # keep-sorted start
+        "scope": docutils_directives.unchanged_required,
+        # keep-sorted end
+    }
+
+    @override
+    def transform_content(self, contentnode: addnodes.desc_content) -> None:
+        super().transform_content(contentnode)
+        scope = self.options.get("scope")
+        if not scope:
+            return
+        field = docutils_nodes.field(
+            "",
+            docutils_nodes.field_name("", _("Scope")),
+            docutils_nodes.field_body("", docutils_nodes.paragraph("", scope)),
+        )
+        if len(contentnode) > 0 and isinstance(
+            contentnode[0], docutils_nodes.field_list
+        ):
+            contentnode[0].insert(0, field)
+        else:
+            contentnode.insert(0, docutils_nodes.field_list("", field))
+
     @override
     def _get_signature_object_type(self) -> str:
         return "flag"
diff --git a/sphinxdocs/tests/sphinx_stardoc/sphinx_output_test.py b/sphinxdocs/tests/sphinx_stardoc/sphinx_output_test.py
index e6653b1..dabaea0 100644
--- a/sphinxdocs/tests/sphinx_stardoc/sphinx_output_test.py
+++ b/sphinxdocs/tests/sphinx_stardoc/sphinx_output_test.py
@@ -122,6 +122,42 @@
     def test_xrefs(self, text, href):
         self.assert_xref("xrefs", text=text, href=href)
 
+    def _find_flag_body(self, flag_id):
+        doc = self._doc_element("target")
+        for dl in doc.findall(".//dl[@class='bzl flag']"):
+            if dl.find(f"dt[@id='{flag_id}']") is not None:
+                return dl.find("dd")
+        self.fail(f"No flag found with id={flag_id!r}")
+
+    def _assert_flag_fields(self, flag_id, expected_fields, expected_paragraphs):
+        dd = self._find_flag_body(flag_id)
+        self.assertEqual(["dl", "p"], [child.tag for child in dd])
+        field_list = dd.find("dl")
+        self.assertIsNotNone(field_list)
+        dts = ["".join(dt.itertext()) for dt in field_list.findall("dt")]
+        dds = ["".join(d.itertext()).strip() for d in field_list.findall("dd")]
+        self.assertEqual(expected_fields, list(zip(dts, dds, strict=True)))
+        paragraphs = ["".join(p.itertext()).strip() for p in dd.findall("p")]
+        self.assertEqual(expected_paragraphs, paragraphs)
+
+    def test_flag_without_scope(self):
+        dd = self._find_flag_body("myflag")
+        self.assertIsNone(dd.find("dl"))
+
+    def test_flag_with_scope(self):
+        self._assert_flag_fields(
+            "scopedflag",
+            [("Scope:", "universal")],
+            ["Some doc about scopedflag"],
+        )
+
+    def test_flag_with_scope_and_existing_field_list(self):
+        self._assert_flag_fields(
+            "scopedflag_with_fields",
+            [("Scope:", "project"), ("Default:", "True")],
+            ["Some doc about scopedflag_with_fields"],
+        )
+
 
 if __name__ == "__main__":
     absltest.main()
diff --git a/sphinxdocs/tests/sphinx_stardoc/target.md b/sphinxdocs/tests/sphinx_stardoc/target.md
index 447a5ac..adf0fac 100644
--- a/sphinxdocs/tests/sphinx_stardoc/target.md
+++ b/sphinxdocs/tests/sphinx_stardoc/target.md
@@ -21,3 +21,19 @@
 :::{bzl:flag} myflag
 
 :::
+
+:::{bzl:flag} scopedflag
+:scope: universal
+
+Some doc about scopedflag
+
+:::
+
+:::{bzl:flag} scopedflag_with_fields
+:scope: project
+
+:default: True
+
+Some doc about scopedflag_with_fields
+
+:::