Bug 987618 - More cosmetic changes in Codegen.py. r=bz.
authorJason Orendorff <jorendorff@mozilla.com>
Fri, 25 Apr 2014 11:50:34 -0500
changeset 180608 cfe59efce491a31ea6f5c86daff91179ed532c74
parent 180607 d6064bbed583e732e28b5ecdb31d75b780976afe
child 180609 f42f8c4bfd26cee4b9900a5a299479bae3d08ada
push id272
push userpvanderbeken@mozilla.com
push dateMon, 05 May 2014 16:31:18 +0000
reviewersbz
bugs987618
milestone31.0a1
Bug 987618 - More cosmetic changes in Codegen.py. r=bz.
dom/bindings/Codegen.py
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -1,20 +1,18 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
 # You can obtain one at http://mozilla.org/MPL/2.0/.
 
 # Common codegen classes.
 
-import operator
 import os
 import re
 import string
 import math
-import itertools
 import textwrap
 
 from WebIDL import BuiltinTypes, IDLBuiltinType, IDLNullValue, IDLSequenceType, IDLType, IDLAttribute, IDLUndefinedValue
 from Configuration import NoSuchDescriptorError, getTypesFromDescriptor, getTypesFromDictionary, getTypesFromCallback, Descriptor
 
 AUTOGENERATED_WARNING_COMMENT = \
     "/* THIS FILE IS AUTOGENERATED - DO NOT EDIT */\n\n"
 ADDPROPERTY_HOOK_NAME = '_addProperty'
@@ -501,17 +499,17 @@ def CallOnUnforgeableHolder(descriptor, 
     If isXrayCheck is not None it should be a string that contains a statement
     returning whether proxy is an Xray. If isXrayCheck is None the generated
     code won't try to unwrap Xrays.
 
     If useSharedRoot is true, we will use an existing
     JS::Rooted<JSObject*> sharedRoot for storing our unforgeable holder instead
     of declaring a new Rooted.
     """
-    if not isXrayCheck is None:
+    if isXrayCheck is not None:
         pre = fill(
             """
             // Scope for 'global', 'ac' and 'unforgeableHolder'
             {
               JS::Rooted<JSObject*> global(cx);
               Maybe<JSAutoCompartment> ac;
               if (${isXrayCheck}) {
                 global = js::GetGlobalForObjectCrossCompartment(js::UncheckedUnwrap(proxy));
@@ -554,17 +552,17 @@ class CGPrototypeJSClass(CGThing):
         self.descriptor = descriptor
         self.properties = properties
 
     def declare(self):
         # We're purely for internal consumption
         return ""
 
     def define(self):
-        (prototypeID, depth) = PrototypeIDAndDepth(self.descriptor)
+        prototypeID, depth = PrototypeIDAndDepth(self.descriptor)
         slotCount = "DOM_INTERFACE_PROTO_SLOTS_BASE"
         if UseHolderForUnforgeable(self.descriptor):
             slotCount += " + 1 /* slot for the JSObject holding the unforgeable properties */"
         return fill(
             """
             static const DOMIfaceAndProtoJSClass PrototypeClass = {
               {
                 "${name}Prototype",
@@ -617,17 +615,17 @@ class CGInterfaceObjectJSClass(CGThing):
         else:
             ctorname = "ThrowingConstructor"
         if NeedsGeneratedHasInstance(self.descriptor):
             hasinstance = HASINSTANCE_HOOK_NAME
         elif self.descriptor.interface.hasInterfacePrototypeObject():
             hasinstance = "InterfaceHasInstance"
         else:
             hasinstance = "nullptr"
-        (prototypeID, depth) = PrototypeIDAndDepth(self.descriptor)
+        prototypeID, depth = PrototypeIDAndDepth(self.descriptor)
         slotCount = "DOM_INTERFACE_SLOTS_BASE"
         if len(self.descriptor.interface.namedConstructors) > 0:
             slotCount += (" + %i /* slots for the named constructors */" %
                           len(self.descriptor.interface.namedConstructors))
         return fill(  # BOGUS extra newline at the top
             """
 
             static const DOMIfaceAndProtoJSClass InterfaceObjectClass = {
@@ -681,18 +679,18 @@ class CGList(CGThing):
         self.children.append(child)
 
     def prepend(self, child):
         self.children.insert(0, child)
 
     def extend(self, kids):
         self.children.extend(kids)
 
-    def join(self, generator):
-        return self.joiner.join(filter(lambda s: len(s) > 0, (child for child in generator)))
+    def join(self, iterable):
+        return self.joiner.join(s for s in iterable if len(s) > 0)
 
     def declare(self):
         return self.join(child.declare() for child in self.children if child is not None)
 
     def define(self):
         return self.join(child.define() for child in self.children if child is not None)
 
     def deps(self):
@@ -1108,31 +1106,21 @@ class CGHeaders(CGWrapper):
     @staticmethod
     def getDeclarationFilename(decl):
         # Use our local version of the header, not the exported one, so that
         # test bindings, which don't export, will work correctly.
         basename = os.path.basename(decl.filename())
         return basename.replace('.webidl', 'Binding.h')
 
 
-def SortedTuples(l):
-    """
-    Sort a list of tuples based on the first item in the tuple
-    """
-    return sorted(l, key=operator.itemgetter(0))
-
-
 def SortedDictValues(d):
     """
     Returns a list of values from the dict sorted by key.
     """
-    # Create a list of tuples containing key and value, sorted on key.
-    d = SortedTuples(d.items())
-    # We're only interested in the values.
-    return (i[1] for i in d)
+    return [v for k, v in sorted(d.items())]
 
 
 def UnionTypes(descriptors, dictionaries, callbacks, config):
     """
     Returns a tuple containing a set of header filenames to include in
     UnionTypes.h, a set of header filenames to include in UnionTypes.cpp, a set
     of tuples containing a type declaration and a boolean if the type is a
     struct for member types of the unions and a CGList containing CGUnionStructs
@@ -1142,27 +1130,26 @@ def UnionTypes(descriptors, dictionaries
     # Now find all the things we'll need as arguments and return values because
     # we need to wrap or unwrap them.
     headers = set()
     implheaders = set(["UnionTypes.h"])
     declarations = set()
     unionStructs = dict()
     owningUnionStructs = dict()
 
-    def addInfoForType((t, descriptor, dictionary)):
-        """
-        Add info for the given type.  descriptor and dictionary, if passed, are
-        used to figure out what to do with interface types.
-        """
+    for t, descriptor, dictionary in getAllTypes(descriptors, dictionaries, callbacks):
+        # Add info for the given type.  descriptor and dictionary, if present, are
+        # used to figure out what to do with interface types.
         assert not descriptor or not dictionary
+
         t = t.unroll()
         if not t.isUnion():
-            return
+            continue
         name = str(t)
-        if not name in unionStructs:
+        if name not in unionStructs:
             providers = getRelevantProviders(descriptor, config)
             # FIXME: Unions are broken in workers.  See bug 809899.
             unionStructs[name] = CGUnionStruct(t, providers[0])
             owningUnionStructs[name] = CGUnionStruct(t, providers[0],
                                                      ownsMembers=True)
 
             for f in t.flatMemberTypes:
                 f = f.unroll()
@@ -1199,43 +1186,41 @@ def UnionTypes(descriptors, dictionaries
                     # unfortunately.
                     headers.add(CGHeaders.getDeclarationFilename(f.inner))
                 elif f.isCallback():
                     # Callbacks always use strong refs, so we need to include
                     # the right header to be able to Release() in our inlined
                     # code.
                     headers.add(CGHeaders.getDeclarationFilename(f))
 
-    map(addInfoForType, getAllTypes(descriptors, dictionaries, callbacks))
-
     return (headers, implheaders, declarations,
-            CGList(itertools.chain(SortedDictValues(unionStructs),
-                                   SortedDictValues(owningUnionStructs)), "\n"))
+            CGList(SortedDictValues(unionStructs) +
+                   SortedDictValues(owningUnionStructs),
+                   "\n"))
 
 
 def UnionConversions(descriptors, dictionaries, callbacks, config):
     """
     Returns a CGThing to declare all union argument conversion helper structs.
     """
     # Now find all the things we'll need as arguments because we
     # need to unwrap them.
     headers = set()
     unionConversions = dict()
 
-    def addInfoForType((t, descriptor, dictionary)):
-        """
-        Add info for the given type.  descriptor and dictionary, if passed, are
-        used to figure out what to do with interface types.
-        """
+    for t, descriptor, dictionary in getAllTypes(descriptors, dictionaries, callbacks):
+        # Add info for the given type.  descriptor and dictionary, if passed, are
+        # used to figure out what to do with interface types.
         assert not descriptor or not dictionary
+
         t = t.unroll()
         if not t.isUnion():
-            return
+            continue
         name = str(t)
-        if not name in unionConversions:
+        if name not in unionConversions:
             providers = getRelevantProviders(descriptor, config)
             unionConversions[name] = CGUnionConversionStruct(t, providers[0])
             for f in t.flatMemberTypes:
                 f = f.unroll()
                 if f.isInterface():
                     if f.isSpiderMonkeyInterface():
                         headers.add("jsfriendapi.h")
                         headers.add("mozilla/dom/TypedArray.h")
@@ -1256,18 +1241,16 @@ def UnionConversions(descriptors, dictio
                     if (f.isGeckoInterface() and
                         providers[0].getDescriptor(f.inner.identifier.name).hasXPConnectImpls):
                         headers.add("nsDOMQS.h")
                 elif f.isDictionary():
                     headers.add(CGHeaders.getDeclarationFilename(f.inner))
                 elif f.isPrimitive():
                     headers.add("mozilla/dom/PrimitiveConversions.h")
 
-    map(addInfoForType, getAllTypes(descriptors, dictionaries, callbacks))
-
     return (headers,
             CGWrapper(CGList(SortedDictValues(unionConversions), "\n"),
                       post="\n\n"))
 
 
 class Argument():
     """
     A class for outputting the type and name of an argument
@@ -1410,18 +1393,20 @@ class CGGetJSClassMethod(CGAbstractMetho
         return "  return Class.ToJSClass();\n"
 
 
 class CGAddPropertyHook(CGAbstractClassHook):
     """
     A hook for addProperty, used to preserve our wrapper from GC.
     """
     def __init__(self, descriptor):
-        args = [Argument('JSContext*', 'cx'), Argument('JS::Handle<JSObject*>', 'obj'),
-                Argument('JS::Handle<jsid>', 'id'), Argument('JS::MutableHandle<JS::Value>', 'vp')]
+        args = [Argument('JSContext*', 'cx'),
+                Argument('JS::Handle<JSObject*>', 'obj'),
+                Argument('JS::Handle<jsid>', 'id'),
+                Argument('JS::MutableHandle<JS::Value>', 'vp')]
         CGAbstractClassHook.__init__(self, descriptor, ADDPROPERTY_HOOK_NAME,
                                      'bool', args)
 
     def generate_code(self):
         assert self.descriptor.wrapperCache
         return indent(dedent("""
             // We don't want to preserve if we don't have a wrapper.
             if (self->GetWrapperPreserveColor()) {
@@ -1465,17 +1450,19 @@ class CGClassFinalizeHook(CGAbstractClas
         return indent(finalizeHook(self.descriptor, self.name, self.args[0].name).define())
 
 
 class CGClassConstructor(CGAbstractStaticMethod):
     """
     JS-visible constructor for our objects
     """
     def __init__(self, descriptor, ctor, name=CONSTRUCT_HOOK_NAME):
-        args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'), Argument('JS::Value*', 'vp')]
+        args = [Argument('JSContext*', 'cx'),
+                Argument('unsigned', 'argc'),
+                Argument('JS::Value*', 'vp')]
         CGAbstractStaticMethod.__init__(self, descriptor, name, 'bool', args)
         self._ctor = ctor
 
     def define(self):
         if not self._ctor:
             return ""
         return CGAbstractStaticMethod.define(self)
 
@@ -1653,18 +1640,20 @@ class CGNamedConstructors(CGThing):
             """,
             name=self.descriptor.name,
             constructorID=constructorID,
             namedConstructors=namedConstructors)
 
 
 class CGClassHasInstanceHook(CGAbstractStaticMethod):
     def __init__(self, descriptor):
-        args = [Argument('JSContext*', 'cx'), Argument('JS::Handle<JSObject*>', 'obj'),
-                Argument('JS::MutableHandle<JS::Value>', 'vp'), Argument('bool*', 'bp')]
+        args = [Argument('JSContext*', 'cx'),
+                Argument('JS::Handle<JSObject*>', 'obj'),
+                Argument('JS::MutableHandle<JS::Value>', 'vp'),
+                Argument('bool*', 'bp')]
         CGAbstractStaticMethod.__init__(self, descriptor, HASINSTANCE_HOOK_NAME,
                                         'bool', args)
 
     def define(self):
         if not NeedsGeneratedHasInstance(self.descriptor):
             return ""
         return CGAbstractStaticMethod.define(self)
 
@@ -1940,17 +1929,17 @@ def overloadLength(arguments):
     i = len(arguments)
     while i > 0 and arguments[i - 1].optional:
         i -= 1
     return i
 
 
 def methodLength(method):
     signatures = method.signatures()
-    return min(overloadLength(arguments) for (retType, arguments) in signatures)
+    return min(overloadLength(arguments) for retType, arguments in signatures)
 
 
 class MethodDefiner(PropertyDefiner):
     """
     A class for defining methods on a prototype object.
     """
     def __init__(self, descriptor, name, static):
         PropertyDefiner.__init__(self, descriptor, name)
@@ -2394,17 +2383,17 @@ class CGCreateInterfaceObjectsMethod(CGA
 
         prefCacheData = []
         for var in self.properties.arrayNames():
             props = getattr(self.properties, var)
             prefCacheData.extend(props.prefCacheData)
         if len(prefCacheData) != 0:
             prefCacheData = [
                 CGGeneric('Preferences::AddBoolVarCache(%s, "%s");\n' % (ptr, pref))
-                for (pref, ptr) in prefCacheData]
+                for pref, ptr in prefCacheData]
             prefCache = CGWrapper(CGIndenter(CGList(prefCacheData)),
                                   pre=("static bool sPrefCachesInited = false;\n"
                                        "if (!sPrefCachesInited) {\n"
                                        "  sPrefCachesInited = true;\n"),
                                   post="}\n")
         else:
             prefCache = None
 
@@ -4641,17 +4630,17 @@ def instantiateJSToNativeConversion(info
     """
     Take a JSToNativeConversionInfo as returned by getJSToNativeConversionInfo
     and a set of replacements as required by the strings in such an object, and
     generate code to convert into stack C++ types.
 
     If checkForValue is True, then the conversion will get wrapped in
     a check for ${haveValue}.
     """
-    (templateBody, declType, holderType, dealWithOptional) = (
+    templateBody, declType, holderType, dealWithOptional = (
         info.template, info.declType, info.holderType, info.dealWithOptional)
 
     if dealWithOptional and not checkForValue:
         raise TypeError("Have to deal with optional things, but don't know how")
     if checkForValue and declType is None:
         raise TypeError("Need to predeclare optional things, so they will be "
                         "outside the check for big enough arg count!")
 
@@ -4992,20 +4981,20 @@ def getWrapTemplateForType(type, descrip
         return (setUndefined(), True)
 
     if type.isArray():
         raise TypeError("Can't handle array return values yet")
 
     if type.isSequence():
         if type.nullable():
             # Nullable sequences are Nullable< nsTArray<T> >
-            (recTemplate, recInfall) = getWrapTemplateForType(type.inner, descriptorProvider,
-                                                              "%s.Value()" % result, successCode,
-                                                              returnsNewObject, exceptionCode,
-                                                              typedArraysAreStructs)
+            recTemplate, recInfall = getWrapTemplateForType(type.inner, descriptorProvider,
+                                                            "%s.Value()" % result, successCode,
+                                                            returnsNewObject, exceptionCode,
+                                                            typedArraysAreStructs)
             code = fill(
                 """
 
                 if (${result}.IsNull()) {
                   $*{setNull}
                 }
                 $*{recTemplate}
                 """,
@@ -5087,17 +5076,17 @@ def getWrapTemplateForType(type, descrip
                 else:
                     wrapMethod = "WrapNewBindingNonWrapperCachedObject"
             wrap = "%s(cx, ${obj}, %s, ${jsvalHandle})" % (wrapMethod, result)
             if not descriptor.hasXPConnectImpls:
                 # Can only fail to wrap as a new-binding object
                 # if they already threw an exception.
                 #XXX Assertion disabled for now, see bug 991271.
                 failed = ("MOZ_ASSERT(true || JS_IsExceptionPending(cx));\n" +
-                          "%s" % exceptionCode)
+                          exceptionCode)
             else:
                 if descriptor.notflattened:
                     raise TypeError("%s has XPConnect impls but not flattened; "
                                     "fallback won't work correctly" %
                                     descriptor.interface.identifier.name)
                 # Try old-style wrapping for bindings which might be XPConnect impls.
                 failed = wrapAndSetPtr("HandleNewBindingWrappingFailure(cx, ${obj}, %s, ${jsvalHandle})" % result)
         else:
@@ -5187,20 +5176,20 @@ def getWrapTemplateForType(type, descrip
         return (setter(toValue % result, wrapAsType=type), False)
 
     if not (type.isUnion() or type.isPrimitive() or type.isDictionary() or
             type.isDate() or
             (type.isSpiderMonkeyInterface() and typedArraysAreStructs)):
         raise TypeError("Need to learn to wrap %s" % type)
 
     if type.nullable():
-        (recTemplate, recInfal) = getWrapTemplateForType(type.inner, descriptorProvider,
-                                                         "%s.Value()" % result, successCode,
-                                                         returnsNewObject, exceptionCode,
-                                                         typedArraysAreStructs)
+        recTemplate, recInfal = getWrapTemplateForType(type.inner, descriptorProvider,
+                                                       "%s.Value()" % result, successCode,
+                                                       returnsNewObject, exceptionCode,
+                                                       typedArraysAreStructs)
         return ("if (%s.IsNull()) {\n" % result +
                 indent(setNull()) +
                 "}\n" +
                 recTemplate, recInfal)
 
     if type.isSpiderMonkeyInterface():
         assert typedArraysAreStructs
         # See comments in WrapNewBindingObject explaining why we need
@@ -5411,20 +5400,20 @@ def getRetvalDeclarationForType(returnTy
     if returnType.isObject() or returnType.isSpiderMonkeyInterface():
         return CGGeneric("JSObject*"), False, None, None
     if returnType.isSequence():
         nullable = returnType.nullable()
         if nullable:
             returnType = returnType.inner
         # If our result is already addrefed, use the right type in the
         # sequence argument here.
-        (result, _, _, _) = getRetvalDeclarationForType(returnType.inner,
-                                                        descriptorProvider,
-                                                        resultAlreadyAddRefed,
-                                                        isMember="Sequence")
+        result, _, _, _ = getRetvalDeclarationForType(returnType.inner,
+                                                      descriptorProvider,
+                                                      resultAlreadyAddRefed,
+                                                      isMember="Sequence")
         # While we have our inner type, set up our rooter, if needed
         if not isMember and typeNeedsRooting(returnType):
             rooter = CGGeneric("SequenceRooter<%s > resultRooter(cx, &result);\n" %
                                result.define())
         else:
             rooter = None
         result = CGTemplatedType("nsTArray", result)
         if nullable:
@@ -5463,17 +5452,17 @@ def getRetvalDeclarationForType(returnTy
         if returnType.nullable():
             result = CGTemplatedType("Nullable", result)
         return result, False, None, None
     raise TypeError("Don't know how to declare return value for %s" %
                     returnType)
 
 
 def isResultAlreadyAddRefed(extendedAttributes):
-    return not 'resultNotAddRefed' in extendedAttributes
+    return 'resultNotAddRefed' not in extendedAttributes
 
 
 def needCx(returnType, arguments, extendedAttributes, considerTypes):
     return (considerTypes and
             (typeNeedsCx(returnType, True) or
              any(typeNeedsCx(a.type) for a in arguments)) or
             'implicitJSContext' in extendedAttributes)
 
@@ -5502,22 +5491,22 @@ class CGCallGenerator(CGThing):
                  static, object="self", argsPost=[]):
         CGThing.__init__(self)
 
         assert errorReport is None or isinstance(errorReport, CGThing)
 
         isFallible = errorReport is not None
 
         resultAlreadyAddRefed = isResultAlreadyAddRefed(extendedAttributes)
-        (result, resultOutParam, resultRooter, resultArgs) = \
+        result, resultOutParam, resultRooter, resultArgs = \
             getRetvalDeclarationForType(
                 returnType, descriptorProvider, resultAlreadyAddRefed)
 
         args = CGList([CGGeneric(arg) for arg in argsPre], ", ")
-        for (a, name) in arguments:
+        for a, name in arguments:
             arg = CGGeneric(name)
 
             # Now constify the things that need it
             def needsConst(a):
                 if a.type.isDictionary():
                     return True
                 if a.type.isSequence():
                     return True
@@ -5879,34 +5868,34 @@ class CGPerSignatureCall(CGThing):
                 # or 'object' types, or other things that we represent as actual
                 # JSAPI types, present.  Effectively, we're emulating a
                 # CrossCompartmentWrapper, but working with the C++ types, not the
                 # original list of JS::Values.
                 cgThings.append(CGGeneric("Maybe<JSAutoCompartment> ac;\n"))
                 xraySteps.append(CGGeneric("ac.construct(cx, obj);\n"))
                 xraySteps.extend(
                     wrapArgIntoCurrentCompartment(arg, argname, isMember=False)
-                    for (arg, argname) in self.getArguments())
+                    for arg, argname in self.getArguments())
 
             cgThings.append(
                 CGIfWrapper(CGList(xraySteps),
                             "objIsXray"))
 
         cgThings.append(CGCallGenerator(
             self.getErrorReport() if self.isFallible() else None,
             self.getArguments(), argsPre, returnType,
             self.extendedAttributes, descriptor, nativeMethodName,
             static, argsPost=argsPost))
         self.cgRoot = CGList(cgThings)
 
     def getArguments(self):
-        return [(a, "arg" + str(i)) for (i, a) in enumerate(self.arguments)]
+        return [(a, "arg" + str(i)) for i, a in enumerate(self.arguments)]
 
     def isFallible(self):
-        return not 'infallible' in self.extendedAttributes
+        return 'infallible' not in self.extendedAttributes
 
     def wrap_return_value(self):
         returnsNewObject = memberReturnsNewObject(self.idlNode)
         if returnsNewObject:
             # We better be returning addrefed things!
             assert(isResultAlreadyAddRefed(self.extendedAttributes) or
                    # NewObject can return raw pointers to owned objects
                    (self.returnType.isGeckoInterface() and
@@ -6099,17 +6088,17 @@ class CGMethodCall(CGThing):
                 self.cgRoot.prepend(CGGeneric(code))
             return
 
         # Need to find the right overload
         maxArgCount = method.maxArgCount
         allowedArgCounts = method.allowedArgCounts
 
         argCountCases = []
-        for (argCountIdx, argCount) in enumerate(allowedArgCounts):
+        for argCountIdx, argCount in enumerate(allowedArgCounts):
             possibleSignatures = method.signaturesForArgCount(argCount)
 
             # Try to optimize away cases when the next argCount in the list
             # will have the same code as us; if it does, we can fall through to
             # that case.
             if argCountIdx+1 < len(allowedArgCounts):
                 nextPossibleSignatures = \
                     method.signaturesForArgCount(allowedArgCounts[argCountIdx+1])
@@ -6590,17 +6579,18 @@ class CGAbstractStaticBindingMethod(CGAb
     """
     Common class to generate the JSNatives for all our static methods, getters
     and setters.  This will generate the function declaration and unwrap the
     global object.  Subclasses are expected to override the generate_code
     function to do the rest of the work.  This function should return a
     CGThing which is already properly indented.
     """
     def __init__(self, descriptor, name):
-        args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'),
+        args = [Argument('JSContext*', 'cx'),
+                Argument('unsigned', 'argc'),
                 Argument('JS::Value*', 'vp')]
         CGAbstractStaticMethod.__init__(self, descriptor, name, "bool", args)
 
     def definition_body(self):
         # Make sure that "obj" is in the same compartment as "cx", since we'll
         # later use it to wrap return values.
         unwrap = indent(dedent("""
             JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@@ -6620,17 +6610,18 @@ def MakeNativeName(name):
 class CGGenericMethod(CGAbstractBindingMethod):
     """
     A class for generating the C++ code for an IDL method.
 
     If allowCrossOriginThis is true, then this-unwrapping will first do an
     UncheckedUnwrap and after that operate on the result.
     """
     def __init__(self, descriptor, allowCrossOriginThis=False):
-        args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'),
+        args = [Argument('JSContext*', 'cx'),
+                Argument('unsigned', 'argc'),
                 Argument('JS::Value*', 'vp')]
         unwrapFailureCode = (
             'return ThrowInvalidThis(cx, args, GetInvalidThisErrorForMethod(%%(securityError)s), "%s");\n' %
             descriptor.interface.identifier.name)
         name = "genericCrossOriginMethod" if allowCrossOriginThis else "genericMethod"
         CGAbstractBindingMethod.__init__(self, descriptor, name,
                                          args,
                                          unwrapFailureCode=unwrapFailureCode,
@@ -6648,17 +6639,18 @@ class CGGenericMethod(CGAbstractBindingM
 class CGSpecializedMethod(CGAbstractStaticMethod):
     """
     A class for generating the C++ code for a specialized method that the JIT
     can call with lower overhead.
     """
     def __init__(self, descriptor, method):
         self.method = method
         name = CppKeywords.checkMethodName(method.identifier.name)
-        args = [Argument('JSContext*', 'cx'), Argument('JS::Handle<JSObject*>', 'obj'),
+        args = [Argument('JSContext*', 'cx'),
+                Argument('JS::Handle<JSObject*>', 'obj'),
                 Argument('%s*' % descriptor.nativeType, 'self'),
                 Argument('const JSJitMethodCallArgs&', 'args')]
         CGAbstractStaticMethod.__init__(self, descriptor, name, 'bool', args)
 
     def definition_body(self):
         nativeName = CGSpecializedMethod.makeNativeName(self.descriptor,
                                                         self.method)
         return CGMethodCall(nativeName, self.method.isStatic(), self.descriptor,
@@ -6736,17 +6728,18 @@ class CGJsonifierMethod(CGSpecializedMet
 
 
 class CGLegacyCallHook(CGAbstractBindingMethod):
     """
     Call hook for our object
     """
     def __init__(self, descriptor):
         self._legacycaller = descriptor.operations["LegacyCaller"]
-        args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'),
+        args = [Argument('JSContext*', 'cx'),
+                Argument('unsigned', 'argc'),
                 Argument('JS::Value*', 'vp')]
         # Our "self" is actually the callee in this case, not the thisval.
         CGAbstractBindingMethod.__init__(
             self, descriptor, LEGACYCALLER_HOOK_NAME,
             args, getThisObj="&args.callee()")
 
     def define(self):
         if not self._legacycaller:
@@ -6762,18 +6755,20 @@ class CGLegacyCallHook(CGAbstractBinding
 
 class CGNewResolveHook(CGAbstractBindingMethod):
     """
     NewResolve hook for objects with custom hooks.
     """
     def __init__(self, descriptor):
         assert descriptor.interface.getExtendedAttribute("NeedNewResolve")
 
-        args = [Argument('JSContext*', 'cx'), Argument('JS::Handle<JSObject*>', 'obj'),
-                Argument('JS::Handle<jsid>', 'id'), Argument('unsigned', 'flags'),
+        args = [Argument('JSContext*', 'cx'),
+                Argument('JS::Handle<JSObject*>', 'obj'),
+                Argument('JS::Handle<jsid>', 'id'),
+                Argument('unsigned', 'flags'),
                 Argument('JS::MutableHandle<JSObject*>', 'objp')]
         # Our "self" is actually the "obj" argument in this case, not the thisval.
         CGAbstractBindingMethod.__init__(
             self, descriptor, NEWRESOLVE_HOOK_NAME,
             args, getThisObj="", callArgs="")
 
     def generate_code(self):
         return CGGeneric(indent(dedent("""
@@ -6901,17 +6896,18 @@ class CGStaticMethod(CGAbstractStaticBin
         return CGMethodCall(nativeName, True, self.descriptor, self.method)
 
 
 class CGGenericGetter(CGAbstractBindingMethod):
     """
     A class for generating the C++ code for an IDL attribute getter.
     """
     def __init__(self, descriptor, lenientThis=False, allowCrossOriginThis=False):
-        args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'),
+        args = [Argument('JSContext*', 'cx'),
+                Argument('unsigned', 'argc'),
                 Argument('JS::Value*', 'vp')]
         if lenientThis:
             name = "genericLenientGetter"
             unwrapFailureCode = dedent("""
                 MOZ_ASSERT(!JS_IsExceptionPending(cx));
                 if (!ReportLenientThisUnwrappingFailure(cx, &args.callee())) {
                   return false;
                 }
@@ -6995,19 +6991,19 @@ class CGSpecializedGetter(CGAbstractStat
                 indent(CGGetterCall(self.attr.type, nativeName,
                                     self.descriptor, self.attr).define()))
 
     @staticmethod
     def makeNativeName(descriptor, attr):
         name = attr.identifier.name
         nativeName = MakeNativeName(descriptor.binaryNames.get(name, name))
         # resultOutParam does not depend on whether resultAlreadyAddRefed is set
-        (_, resultOutParam, _, _) = getRetvalDeclarationForType(attr.type,
-                                                                descriptor,
-                                                                False)
+        _, resultOutParam, _, _ = getRetvalDeclarationForType(attr.type,
+                                                              descriptor,
+                                                              False)
         infallible = ('infallible' in
                       descriptor.getExtendedAttributes(attr, getter=True))
         if resultOutParam or attr.type.nullable() or not infallible:
             nativeName = "Get" + nativeName
         return nativeName
 
 
 class CGStaticGetter(CGAbstractStaticBindingMethod):
@@ -7026,17 +7022,18 @@ class CGStaticGetter(CGAbstractStaticBin
                                        self.descriptor, self.attr))
 
 
 class CGGenericSetter(CGAbstractBindingMethod):
     """
     A class for generating the C++ code for an IDL attribute setter.
     """
     def __init__(self, descriptor, lenientThis=False, allowCrossOriginThis=False):
-        args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'),
+        args = [Argument('JSContext*', 'cx'),
+                Argument('unsigned', 'argc'),
                 Argument('JS::Value*', 'vp')]
         if lenientThis:
             name = "genericLenientSetter"
             unwrapFailureCode = dedent("""
                 MOZ_ASSERT(!JS_IsExceptionPending(cx));
                 if (!ReportLenientThisUnwrappingFailure(cx, &args.callee())) {
                   return false;
                 }
@@ -7962,22 +7959,22 @@ class CGUnionStruct(CGThing):
             else:
                 # BOGUS blank line in method
                 traceBody = "\n"
             methods.append(ClassMethod("TraceUnion", "void",
                                        [Argument("JSTracer*", "trc")],
                                        body=traceBody))
             if CGUnionStruct.isUnionCopyConstructible(self.type):
                 constructors.append(
-                    ClassConstructor([Argument("const %s&" % selfName,
-                                               "aOther")],
-                                     bodyInHeader=True,
-                                     visibility="public",
-                                     explicit=True,
-                                     body="*this = aOther;"))
+                    ClassConstructor(
+                        [Argument("const %s&" % selfName, "aOther")],
+                        bodyInHeader=True,
+                        visibility="public",
+                        explicit=True,
+                        body="*this = aOther;\n"))
                 methods.append(ClassMethod(
                     "operator=", "void",
                     [Argument("const %s&" % selfName, "aOther")],
                     body=CGSwitch("aOther.mType", assignmentCases).define()))
                 disallowCopyConstruction = False
             else:
                 disallowCopyConstruction = True
         else:
@@ -8226,37 +8223,32 @@ class ClassMethod(ClassItem):
             className=cgClass.getNameString(),
             name=self.name,
             args=', '.join([a.define() for a in self.args]),
             const=' const' if self.const else '',
             body=self.getBody())
 
 
 class ClassUsingDeclaration(ClassItem):
-    """"
+    """
     Used for importing a name from a base class into a CGClass
 
     baseClass is the name of the base class to import the name from
 
     name is the name to import
 
     visibility determines the visibility of the name (public,
     protected, private), defaults to public.
     """
     def __init__(self, baseClass, name, visibility='public'):
         self.baseClass = baseClass
         ClassItem.__init__(self, name, visibility)
 
     def declare(self, cgClass):
-        return string.Template(
-            "using ${baseClass}::${name};\n\n"
-        ).substitute({
-            'baseClass': self.baseClass,
-            'name': self.name
-        })
+        return "using %s::%s;\n\n" % (self.baseClass, self.name)
 
     def define(self, cgClass):
         return ''
 
 
 class ClassConstructor(ClassItem):
     """
     Used for adding a constructor to a CGClass.
@@ -8599,17 +8591,17 @@ class CGClass(CGThing):
         order = [self.enums, self.unions,
                  self.typedefs, self.members,
                  self.constructors + disallowedCopyConstructors,
                  self.destructors, self.methods]
 
         lastVisibility = self.defaultVisibility
         pieces = []
         for memberList in order:
-            (code, lastVisibility) = declareMembers(self, memberList, lastVisibility)
+            code, lastVisibility = declareMembers(self, memberList, lastVisibility)
 
             if code:
                 code = code.rstrip() + "\n"  # remove extra blank lines at the end
                 pieces.append(code)
 
         result += '\n'.join(pieces)
         result += '};\n'
         result = indent(result, len(self.indent))
@@ -8628,19 +8620,19 @@ class CGClass(CGThing):
                     itemCount += 1
             return (result, itemCount)
 
         order = [(self.members, ''), (self.constructors, '\n'),
                  (self.destructors, '\n'), (self.methods, '\n')]
 
         result = self.extradefinitions
         itemCount = 0
-        for (memberList, separator) in order:
-            (memberString, itemCount) = defineMembers(self, memberList,
-                                                      itemCount, separator)
+        for memberList, separator in order:
+            memberString, itemCount = defineMembers(self, memberList,
+                                                    itemCount, separator)
             result = result + memberString
         return result
 
 
 class CGResolveOwnProperty(CGAbstractStaticMethod):
     def __init__(self, descriptor):
         args = [Argument('JSContext*', 'cx'),
                 Argument('JS::Handle<JSObject*>', 'wrapper'),
@@ -8792,17 +8784,17 @@ class CGProxySpecialOperation(CGPerSigna
     def __init__(self, descriptor, operation, checkFound=True):
         self.checkFound = checkFound
 
         nativeName = MakeNativeName(descriptor.binaryNames.get(operation, operation))
         operation = descriptor.operations[operation]
         assert len(operation.signatures()) == 1
         signature = operation.signatures()[0]
 
-        (returnType, arguments) = signature
+        returnType, arguments = signature
 
         # We pass len(arguments) as the final argument so that the
         # CGPerSignatureCall won't do any argument conversion of its own.
         CGPerSignatureCall.__init__(self, returnType, arguments, nativeName,
                                     False, descriptor, operation,
                                     len(arguments))
 
         if operation.isSetter() or operation.isCreator():
@@ -9059,17 +9051,18 @@ class CGProxyUnwrap(CGAbstractMethod):
             MOZ_ASSERT(IsProxy(obj));
             return static_cast<${type}*>(js::GetProxyPrivate(obj).toPrivate());
             """,
             type=self.descriptor.nativeType))
 
 
 class CGDOMJSProxyHandler_getOwnPropertyDescriptor(ClassMethod):
     def __init__(self, descriptor):
-        args = [Argument('JSContext*', 'cx'), Argument('JS::Handle<JSObject*>', 'proxy'),
+        args = [Argument('JSContext*', 'cx'),
+                Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('JS::MutableHandle<JSPropertyDescriptor>', 'desc'),
                 Argument('unsigned', 'flags')]
         ClassMethod.__init__(self, "getOwnPropertyDescriptor", "bool", args,
                              virtual=True, override=True)
         self.descriptor = descriptor
 
     def getBody(self):
@@ -9119,28 +9112,28 @@ class CGDOMJSProxyHandler_getOwnProperty
                 callOnUnforgeable=CallOnUnforgeableHolder(self.descriptor, tryHolder))
         else:
             getUnforgeable = ""
 
         if indexedSetter or self.descriptor.operations['NamedSetter']:
             setOrIndexedGet += "if (flags & JSRESOLVE_ASSIGNING) {\n"
             if indexedSetter:
                 setOrIndexedGet += ("  if (IsArrayIndex(index)) {\n")
-                if not 'IndexedCreator' in self.descriptor.operations:
+                if 'IndexedCreator' not in self.descriptor.operations:
                     # FIXME need to check that this is a 'supported property
                     # index'.  But if that happens, watch out for the assumption
                     # below that the name setter always returns for
                     # IsArrayIndex(index).
                     assert False
                 setOrIndexedGet += ("    FillPropertyDescriptor(desc, proxy, JSVAL_VOID, false);\n" +
                                     "    return true;\n" +
                                     "  }\n")
             setOrIndexedGet += indent(getUnforgeable)
             if self.descriptor.operations['NamedSetter']:
-                if not 'NamedCreator' in self.descriptor.operations:
+                if 'NamedCreator' not in self.descriptor.operations:
                     # FIXME need to check that this is a 'supported property name'
                     assert False
                 create = CGGeneric("FillPropertyDescriptor(desc, proxy, JSVAL_VOID, false);\n"
                                    "return true;\n")
                 # If we have an indexed setter we've already returned
                 if (self.descriptor.supportsIndexedProperties() and
                         not indexedSetter):
                     create = CGIfWrapper(create, "!IsArrayIndex(index)")
@@ -9204,29 +9197,30 @@ class CGDOMJSProxyHandler_getOwnProperty
             return true;
             """,
             setOrIndexedGet=setOrIndexedGet,
             namedGet=namedGet)
 
 
 class CGDOMJSProxyHandler_defineProperty(ClassMethod):
     def __init__(self, descriptor):
-        args = [Argument('JSContext*', 'cx'), Argument('JS::Handle<JSObject*>', 'proxy'),
+        args = [Argument('JSContext*', 'cx'),
+                Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('JS::MutableHandle<JSPropertyDescriptor>', 'desc'),
                 Argument('bool*', 'defined')]
         ClassMethod.__init__(self, "defineProperty", "bool", args, virtual=True, override=True)
         self.descriptor = descriptor
 
     def getBody(self):
         set = ""
 
         indexedSetter = self.descriptor.operations['IndexedSetter']
         if indexedSetter:
-            if not (self.descriptor.operations['IndexedCreator'] is indexedSetter):
+            if self.descriptor.operations['IndexedCreator'] is not indexedSetter:
                 raise TypeError("Can't handle creator that's different from the setter")
             set += ("int32_t index = GetArrayIndexFromId(cx, id);\n" +
                     "if (IsArrayIndex(index)) {\n" +
                     "  *defined = true;" +  # SUPER BOGUS missing newline here
                     indent(CGProxyIndexedSetter(self.descriptor).define()) +
                     "  return true;\n" +
                     "}\n") % self.descriptor.nativeType
         elif self.descriptor.supportsIndexedProperties():
@@ -9250,17 +9244,17 @@ class CGDOMJSProxyHandler_defineProperty
                                    "}\n"
                                    "\n")  # BOGUS extra blank line at end of block or method
             set += CallOnUnforgeableHolder(self.descriptor,
                                            defineOnUnforgeable,
                                            "xpc::WrapperFactory::IsXrayWrapper(proxy)")
 
         namedSetter = self.descriptor.operations['NamedSetter']
         if namedSetter:
-            if not self.descriptor.operations['NamedCreator'] is namedSetter:
+            if self.descriptor.operations['NamedCreator'] is not namedSetter:
                 raise TypeError("Can't handle creator that's different from the setter")
             # If we support indexed properties, we won't get down here for
             # indices, so we can just do our setter unconditionally here.
             set += fill(
                 """
                 *defined = true;
                 $*{callSetter}
 
@@ -9282,29 +9276,30 @@ class CGDOMJSProxyHandler_defineProperty
                     name=self.descriptor.name)
             set += ("return mozilla::dom::DOMProxyHandler::defineProperty(%s);\n" %
                     ", ".join(a.name for a in self.args))
         return set
 
 
 class CGDOMJSProxyHandler_delete(ClassMethod):
     def __init__(self, descriptor):
-        args = [Argument('JSContext*', 'cx'), Argument('JS::Handle<JSObject*>', 'proxy'),
+        args = [Argument('JSContext*', 'cx'),
+                Argument('JS::Handle<JSObject*>', 'proxy'),
                 Argument('JS::Handle<jsid>', 'id'),
                 Argument('bool*', 'bp')]
         ClassMethod.__init__(self, "delete_", "bool", args,
                              virtual=True, override=True)
         self.descriptor = descriptor
 
     def getBody(self):
         def getDeleterBody(type):
             """
             type should be "Named" or "Indexed"
             """
-            assert type is "Named" or type is "Indexed"
+            assert type in ("Named", "Indexed")
             deleter = self.descriptor.operations[type + 'Deleter']
             if deleter:
                 if (not deleter.signatures()[0][0].isPrimitive() or
                     deleter.signatures()[0][0].nullable() or
                     deleter.signatures()[0][0].tag() != IDLType.Tags.bool):
                     setBp = "*bp = true;\n"
                 else:
                     setBp = dedent("""
@@ -9645,17 +9640,18 @@ class CGDOMJSProxyHandler_get(ClassMetho
             return true;
             """,
             indexedOrExpando=getIndexedOrExpando,
             named=getNamed)
 
 
 class CGDOMJSProxyHandler_className(ClassMethod):
     def __init__(self, descriptor):
-        args = [Argument('JSContext*', 'cx'), Argument('JS::Handle<JSObject*>', 'proxy')]
+        args = [Argument('JSContext*', 'cx'),
+                Argument('JS::Handle<JSObject*>', 'proxy')]
         ClassMethod.__init__(self, "className", "const char*", args,
                              virtual=True, override=True)
         self.descriptor = descriptor
 
     def getBody(self):
         return 'return "%s";\n' % self.descriptor.name
 
 
@@ -9673,17 +9669,17 @@ class CGDOMJSProxyHandler_finalizeInBack
 class CGDOMJSProxyHandler_finalize(ClassMethod):
     def __init__(self, descriptor):
         args = [Argument('JSFreeOp*', 'fop'), Argument('JSObject*', 'proxy')]
         ClassMethod.__init__(self, "finalize", "void", args,
                              virtual=True, override=True)
         self.descriptor = descriptor
 
     def getBody(self):
-        return ("%s self = UnwrapProxy(proxy);\n\n" % (self.descriptor.nativeType + "*") +
+        return ("%s* self = UnwrapProxy(proxy);\n\n" % self.descriptor.nativeType +
                 finalizeHook(self.descriptor, FINALIZE_HOOK_NAME, self.args[0].name).define())
 
 
 class CGDOMJSProxyHandler_slice(ClassMethod):
     def __init__(self, descriptor):
         assert descriptor.supportsIndexedProperties()
 
         args = [Argument('JSContext*', 'cx'),
@@ -9800,19 +9796,17 @@ class CGDOMJSProxyHandlerDefiner(CGThing
 
     def define(self):
         return self.handlerThing.define()
 
 
 def stripTrailingWhitespace(text):
     tail = '\n' if text.endswith('\n') else ''
     lines = text.splitlines()
-    for i in range(len(lines)):
-        lines[i] = lines[i].rstrip()
-    return '\n'.join(lines) + tail
+    return '\n'.join(line.rstrip() for line in lines) + tail
 
 
 class CGDescriptor(CGThing):
     def __init__(self, descriptor):
         CGThing.__init__(self)
 
         assert not descriptor.concrete or descriptor.interface.hasInterfacePrototypeObject()
 
@@ -10336,17 +10330,17 @@ class CGDictionary(CGThing):
         ], body=body)
 
     def assignmentOperator(self):
         body = CGList([])
         if self.dictionary.parent:
             body.append(CGGeneric(
                 "%s::operator=(aOther);\n" %
                 self.makeClassName(self.dictionary.parent)))
-        for (m, _) in self.memberInfo:
+        for m, _ in self.memberInfo:
             memberName = self.makeMemberName(m.identifier.name)
             if not m.defaultValue:
                 memberAssign = CGGeneric(fill(
                     """
                     if (aOther.${name}.WasPassed()) {
                       ${name}.Construct();
                       ${name}.Value() = aOther.${name}.Value();
                     } else {
@@ -10432,17 +10426,17 @@ class CGDictionary(CGThing):
             body="// Doesn't matter what int we pass to the parent constructor\n")
 
         fastStruct = CGClass("Fast" + selfName,
                              bases=[ClassBase(selfName)],
                              constructors=[fastDictionaryCtor],
                              isStruct=True)
 
         return CGList([struct,
-                       CGNamespace.build(['binding_detail'], fastStruct)],
+                       CGNamespace('binding_detail', fastStruct)],
                       "\n")
 
     def deps(self):
         return self.dictionary.getDeps()
 
     @staticmethod
     def makeDictionaryName(dictionary):
         return dictionary.identifier.name
@@ -10450,26 +10444,26 @@ class CGDictionary(CGThing):
     def makeClassName(self, dictionary):
         return self.makeDictionaryName(dictionary)
 
     @staticmethod
     def makeMemberName(name):
         return "m" + name[0].upper() + name[1:]
 
     def getMemberType(self, memberInfo):
-        (_, conversionInfo) = memberInfo
+        _, conversionInfo = memberInfo
         # We can't handle having a holderType here
         assert conversionInfo.holderType is None
         declType = conversionInfo.declType
         if conversionInfo.dealWithOptional:
             declType = CGTemplatedType("Optional", declType)
         return declType.define()
 
     def getMemberConversion(self, memberInfo):
-        (member, conversionInfo) = memberInfo
+        member, conversionInfo = memberInfo
         replacements = {
             "val": "temp.ref()",
             "mutableVal": "&temp.ref()",
             "declName": self.makeMemberName(member.identifier.name),
             # We need a holder name for external interfaces, but
             # it's scoped down to the conversion so we can just use
             # anything we want.
             "holderName": "holder"
@@ -10615,17 +10609,17 @@ class CGDictionary(CGThing):
         return trace.define()
 
     def getMemberInitializer(self, memberInfo):
         """
         Get the right initializer for the member.  Most members don't need one,
         but we need to pre-initialize 'any' and 'object' that have a default
         value, so they're safe to trace at all times.
         """
-        (member, _) = memberInfo
+        member, _ = memberInfo
         if not member.defaultValue:
             # No default value means no need to set it up front, since it's
             # inside an Optional and won't get traced until it's actually set
             # up.
             return None
         type = member.type
         if type.isAny():
             return "JS::UndefinedValue()"
@@ -10748,29 +10742,29 @@ class ForwardDeclarationBuilder:
     def __init__(self):
         """
         The set of declarations is represented as a tree of nested namespaces.
         Each tree node has a set of declarations |decls| and a dict |children|.
         Each declaration is a pair consisting of the class name and a boolean
         that is true iff the class is really a struct. |children| maps the
         names of inner namespaces to the declarations in that namespace.
         """
-        self.decls = set([])
+        self.decls = set()
         self.children = {}
 
     def _listAdd(self, namespaces, name, isStruct=False):
         """
         Add a forward declaration, where |namespaces| is a list of namespaces.
         |name| should not contain any other namespaces.
         """
         if namespaces:
             child = self.children.setdefault(namespaces[0], ForwardDeclarationBuilder())
             child._listAdd(namespaces[1:], name, isStruct)
         else:
-            assert not '::' in name
+            assert '::' not in name
             self.decls.add((name, isStruct))
 
     def addInMozillaDom(self, name, isStruct=False):
         """
         Add a forward declaration to the mozilla::dom:: namespace. |name| should not
         contain any other namespaces.
         """
         self._listAdd(["mozilla", "dom"], name, isStruct)
@@ -10785,21 +10779,21 @@ class ForwardDeclarationBuilder:
 
     def _build(self, atTopLevel):
         """
         Return a codegenerator for the forward declarations.
         """
         decls = []
         if self.decls:
             decls.append(CGList([CGClassForwardDeclare(cname, isStruct)
-                                 for (cname, isStruct) in sorted(self.decls)]))
+                                 for cname, isStruct in sorted(self.decls)]))
         for namespace, child in sorted(self.children.iteritems()):
             decls.append(CGNamespace(namespace, child._build(atTopLevel=False), declareOnly=True))
 
-        cg = CGList(decls, joiner='\n')
+        cg = CGList(decls, "\n")
         if not atTopLevel and len(decls) + len(self.decls) > 1:
             cg = CGWrapper(cg, pre='\n', post='\n')
         return cg
 
     def build(self):
         return self._build(atTopLevel=True)
 
 
@@ -10936,17 +10930,17 @@ class CGBindingRoot(CGThing):
                                     dictionaries,
                                     mainCallbacks + workerCallbacks))))
 
         bindingHeaders["nsDOMQS.h"] = any(d.hasXPConnectImpls for d in descriptors)
         # Only mainthread things can have hasXPConnectImpls
         provider = config.getDescriptorProvider(False)
 
         def checkForXPConnectImpls(typeInfo):
-            (type, _, _) = typeInfo
+            type, _, _ = typeInfo
             type = type.unroll()
             if not type.isInterface() or not type.isGeckoInterface():
                 return False
             try:
                 typeDesc = provider.getDescriptor(type.inner.identifier.name)
             except NoSuchDescriptorError:
                 return False
             return typeDesc.hasXPConnectImpls
@@ -11017,18 +11011,19 @@ class CGBindingRoot(CGThing):
         curr = CGList([CGForwardDeclarations(config, descriptors,
                                              mainCallbacks, workerCallbacks,
                                              dictionaries,
                                              callbackDescriptors + jsImplemented),
                        curr],
                       "\n")
 
         # Add header includes.
-        bindingHeaders = [header for (header, include) in
-                          bindingHeaders.iteritems() if include]
+        bindingHeaders = [header
+                          for header, include in bindingHeaders.iteritems()
+                          if include]
         declareIncludes = [
             'mozilla/dom/BindingDeclarations.h',
             'mozilla/dom/Nullable.h',
             'mozilla/ErrorResult.h',
             'jspubtd.h',
             'js/RootingAPI.h',
         ]
         if jsImplemented:
@@ -11257,17 +11252,17 @@ class CGNativeMember(ClassMethod):
             if nullable:
                 dictType = CGTemplatedType("Nullable", dictType)
             args.append(Argument("%s&" % dictType.define(), "aRetVal"))
         elif returnType.isUnion():
             args.append(Argument("%s&" %
                                  CGUnionStruct.unionTypeDecl(returnType, True),
                                  "aRetVal"))
         # And the ErrorResult
-        if not 'infallible' in self.extendedAttrs:
+        if 'infallible' not in self.extendedAttrs:
             # Use aRv so it won't conflict with local vars named "rv"
             args.append(Argument("ErrorResult&", "aRv"))
         # The legacycaller thisval
         if self.member.isMethod() and self.member.isLegacycaller():
             # If it has an identifier, we can't deal with it yet
             assert self.member.isIdentifierLess()
             args.insert(0, Argument("JS::Value", "aThisVal"))
         # And jscontext bits.
@@ -11396,18 +11391,17 @@ class CGNativeMember(ClassMethod):
 
     def getArgType(self, type, optional, isMember):
         """
         Get the type of an argument declaration.  Returns the type CGThing, and
         whether this should be a const ref.
 
         isMember can be False, "Sequence", or "Variadic"
         """
-        (decl, ref, handleNullable) = self.doGetArgType(type, optional,
-                                                        isMember)
+        decl, ref, handleNullable = self.doGetArgType(type, optional, isMember)
         decl = CGGeneric(decl)
         if handleNullable and type.nullable():
             decl = CGTemplatedType("Nullable", decl)
             ref = True
         if isMember == "Variadic":
             arrayType = "Sequence" if self.variadicIsSequence else "nsTArray"
             decl = CGTemplatedType(arrayType, decl)
             ref = True
@@ -11417,19 +11411,19 @@ class CGNativeMember(ClassMethod):
             decl = CGTemplatedType("Optional", decl)
             ref = True
         return (decl, ref)
 
     def getArg(self, arg):
         """
         Get the full argument declaration for an argument
         """
-        (decl, ref) = self.getArgType(arg.type,
-                                      arg.optional and not arg.defaultValue,
-                                      "Variadic" if arg.variadic else False)
+        decl, ref = self.getArgType(arg.type,
+                                    arg.optional and not arg.defaultValue,
+                                    "Variadic" if arg.variadic else False)
         if ref:
             decl = CGWrapper(decl, pre="const ", post="&")
 
         return Argument(decl.define(), arg.identifier.name)
 
 
 class CGExampleMethod(CGNativeMember):
     def __init__(self, descriptor, method, signature, isConstructor, breakAfter=True):
@@ -11486,17 +11480,17 @@ class CGBindingImplClass(CGClass):
 
         iface = descriptor.interface
 
         self.methodDecls = []
 
         def appendMethod(m, isConstructor=False):
             sigs = m.signatures()
             for s in sigs[:-1]:
-                # Don't put an empty line after overloads, until we
+                # Don't put a blank line after overloads, until we
                 # get to the last one.
                 self.methodDecls.append(cgMethod(descriptor, m, s,
                                                  isConstructor,
                                                  breakAfter=False))
             self.methodDecls.append(cgMethod(descriptor, m, sigs[-1],
                                              isConstructor))
 
         if iface.ctor():
@@ -11516,17 +11510,17 @@ class CGBindingImplClass(CGClass):
         # Now do the special operations
         def appendSpecialOperation(name, op):
             if op is None:
                 return
             if name == "IndexedCreator" or name == "NamedCreator":
                 # These are identical to the setters
                 return
             assert len(op.signatures()) == 1
-            (returnType, args) = op.signatures()[0]
+            returnType, args = op.signatures()[0]
             # Make a copy of the args, since we plan to modify them.
             args = list(args)
             if op.isGetter() or op.isDeleter():
                 # This is a total hack.  The '&' belongs with the
                 # type, not the name!  But it works, and is simpler
                 # than trying to somehow make this pretty.
                 args.append(FakeArgument(BuiltinTypes[IDLBuiltinType.Types.boolean],
                                          op, name="&found"))
@@ -11550,17 +11544,17 @@ class CGBindingImplClass(CGClass):
             self.methodDecls.append(
                 CGNativeMember(descriptor, op,
                                name,
                                (returnType, args),
                                descriptor.getExtendedAttributes(op)))
         # Sort things by name so we get stable ordering in the output.
         ops = descriptor.operations.items()
         ops.sort(key=lambda x: x[0])
-        for (name, op) in ops:
+        for name, op in ops:
             appendSpecialOperation(name, op)
         # If we support indexed properties, then we need a Length()
         # method so we know which indices are supported.
         if descriptor.supportsIndexedProperties():
             # But we don't need it if we already have an infallible
             # "length" attribute, which we often do.
             haveLengthAttr = any(
                 m for m in iface.members if m.isAttr() and
@@ -12443,18 +12437,18 @@ class CallbackMember(CGNativeMember):
         if assignRetval == "":
             assignRetval = "\n"  # BOGUS extra blank line
         return type + assignRetval
 
     def getArgConversions(self):
         # Just reget the arglist from self.originalSig, because our superclasses
         # just have way to many members they like to clobber, so I can't find a
         # safe member name to store it in.
-        argConversions = [self.getArgConversion(i, arg) for (i, arg)
-                          in enumerate(self.originalSig[1])]
+        argConversions = [self.getArgConversion(i, arg)
+                          for i, arg in enumerate(self.originalSig[1])]
         if not argConversions:
             return "\n\n"  # BOGUS extra blank line
 
         # Do them back to front, so our argc modifications will work
         # correctly, because we examine trailing arguments first.
         argConversions.reverse()
         # Wrap each one in a scope so that any locals it has don't leak out, and
         # also so that we can just "break;" for our successCode.
@@ -12837,18 +12831,18 @@ class GlobalGenRoots():
             structName = dict.identifier.name + "Atoms"
             structs.append((structName,
                             CGWrapper(CGClass(structName,
                                               bases=None,
                                               isStruct=True,
                                               members=classMembers), post='\n')))
 
         structs.sort()
-        generatedStructs = [struct for (structName, struct) in structs]
-        structNames = [structName for (structName, struct) in structs]
+        generatedStructs = [struct for structName, struct in structs]
+        structNames = [structName for structName, struct in structs]
 
         mainStruct = CGWrapper(CGClass("PerThreadAtomCache",
                                        bases=[ClassBase(structName) for structName in structNames],
                                        isStruct=True),
                                post='\n')
 
         structs = CGList(generatedStructs + [mainStruct])
 
@@ -13006,17 +13000,17 @@ class GlobalGenRoots():
 
         # Wrap all of that in our namespaces.
         curr = CGNamespace.build(['mozilla', 'dom'], unions)
 
         curr = CGWrapper(curr, post='\n')
 
         namespaces = []
         stack = [CGList([])]
-        for (clazz, isStruct) in SortedTuples(declarations):
+        for clazz, isStruct in sorted(declarations):
             elements = clazz.split("::")
             clazz = CGClassForwardDeclare(elements.pop(), isStruct=isStruct)
             i = 0
             if len(elements) > 0:
                 common = min(len(namespaces), len(elements))
                 while i < common and namespaces[i] == elements[i]:
                     i += 1
 
@@ -13045,20 +13039,20 @@ class GlobalGenRoots():
         curr = CGIncludeGuard('UnionTypes', curr)
 
         # Done.
         return curr
 
     @staticmethod
     def UnionConversions(config):
 
-        (headers, unions) = UnionConversions(config.getDescriptors(),
-                                             config.getDictionaries(),
-                                             config.getCallbacks(),
-                                             config)
+        headers, unions = UnionConversions(config.getDescriptors(),
+                                           config.getDictionaries(),
+                                           config.getCallbacks(),
+                                           config)
 
         # Wrap all of that in our namespaces.
         curr = CGNamespace.build(['mozilla', 'dom'], unions)
 
         curr = CGWrapper(curr, post='\n')
 
         headers.update(["nsDebug.h", "mozilla/dom/UnionTypes.h"])
         curr = CGHeaders([], [], [], [], headers, [], 'UnionConversions', curr)
@@ -13078,17 +13072,17 @@ class CGEventGetter(CGNativeMember):
         CGNativeMember.__init__(self, descriptor, attr,
                                 CGSpecializedGetter.makeNativeName(descriptor,
                                                                    attr),
                                 (attr.type, []),
                                 ea)
         self.body = self.getMethodBody()
 
     def getArgs(self, returnType, argList):
-        if not 'infallible' in self.extendedAttrs:
+        if 'infallible' not in self.extendedAttrs:
             raise TypeError("Event code generator does not support [Throws]!")
         if not self.member.isAttr():
             raise TypeError("Event code generator does not support methods")
         if self.member.isStatic():
             raise TypeError("Event code generators does not support static attributes")
         return CGNativeMember.getArgs(self, returnType, argList)
 
     def getMethodBody(self):
@@ -13150,19 +13144,19 @@ class CGEventMethod(CGNativeMember):
                                 variadicIsSequence=True)
         self.originalArgs = list(self.args)
 
     def getArgs(self, returnType, argList):
         args = [self.getArg(arg) for arg in argList]
         return args
 
     def getArg(self, arg):
-        (decl, ref) = self.getArgType(arg.type,
-                                      arg.optional and not arg.defaultValue,
-                                      "Variadic" if arg.variadic else False)
+        decl, ref = self.getArgType(arg.type,
+                                    arg.optional and not arg.defaultValue,
+                                    "Variadic" if arg.variadic else False)
         if ref:
             decl = CGWrapper(decl, pre="const ", post="&")
 
         name = arg.identifier.name
         name = "a" + name[0].upper() + name[1:]
         return Argument(decl.define(), name)
 
     def declare(self, cgClass):