script: Limit public exports. (#34915)

* script: Restrict reexport visibility of DOM types.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* script: Mass pub->pub(crate) conversion.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* script: Hide existing dead code warnings.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* Formatting.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* Fix clippy warnings.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* Formatting.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* Fix unit tests.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* Fix clippy.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* More formatting.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

---------

Signed-off-by: Josh Matthews <josh@joshmatthews.net>
This commit is contained in:
Josh Matthews 2025-01-10 03:19:19 -05:00 committed by GitHub
parent f220d6d3a5
commit c94d909a86
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
585 changed files with 5411 additions and 5013 deletions

View file

@ -2281,7 +2281,7 @@ class CGTemplatedType(CGWrapper):
class CGNamespace(CGWrapper):
def __init__(self, namespace, child, public=False):
pub = "pub " if public else ""
pub = "pub(crate) " if public else ""
pre = f"{pub}mod {namespace} {{\n"
post = f"}} // mod {namespace}"
CGWrapper.__init__(self, child, pre=pre, post=post)
@ -2656,7 +2656,7 @@ def DomTypes(descriptors, descriptorProvider, dictionaries, callbacks, typedefs,
"Sized",
]
joinedTraits = ' + '.join(traits)
elements = [CGGeneric(f"pub trait DomTypes: {joinedTraits} where Self: 'static {{\n")]
elements = [CGGeneric(f"pub(crate) trait DomTypes: {joinedTraits} where Self: 'static {{\n")]
for descriptor in descriptors:
iface_name = descriptor.interface.identifier.name
traits = []
@ -2737,7 +2737,7 @@ def DomTypeHolder(descriptors, descriptorProvider, dictionaries, callbacks, type
elements = [
CGGeneric(
"#[derive(JSTraceable, MallocSizeOf, PartialEq)]\n"
"pub struct DomTypeHolder;\n"
"pub(crate) struct DomTypeHolder;\n"
"impl crate::DomTypes for DomTypeHolder {\n"
),
]
@ -4882,7 +4882,7 @@ class CGEnum(CGThing):
decl = f"""
#[repr(usize)]
#[derive({derives})]
pub enum {ident} {{
pub(crate) enum {ident} {{
{enums}
}}
"""
@ -4900,12 +4900,12 @@ use js::rust::HandleValue;
use js::rust::MutableHandleValue;
use js::jsval::JSVal;
pub const pairs: &[(&str, super::{ident})] = &[
pub(crate) const pairs: &[(&str, super::{ident})] = &[
{pairs},
];
impl super::{ident} {{
pub fn as_str(&self) -> &'static str {{
pub(crate) fn as_str(&self) -> &'static str {{
pairs[*self as usize].0
}}
}}
@ -4994,7 +4994,7 @@ class CGConstant(CGThing):
elif tag == IDLType.Tags.double:
const_type = "f64"
return f"pub const {name}: {const_type} = {value};\n"
return f"pub(crate) const {name}: {const_type} = {value};\n"
def getUnionTypeTemplateVars(type, descriptorProvider):
@ -5093,7 +5093,7 @@ class CGUnionStruct(CGThing):
derives = ["JSTraceable"] + self.derives
return f"""
#[derive({", ".join(derives)})]
pub enum {self.type} {{
pub(crate) enum {self.type} {{
{joinedEnumValues}
}}
@ -5468,7 +5468,7 @@ class ClassConstructor(ClassItem):
body = f' {{\n{body}}}'
return f"""
pub unsafe fn {self.getDecorators(True)}new({args}) -> Rc<{cgClass.getNameString()}>{body}
pub(crate) unsafe fn {self.getDecorators(True)}new({args}) -> Rc<{cgClass.getNameString()}>{body}
"""
def define(self, cgClass):
@ -5560,7 +5560,7 @@ class CGClass(CGThing):
myself = ''
if self.decorators != '':
myself += f'{self.decorators}\n'
myself += f'{self.indent}pub struct {self.name}{specialization}'
myself += f'{self.indent}pub(crate) struct {self.name}{specialization}'
result += myself
assert len(self.bases) == 1 # XXjdm Can we support multiple inheritance?
@ -5568,7 +5568,7 @@ class CGClass(CGThing):
result += ' {\n'
if self.bases:
self.members = [ClassMember("parent", self.bases[0].name, "pub")] + self.members
self.members = [ClassMember("parent", self.bases[0].name, "pub(crate)")] + self.members
result += CGIndenter(CGGeneric(self.extradeclarations),
len(self.indent)).define()
@ -6628,8 +6628,9 @@ class CGInterfaceTrait(CGThing):
methods.append(CGGeneric("fn Length(&self) -> u32;\n"))
if methods:
name = descriptor.interface.identifier.name
self.cgRoot = CGWrapper(CGIndenter(CGList(methods, "")),
pre=f"pub trait {descriptor.interface.identifier.name}Methods<D: DomTypes> {{\n",
pre=f"pub(crate) trait {name}Methods<D: DomTypes> {{\n",
post="}")
else:
self.cgRoot = CGGeneric("")
@ -6950,7 +6951,8 @@ class CGDescriptor(CGThing):
if reexports:
reexports = ', '.join([reexportedName(name) for name in reexports])
cgThings = CGList([CGGeneric(f'pub use self::{toBindingNamespace(descriptor.name)}::{{{reexports}}};'),
namespace = toBindingNamespace(descriptor.name)
cgThings = CGList([CGGeneric(f'pub(crate) use self::{namespace}::{{{reexports}}};'),
cgThings], '\n')
self.cgRoot = cgThings
@ -6972,7 +6974,7 @@ class CGNonNamespacedEnum(CGThing):
# Build the enum body.
joinedEntries = ',\n'.join(entries)
enumstr = f"{comment}pub enum {enumName} {{\n{joinedEntries}\n}}\n"
enumstr = f"{comment}pub(crate) enum {enumName} {{\n{joinedEntries}\n}}\n"
if repr:
enumstr = f"#[repr({repr})]\n{enumstr}"
if deriving:
@ -7025,10 +7027,10 @@ class CGDictionary(CGThing):
typeName = f"{self.makeModuleName(d.parent)}::{self.makeClassName(d.parent)}"
if type_needs_tracing(d.parent):
typeName = f"RootedTraceableBox<{typeName}>"
inheritance = f" pub parent: {typeName},\n"
inheritance = f" pub(crate) parent: {typeName},\n"
else:
inheritance = ""
memberDecls = [f" pub {self.makeMemberName(m[0].identifier.name)}: {self.getMemberType(m)},"
memberDecls = [f" pub(crate) {self.makeMemberName(m[0].identifier.name)}: {self.getMemberType(m)},"
for m in self.memberInfo]
derive = ["JSTraceable"] + self.derives
@ -7069,7 +7071,7 @@ class CGDictionary(CGThing):
return (
f"#[derive({', '.join(derive)})]\n"
f"{mustRoot}"
f"pub struct {self.makeClassName(d)} {{\n"
f"pub(crate) struct {self.makeClassName(d)} {{\n"
f"{inheritance}"
f"{joinedMemberDecls}\n"
"}\n"
@ -7142,7 +7144,7 @@ class CGDictionary(CGThing):
return (
f"impl {selfName} {{\n"
f"{CGIndenter(CGGeneric(self.makeEmpty()), indentLevel=4).define()}\n"
" pub fn new(cx: SafeJSContext, val: HandleValue) \n"
" pub(crate) fn new(cx: SafeJSContext, val: HandleValue) \n"
f" -> Result<ConversionResult<{actualType}>, ()> {{\n"
f" {unsafe_if_necessary} {{\n"
" let object = if val.get().is_null_or_undefined() {\n"
@ -7246,7 +7248,7 @@ class CGDictionary(CGThing):
parentTemplate = "parent: %s::%s::empty(),\n"
fieldTemplate = "%s: %s,\n"
functionTemplate = (
"pub fn empty() -> Self {\n"
"pub(crate) fn empty() -> Self {\n"
" Self {\n"
"%s"
" }\n"
@ -7256,7 +7258,7 @@ class CGDictionary(CGThing):
parentTemplate = "dictionary.parent = %s::%s::empty();\n"
fieldTemplate = "dictionary.%s = %s;\n"
functionTemplate = (
"pub fn empty() -> RootedTraceableBox<Self> {\n"
"pub(crate) fn empty() -> RootedTraceableBox<Self> {\n"
" let mut dictionary = RootedTraceableBox::new(Self::default());\n"
"%s"
" dictionary\n"
@ -7341,14 +7343,14 @@ class CGRegisterProxyHandlers(CGThing):
def __init__(self, config):
descriptors = config.getDescriptors(proxy=True)
body = "".join(
f" pub static {desc.name}: std::sync::atomic::AtomicPtr<libc::c_void> =\n"
f" pub(crate) static {desc.name}: std::sync::atomic::AtomicPtr<libc::c_void> =\n"
" std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());\n"
for desc in descriptors
)
self.root = CGList([
CGGeneric(
"#[allow(non_upper_case_globals)]\n"
"pub mod proxy_handlers {\n"
"pub(crate) mod proxy_handlers {\n"
f"{body}}}\n"
),
CGRegisterProxyHandlersMethod(descriptors),
@ -7400,9 +7402,9 @@ class CGBindingRoot(CGThing):
if t.innerType.isUnion() and not t.innerType.nullable():
# Allow using the typedef's name for accessing variants.
typeDefinition = f"pub use self::{type} as {name};"
typeDefinition = f"pub(crate) use self::{type} as {name};"
else:
typeDefinition = f"pub type {name} = {type};"
typeDefinition = f"pub(crate) type {name} = {type};"
cgthings.append(CGGeneric(typeDefinition))
@ -8207,7 +8209,6 @@ class GlobalGenRoots():
"crate::dom::bindings::codegen",
"crate::script_runtime::JSContext",
"js::rust::HandleObject",
"phf",
]
imports = CGList([CGGeneric(f"use {mod};") for mod in mods], "\n")
@ -8220,7 +8221,7 @@ class GlobalGenRoots():
global_flags = CGWrapper(CGIndenter(CGList([
CGGeneric(f"const {args[0]} = {args[1]};")
for args in flags
], "\n")), pre="#[derive(Clone, Copy)]\npub struct Globals: u8 {\n", post="\n}")
], "\n")), pre="#[derive(Clone, Copy)]\npub(crate) struct Globals: u8 {\n", post="\n}")
globals_ = CGWrapper(CGIndenter(global_flags), pre="bitflags::bitflags! {\n", post="\n}")
phf = CGGeneric("include!(concat!(env!(\"OUT_DIR\"), \"/InterfaceObjectMapPhf.rs\"));")
@ -8262,9 +8263,9 @@ class GlobalGenRoots():
return CGList([
CGGeneric(AUTOGENERATED_WARNING_COMMENT),
CGGeneric(f"pub const PROTO_OR_IFACE_LENGTH: usize = {len(protos) + len(constructors)};\n"),
CGGeneric(f"pub const MAX_PROTO_CHAIN_LENGTH: usize = {config.maxProtoChainLength};\n\n"),
CGGeneric("#[allow(clippy::enum_variant_names)]"),
CGGeneric(f"pub(crate) const PROTO_OR_IFACE_LENGTH: usize = {len(protos) + len(constructors)};\n"),
CGGeneric(f"pub(crate) const MAX_PROTO_CHAIN_LENGTH: usize = {config.maxProtoChainLength};\n\n"),
CGGeneric("#[allow(clippy::enum_variant_names, dead_code)]"),
CGNonNamespacedEnum('ID', protos, 0, deriving="PartialEq, Copy, Clone", repr="u16"),
CGNonNamespacedEnum('Constructor', constructors, len(protos),
deriving="PartialEq, Copy, Clone", repr="u16"),
@ -8273,7 +8274,7 @@ class GlobalGenRoots():
indentLevel=4),
pre=f"static INTERFACES: [&str; {len(protos)}] = [\n",
post="\n];\n\n"),
CGGeneric("pub fn proto_id_to_name(proto_id: u16) -> &'static str {\n"
CGGeneric("pub(crate) fn proto_id_to_name(proto_id: u16) -> &'static str {\n"
" debug_assert!(proto_id < ID::Last as u16);\n"
" INTERFACES[proto_id as usize]\n"
"}\n\n"),
@ -8296,7 +8297,7 @@ class GlobalGenRoots():
for d in config.getDescriptors(register=True,
isCallback=False,
isIteratorInterface=False)])
curr = CGList([CGGeneric(f"pub use crate::dom::{name.lower()}::{MakeNativeName(name)};\n")
curr = CGList([CGGeneric(f"pub(crate) use crate::dom::{name.lower()}::{MakeNativeName(name)};\n")
for name in descriptors])
curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT)
return curr
@ -8313,7 +8314,7 @@ class GlobalGenRoots():
| set(leafModule(d) for d in config.getDictionaries()))
curr = CGList([CGGeneric(
"#[allow(clippy::derivable_impls)]\n"
f"pub mod {name};\n"
f"pub(crate) mod {name};\n"
) for name in sorted(descriptors)])
curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT)
return curr
@ -8360,17 +8361,17 @@ class GlobalGenRoots():
typeIdCode = []
topTypeVariants = [
("ID used by abstract interfaces.", "pub abstract_: ()"),
("ID used by interfaces that are not castable.", "pub alone: ()"),
("ID used by abstract interfaces.", "pub(crate) abstract_: ()"),
("ID used by interfaces that are not castable.", "pub(crate) alone: ()"),
]
topTypeVariants += [
(f"ID used by interfaces that derive from {typeName}.",
f"pub {typeName.lower()}: {typeName}TypeId")
f"pub(crate) {typeName.lower()}: {typeName}TypeId")
for typeName in topTypes
]
topTypeVariantsAsStrings = [CGGeneric(f"/// {variant[0]}\n{variant[1]},") for variant in topTypeVariants]
typeIdCode.append(CGWrapper(CGIndenter(CGList(topTypeVariantsAsStrings, "\n"), 4),
pre="#[derive(Copy)]\npub union TopTypeId {\n",
pre="#[derive(Copy)]\npub(crate) union TopTypeId {\n",
post="\n}\n\n"))
typeIdCode.append(CGGeneric("""\
@ -8393,12 +8394,12 @@ impl Clone for TopTypeId {
variants += [CGGeneric(type_id_variant(derivedName)) for derivedName in derived]
derives = "Clone, Copy, Debug, PartialEq"
typeIdCode.append(CGWrapper(CGIndenter(CGList(variants, ",\n"), 4),
pre=f"#[derive({derives})]\npub enum {base}TypeId {{\n",
pre=f"#[derive({derives})]\npub(crate) enum {base}TypeId {{\n",
post="\n}\n\n"))
if base in topTypes:
typeIdCode.append(CGGeneric(f"""
impl {base} {{
pub fn type_id(&self) -> &'static {base}TypeId {{
pub(crate) fn type_id(&self) -> &'static {base}TypeId {{
unsafe {{
&get_dom_class(self.reflector().get_jsobject().get())
.unwrap()