Bug 1464869 - Run autopep8 on xpcom/ r=Nika

MozReview-Commit-ID: JDdoIvkmOIx

--HG--
extra : rebase_source : c23ee8d3da399dd837eccf6a63a50cd50f5e81c6
This commit is contained in:
Sylvestre Ledru 2018-05-25 21:29:52 -07:00
Родитель 89e4661534
Коммит 34a5216fe7
12 изменённых файлов: 400 добавлений и 350 удалений

Просмотреть файл

@ -1,6 +1,7 @@
#!/usr/bin/env python
from collections import OrderedDict
class Mod:
"""
A nserror module. When used with a `with` statement, binds the itself to
@ -17,6 +18,7 @@ class Mod:
def __exit__(self, _type, _value, _traceback):
Mod.active = None
modules = OrderedDict()
# To add error code to your module, you need to do the following:
@ -95,15 +97,19 @@ MODULE_BASE_OFFSET = 0x45
NS_ERROR_SEVERITY_SUCCESS = 0
NS_ERROR_SEVERITY_ERROR = 1
def SUCCESS_OR_FAILURE(sev, module, code):
return (sev << 31) | ((module + MODULE_BASE_OFFSET) << 16) | code
def FAILURE(code):
return SUCCESS_OR_FAILURE(NS_ERROR_SEVERITY_ERROR, Mod.active.num, code)
def SUCCESS(code):
return SUCCESS_OR_FAILURE(NS_ERROR_SEVERITY_SUCCESS, Mod.active.num, code)
# Errors is an ordered dictionary, so that we can recover the order in which
# they were defined. This is important for determining which name is the
# canonical name for an error code.
@ -196,7 +202,6 @@ with modules["BASE"]:
errors["NS_BASE_STREAM_WOULD_BLOCK"] = FAILURE(7)
# =======================================================================
# 3: NS_ERROR_MODULE_GFX
# =======================================================================
@ -220,7 +225,6 @@ with modules["GFX"]:
errors["NS_ERROR_GFX_CMAP_MALFORMED"] = FAILURE(51)
# =======================================================================
# 4: NS_ERROR_MODULE_WIDGET
# =======================================================================
@ -238,7 +242,6 @@ with modules["WIDGET"]:
errors["NS_SUCCESS_EVENT_HANDLED_ASYNCHRONOUSLY"] = SUCCESS(2)
# =======================================================================
# 6: NS_ERROR_MODULE_NETWORK
# =======================================================================
@ -357,7 +360,6 @@ with modules["NETWORK"]:
# probably in the process of being torn down.
errors["NS_ERROR_DOCSHELL_DYING"] = FAILURE(78)
# FTP specific error codes:
errors["NS_ERROR_FTP_LOGIN"] = FAILURE(21)
@ -379,7 +381,6 @@ with modules["NETWORK"]:
# hostname cannot be resolved.
errors["NS_ERROR_UNKNOWN_PROXY_HOST"] = FAILURE(42)
# Socket specific error codes:
# The specified socket type does not exist.
@ -412,7 +413,6 @@ with modules["NETWORK"]:
# The host string is an IP address.
errors["NS_ERROR_HOST_IS_IP_ADDRESS"] = FAILURE(81)
# StreamLoader specific result codes:
# Result code returned by nsIStreamLoaderObserver to indicate that the
@ -451,7 +451,6 @@ with modules["NETWORK"]:
errors["NS_ERROR_INTERCEPTION_FAILED"] = FAILURE(100)
# =======================================================================
# 7: NS_ERROR_MODULE_PLUGINS
# =======================================================================
@ -463,7 +462,6 @@ with modules["PLUGINS"]:
errors["NS_ERROR_PLUGIN_CLICKTOPLAY"] = FAILURE(1004)
# =======================================================================
# 8: NS_ERROR_MODULE_LAYOUT
# =======================================================================
@ -476,7 +474,6 @@ with modules["LAYOUT"]:
errors["NS_POSITION_BEFORE_TABLE"] = SUCCESS(3)
# =======================================================================
# 9: NS_ERROR_MODULE_HTMLPARSER
# =======================================================================
@ -508,7 +505,6 @@ with modules["HTMLPARSER"]:
errors["NS_HTMLPARSER_VALID_META_CHARSET"] = SUCCESS(3000)
# =======================================================================
# 10: NS_ERROR_MODULE_RDF
# =======================================================================
@ -530,7 +526,6 @@ with modules["RDF"]:
errors["NS_RDF_STOP_VISIT"] = SUCCESS(4)
# =======================================================================
# 11: NS_ERROR_MODULE_UCONV
# =======================================================================
@ -557,7 +552,6 @@ with modules["UCONV"]:
# END DEPRECATED
# =======================================================================
# 13: NS_ERROR_MODULE_FILES
# =======================================================================
@ -589,7 +583,6 @@ with modules["FILES"]:
errors["NS_SUCCESS_AGGREGATE_RESULT"] = SUCCESS(2)
# =======================================================================
# 14: NS_ERROR_MODULE_DOM
# =======================================================================
@ -659,9 +652,12 @@ with modules["DOM"]:
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)
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)
# When manipulating the bytecode cache with the JS API, some transcoding
# errors, such as a different bytecode format can cause failures of the
@ -684,7 +680,6 @@ with modules["DOM"]:
errors["NS_SUCCESS_DOM_SCRIPT_EVALUATION_THREW_UNCATCHABLE"] = SUCCESS(3)
# =======================================================================
# 15: NS_ERROR_MODULE_IMGLIB
# =======================================================================
@ -697,7 +692,6 @@ with modules["IMGLIB"]:
errors["NS_IMAGELIB_ERROR_NO_ENCODER"] = FAILURE(9)
# =======================================================================
# 17: NS_ERROR_MODULE_EDITOR
# =======================================================================
@ -708,7 +702,6 @@ with modules["EDITOR"]:
errors["NS_SUCCESS_EDITOR_FOUND_TARGET"] = SUCCESS(2)
# =======================================================================
# 18: NS_ERROR_MODULE_XPCONNECT
# =======================================================================
@ -770,7 +763,6 @@ with modules["XPCONNECT"]:
# any new errors here should have an associated entry added in xpc.msg
# =======================================================================
# 19: NS_ERROR_MODULE_PROFILE
# =======================================================================
@ -778,7 +770,6 @@ with modules["PROFILE"]:
errors["NS_ERROR_LAUNCHED_CHILD_PROCESS"] = FAILURE(200)
# =======================================================================
# 21: NS_ERROR_MODULE_SECURITY
# =======================================================================
@ -815,7 +806,6 @@ with modules["SECURITY"]:
errors["NS_ERROR_CMS_ENCRYPT_INCOMPLETE"] = FAILURE(1057)
# =======================================================================
# 22: NS_ERROR_MODULE_DOM_XPATH
# =======================================================================
@ -825,7 +815,6 @@ with modules["DOM_XPATH"]:
errors["NS_ERROR_DOM_TYPE_ERR"] = FAILURE(52)
# =======================================================================
# 24: NS_ERROR_MODULE_URILOADER
# =======================================================================
@ -851,7 +840,6 @@ with modules["URILOADER"]:
errors["NS_REFRESHURI_HEADER_FOUND"] = SUCCESS(2)
# =======================================================================
# 25: NS_ERROR_MODULE_CONTENT
# =======================================================================
@ -880,7 +868,6 @@ with modules["CONTENT"]:
errors["NS_FINDBROADCASTER_AWAIT_OVERLAYS"] = SUCCESS(14)
# =======================================================================
# 27: NS_ERROR_MODULE_XSLT
# =======================================================================
@ -923,7 +910,6 @@ with modules["XSLT"]:
errors["NS_XSLT_GET_NEW_HANDLER"] = SUCCESS(1)
# =======================================================================
# 28: NS_ERROR_MODULE_IPC
# =======================================================================
@ -948,7 +934,6 @@ with modules["SVG"]:
errors["NS_ERROR_DOM_SVG_MATRIX_NOT_INVERTABLE"] = FAILURE(2)
# =======================================================================
# 30: NS_ERROR_MODULE_STORAGE
# =======================================================================
@ -966,7 +951,6 @@ with modules["STORAGE"]:
errors["NS_ERROR_STORAGE_CONSTRAINT"] = FAILURE(3)
# =======================================================================
# 32: NS_ERROR_MODULE_DOM_FILE
# =======================================================================
@ -976,7 +960,6 @@ with modules["DOM_FILE"]:
errors["NS_ERROR_DOM_FILE_ABORT_ERR"] = FAILURE(2)
# =======================================================================
# 33: NS_ERROR_MODULE_DOM_INDEXEDDB
# =======================================================================
@ -996,7 +979,6 @@ with modules["DOM_INDEXEDDB"]:
errors["NS_ERROR_DOM_INDEXEDDB_RECOVERABLE_ERR"] = FAILURE(1001)
# =======================================================================
# 34: NS_ERROR_MODULE_DOM_FILEHANDLE
# =======================================================================
@ -1155,7 +1137,6 @@ with modules["GENERAL"]:
errors["NS_SUCCESS_RESTART_APP_NOT_SAME_PROFILE"] = SUCCESS(3)
errors["NS_SUCCESS_UNORM_NOTFOUND"] = SUCCESS(17)
# a11y
# raised when current pivot's position is needed but it's not in the tree
errors["NS_ERROR_NOT_IN_TREE"] = FAILURE(38)
@ -1209,6 +1190,7 @@ const nsresult
#endif // ErrorList_h__
""".format(",\n".join(items)))
def error_names_internal_h(output):
"""Generate ErrorNamesInternal.h, which is a header file declaring one
function, const char* GetErrorNameInternal(nsresult). This method is not

Просмотреть файл

@ -1,10 +1,13 @@
#!/usr/bin/env python
services = []
def service(name, iface, contractid):
"""Define a convenient service getter"""
services.append((name, iface, contractid))
service('ChromeRegistryService', 'nsIChromeRegistry',
"@mozilla.org/chrome/chrome-registry;1")
service('ToolkitChromeRegistryService', 'nsIToolkitChromeRegistry',
@ -84,6 +87,7 @@ CPP_INCLUDES = """
#
# XXX(nika): would it be a good idea to unify Services.jsm into here too?
def services_h(output):
output.write("""\
/* THIS FILE IS GENERATED BY Services.py - DO NOT EDIT */
@ -130,9 +134,9 @@ Get%(name)s()
} // namespace mozilla
#endif // defined(MOZILLA_INTERNAL_API)
""" % {
'name': name,
'type': iface,
})
'name': name,
'type': iface,
})
output.write("#endif // !defined(mozilla_Services_h)\n")
@ -167,10 +171,10 @@ XPCOMService_Get%(name)s()
}
} // extern "C"
""" % {
'name': name,
'type': iface,
'contractid': contractid,
})
'name': name,
'type': iface,
'contractid': contractid,
})
output.write("""
/**
@ -208,6 +212,6 @@ pub fn get_%(name)s() -> Option<RefPtr<::interfaces::%(type)s>> {
unsafe { RefPtr::from_raw_dont_addref(XPCOMService_Get%(name)s()) }
}
""" % {
'name': name,
'type': iface,
})
'name': name,
'type': iface,
})

Просмотреть файл

@ -194,289 +194,291 @@ The bytes in the generated array has the following meaning:
import sys
class InputError(Exception):
"""Exception raised for errors in the input file."""
"""Exception raised for errors in the input file."""
def to_dafsa(words):
"""Generates a DAFSA from a word list and returns the source node.
"""Generates a DAFSA from a word list and returns the source node.
Each word is split into characters so that each character is represented by
a unique node. It is assumed the word list is not empty.
"""
if not words:
raise InputError('The domain list must not be empty')
def ToNodes(word):
"""Split words into characters"""
if not 0x1F < ord(word[0]) < 0x80:
raise InputError('Domain names must be printable 7-bit ASCII')
if len(word) == 1:
return chr(ord(word[0]) & 0x0F), [None]
return word[0], [ToNodes(word[1:])]
return [ToNodes(word) for word in words]
Each word is split into characters so that each character is represented by
a unique node. It is assumed the word list is not empty.
"""
if not words:
raise InputError('The domain list must not be empty')
def ToNodes(word):
"""Split words into characters"""
if not 0x1F < ord(word[0]) < 0x80:
raise InputError('Domain names must be printable 7-bit ASCII')
if len(word) == 1:
return chr(ord(word[0]) & 0x0F), [None]
return word[0], [ToNodes(word[1:])]
return [ToNodes(word) for word in words]
def to_words(node):
"""Generates a word list from all paths starting from an internal node."""
if not node:
return ['']
return [(node[0] + word) for child in node[1] for word in to_words(child)]
"""Generates a word list from all paths starting from an internal node."""
if not node:
return ['']
return [(node[0] + word) for child in node[1] for word in to_words(child)]
def reverse(dafsa):
"""Generates a new DAFSA that is reversed, so that the old sink node becomes
the new source node.
"""
sink = []
nodemap = {}
def dfs(node, parent):
"""Creates reverse nodes.
A new reverse node will be created for each old node. The new node will
get a reversed label and the parents of the old node as children.
"""Generates a new DAFSA that is reversed, so that the old sink node becomes
the new source node.
"""
if not node:
sink.append(parent)
elif id(node) not in nodemap:
nodemap[id(node)] = (node[0][::-1], [parent])
for child in node[1]:
dfs(child, nodemap[id(node)])
else:
nodemap[id(node)][1].append(parent)
sink = []
nodemap = {}
for node in dafsa:
dfs(node, None)
return sink
def dfs(node, parent):
"""Creates reverse nodes.
A new reverse node will be created for each old node. The new node will
get a reversed label and the parents of the old node as children.
"""
if not node:
sink.append(parent)
elif id(node) not in nodemap:
nodemap[id(node)] = (node[0][::-1], [parent])
for child in node[1]:
dfs(child, nodemap[id(node)])
else:
nodemap[id(node)][1].append(parent)
for node in dafsa:
dfs(node, None)
return sink
def join_labels(dafsa):
"""Generates a new DAFSA where internal nodes are merged if there is a one to
one connection.
"""
parentcount = { id(None): 2 }
nodemap = { id(None): None }
"""Generates a new DAFSA where internal nodes are merged if there is a one to
one connection.
"""
parentcount = {id(None): 2}
nodemap = {id(None): None}
def count_parents(node):
"""Count incoming references"""
if id(node) in parentcount:
parentcount[id(node)] += 1
else:
parentcount[id(node)] = 1
for child in node[1]:
count_parents(child)
def count_parents(node):
"""Count incoming references"""
if id(node) in parentcount:
parentcount[id(node)] += 1
else:
parentcount[id(node)] = 1
for child in node[1]:
count_parents(child)
def join(node):
"""Create new nodes"""
if id(node) not in nodemap:
children = [join(child) for child in node[1]]
if len(children) == 1 and parentcount[id(node[1][0])] == 1:
child = children[0]
nodemap[id(node)] = (node[0] + child[0], child[1])
else:
nodemap[id(node)] = (node[0], children)
return nodemap[id(node)]
def join(node):
"""Create new nodes"""
if id(node) not in nodemap:
children = [join(child) for child in node[1]]
if len(children) == 1 and parentcount[id(node[1][0])] == 1:
child = children[0]
nodemap[id(node)] = (node[0] + child[0], child[1])
else:
nodemap[id(node)] = (node[0], children)
return nodemap[id(node)]
for node in dafsa:
count_parents(node)
return [join(node) for node in dafsa]
for node in dafsa:
count_parents(node)
return [join(node) for node in dafsa]
def join_suffixes(dafsa):
"""Generates a new DAFSA where nodes that represent the same word lists
towards the sink are merged.
"""
nodemap = { frozenset(('',)): None }
def join(node):
"""Returns a macthing node. A new node is created if no matching node
exists. The graph is accessed in dfs order.
"""Generates a new DAFSA where nodes that represent the same word lists
towards the sink are merged.
"""
suffixes = frozenset(to_words(node))
if suffixes not in nodemap:
nodemap[suffixes] = (node[0], [join(child) for child in node[1]])
return nodemap[suffixes]
nodemap = {frozenset(('',)): None}
return [join(node) for node in dafsa]
def join(node):
"""Returns a macthing node. A new node is created if no matching node
exists. The graph is accessed in dfs order.
"""
suffixes = frozenset(to_words(node))
if suffixes not in nodemap:
nodemap[suffixes] = (node[0], [join(child) for child in node[1]])
return nodemap[suffixes]
return [join(node) for node in dafsa]
def top_sort(dafsa):
"""Generates list of nodes in topological sort order."""
incoming = {}
"""Generates list of nodes in topological sort order."""
incoming = {}
def count_incoming(node):
"""Counts incoming references."""
if node:
if id(node) not in incoming:
incoming[id(node)] = 1
def count_incoming(node):
"""Counts incoming references."""
if node:
if id(node) not in incoming:
incoming[id(node)] = 1
for child in node[1]:
count_incoming(child)
else:
incoming[id(node)] += 1
for node in dafsa:
count_incoming(node)
for node in dafsa:
incoming[id(node)] -= 1
waiting = [node for node in dafsa if incoming[id(node)] == 0]
nodes = []
while waiting:
node = waiting.pop()
assert incoming[id(node)] == 0
nodes.append(node)
for child in node[1]:
count_incoming(child)
else:
incoming[id(node)] += 1
for node in dafsa:
count_incoming(node)
for node in dafsa:
incoming[id(node)] -= 1
waiting = [node for node in dafsa if incoming[id(node)] == 0]
nodes = []
while waiting:
node = waiting.pop()
assert incoming[id(node)] == 0
nodes.append(node)
for child in node[1]:
if child:
incoming[id(child)] -= 1
if incoming[id(child)] == 0:
waiting.append(child)
return nodes
if child:
incoming[id(child)] -= 1
if incoming[id(child)] == 0:
waiting.append(child)
return nodes
def encode_links(children, offsets, current):
"""Encodes a list of children as one, two or three byte offsets."""
if not children[0]:
# This is an <end_label> node and no links follow such nodes
assert len(children) == 1
return []
guess = 3 * len(children)
assert children
children = sorted(children, key = lambda x: -offsets[id(x)])
while True:
offset = current + guess
buf = []
for child in children:
last = len(buf)
distance = offset - offsets[id(child)]
assert distance > 0 and distance < (1 << 21)
"""Encodes a list of children as one, two or three byte offsets."""
if not children[0]:
# This is an <end_label> node and no links follow such nodes
assert len(children) == 1
return []
guess = 3 * len(children)
assert children
children = sorted(children, key=lambda x: -offsets[id(x)])
while True:
offset = current + guess
buf = []
for child in children:
last = len(buf)
distance = offset - offsets[id(child)]
assert distance > 0 and distance < (1 << 21)
if distance < (1 << 6):
# A 6-bit offset: "s0xxxxxx"
buf.append(distance)
elif distance < (1 << 13):
# A 13-bit offset: "s10xxxxxxxxxxxxx"
buf.append(0x40 | (distance >> 8))
buf.append(distance & 0xFF)
else:
# A 21-bit offset: "s11xxxxxxxxxxxxxxxxxxxxx"
buf.append(0x60 | (distance >> 16))
buf.append((distance >> 8) & 0xFF)
buf.append(distance & 0xFF)
# Distance in first link is relative to following record.
# Distance in other links are relative to previous link.
offset -= distance
if len(buf) == guess:
break
guess = len(buf)
# Set most significant bit to mark end of links in this node.
buf[last] |= (1 << 7)
buf.reverse()
return buf
if distance < (1 << 6):
# A 6-bit offset: "s0xxxxxx"
buf.append(distance)
elif distance < (1 << 13):
# A 13-bit offset: "s10xxxxxxxxxxxxx"
buf.append(0x40 | (distance >> 8))
buf.append(distance & 0xFF)
else:
# A 21-bit offset: "s11xxxxxxxxxxxxxxxxxxxxx"
buf.append(0x60 | (distance >> 16))
buf.append((distance >> 8) & 0xFF)
buf.append(distance & 0xFF)
# Distance in first link is relative to following record.
# Distance in other links are relative to previous link.
offset -= distance
if len(buf) == guess:
break
guess = len(buf)
# Set most significant bit to mark end of links in this node.
buf[last] |= (1 << 7)
buf.reverse()
return buf
def encode_prefix(label):
"""Encodes a node label as a list of bytes without a trailing high byte.
"""Encodes a node label as a list of bytes without a trailing high byte.
This method encodes a node if there is exactly one child and the
child follows immidiately after so that no jump is needed. This label
will then be a prefix to the label in the child node.
"""
assert label
return [ord(c) for c in reversed(label)]
This method encodes a node if there is exactly one child and the
child follows immidiately after so that no jump is needed. This label
will then be a prefix to the label in the child node.
"""
assert label
return [ord(c) for c in reversed(label)]
def encode_label(label):
"""Encodes a node label as a list of bytes with a trailing high byte >0x80.
"""
buf = encode_prefix(label)
# Set most significant bit to mark end of label in this node.
buf[0] |= (1 << 7)
return buf
"""Encodes a node label as a list of bytes with a trailing high byte >0x80.
"""
buf = encode_prefix(label)
# Set most significant bit to mark end of label in this node.
buf[0] |= (1 << 7)
return buf
def encode(dafsa):
"""Encodes a DAFSA to a list of bytes"""
output = []
offsets = {}
"""Encodes a DAFSA to a list of bytes"""
output = []
offsets = {}
for node in reversed(top_sort(dafsa)):
if (len(node[1]) == 1 and node[1][0] and
(offsets[id(node[1][0])] == len(output))):
output.extend(encode_prefix(node[0]))
else:
output.extend(encode_links(node[1], offsets, len(output)))
output.extend(encode_label(node[0]))
offsets[id(node)] = len(output)
for node in reversed(top_sort(dafsa)):
if (len(node[1]) == 1 and node[1][0] and
(offsets[id(node[1][0])] == len(output))):
output.extend(encode_prefix(node[0]))
else:
output.extend(encode_links(node[1], offsets, len(output)))
output.extend(encode_label(node[0]))
offsets[id(node)] = len(output)
output.extend(encode_links(dafsa, offsets, len(output)))
output.reverse()
return output
output.extend(encode_links(dafsa, offsets, len(output)))
output.reverse()
return output
def to_cxx(data, preamble=None):
"""Generates C++ code from a list of encoded bytes."""
text = '/* This file is generated. DO NOT EDIT!\n\n'
text += 'The byte array encodes a dictionary of strings and values. See '
text += 'make_dafsa.py for documentation.'
text += '*/\n\n'
"""Generates C++ code from a list of encoded bytes."""
text = '/* This file is generated. DO NOT EDIT!\n\n'
text += 'The byte array encodes a dictionary of strings and values. See '
text += 'make_dafsa.py for documentation.'
text += '*/\n\n'
if preamble:
text += preamble
text += '\n\n'
if preamble:
text += preamble
text += '\n\n'
text += 'const unsigned char kDafsa[%s] = {\n' % len(data)
for i in range(0, len(data), 12):
text += ' '
text += ', '.join('0x%02x' % byte for byte in data[i:i + 12])
text += ',\n'
text += '};\n'
return text
text += 'const unsigned char kDafsa[%s] = {\n' % len(data)
for i in range(0, len(data), 12):
text += ' '
text += ', '.join('0x%02x' % byte for byte in data[i:i + 12])
text += ',\n'
text += '};\n'
return text
def words_to_cxx(words, preamble=None):
"""Generates C++ code from a word list"""
dafsa = to_dafsa(words)
for fun in (reverse, join_suffixes, reverse, join_suffixes, join_labels):
dafsa = fun(dafsa)
return to_cxx(encode(dafsa), preamble)
"""Generates C++ code from a word list"""
dafsa = to_dafsa(words)
for fun in (reverse, join_suffixes, reverse, join_suffixes, join_labels):
dafsa = fun(dafsa)
return to_cxx(encode(dafsa), preamble)
def parse_gperf(infile):
"""Parses gperf file and extract strings and return code"""
lines = [line.strip() for line in infile]
"""Parses gperf file and extract strings and return code"""
lines = [line.strip() for line in infile]
# Extract the preamble.
first_delimeter = lines.index('%%')
preamble = '\n'.join(lines[0:first_delimeter])
# Extract the preamble.
first_delimeter = lines.index('%%')
preamble = '\n'.join(lines[0:first_delimeter])
# Extract strings after the first '%%' and before the second '%%'.
begin = first_delimeter + 1
end = lines.index('%%', begin)
lines = lines[begin:end]
for line in lines:
if line[-3:-1] != ', ':
raise InputError('Expected "domainname, <digit>", found "%s"' % line)
# Technically the DAFSA format could support return values in range [0-31],
# but the values below are the only with a defined meaning.
if line[-1] not in '0124':
raise InputError('Expected value to be one of {0,1,2,4}, found "%s"' %
line[-1])
return (preamble, [line[:-3] + line[-1] for line in lines])
# Extract strings after the first '%%' and before the second '%%'.
begin = first_delimeter + 1
end = lines.index('%%', begin)
lines = lines[begin:end]
for line in lines:
if line[-3:-1] != ', ':
raise InputError('Expected "domainname, <digit>", found "%s"' % line)
# Technically the DAFSA format could support return values in range [0-31],
# but the values below are the only with a defined meaning.
if line[-1] not in '0124':
raise InputError('Expected value to be one of {0,1,2,4}, found "%s"' %
line[-1])
return (preamble, [line[:-3] + line[-1] for line in lines])
def main(outfile, infile):
with open(infile, 'r') as infile:
preamble, words = parse_gperf(infile)
outfile.write(words_to_cxx(words, preamble))
return 0
with open(infile, 'r') as infile:
preamble, words = parse_gperf(infile)
outfile.write(words_to_cxx(words, preamble))
return 0
if __name__ == '__main__':
if len(sys.argv) != 3:
print('usage: %s infile outfile' % sys.argv[0])
sys.exit(1)
if len(sys.argv) != 3:
print('usage: %s infile outfile' % sys.argv[0])
sys.exit(1)
with open(sys.argv[2], 'w') as outfile:
sys.exit(main(outfile, sys.argv[1]))
with open(sys.argv[2], 'w') as outfile:
sys.exit(main(outfile, sys.argv[1]))

Просмотреть файл

@ -65,11 +65,11 @@ def attributeParamlist(a, getter):
return ", ".join(l)
def attributeAsNative(a, getter, declType = 'NS_IMETHOD'):
params = {'returntype': attributeReturnType(a, declType),
'binaryname': attributeNativeName(a, getter),
'paramlist': attributeParamlist(a, getter)}
return "%(returntype)s %(binaryname)s(%(paramlist)s)" % params
def attributeAsNative(a, getter, declType='NS_IMETHOD'):
params = {'returntype': attributeReturnType(a, declType),
'binaryname': attributeNativeName(a, getter),
'paramlist': attributeParamlist(a, getter)}
return "%(returntype)s %(binaryname)s(%(paramlist)s)" % params
def methodNativeName(m):
@ -92,7 +92,7 @@ def methodReturnType(m, macro):
return ret
def methodAsNative(m, declType = 'NS_IMETHOD'):
def methodAsNative(m, declType='NS_IMETHOD'):
return "%s %s(%s)" % (methodReturnType(m, declType),
methodNativeName(m),
paramlistAsNative(m))
@ -159,6 +159,7 @@ def paramlistNames(m):
return ''
return ', '.join(names)
header = """/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM %(filename)s
*/
@ -337,6 +338,7 @@ def write_interface(iface, fd):
# Confirm that no names of methods will overload in this interface
names = set()
def record_name(name):
if name in names:
raise Exception("Unexpected overloaded virtual method %s in interface %s"
@ -383,7 +385,7 @@ def write_interface(iface, fd):
if a.realtype.kind != 'builtin':
assert realtype.endswith(' *'), "bad infallible type"
tmpl = attr_refcnt_infallible_tmpl
realtype = realtype[:-2] # strip trailing pointer
realtype = realtype[:-2] # strip trailing pointer
fd.write(tmpl % {'realtype': realtype,
'nativename': attributeNativeName(a, getter=True),
@ -453,7 +455,8 @@ def write_interface(iface, fd):
for member in iface.members:
if isinstance(member, xpidl.Attribute):
if member.infallible:
fd.write("\\\n using %s::%s; " % (iface.name, attributeNativeName(member, True)))
fd.write("\\\n using %s::%s; " %
(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))
@ -464,9 +467,9 @@ def write_interface(iface, fd):
elif not member.kind in ('attribute', 'method'):
fd.write('\\')
writeDeclaration(fd, iface, True);
writeDeclaration(fd, iface, True)
fd.write(iface_nonvirtual % names)
writeDeclaration(fd, iface, False);
writeDeclaration(fd, iface, False)
fd.write(iface_forward % names)
def emitTemplate(forward_infallible, tmpl, tmpl_notxpcom=None):
@ -475,7 +478,8 @@ def write_interface(iface, fd):
for member in iface.members:
if isinstance(member, xpidl.Attribute):
if forward_infallible and member.infallible:
fd.write("\\\n using %s::%s; " % (iface.name, attributeNativeName(member, True)))
fd.write("\\\n using %s::%s; " %
(iface.name, attributeNativeName(member, True)))
fd.write(tmpl % {'asNative': attributeAsNative(member, True),
'nativeName': attributeNativeName(member, True),
'paramList': attributeParamNames(member)})
@ -527,5 +531,6 @@ def main(outputfile):
# Instantiate the parser.
p = xpidl.IDLParser(outputdir=cachedir)
if __name__ == '__main__':
main(None)

Просмотреть файл

@ -58,7 +58,7 @@ def get_type(type, calltype, iid_is=None, size_is=None):
type = type.realtype
if isinstance(type, xpidl.Builtin):
ret = { 'tag': TypeMap[type.name] }
ret = {'tag': TypeMap[type.name]}
if type.name in ['string', 'wstring'] and size_is is not None:
ret['tag'] += '_SIZE_IS'
ret['size_is'] = size_is
@ -98,7 +98,7 @@ def get_type(type, calltype, iid_is=None, size_is=None):
'iid_is': iid_is,
}
else:
return { 'tag': 'TD_VOID' }
return {'tag': 'TD_VOID'}
raise Exception("Unknown type!")
@ -156,7 +156,7 @@ def build_interface(iface):
consts.append({
'name': c.name,
'type': get_type(c.basetype, ''),
'value': c.getValue(), # All of our consts are numbers
'value': c.getValue(), # All of our consts are numbers
})
def build_method(m):
@ -240,6 +240,8 @@ def build_typelib(idl):
return [build_interface(p) for p in idl.productions if exported(p)]
# Link a list of typelibs together into a single typelib
def link(typelibs):
linked = list(itertools.chain.from_iterable(typelibs))
assert len(set(iface['name'] for iface in linked)) == len(linked), \
@ -247,5 +249,7 @@ def link(typelibs):
return linked
# Write the typelib into the fd file
def write(typelib, fd):
json.dump(typelib, fd, indent=2)

Просмотреть файл

@ -33,7 +33,8 @@ class TestParser(unittest.TestCase):
self.assertEqual("foo", i.productions[0].name)
def testAttributes(self):
i = self.p.parse("[scriptable, builtinclass, function, uuid(abc)] interface foo {};", filename='f')
i = self.p.parse(
"[scriptable, builtinclass, function, uuid(abc)] interface foo {};", filename='f')
self.assertTrue(isinstance(i, xpidl.IDL))
self.assertTrue(isinstance(i.productions[0], xpidl.Interface))
iface = i.productions[0]
@ -101,13 +102,16 @@ attribute long bar;
void getBar();
};""", filename='f')
self.assertTrue(isinstance(i, xpidl.IDL))
class FdMock:
def write(self, s):
pass
try:
header.print_header(i, FdMock(), filename='f')
except Exception as e:
self.assertEqual(e.args[0], "Unexpected overloaded virtual method GetBar in interface foo")
self.assertEqual(
e.args[0], "Unexpected overloaded virtual method GetBar in interface foo")
if __name__ == '__main__':
mozunit.main(runwith='unittest')

Просмотреть файл

@ -207,6 +207,7 @@ pub unsafe fn %(name)s(&self, %(params)s) -> %(ret_ty)s {
}
"""
def methodAsWrapper(iface, m):
try:
param_list = methodRawParamList(iface, m)
@ -235,6 +236,7 @@ pub unsafe fn %(name)s(&self) -> %(realtype)s {
}
"""
def attrAsWrapper(iface, m, getter):
try:
if m.implicit_jscontext:
@ -304,7 +306,7 @@ def print_rust_bindings(idl, fd, filename):
if printdoccomments:
fd.write("/// `typedef %s %s;`\n///\n" %
(p.realtype.nativeType('in'), p.name))
(p.realtype.nativeType('in'), p.name))
fd.write(doccomments(p.doccomments))
fd.write("pub type %s = %s;\n\n" % (p.name, p.realtype.rustType('in')))
except xpidl.RustNoncompat as reason:
@ -481,10 +483,10 @@ def write_interface(iface, fd):
if printdoccomments:
if iface.base is not None:
fd.write("/// `interface %s : %s`\n///\n" %
(iface.name, iface.base))
(iface.name, iface.base))
else:
fd.write("/// `interface %s`\n///\n" %
iface.name)
iface.name)
printComments(fd, iface.doccomments, '')
fd.write(struct_tmpl % names)

Просмотреть файл

@ -52,7 +52,8 @@ def attlistToIDL(attlist):
attlist.sort(cmp=lambda a, b: cmp(a[0], b[0]))
return '[%s] ' % ','.join(["%s%s" % (name, value is not None and '(%s)' % value or '')
for name, value, aloc in attlist])
for name, value, aloc in attlist])
_paramsHardcode = {
2: ('array', 'shared', 'iid_is', 'size_is', 'retval'),
@ -131,7 +132,8 @@ class Builtin(object):
def nativeType(self, calltype, shared=False, const=False):
if const:
print >>sys.stderr, IDLError("[const] doesn't make sense on builtin types.", self.location, warning=True)
print >>sys.stderr, IDLError(
"[const] doesn't make sense on builtin types.", self.location, warning=True)
const = 'const '
elif calltype == 'in' and self.isPointer():
const = 'const '
@ -154,6 +156,7 @@ class Builtin(object):
return "%s%s" % (calltype != 'in' and '*mut ' or '', rustname)
builtinNames = [
Builtin('boolean', 'bool', 'bool'),
Builtin('void', 'void', 'libc::c_void'),
@ -220,6 +223,7 @@ class Location(object):
class NameMap(object):
"""Map of name -> object. Each object must have a .name and .location property.
Setting the same name twice throws an error."""
def __init__(self):
self._d = {}
@ -236,7 +240,8 @@ class NameMap(object):
def set(self, object):
if object.name in builtinMap:
raise IDLError("name '%s' is a builtin and cannot be redeclared" % (object.name), object.location)
raise IDLError("name '%s' is a builtin and cannot be redeclared" %
(object.name), object.location)
if object.name.startswith("_"):
object.name = object.name[1:]
if object.name in self._d:
@ -248,7 +253,8 @@ class NameMap(object):
elif isinstance(old, Interface) and isinstance(object, Forward):
pass
else:
raise IDLError("name '%s' specified twice. Previous location: %s" % (object.name, self._d[object.name].location), object.location)
raise IDLError("name '%s' specified twice. Previous location: %s" %
(object.name, self._d[object.name].location), object.location)
else:
self._d[object.name] = object
@ -261,6 +267,7 @@ class NameMap(object):
class RustNoncompat(Exception):
"""Thie exception is raised when a particular type or function cannot be safely exposed to rust code"""
def __init__(self, reason):
self.reason = reason
@ -659,7 +666,8 @@ class Interface(object):
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)
raise IDLError(
"interface '%s' has multiple methods, but marked 'function'" % self.name, self.location)
else:
has_method = True
@ -667,16 +675,19 @@ class Interface(object):
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)
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'" % (self.name, self.base), self.location, warning=True)
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)
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
self.implicit_builtinclass = True # Inherit implicit builtinclass from base
for member in self.members:
member.resolve(self)
@ -789,7 +800,7 @@ class InterfaceAttributes(object):
'main_process_scriptable_only': (False, setmain_process_scriptable_only),
'shim': (True, setshim),
'shimfile': (True, setshimfile),
}
}
def __init__(self, attlist, location):
def badattribute(self):
@ -849,7 +860,8 @@ class ConstMember(object):
while isinstance(basetype, Typedef):
basetype = basetype.realtype
if not isinstance(basetype, Builtin) or not basetype.maybeConst:
raise IDLError("const may only be a short or long type, not %s" % self.type, self.location)
raise IDLError("const may only be a short or long type, not %s" %
self.type, self.location)
self.basetype = basetype
@ -1024,16 +1036,19 @@ class Method(object):
p.resolve(self)
for p in self.params:
if p.retval and p != self.params[-1]:
raise IDLError("'retval' parameter '%s' is not the last parameter" % p.name, self.location)
raise IDLError("'retval' parameter '%s' is not the last parameter" %
p.name, self.location)
if p.size_is:
found_size_param = False
for size_param in self.params:
if p.size_is == size_param.name:
found_size_param = True
if getBuiltinOrNativeTypeName(size_param.realtype) != 'unsigned long':
raise IDLError("is_size parameter must have type 'unsigned long'", self.location)
raise IDLError(
"is_size parameter must have type 'unsigned long'", self.location)
if not found_size_param:
raise IDLError("could not find is_size parameter '%s'" % p.size_is, self.location)
raise IDLError("could not find is_size parameter '%s'" %
p.size_is, self.location)
def isScriptable(self):
if not self.iface.attributes.scriptable:
@ -1214,7 +1229,7 @@ class IDLParser(object):
'native': 'NATIVE',
'typedef': 'TYPEDEF',
'webidl': 'WEBIDL',
}
}
tokens = [
'IDENTIFIER',
@ -1226,7 +1241,7 @@ class IDLParser(object):
'LSHIFT',
'RSHIFT',
'NATIVEID',
]
]
tokens.extend(keywords.values())
@ -1401,7 +1416,7 @@ class IDLParser(object):
doccomments.extend(atts['doccomments'])
doccomments.extend(p.slice[2].doccomments)
l = lambda: self.getLocation(p, 2)
def l(): return self.getLocation(p, 2)
if body is None:
# forward-declared interface... must not have attributes!
@ -1598,7 +1613,8 @@ class IDLParser(object):
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)
raise IDLError(
"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)
@ -1638,6 +1654,7 @@ 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:]:

Просмотреть файл

@ -32,16 +32,20 @@ U32_HIGH_BIT = 0x80000000
# used as the offset basis for indexing into the values table.
#
# NOTE: C++ implementation is in xptinfo.cpp
def hash(bytes, h=FNV_OFFSET_BASIS):
for byte in bytes:
h ^= byte # xor-in the byte
h *= FNV_PRIME # Multiply by the FNV prime
h &= 0xffffffff # clamp to 32-bits
h &= 0xffffffff # clamp to 32-bits
return h
IntermediateBucket = namedtuple('IntermediateBucket', ['index', 'entries'])
HashEntry = namedtuple('HashEntry', ['key', 'value'])
class PerfectHash(object):
"""An object representing a perfect hash function"""

Просмотреть файл

@ -18,14 +18,17 @@ from collections import OrderedDict
# generate a more efficient modulo due to it being a power of 2.
PHFSIZE = 512
def indented(s):
return s.replace('\n', '\n ')
def cpp(v):
if type(v) == bool:
return "true" if v else "false"
return str(v)
def mkstruct(*fields):
def mk(comment, **vals):
assert len(fields) == len(vals)
@ -36,6 +39,7 @@ def mkstruct(*fields):
return r
return mk
##########################################################
# Ensure these fields are in the same order as xptinfo.h #
##########################################################
@ -129,11 +133,13 @@ def split_at_idxs(s, lengths):
idx += length
assert idx == len(s)
def split_iid(iid): # Get the individual components out of an IID string.
iid = iid.replace('-', '') # Strip any '-' delimiters
def split_iid(iid): # Get the individual components out of an IID string.
iid = iid.replace('-', '') # Strip any '-' delimiters
return tuple(split_at_idxs(iid, (8, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2)))
def iid_bytes(iid): # Get the byte representation of the IID for hashing.
def iid_bytes(iid): # Get the byte representation of the IID for hashing.
bs = bytearray()
for num in split_iid(iid):
b = bytearray.fromhex(num)
@ -145,6 +151,8 @@ def iid_bytes(iid): # Get the byte representation of the IID for hashing.
return bs
# Split a 16-bit integer into its high and low 8 bits
def splitint(i):
assert i < 2**16
return (i >> 8, i & 0xff)
@ -157,23 +165,23 @@ def splitint(i):
# These are some types which should have known indexes into the extra types
# array.
utility_types = [
{ 'tag': 'TD_INT8' },
{ 'tag': 'TD_UINT8' },
{ 'tag': 'TD_INT16' },
{ 'tag': 'TD_UINT16' },
{ 'tag': 'TD_INT32' },
{ 'tag': 'TD_UINT32' },
{ 'tag': 'TD_INT64' },
{ 'tag': 'TD_UINT64' },
{ 'tag': 'TD_FLOAT' },
{ 'tag': 'TD_DOUBLE' },
{ 'tag': 'TD_BOOL' },
{ 'tag': 'TD_CHAR' },
{ 'tag': 'TD_WCHAR' },
{ 'tag': 'TD_PNSIID' },
{ 'tag': 'TD_PSTRING' },
{ 'tag': 'TD_PWSTRING' },
{ 'tag': 'TD_INTERFACE_IS_TYPE', 'iid_is': 0 },
{'tag': 'TD_INT8'},
{'tag': 'TD_UINT8'},
{'tag': 'TD_INT16'},
{'tag': 'TD_UINT16'},
{'tag': 'TD_INT32'},
{'tag': 'TD_UINT32'},
{'tag': 'TD_INT64'},
{'tag': 'TD_UINT64'},
{'tag': 'TD_FLOAT'},
{'tag': 'TD_DOUBLE'},
{'tag': 'TD_BOOL'},
{'tag': 'TD_CHAR'},
{'tag': 'TD_WCHAR'},
{'tag': 'TD_PNSIID'},
{'tag': 'TD_PSTRING'},
{'tag': 'TD_PWSTRING'},
{'tag': 'TD_INTERFACE_IS_TYPE', 'iid_is': 0},
]
@ -195,7 +203,7 @@ def link_to_cpp(interfaces, fd):
if name is not None:
idx = name_phf.lookup(bytearray(name, 'ascii'))
if iid_phf.values[idx]['name'] == name:
return idx + 1 # One-based, so we can use 0 as a sentinel.
return idx + 1 # One-based, so we can use 0 as a sentinel.
return 0
# NOTE: State used while linking. This is done with closures rather than a
@ -228,7 +236,7 @@ def link_to_cpp(interfaces, fd):
"%d = %s" % (idx, do['name']),
# These methods are defined at the top of the generated file.
mUnwrap="UnwrapDOMObject<mozilla::dom::prototypes::id::%s, %s>" %
(do['name'], do['native']),
(do['name'], do['native']),
mWrap="WrapDOMObject<%s>" % do['native'],
mCleanup="CleanupDOMObject<%s>" % do['native'],
))
@ -255,7 +263,7 @@ def link_to_cpp(interfaces, fd):
types.append(lower_type(type))
return idx
def describe_type(type): # Create the type's documentation comment.
def describe_type(type): # Create the type's documentation comment.
tag = type['tag'][3:].lower()
if tag == 'array':
return '%s[size_is=%d]' % (
@ -312,7 +320,7 @@ def link_to_cpp(interfaces, fd):
methodname = "%s::%s" % (ifacename, method['name'])
if 'notxpcom' in method['flags'] or 'hidden' in method['flags']:
paramidx = name = numparams = 0 # hide parameters
paramidx = name = numparams = 0 # hide parameters
else:
name = lower_string(method['name'])
numparams = len(method['params'])
@ -361,17 +369,17 @@ def link_to_cpp(interfaces, fd):
mValue="(uint32_t)%d" % const['value'],
))
def lower_prop_hooks(iface): # XXX: Used by xpt shims
def lower_prop_hooks(iface): # XXX: Used by xpt shims
assert iface['shim'] is not None
# Add an include for the Binding file for the shim.
includes.add("mozilla/dom/%sBinding.h" %
(iface['shimfile'] or iface['shim']))
(iface['shimfile'] or iface['shim']))
# Add the property hook reference to the sPropHooks table.
prophooks.append(
"mozilla::dom::%sBinding::sNativePropertyHooks, // %d = %s(%s)" % \
(iface['shim'], len(prophooks), iface['name'], iface['shim']))
"mozilla::dom::%sBinding::sNativePropertyHooks, // %d = %s(%s)" %
(iface['shim'], len(prophooks), iface['name'], iface['shim']))
def collect_base_info(iface):
methods = 0
@ -493,7 +501,7 @@ namespace detail {
# Static data arrays
def array(ty, name, els):
fd.write("const %s %s[] = {%s\n};\n\n" %
(ty, name, ','.join(indented('\n' + str(e)) for e in els)))
(ty, name, ','.join(indented('\n' + str(e)) for e in els)))
array("nsXPTInterfaceInfo", "sInterfaces", ifaces)
array("nsXPTType", "sTypes", types)
array("nsXPTParamInfo", "sParams", params)
@ -572,5 +580,6 @@ def main():
with open(args.outfile, 'w') as fd:
link_and_write(args.xpts, fd)
if __name__ == '__main__':
main()

Просмотреть файл

@ -45,6 +45,7 @@ def get_output(bin, file):
stdout, _ = p.communicate()
return stdout
if "MOZILLA_OBJDIR" in os.environ:
class CheckXPTDump(unittest.TestCase):
def test_xpt_dump_diffs(self):
@ -270,15 +271,18 @@ class TestTypelibRoundtrip(unittest.TestCase, TypelibCompareMixin):
i.methods.append(xpt.Method("One", xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)),
params=[
xpt.Param(xpt.SimpleType(xpt.Type.Tags.int64)),
xpt.Param(xpt.SimpleType(xpt.Type.Tags.float, pointer=True))
]))
xpt.Param(xpt.SimpleType(
xpt.Type.Tags.float, pointer=True))
]))
self.checkRoundtrip(t)
# test some other types (should really be more thorough)
i.methods.append(xpt.Method("Two", xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)),
params=[
xpt.Param(xpt.SimpleType(xpt.Type.Tags.UTF8String, pointer=True)),
xpt.Param(xpt.SimpleType(xpt.Type.Tags.wchar_t_ptr, pointer=True))
]))
xpt.Param(xpt.SimpleType(
xpt.Type.Tags.UTF8String, pointer=True)),
xpt.Param(xpt.SimpleType(
xpt.Type.Tags.wchar_t_ptr, pointer=True))
]))
self.checkRoundtrip(t)
# add a method with an InterfaceType argument
bar = xpt.Interface("IBar")
@ -286,7 +290,7 @@ class TestTypelibRoundtrip(unittest.TestCase, TypelibCompareMixin):
i.methods.append(xpt.Method("IFaceMethod", xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)),
params=[
xpt.Param(xpt.InterfaceType(bar))
]))
]))
self.checkRoundtrip(t)
# add a method with an InterfaceIsType argument
@ -294,7 +298,7 @@ class TestTypelibRoundtrip(unittest.TestCase, TypelibCompareMixin):
params=[
xpt.Param(xpt.InterfaceIsType(1)),
xpt.Param(xpt.SimpleType(xpt.Type.Tags.nsIID))
]))
]))
self.checkRoundtrip(t)
# add a method with an ArrayType argument
@ -305,7 +309,7 @@ class TestTypelibRoundtrip(unittest.TestCase, TypelibCompareMixin):
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
@ -319,7 +323,7 @@ class TestTypelibRoundtrip(unittest.TestCase, TypelibCompareMixin):
4, 5)),
xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)),
xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)),
]))
]))
self.checkRoundtrip(t)
@ -406,10 +410,12 @@ class TestXPTLink(unittest.TestCase):
# Add some IID values
t1 = xpt.Typelib()
# add an unresolved interface
t1.interfaces.append(xpt.Interface("IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", scriptable=True))
t1.interfaces.append(xpt.Interface(
"IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", scriptable=True))
t2 = xpt.Typelib()
# add an unresolved interface
t2.interfaces.append(xpt.Interface("IBar", iid="44332211-6655-8877-0099-aabbccddeeff", scriptable=True))
t2.interfaces.append(xpt.Interface(
"IBar", iid="44332211-6655-8877-0099-aabbccddeeff", scriptable=True))
t3 = xpt.xpt_link([t1, t2])
self.assertEqual(2, len(t3.interfaces))
@ -451,7 +457,8 @@ class TestXPTLink(unittest.TestCase):
# Unresolved in both, but t1 has an IID value
t1 = xpt.Typelib()
# add an unresolved interface with a valid IID
t1.interfaces.append(xpt.Interface("IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", scriptable=True))
t1.interfaces.append(xpt.Interface(
"IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", scriptable=True))
t2 = xpt.Typelib()
# add an unresolved interface, no IID
t2.interfaces.append(xpt.Interface("IFoo"))
@ -466,7 +473,8 @@ class TestXPTLink(unittest.TestCase):
t1.interfaces.append(xpt.Interface("IFoo"))
t2 = xpt.Typelib()
# add an unresolved interface with a valid IID
t2.interfaces.append(xpt.Interface("IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", scriptable=True))
t2.interfaces.append(xpt.Interface(
"IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", scriptable=True))
t3 = xpt.xpt_link([t1, t2])
self.assertEqual(1, len(t3.interfaces))
@ -766,5 +774,6 @@ class TestXPTLink(unittest.TestCase):
self.assertEqual(t3.interfaces[1],
t3.interfaces[0].methods[0].params[0].type.element_type.iface)
if __name__ == '__main__':
mozunit.main()

Просмотреть файл

@ -296,7 +296,7 @@ class Type(object):
'CString',
'AString',
'jsval',
)
)
def __init__(self, pointer=False, reference=False):
self.pointer = pointer
@ -757,6 +757,7 @@ class CachedStringWriter(object):
A cache that sits in front of a file to avoid adding the same
string multiple times.
"""
def __init__(self, file, data_pool_offset):
self.file = file
self.data_pool_offset = data_pool_offset
@ -1075,6 +1076,7 @@ class Method(object):
self.encodeflags(),
num_params)
class Constant(object):
"""
A constant value of a specific type defined on an interface.
@ -1196,7 +1198,8 @@ class Interface(object):
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)
raise DataError(
"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
@ -1468,7 +1471,8 @@ class Typelib(object):
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))
raise FileFormatError(
"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
@ -1522,14 +1526,17 @@ class Typelib(object):
self.interfaces.sort()
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))
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,
@ -1661,7 +1668,7 @@ class Typelib(object):
str(m.result.type),
m.name,
m.params and ", ".join(str(p) for p in m.params) or ""
))
))
out.write(" Constants:\n")
if len(i.constants) == 0:
out.write(" No Constants\n")
@ -1786,7 +1793,7 @@ def xpt_link(inputs):
elif isinstance(t, ArrayType) and \
isinstance(t.element_type, InterfaceType) and \
t.element_type.iface in merged_interfaces:
t.element_type.iface = merged_interfaces[t.element_type.iface]
t.element_type.iface = merged_interfaces[t.element_type.iface]
for i in interfaces:
# Replace parent references
@ -1831,6 +1838,7 @@ def xpt_link(inputs):
interfaces.sort()
return Typelib(interfaces=interfaces)
if __name__ == '__main__':
if len(sys.argv) < 3:
print >>sys.stderr, "xpt <dump|link|linkgen> <files>"