diff -up mozilla-esr17/build/appini_header.py.python mozilla-esr17/build/appini_header.py --- mozilla-esr17/build/appini_header.py.python 2013-06-18 20:47:00.000000000 +0200 +++ mozilla-esr17/build/appini_header.py 2013-06-19 23:09:22.000000000 +0200 @@ -25,8 +25,13 @@ def main(file): flags.add('NS_XRE_ENABLE_CRASH_REPORTER') except: pass appdata = dict(("%s:%s" % (s, o), config.get(s, o)) for s in config.sections() for o in config.options(s)) - appdata['flags'] = ' | '.join(flags) if flags else '0' - appdata['App:profile'] = '"%s"' % appdata['App:profile'] if 'App:profile' in appdata else 'NULL' + appdata['flags'] = '0' + if flags: + appdata['flags'] = ' | '.join(flags) + + appdata['App:profile'] = 'NULL' + if 'App:profile' in appdata: + appdata['App:profile'] = '"%s"' % appdata['App:profile'] print '''#include "nsXREAppData.h" static const nsXREAppData sAppData = { diff -up mozilla-esr17/build/ConfigStatus.py.python mozilla-esr17/build/ConfigStatus.py --- mozilla-esr17/build/ConfigStatus.py.python 2013-06-18 20:47:00.000000000 +0200 +++ mozilla-esr17/build/ConfigStatus.py 2013-06-19 23:09:22.000000000 +0200 @@ -6,7 +6,6 @@ # drop-in replacement for autoconf 2.13's config.status, with features # borrowed from autoconf > 2.5, and additional features. -from __future__ import with_statement from optparse import OptionParser import sys, re, os, posixpath, ntpath from StringIO import StringIO @@ -76,13 +75,13 @@ class FileAvoidWrite(StringIO): return except IOError: pass - finally: - file.close() + file.close() log("creating %s" % relpath(self.filename, os.curdir)) ensureParentDir(self.filename) - with open(self.filename, 'w') as file: - file.write(buf) + ff = open(self.filename, 'w') + ff.write(buf) + ff.close() def __enter__(self): return self @@ -203,8 +202,12 @@ class ConfigEnvironment(object): pp.context.update(DEPTH = self.get_depth(path)) pp.do_filter('attemptSubstitution') pp.setMarker(None) - with FileAvoidWrite(path) as pp.out: + pp.out = FileAvoidWrite(path) + pp.out.__enter__() + try: pp.do_include(input) + finally: + pp.out.__exit__(0, 0, 0) def create_config_header(self, path): '''Creates the given config header. A config header is generated by @@ -216,7 +219,8 @@ class ConfigEnvironment(object): "#undef UNKNOWN_NAME" is turned into "/* #undef UNKNOWN_NAME */" Whitespaces are preserved. ''' - with open(self.get_input(path), 'rU') as input: + input = open(self.get_input(path), 'rU') + if 1: ensureParentDir(path) output = FileAvoidWrite(path) r = re.compile('^\s*#\s*(?P<cmd>[a-z]+)(?:\s+(?P<name>\S+)(?:\s+(?P<value>\S+))?)?', re.U) @@ -237,6 +241,7 @@ class ConfigEnvironment(object): output.write(l) output.close() + input.close() def config_status(topobjdir = '.', topsrcdir = '.', defines = [], non_global_defines = [], substs = [], diff -up mozilla-esr17/build/virtualenv/populate_virtualenv.py.python mozilla-esr17/build/virtualenv/populate_virtualenv.py --- mozilla-esr17/build/virtualenv/populate_virtualenv.py.python 2013-06-18 20:47:01.000000000 +0200 +++ mozilla-esr17/build/virtualenv/populate_virtualenv.py 2013-06-19 23:09:22.000000000 +0200 @@ -5,7 +5,6 @@ # This file contains code for populating the virtualenv environment for # Mozilla's build system. It is typically called as part of configure. -from __future__ import with_statement import os.path import subprocess import sys @@ -43,8 +42,9 @@ def populate_virtualenv(top_source_direc if package[0].endswith('.pth'): assert len(package) == 2 - with open(os.path.join(distutils.sysconfig.get_python_lib(), package[0]), 'a') as f: - f.write("%s\n" % os.path.join(top_source_directory, package[1])) + f = open(os.path.join(distutils.sysconfig.get_python_lib(), package[0]), 'a') + f.write("%s\n" % os.path.join(top_source_directory, package[1])) + f.close() def call_setup(directory, arguments): """Calls setup.py in a directory.""" diff -up mozilla-esr17/config/expandlibs_exec.py.python mozilla-esr17/config/expandlibs_exec.py --- mozilla-esr17/config/expandlibs_exec.py.python 2013-06-18 20:47:01.000000000 +0200 +++ mozilla-esr17/config/expandlibs_exec.py 2013-06-19 23:09:22.000000000 +0200 @@ -20,13 +20,11 @@ With the --symbol-order argument, follow relevant linker options to change the order in which the linker puts the symbols appear in the resulting binary. Only works for ELF targets. ''' -from __future__ import with_statement import sys import os from expandlibs import ExpandArgs, relativize, isObject, ensureParentDir, ExpandLibsDeps import expandlibs_config as conf from optparse import OptionParser -import subprocess import tempfile import shutil import subprocess @@ -73,7 +71,11 @@ class ExpandArgsMore(ExpandArgs): elif os.path.exists(arg) and len(ar_extract): tmp = tempfile.mkdtemp(dir=os.curdir) self.tmp.append(tmp) - subprocess.call(ar_extract + [os.path.abspath(arg)], cwd=tmp) + tmp_arg = ar_extract + [os.path.abspath(arg)] + oldir = os.getcwd() + os.chdir(tmp) + os.system(' '.join(tmp_arg)) + os.chdir(oldir) objs = [] for root, dirs, files in os.walk(tmp): objs += [relativize(os.path.join(root, f)) for f in files if isObject(f)] @@ -165,8 +167,8 @@ class ExpandArgsMore(ExpandArgs): def orderSymbols(self, order): '''Given a file containing a list of symbols, adds the appropriate argument to make the linker put the symbols in that order.''' - with open(order) as file: - sections = self._getOrderedSections([l.strip() for l in file.readlines() if l.strip()]) + ff = open(order) + sections = self._getOrderedSections([l.strip() for l in ff.readlines() if l.strip()]) split_sections = {} linked_sections = [s[0] for s in SECTION_INSERT_BEFORE] for s in sections: @@ -293,29 +295,38 @@ def main(): deps.pop(0) # Remove command deps.pop(0) - with ExpandArgsMore(args) as args: + args2 = ExpandArgsMore(args) + args2.__enter__() + try: if options.extract: - args.extract() + args2.extract() if options.symbol_order: - args.orderSymbols(options.symbol_order) + args2.orderSymbols(options.symbol_order) if options.uselist: - args.makelist() + args2.makelist() if options.verbose: - print >>sys.stderr, "Executing: " + " ".join(args) - for tmp in [f for f in args.tmp if os.path.isfile(f)]: + print >>sys.stderr, "Executing: " + " ".join(args2) + for tmp in [f for f in args2.tmp if os.path.isfile(f)]: print >>sys.stderr, tmp + ":" - with open(tmp) as file: - print >>sys.stderr, "".join([" " + l for l in file.readlines()]) + ff = open(tmp) + ff.__enter__() + try: + print >>sys.stderr, "".join([" " + l for l in ff.readlines()]) + finally: + ff.__exit__(0, 0, 0) sys.stderr.flush() - ret = subprocess.call(args) + ret = subprocess.call(args2) if ret: exit(ret) + finally: + args2.__exit__(0, 0, 0) if not options.depend: return ensureParentDir(options.depend) - with open(options.depend, 'w') as depfile: - depfile.write("%s : %s\n" % (options.target, ' '.join(dep for dep in deps if os.path.isfile(dep) and dep != options.target))) + depfile = open(options.depend, 'w') + depfile.write("%s : %s\n" % (options.target, ' '.join(dep for dep in deps if os.path.isfile(dep) and dep != options.target))) + depfile.close() if __name__ == '__main__': diff -up mozilla-esr17/config/expandlibs_gen.py.python mozilla-esr17/config/expandlibs_gen.py --- mozilla-esr17/config/expandlibs_gen.py.python 2013-06-18 20:47:01.000000000 +0200 +++ mozilla-esr17/config/expandlibs_gen.py 2013-06-19 23:09:22.000000000 +0200 @@ -5,7 +5,6 @@ '''Given a list of object files and library names, prints a library descriptor to standard output''' -from __future__ import with_statement import sys import os import expandlibs_config as conf @@ -39,9 +38,11 @@ if __name__ == '__main__': raise Exception("Missing option: -o") ensureParentDir(options.output) - with open(options.output, 'w') as outfile: - print >>outfile, generate(args) + outfile = open(options.output, 'w') + print >>outfile, generate(args) + outfile.close() if options.depend: ensureParentDir(options.depend) - with open(options.depend, 'w') as depfile: - depfile.write("%s : %s\n" % (options.output, ' '.join(ExpandLibsDeps(args)))) + depfile = open(options.depend, 'w') + depfile.write("%s : %s\n" % (options.output, ' '.join(ExpandLibsDeps(args)))) + depfile.close() diff -up mozilla-esr17/config/expandlibs.py.python mozilla-esr17/config/expandlibs.py --- mozilla-esr17/config/expandlibs.py.python 2013-06-18 20:47:01.000000000 +0200 +++ mozilla-esr17/config/expandlibs.py 2013-06-19 23:09:22.000000000 +0200 @@ -26,7 +26,6 @@ ${LIB_PREFIX}${ROOT}.${LIB_SUFFIX} follo descriptor contains. And for each of these LIBS, also apply the same rules. ''' -from __future__ import with_statement import sys, os, errno import expandlibs_config as conf @@ -75,15 +74,15 @@ class LibDescriptor(dict): '''Creates an instance of a lib descriptor, initialized with contents from a list of strings when given. This is intended for use with file.readlines()''' - if isinstance(content, list) and all([isinstance(item, str) for item in content]): - pass - elif content is not None: - raise TypeError("LibDescriptor() arg 1 must be None or a list of strings") super(LibDescriptor, self).__init__() for key in self.KEYS: self[key] = [] - if not content: + if content == None: return + if isinstance(content, list): + for item in content: + if not isinstance(item, str): + raise TypeError("LibDescriptor() arg 1 must be None or a list of strings") for key, value in [(s.strip() for s in item.split('=', 2)) for item in content if item.find('=') >= 0]: if key in self.KEYS: self[key] = value.split() @@ -118,8 +117,9 @@ class ExpandArgs(list): def _expand_desc(self, arg): '''Internal function taking care of lib descriptor expansion only''' if os.path.exists(arg + conf.LIBS_DESC_SUFFIX): - with open(arg + conf.LIBS_DESC_SUFFIX, 'r') as f: - desc = LibDescriptor(f.readlines()) + f = open(arg + conf.LIBS_DESC_SUFFIX, 'r') + desc = LibDescriptor(f.readlines()) + f.close() objs = [relativize(o) for o in desc['OBJS']] for lib in desc['LIBS']: objs += self._expand(lib) diff -up mozilla-esr17/config/optimizejars.py.python mozilla-esr17/config/optimizejars.py --- mozilla-esr17/config/optimizejars.py.python 2013-06-18 20:47:01.000000000 +0200 +++ mozilla-esr17/config/optimizejars.py 2013-06-19 23:09:22.000000000 +0200 @@ -287,14 +287,17 @@ def optimizejar(jar, outjar, inlog = Non outfd.write(dirend_data) print "Stripped %d bytes" % total_stripped - print "%s %d/%d in %s" % (("Ordered" if inlog is not None else "Deoptimized"), + tmp_str = "Ordered" + if inlog is None: + tmp_str = "Deoptimized" + print "%s %d/%d in %s" % (tmp_str, reordered_count, len(central_directory), outjar) outfd.close() return outlog if len(sys.argv) != 5: print "Usage: --optimize|--deoptimize %s JAR_LOG_DIR IN_JAR_DIR OUT_JAR_DIR" % sys.argv[0] - exit(1) + sys.exit(1) jar_regex = re.compile("\\.jar?$") diff -up mozilla-esr17/configure.python mozilla-esr17/configure --- mozilla-esr17/configure.python 2013-06-18 20:48:48.000000000 +0200 +++ mozilla-esr17/configure 2013-06-19 23:09:23.000000000 +0200 @@ -1176,7 +1176,7 @@ NSS_VERSION=3 GLIB_VERSION=1.2.0 PERL_VERSION=5.006 -PYTHON_VERSION=2.5 +PYTHON_VERSION=2.4 CAIRO_VERSION=1.10 PANGO_VERSION=1.14.0 GTK2_VERSION=2.10.0 diff -up mozilla-esr17/config/writemozinfo.py.python mozilla-esr17/config/writemozinfo.py --- mozilla-esr17/config/writemozinfo.py.python 2013-06-18 20:47:01.000000000 +0200 +++ mozilla-esr17/config/writemozinfo.py 2013-06-19 23:09:23.000000000 +0200 @@ -9,7 +9,6 @@ # configuration, such as the target OS and CPU. # # The output file is intended to be used as input to the mozinfo package. -from __future__ import with_statement import os, re, sys def build_dict(env=os.environ): @@ -102,8 +101,12 @@ def write_json(file, env=os.environ): """ s = jsonify(build_dict(env)) if isinstance(file, basestring): - with open(file, "w") as f: + f = open(file, "w") + f.__enter__() + try: f.write(s) + finally: + f.__exit__() else: file.write(s) diff -up mozilla-esr17/dom/bindings/Codegen.py.python mozilla-esr17/dom/bindings/Codegen.py --- mozilla-esr17/dom/bindings/Codegen.py.python 2013-06-18 20:47:06.000000000 +0200 +++ mozilla-esr17/dom/bindings/Codegen.py 2013-06-19 23:09:23.000000000 +0200 @@ -45,7 +45,7 @@ def toStringBool(arg): def toBindingNamespace(arg): return re.sub("((_workers)?$)", "Binding\\1", arg); -class CGThing(): +class CGThing: """ Abstract base class for things that spit out code. """ @@ -78,8 +78,9 @@ class CGNativePropertyHooks(CGThing): else: enumerateOwnProperties = resolveOwnProperty = "NULL" parent = self.descriptor.interface.parent - parentHooks = ("&" + toBindingNamespace(parent.identifier.name) + "::NativeHooks" - if parent else 'NULL') + parentHooks = ('NULL') + if parent: + parentHooks = ("&" + toBindingNamespace(parent.identifier.name) + "::NativeHooks") return """ const NativePropertyHooks NativeHooks = { %s, ResolveProperty, %s, EnumerateProperties, %s }; """ % (resolveOwnProperty, enumerateOwnProperties, parentHooks) @@ -92,7 +93,9 @@ def DOMClass(descriptor): # padding. protoList.extend(['prototypes::id::_ID_Count'] * (descriptor.config.maxProtoChainLength - len(protoList))) prototypeChainString = ', '.join(protoList) - nativeHooks = "NULL" if descriptor.workers else "&NativeHooks" + nativeHooks = "&NativeHooks" + if descriptor.workers: + nativeHooks = "NULL" return """{ { %s }, %s, %s @@ -109,7 +112,12 @@ class CGDOMJSClass(CGThing): def declare(self): return "extern DOMJSClass Class;\n" def define(self): - traceHook = TRACE_HOOK_NAME if self.descriptor.customTrace else 'NULL' + traceHook = 'NULL' + if self.descriptor.customTrace: + traceHook = TRACE_HOOK_NAME + property_hook_name = 'JS_PropertyStub' + if self.descriptor.concrete and not self.descriptor.workers and self.descriptor.wrapperCache: + property_hook_name = ADDPROPERTY_HOOK_NAME return """ DOMJSClass Class = { { "%s", @@ -133,7 +141,7 @@ DOMJSClass Class = { -1 }; """ % (self.descriptor.interface.identifier.name, - ADDPROPERTY_HOOK_NAME if self.descriptor.concrete and not self.descriptor.workers and self.descriptor.wrapperCache else 'JS_PropertyStub', + property_hook_name, FINALIZE_HOOK_NAME, traceHook, CGIndenter(CGGeneric(DOMClass(self.descriptor))).define()) @@ -175,7 +183,9 @@ class CGInterfaceObjectJSClass(CGThing): def define(self): if not self.descriptor.hasInstanceInterface: return "" - ctorname = "NULL" if not self.descriptor.interface.ctor() else CONSTRUCT_HOOK_NAME + ctorname = CONSTRUCT_HOOK_NAME + if not self.descriptor.interface.ctor(): + ctorname = "NULL" hasinstance = HASINSTANCE_HOOK_NAME return """ static JSClass InterfaceObjectClass = { @@ -509,7 +519,7 @@ def UnionConversions(descriptors): return CGWrapper(CGList(SortedDictValues(unionConversions), "\n"), post="\n\n") -class Argument(): +class Argument: """ A class for outputting the type and name of an argument """ @@ -570,7 +580,9 @@ class CGAbstractMethod(CGThing): if self.static: decorators.append('static') decorators.append(self.returnType) - maybeNewline = " " if self.inline else "\n" + maybeNewline = "\n" + if self.inline: + maybeNewline = " " return ' '.join(decorators) + maybeNewline def declare(self): if self.inline: @@ -579,7 +591,10 @@ class CGAbstractMethod(CGThing): def _define(self): return self.definition_prologue() + "\n" + self.definition_body() + self.definition_epilogue() def define(self): - return "" if self.inline else self._define() + ret_PYTHON24 = self._define() + if self.inline: + ret_PYTHON24 = "" + return ret_PYTHON24 def definition_prologue(self): return "%s%s%s(%s)\n{" % (self._template(), self._decorators(), self.name, self._argstring()) @@ -644,7 +659,9 @@ def finalizeHook(descriptor, hookName, c return """if (self) { self->%s(%s); }""" % (hookName, context) - clearWrapper = "ClearWrapper(self, self);\n" if descriptor.wrapperCache else "" + clearWrapper = "" + if descriptor.wrapperCache: + clearWrapper = "ClearWrapper(self, self);\n" if descriptor.workers: release = "self->Release();" else: @@ -942,7 +959,12 @@ class MethodDefiner(PropertyDefiner): for m in methods if not isChromeOnly(m)] # FIXME Check for an existing iterator on the interface first. - if any(m.isGetter() and m.isIndexed() for m in methods): + method_indexed = False + for m in methods: + if m.isGetter() and m.isIndexed(): + method_indexed = True + break + if method_indexed: self.regular.append({"name": 'iterator', "methodInfo": False, "nativeName": "JS_ArrayIterator", @@ -997,10 +1019,19 @@ class MethodDefiner(PropertyDefiner): class AttrDefiner(PropertyDefiner): def __init__(self, descriptor, name): PropertyDefiner.__init__(self, descriptor, name) - self.name = name - attributes = [m for m in descriptor.interface.members if m.isAttr()] - self.chrome = [m for m in attributes if isChromeOnly(m)] - self.regular = [m for m in attributes if not isChromeOnly(m)] + self.name = name + attributes = [] + for m in descriptor.interface.members: + if m.isAttr(): + attributes.append(m) + self.chrome = [] + for m in attributes: + if isChromeOnly(m): + self.chrome.append(m) + self.regular = [] + for m in attributes: + if not isChromeOnly(m): + self.regular.append(m) def generateArray(self, array, name, doIdArrays): if len(array) == 0: @@ -1036,11 +1067,20 @@ class ConstDefiner(PropertyDefiner): """ def __init__(self, descriptor, name): PropertyDefiner.__init__(self, descriptor, name) - self.name = name - constants = [m for m in descriptor.interface.members if m.isConst()] - self.chrome = [m for m in constants if isChromeOnly(m)] - self.regular = [m for m in constants if not isChromeOnly(m)] - + self.name = name + constants = [] + for m in descriptor.interface.members: + if m.isConst(): + constants.append(m) + self.chrome = [] + for m in constants: + if isChromeOnly(m): + self.chrome.append(m) + self.regular = [] + for m in constants: + if not isChromeOnly(m): + self.regular.append(m) + def generateArray(self, array, name, doIdArrays): if len(array) == 0: return "" @@ -1056,7 +1096,7 @@ class ConstDefiner(PropertyDefiner): 'ConstantSpec', PropertyDefiner.getControllingPref, specData, doIdArrays) -class PropertyArrays(): +class PropertyArrays: def __init__(self, descriptor): self.staticMethods = MethodDefiner(descriptor, "StaticMethods", True) self.methods = MethodDefiner(descriptor, "Methods", False) @@ -1072,9 +1112,19 @@ class PropertyArrays(): return [ "methods", "attrs", "consts" ] def hasChromeOnly(self): - return any(getattr(self, a).hasChromeOnly() for a in self.arrayNames()) + any_chrome_only = False + for a in self.arrayNames(): + if getattr(self, a).hasChromeOnly(): + any_chrome_only = True + break + return any_chrome_only def hasNonChromeOnly(self): - return any(getattr(self, a).hasNonChromeOnly() for a in self.arrayNames()) + any_non_chrome_only = False + for a in self.arrayNames(): + if getattr(self, a).hasNonChromeOnly(): + any_non_chrome_only = True + break + return any_non_chrome_only def __str__(self): define = "" for array in self.arrayNames(): @@ -1085,7 +1135,10 @@ class CGNativeProperties(CGList): def __init__(self, descriptor, properties): def generateNativeProperties(name, chrome): def check(p): - return p.hasChromeOnly() if chrome else p.hasNonChromeOnly() + if chrome: + return p.hasChromeOnly() + else: + return p.hasNonChromeOnly() nativeProps = [] for array in properties.arrayNames(): @@ -1223,20 +1276,36 @@ class CGCreateInterfaceObjectsMethod(CGA chromeProperties = accessCheck + " ? &sChromeOnlyNativeProperties : nullptr" else: chromeProperties = "nullptr" + + need_proto = "NULL" + if needInterfacePrototypeObject: + need_proto = "&PrototypeClass" + + need_interface_class = "NULL" + if needInterfaceObjectClass: + need_interface_class = "&InterfaceObjectClass" + + construct_hook_str = "NULL" + if needConstructor: + construct_hook_str = constructHook + + need_interface_obj = "NULL" + if needInterfaceObject: + need_interface_obj = '"' + self.descriptor.interface.identifier.name + '"' call = """return dom::CreateInterfaceObjects(aCx, aGlobal, aReceiver, parentProto, %s, %s, %s, %d, %s, %s, %s, %s);""" % ( - "&PrototypeClass" if needInterfacePrototypeObject else "NULL", - "&InterfaceObjectClass" if needInterfaceObjectClass else "NULL", - constructHook if needConstructor else "NULL", + need_proto, + need_interface_class, + construct_hook_str, constructArgs, domClass, properties, chromeProperties, - '"' + self.descriptor.interface.identifier.name + '"' if needInterfaceObject else "NULL") + need_interface_obj) functionBody = CGList( [CGGeneric(getParentProto), initIds, prefCache, CGGeneric(call)], "\n\n") @@ -1485,7 +1554,7 @@ numericTags = [ IDLType.Tags.float, IDLType.Tags.double ] -class CastableObjectUnwrapper(): +class CastableObjectUnwrapper: """ A class for unwrapping an object named by the "source" argument based on the passed-in descriptor and storing it in a variable @@ -1894,8 +1963,8 @@ for (uint32_t i = 0; i < length; ++i) { templateBody = CGList([interfaceObject, templateBody], "\n") else: templateBody = CGList([templateBody, object], "\n") - - if any([arrayObject, dateObject, nonPlatformObject, object]): + + if arrayObject or dateObject or nonPlatformObject or object: templateBody.prepend(CGGeneric("JSObject& argObj = ${val}.toObject();")) templateBody = CGWrapper(CGIndenter(templateBody), pre="if (${val}.isObject()) {\n", @@ -1905,7 +1974,11 @@ for (uint32_t i = 0; i < length; ++i) { otherMemberTypes = filter(lambda t: t.isString() or t.isEnum(), memberTypes) - otherMemberTypes.extend(t for t in memberTypes if t.isPrimitive()) + otherMemberTypes_extend_PYTHON24 = [] + for t in memberTypes: + if t.isPrimitive(): + otherMemberTypes_extend_PYTHON24.append(t) + otherMemberTypes.extend(otherMemberTypes_extend_PYTHON24) if len(otherMemberTypes) > 0: assert len(otherMemberTypes) == 1 memberType = otherMemberTypes[0] @@ -2470,7 +2543,10 @@ def convertConstIDLValueToJSVal(value): if tag in [IDLType.Tags.int64, IDLType.Tags.uint64]: return "DOUBLE_TO_JSVAL(%s)" % (value.value) if tag == IDLType.Tags.bool: - return "JSVAL_TRUE" if value.value else "JSVAL_FALSE" + ret_PYTHON24 = "JSVAL_FALSE" + if value.value: + ret_PYTHON24 = "JSVAL_TRUE" + return ret_PYTHON24 if tag in [IDLType.Tags.float, IDLType.Tags.double]: return "DOUBLE_TO_JSVAL(%s)" % (value.value) raise TypeError("Const value of unhandled type: " + value.type) @@ -2781,10 +2857,16 @@ def infallibleForAttr(attr, descriptorPr memberIsCreator(attr))[1] def typeNeedsCx(type): + type_need_cx = False + if type is not None and type.isUnion(): + for t in type.unroll().flatMemberTypes: + if typeNeedsCx(t): + type_need_cx = True + break + return (type is not None and (type.isCallback() or type.isAny() or type.isObject() or - (type.isUnion() and - any(typeNeedsCx(t) for t in type.unroll().flatMemberTypes)))) + (type_need_cx))) # Returns a tuple consisting of a CGThing containing the type of the return # value, or None if there is no need for a return value, and a boolean signaling @@ -2872,8 +2954,13 @@ class CGCallGenerator(CGThing): if isFallible: args.append(CGGeneric("rv")) + some_type_needs_cx = False + for (a, _) in arguments: + if typeNeedsCx(a.type): + some_type_needs_cx = True + break needsCx = (typeNeedsCx(returnType) or - any(typeNeedsCx(a.type) for (a, _) in arguments) or + some_type_needs_cx or 'implicitJSContext' in extendedAttributes) if not "cx" in argsPre and needsCx: @@ -2957,15 +3044,21 @@ class CGPerSignatureCall(CGThing): invalidEnumValueFatal=not setter) for i in range(argConversionStartsAt, self.argCount)]) + get_err_reports = None + if self.isFallible(): + get_err_reports = self.getErrorReport() cgThings.append(CGCallGenerator( - self.getErrorReport() if self.isFallible() else None, + get_err_reports, self.getArguments(), self.argsPre, returnType, self.extendedAttributes, descriptor, nativeMethodName, static)) self.cgRoot = CGList(cgThings, "\n") def getArgv(self): - return "argv" if self.argCount > 0 else "" + ret_PYTHON24 = "" + if self.argCount > 0: + ret_PYTHON24 = "argv" + return ret_PYTHON24 def getArgvDecl(self): return "\nJS::Value* argv = JS_ARGV(cx, vp);\n" def getArgc(self): @@ -3293,7 +3386,7 @@ class CGGetterCall(CGPerSignatureCall): nativeMethodName, False, descriptor, attr, getter=True) -class FakeArgument(): +class FakeArgument: """ A class that quacks like an IDLArgument. This is used to make setters look like method calls or for special operations. @@ -3325,7 +3418,7 @@ class CGSetterCall(CGPerSignatureCall): # We just get our stuff from our last arg no matter what return "" -class FakeCastableDescriptor(): +class FakeCastableDescriptor: def __init__(self, descriptor): self.castable = True self.workers = descriptor.workers @@ -3501,7 +3594,9 @@ class CGMemberJITInfo(CGThing): def defineJitInfo(self, infoName, opName, infallible): protoID = "prototypes::id::%s" % self.descriptor.interface.identifier.name depth = "PrototypeTraits<%s>::Depth" % protoID - failstr = "true" if infallible else "false" + failstr = "false" + if infallible: + failstr = "true" return ("\n" "const JSJitInfo %s = {\n" " %s,\n" @@ -3713,12 +3808,15 @@ return true;""" post="\n" "}") + holder_PYTHON24 = None + if holderType: + holder_PYTHON24 = holderType.define() return { "name": name, "structType": structType, "externalType": externalType, "setter": CGIndenter(setter).define(), - "holderType": holderType.define() if holderType else None + "holderType": holder_PYTHON24 } def mapTemplate(template, templateVarArray): @@ -3931,22 +4029,29 @@ class ClassMethod(ClassItem): return self.body def declare(self, cgClass): - templateClause = 'template <%s>\n' % ', '.join(self.templateArgs) \ - if self.bodyInHeader and self.templateArgs else '' - args = ', '.join([str(a) for a in self.args]) + + templateClause = "" + if self.bodyInHeader and self.templateArgs: + templateClause = 'template <%s>\n' % ', '.join(self.templateArgs) + args_to_add = [] + for a in self.args: + args_to_add.append(str(a)) + args = ', '.join(args_to_add) if self.bodyInHeader: body = CGIndenter(CGGeneric(self.getBody())).define() body = '\n{\n' + body + '\n}' else: body = ';' - + is_const = '' + if self.const: + is_const = ' const' return string.Template("""${templateClause}${decorators}${returnType} ${name}(${args})${const}${body} """).substitute({ 'templateClause': templateClause, 'decorators': self.getDecorators(True), 'returnType': self.returnType, 'name': self.name, - 'const': ' const' if self.const else '', + 'const': is_const, 'args': args, 'body': body }) @@ -3970,6 +4075,9 @@ ${name}(${args})${const}${body} body = CGIndenter(CGGeneric(self.getBody())).define() + is_const = '' + if self.const: + is_const = ' const' return string.Template("""${templateClause}${decorators}${returnType} ${className}::${name}(${args})${const} { @@ -3981,7 +4089,7 @@ ${body} 'className': cgClass.getNameString(), 'name': self.name, 'args': args, - 'const': ' const' if self.const else '', + 'const': is_const, 'body': body }) class ClassConstructor(ClassItem): @@ -4083,7 +4191,10 @@ class ClassMember(ClassItem): ClassItem.__init__(self, name, visibility) def declare(self, cgClass): - return '%s%s %s;\n' % ('static ' if self.static else '', self.type, + is_static = '' + if self.static: + is_static = 'static ' + return '%s%s %s;\n' % (is_static, self.type, self.name) def define(self, cgClass): @@ -4122,7 +4233,10 @@ class ClassEnum(ClassItem): else: entry = '%s = %s' % (self.entries[i], self.values[i]) entries.append(entry) - name = '' if not self.name else ' ' + self.name + name = ' ' + self.name + if not self.name: + name = '' + return 'enum%s\n{\n %s\n};\n' % (name, ',\n '.join(entries)) def define(self, cgClass): @@ -4145,7 +4259,10 @@ class CGClass(CGThing): self.templateSpecialization = templateSpecialization self.isStruct = isStruct self.indent = indent - self.defaultVisibility ='public' if isStruct else 'private' + self.defaultVisibility = 'private' + if isStruct: + self.defaultVisibility = 'public' + def getNameString(self): className = self.name @@ -4163,7 +4280,9 @@ class CGClass(CGThing): result = result + self.indent + 'template <%s>\n' \ % ','.join([str(a) for a in templateArgs]) - type = 'struct' if self.isStruct else 'class' + type = 'class' + if self.isStruct: + type = 'struct' if self.templateSpecialization: specialization = \ @@ -4357,7 +4476,10 @@ class CGClassForwardDeclare(CGThing): self.name = name self.isStruct = isStruct def declare(self): - type = 'struct' if self.isStruct else 'class' + type = 'class' + if self.isStruct: + type = 'struct' + return '%s %s;\n' % (type, self.name) def define(self): # Header only @@ -5046,8 +5168,13 @@ class CGDictionary(CGThing): def __init__(self, dictionary, descriptorProvider): self.dictionary = dictionary; self.workers = descriptorProvider.workers - if all(CGDictionary(d, descriptorProvider).generatable for - d in CGDictionary.getDictionaryDependencies(dictionary)): + is_generatable = True + for d in CGDictionary.getDictionaryDependencies(dictionary): + if not CGDictionary(d, descriptorProvider).generatable: + is_generatable = False + break + + if is_generatable: self.generatable = True else: self.generatable = False @@ -5165,7 +5292,9 @@ class CGDictionary(CGThing): @staticmethod def makeDictionaryName(dictionary, workers): - suffix = "Workers" if workers else "" + suffix = "" + if workers: + suffix = "Workers" return dictionary.identifier.name + suffix def makeClassName(self, dictionary): @@ -5433,7 +5562,7 @@ class CGBindingRoot(CGThing): return stripTrailingWhitespace(self.root.define()) -class GlobalGenRoots(): +class GlobalGenRoots: """ Roots for global codegen. diff -up mozilla-esr17/dom/bindings/Configuration.py.python mozilla-esr17/dom/bindings/Configuration.py --- mozilla-esr17/dom/bindings/Configuration.py.python 2013-06-18 20:47:06.000000000 +0200 +++ mozilla-esr17/dom/bindings/Configuration.py 2013-06-19 23:09:23.000000000 +0200 @@ -219,7 +219,10 @@ class Descriptor(DescriptorProvider): self.interface.identifier.name) def make_name(name): - return name + "_workers" if self.workers else name + ret = name + if self.workers: + ret = name + "_workers" + return ret self.name = make_name(interface.identifier.name) # self.extendedAttributes is a dict of dicts, keyed on @@ -292,11 +295,15 @@ class Descriptor(DescriptorProvider): assert member.isAttr() assert bool(getter) != bool(setter) - key = 'getterOnly' if getter else 'setterOnly' + key = 'setterOnly' + if getter: + key = 'getterOnly' attrs = self.extendedAttributes['all'].get(name, []) + self.extendedAttributes[key].get(name, []) infallible = member.getExtendedAttribute("Infallible") if infallible is None: - infallibleAttr = "GetterInfallible" if getter else "SetterInfallible" + infallibleAttr = "SetterInfallible" + if getter: + infallibleAttr = "GetterInfallible" infallible = member.getExtendedAttribute(infallibleAttr) ensureValidInfallibleExtendedAttribute(infallible) diff -up mozilla-esr17/dom/bindings/parser/WebIDL.py.python mozilla-esr17/dom/bindings/parser/WebIDL.py --- mozilla-esr17/dom/bindings/parser/WebIDL.py.python 2013-06-18 20:47:06.000000000 +0200 +++ mozilla-esr17/dom/bindings/parser/WebIDL.py 2013-06-19 23:09:23.000000000 +0200 @@ -59,9 +59,13 @@ class WebIDLError(Exception): self.warning = warning def __str__(self): + add_comma = "" + if len(self.locations) != 0: + add_comma = ", " + len(self.locations) return "%s: %s%s%s" % (self.warning and 'warning' or 'error', self.message, - ", " if len(self.locations) != 0 else "", + add_comma, "\n".join(self.locations)) class Location(object): @@ -70,7 +74,9 @@ class Location(object): self._lineno = lineno self._lexpos = lexpos self._lexdata = lexer.lexdata - self._file = filename if filename else "<unknown>" + self._file = "<unknown>" + if filename: + self._file = filename def __eq__(self, other): return self._lexpos == other._lexpos and \ @@ -467,7 +473,8 @@ class IDLInterface(IDLObjectWithScope): IDLScope.resolveIdentifierConflict(self, identifier, originalObject, newObject) assert False # Not reached - + print self.members + print iter(self.members) retval = originalObject.addOverload(newObject) # Might be a ctor, which isn't in self.members if newObject in self.members: @@ -481,7 +488,10 @@ class IDLInterface(IDLObjectWithScope): self._finished = True assert not self.parent or isinstance(self.parent, IDLIdentifierPlaceholder) - parent = self.parent.finish(scope) if self.parent else None + + parent = None + if self.parent: + parent = self.parent.finish(scope) if parent and isinstance(parent, IDLExternalInterface): raise WebIDLError("%s inherits from %s which does not have " "a definition" % @@ -492,7 +502,7 @@ class IDLInterface(IDLObjectWithScope): self.parent = parent - assert iter(self.members) + #assert iter(self.members) if self.parent: self.parent.finish(scope) @@ -637,7 +647,12 @@ class IDLInterface(IDLObjectWithScope): return depth def hasConstants(self): - return any(m.isConst() for m in self.members) + any_const_member = False + for m in self.members: + if m.isConst(): + any_const_member = True + break + return any_const_member def hasInterfaceObject(self): if self.isCallback(): @@ -667,8 +682,9 @@ class IDLInterface(IDLObjectWithScope): if not self.hasInterfaceObject(): raise WebIDLError("Constructor and NoInterfaceObject are incompatible", [self.location]) - - args = attrlist[0] if len(attrlist) else [] + args = [] + if len(attrlist): + args = attrlist[0] retType = IDLWrapperType(self.location, self) @@ -681,7 +697,9 @@ class IDLInterface(IDLObjectWithScope): method.addExtendedAttributes(["Creator"]) method.resolve(self) - self._extendedAttrDict[identifier] = attrlist if len(attrlist) else True + self._extendedAttrDict[identifier] = True + if len(attrlist): + self._extendedAttrDict[identifier] = attrlist def addImplementedInterface(self, implementedInterface): assert(isinstance(implementedInterface, IDLInterface)) @@ -1860,7 +1878,9 @@ class IDLInterfaceMember(IDLObjectWithId attrlist = list(attr) identifier = attrlist.pop(0) self.handleExtendedAttribute(identifier, attrlist) - self._extendedAttrDict[identifier] = attrlist if len(attrlist) else True + self._extendedAttrDict[identifier] = True + if len(attrlist): + self._extendedAttrDict[identifier] = attrlist def handleExtendedAttribute(self, name, list): pass @@ -2660,7 +2680,9 @@ class Parser(Tokenizer): """ InterfaceMembers : ExtendedAttributeList InterfaceMember InterfaceMembers """ - p[0] = [p[2]] if p[2] else [] + p[0] = [] + if p[2]: + p[0] = [p[2]] assert not p[1] or p[2] p[2].addExtendedAttributes(p[1]) @@ -2915,17 +2937,31 @@ class Parser(Tokenizer): raise WebIDLError("Duplicate qualifiers are not allowed", [self.getLocation(p, 1)]) - static = True if IDLMethod.Special.Static in p[1] else False + static = False + if IDLMethod.Special.Static in p[1]: + static = True # If static is there that's all that's allowed. This is disallowed # by the parser, so we can assert here. assert not static or len(qualifiers) == 1 - getter = True if IDLMethod.Special.Getter in p[1] else False - setter = True if IDLMethod.Special.Setter in p[1] else False - creator = True if IDLMethod.Special.Creator in p[1] else False - deleter = True if IDLMethod.Special.Deleter in p[1] else False - legacycaller = True if IDLMethod.Special.LegacyCaller in p[1] else False - stringifier = True if IDLMethod.Special.Stringifier in p[1] else False + getter = False + if IDLMethod.Special.Getter in p[1]: + getter = True + setter = False + if IDLMethod.Special.Setter in p[1]: + setter = True + creator = False + if IDLMethod.Special.Creator in p[1]: + creator = True + deleter = False + if IDLMethod.Special.Deleter in p[1]: + deleter = True + legacycaller = False + if IDLMethod.Special.LegacyCaller in p[1]: + legacycaller = True + stringifier = False + if IDLMethod.Special.Stringifier in p[1]: + stringifier = True if getter or deleter: if setter or creator: @@ -2939,9 +2975,12 @@ class Parser(Tokenizer): specialType = IDLMethod.NamedOrIndexed.Neither if getter or deleter: + getter_deleter = "deleter" + if getter: + getter_deleter = "getter" if len(arguments) != 1: raise WebIDLError("%s has wrong number of arguments" % - ("getter" if getter else "deleter"), + (getter_deleter), [self.getLocation(p, 2)]) argType = arguments[0].type if argType == BuiltinTypes[IDLBuiltinType.Types.domstring]: @@ -2950,21 +2989,27 @@ class Parser(Tokenizer): specialType = IDLMethod.NamedOrIndexed.Indexed else: raise WebIDLError("%s has wrong argument type (must be DOMString or UnsignedLong)" % - ("getter" if getter else "deleter"), + (getter_deleter), [arguments[0].location]) if arguments[0].optional or arguments[0].variadic: + optional_variadic = "variadic" + if arguments[0].optional: + optional_variadic = "optional" raise WebIDLError("%s cannot have %s argument" % - ("getter" if getter else "deleter", - "optional" if arguments[0].optional else "variadic"), + (getter_deleter, + optional_variadic), [arguments[0].location]) if getter: if returnType.isVoid(): raise WebIDLError("getter cannot have void return type", [self.getLocation(p, 2)]) if setter or creator: + setter_creator = "creator" + if setter: + setter_creator = "setter" if len(arguments) != 2: raise WebIDLError("%s has wrong number of arguments" % - ("setter" if setter else "creator"), + (setter_creator), [self.getLocation(p, 2)]) argType = arguments[0].type if argType == BuiltinTypes[IDLBuiltinType.Types.domstring]: @@ -2973,17 +3018,23 @@ class Parser(Tokenizer): specialType = IDLMethod.NamedOrIndexed.Indexed else: raise WebIDLError("%s has wrong argument type (must be DOMString or UnsignedLong)" % - ("setter" if setter else "creator"), + (setter_creator), [arguments[0].location]) if arguments[0].optional or arguments[0].variadic: + optional_variadic = "variadic" + if arguments[0].optional: + optional_variadic = "optional" raise WebIDLError("%s cannot have %s argument" % - ("setter" if setter else "creator", - "optional" if arguments[0].optional else "variadic"), + (setter_creator, + optional_variadic), [arguments[0].location]) if arguments[1].optional or arguments[1].variadic: + optional_variadic = "variadic" + if arguments[1].optional: + optional_variadic = "optional" raise WebIDLError("%s cannot have %s argument" % - ("setter" if setter else "creator", - "optional" if arguments[1].optional else "variadic"), + (setter_creator, + optional_variadic), [arguments[1].location]) if stringifier: @@ -3007,7 +3058,9 @@ class Parser(Tokenizer): raise WebIDLError("Cannot have a non-optional argument following an optional argument", [argument.location]) inOptionalArguments = argument.optional - variadicArgument = argument if argument.variadic else None + variadicArgument = None + if argument.variadic: + variadicArgument = argument # identifier might be None. This is only permitted for special methods. if not identifier: @@ -3017,15 +3070,27 @@ class Parser(Tokenizer): [self.getLocation(p, 2)]) location = BuiltinLocation("<auto-generated-identifier>") + named_indexed = "" + if specialType == IDLMethod.NamedOrIndexed.Named: + named_indexed = "named" + if specialType == IDLMethod.NamedOrIndexed.Indexed: + named_indexed = "indexed" + a_getter = "" + if getter: a_getter = "getter" + a_setter = "" + if setter: a_setter = "setter" + a_deleter = "" + if deleter: a_deleter = "deleter" + a_creator = "" + if creator: a_creator = "creator" + a_legacycaller = "" + if legacycaller: a_legacycaller = "legacycaller" + a_stringifier = "" + if stringifier: a_stringifier = "stringifier" identifier = IDLUnresolvedIdentifier(location, "__%s%s%s%s%s%s%s" % - ("named" if specialType == IDLMethod.NamedOrIndexed.Named else \ - "indexed" if specialType == IDLMethod.NamedOrIndexed.Indexed else "", - "getter" if getter else "", - "setter" if setter else "", - "deleter" if deleter else "", - "creator" if creator else "", - "legacycaller" if legacycaller else "", - "stringifier" if stringifier else ""), allowDoubleUnderscore=True) + (named_indexed, + a_getter, a_setter, a_deleter, a_creator, a_legacycaller, a_stringifier), + allowDoubleUnderscore=True) method = IDLMethod(self.getLocation(p, 2), identifier, returnType, arguments, static=static, getter=getter, setter=setter, creator=creator, @@ -3116,7 +3181,9 @@ class Parser(Tokenizer): """ ArgumentList : Argument Arguments """ - p[0] = [p[1]] if p[1] else [] + p[0] = [] + if p[1]: + p[0] = [p[1]] p[0].extend(p[2]) def p_ArgumentListEmpty(self, p): @@ -3129,7 +3196,9 @@ class Parser(Tokenizer): """ Arguments : COMMA Argument Arguments """ - p[0] = [p[2]] if p[2] else [] + p[0] = [] + if p[2]: + p[0] = [p[2]] p[0].extend(p[3]) def p_ArgumentsEmpty(self, p): @@ -3233,7 +3302,9 @@ class Parser(Tokenizer): """ ExtendedAttributes : COMMA ExtendedAttribute ExtendedAttributes """ - p[0] = [p[2]] if p[2] else [] + p[0] = [] + if p[2]: + p[0] = [p[2]] p[0].extend(p[3]) def p_ExtendedAttributesEmpty(self, p): diff -up mozilla-esr17/ipc/ipdl/ipdl/lower.py.python mozilla-esr17/ipc/ipdl/ipdl/lower.py --- mozilla-esr17/ipc/ipdl/ipdl/lower.py.python 2013-06-18 20:47:19.000000000 +0200 +++ mozilla-esr17/ipc/ipdl/ipdl/lower.py 2013-06-19 23:09:23.000000000 +0200 @@ -5057,7 +5057,10 @@ class _GenerateProtocolActorCode(ipdl.as action = ExprVar('Trigger::Recv') else: assert 0 and 'unknown combo %s/%s'% (self.side, direction) - msgid = md.pqMsgId() if not reply else md.pqReplyId() + + msgid = md.pqMsgId() + if reply: + msgid = md.pqReplyId() ifbad = StmtIf(ExprNot( ExprCall( ExprVar(self.protocol.name +'::Transition'), diff -up mozilla-esr17/js/src/build/ConfigStatus.py.python mozilla-esr17/js/src/build/ConfigStatus.py --- mozilla-esr17/js/src/build/ConfigStatus.py.python 2013-06-18 20:47:19.000000000 +0200 +++ mozilla-esr17/js/src/build/ConfigStatus.py 2013-06-19 23:09:23.000000000 +0200 @@ -6,7 +6,6 @@ # drop-in replacement for autoconf 2.13's config.status, with features # borrowed from autoconf > 2.5, and additional features. -from __future__ import with_statement from optparse import OptionParser import sys, re, os, posixpath, ntpath from StringIO import StringIO @@ -76,13 +75,13 @@ class FileAvoidWrite(StringIO): return except IOError: pass - finally: - file.close() + file.close() log("creating %s" % relpath(self.filename, os.curdir)) ensureParentDir(self.filename) - with open(self.filename, 'w') as file: - file.write(buf) + ff = open(self.filename, 'w') + ff.write(buf) + ff.close() def __enter__(self): return self @@ -203,8 +202,12 @@ class ConfigEnvironment(object): pp.context.update(DEPTH = self.get_depth(path)) pp.do_filter('attemptSubstitution') pp.setMarker(None) - with FileAvoidWrite(path) as pp.out: + pp.out = FileAvoidWrite(path) + pp.out.__enter__() + try: pp.do_include(input) + finally: + pp.out.__exit__(0, 0, 0) def create_config_header(self, path): '''Creates the given config header. A config header is generated by @@ -216,7 +219,8 @@ class ConfigEnvironment(object): "#undef UNKNOWN_NAME" is turned into "/* #undef UNKNOWN_NAME */" Whitespaces are preserved. ''' - with open(self.get_input(path), 'rU') as input: + input = open(self.get_input(path), 'rU') + if 1: ensureParentDir(path) output = FileAvoidWrite(path) r = re.compile('^\s*#\s*(?P<cmd>[a-z]+)(?:\s+(?P<name>\S+)(?:\s+(?P<value>\S+))?)?', re.U) @@ -237,6 +241,7 @@ class ConfigEnvironment(object): output.write(l) output.close() + input.close() def config_status(topobjdir = '.', topsrcdir = '.', defines = [], non_global_defines = [], substs = [], diff -up mozilla-esr17/js/src/builtin/embedjs.py.python mozilla-esr17/js/src/builtin/embedjs.py --- mozilla-esr17/js/src/builtin/embedjs.py.python 2013-06-18 20:47:19.000000000 +0200 +++ mozilla-esr17/js/src/builtin/embedjs.py 2013-06-19 23:09:23.000000000 +0200 @@ -8,16 +8,17 @@ # It expects error messages in the JS code to be referenced by their C enum # keys as literals. -from __future__ import with_statement import re, sys, os, js2c, fileinput def replaceErrorMsgs(source_files, messages_file, output_file): messages = buildMessagesTable(messages_file) - with open(output_file, 'w') as output: + output = open(output_file, 'w') + if 1: if len(source_files) == 0: return for line in fileinput.input(source_files): output.write(replaceMessages(line, messages)) + output.close() def buildMessagesTable(messages_file): table = {} @@ -46,4 +47,4 @@ def main(): os.remove(combined_file) if __name__ == "__main__": - main() \ No newline at end of file + main() diff -up mozilla-esr17/js/src/config/expandlibs_exec.py.python mozilla-esr17/js/src/config/expandlibs_exec.py --- mozilla-esr17/js/src/config/expandlibs_exec.py.python 2013-06-18 20:47:19.000000000 +0200 +++ mozilla-esr17/js/src/config/expandlibs_exec.py 2013-06-19 23:09:23.000000000 +0200 @@ -20,13 +20,11 @@ With the --symbol-order argument, follow relevant linker options to change the order in which the linker puts the symbols appear in the resulting binary. Only works for ELF targets. ''' -from __future__ import with_statement import sys import os from expandlibs import ExpandArgs, relativize, isObject, ensureParentDir, ExpandLibsDeps import expandlibs_config as conf from optparse import OptionParser -import subprocess import tempfile import shutil import subprocess @@ -73,7 +71,11 @@ class ExpandArgsMore(ExpandArgs): elif os.path.exists(arg) and len(ar_extract): tmp = tempfile.mkdtemp(dir=os.curdir) self.tmp.append(tmp) - subprocess.call(ar_extract + [os.path.abspath(arg)], cwd=tmp) + tmp_arg = ar_extract + [os.path.abspath(arg)] + oldir = os.getcwd() + os.chdir(tmp) + os.system(' '.join(tmp_arg)) + os.chdir(oldir) objs = [] for root, dirs, files in os.walk(tmp): objs += [relativize(os.path.join(root, f)) for f in files if isObject(f)] @@ -165,8 +167,8 @@ class ExpandArgsMore(ExpandArgs): def orderSymbols(self, order): '''Given a file containing a list of symbols, adds the appropriate argument to make the linker put the symbols in that order.''' - with open(order) as file: - sections = self._getOrderedSections([l.strip() for l in file.readlines() if l.strip()]) + ff = open(order) + sections = self._getOrderedSections([l.strip() for l in ff.readlines() if l.strip()]) split_sections = {} linked_sections = [s[0] for s in SECTION_INSERT_BEFORE] for s in sections: @@ -293,29 +295,38 @@ def main(): deps.pop(0) # Remove command deps.pop(0) - with ExpandArgsMore(args) as args: + args2 = ExpandArgsMore(args) + args2.__enter__() + try: if options.extract: - args.extract() + args2.extract() if options.symbol_order: - args.orderSymbols(options.symbol_order) + args2.orderSymbols(options.symbol_order) if options.uselist: - args.makelist() + args2.makelist() if options.verbose: - print >>sys.stderr, "Executing: " + " ".join(args) - for tmp in [f for f in args.tmp if os.path.isfile(f)]: + print >>sys.stderr, "Executing: " + " ".join(args2) + for tmp in [f for f in args2.tmp if os.path.isfile(f)]: print >>sys.stderr, tmp + ":" - with open(tmp) as file: - print >>sys.stderr, "".join([" " + l for l in file.readlines()]) + ff = open(tmp) + ff.__enter__() + try: + print >>sys.stderr, "".join([" " + l for l in ff.readlines()]) + finally: + ff.__exit__(0, 0, 0) sys.stderr.flush() - ret = subprocess.call(args) + ret = subprocess.call(args2) if ret: exit(ret) + finally: + args2.__exit__(0, 0, 0) if not options.depend: return ensureParentDir(options.depend) - with open(options.depend, 'w') as depfile: - depfile.write("%s : %s\n" % (options.target, ' '.join(dep for dep in deps if os.path.isfile(dep) and dep != options.target))) + depfile = open(options.depend, 'w') + depfile.write("%s : %s\n" % (options.target, ' '.join(dep for dep in deps if os.path.isfile(dep) and dep != options.target))) + depfile.close() if __name__ == '__main__': diff -up mozilla-esr17/js/src/config/expandlibs_gen.py.python mozilla-esr17/js/src/config/expandlibs_gen.py --- mozilla-esr17/js/src/config/expandlibs_gen.py.python 2013-06-18 20:47:19.000000000 +0200 +++ mozilla-esr17/js/src/config/expandlibs_gen.py 2013-06-19 23:09:23.000000000 +0200 @@ -5,7 +5,6 @@ '''Given a list of object files and library names, prints a library descriptor to standard output''' -from __future__ import with_statement import sys import os import expandlibs_config as conf @@ -39,9 +38,11 @@ if __name__ == '__main__': raise Exception("Missing option: -o") ensureParentDir(options.output) - with open(options.output, 'w') as outfile: - print >>outfile, generate(args) + outfile = open(options.output, 'w') + print >>outfile, generate(args) + outfile.close() if options.depend: ensureParentDir(options.depend) - with open(options.depend, 'w') as depfile: - depfile.write("%s : %s\n" % (options.output, ' '.join(ExpandLibsDeps(args)))) + depfile = open(options.depend, 'w') + depfile.write("%s : %s\n" % (options.output, ' '.join(ExpandLibsDeps(args)))) + depfile.close() diff -up mozilla-esr17/js/src/config/expandlibs.py.python mozilla-esr17/js/src/config/expandlibs.py --- mozilla-esr17/js/src/config/expandlibs.py.python 2013-06-18 20:47:19.000000000 +0200 +++ mozilla-esr17/js/src/config/expandlibs.py 2013-06-19 23:09:23.000000000 +0200 @@ -26,7 +26,6 @@ ${LIB_PREFIX}${ROOT}.${LIB_SUFFIX} follo descriptor contains. And for each of these LIBS, also apply the same rules. ''' -from __future__ import with_statement import sys, os, errno import expandlibs_config as conf @@ -75,15 +74,15 @@ class LibDescriptor(dict): '''Creates an instance of a lib descriptor, initialized with contents from a list of strings when given. This is intended for use with file.readlines()''' - if isinstance(content, list) and all([isinstance(item, str) for item in content]): - pass - elif content is not None: - raise TypeError("LibDescriptor() arg 1 must be None or a list of strings") super(LibDescriptor, self).__init__() for key in self.KEYS: self[key] = [] - if not content: + if content == None: return + if isinstance(content, list): + for item in content: + if not isinstance(item, str): + raise TypeError("LibDescriptor() arg 1 must be None or a list of strings") for key, value in [(s.strip() for s in item.split('=', 2)) for item in content if item.find('=') >= 0]: if key in self.KEYS: self[key] = value.split() @@ -118,8 +117,9 @@ class ExpandArgs(list): def _expand_desc(self, arg): '''Internal function taking care of lib descriptor expansion only''' if os.path.exists(arg + conf.LIBS_DESC_SUFFIX): - with open(arg + conf.LIBS_DESC_SUFFIX, 'r') as f: - desc = LibDescriptor(f.readlines()) + f = open(arg + conf.LIBS_DESC_SUFFIX, 'r') + desc = LibDescriptor(f.readlines()) + f.close() objs = [relativize(o) for o in desc['OBJS']] for lib in desc['LIBS']: objs += self._expand(lib) diff -up mozilla-esr17/js/src/configure.python mozilla-esr17/js/src/configure --- mozilla-esr17/js/src/configure.python 2013-06-18 20:48:48.000000000 +0200 +++ mozilla-esr17/js/src/configure 2013-06-19 23:09:23.000000000 +0200 @@ -934,7 +934,7 @@ _SUBDIR_CONFIG_ARGS="$ac_configure_args" NSPR_VERSION=4 PERL_VERSION=5.006 -PYTHON_VERSION=2.5 +PYTHON_VERSION=2.4 WINDRES_VERSION=2.14.90 W32API_VERSION=3.14 diff -up mozilla-esr17/js/xpconnect/src/codegen.py.python mozilla-esr17/js/xpconnect/src/codegen.py --- mozilla-esr17/js/xpconnect/src/codegen.py.python 2013-06-18 20:47:26.000000000 +0200 +++ mozilla-esr17/js/xpconnect/src/codegen.py 2013-06-19 23:09:23.000000000 +0200 @@ -482,8 +482,11 @@ def writeStub(f, customMethodCalls, memb argumentValues = (customMethodCall['additionalArgumentValues'] % header.methodNativeName(member)) if isAttr: + strict_str = "" + if isSetter: + strict_str = ", strict" callTemplate += (" return %s(cx, obj, id%s, %s, vp_);\n" - % (templateName, ", strict" if isSetter else "", argumentValues)) + % (templateName, strict_str, argumentValues)) else: callTemplate += (" return %s(cx, argc, %s, vp);\n" % (templateName, argumentValues)) diff -up mozilla-esr17/js/xpconnect/src/dombindingsgen.py.python mozilla-esr17/js/xpconnect/src/dombindingsgen.py --- mozilla-esr17/js/xpconnect/src/dombindingsgen.py.python 2013-06-18 20:47:26.000000000 +0200 +++ mozilla-esr17/js/xpconnect/src/dombindingsgen.py 2013-06-19 23:09:23.000000000 +0200 @@ -159,7 +159,10 @@ class DOMClass(UserDict.DictMixin): def ops(getterType, setterType): def opType(type): - return type + (" " if type.endswith('>') else "") + if type.endswith('>'): + return type + " " + else: + return type if getterType or setterType: opsClass = ", Ops<" @@ -178,7 +181,10 @@ class DOMClass(UserDict.DictMixin): if key == 'indexOps': return ops(self.indexGetter and self.indexGetterType, self.indexSetter and self.indexSetterType) if key == 'nameOps': - return ops(self.nameGetter and self.nameGetterType, self.nameSetter and self.nameSetterType) if self.nameGetter else "" + if self.nameGetter: + return ops(self.nameGetter and self.nameGetterType, self.nameSetter and self.nameSetterType) + else: + return "" if key == 'listClass': if self.base: @@ -191,7 +197,10 @@ class DOMClass(UserDict.DictMixin): def __cmp__(x, y): if x.isBase != y.isBase: - return -1 if x.isBase else 1 + if x.isBase: + return -1 + else: + return 1; return cmp(x.name, y.name) class Configuration: diff -up mozilla-esr17/js/xpconnect/src/qsgen.py.python mozilla-esr17/js/xpconnect/src/qsgen.py --- mozilla-esr17/js/xpconnect/src/qsgen.py.python 2013-06-18 20:47:26.000000000 +0200 +++ mozilla-esr17/js/xpconnect/src/qsgen.py 2013-06-19 23:09:23.000000000 +0200 @@ -817,8 +817,11 @@ def writeQuickStub(f, customMethodCalls, argumentValues = (customMethodCall['additionalArgumentValues'] % nativeName) if isAttr: + templateStrict = ", strict" + if not isSetter: + templateStrict = "" callTemplate += (" return %s(cx, obj, id%s, %s, vp_);\n" - % (templateName, ", strict" if isSetter else "", argumentValues)) + % (templateName, templateStrict, argumentValues)) else: callTemplate += (" return %s(cx, argc, %s, vp);\n" % (templateName, argumentValues)) diff -up mozilla-esr17/python/virtualenv/virtualenv.py.python mozilla-esr17/python/virtualenv/virtualenv.py --- mozilla-esr17/python/virtualenv/virtualenv.py.python 2013-06-18 20:47:54.000000000 +0200 +++ mozilla-esr17/python/virtualenv/virtualenv.py 2013-06-19 23:38:15.000000000 +0200 @@ -24,10 +24,12 @@ from distutils.util import strtobool import struct import subprocess +''' if sys.version_info < (2, 5): print('ERROR: %s' % sys.exc_info()[1]) print('ERROR: this script requires Python 2.5 or greater.') sys.exit(101) +''' try: set @@ -1268,6 +1270,11 @@ def install_python(home_dir, lib_dir, in site_filename_dst = change_prefix(site_filename, home_dir) site_dir = os.path.dirname(site_filename_dst) writefile(site_filename_dst, SITE_PY) + cont = open(site_filename_dst).read() + site_f = open(site_filename_dst, 'wb') + site_f.write(re.sub(r'sys.maxsize', 'sys.maxint', cont)) + site_f.close() + writefile(join(site_dir, 'orig-prefix.txt'), prefix) site_packages_filename = join(site_dir, 'no-global-site-packages.txt') if not site_packages: diff -up mozilla-esr17/toolkit/components/telemetry/gen-histogram-data.py.python mozilla-esr17/toolkit/components/telemetry/gen-histogram-data.py --- mozilla-esr17/toolkit/components/telemetry/gen-histogram-data.py.python 2013-06-18 20:48:02.000000000 +0200 +++ mozilla-esr17/toolkit/components/telemetry/gen-histogram-data.py 2013-06-19 23:09:23.000000000 +0200 @@ -5,8 +5,6 @@ # Write out histogram information for C++. The histograms are defined # in a file provided as a command-line argument. -from __future__ import with_statement - import sys import histogram_tools diff -up mozilla-esr17/toolkit/components/telemetry/gen-histogram-enum.py.python mozilla-esr17/toolkit/components/telemetry/gen-histogram-enum.py --- mozilla-esr17/toolkit/components/telemetry/gen-histogram-enum.py.python 2013-06-18 20:48:02.000000000 +0200 +++ mozilla-esr17/toolkit/components/telemetry/gen-histogram-enum.py 2013-06-19 23:09:23.000000000 +0200 @@ -6,8 +6,6 @@ # histograms. The histograms are defined in a file provided as a # command-line argument. -from __future__ import with_statement - import sys import histogram_tools diff -up mozilla-esr17/toolkit/components/telemetry/histogram_tools.py.python mozilla-esr17/toolkit/components/telemetry/histogram_tools.py --- mozilla-esr17/toolkit/components/telemetry/histogram_tools.py.python 2013-06-18 20:48:02.000000000 +0200 +++ mozilla-esr17/toolkit/components/telemetry/histogram_tools.py 2013-06-19 23:09:23.000000000 +0200 @@ -2,14 +2,13 @@ # 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/. -from __future__ import with_statement - import simplejson as json def from_file(filename): """Return an iterator that provides (name, definition) tuples of histograms defined in filename. """ - with open(filename, 'r') as f: - histograms = json.load(f, object_pairs_hook=json.OrderedDict) - return histograms.iteritems() + f = open(filename, 'r') + histograms = json.load(f, object_pairs_hook=json.OrderedDict) + f.close() + return histograms.iteritems() diff -up mozilla-esr17/xpcom/idl-parser/header.py.python mozilla-esr17/xpcom/idl-parser/header.py --- mozilla-esr17/xpcom/idl-parser/header.py.python 2013-06-18 20:48:08.000000000 +0200 +++ mozilla-esr17/xpcom/idl-parser/header.py 2013-06-19 23:09:23.000000000 +0200 @@ -7,7 +7,7 @@ """Print a C++ header file for the IDL files specified on the command line""" -import sys, os.path, re, xpidl, itertools, glob +import sys, os.path, re, xpidl, itertools, glob, string printdoccomments = False @@ -159,7 +159,7 @@ forward_decl = """class %(name)s; /* for def idl_basename(f): """returns the base name of a file with the last extension stripped""" - return os.path.basename(f).rpartition('.')[0] + return string.split(os.path.basename(f), '.')[0] def print_header(idl, fd, filename): fd.write(header % {'filename': filename, @@ -333,11 +333,17 @@ def write_interface(iface, fd): fd.write(" %s = 0;\n" % attributeAsNative(a, True)) if a.infallible: + args = '' + if a.implicit_jscontext: + args = 'JSContext* cx' + argnames = '' + if a.implicit_jscontext: + argnames = 'cx, ' fd.write(attr_infallible_tmpl % {'realtype': a.realtype.nativeType('in'), 'nativename': attributeNativeName(a, getter=True), - 'args': '' if not a.implicit_jscontext else 'JSContext* cx', - 'argnames': '' if not a.implicit_jscontext else 'cx, '}) + 'args': args, + 'argnames': argnames}) if not a.readonly: fd.write(" %s = 0;\n" % attributeAsNative(a, False)) @@ -475,7 +481,9 @@ if __name__ == '__main__': o.add_option('--regen', action='store_true', dest='regen', default=False, help="Regenerate IDL Parser cache") options, args = o.parse_args() - file = args[0] if args else None + file = None + if args: + file = args[0] if options.cachedir is not None: if not os.path.isdir(options.cachedir): diff -up mozilla-esr17/xpcom/idl-parser/typelib.py.python mozilla-esr17/xpcom/idl-parser/typelib.py --- mozilla-esr17/xpcom/idl-parser/typelib.py.python 2013-06-18 20:48:08.000000000 +0200 +++ mozilla-esr17/xpcom/idl-parser/typelib.py 2013-06-19 23:09:23.000000000 +0200 @@ -260,7 +260,9 @@ if __name__ == '__main__': o.add_option('--regen', action='store_true', dest='regen', default=False, help="Regenerate IDL Parser cache") options, args = o.parse_args() - file = args[0] if args else None + file = None + if args: + file = args[0] if options.cachedir is not None: if not os.path.isdir(options.cachedir): diff -up mozilla-esr17/xpcom/typelib/xpt/tools/xpt.py.python mozilla-esr17/xpcom/typelib/xpt/tools/xpt.py --- mozilla-esr17/xpcom/typelib/xpt/tools/xpt.py.python 2013-06-18 20:48:08.000000000 +0200 +++ mozilla-esr17/xpcom/typelib/xpt/tools/xpt.py 2013-06-19 23:09:23.000000000 +0200 @@ -65,7 +65,6 @@ InterfaceType() - construct a new """ -from __future__ import with_statement import os, sys import struct import operator @@ -102,7 +101,7 @@ class Type(object): this class directly. Rather, use one of its subclasses. """ - _prefixdescriptor = struct.Struct(">B") + _prefixdescriptor = struct Tags = enum( # The first 18 entries are SimpleTypeDescriptor 'int8', @@ -184,13 +183,13 @@ class Type(object): """ start = data_pool + offset - 1 - (data,) = Type._prefixdescriptor.unpack(map[start:start + Type._prefixdescriptor.size]) + (data,) = Type._prefixdescriptor.unpack(">B", map[start:start + Type._prefixdescriptor.calcsize(">B")]) # first three bits are the flags flags = data & 0xE0 flags = Type.decodeflags(flags) # last five bits is the tag tag = data & 0x1F - offset += Type._prefixdescriptor.size + offset += Type._prefixdescriptor.calcsize(">B") t = None if tag <= Type.Tags.wchar_t_ptr or tag >= Type.Tags.UTF8String: t = SimpleType.get(data, tag, flags) @@ -214,7 +213,7 @@ class Type(object): and the subclass method must be called. """ - file.write(Type._prefixdescriptor.pack(self.encodeflags() | self.tag)) + file.write(Type._prefixdescriptor.pack(">B", self.encodeflags() | self.tag)) class SimpleType(Type): """ @@ -263,7 +262,7 @@ class InterfaceType(Type): (InterfaceTypeDescriptor from the typelib specification.) """ - _descriptor = struct.Struct(">H") + _descriptor = struct def __init__(self, iface, pointer=True, **kwargs): if not pointer: @@ -285,8 +284,8 @@ class InterfaceType(Type): if not flags['pointer']: return None, offset start = data_pool + offset - 1 - (iface_index,) = InterfaceType._descriptor.unpack(map[start:start + InterfaceType._descriptor.size]) - offset += InterfaceType._descriptor.size + (iface_index,) = InterfaceType._descriptor.unpack(">H", map[start:start + InterfaceType._descriptor.calcsize(">H")]) + offset += InterfaceType._descriptor.calcsize(">H") iface = None # interface indices are 1-based if iface_index > 0 and iface_index <= len(typelib.interfaces): @@ -301,7 +300,7 @@ class InterfaceType(Type): """ Type.write(self, typelib, file) # write out the interface index (1-based) - file.write(InterfaceType._descriptor.pack(typelib.interfaces.index(self.iface) + 1)) + file.write(InterfaceType._descriptor.pack(">H", typelib.interfaces.index(self.iface) + 1)) def __str__(self): if self.iface: @@ -315,7 +314,7 @@ class InterfaceIsType(Type): typelib specification.) """ - _descriptor = struct.Struct(">B") + _descriptor = struct _cache = {} def __init__(self, param_index, pointer=True, **kwargs): @@ -339,8 +338,8 @@ class InterfaceIsType(Type): if not flags['pointer']: return None, offset start = data_pool + offset - 1 - (param_index,) = InterfaceIsType._descriptor.unpack(map[start:start + InterfaceIsType._descriptor.size]) - offset += InterfaceIsType._descriptor.size + (param_index,) = InterfaceIsType._descriptor.unpack(">B", map[start:start + InterfaceIsType._descriptor.calcsize(">B")]) + offset += InterfaceIsType._descriptor.calcsize(">B") if param_index not in InterfaceIsType._cache: InterfaceIsType._cache[param_index] = InterfaceIsType(param_index, **flags) return InterfaceIsType._cache[param_index], offset @@ -352,7 +351,7 @@ class InterfaceIsType(Type): """ Type.write(self, typelib, file) - file.write(InterfaceIsType._descriptor.pack(self.param_index)) + file.write(InterfaceIsType._descriptor.pack(">B", self.param_index)) def __str__(self): return "InterfaceIs *" @@ -364,7 +363,7 @@ class ArrayType(Type): (ArrayTypeDescriptor from the typelib specification.) """ - _descriptor = struct.Struct(">BB") + _descriptor = struct def __init__(self, element_type, size_is_arg_num, length_is_arg_num, pointer=True, **kwargs): @@ -388,8 +387,8 @@ class ArrayType(Type): if not flags['pointer']: return None, offset start = data_pool + offset - 1 - (size_is_arg_num, length_is_arg_num) = ArrayType._descriptor.unpack(map[start:start + ArrayType._descriptor.size]) - offset += ArrayType._descriptor.size + (size_is_arg_num, length_is_arg_num) = ArrayType._descriptor.unpack(">BB", map[start:start + ArrayType._descriptor.calcsize(">BB")]) + offset += ArrayType._descriptor.calcsize(">BB") t, offset = Type.read(typelib, map, data_pool, offset) return ArrayType(t, size_is_arg_num, length_is_arg_num, **flags), offset @@ -400,7 +399,7 @@ class ArrayType(Type): """ Type.write(self, typelib, file) - file.write(ArrayType._descriptor.pack(self.size_is_arg_num, + file.write(ArrayType._descriptor.pack(">BB", self.size_is_arg_num, self.length_is_arg_num)) self.element_type.write(typelib, file) @@ -414,7 +413,7 @@ class StringWithSizeType(Type): from the typelib specification.) """ - _descriptor = struct.Struct(">BB") + _descriptor = struct def __init__(self, size_is_arg_num, length_is_arg_num, pointer=True, **kwargs): @@ -437,8 +436,8 @@ class StringWithSizeType(Type): if not flags['pointer']: return None, offset start = data_pool + offset - 1 - (size_is_arg_num, length_is_arg_num) = StringWithSizeType._descriptor.unpack(map[start:start + StringWithSizeType._descriptor.size]) - offset += StringWithSizeType._descriptor.size + (size_is_arg_num, length_is_arg_num) = StringWithSizeType._descriptor.unpack(">BB", map[start:start + StringWithSizeType._descriptor.calcsize(">BB")]) + offset += StringWithSizeType._descriptor.calcsize(">BB") return StringWithSizeType(size_is_arg_num, length_is_arg_num, **flags), offset def write(self, typelib, file): @@ -448,7 +447,7 @@ class StringWithSizeType(Type): """ Type.write(self, typelib, file) - file.write(StringWithSizeType._descriptor.pack(self.size_is_arg_num, + file.write(StringWithSizeType._descriptor.pack(">BB", self.size_is_arg_num, self.length_is_arg_num)) def __str__(self): @@ -461,7 +460,7 @@ class WideStringWithSizeType(Type): (WideStringWithSizeTypeDescriptor from the typelib specification.) """ - _descriptor = struct.Struct(">BB") + _descriptor = struct def __init__(self, size_is_arg_num, length_is_arg_num, pointer=True, **kwargs): @@ -484,8 +483,8 @@ class WideStringWithSizeType(Type): if not flags['pointer']: return None, offset start = data_pool + offset - 1 - (size_is_arg_num, length_is_arg_num) = WideStringWithSizeType._descriptor.unpack(map[start:start + WideStringWithSizeType._descriptor.size]) - offset += WideStringWithSizeType._descriptor.size + (size_is_arg_num, length_is_arg_num) = WideStringWithSizeType._descriptor.unpack(">BB", map[start:start + WideStringWithSizeType._descriptor.calcsize(">BB")]) + offset += WideStringWithSizeType._descriptor.calcsize(">BB") return WideStringWithSizeType(size_is_arg_num, length_is_arg_num, **flags), offset def write(self, typelib, file): @@ -495,7 +494,7 @@ class WideStringWithSizeType(Type): """ Type.write(self, typelib, file) - file.write(WideStringWithSizeType._descriptor.pack(self.size_is_arg_num, + file.write(WideStringWithSizeType._descriptor.pack(">BB", self.size_is_arg_num, self.length_is_arg_num)) def __str__(self): @@ -507,7 +506,7 @@ class Param(object): (ParamDescriptor from the typelib specification.) """ - _descriptorstart = struct.Struct(">B") + _descriptorstart = struct def __init__(self, type, in_=True, out=False, retval=False, shared=False, dipper=False, optional=False): @@ -574,11 +573,11 @@ class Param(object): following this ParamDescriptor. """ start = data_pool + offset - 1 - (flags,) = Param._descriptorstart.unpack(map[start:start + Param._descriptorstart.size]) + (flags,) = Param._descriptorstart.unpack(">B", map[start:start + Param._descriptorstart.calcsize(">B")]) # only the first five bits are flags flags &= 0xFC flags = Param.decodeflags(flags) - offset += Param._descriptorstart.size + offset += Param._descriptorstart.calcsize(">B") t, offset = Type.read(typelib, map, data_pool, offset) p = Param(t, **flags) return p, offset @@ -589,7 +588,7 @@ class Param(object): to the correct position. """ - file.write(Param._descriptorstart.pack(self.encodeflags())) + file.write(Param._descriptorstart.pack(">B", self.encodeflags())) self.type.write(typelib, file) def prefix(self): @@ -626,7 +625,7 @@ class Method(object): (MethodDescriptor from the typelib specification.) """ - _descriptorstart = struct.Struct(">BIB") + _descriptorstart = struct def __init__(self, name, result, params=[], getter=False, setter=False, notxpcom=False, @@ -724,13 +723,13 @@ class Method(object): """ start = data_pool + offset - 1 - flags, name_offset, num_args = Method._descriptorstart.unpack(map[start:start + Method._descriptorstart.size]) + flags, name_offset, num_args = Method._descriptorstart.unpack(">BIB", map[start:start + Method._descriptorstart.calcsize(">BIB")]) # only the first seven bits are flags flags &= 0xFE flags = Method.decodeflags(flags) name = Typelib.read_string(map, data_pool, name_offset) m = Method(name, None, **flags) - offset += Method._descriptorstart.size + offset += Method._descriptorstart.calcsize(">BIB") offset = m.read_params(typelib, map, data_pool, offset, num_args) offset = m.read_result(typelib, map, data_pool, offset) return m, offset @@ -741,7 +740,7 @@ class Method(object): seeked to the right position. """ - file.write(Method._descriptorstart.pack(self.encodeflags(), + file.write(Method._descriptorstart.pack(">BIB", self.encodeflags(), self._name_offset, len(self.params))) for p in self.params: @@ -767,7 +766,7 @@ class Constant(object): (ConstantDesciptor from the typelib specification.) """ - _descriptorstart = struct.Struct(">I") + _descriptorstart = struct # Actual value is restricted to this set of types #XXX: the spec lies, the source allows a bunch more # http://hg.mozilla.org/mozilla-central/annotate/9c85f9aaec8c/xpcom/typelib/xpt/src/xpt_struct.c#l689 @@ -792,9 +791,9 @@ class Constant(object): """ start = data_pool + offset - 1 - (name_offset,) = Constant._descriptorstart.unpack(map[start:start + Constant._descriptorstart.size]) + (name_offset,) = Constant._descriptorstart.unpack(">I", map[start:start + Constant._descriptorstart.calcsize(">I")]) name = Typelib.read_string(map, data_pool, name_offset) - offset += Constant._descriptorstart.size + offset += Constant._descriptorstart.calcsize(">I") # Read TypeDescriptor t, offset = Type.read(typelib, map, data_pool, offset) c = None @@ -812,7 +811,7 @@ class Constant(object): to be seeked to the proper position. """ - file.write(Constant._descriptorstart.pack(self._name_offset)) + file.write(Constant._descriptorstart.pack(">I", self._name_offset)) self.type.write(typelib, file) tt = Constant.typemap[self.type.tag] file.write(struct.pack(tt, self.value)) @@ -840,8 +839,8 @@ class Interface(object): (InterfaceDescriptor from the typelib specification.) """ - _direntry = struct.Struct(">16sIII") - _descriptorstart = struct.Struct(">HH") + _direntry = struct + _descriptorstart = struct UNRESOLVED_IID = "00000000-0000-0000-0000-000000000000" @@ -909,11 +908,11 @@ class Interface(object): if offset == 0: return start = data_pool + offset - 1 - parent, num_methods = Interface._descriptorstart.unpack(map[start:start + Interface._descriptorstart.size]) + parent, num_methods = Interface._descriptorstart.unpack(">HH", map[start:start + Interface._descriptorstart.calcsize(">HH")]) if parent > 0 and parent <= len(typelib.interfaces): self.parent = typelib.interfaces[parent - 1] # Read methods - offset += Interface._descriptorstart.size + offset += Interface._descriptorstart.calcsize(">HH") for i in range(num_methods): m, offset = Method.read(typelib, map, data_pool, offset) self.methods.append(m) @@ -944,7 +943,7 @@ class Interface(object): to |file|, which is assumed to be seeked to the correct offset. """ - file.write(Interface._direntry.pack(Typelib.string_to_iid(self.iid), + file.write(Interface._direntry.pack(">16sIII", Typelib.string_to_iid(self.iid), self._name_offset, self._namespace_offset, self._descriptor_offset)) @@ -963,7 +962,7 @@ class Interface(object): parent_idx = 0 if self.parent: parent_idx = typelib.interfaces.index(self.parent) + 1 - file.write(Interface._descriptorstart.pack(parent_idx, len(self.methods))) + file.write(Interface._descriptorstart.pack(">HH", parent_idx, len(self.methods))) for m in self.methods: m.write(typelib, file) file.write(struct.pack(">H", len(self.constants))) @@ -1011,7 +1010,7 @@ class Typelib(object): or the static Typelib.read method may be called to read one from a file. """ - _header = struct.Struct(">16sBBHIII") + _header = struct def __init__(self, version=TYPELIB_VERSION, interfaces=[], annotations=[]): """ @@ -1067,10 +1066,11 @@ class Typelib(object): expected_size = None if isinstance(input_file, basestring): filename = input_file - with open(input_file, "rb") as f: - st = os.fstat(f.fileno()) - data = f.read(st.st_size) - expected_size = st.st_size + f = open(input_file, "rb") + st = os.fstat(f.fileno()) + data = f.read(st.st_size) + expected_size = st.st_size + f.close() else: data = input_file.read() @@ -1080,7 +1080,7 @@ class Typelib(object): num_interfaces, file_length, interface_directory_offset, - data_pool_offset) = Typelib._header.unpack(data[:Typelib._header.size]) + data_pool_offset) = Typelib._header.unpack(">16sBBHIII", data[:Typelib._header.calcsize(">16sBBHIII")]) if magic != XPT_MAGIC: raise FileFormatError, "Bad magic: %s" % magic xpt = Typelib((major_ver, minor_ver)) @@ -1095,7 +1095,7 @@ class Typelib(object): interface_directory_offset -= 1 # make a half-hearted attempt to read Annotations, # since XPIDL doesn't produce any anyway. - start = Typelib._header.size + start = Typelib._header.calcsize(">16sBBHIII") (anno, ) = struct.unpack(">B", data[start:start + struct.calcsize(">B")]) islast = anno & 0x80 tag = anno & 0x7F @@ -1105,9 +1105,9 @@ class Typelib(object): for i in range(num_interfaces): # iid, name, namespace, interface_descriptor - start = interface_directory_offset + i * Interface._direntry.size - end = interface_directory_offset + (i+1) * Interface._direntry.size - ide = Interface._direntry.unpack(data[start:end]) + start = interface_directory_offset + i * Interface._direntry.calcsize(">16sIII") + end = interface_directory_offset + (i+1) * Interface._direntry.calcsize(">16sIII") + ide = Interface._direntry.unpack(">16sIII", data[start:end]) iid = Typelib.iid_to_string(ide[0]) name = Typelib.read_string(data, data_pool_offset, ide[1]) namespace = Typelib.read_string(data, data_pool_offset, ide[2]) @@ -1144,14 +1144,14 @@ class Typelib(object): def writefd(self, fd): # write out space for a header + one empty annotation, # padded to 4-byte alignment. - headersize = (Typelib._header.size + 1) + headersize = (Typelib._header.calcsize(">16sBBHIII") + 1) if headersize % 4: headersize += 4 - headersize % 4 fd.write("\x00" * headersize) # save this offset, it's the interface directory offset. interface_directory_offset = fd.tell() # write out space for an interface directory - fd.write("\x00" * Interface._direntry.size * len(self.interfaces)) + fd.write("\x00" * Interface._direntry.calcsize(">16sIII") * len(self.interfaces)) # save this offset, it's the data pool offset. data_pool_offset = fd.tell() # write out all the interface descriptors to the data pool @@ -1161,7 +1161,7 @@ class Typelib(object): # now, seek back and write the header file_len = fd.tell() fd.seek(0) - fd.write(Typelib._header.pack(XPT_MAGIC, + fd.write(Typelib._header.pack(">16sBBHIII", XPT_MAGIC, TYPELIB_VERSION[0], TYPELIB_VERSION[1], len(self.interfaces), @@ -1185,8 +1185,9 @@ class Typelib(object): """ self._sanityCheck() if isinstance(output_file, basestring): - with open(output_file, "wb") as f: - self.writefd(f) + f = open(output_file, "wb") + self.writefd(f) + f.close() else: self.writefd(output_file)