Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clippy: Fix warnings in generated code #31721

Merged
merged 4 commits into from Mar 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
90 changes: 49 additions & 41 deletions components/script/dom/bindings/codegen/CodegenRust.py
Expand Up @@ -420,14 +420,14 @@ def pickFirstSignature(condition, filterLambda):
caseBody.append(CGGeneric("if %s.get().is_object() {" %
(distinguishingArg)))
for idx, sig in enumerate(interfacesSigs):
caseBody.append(CGIndenter(CGGeneric("loop {")))
caseBody.append(CGIndenter(CGGeneric("'_block: {")))
type = sig[1][distinguishingIndex].type

# The argument at index distinguishingIndex can't possibly
# be unset here, because we've already checked that argc is
# large enough that we can examine this argument.
info = getJSToNativeConversionInfo(
type, descriptor, failureCode="break;", isDefinitelyObject=True)
type, descriptor, failureCode="break '_block;", isDefinitelyObject=True)
template = info.template
declType = info.declType

Expand Down Expand Up @@ -1410,7 +1410,7 @@ def define(self):
return self.converter.define()


def wrapForType(jsvalRef, result='result', successCode='return true;', pre=''):
def wrapForType(jsvalRef, result='result', successCode='true', pre=''):
"""
Reflect a Rust value into JS.

Expand Down Expand Up @@ -1672,11 +1672,11 @@ def generateGuardedArray(self, array, name, specTemplate, specTerminator,
prefableSpecs.append(
prefableTemplate % (cond, name + "_specs", len(specs) - 1))

specsArray = ("const %s_specs: &'static [&'static[%s]] = &[\n"
specsArray = ("const %s_specs: &[&[%s]] = &[\n"
+ ",\n".join(specs) + "\n"
+ "];\n") % (name, specType)

prefArray = ("const %s: &'static [Guard<&'static [%s]>] = &[\n"
prefArray = ("const %s: &[Guard<&[%s]>] = &[\n"
+ ",\n".join(prefableSpecs) + "\n"
+ "];\n") % (name, specType)
return specsArray + prefArray
Expand Down Expand Up @@ -1851,6 +1851,8 @@ def specData(m):
flags = m["flags"]
if self.unforgeable:
flags += " | JSPROP_PERMANENT | JSPROP_READONLY"
if flags != "0":
flags = f"({flags}) as u16"
if "selfHostedName" in m:
selfHostedName = '%s as *const u8 as *const libc::c_char' % str_to_const_array(m["selfHostedName"])
assert not m.get("methodInfo", True)
Expand Down Expand Up @@ -1882,7 +1884,7 @@ def specData(m):
' name: %s,\n'
' call: JSNativeWrapper { op: %s, info: %s },\n'
' nargs: %s,\n'
' flags: (%s) as u16,\n'
' flags: %s,\n'
' selfHostedName: %s\n'
' }')
specTerminator = (
Expand Down Expand Up @@ -2015,7 +2017,7 @@ def template(m):
if m["name"] == "@@toStringTag":
return """ JSPropertySpec {
name: JSPropertySpec_Name { symbol_: SymbolCode::%s as usize + 1 },
attributes_: (%s) as u8,
attributes_: (%s),
kind_: (%s),
u: JSPropertySpec_AccessorsOrValue {
value: JSPropertySpec_ValueWrapper {
Expand All @@ -2029,7 +2031,7 @@ def template(m):
"""
return """ JSPropertySpec {
name: JSPropertySpec_Name { string_: %s as *const u8 as *const libc::c_char },
attributes_: (%s) as u8,
attributes_: (%s),
kind_: (%s),
u: JSPropertySpec_AccessorsOrValue {
accessors: JSPropertySpec_AccessorsOrValue_Accessors {
Expand Down Expand Up @@ -2171,6 +2173,11 @@ def __init__(self, child, descriptors, callbacks, dictionaries, enums, typedefs,
'unused_variables',
'unused_assignments',
'unused_mut',
'clippy::approx_constant',
'clippy::let_unit_value',
'clippy::needless_return',
'clippy::too_many_arguments',
'clippy::unnecessary_cast',
]

def componentTypes(type):
Expand Down Expand Up @@ -2483,13 +2490,13 @@ def define(self):
name: %(name)s as *const u8 as *const libc::c_char,
flags:
// JSCLASS_HAS_RESERVED_SLOTS(%(slotCount)s)
(%(slotCount)s & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT,
(%(slotCount)s ) << JSCLASS_RESERVED_SLOTS_SHIFT,
cOps: 0 as *const _,
spec: ptr::null(),
ext: ptr::null(),
oOps: ptr::null(),
};
""" % {'name': name, 'slotCount': slotCount}
""" % {'name': name, 'slotCount': f"{slotCount} & JSCLASS_RESERVED_SLOTS_MASK" if slotCount > 0 else "0"}


class CGInterfaceObjectJSClass(CGThing):
Expand Down Expand Up @@ -2800,7 +2807,7 @@ def define(self):
)
post = (
"\n})());\n"
"return result"
"result"
)
body = CGWrapper(CGIndenter(body), pre=pre, post=post)

Expand Down Expand Up @@ -2956,7 +2963,7 @@ def definition_body(self):
SetProxyReservedSlot(
obj.get(),
0,
&PrivateValue(raw.as_ptr() as *const %(concreteType)s as *const libc::c_void),
&PrivateValue(raw.as_ptr() as *const libc::c_void),
);
"""
create = create % {"concreteType": self.descriptor.concreteType,
Expand All @@ -2983,7 +2990,7 @@ def definition_body(self):
JS_SetReservedSlot(
obj.get(),
DOM_OBJECT_SLOT,
&PrivateValue(raw.as_ptr() as *const %(concreteType)s as *const libc::c_void),
&PrivateValue(raw.as_ptr() as *const libc::c_void),
);
"""
create = create % {"concreteType": self.descriptor.concreteType}
Expand Down Expand Up @@ -3051,7 +3058,7 @@ def definition_body(self):
create_global_object(
cx,
&Class.base,
raw.as_ptr() as *const %(concreteType)s as *const libc::c_void,
raw.as_ptr() as *const libc::c_void,
_trace,
obj.handle_mut(),
origin);
Expand Down Expand Up @@ -3091,9 +3098,9 @@ def define(self):
depth = self.descriptor.prototypeDepth
check = "class.interface_chain[%s] == PrototypeList::ID::%s" % (depth, name)
elif self.descriptor.proxy:
check = "class as *const _ == &Class as *const _"
check = "ptr::eq(class, &Class)"
else:
check = "class as *const _ == &Class.dom_class as *const _"
check = "ptr::eq(class, &Class.dom_class)"
return """\
impl IDLInterface for %(name)s {
#[inline]
Expand All @@ -3104,7 +3111,7 @@ def define(self):

impl PartialEq for %(name)s {
fn eq(&self, other: &%(name)s) -> bool {
self as *const %(name)s == &*other
self as *const %(name)s == other
}
}
""" % {'check': check, 'name': name}
Expand Down Expand Up @@ -3268,7 +3275,7 @@ def definition_body(self):
}
""",
name=name, nameAsArray=str_to_const_array(name), conditions=ret_conditions)
ret += 'return true;\n'
ret += 'true\n'
return CGGeneric(ret)


Expand Down Expand Up @@ -3381,14 +3388,14 @@ def definition_body(self):
code.append(CGGeneric("""
rooted!(in(*cx) let mut prototype = ptr::null_mut::<JSObject>());
create_interface_prototype_object(cx,
global.into(),
prototype_proto.handle().into(),
global,
prototype_proto.handle(),
&PrototypeClass,
%(methods)s,
%(attrs)s,
%(consts)s,
%(unscopables)s,
prototype.handle_mut().into());
prototype.handle_mut());
assert!(!prototype.is_null());
assert!((*cache)[PrototypeList::ID::%(id)s as usize].is_null());
(*cache)[PrototypeList::ID::%(id)s as usize] = prototype.get();
Expand Down Expand Up @@ -3416,7 +3423,7 @@ def definition_body(self):

rooted!(in(*cx) let mut interface = ptr::null_mut::<JSObject>());
create_noncallback_interface_object(cx,
global.into(),
global,
interface_proto.handle(),
&INTERFACE_OBJECT_CLASS,
%(static_methods)s,
Expand Down Expand Up @@ -3455,15 +3462,16 @@ def defineAlias(alias):
defineFn = "JS_DefineProperty"
prop = '"%s"' % alias
enumFlags = "JSPROP_ENUMERATE"
if enumFlags != "0":
enumFlags = f"{enumFlags} as u32"
return CGList([
getSymbolJSID,
# XXX If we ever create non-enumerable properties that can
# be aliased, we should consider making the aliases
# match the enumerability of the property being aliased.
CGGeneric(fill(
"""
assert!(${defineFn}(*cx, prototype.handle(), ${prop}, aliasedVal.handle(),
${enumFlags} as u32));
assert!(${defineFn}(*cx, prototype.handle(), ${prop}, aliasedVal.handle(), ${enumFlags}));
""",
defineFn=defineFn,
prop=prop,
Expand Down Expand Up @@ -3492,7 +3500,7 @@ def defineAliasesFor(m):

constructors = self.descriptor.interface.legacyFactoryFunctions
if constructors:
decl = "let named_constructors: [(ConstructorClassHook, &'static [u8], u32); %d]" % len(constructors)
decl = "let named_constructors: [(ConstructorClassHook, &[u8], u32); %d]" % len(constructors)
specs = []
for constructor in constructors:
hook = CONSTRUCT_HOOK_NAME + "_" + constructor.identifier.name
Expand Down Expand Up @@ -3879,7 +3887,7 @@ def isFallible(self):
return 'infallible' not in self.extendedAttributes

def wrap_return_value(self):
return wrapForType('MutableHandleValue::from_raw(args.rval())')
return wrapForType('MutableHandleValue::from_raw(args.rval())', successCode='return true;')

def define(self):
return (self.cgRoot.define() + "\n" + self.wrap_return_value())
Expand Down Expand Up @@ -3972,7 +3980,7 @@ def __init__(self, argsPre, argType, nativeMethodName, descriptor, attr):

def wrap_return_value(self):
# We have no return value
return "\nreturn true;"
return "\ntrue"

def getArgc(self):
return "1"
Expand Down Expand Up @@ -4090,7 +4098,7 @@ def definition_body(self):
parents -= 1
ret += fill(form, parentclass="")
ret += ('(*args).rval().set(ObjectValue(*result));\n'
'return true;\n')
'true\n')
return CGGeneric(ret)


Expand Down Expand Up @@ -4666,7 +4674,7 @@ def __init__(self, enum):
use js::rust::MutableHandleValue;
use js::jsval::JSVal;

pub const pairs: &'static [(&'static str, super::${ident})] = &[
pub const pairs: &[(&str, super::${ident})] = &[
${pairs},
];

Expand Down Expand Up @@ -5645,7 +5653,7 @@ def getBody(self):
}
}
""" + namedGet + """\
return true;"""
true"""

def definition_body(self):
return CGGeneric(self.getBody())
Expand Down Expand Up @@ -5803,7 +5811,7 @@ def getBody(self):
return false;
}

return true;
true
""")

return body
Expand Down Expand Up @@ -5862,7 +5870,7 @@ def getBody(self):
return false;
}

return true;
true
""")

return body
Expand Down Expand Up @@ -5937,7 +5945,7 @@ def getBody(self):
}
""" + named + """\
*bp = false;
return true;"""
true"""

def definition_body(self):
return CGGeneric(self.getBody())
Expand Down Expand Up @@ -6038,7 +6046,7 @@ def getBody(self):
}
%s
vp.set(UndefinedValue());
return true;""" % (maybeCrossOriginGet, getIndexedOrExpando, getNamed)
true""" % (maybeCrossOriginGet, getIndexedOrExpando, getNamed)

def definition_body(self):
return CGGeneric(self.getBody())
Expand Down Expand Up @@ -6309,9 +6317,9 @@ def contains_unsafe_arg(arguments):
methods = []
for name, arguments, rettype in members():
arguments = list(arguments)
methods.append(CGGeneric("%sfn %s(&self%s) -> %s;\n" % (
methods.append(CGGeneric("%sfn %s(&self%s)%s;\n" % (
'unsafe ' if contains_unsafe_arg(arguments) else '',
name, fmt(arguments), rettype))
name, fmt(arguments), f" -> {rettype}" if rettype != '()' else ''))
)

if methods:
Expand Down Expand Up @@ -6772,7 +6780,7 @@ def reexportedName(name):
if unscopableNames:
haveUnscopables = True
cgThings.append(
CGList([CGGeneric("const unscopable_names: &'static [&'static [u8]] = &["),
CGList([CGGeneric("const unscopable_names: &[&[u8]] = &["),
CGIndenter(CGList([CGGeneric(str_to_const_array(name)) for
name in unscopableNames], ",\n")),
CGGeneric("];\n")], "\n"))
Expand All @@ -6791,7 +6799,7 @@ def reexportedName(name):
haveLegacyWindowAliases = len(legacyWindowAliases) != 0
if haveLegacyWindowAliases:
cgThings.append(
CGList([CGGeneric("const legacy_window_aliases: &'static [&'static [u8]] = &["),
CGList([CGGeneric("const legacy_window_aliases: &[&[u8]] = &["),
CGIndenter(CGList([CGGeneric(str_to_const_array(name)) for
name in legacyWindowAliases], ",\n")),
CGGeneric("];\n")], "\n"))
Expand Down Expand Up @@ -7618,9 +7626,9 @@ def __init__(self, sig, name, descriptorProvider, needThisHandling):
# Check for variadic arguments
lastArg = args[self.argCount - 1]
if lastArg.variadic:
argCount = "0" if self.argCount == 1 else f"({self.argCount} - 1)"
self.argCountStr = (
"(%d - 1) + %s.len()" % (self.argCount,
lastArg.identifier.name))
"%s + %s.len()" % (argCount, lastArg.identifier.name))
else:
self.argCountStr = "%d" % self.argCount
self.needThisHandling = needThisHandling
Expand Down Expand Up @@ -8121,7 +8129,7 @@ def PrototypeList(config):
CGWrapper(CGIndenter(CGList([CGGeneric('"' + name + '"') for name in protos],
",\n"),
indentLevel=4),
pre="static INTERFACES: [&'static str; %d] = [\n" % len(protos),
pre="static INTERFACES: [&str; %d] = [\n" % len(protos),
post="\n];\n\n"),
CGGeneric("pub fn proto_id_to_name(proto_id: u16) -> &'static str {\n"
" debug_assert!(proto_id < ID::Last as u16);\n"
Expand Down