--- a/xpcom/base/ErrorList.py
+++ b/xpcom/base/ErrorList.py
@@ -24,17 +24,18 @@ modules = OrderedDict()
# To add error code to your module, you need to do the following:
#
# 1) Add a module offset code. Add yours to the bottom of the list
# right below this comment, adding 1.
#
# 2) In your module, define a header file which uses one of the
# NE_ERROR_GENERATExxxxxx macros. Some examples below:
#
-# #define NS_ERROR_MYMODULE_MYERROR1 NS_ERROR_GENERATE(NS_ERROR_SEVERITY_ERROR,NS_ERROR_MODULE_MYMODULE,1)
+# #define NS_ERROR_MYMODULE_MYERROR1 \
+# NS_ERROR_GENERATE(NS_ERROR_SEVERITY_ERROR,NS_ERROR_MODULE_MYMODULE,1)
# #define NS_ERROR_MYMODULE_MYERROR2 NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_MYMODULE,2)
# #define NS_ERROR_MYMODULE_MYERROR3 NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_MYMODULE,3)
# @name Standard Module Offset Code. Each Module should identify a unique number
# and then all errors associated with that module become offsets from the
# base associated with that module id. There are 16 bits of code bits for
# each module.
@@ -647,22 +648,19 @@ with modules["DOM"]:
errors["NS_ERROR_DOM_MALFORMED_URI"] = FAILURE(1016)
errors["NS_ERROR_DOM_INVALID_HEADER_NAME"] = FAILURE(1017)
errors["NS_ERROR_DOM_INVALID_STATE_XHR_HAS_INVALID_CONTEXT"] = FAILURE(1018)
errors["NS_ERROR_DOM_INVALID_STATE_XHR_MUST_BE_OPENED"] = FAILURE(1019)
errors["NS_ERROR_DOM_INVALID_STATE_XHR_MUST_NOT_BE_SENDING"] = FAILURE(1020)
errors["NS_ERROR_DOM_INVALID_STATE_XHR_MUST_NOT_BE_LOADING_OR_DONE"] = FAILURE(1021)
errors["NS_ERROR_DOM_INVALID_STATE_XHR_HAS_WRONG_RESPONSETYPE_FOR_RESPONSEXML"] = FAILURE(1022)
- errors["NS_ERROR_DOM_INVALID_STATE_XHR_HAS_WRONG_RESPONSETYPE_FOR_RESPONSETEXT"] = FAILURE(
- 1023)
- errors["NS_ERROR_DOM_INVALID_STATE_XHR_CHUNKED_RESPONSETYPES_UNSUPPORTED_FOR_SYNC"] = FAILURE(
- 1024)
- errors["NS_ERROR_DOM_INVALID_ACCESS_XHR_TIMEOUT_AND_RESPONSETYPE_UNSUPPORTED_FOR_SYNC"] = FAILURE(
- 1025)
+ errors["NS_ERROR_DOM_INVALID_STATE_XHR_HAS_WRONG_RESPONSETYPE_FOR_RESPONSETEXT"] = FAILURE(1023) # NOQA: E501
+ errors["NS_ERROR_DOM_INVALID_STATE_XHR_CHUNKED_RESPONSETYPES_UNSUPPORTED_FOR_SYNC"] = FAILURE(1024) # NOQA: E501
+ errors["NS_ERROR_DOM_INVALID_ACCESS_XHR_TIMEOUT_AND_RESPONSETYPE_UNSUPPORTED_FOR_SYNC"] = FAILURE(1025) # NOQA: E501
# When manipulating the bytecode cache with the JS API, some transcoding
# errors, such as a different bytecode format can cause failures of the
# decoding process.
errors["NS_ERROR_DOM_JS_DECODING_ERROR"] = FAILURE(1026)
# May be used to indicate when e.g. setting a property value didn't
# actually change the value, like for obj.foo = "bar"; obj.foo = "bar";
@@ -1043,17 +1041,18 @@ with modules["DOM_PUSH"]:
errors["NS_ERROR_DOM_PUSH_MISMATCHED_KEY_ERR"] = FAILURE(6)
errors["NS_ERROR_DOM_PUSH_GCM_DISABLED"] = FAILURE(7)
# =======================================================================
# 41: NS_ERROR_MODULE_DOM_MEDIA
# =======================================================================
with modules["DOM_MEDIA"]:
- # HTMLMediaElement API errors from https://html.spec.whatwg.org/multipage/embedded-content.html#media-elements
+ # HTMLMediaElement API errors from
+ # https://html.spec.whatwg.org/multipage/embedded-content.html#media-elements
errors["NS_ERROR_DOM_MEDIA_ABORT_ERR"] = FAILURE(1)
errors["NS_ERROR_DOM_MEDIA_NOT_ALLOWED_ERR"] = FAILURE(2)
errors["NS_ERROR_DOM_MEDIA_NOT_SUPPORTED_ERR"] = FAILURE(3)
# HTMLMediaElement internal decoding error
errors["NS_ERROR_DOM_MEDIA_DECODE_ERR"] = FAILURE(4)
errors["NS_ERROR_DOM_MEDIA_FATAL_ERR"] = FAILURE(5)
errors["NS_ERROR_DOM_MEDIA_METADATA_ERR"] = FAILURE(6)
--- a/xpcom/idl-parser/xpidl/header.py
+++ b/xpcom/idl-parser/xpidl/header.py
@@ -296,22 +296,22 @@ iface_nonvirtual = """
/* Use this macro when declaring the members of this interface when the
class doesn't implement the interface. This is useful for forwarding. */
#define NS_DECL_NON_VIRTUAL_%(macroname)s """
iface_forward = """
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
-#define NS_FORWARD_%(macroname)s(_to) """
+#define NS_FORWARD_%(macroname)s(_to) """ # NOQA: E501
iface_forward_safe = """
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
-#define NS_FORWARD_SAFE_%(macroname)s(_to) """
+#define NS_FORWARD_SAFE_%(macroname)s(_to) """ # NOQA: E501
attr_builtin_infallible_tmpl = """\
inline %(realtype)s%(nativename)s(%(args)s)
{
%(realtype)sresult;
mozilla::DebugOnly<nsresult> rv = %(nativename)s(%(argnames)s&result);
MOZ_ASSERT(NS_SUCCEEDED(rv));
return result;
@@ -459,17 +459,17 @@ def write_interface(iface, fd):
(iface.name, attributeNativeName(member, True)))
fd.write("\\\n %s%s; " % (attributeAsNative(member, True, declType), suffix))
if not member.readonly:
fd.write("\\\n %s%s; " % (attributeAsNative(member, False, declType), suffix))
elif isinstance(member, xpidl.Method):
fd.write("\\\n %s%s; " % (methodAsNative(member, declType), suffix))
if len(iface.members) == 0:
fd.write('\\\n /* no methods! */')
- elif not member.kind in ('attribute', 'method'):
+ elif member.kind not in ('attribute', 'method'):
fd.write('\\')
writeDeclaration(fd, iface, True)
fd.write(iface_nonvirtual % names)
writeDeclaration(fd, iface, False)
fd.write(iface_forward % names)
def emitTemplate(forward_infallible, tmpl, tmpl_notxpcom=None):
@@ -493,29 +493,29 @@ def write_interface(iface, fd):
'nativeName': methodNativeName(member),
'paramList': paramlistNames(member)})
else:
fd.write(tmpl % {'asNative': methodAsNative(member),
'nativeName': methodNativeName(member),
'paramList': paramlistNames(member)})
if len(iface.members) == 0:
fd.write('\\\n /* no methods! */')
- elif not member.kind in ('attribute', 'method'):
+ elif member.kind not in ('attribute', 'method'):
fd.write('\\')
emitTemplate(True,
"\\\n %(asNative)s override { return _to %(nativeName)s(%(paramList)s); } ")
fd.write(iface_forward_safe % names)
# Don't try to safely forward notxpcom functions, because we have no
# sensible default error return. Instead, the caller will have to
# implement them.
emitTemplate(False,
- "\\\n %(asNative)s override { return !_to ? NS_ERROR_NULL_POINTER : _to->%(nativeName)s(%(paramList)s); } ",
+ "\\\n %(asNative)s override { return !_to ? NS_ERROR_NULL_POINTER : _to->%(nativeName)s(%(paramList)s); } ", # NOQA: E501
"\\\n %(asNative)s override; ")
fd.write('\n\n')
def main(outputfile):
cachedir = os.path.dirname(outputfile.name if outputfile else '') or '.'
if not os.path.isdir(cachedir):
@@ -524,13 +524,13 @@ def main(outputfile):
# Delete the lex/yacc files. Ply is too stupid to regenerate them
# properly
for fileglobs in [os.path.join(cachedir, f) for f in ["xpidllex.py*", "xpidlyacc.py*"]]:
for filename in glob.glob(fileglobs):
os.remove(filename)
# Instantiate the parser.
- p = xpidl.IDLParser(outputdir=cachedir)
+ xpidl.IDLParser(outputdir=cachedir)
if __name__ == '__main__':
main(None)
--- a/xpcom/idl-parser/xpidl/jsonxpt.py
+++ b/xpcom/idl-parser/xpidl/jsonxpt.py
@@ -2,18 +2,16 @@
# jsonxpt.py - Generate json XPT typelib files from IDL.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""Generate a json XPT typelib for an IDL file"""
-import os
-import sys
import xpidl
import json
import itertools
# A map of xpidl.py types to xpt enum variants
TypeMap = {
# builtins
'boolean': 'TD_BOOL',
--- a/xpcom/idl-parser/xpidl/rust.py
+++ b/xpcom/idl-parser/xpidl/rust.py
@@ -29,17 +29,16 @@
# nostdcall methods on x86 windows will use the thiscall ABI, which is not
# stable in rust right now, so we cannot generate bindings to them.
# In general, passing C++ objects by value over the C ABI is not a good idea,
# and when possible we should avoid doing so. We don't generate bindings for
# these methods here currently.
-import sys
import os.path
import re
import xpidl
class AutoIndent(object):
"""A small autoindenting wrapper around a fd.
Used to make the code output more readable."""
--- a/xpcom/idl-parser/xpidl/xpidl.py
+++ b/xpcom/idl-parser/xpidl/xpidl.py
@@ -261,17 +261,20 @@ class NameMap(object):
def get(self, id, location):
try:
return self[id]
except KeyError:
raise IDLError("Name '%s' not found", location)
class RustNoncompat(Exception):
- """Thie exception is raised when a particular type or function cannot be safely exposed to rust code"""
+ """
+ This exception is raised when a particular type or function cannot be safely exposed to
+ rust code
+ """
def __init__(self, reason):
self.reason = reason
def __str__(self):
return self.reason
@@ -662,34 +665,38 @@ class Interface(object):
self.doccomments = parent.getName(self.name, None).doccomments
if self.attributes.function:
has_method = False
for member in self.members:
if member.kind is 'method':
if has_method:
raise IDLError(
- "interface '%s' has multiple methods, but marked 'function'" % self.name, self.location)
+ "interface '%s' has multiple methods, but marked 'function'" %
+ self.name, self.location)
else:
has_method = True
parent.setName(self)
if self.base is not None:
realbase = parent.getName(self.base, self.location)
if realbase.kind != 'interface':
raise IDLError("interface '%s' inherits from non-interface type '%s'" %
(self.name, self.base), self.location)
if self.attributes.scriptable and not realbase.attributes.scriptable:
- raise IDLError("interface '%s' is scriptable but derives from non-scriptable '%s'" %
+ raise IDLError("interface '%s' is scriptable but derives from "
+ "non-scriptable '%s'" %
(self.name, self.base), self.location, warning=True)
- if self.attributes.scriptable and realbase.attributes.builtinclass and not self.attributes.builtinclass:
- raise IDLError("interface '%s' is not builtinclass but derives from builtinclass '%s'" % (
- self.name, self.base), self.location)
+ if (self.attributes.scriptable and realbase.attributes.builtinclass and
+ not self.attributes.builtinclass):
+ raise IDLError("interface '%s' is not builtinclass but derives from "
+ "builtinclass '%s'" %
+ (self.name, self.base), self.location)
if realbase.implicit_builtinclass:
self.implicit_builtinclass = True # Inherit implicit builtinclass from base
for member in self.members:
member.resolve(self)
# The number 250 is NOT arbitrary; this number is the maximum number of
@@ -947,17 +954,20 @@ class Attribute(object):
if (self.null is not None and
getBuiltinOrNativeTypeName(self.realtype) != '[domstring]'):
raise IDLError("'Null' attribute can only be used on DOMString",
self.location)
if (self.undefined is not None and
getBuiltinOrNativeTypeName(self.realtype) != '[domstring]'):
raise IDLError("'Undefined' attribute can only be used on DOMString",
self.location)
- if self.infallible and not self.realtype.kind in ['builtin', 'interface', 'forward', 'webidl']:
+ if self.infallible and self.realtype.kind not in ['builtin',
+ 'interface',
+ 'forward',
+ 'webidl']:
raise IDLError('[infallible] only works on interfaces, domobjects, and builtin types '
'(numbers, booleans, and raw char types)',
self.location)
if self.infallible and not iface.attributes.builtinclass:
raise IDLError('[infallible] attributes are only allowed on '
'[builtinclass] interfaces',
self.location)
@@ -1115,17 +1125,18 @@ class Param(object):
elif name == 'iid_is':
if value is None:
raise IDLError("'iid_is' must specify a parameter", aloc)
self.iid_is = value
elif name == 'Null':
if value is None:
raise IDLError("'Null' must specify a parameter", aloc)
if value not in ('Empty', 'Null', 'Stringify'):
- raise IDLError("'Null' parameter value must be 'Empty', 'Null', or 'Stringify'",
+ raise IDLError("'Null' parameter value must be 'Empty', 'Null', "
+ "or 'Stringify'",
aloc)
self.null = value
elif name == 'Undefined':
if value is None:
raise IDLError("'Undefined' must specify a parameter", aloc)
if value not in ('Empty', 'Null'):
raise IDLError("'Undefined' parameter value must be 'Empty' or 'Null'",
aloc)
@@ -1169,33 +1180,33 @@ class Param(object):
kwargs = {}
if self.shared:
kwargs['shared'] = True
if self.const:
kwargs['const'] = True
try:
return self.realtype.nativeType(self.paramtype, **kwargs)
- except IDLError, e:
+ except IDLError as e:
raise IDLError(e.message, self.location)
- except TypeError, e:
+ except TypeError as e:
raise IDLError("Unexpected parameter attribute", self.location)
def rustType(self):
kwargs = {}
if self.shared:
kwargs['shared'] = True
if self.const:
kwargs['const'] = True
try:
return self.realtype.rustType(self.paramtype, **kwargs)
- except IDLError, e:
+ except IDLError as e:
raise IDLError(e.message, self.location)
- except TypeError, e:
+ except TypeError as e:
raise IDLError("Unexpected parameter attribute", self.location)
def toIDL(self):
return "%s%s %s %s" % (paramAttlistToIDL(self.attlist),
self.paramtype,
self.type,
self.name)
@@ -1269,17 +1280,17 @@ class IDLParser(object):
def t_singlelinecomment(self, t):
r'(?m)//.*?$'
def t_IID(self, t):
return t
t_IID.__doc__ = r'%(c)s{8}-%(c)s{4}-%(c)s{4}-%(c)s{4}-%(c)s{12}' % {'c': hexchar}
def t_IDENTIFIER(self, t):
- r'(unsigned\ long\ long|unsigned\ short|unsigned\ long|long\ long)(?!_?[A-Za-z][A-Za-z_0-9])|_?[A-Za-z][A-Za-z_0-9]*'
+ r'(unsigned\ long\ long|unsigned\ short|unsigned\ long|long\ long)(?!_?[A-Za-z][A-Za-z_0-9])|_?[A-Za-z][A-Za-z_0-9]*' # NOQA: E501
t.type = self.keywords.get(t.value, 'IDENTIFIER')
return t
def t_LCDATA(self, t):
r'(?s)%\{[ ]*C\+\+[ ]*\n(?P<cdata>.*?\n?)%\}[ ]*(C\+\+)?'
t.type = 'CDATA'
t.value = t.lexer.lexmatch.group('cdata')
t.lexer.lineno += t.value.count('\n')
@@ -1411,34 +1422,34 @@ class IDLParser(object):
"""interface : attributes INTERFACE IDENTIFIER ifacebase ifacebody ';'"""
atts, INTERFACE, name, base, body, SEMI = p[1:]
attlist = atts['attlist']
doccomments = []
if 'doccomments' in atts:
doccomments.extend(atts['doccomments'])
doccomments.extend(p.slice[2].doccomments)
- def l(): return self.getLocation(p, 2)
+ def loc(): return self.getLocation(p, 2)
if body is None:
# forward-declared interface... must not have attributes!
if len(attlist) != 0:
raise IDLError("Forward-declared interface must not have attributes",
list[0][3])
if base is not None:
raise IDLError("Forward-declared interface must not have a base",
- l())
- p[0] = Forward(name=name, location=l(), doccomments=doccomments)
+ loc())
+ p[0] = Forward(name=name, location=loc(), doccomments=doccomments)
else:
p[0] = Interface(name=name,
attlist=attlist,
base=base,
members=body,
- location=l(),
+ location=loc(),
doccomments=doccomments)
def p_ifacebody(self, p):
"""ifacebody : '{' members '}'
| """
if len(p) > 1:
p[0] = p[2]
@@ -1609,17 +1620,18 @@ class IDLParser(object):
def p_idlist_continue(self, p):
"""idlist : IDENTIFIER ',' idlist"""
p[0] = list(p[3])
p[0].insert(0, p[1])
def p_error(self, t):
if not t:
raise IDLError(
- "Syntax Error at end of file. Possibly due to missing semicolon(;), braces(}) or both", None)
+ "Syntax Error at end of file. Possibly due to missing semicolon(;), braces(}) "
+ "or both", None)
else:
location = Location(self.lexer, t.lineno, t.lexpos)
raise IDLError("invalid syntax", location)
def __init__(self, outputdir=''):
self._doccomments = []
self.lexer = lex.lex(object=self,
outputdir=outputdir,
@@ -1653,10 +1665,10 @@ class IDLParser(object):
def getLocation(self, p, i):
return Location(self.lexer, p.lineno(i), p.lexpos(i))
if __name__ == '__main__':
p = IDLParser()
for f in sys.argv[1:]:
- print "Parsing %s" % f
+ print("Parsing %s" % f)
p.parse(open(f).read(), filename=f)
--- a/xpcom/reflect/xptinfo/xptcodegen.py
+++ b/xpcom/reflect/xptinfo/xptcodegen.py
@@ -5,17 +5,16 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# NOTE: Once shims are removed, this code can be cleaned up, removing all
# reference to them.
import json
from perfecthash import PerfectHash
-import time
from collections import OrderedDict
# We fix the number of entries in our intermediate table used by the perfect
# hashes to 512. This number is constant in xptinfo, allowing the compiler to
# generate a more efficient modulo due to it being a power of 2.
PHFSIZE = 512
@@ -217,17 +216,18 @@ def link_to_cpp(interfaces, fd):
methods = []
consts = []
prophooks = []
domobjects = []
domobject_cache = {}
strings = OrderedDict()
def lower_uuid(uuid):
- return "{0x%s, 0x%s, 0x%s, {0x%s, 0x%s, 0x%s, 0x%s, 0x%s, 0x%s, 0x%s, 0x%s}}" % split_iid(uuid)
+ return ("{0x%s, 0x%s, 0x%s, {0x%s, 0x%s, 0x%s, 0x%s, 0x%s, 0x%s, 0x%s, 0x%s}}" %
+ split_iid(uuid))
def lower_domobject(do):
assert do['tag'] == 'TD_DOMOBJECT'
idx = domobject_cache.get(do['name'])
if idx is None:
idx = domobject_cache[do['name']] = len(domobjects)
--- a/xpcom/typelib/xpt/tools/runtests.py
+++ b/xpcom/typelib/xpt/tools/runtests.py
@@ -62,19 +62,20 @@ if "MOZILLA_OBJDIR" in os.environ:
t = xpt.Typelib.read(fullpath)
self.assert_(t is not None)
outf = StringIO()
t.dump(outf)
out = outf.getvalue()
# now run xpt_dump on it
out2 = get_output(xptdump, fullpath)
if out != out2:
- print "diff %s" % f
- for line in difflib.unified_diff(out2.split("\n"), out.split("\n"), lineterm=""):
- print line
+ print("diff %s" % f)
+
+ for line in difflib.unified_diff(out2.split("\n"), out.split("\n"), lineterm=""): # NOQA: E501
+ print(line)
self.assert_(out == out2, "xpt_dump output should be identical for %s" % f)
class TestIIDString(unittest.TestCase):
def test_iid_str_roundtrip(self):
iid_str = "11223344-5566-7788-9900-aabbccddeeff"
iid = xpt.Typelib.string_to_iid(iid_str)
self.assertEqual(iid_str, xpt.Typelib.iid_to_string(iid))
@@ -308,27 +309,28 @@ class TestTypelibRoundtrip(unittest.Test
xpt.SimpleType(xpt.Type.Tags.int32),
1, 2)),
xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)),
xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)),
]))
self.checkRoundtrip(t)
# add a method with a StringWithSize and WideStringWithSize arguments
- i.methods.append(xpt.Method("StringWithSizeMethod", xpt.Param(xpt.SimpleType(xpt.Type.Tags.void)),
+ i.methods.append(xpt.Method("StringWithSizeMethod",
+ xpt.Param(xpt.SimpleType(xpt.Type.Tags.void)),
params=[
xpt.Param(xpt.StringWithSizeType(
1, 2)),
xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)),
xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)),
xpt.Param(xpt.WideStringWithSizeType(
4, 5)),
xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)),
xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)),
- ]))
+ ]))
self.checkRoundtrip(t)
class TestInterfaceCmp(unittest.TestCase):
def test_unresolvedName(self):
"""
Test comparison function on xpt.Interface by name.
--- a/xpcom/typelib/xpt/tools/xpt.py
+++ b/xpcom/typelib/xpt/tools/xpt.py
@@ -665,17 +665,18 @@ class StringWithSizeType(Type):
file |map| with data pool offset |data_pool|.
Returns (StringWithSizeType, next offset),
where |next offset| is an offset suitable for reading the data
following this StringWithSizeTypeDescriptor.
"""
if not flags['pointer']:
return None, offset
start = data_pool + offset - 1
- (size_is_arg_num, length_is_arg_num) = StringWithSizeType._descriptor.unpack_from(map, start)
+ (size_is_arg_num, length_is_arg_num) = StringWithSizeType._descriptor.unpack_from(map,
+ start)
offset += StringWithSizeType._descriptor.size
return StringWithSizeType(size_is_arg_num, length_is_arg_num, **flags), offset
def write(self, typelib, file):
"""
Write a StringWithSizeTypeDescriptor to |file|, which is assumed
to be seeked to the proper position.
@@ -725,17 +726,19 @@ class WideStringWithSizeType(Type):
file |map| with data pool offset |data_pool|.
Returns (WideStringWithSizeType, next offset),
where |next offset| is an offset suitable for reading the data
following this WideStringWithSizeTypeDescriptor.
"""
if not flags['pointer']:
return None, offset
start = data_pool + offset - 1
- (size_is_arg_num, length_is_arg_num) = WideStringWithSizeType._descriptor.unpack_from(map, start)
+ (size_is_arg_num, length_is_arg_num) = (
+ WideStringWithSizeType._descriptor.unpack_from(map,
+ start))
offset += WideStringWithSizeType._descriptor.size
return WideStringWithSizeType(size_is_arg_num, length_is_arg_num, **flags), offset
def write(self, typelib, file):
"""
Write a WideStringWithSizeTypeDescriptor to |file|, which is assumed
to be seeked to the proper position.
@@ -1150,20 +1153,21 @@ class Constant(object):
"""
self._name_offset = string_writer.write(self.name)
def code_gen(self, typelib, cd):
string_index = cd.add_string(self.name)
# The static cast is needed for disambiguation.
- return "{%d, %s, XPTConstValue(static_cast<%s>(%d))}" % (string_index,
- self.type.code_gen(typelib, cd),
- Constant.memberTypeMap[self.type.tag],
- self.value)
+ return ("{%d, %s, XPTConstValue(static_cast<%s>(%d))}" %
+ (string_index,
+ self.type.code_gen(typelib, cd),
+ Constant.memberTypeMap[self.type.tag],
+ self.value))
def __repr__(self):
return "Constant(%s, %s, %d)" % (self.name, str(self.type), self.value)
class Interface(object):
"""
An Interface represents an object, with its associated methods
@@ -1194,26 +1198,28 @@ class Interface(object):
self.builtinclass = builtinclass
self.main_process_scriptable_only = main_process_scriptable_only
# For sanity, if someone constructs an Interface and passes
# in methods or constants, then it's resolved.
if self.methods or self.constants:
# make sure it has a valid IID
if self.iid == Interface.UNRESOLVED_IID:
raise DataError(
- "Cannot instantiate Interface %s containing methods or constants with an unresolved IID" % self.name)
+ "Cannot instantiate Interface %s containing methods or constants with an "
+ "unresolved IID" % self.name)
self.resolved = True
# These are only used for writing out the interface
self._descriptor_offset = 0
self._name_offset = 0
self._namespace_offset = 0
self.xpt_filename = None
def __repr__(self):
- return "Interface('%s', '%s', '%s', methods=%s)" % (self.name, self.iid, self.namespace, self.methods)
+ return ("Interface('%s', '%s', '%s', methods=%s)" %
+ (self.name, self.iid, self.namespace, self.methods))
def __str__(self):
return "Interface(name='%s', iid='%s')" % (self.name, self.iid)
def __hash__(self):
return hash((self.name, self.iid))
def __cmp__(self, other):
@@ -1467,17 +1473,18 @@ class Typelib(object):
interface_directory_offset,
data_pool_offset) = Typelib._header.unpack_from(data)
if magic != XPT_MAGIC:
raise FileFormatError("Bad magic: %s" % magic)
xpt = Typelib((major_ver, minor_ver))
xpt.filename = filename
if expected_size and file_length != expected_size:
raise FileFormatError(
- "File is of wrong length, got %d bytes, expected %d" % (expected_size, file_length))
+ "File is of wrong length, got %d bytes, expected %d" %
+ (expected_size, file_length))
# XXX: by spec this is a zero-based file offset. however,
# the xpt_xdr code always subtracts 1 from data offsets
# (because that's what you do in the data pool) so it
# winds up accidentally treating this as 1-based.
# Filed as: https://bugzilla.mozilla.org/show_bug.cgi?id=575343
interface_directory_offset -= 1
# make a half-hearted attempt to read Annotations,
# since XPIDL doesn't produce any anyway.
@@ -1501,17 +1508,17 @@ class Typelib(object):
xpt.interfaces.append(iface)
for iface in xpt.interfaces:
iface.read_descriptor(xpt, data, data_pool_offset)
return xpt
@staticmethod
def code_gen_iid(iid):
chunks = iid.split('-')
- return "{0x%s, 0x%s, 0x%s, {0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x}}" % (
+ return "{0x%s, 0x%s, 0x%s, {0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x, 0x%02x}}" % ( # NOQA: E501
chunks[0], chunks[1], chunks[2],
int(chunks[3][0:2], 16), int(chunks[3][2:4], 16),
int(chunks[4][0:2], 16), int(chunks[4][2:4], 16),
int(chunks[4][4:6], 16), int(chunks[4][6:8], 16),
int(chunks[4][8:10], 16), int(chunks[4][10:12], 16))
def __repr__(self):
return "<Typelib with %d interfaces>" % len(self.interfaces)
@@ -1527,21 +1534,23 @@ class Typelib(object):
for i in self.interfaces:
if i.parent and i.parent not in self.interfaces:
raise DataError("Interface %s has parent %s not present in typelib!" %
(i.name, i.parent.name))
for m in i.methods:
for n, p in enumerate(m.params):
if isinstance(p, InterfaceType) and \
p.iface not in self.interfaces:
- raise DataError("Interface method %s::%s, parameter %d references interface %s not present in typelib!" % (
- i.name, m.name, n, p.iface.name))
+ raise DataError("Interface method %s::%s, parameter %d references"
+ "interface %s not present in typelib!" % (
+ i.name, m.name, n, p.iface.name))
if isinstance(m.result, InterfaceType) and m.result.iface not in self.interfaces:
- raise DataError("Interface method %s::%s, result references interface %s not present in typelib!" % (
- i.name, m.name, m.result.iface.name))
+ raise DataError("Interface method %s::%s, result references interface %s not "
+ "present in typelib!" % (
+ i.name, m.name, m.result.iface.name))
def writefd(self, fd):
# write out space for a header + one empty annotation,
# padded to 4-byte alignment.
headersize = (Typelib._header.size + 1)
if headersize % 4:
headersize += 4 - headersize % 4
fd.write("\x00" * headersize)
@@ -1824,17 +1833,18 @@ def xpt_link(inputs):
if i.parent:
maybe_add_to_worklist(i.parent)
for m in i.methods:
if isinstance(m.result.type, InterfaceType):
maybe_add_to_worklist(m.result.type.iface)
for p in m.params:
if isinstance(p.type, InterfaceType):
maybe_add_to_worklist(p.type.iface)
- elif isinstance(p.type, ArrayType) and isinstance(p.type.element_type, InterfaceType):
+ elif (isinstance(p.type, ArrayType) and
+ isinstance(p.type.element_type, InterfaceType)):
maybe_add_to_worklist(p.type.element_type.iface)
interfaces = list(required_interfaces)
# Re-sort interfaces (by IID)
interfaces.sort()
return Typelib(interfaces=interfaces)