CodeGeneratorJS.pm   [plain text]


#
# Copyright (C) 2005, 2006, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
# Copyright (C) 2006 Anders Carlsson <andersca@mac.com>
# Copyright (C) 2006, 2007 Samuel Weinig <sam@webkit.org>
# Copyright (C) 2006 Alexey Proskuryakov <ap@webkit.org>
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
# Copyright (C) 2009 Cameron McCormack <cam@mcc.id.au>
# Copyright (C) Research In Motion Limited 2010. All rights reserved.
# Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
# Copyright (C) 2011 Patrick Gansterer <paroga@webkit.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with this library; see the file COPYING.LIB.  If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.

package CodeGeneratorJS;

use strict;

use constant FileNamePrefix => "JS";

my $codeGenerator;

my $module = "";
my $outputDir = "";
my $writeDependencies = 0;

my @headerContentHeader = ();
my @headerContent = ();
my %headerIncludes = ();
my %headerTrailingIncludes = ();

my @implContentHeader = ();
my @implContent = ();
my %implIncludes = ();
my @depsContent = ();
my $numCachedAttributes = 0;
my $currentCachedAttribute = 0;

# Default .h template
my $headerTemplate = << "EOF";
/*
    This file is part of the WebKit open source project.
    This file has been generated by generate-bindings.pl. DO NOT MODIFY!

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/
EOF

# Default constructor
sub new
{
    my $object = shift;
    my $reference = { };

    $codeGenerator = shift;
    $outputDir = shift;
    shift; # $outputHeadersDir
    shift; # $useLayerOnTop
    shift; # $preprocessor
    $writeDependencies = shift;

    bless($reference, $object);
    return $reference;
}

sub leftShift($$) {
    my ($value, $distance) = @_;
    return (($value << $distance) & 0xFFFFFFFF);
}

# Params: 'domClass' struct
sub GenerateInterface
{
    my $object = shift;
    my $dataNode = shift;
    my $defines = shift;

    $codeGenerator->LinkOverloadedFunctions($dataNode);

    # Start actual generation
    if ($dataNode->extendedAttributes->{"Callback"}) {
        $object->GenerateCallbackHeader($dataNode);
        $object->GenerateCallbackImplementation($dataNode);
    } else {
        $object->GenerateHeader($dataNode);
        $object->GenerateImplementation($dataNode);
    }

    $object->WriteData($dataNode);
}

sub GenerateAttributeEventListenerCall
{
    my $className = shift;
    my $implSetterFunctionName = shift;
    my $windowEventListener = shift;

    my $wrapperObject = $windowEventListener ? "globalObject" : "thisObject";
    my @GenerateEventListenerImpl = ();

    if ($className eq "JSSVGElementInstance") {
        # SVGElementInstances have to create JSEventListeners with the wrapper equal to the correspondingElement
        $wrapperObject = "asObject(correspondingElementWrapper)";

        push(@GenerateEventListenerImpl, <<END);
    JSValue correspondingElementWrapper = toJS(exec, castedThis->globalObject(), impl->correspondingElement());
    if (correspondingElementWrapper.isObject())
END

        # Add leading whitespace to format the impl->set... line correctly
        push(@GenerateEventListenerImpl, "    ");
    }

    push(@GenerateEventListenerImpl, "    impl->set$implSetterFunctionName(createJSAttributeEventListener(exec, value, $wrapperObject));\n");
    return @GenerateEventListenerImpl;
}

sub GenerateEventListenerCall
{
    my $className = shift;
    my $functionName = shift;
    my $passRefPtrHandling = ($functionName eq "add") ? "" : ".get()";

    $implIncludes{"JSEventListener.h"} = 1;

    my @GenerateEventListenerImpl = ();
    my $wrapperObject = "castedThis";
    if ($className eq "JSSVGElementInstance") {
        # SVGElementInstances have to create JSEventListeners with the wrapper equal to the correspondingElement
        $wrapperObject = "asObject(correspondingElementWrapper)";

        push(@GenerateEventListenerImpl, <<END);
    JSValue correspondingElementWrapper = toJS(exec, castedThis->globalObject(), impl->correspondingElement());
    if (!correspondingElementWrapper.isObject())
        return JSValue::encode(jsUndefined());
END
    }

    push(@GenerateEventListenerImpl, <<END);
    JSValue listener = exec->argument(1);
    if (!listener.isObject())
        return JSValue::encode(jsUndefined());
    impl->${functionName}EventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), $wrapperObject, false, currentWorld(exec))$passRefPtrHandling, exec->argument(2).toBoolean(exec));
    return JSValue::encode(jsUndefined());
END
    return @GenerateEventListenerImpl;
}

# Params: 'idlDocument' struct
sub GenerateModule
{
    my $object = shift;
    my $dataNode = shift;

    $module = $dataNode->module;
}

sub GetParentClassName
{
    my $dataNode = shift;

    return $dataNode->extendedAttributes->{"JSLegacyParent"} if $dataNode->extendedAttributes->{"JSLegacyParent"};
    return "JSDOMWrapper" if (@{$dataNode->parents} eq 0);
    return "JS" . $codeGenerator->StripModule($dataNode->parents(0));
}

sub GetCallbackClassName
{
    my $className = shift;

    return "JSCustomVoidCallback" if $className eq "VoidCallback";
    return "JS$className";
}

sub IndexGetterReturnsStrings
{
    my $type = shift;

    return 1 if $type eq "CSSStyleDeclaration" or $type eq "MediaList" or $type eq "DOMStringList" or $type eq "DOMTokenList" or $type eq "DOMSettableTokenList";
    return 0;
}

sub AddIncludesForTypeInImpl
{
    my $type = $codeGenerator->StripModule(shift);
    my $isCallback = @_ ? shift : 0;
    
    AddIncludesForType($type, $isCallback, \%implIncludes);
    
    # additional includes (things needed to compile the bindings but not the header)
    if ($type eq "CanvasRenderingContext2D") {
        $implIncludes{"CanvasGradient.h"} = 1;
        $implIncludes{"CanvasPattern.h"} = 1;
        $implIncludes{"CanvasStyle.h"} = 1;
    }

    if ($type eq "CanvasGradient" or $type eq "XPathNSResolver" or $type eq "MessagePort") {
        $implIncludes{"PlatformString.h"} = 1;
    }

    if ($type eq "Document") {
        $implIncludes{"NodeFilter.h"} = 1;
    }

    if ($type eq "MediaQueryListListener") {
        $implIncludes{"MediaQueryListListener.h"} = 1;
    }
}

sub AddIncludesForTypeInHeader
{
    my $type = $codeGenerator->StripModule(shift);
    my $isCallback = @_ ? shift : 0;
    
    AddIncludesForType($type, $isCallback, \%headerIncludes);
}

sub AddIncludesForType
{
    my $type = shift;
    my $isCallback = shift;
    my $includesRef = shift;

    # When we're finished with the one-file-per-class
    # reorganization, we won't need these special cases.
    if ($codeGenerator->IsPrimitiveType($type) or $codeGenerator->SkipIncludeHeader($type)
        or $type eq "DOMString" or $type eq "DOMObject" or $type eq "Array" or $type eq "DOMTimeStamp") {
    } elsif ($type =~ /SVGPathSeg/) {
        my $joinedName = $type;
        $joinedName =~ s/Abs|Rel//;
        $includesRef->{"${joinedName}.h"} = 1;
    } elsif ($type eq "XPathNSResolver") {
        $includesRef->{"JSXPathNSResolver.h"} = 1;
        $includesRef->{"JSCustomXPathNSResolver.h"} = 1;
    } elsif ($type eq "DOMString[]") {
        # FIXME: Add proper support for T[], T[]?, sequence<T>
        $includesRef->{"JSDOMStringList.h"} = 1;
    } elsif ($type eq "unsigned long[]") {
        $includesRef->{"<wtf/Vector.h>"} = 1;
    } elsif ($isCallback) {
        $includesRef->{"JS${type}.h"} = 1;
    } elsif (IsTypedArrayType($type)) {
        $includesRef->{"<wtf/${type}.h>"} = 1;
    } elsif ($codeGenerator->GetArrayType($type)) {
    } else {
        # default, include the same named file
        $includesRef->{"${type}.h"} = 1;
    }
}

# FIXME: This method will go away once all SVG animated properties are converted to the new scheme.
sub AddIncludesForSVGAnimatedType
{
    my $type = shift;
    $type =~ s/SVGAnimated//;

    if ($type eq "Point" or $type eq "Rect") {
        $implIncludes{"Float$type.h"} = 1;
    } elsif ($type eq "String") {
        $implIncludes{"PlatformString.h"} = 1;
    }
}

sub AddToImplIncludes
{
    my $header = shift;
    my $conditional = shift;

    if (not $conditional) {
        $implIncludes{$header} = 1;
    } elsif (not exists($implIncludes{$header})) {
        $implIncludes{$header} = $conditional;
    } else {
        my $oldValue = $implIncludes{$header};
        if ($oldValue ne 1) {
            my %newValue = ();
            $newValue{$conditional} = 1;
            foreach my $condition (split(/\|/, $oldValue)) {
                $newValue{$condition} = 1;
            }
            $implIncludes{$header} = join("|", sort keys %newValue);
        }
    }
}

sub IsScriptProfileType
{
    my $type = shift;
    return 1 if ($type eq "ScriptProfileNode");
    return 0;
}

sub IsTypedArrayType
{
    my $type = shift;
    return 1 if (($type eq "ArrayBuffer") or ($type eq "ArrayBufferView"));
    return 1 if (($type eq "Uint8Array") or ($type eq "Uint8ClampedArray") or ($type eq "Uint16Array") or ($type eq "Uint32Array"));
    return 1 if (($type eq "Int8Array") or ($type eq "Int16Array") or ($type eq "Int32Array"));
    return 1 if (($type eq "Float32Array") or ($type eq "Float64Array"));
    return 0;
}

sub AddTypedefForScriptProfileType
{
    my $type = shift;
    (my $jscType = $type) =~ s/Script//;

    push(@headerContent, "typedef JSC::$jscType $type;\n\n");
}

sub AddClassForwardIfNeeded
{
    my $implClassName = shift;

    # SVGAnimatedLength/Number/etc. are typedefs to SVGAnimatedTemplate, so don't use class forwards for them!
    unless ($codeGenerator->IsSVGAnimatedType($implClassName) or IsScriptProfileType($implClassName) or IsTypedArrayType($implClassName)) {
        push(@headerContent, "class $implClassName;\n\n");
    # ScriptProfile and ScriptProfileNode are typedefs to JSC::Profile and JSC::ProfileNode.
    } elsif (IsScriptProfileType($implClassName)) {
        $headerIncludes{"<profiler/ProfileNode.h>"} = 1;
        AddTypedefForScriptProfileType($implClassName);
    }
}

sub HashValueForClassAndName
{
    my $class = shift;
    my $name = shift;

    # SVG Filter enums live in WebCore namespace (platform/graphics/)
    if ($class =~ /^SVGFE*/ or $class =~ /^SVGComponentTransferFunctionElement$/) {
        return "WebCore::$name";
    }

    return "${class}::$name";
}

sub hashTableAccessor
{
    my $noStaticTables = shift;
    my $className = shift;
    if ($noStaticTables) {
        return "get${className}Table(exec)";
    } else {
        return "&${className}Table";
    }
}

sub prototypeHashTableAccessor
{
    my $noStaticTables = shift;
    my $className = shift;
    if ($noStaticTables) {
        return "get${className}PrototypeTable(exec)";
    } else {
        return "&${className}PrototypeTable";
    }
}

sub GenerateGetOwnPropertySlotBody
{
    my ($dataNode, $interfaceName, $className, $implClassName, $hasAttributes, $inlined) = @_;

    my $namespaceMaybe = ($inlined ? "JSC::" : "");

    my @getOwnPropertySlotImpl = ();

    if ($interfaceName eq "NamedNodeMap" or $interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection") {
        push(@getOwnPropertySlotImpl, "    ${namespaceMaybe}JSValue proto = thisObject->prototype();\n");
        push(@getOwnPropertySlotImpl, "    if (proto.isObject() && jsCast<${namespaceMaybe}JSObject*>(asObject(proto))->hasProperty(exec, propertyName))\n");
        push(@getOwnPropertySlotImpl, "        return false;\n\n");
    }

    my $manualLookupGetterGeneration = sub {
        my $requiresManualLookup = $dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NamedGetter"};
        if ($requiresManualLookup) {
            push(@getOwnPropertySlotImpl, "    const ${namespaceMaybe}HashEntry* entry = ${className}Table.entry(exec, propertyName);\n");
            push(@getOwnPropertySlotImpl, "    if (entry) {\n");
            push(@getOwnPropertySlotImpl, "        slot.setCustom(thisObject, entry->propertyGetter());\n");
            push(@getOwnPropertySlotImpl, "        return true;\n");
            push(@getOwnPropertySlotImpl, "    }\n");
        }
    };

    if (!$dataNode->extendedAttributes->{"CustomNamedGetter"}) {
        &$manualLookupGetterGeneration();
    }

    if ($dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
        push(@getOwnPropertySlotImpl, "    bool ok;\n");
        push(@getOwnPropertySlotImpl, "    unsigned index = propertyName.toUInt32(ok);\n");

        # If the item function returns a string then we let the TreatReturnedNullStringAs handle the cases
        # where the index is out of range.
        if (IndexGetterReturnsStrings($implClassName)) {
            push(@getOwnPropertySlotImpl, "    if (ok) {\n");
        } else {
            push(@getOwnPropertySlotImpl, "    if (ok && index < static_cast<$implClassName*>(thisObject->impl())->length()) {\n");
        }
        if ($dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
            push(@getOwnPropertySlotImpl, "        slot.setValue(thisObject->getByIndex(exec, index));\n");
        } else {
            push(@getOwnPropertySlotImpl, "        slot.setCustomIndex(thisObject, index, indexGetter);\n");
        }
        push(@getOwnPropertySlotImpl, "        return true;\n");
        push(@getOwnPropertySlotImpl, "    }\n");
    }

    if ($dataNode->extendedAttributes->{"NamedGetter"} || $dataNode->extendedAttributes->{"CustomNamedGetter"}) {
        push(@getOwnPropertySlotImpl, "    if (canGetItemsForName(exec, static_cast<$implClassName*>(thisObject->impl()), propertyName)) {\n");
        push(@getOwnPropertySlotImpl, "        slot.setCustom(thisObject, thisObject->nameGetter);\n");
        push(@getOwnPropertySlotImpl, "        return true;\n");
        push(@getOwnPropertySlotImpl, "    }\n");
        if ($inlined) {
            $headerIncludes{"wtf/text/AtomicString.h"} = 1;
        } else {
            $implIncludes{"wtf/text/AtomicString.h"} = 1;
        }
    }

    if ($dataNode->extendedAttributes->{"CustomNamedGetter"}) {
        &$manualLookupGetterGeneration();
    }

    if ($dataNode->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}) {
        push(@getOwnPropertySlotImpl, "    if (thisObject->getOwnPropertySlotDelegate(exec, propertyName, slot))\n");
        push(@getOwnPropertySlotImpl, "        return true;\n");
    }

    if ($hasAttributes) {
        if ($inlined) {
            die "Cannot inline if NoStaticTables is set." if ($dataNode->extendedAttributes->{"JSNoStaticTables"});
            push(@getOwnPropertySlotImpl, "    return ${namespaceMaybe}getStaticValueSlot<$className, Base>(exec, s_info.staticPropHashTable, thisObject, propertyName, slot);\n");
        } else {
            push(@getOwnPropertySlotImpl, "    return ${namespaceMaybe}getStaticValueSlot<$className, Base>(exec, " . hashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, slot);\n");
        }
    } else {
        push(@getOwnPropertySlotImpl, "    return Base::getOwnPropertySlot(thisObject, exec, propertyName, slot);\n");
    }

    return @getOwnPropertySlotImpl;
}

sub GenerateGetOwnPropertyDescriptorBody
{
    my ($dataNode, $interfaceName, $className, $implClassName, $hasAttributes, $inlined) = @_;
    
    my $namespaceMaybe = ($inlined ? "JSC::" : "");
    
    my @getOwnPropertyDescriptorImpl = ();
    if ($dataNode->extendedAttributes->{"CheckSecurity"}) {
        if ($interfaceName eq "DOMWindow") {
            push(@implContent, "    if (!thisObject->allowsAccessFrom(exec))\n");
        } else {
            push(@implContent, "    if (!shouldAllowAccessToFrame(exec, thisObject->impl()->frame()))\n");
        }
        push(@implContent, "        return false;\n");
    }
    
    if ($interfaceName eq "NamedNodeMap" or $interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection") {
        push(@getOwnPropertyDescriptorImpl, "    ${namespaceMaybe}JSValue proto = thisObject->prototype();\n");
        push(@getOwnPropertyDescriptorImpl, "    if (proto.isObject() && jsCast<${namespaceMaybe}JSObject*>(asObject(proto))->hasProperty(exec, propertyName))\n");
        push(@getOwnPropertyDescriptorImpl, "        return false;\n\n");
    }
    
    my $manualLookupGetterGeneration = sub {
        my $requiresManualLookup = $dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NamedGetter"};
        if ($requiresManualLookup) {
            push(@getOwnPropertyDescriptorImpl, "    const ${namespaceMaybe}HashEntry* entry = ${className}Table.entry(exec, propertyName);\n");
            push(@getOwnPropertyDescriptorImpl, "    if (entry) {\n");
            push(@getOwnPropertyDescriptorImpl, "        PropertySlot slot;\n");
            push(@getOwnPropertyDescriptorImpl, "        slot.setCustom(thisObject, entry->propertyGetter());\n");
            push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(slot.getValue(exec, propertyName), entry->attributes());\n");
            push(@getOwnPropertyDescriptorImpl, "        return true;\n");
            push(@getOwnPropertyDescriptorImpl, "    }\n");
        }
    };

    if (!$dataNode->extendedAttributes->{"CustomNamedGetter"}) {
        &$manualLookupGetterGeneration();
    }

    if ($dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
        push(@getOwnPropertyDescriptorImpl, "    bool ok;\n");
        push(@getOwnPropertyDescriptorImpl, "    unsigned index = propertyName.toUInt32(ok);\n");
        push(@getOwnPropertyDescriptorImpl, "    if (ok && index < static_cast<$implClassName*>(thisObject->impl())->length()) {\n");
        if ($dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
            # Assume that if there's a setter, the index will be writable
            if ($dataNode->extendedAttributes->{"CustomIndexedSetter"}) {
                push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(thisObject->getByIndex(exec, index), ${namespaceMaybe}DontDelete);\n");
            } else {
                push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(thisObject->getByIndex(exec, index), ${namespaceMaybe}DontDelete | ${namespaceMaybe}ReadOnly);\n");
            }
        } else {
            push(@getOwnPropertyDescriptorImpl, "        ${namespaceMaybe}PropertySlot slot;\n");
            push(@getOwnPropertyDescriptorImpl, "        slot.setCustomIndex(thisObject, index, indexGetter);\n");
            # Assume that if there's a setter, the index will be writable
            if ($dataNode->extendedAttributes->{"CustomIndexedSetter"}) {
                push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(slot.getValue(exec, propertyName), ${namespaceMaybe}DontDelete);\n");
            } else {
                push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(slot.getValue(exec, propertyName), ${namespaceMaybe}DontDelete | ${namespaceMaybe}ReadOnly);\n");
            }
        }
        push(@getOwnPropertyDescriptorImpl, "        return true;\n");
        push(@getOwnPropertyDescriptorImpl, "    }\n");
    }

    if ($dataNode->extendedAttributes->{"NamedGetter"} || $dataNode->extendedAttributes->{"CustomNamedGetter"}) {
        push(@getOwnPropertyDescriptorImpl, "    if (canGetItemsForName(exec, static_cast<$implClassName*>(thisObject->impl()), propertyName)) {\n");
        push(@getOwnPropertyDescriptorImpl, "        ${namespaceMaybe}PropertySlot slot;\n");
        push(@getOwnPropertyDescriptorImpl, "        slot.setCustom(thisObject, nameGetter);\n");
        push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(slot.getValue(exec, propertyName), ReadOnly | DontDelete | DontEnum);\n");
        push(@getOwnPropertyDescriptorImpl, "        return true;\n");
        push(@getOwnPropertyDescriptorImpl, "    }\n");
        if ($inlined) {
            $headerIncludes{"wtf/text/AtomicString.h"} = 1;
        } else {
            $implIncludes{"wtf/text/AtomicString.h"} = 1;
        }
    }

    if ($dataNode->extendedAttributes->{"CustomNamedGetter"}) {
        &$manualLookupGetterGeneration();
    }

    if ($dataNode->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}) {
        push(@getOwnPropertyDescriptorImpl, "    if (thisObject->getOwnPropertyDescriptorDelegate(exec, propertyName, descriptor))\n");
        push(@getOwnPropertyDescriptorImpl, "        return true;\n");
    }

    if ($hasAttributes) {
        if ($inlined) {
            die "Cannot inline if NoStaticTables is set." if ($dataNode->extendedAttributes->{"JSNoStaticTables"});
            push(@getOwnPropertyDescriptorImpl, "    return ${namespaceMaybe}getStaticValueDescriptor<$className, Base>(exec, s_info.staticPropHashTable, thisObject, propertyName, descriptor);\n");
        } else {
            push(@getOwnPropertyDescriptorImpl, "    return ${namespaceMaybe}getStaticValueDescriptor<$className, Base>(exec, " . hashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, descriptor);\n");
        }
    } else {
        push(@getOwnPropertyDescriptorImpl, "    return Base::getOwnPropertyDescriptor(thisObject, exec, propertyName, descriptor);\n");
    }
    
    return @getOwnPropertyDescriptorImpl;
}

sub GenerateHeaderContentHeader
{
    my $dataNode = shift;
    my $className = "JS" . $dataNode->name;

    my @headerContentHeader = split("\r", $headerTemplate);

    # - Add header protection
    push(@headerContentHeader, "\n#ifndef $className" . "_h");
    push(@headerContentHeader, "\n#define $className" . "_h\n\n");

    my $conditionalString = $codeGenerator->GenerateConditionalString($dataNode);
    push(@headerContentHeader, "#if ${conditionalString}\n\n") if $conditionalString;
    return @headerContentHeader;
}

sub GenerateImplementationContentHeader
{
    my $dataNode = shift;
    my $className = "JS" . $dataNode->name;

    my @implContentHeader = split("\r", $headerTemplate);

    push(@implContentHeader, "\n#include \"config.h\"\n");
    my $conditionalString = $codeGenerator->GenerateConditionalString($dataNode);
    push(@implContentHeader, "\n#if ${conditionalString}\n\n") if $conditionalString;
    push(@implContentHeader, "#include \"$className.h\"\n\n");
    return @implContentHeader;
}

my %usesToJSNewlyCreated = (
    "CDATASection" => 1,
    "Element" => 1,
    "Node" => 1,
    "Text" => 1,
    "Touch" => 1,
    "TouchList" => 1
);

sub GetAttributeGetterName
{
    my ($interfaceName, $className, $attribute) = @_;
    if ($attribute->isStatic) {
        return $codeGenerator->WK_lcfirst($className) . "Constructor" . $codeGenerator->WK_ucfirst($attribute->signature->name);
    }
    return "js" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "");
}

sub GetAttributeSetterName
{
    my ($interfaceName, $className, $attribute) = @_;
    if ($attribute->isStatic) {
        return "set" . $codeGenerator->WK_ucfirst($className) . "Constructor" . $codeGenerator->WK_ucfirst($attribute->signature->name);
    }
    return "setJS" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "");
}

sub GetFunctionName
{
    my ($className, $function) = @_;
    my $kind = $function->isStatic ? "Constructor" : "Prototype";
    return $codeGenerator->WK_lcfirst($className) . $kind . "Function" . $codeGenerator->WK_ucfirst($function->signature->name);
}

sub GenerateHeader
{
    my $object = shift;
    my $dataNode = shift;

    my $interfaceName = $dataNode->name;
    my $className = "JS$interfaceName";
    my $implClassName = $interfaceName;
    my @ancestorInterfaceNames = ();
    my %structureFlags = ();

    # We only support multiple parents with SVG (for now).
    if (@{$dataNode->parents} > 1) {
        die "A class can't have more than one parent" unless $interfaceName =~ /SVG/;
        $codeGenerator->AddMethodsConstantsAndAttributesFromParentClasses($dataNode, \@ancestorInterfaceNames);
    }

    my $hasLegacyParent = $dataNode->extendedAttributes->{"JSLegacyParent"};
    my $hasRealParent = @{$dataNode->parents} > 0;
    my $hasParent = $hasLegacyParent || $hasRealParent;
    my $parentClassName = GetParentClassName($dataNode);
    my $eventTarget = $dataNode->extendedAttributes->{"EventTarget"};
    my $needsMarkChildren = $dataNode->extendedAttributes->{"JSCustomMarkFunction"} || $dataNode->extendedAttributes->{"EventTarget"};

    # - Add default header template and header protection
    push(@headerContentHeader, GenerateHeaderContentHeader($dataNode));

    if ($hasParent) {
        $headerIncludes{"$parentClassName.h"} = 1;
    } else {
        $headerIncludes{"JSDOMBinding.h"} = 1;
        $headerIncludes{"<runtime/JSGlobalObject.h>"} = 1;
        $headerIncludes{"<runtime/ObjectPrototype.h>"} = 1;
    }

    if ($dataNode->extendedAttributes->{"CustomCall"}) {
        $headerIncludes{"<runtime/CallData.h>"} = 1;
    }

    if ($dataNode->extendedAttributes->{"JSInlineGetOwnPropertySlot"}) {
        $headerIncludes{"<runtime/Lookup.h>"} = 1;
        $headerIncludes{"<wtf/AlwaysInline.h>"} = 1;
    }

    if ($hasParent && $dataNode->extendedAttributes->{"JSGenerateToNativeObject"}) {
        if (IsTypedArrayType($implClassName)) {
            $headerIncludes{"<wtf/$implClassName.h>"} = 1;
        } else {
            $headerIncludes{"$implClassName.h"} = 1;
        }
    }
    
    $headerIncludes{"<runtime/JSObject.h>"} = 1;
    $headerIncludes{"SVGElement.h"} = 1 if $className =~ /^JSSVG/;

    my $implType = $implClassName;
    my ($svgPropertyType, $svgListPropertyType, $svgNativeType) = GetSVGPropertyTypes($implType);
    $implType = $svgNativeType if $svgNativeType;

    my $svgPropertyOrListPropertyType;
    $svgPropertyOrListPropertyType = $svgPropertyType if $svgPropertyType;
    $svgPropertyOrListPropertyType = $svgListPropertyType if $svgListPropertyType;

    my $numConstants = @{$dataNode->constants};
    my $numAttributes = @{$dataNode->attributes};
    my $numFunctions = @{$dataNode->functions};

    push(@headerContent, "\nnamespace WebCore {\n\n");

    if ($codeGenerator->IsSVGAnimatedType($implClassName)) {
        $headerIncludes{"$implClassName.h"} = 1;
    } else {
        # Implementation class forward declaration
        if ($interfaceName eq "DOMWindow" || $dataNode->extendedAttributes->{"IsWorkerContext"}) {
            AddClassForwardIfNeeded($implClassName) unless $svgPropertyOrListPropertyType;
        }
    }

    AddClassForwardIfNeeded("JSDOMWindowShell") if $interfaceName eq "DOMWindow";
    AddClassForwardIfNeeded("JSDictionary") if IsConstructorTemplate($dataNode, "Event");

    # Class declaration
    push(@headerContent, "class $className : public $parentClassName {\n");

    # Static create methods
    push(@headerContent, "public:\n");
    push(@headerContent, "    typedef $parentClassName Base;\n");
    if ($interfaceName eq "DOMWindow") {
        push(@headerContent, "    static $className* create(JSC::JSGlobalData& globalData, JSC::Structure* structure, PassRefPtr<$implType> impl, JSDOMWindowShell* windowShell)\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalData.heap)) ${className}(globalData, structure, impl, windowShell);\n");
        push(@headerContent, "        ptr->finishCreation(globalData, windowShell);\n");
        push(@headerContent, "        return ptr;\n");
        push(@headerContent, "    }\n\n");
    } elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
        push(@headerContent, "    static $className* create(JSC::JSGlobalData& globalData, JSC::Structure* structure, PassRefPtr<$implType> impl)\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalData.heap)) ${className}(globalData, structure, impl);\n");
        push(@headerContent, "        ptr->finishCreation(globalData);\n");
        push(@headerContent, "        return ptr;\n");
        push(@headerContent, "    }\n\n");
    } else {
        AddIncludesForTypeInHeader($implType) unless $svgPropertyOrListPropertyType;
        push(@headerContent, "    static $className* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<$implType> impl)\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalObject->globalData().heap)) $className(structure, globalObject, impl);\n");
        push(@headerContent, "        ptr->finishCreation(globalObject->globalData());\n");
        push(@headerContent, "        return ptr;\n");
        push(@headerContent, "    }\n\n");
    }

    # Prototype
    push(@headerContent, "    static JSC::JSObject* createPrototype(JSC::ExecState*, JSC::JSGlobalObject*);\n") unless ($dataNode->extendedAttributes->{"ExtendsDOMGlobalObject"});

    $headerTrailingIncludes{"${className}Custom.h"} = 1 if $dataNode->extendedAttributes->{"JSCustomHeader"};

    $implIncludes{"${className}Custom.h"} = 1 if !$dataNode->extendedAttributes->{"JSCustomHeader"} && ($dataNode->extendedAttributes->{"CustomPutFunction"} || $dataNode->extendedAttributes->{"CustomNamedSetter"});

    my $hasGetter = $numAttributes > 0
                 || !$dataNode->extendedAttributes->{"OmitConstructor"}
                 || $dataNode->extendedAttributes->{"IndexedGetter"}
                 || $dataNode->extendedAttributes->{"NumericIndexedGetter"}
                 || $dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}
                 || $dataNode->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}
                 || $dataNode->extendedAttributes->{"NamedGetter"}
                 || $dataNode->extendedAttributes->{"CustomNamedGetter"};

    # Getters
    if ($hasGetter) {
        push(@headerContent, "    static bool getOwnPropertySlot(JSC::JSCell*, JSC::ExecState*, const JSC::Identifier& propertyName, JSC::PropertySlot&);\n");
        push(@headerContent, "    static bool getOwnPropertyDescriptor(JSC::JSObject*, JSC::ExecState*, const JSC::Identifier& propertyName, JSC::PropertyDescriptor&);\n");
        push(@headerContent, "    static bool getOwnPropertySlotByIndex(JSC::JSCell*, JSC::ExecState*, unsigned propertyName, JSC::PropertySlot&);\n") if ($dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"}) && !$dataNode->extendedAttributes->{"CustomNamedGetter"};
        push(@headerContent, "    bool getOwnPropertySlotDelegate(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);\n") if $dataNode->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"};
        push(@headerContent, "    bool getOwnPropertyDescriptorDelegate(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);\n") if $dataNode->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"};
        $structureFlags{"JSC::OverridesGetOwnPropertySlot"} = 1;
    }

    # Check if we have any writable properties
    my $hasReadWriteProperties = 0;
    foreach (@{$dataNode->attributes}) {
        if ($_->type !~ /^readonly\ attribute$/ && !$_->isStatic) {
            $hasReadWriteProperties = 1;
        }
    }

    my $hasSetter = $hasReadWriteProperties
                 || $dataNode->extendedAttributes->{"CustomPutFunction"}
                 || $dataNode->extendedAttributes->{"CustomNamedSetter"}
                 || $dataNode->extendedAttributes->{"CustomIndexedSetter"};

    # Getters
    if ($hasSetter) {
        push(@headerContent, "    static void put(JSC::JSCell*, JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSValue, JSC::PutPropertySlot&);\n");
        push(@headerContent, "    static void putByIndex(JSC::JSCell*, JSC::ExecState*, unsigned propertyName, JSC::JSValue, bool shouldThrow);\n") if $dataNode->extendedAttributes->{"CustomIndexedSetter"};
        push(@headerContent, "    bool putDelegate(JSC::ExecState*, const JSC::Identifier&, JSC::JSValue, JSC::PutPropertySlot&);\n") if $dataNode->extendedAttributes->{"CustomNamedSetter"};
    }

    if (!$hasParent) {
        push(@headerContent, "    static void destroy(JSC::JSCell*);\n");
        push(@headerContent, "    ~${className}();\n");
    }

    # Class info
    push(@headerContent, "    static const JSC::ClassInfo s_info;\n\n");

    # Structure ID
    if ($interfaceName eq "DOMWindow") {
        $structureFlags{"JSC::ImplementsHasInstance"} = 1;
    }
    push(@headerContent, "    static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)\n");
    push(@headerContent, "    {\n");
    if ($interfaceName eq "DOMWindow" || $dataNode->extendedAttributes->{"IsWorkerContext"}) {
        push(@headerContent, "        return JSC::Structure::create(globalData, globalObject, prototype, JSC::TypeInfo(JSC::GlobalObjectType, StructureFlags), &s_info);\n");
    } else {
        push(@headerContent, "        return JSC::Structure::create(globalData, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), &s_info);\n");
    }
    push(@headerContent, "    }\n\n");

    # Custom pushEventHandlerScope function
    push(@headerContent, "    JSC::ScopeChainNode* pushEventHandlerScope(JSC::ExecState*, JSC::ScopeChainNode*) const;\n\n") if $dataNode->extendedAttributes->{"JSCustomPushEventHandlerScope"};

    # Custom call functions
    push(@headerContent, "    static JSC::CallType getCallData(JSC::JSCell*, JSC::CallData&);\n\n") if $dataNode->extendedAttributes->{"CustomCall"};

    # Custom deleteProperty function
    push(@headerContent, "    static bool deleteProperty(JSC::JSCell*, JSC::ExecState*, const JSC::Identifier&);\n") if $dataNode->extendedAttributes->{"CustomDeleteProperty"};

    # Custom getPropertyNames function exists on DOMWindow
    if ($interfaceName eq "DOMWindow") {
        push(@headerContent, "    static void getPropertyNames(JSC::JSObject*, JSC::ExecState*, JSC::PropertyNameArray&, JSC::EnumerationMode mode = JSC::ExcludeDontEnumProperties);\n");
        $structureFlags{"JSC::OverridesGetPropertyNames"} = 1;
    }

    # Custom getOwnPropertyNames function
    if ($dataNode->extendedAttributes->{"CustomEnumerateProperty"} || $dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
        push(@headerContent, "    static void getOwnPropertyNames(JSC::JSObject*, JSC::ExecState*, JSC::PropertyNameArray&, JSC::EnumerationMode mode = JSC::ExcludeDontEnumProperties);\n");
        $structureFlags{"JSC::OverridesGetPropertyNames"} = 1;       
    }

    # Custom defineOwnProperty function
    push(@headerContent, "    static bool defineOwnProperty(JSC::JSObject*, JSC::ExecState*, const JSC::Identifier& propertyName, JSC::PropertyDescriptor&, bool shouldThrow);\n") if $dataNode->extendedAttributes->{"JSCustomDefineOwnProperty"};

    # Override toBoolean to return false for objects that want to 'MasqueradesAsUndefined'.
    if ($dataNode->extendedAttributes->{"MasqueradesAsUndefined"}) {
        $structureFlags{"JSC::MasqueradesAsUndefined"} = 1;
    }

    # Constructor object getter
    push(@headerContent, "    static JSC::JSValue getConstructor(JSC::ExecState*, JSC::JSGlobalObject*);\n") if !$dataNode->extendedAttributes->{"OmitConstructor"};

    my $numCustomFunctions = 0;
    my $numCustomAttributes = 0;

    # Attribute and function enums
    if ($numAttributes > 0) {
        foreach (@{$dataNode->attributes}) {
            my $attribute = $_;
            $numCustomAttributes++ if $attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCustom"};
            $numCustomAttributes++ if ($attribute->signature->extendedAttributes->{"CustomGetter"} || $attribute->signature->extendedAttributes->{"JSCustomGetter"});
            $numCustomAttributes++ if ($attribute->signature->extendedAttributes->{"CustomSetter"} || $attribute->signature->extendedAttributes->{"JSCustomSetter"});
            if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) {
                my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
                push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
                push(@headerContent, "    JSC::WriteBarrier<JSC::Unknown> m_" . $attribute->signature->name . ";\n");
                $numCachedAttributes++;
                $needsMarkChildren = 1;
                push(@headerContent, "#endif\n") if $conditionalString;
            }
        }
    }

    # visit function
    if ($needsMarkChildren) {
        push(@headerContent, "    static void visitChildren(JSCell*, JSC::SlotVisitor&);\n\n");
        $structureFlags{"JSC::OverridesVisitChildren"} = 1;
    }

    if ($numCustomAttributes > 0) {
        push(@headerContent, "\n    // Custom attributes\n");

        foreach my $attribute (@{$dataNode->attributes}) {
            my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
            if ($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCustom"} || $attribute->signature->extendedAttributes->{"CustomGetter"} || $attribute->signature->extendedAttributes->{"JSCustomGetter"}) {
                push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
                my $methodName = $codeGenerator->WK_lcfirst($attribute->signature->name);
                push(@headerContent, "    JSC::JSValue " . $methodName . "(JSC::ExecState*) const;\n");
                push(@headerContent, "#endif\n") if $conditionalString;
            }
            if (($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCustom"} || $attribute->signature->extendedAttributes->{"CustomSetter"} || $attribute->signature->extendedAttributes->{"JSCustomSetter"}) && $attribute->type !~ /^readonly/) {
                push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
                push(@headerContent, "    void set" . $codeGenerator->WK_ucfirst($attribute->signature->name) . "(JSC::ExecState*, JSC::JSValue);\n");
                push(@headerContent, "#endif\n") if $conditionalString;
            }
        }
    }

    foreach my $function (@{$dataNode->functions}) {
        $numCustomFunctions++ if $function->signature->extendedAttributes->{"Custom"} || $function->signature->extendedAttributes->{"JSCustom"};
    }

    if ($numCustomFunctions > 0) {
        push(@headerContent, "\n    // Custom functions\n");
        foreach my $function (@{$dataNode->functions}) {
            next unless $function->signature->extendedAttributes->{"Custom"} or $function->signature->extendedAttributes->{"JSCustom"};
            next if $function->{overloads} && $function->{overloadIndex} != 1;
            my $conditionalString = $codeGenerator->GenerateConditionalString($function->signature);
            push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
            my $functionImplementationName = $function->signature->extendedAttributes->{"ImplementedAs"} || $codeGenerator->WK_lcfirst($function->signature->name);
            push(@headerContent, "    " . ($function->isStatic ? "static " : "") . "JSC::JSValue " . $functionImplementationName . "(JSC::ExecState*);\n");
            push(@headerContent, "#endif\n") if $conditionalString;
        }
    }

    if (!$hasParent) {
        push(@headerContent, "    $implType* impl() const { return m_impl; }\n");
        push(@headerContent, "    void releaseImpl() { m_impl->deref(); m_impl = 0; }\n\n");
        push(@headerContent, "    void releaseImplIfNotNull() { if (m_impl) { m_impl->deref(); m_impl = 0; } }\n\n");
        push(@headerContent, "private:\n");
        push(@headerContent, "    $implType* m_impl;\n");
    } elsif ($dataNode->extendedAttributes->{"JSGenerateToNativeObject"}) {
        push(@headerContent, "    $implClassName* impl() const\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        return static_cast<$implClassName*>(Base::impl());\n");
        push(@headerContent, "    }\n");
    }

    if (IsTypedArrayType($implType) and ($implType ne "ArrayBufferView") and ($implType ne "ArrayBuffer")) {
        push(@headerContent, "    static const JSC::TypedArrayType TypedArrayStorageType = JSC::");
        push(@headerContent, "TypedArrayInt8") if $implType eq "Int8Array";
        push(@headerContent, "TypedArrayInt16") if $implType eq "Int16Array";
        push(@headerContent, "TypedArrayInt32") if $implType eq "Int32Array";
        push(@headerContent, "TypedArrayUint8") if $implType eq "Uint8Array";
        push(@headerContent, "TypedArrayUint8Clamped") if $implType eq "Uint8ClampedArray";
        push(@headerContent, "TypedArrayUint16") if $implType eq "Uint16Array";
        push(@headerContent, "TypedArrayUint32") if $implType eq "Uint32Array";
        push(@headerContent, "TypedArrayFloat32") if $implType eq "Float32Array";
        push(@headerContent, "TypedArrayFloat64") if $implType eq "Float64Array";
        push(@headerContent, ";\n");
        push(@headerContent, "    intptr_t m_storageLength;\n");
        push(@headerContent, "    void* m_storage;\n");
    }

    push(@headerContent, "protected:\n");
    # Constructor
    if ($interfaceName eq "DOMWindow") {
        push(@headerContent, "    $className(JSC::JSGlobalData&, JSC::Structure*, PassRefPtr<$implType>, JSDOMWindowShell*);\n");
    } elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
        push(@headerContent, "    $className(JSC::JSGlobalData&, JSC::Structure*, PassRefPtr<$implType>);\n");
    } else {
        push(@headerContent, "    $className(JSC::Structure*, JSDOMGlobalObject*, PassRefPtr<$implType>);\n");
        push(@headerContent, "    void finishCreation(JSC::JSGlobalData&);\n");
    }

    # structure flags
    push(@headerContent, "    static const unsigned StructureFlags = ");
    foreach my $structureFlag (keys %structureFlags) {
        push(@headerContent, $structureFlag . " | ");
    }
    push(@headerContent, "Base::StructureFlags;\n");

    # Index getter
    if ($dataNode->extendedAttributes->{"IndexedGetter"}) {
        push(@headerContent, "    static JSC::JSValue indexGetter(JSC::ExecState*, JSC::JSValue, unsigned);\n");
    }
    if ($dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
        push(@headerContent, "    JSC::JSValue getByIndex(JSC::ExecState*, unsigned index);\n");
    }

    # Index setter
    if ($dataNode->extendedAttributes->{"CustomIndexedSetter"}) {
        push(@headerContent, "    void indexSetter(JSC::ExecState*, unsigned index, JSC::JSValue);\n");
    }
    # Name getter
    if ($dataNode->extendedAttributes->{"NamedGetter"} || $dataNode->extendedAttributes->{"CustomNamedGetter"}) {
        push(@headerContent, "private:\n");
        push(@headerContent, "    static bool canGetItemsForName(JSC::ExecState*, $implClassName*, const JSC::Identifier&);\n");
        push(@headerContent, "    static JSC::JSValue nameGetter(JSC::ExecState*, JSC::JSValue, const JSC::Identifier&);\n");
    }

    push(@headerContent, "};\n\n");

    if ($dataNode->extendedAttributes->{"JSInlineGetOwnPropertySlot"} && !$dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}) {
        push(@headerContent, "ALWAYS_INLINE bool ${className}::getOwnPropertySlot(JSC::JSCell* cell, JSC::ExecState* exec, const JSC::Identifier& propertyName, JSC::PropertySlot& slot)\n");
        push(@headerContent, "{\n");
        push(@headerContent, "    ${className}* thisObject = JSC::jsCast<${className}*>(cell);\n");
        push(@headerContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
        push(@headerContent, GenerateGetOwnPropertySlotBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 1));
        push(@headerContent, "}\n\n");
        push(@headerContent, "ALWAYS_INLINE bool ${className}::getOwnPropertyDescriptor(JSC::JSObject* object, JSC::ExecState* exec, const JSC::Identifier& propertyName, JSC::PropertyDescriptor& descriptor)\n");
        push(@headerContent, "{\n");
        push(@headerContent, "    ${className}* thisObject = JSC::jsCast<${className}*>(object);\n");
        push(@headerContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
        push(@headerContent, GenerateGetOwnPropertyDescriptorBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 1));
        push(@headerContent, "}\n\n");
    }

    if (!$hasParent ||
        $dataNode->extendedAttributes->{"JSGenerateIsReachable"} || 
        $dataNode->extendedAttributes->{"JSCustomIsReachable"} || 
        $dataNode->extendedAttributes->{"JSCustomFinalize"} ||
        $dataNode->extendedAttributes->{"ActiveDOMObject"}) {
        push(@headerContent, "class JS${implClassName}Owner : public JSC::WeakHandleOwner {\n");
        push(@headerContent, "    virtual bool isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown>, void* context, JSC::SlotVisitor&);\n");
        push(@headerContent, "    virtual void finalize(JSC::Handle<JSC::Unknown>, void* context);\n");
        push(@headerContent, "};\n");
        push(@headerContent, "\n");
        push(@headerContent, "inline JSC::WeakHandleOwner* wrapperOwner(DOMWrapperWorld*, $implType*)\n");
        push(@headerContent, "{\n");
        push(@headerContent, "    DEFINE_STATIC_LOCAL(JS${implClassName}Owner, js${implClassName}Owner, ());\n");
        push(@headerContent, "    return &js${implClassName}Owner;\n");
        push(@headerContent, "}\n");
        push(@headerContent, "\n");
        push(@headerContent, "inline void* wrapperContext(DOMWrapperWorld* world, $implType*)\n");
        push(@headerContent, "{\n");
        push(@headerContent, "    return world;\n");
        push(@headerContent, "}\n");
        push(@headerContent, "\n");
    }

    if (!$hasParent || $dataNode->extendedAttributes->{"JSGenerateToJSObject"} || ($dataNode->extendedAttributes->{"CustomToJSObject"} || $dataNode->extendedAttributes->{"JSCustomToJSObject"})) {
        push(@headerContent, "JSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject*, $implType*);\n");
    }
    if (!$hasParent || $dataNode->extendedAttributes->{"JSGenerateToNativeObject"}) {
        if ($interfaceName eq "NodeFilter") {
            push(@headerContent, "PassRefPtr<NodeFilter> toNodeFilter(JSC::JSGlobalData&, JSC::JSValue);\n");
        } else {
            push(@headerContent, "$implType* to${interfaceName}(JSC::JSValue);\n");
        }
    }
    if ($usesToJSNewlyCreated{$interfaceName}) {
        push(@headerContent, "JSC::JSValue toJSNewlyCreated(JSC::ExecState*, JSDOMGlobalObject*, $interfaceName*);\n");
    }
    
    push(@headerContent, "\n");

    # Add prototype declaration.
    %structureFlags = ();
    push(@headerContent, "class ${className}Prototype : public JSC::JSNonFinalObject {\n");
    push(@headerContent, "public:\n");
    push(@headerContent, "    typedef JSC::JSNonFinalObject Base;\n");
    if ($interfaceName ne "DOMWindow" && !$dataNode->extendedAttributes->{"IsWorkerContext"}) {
        push(@headerContent, "    static JSC::JSObject* self(JSC::ExecState*, JSC::JSGlobalObject*);\n");
    }

    push(@headerContent, "    static ${className}Prototype* create(JSC::JSGlobalData& globalData, JSC::JSGlobalObject* globalObject, JSC::Structure* structure)\n");
    push(@headerContent, "    {\n");
    push(@headerContent, "        ${className}Prototype* ptr = new (NotNull, JSC::allocateCell<${className}Prototype>(globalData.heap)) ${className}Prototype(globalData, globalObject, structure);\n");
    push(@headerContent, "        ptr->finishCreation(globalData);\n");
    push(@headerContent, "        return ptr;\n");
    push(@headerContent, "    }\n\n");

    push(@headerContent, "    static const JSC::ClassInfo s_info;\n");
    if ($numFunctions > 0 || $numConstants > 0) {
        push(@headerContent, "    static bool getOwnPropertySlot(JSC::JSCell*, JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);\n");
        push(@headerContent, "    static bool getOwnPropertyDescriptor(JSC::JSObject*, JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);\n");
        $structureFlags{"JSC::OverridesGetOwnPropertySlot"} = 1;
    }
    if ($dataNode->extendedAttributes->{"JSCustomMarkFunction"} or $needsMarkChildren) {
        $structureFlags{"JSC::OverridesVisitChildren"} = 1;
    }
    push(@headerContent,
        "    static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)\n" .
        "    {\n" .
        "        return JSC::Structure::create(globalData, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), &s_info);\n" .
        "    }\n");
    if ($dataNode->extendedAttributes->{"JSCustomNamedGetterOnPrototype"}) {
        push(@headerContent, "    static void put(JSC::JSCell*, JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSValue, JSC::PutPropertySlot&);\n");
        push(@headerContent, "    bool putDelegate(JSC::ExecState*, const JSC::Identifier&, JSC::JSValue, JSC::PutPropertySlot&);\n");
    }

    # Custom defineOwnProperty function
    push(@headerContent, "    static bool defineOwnProperty(JSC::JSObject*, JSC::ExecState*, const JSC::Identifier& propertyName, JSC::PropertyDescriptor&, bool shouldThrow);\n") if $dataNode->extendedAttributes->{"JSCustomDefineOwnPropertyOnPrototype"};

    push(@headerContent, "\nprivate:\n");
    push(@headerContent, "    ${className}Prototype(JSC::JSGlobalData& globalData, JSC::JSGlobalObject*, JSC::Structure* structure) : JSC::JSNonFinalObject(globalData, structure) { }\n");

    # structure flags
    push(@headerContent, "protected:\n");
    push(@headerContent, "    static const unsigned StructureFlags = ");
    foreach my $structureFlag (keys %structureFlags) {
        push(@headerContent, $structureFlag . " | ");
    }
    push(@headerContent, "Base::StructureFlags;\n");

    push(@headerContent, "};\n\n");

    if (!$dataNode->extendedAttributes->{"OmitConstructor"}) {
        $headerIncludes{"JSDOMBinding.h"} = 1;
        GenerateConstructorDeclaration(\@headerContent, $className, $dataNode, $interfaceName);
    }

    if ($numFunctions > 0) {
        push(@headerContent,"// Functions\n\n");
        foreach my $function (@{$dataNode->functions}) {
            next if $function->{overloadIndex} && $function->{overloadIndex} > 1;
            my $conditionalString = $codeGenerator->GenerateConditionalString($function->signature);
            push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
            my $functionName = GetFunctionName($className, $function);
            push(@headerContent, "JSC::EncodedJSValue JSC_HOST_CALL ${functionName}(JSC::ExecState*);\n");
            push(@headerContent, "#endif\n") if $conditionalString;
        }
    }

    if ($numAttributes > 0 || !$dataNode->extendedAttributes->{"OmitConstructor"}) {
        push(@headerContent,"// Attributes\n\n");
        foreach my $attribute (@{$dataNode->attributes}) {
            my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
            push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
            my $getter = GetAttributeGetterName($interfaceName, $className, $attribute);
            push(@headerContent, "JSC::JSValue ${getter}(JSC::ExecState*, JSC::JSValue, const JSC::Identifier&);\n");
            unless ($attribute->type =~ /readonly/) {
                my $setter = GetAttributeSetterName($interfaceName, $className, $attribute);
                push(@headerContent, "void ${setter}(JSC::ExecState*, JSC::JSObject*, JSC::JSValue);\n");
            }
            push(@headerContent, "#endif\n") if $conditionalString;
        }
        
        if (!$dataNode->extendedAttributes->{"OmitConstructor"}) {
            my $getter = "js" . $interfaceName . "Constructor";
            push(@headerContent, "JSC::JSValue ${getter}(JSC::ExecState*, JSC::JSValue, const JSC::Identifier&);\n");
        }

        if ($dataNode->extendedAttributes->{"ReplaceableConstructor"}) {
            my $constructorFunctionName = "setJS" . $interfaceName . "Constructor";
            push(@headerContent, "void ${constructorFunctionName}(JSC::ExecState*, JSC::JSObject*, JSC::JSValue);\n");
        }
    }

    if ($numConstants > 0) {
        push(@headerContent,"// Constants\n\n");
        foreach my $constant (@{$dataNode->constants}) {
            my $conditionalString = $codeGenerator->GenerateConditionalString($constant);
            push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
            my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($constant->name);
            push(@headerContent, "JSC::JSValue ${getter}(JSC::ExecState*, JSC::JSValue, const JSC::Identifier&);\n");
            push(@headerContent, "#endif\n") if $conditionalString;
        }
    }

    my $conditionalString = $codeGenerator->GenerateConditionalString($dataNode);
    push(@headerContent, "\n} // namespace WebCore\n\n");
    push(@headerContent, "#endif // ${conditionalString}\n\n") if $conditionalString;
    push(@headerContent, "#endif\n");

    # - Generate dependencies.
    if ($writeDependencies && @ancestorInterfaceNames) {
        push(@depsContent, "$className.h : ", join(" ", map { "$_.idl" } @ancestorInterfaceNames), "\n");
        push(@depsContent, map { "$_.idl :\n" } @ancestorInterfaceNames); 
    }
}

sub GenerateAttributesHashTable($$)
{
    my ($object, $dataNode) = @_;

    # FIXME: These should be functions on $dataNode.
    my $interfaceName = $dataNode->name;
    my $className = "JS$interfaceName";
    
    # - Add all attributes in a hashtable definition
    my $numAttributes = @{$dataNode->attributes};
    $numAttributes++ if !$dataNode->extendedAttributes->{"OmitConstructor"};

    return 0  if !$numAttributes;

    my $hashSize = $numAttributes;
    my $hashName = $className . "Table";

    my @hashKeys = ();
    my @hashSpecials = ();
    my @hashValue1 = ();
    my @hashValue2 = ();
    my %conditionals = ();

    my @entries = ();

    foreach my $attribute (@{$dataNode->attributes}) {
        next if ($attribute->isStatic);
        my $name = $attribute->signature->name;
        push(@hashKeys, $name);

        my @specials = ();
        push(@specials, "DontDelete") unless $attribute->signature->extendedAttributes->{"Deletable"};
        push(@specials, "DontEnum") if $attribute->signature->extendedAttributes->{"NotEnumerable"};
        push(@specials, "ReadOnly") if $attribute->type =~ /readonly/;
        my $special = (@specials > 0) ? join(" | ", @specials) : "0";
        push(@hashSpecials, $special);

        my $getter = GetAttributeGetterName($interfaceName, $className, $attribute);
        push(@hashValue1, $getter);

        if ($attribute->type =~ /readonly/) {
            push(@hashValue2, "0");
        } else {
            my $setter = GetAttributeSetterName($interfaceName, $className, $attribute);
            push(@hashValue2, $setter);
        }

        my $conditional = $attribute->signature->extendedAttributes->{"Conditional"};
        if ($conditional) {
            $conditionals{$name} = $conditional;
        }
    }

    if (!$dataNode->extendedAttributes->{"OmitConstructor"}) {
        push(@hashKeys, "constructor");
        my $getter = "js" . $interfaceName . "Constructor";
        push(@hashValue1, $getter);
        if ($dataNode->extendedAttributes->{"ReplaceableConstructor"}) {
            my $setter = "setJS" . $interfaceName . "Constructor";
            push(@hashValue2, $setter);
            push(@hashSpecials, "DontEnum | DontDelete");
        } else {            
            push(@hashValue2, "0");
            push(@hashSpecials, "DontEnum | ReadOnly");
        }
    }

    $object->GenerateHashTable($hashName, $hashSize,
                               \@hashKeys, \@hashSpecials,
                               \@hashValue1, \@hashValue2,
                               \%conditionals);
    return $numAttributes;
}

sub GenerateParametersCheckExpression
{
    my $numParameters = shift;
    my $function = shift;

    my @andExpression = ();
    push(@andExpression, "argsCount == $numParameters");
    my $parameterIndex = 0;
    my %usedArguments = ();
    foreach my $parameter (@{$function->parameters}) {
        last if $parameterIndex >= $numParameters;
        my $value = "arg$parameterIndex";
        my $type = $codeGenerator->StripModule($parameter->type);

        # Only DOMString or wrapper types are checked.
        # For DOMString, Null, Undefined and any Object are accepted too, as
        # these are acceptable values for a DOMString argument (any Object can
        # be converted to a string via .toString).
        if ($codeGenerator->IsStringType($type)) {
            push(@andExpression, "(${value}.isUndefinedOrNull() || ${value}.isString() || ${value}.isObject())");
            $usedArguments{$parameterIndex} = 1;
        } elsif ($parameter->extendedAttributes->{"Callback"}) {
            # For Callbacks only checks if the value is null or object.
            push(@andExpression, "(${value}.isNull() || ${value}.isFunction())");
            $usedArguments{$parameterIndex} = 1;
        } elsif (IsArrayType($type)) {
            # FIXME: Add proper support for T[], T[]?, sequence<T>
            push(@andExpression, "(${value}.isNull() || (${value}.isObject() && asObject(${value})->inherits(&JSArray::s_info)))");
            $usedArguments{$parameterIndex} = 1;
        } elsif (!IsNativeType($type)) {
            push(@andExpression, "(${value}.isNull() || (${value}.isObject() && asObject(${value})->inherits(&JS${type}::s_info)))");
            $usedArguments{$parameterIndex} = 1;
        }
        $parameterIndex++;
    }
    my $res = join(" && ", @andExpression);
    $res = "($res)" if @andExpression > 1;
    return ($res, keys %usedArguments);
}

sub GenerateFunctionParametersCheck
{
    my $function = shift;

    my @orExpression = ();
    my $numParameters = 0;
    my @neededArguments = ();

    foreach my $parameter (@{$function->parameters}) {
        if ($parameter->extendedAttributes->{"Optional"}) {
            my ($expression, @usedArguments) = GenerateParametersCheckExpression($numParameters, $function);
            push(@orExpression, $expression);
            push(@neededArguments, @usedArguments);
        }
        $numParameters++;
    }
    my ($expression, @usedArguments) = GenerateParametersCheckExpression($numParameters, $function);
    push(@orExpression, $expression);
    push(@neededArguments, @usedArguments);
    return (join(" || ", @orExpression), @neededArguments);
}

sub GenerateOverloadedFunction
{
    my $function = shift;
    my $dataNode = shift;
    my $implClassName = shift;

    # Generate code for choosing the correct overload to call. Overloads are
    # chosen based on the total number of arguments passed and the type of
    # values passed in non-primitive argument slots. When more than a single
    # overload is applicable, precedence is given according to the order of
    # declaration in the IDL.

    my $kind = $function->isStatic ? "Constructor" : "Prototype";
    my $functionName = "js${implClassName}${kind}Function" . $codeGenerator->WK_ucfirst($function->signature->name);

    push(@implContent, "EncodedJSValue JSC_HOST_CALL ${functionName}(ExecState* exec)\n");
    push(@implContent, <<END);
{
    size_t argsCount = exec->argumentCount();
END

    my %fetchedArguments = ();

    foreach my $overload (@{$function->{overloads}}) {
        my ($parametersCheck, @neededArguments) = GenerateFunctionParametersCheck($overload);

        foreach my $parameterIndex (@neededArguments) {
            next if exists $fetchedArguments{$parameterIndex};
            push(@implContent, "    JSValue arg$parameterIndex(exec->argument($parameterIndex));\n");
            $fetchedArguments{$parameterIndex} = 1;
        }

        push(@implContent, "    if ($parametersCheck)\n");
        push(@implContent, "        return ${functionName}$overload->{overloadIndex}(exec);\n");
    }
    push(@implContent, <<END);
    return throwVMTypeError(exec);
}

END
}

sub GenerateImplementation
{
    my ($object, $dataNode) = @_;

    my $interfaceName = $dataNode->name;
    my $className = "JS$interfaceName";
    my $implClassName = $interfaceName;

    my $hasLegacyParent = $dataNode->extendedAttributes->{"JSLegacyParent"};
    my $hasRealParent = @{$dataNode->parents} > 0;
    my $hasParent = $hasLegacyParent || $hasRealParent;
    my $parentClassName = GetParentClassName($dataNode);
    my $visibleInterfaceName = $codeGenerator->GetVisibleInterfaceName($dataNode);
    my $eventTarget = $dataNode->extendedAttributes->{"EventTarget"};
    my $needsMarkChildren = $dataNode->extendedAttributes->{"JSCustomMarkFunction"} || $dataNode->extendedAttributes->{"EventTarget"};

    # - Add default header template
    push(@implContentHeader, GenerateImplementationContentHeader($dataNode));

    AddIncludesForSVGAnimatedType($interfaceName) if $className =~ /^JSSVGAnimated/;

    $implIncludes{"<wtf/GetPtr.h>"} = 1;
    $implIncludes{"<runtime/PropertyNameArray.h>"} = 1 if $dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"};

    AddIncludesForTypeInImpl($interfaceName);

    @implContent = ();

    push(@implContent, "\nusing namespace JSC;\n\n");
    push(@implContent, "namespace WebCore {\n\n");

    push(@implContent, "ASSERT_CLASS_FITS_IN_CELL($className);\n");

    my $numAttributes = GenerateAttributesHashTable($object, $dataNode);

    my $numConstants = @{$dataNode->constants};
    my $numFunctions = @{$dataNode->functions};

    # - Add all constants
    if (!$dataNode->extendedAttributes->{"OmitConstructor"}) {
        my $hashSize = $numConstants;
        my $hashName = $className . "ConstructorTable";

        my @hashKeys = ();
        my @hashValue1 = ();
        my @hashValue2 = ();
        my @hashSpecials = ();
        my %conditionals = ();

        # FIXME: we should not need a function for every constant.
        foreach my $constant (@{$dataNode->constants}) {
            my $name = $constant->name;
            push(@hashKeys, $name);
            my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($name);
            push(@hashValue1, $getter);
            push(@hashValue2, "0");
            push(@hashSpecials, "DontDelete | ReadOnly");

            my $implementedBy = $constant->extendedAttributes->{"ImplementedBy"};
            if ($implementedBy) {
                $implIncludes{"${implementedBy}.h"} = 1;
            }
            my $conditional = $constant->extendedAttributes->{"Conditional"};
            if ($conditional) {
                $conditionals{$name} = $conditional;
            }
        }

        foreach my $attribute (@{$dataNode->attributes}) {
            next unless ($attribute->isStatic);
            my $name = $attribute->signature->name;
            push(@hashKeys, $name);

            my @specials = ();
            push(@specials, "DontDelete") unless $attribute->signature->extendedAttributes->{"Deletable"};
            push(@specials, "ReadOnly") if $attribute->type =~ /readonly/;
            my $special = (@specials > 0) ? join(" | ", @specials) : "0";
            push(@hashSpecials, $special);

            my $getter = GetAttributeGetterName($interfaceName, $className, $attribute);
            push(@hashValue1, $getter);

            if ($attribute->type =~ /readonly/) {
                push(@hashValue2, "0");
            } else {
                my $setter = GetAttributeSetterName($interfaceName, $className, $attribute);
                push(@hashValue2, $setter);
            }

            my $conditional = $attribute->signature->extendedAttributes->{"Conditional"};
            if ($conditional) {
                $conditionals{$name} = $conditional;
            }
        }

        foreach my $function (@{$dataNode->functions}) {
            next unless ($function->isStatic);
            next if $function->{overloadIndex} && $function->{overloadIndex} > 1;
            my $name = $function->signature->name;
            push(@hashKeys, $name);

            my $functionName = GetFunctionName($className, $function);
            push(@hashValue1, $functionName);

            my $numParameters = @{$function->parameters};
            push(@hashValue2, $numParameters);

            my @specials = ();
            push(@specials, "DontDelete") unless $function->signature->extendedAttributes->{"Deletable"};
            push(@specials, "DontEnum") if $function->signature->extendedAttributes->{"NotEnumerable"};
            push(@specials, "JSC::Function");
            my $special = (@specials > 0) ? join(" | ", @specials) : "0";
            push(@hashSpecials, $special);

            my $conditional = $function->signature->extendedAttributes->{"Conditional"};
            if ($conditional) {
                $conditionals{$name} = $conditional;
            }
        }

        $object->GenerateHashTable($hashName, $hashSize,
                                   \@hashKeys, \@hashSpecials,
                                   \@hashValue1, \@hashValue2,
                                   \%conditionals);

        push(@implContent, $codeGenerator->GenerateCompileTimeCheckForEnumsIfNeeded($dataNode));

        my $protoClassName = "${className}Prototype";
        GenerateConstructorDefinition(\@implContent, $className, $protoClassName, $interfaceName, $visibleInterfaceName, $dataNode);
        if ($dataNode->extendedAttributes->{"NamedConstructor"}) {
            GenerateConstructorDefinition(\@implContent, $className, $protoClassName, $interfaceName, $dataNode->extendedAttributes->{"NamedConstructor"}, $dataNode, "GeneratingNamedConstructor");
        }
    }

    # - Add functions and constants to a hashtable definition
    my $hashSize = $numFunctions + $numConstants;
    my $hashName = $className . "PrototypeTable";

    my @hashKeys = ();
    my @hashValue1 = ();
    my @hashValue2 = ();
    my @hashSpecials = ();
    my %conditionals = ();

    # FIXME: we should not need a function for every constant.
    foreach my $constant (@{$dataNode->constants}) {
        my $name = $constant->name;
        push(@hashKeys, $name);
        my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($name);
        push(@hashValue1, $getter);
        push(@hashValue2, "0");
        push(@hashSpecials, "DontDelete | ReadOnly");

        my $conditional = $constant->extendedAttributes->{"Conditional"};
        if ($conditional) {
            $conditionals{$name} = $conditional;
        }
    }

    foreach my $function (@{$dataNode->functions}) {
        next if ($function->isStatic);
        next if $function->{overloadIndex} && $function->{overloadIndex} > 1;
        my $name = $function->signature->name;
        push(@hashKeys, $name);

        my $functionName = GetFunctionName($className, $function);
        push(@hashValue1, $functionName);

        my $numParameters = @{$function->parameters};
        push(@hashValue2, $numParameters);

        my @specials = ();
        push(@specials, "DontDelete") unless $function->signature->extendedAttributes->{"Deletable"};
        push(@specials, "DontEnum") if $function->signature->extendedAttributes->{"NotEnumerable"};
        push(@specials, "JSC::Function");
        my $special = (@specials > 0) ? join(" | ", @specials) : "0";
        push(@hashSpecials, $special);

        my $conditional = $function->signature->extendedAttributes->{"Conditional"};
        if ($conditional) {
            $conditionals{$name} = $conditional;
        }
    }

    $object->GenerateHashTable($hashName, $hashSize,
                               \@hashKeys, \@hashSpecials,
                               \@hashValue1, \@hashValue2,
                               \%conditionals);

    if ($dataNode->extendedAttributes->{"JSNoStaticTables"}) {
        push(@implContent, "static const HashTable* get${className}PrototypeTable(ExecState* exec)\n");
        push(@implContent, "{\n");
        push(@implContent, "    return getHashTableForGlobalData(exec->globalData(), &${className}PrototypeTable);\n");
        push(@implContent, "}\n\n");
        push(@implContent, "const ClassInfo ${className}Prototype::s_info = { \"${visibleInterfaceName}Prototype\", &Base::s_info, 0, get${className}PrototypeTable, CREATE_METHOD_TABLE(${className}Prototype) };\n\n");
    } else {
        push(@implContent, "const ClassInfo ${className}Prototype::s_info = { \"${visibleInterfaceName}Prototype\", &Base::s_info, &${className}PrototypeTable, 0, CREATE_METHOD_TABLE(${className}Prototype) };\n\n");
    }
    if ($interfaceName ne "DOMWindow" && !$dataNode->extendedAttributes->{"IsWorkerContext"}) {
        push(@implContent, "JSObject* ${className}Prototype::self(ExecState* exec, JSGlobalObject* globalObject)\n");
        push(@implContent, "{\n");
        push(@implContent, "    return getDOMPrototype<${className}>(exec, globalObject);\n");
        push(@implContent, "}\n\n");
    }

    if ($numConstants > 0 || $numFunctions > 0) {
        push(@implContent, "bool ${className}Prototype::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot)\n");
        push(@implContent, "{\n");
        push(@implContent, "    ${className}Prototype* thisObject = jsCast<${className}Prototype*>(cell);\n");

        if ($numConstants eq 0 && $numFunctions eq 0) {
            push(@implContent, "    return Base::getOwnPropertySlot(thisObject, exec, propertyName, slot);\n");        
        } elsif ($numConstants eq 0) {
            push(@implContent, "    return getStaticFunctionSlot<JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, slot);\n");
        } elsif ($numFunctions eq 0) {
            push(@implContent, "    return getStaticValueSlot<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, slot);\n");
        } else {
            push(@implContent, "    return getStaticPropertySlot<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, slot);\n");
        }
        push(@implContent, "}\n\n");

        push(@implContent, "bool ${className}Prototype::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)\n");
        push(@implContent, "{\n");
        push(@implContent, "    ${className}Prototype* thisObject = jsCast<${className}Prototype*>(object);\n");

        if ($numConstants eq 0 && $numFunctions eq 0) {
            push(@implContent, "    return Base::getOwnPropertyDescriptor(thisObject, exec, propertyName, descriptor);\n");        
        } elsif ($numConstants eq 0) {
            push(@implContent, "    return getStaticFunctionDescriptor<JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, descriptor);\n");
        } elsif ($numFunctions eq 0) {
            push(@implContent, "    return getStaticValueDescriptor<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, descriptor);\n");
        } else {
            push(@implContent, "    return getStaticPropertyDescriptor<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, descriptor);\n");
        }
        push(@implContent, "}\n\n");
    }

    if ($dataNode->extendedAttributes->{"JSCustomNamedGetterOnPrototype"}) {
        push(@implContent, "void ${className}Prototype::put(JSCell* cell, ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot)\n");
        push(@implContent, "{\n");
        push(@implContent, "    ${className}Prototype* thisObject = jsCast<${className}Prototype*>(cell);\n");
        push(@implContent, "    if (thisObject->putDelegate(exec, propertyName, value, slot))\n");
        push(@implContent, "        return;\n");
        push(@implContent, "    Base::put(thisObject, exec, propertyName, value, slot);\n");
        push(@implContent, "}\n\n");
    }

    # - Initialize static ClassInfo object
    if ($numAttributes > 0 && $dataNode->extendedAttributes->{"JSNoStaticTables"}) {
        push(@implContent, "static const HashTable* get${className}Table(ExecState* exec)\n");
        push(@implContent, "{\n");
        push(@implContent, "    return getHashTableForGlobalData(exec->globalData(), &${className}Table);\n");
        push(@implContent, "}\n\n");
    }

    push(@implContent, "const ClassInfo $className" . "::s_info = { \"${visibleInterfaceName}\", &Base::s_info, ");

    if ($numAttributes > 0 && !$dataNode->extendedAttributes->{"JSNoStaticTables"}) {
        push(@implContent, "&${className}Table");
    } else {
        push(@implContent, "0");
    }
    if ($numAttributes > 0 && $dataNode->extendedAttributes->{"JSNoStaticTables"}) {
        push(@implContent, ", get${className}Table ");
    } else {
        push(@implContent, ", 0 ");
    }
    push(@implContent, ", CREATE_METHOD_TABLE($className) };\n\n");

    my $implType = $implClassName;
    my ($svgPropertyType, $svgListPropertyType, $svgNativeType) = GetSVGPropertyTypes($implType);
    $implType = $svgNativeType if $svgNativeType;

    my $svgPropertyOrListPropertyType;
    $svgPropertyOrListPropertyType = $svgPropertyType if $svgPropertyType;
    $svgPropertyOrListPropertyType = $svgListPropertyType if $svgListPropertyType;

    # Constructor
    if ($interfaceName eq "DOMWindow") {
        AddIncludesForTypeInImpl("JSDOMWindowShell");
        push(@implContent, "${className}::$className(JSGlobalData& globalData, Structure* structure, PassRefPtr<$implType> impl, JSDOMWindowShell* shell)\n");
        push(@implContent, "    : $parentClassName(globalData, structure, impl, shell)\n");
        push(@implContent, "{\n");
        push(@implContent, "}\n\n");
    } elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
        AddIncludesForTypeInImpl($interfaceName);
        push(@implContent, "${className}::$className(JSGlobalData& globalData, Structure* structure, PassRefPtr<$implType> impl)\n");
        push(@implContent, "    : $parentClassName(globalData, structure, impl)\n");
        push(@implContent, "{\n");
        push(@implContent, "}\n\n");
    } else {
        push(@implContent, "${className}::$className(Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<$implType> impl)\n");
        if ($hasParent) {
            push(@implContent, "    : $parentClassName(structure, globalObject, impl)\n");
        } else {
            push(@implContent, "    : $parentClassName(structure, globalObject)\n");
            push(@implContent, "    , m_impl(impl.leakRef())\n");
        }
        push(@implContent, "{\n");
        push(@implContent, "}\n\n");

        push(@implContent, "void ${className}::finishCreation(JSGlobalData& globalData)\n");
        push(@implContent, "{\n");
        push(@implContent, "    Base::finishCreation(globalData);\n");
        if (IsTypedArrayType($implType) and ($implType ne "ArrayBufferView") and ($implType ne "ArrayBuffer")) {
            push(@implContent, "    TypedArrayDescriptor descriptor(&${className}::s_info, OBJECT_OFFSETOF(${className}, m_storage), OBJECT_OFFSETOF(${className}, m_storageLength));\n");
            push(@implContent, "    globalData.registerTypedArrayDescriptor(impl(), descriptor);\n");
            push(@implContent, "    m_storage = impl()->data();\n");
            push(@implContent, "    m_storageLength = impl()->length();\n");
        }
        push(@implContent, "    ASSERT(inherits(&s_info));\n");
        push(@implContent, "}\n\n");
    }

    if (!$dataNode->extendedAttributes->{"ExtendsDOMGlobalObject"}) {
        push(@implContent, "JSObject* ${className}::createPrototype(ExecState* exec, JSGlobalObject* globalObject)\n");
        push(@implContent, "{\n");
        if ($hasParent && $parentClassName ne "JSC::DOMNodeFilter") {
            push(@implContent, "    return ${className}Prototype::create(exec->globalData(), globalObject, ${className}Prototype::createStructure(exec->globalData(), globalObject, ${parentClassName}Prototype::self(exec, globalObject)));\n");
        } else {
            push(@implContent, "    return ${className}Prototype::create(exec->globalData(), globalObject, ${className}Prototype::createStructure(globalObject->globalData(), globalObject, globalObject->objectPrototype()));\n");
        }
        push(@implContent, "}\n\n");
    }

    if (!$hasParent) {
        # FIXME: This destroy function should not be necessary, as 
        # a finalizer should be called for each DOM object wrapper.
        # However, that seems not to be the case, so this has been
        # added back to avoid leaking while we figure out why the
        # finalizers are not always getting called. The work tracking
        # the finalizer issue is being tracked in http://webkit.org/b/75451
        push(@implContent, "void ${className}::destroy(JSC::JSCell* cell)\n");
        push(@implContent, "{\n");
        push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
        push(@implContent, "    thisObject->${className}::~${className}();\n");
        push(@implContent, "}\n\n");

        # We also need a destructor for the allocateCell to work properly with the destructor-free part of the heap.
        # Otherwise, these destroy functions/destructors won't get called.
        push(@implContent, "${className}::~${className}()\n");
        push(@implContent, "{\n");
        push(@implContent, "    releaseImplIfNotNull();\n");
        push(@implContent, "}\n\n");
    }

    my $hasGetter = $numAttributes > 0
                 || !$dataNode->extendedAttributes->{"OmitConstructor"} 
                 || $dataNode->extendedAttributes->{"IndexedGetter"}
                 || $dataNode->extendedAttributes->{"NumericIndexedGetter"}
                 || $dataNode->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}
                 || $dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}
                 || $dataNode->extendedAttributes->{"NamedGetter"}
                 || $dataNode->extendedAttributes->{"CustomNamedGetter"};

    # Attributes
    if ($hasGetter) {
        if (!$dataNode->extendedAttributes->{"JSInlineGetOwnPropertySlot"} && !$dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}) {
            push(@implContent, "bool ${className}::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot)\n");
            push(@implContent, "{\n");
            push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
            push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
            push(@implContent, GenerateGetOwnPropertySlotBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 0));
            push(@implContent, "}\n\n");
            push(@implContent, "bool ${className}::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)\n");
            push(@implContent, "{\n");
            push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(object);\n");
            push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
            push(@implContent, GenerateGetOwnPropertyDescriptorBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 0));
            push(@implContent, "}\n\n");
        }

        if (($dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"})
                && !$dataNode->extendedAttributes->{"CustomNamedGetter"}) {
            push(@implContent, "bool ${className}::getOwnPropertySlotByIndex(JSCell* cell, ExecState* exec, unsigned propertyName, PropertySlot& slot)\n");
            push(@implContent, "{\n");
            push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
            push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
            push(@implContent, "    if (propertyName < static_cast<$implClassName*>(thisObject->impl())->length()) {\n");
            if ($dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
                push(@implContent, "        slot.setValue(thisObject->getByIndex(exec, propertyName));\n");
            } else {
                push(@implContent, "        slot.setCustomIndex(thisObject, propertyName, thisObject->indexGetter);\n");
            }
            push(@implContent, "        return true;\n");
            push(@implContent, "    }\n");
            push(@implContent, "    return thisObject->methodTable()->getOwnPropertySlot(thisObject, exec, Identifier::from(exec, propertyName), slot);\n");
            push(@implContent, "}\n\n");
        }

        if ($numAttributes > 0) {
            foreach my $attribute (@{$dataNode->attributes}) {
                my $name = $attribute->signature->name;
                my $type = $codeGenerator->StripModule($attribute->signature->type);
                my $getFunctionName = GetAttributeGetterName($interfaceName, $className, $attribute);
                my $implGetterFunctionName = $codeGenerator->WK_lcfirst($name);

                my $attributeConditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
                push(@implContent, "#if ${attributeConditionalString}\n") if $attributeConditionalString;

                push(@implContent, "JSValue ${getFunctionName}(ExecState* exec, JSValue");
                push(@implContent, " slotBase") if !$attribute->isStatic;
                push(@implContent, ", const Identifier&)\n");
                push(@implContent, "{\n");

                if (!$attribute->isStatic) {
                    push(@implContent, "    ${className}* castedThis = jsCast<$className*>(asObject(slotBase));\n");
                }

                if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) {
                    $needsMarkChildren = 1;
                }

                if ($dataNode->extendedAttributes->{"CheckSecurity"} &&
                    !$attribute->signature->extendedAttributes->{"DoNotCheckSecurity"} &&
                    !$attribute->signature->extendedAttributes->{"DoNotCheckSecurityOnGetter"}) {
                    push(@implContent, "    if (!castedThis->allowsAccessFrom(exec))\n");
                    push(@implContent, "        return jsUndefined();\n");
                }

                if ($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCustom"} || $attribute->signature->extendedAttributes->{"CustomGetter"} || $attribute->signature->extendedAttributes->{"JSCustomGetter"}) {
                    push(@implContent, "    return castedThis->$implGetterFunctionName(exec);\n");
                } elsif ($attribute->signature->extendedAttributes->{"CheckSecurityForNode"}) {
                    $implIncludes{"JSDOMBinding.h"} = 1;
                    push(@implContent, "    $implClassName* impl = static_cast<$implClassName*>(castedThis->impl());\n");
                    push(@implContent, "    return shouldAllowAccessToNode(exec, impl->" . $attribute->signature->name . "()) ? " . NativeToJSValue($attribute->signature, 0, $implClassName, "impl->$implGetterFunctionName()", "castedThis") . " : jsNull();\n");
                } elsif ($type eq "EventListener") {
                    $implIncludes{"EventListener.h"} = 1;
                    push(@implContent, "    UNUSED_PARAM(exec);\n");
                    push(@implContent, "    $implClassName* impl = static_cast<$implClassName*>(castedThis->impl());\n");
                    push(@implContent, "    if (EventListener* listener = impl->$implGetterFunctionName()) {\n");
                    push(@implContent, "        if (const JSEventListener* jsListener = JSEventListener::cast(listener)) {\n");
                    if ($implClassName eq "Document" || $implClassName eq "WorkerContext" || $implClassName eq "SharedWorkerContext" || $implClassName eq "DedicatedWorkerContext") {
                        push(@implContent, "            if (JSObject* jsFunction = jsListener->jsFunction(impl))\n");
                    } else {
                        push(@implContent, "            if (JSObject* jsFunction = jsListener->jsFunction(impl->scriptExecutionContext()))\n");
                    }
                    push(@implContent, "                return jsFunction;\n");
                    push(@implContent, "        }\n");
                    push(@implContent, "    }\n");
                    push(@implContent, "    return jsNull();\n");
                } elsif ($attribute->signature->type =~ /Constructor$/) {
                    my $constructorType = $codeGenerator->StripModule($attribute->signature->type);
                    $constructorType =~ s/Constructor$//;
                    # Constructor attribute is only used by DOMWindow.idl, so it's correct to pass castedThis as the global object
                    # Once JSDOMWrappers have a back-pointer to the globalObject we can pass castedThis->globalObject()
                    push(@implContent, "    return JS" . $constructorType . "::getConstructor(exec, castedThis);\n");
                } elsif (!@{$attribute->getterExceptions}) {
                    push(@implContent, "    UNUSED_PARAM(exec);\n") if !$attribute->signature->extendedAttributes->{"CallWith"};

                    my $cacheIndex = 0;
                    if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) {
                        $cacheIndex = $currentCachedAttribute;
                        $currentCachedAttribute++;
                        push(@implContent, "    if (JSValue cachedValue = castedThis->m_" . $attribute->signature->name . ".get())\n");
                        push(@implContent, "        return cachedValue;\n");
                    }

                    my @callWithArgs = GenerateCallWith($attribute->signature->extendedAttributes->{"CallWith"}, \@implContent, "jsUndefined()");

                    if ($svgListPropertyType) {
                        push(@implContent, "    JSValue result =  " . NativeToJSValue($attribute->signature, 0, $implClassName, "castedThis->impl()->$implGetterFunctionName(" . (join ", ", @callWithArgs) . ")", "castedThis") . ";\n");
                    } elsif ($svgPropertyOrListPropertyType) {
                        push(@implContent, "    $svgPropertyOrListPropertyType& impl = castedThis->impl()->propertyReference();\n");
                        if ($svgPropertyOrListPropertyType eq "float") { # Special case for JSSVGNumber
                            push(@implContent, "    JSValue result =  " . NativeToJSValue($attribute->signature, 0, $implClassName, "impl", "castedThis") . ";\n");
                        } else {
                            push(@implContent, "    JSValue result =  " . NativeToJSValue($attribute->signature, 0, $implClassName, "impl.$implGetterFunctionName(" . (join ", ", @callWithArgs) . ")", "castedThis") . ";\n");

                        }
                    } else {
                        my ($functionName, @arguments) = $codeGenerator->GetterExpression(\%implIncludes, $interfaceName, $attribute);
                        if ($attribute->signature->extendedAttributes->{"ImplementedBy"}) {
                            my $implementedBy = $attribute->signature->extendedAttributes->{"ImplementedBy"};
                            $implIncludes{"${implementedBy}.h"} = 1;
                            $functionName = "${implementedBy}::${functionName}";
                            unshift(@arguments, "impl");
                        } elsif ($attribute->isStatic) {
                            $functionName = "${implClassName}::${functionName}";
                        } else {
                            $functionName = "impl->${functionName}";
                        }

                        unshift(@arguments, @callWithArgs);

                        my $jsType = NativeToJSValue($attribute->signature, 0, $implClassName, "${functionName}(" . join(", ", @arguments) . ")", "castedThis");
                        push(@implContent, "    $implClassName* impl = static_cast<$implClassName*>(castedThis->impl());\n") if !$attribute->isStatic;
                        if ($codeGenerator->IsSVGAnimatedType($type)) {
                            push(@implContent, "    RefPtr<$type> obj = $jsType;\n");
                            push(@implContent, "    JSValue result =  toJS(exec, castedThis->globalObject(), obj.get());\n");
                        } else {
                            push(@implContent, "    JSValue result = $jsType;\n");
                        }
                    }

                    push(@implContent, "    castedThis->m_" . $attribute->signature->name . ".set(exec->globalData(), castedThis, result);\n") if ($attribute->signature->extendedAttributes->{"CachedAttribute"});
                    push(@implContent, "    return result;\n");

                } else {
                    my @arguments = ("ec");
                    push(@implContent, "    ExceptionCode ec = 0;\n");

                    unshift(@arguments, GenerateCallWith($attribute->signature->extendedAttributes->{"CallWith"}, \@implContent, "jsUndefined()"));

                    if ($svgPropertyOrListPropertyType) {
                        push(@implContent, "    $svgPropertyOrListPropertyType impl(*castedThis->impl());\n");
                        push(@implContent, "    JSC::JSValue result = " . NativeToJSValue($attribute->signature, 0, $implClassName, "impl.$implGetterFunctionName(" . join(", ", @arguments) . ")", "castedThis") . ";\n");
                    } else {
                        push(@implContent, "    $implClassName* impl = static_cast<$implClassName*>(castedThis->impl());\n");
                        push(@implContent, "    JSC::JSValue result = " . NativeToJSValue($attribute->signature, 0, $implClassName, "impl->$implGetterFunctionName(" . join(", ", @arguments) . ")", "castedThis") . ";\n");
                    }

                    push(@implContent, "    setDOMException(exec, ec);\n");
                    push(@implContent, "    return result;\n");
                }

                push(@implContent, "}\n\n");

                push(@implContent, "#endif\n") if $attributeConditionalString;

                push(@implContent, "\n");
            }

            if (!$dataNode->extendedAttributes->{"OmitConstructor"}) {
                my $constructorFunctionName = "js" . $interfaceName . "Constructor";

                push(@implContent, "JSValue ${constructorFunctionName}(ExecState* exec, JSValue slotBase, const Identifier&)\n");
                push(@implContent, "{\n");
                push(@implContent, "    ${className}* domObject = jsCast<$className*>(asObject(slotBase));\n");

                if ($dataNode->extendedAttributes->{"CheckSecurity"}) {
                    push(@implContent, "    if (!domObject->allowsAccessFrom(exec))\n");
                    push(@implContent, "        return jsUndefined();\n");
                }

                push(@implContent, "    return ${className}::getConstructor(exec, domObject->globalObject());\n");
                push(@implContent, "}\n\n");
            }
        }

        # Check if we have any writable attributes
        my $hasReadWriteProperties = 0;
        foreach my $attribute (@{$dataNode->attributes}) {
            $hasReadWriteProperties = 1 if $attribute->type !~ /^readonly/ && !$attribute->isStatic;
        }

        my $hasSetter = $hasReadWriteProperties
                     || $dataNode->extendedAttributes->{"CustomNamedSetter"}
                     || $dataNode->extendedAttributes->{"CustomIndexedSetter"};

        if ($hasSetter) {
            if (!$dataNode->extendedAttributes->{"CustomPutFunction"}) {
                push(@implContent, "void ${className}::put(JSCell* cell, ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot)\n");
                push(@implContent, "{\n");
                push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
                push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
                if ($dataNode->extendedAttributes->{"CustomIndexedSetter"}) {
                    push(@implContent, "    bool ok;\n");
                    push(@implContent, "    unsigned index = propertyName.toUInt32(ok);\n");
                    push(@implContent, "    if (ok) {\n");
                    push(@implContent, "        thisObject->indexSetter(exec, index, value);\n");
                    push(@implContent, "        return;\n");
                    push(@implContent, "    }\n");
                }
                if ($dataNode->extendedAttributes->{"CustomNamedSetter"}) {
                    push(@implContent, "    if (thisObject->putDelegate(exec, propertyName, value, slot))\n");
                    push(@implContent, "        return;\n");
                }

                if ($hasReadWriteProperties) {
                    push(@implContent, "    lookupPut<$className, Base>(exec, propertyName, value, " . hashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, slot);\n");
                } else {
                    push(@implContent, "    Base::put(thisObject, exec, propertyName, value, slot);\n");
                }
                push(@implContent, "}\n\n");
            }

            if ($dataNode->extendedAttributes->{"CustomIndexedSetter"}) {
                push(@implContent, "void ${className}::putByIndex(JSCell* cell, ExecState* exec, unsigned propertyName, JSValue value, bool)\n");
                push(@implContent, "{\n");
                push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
                push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
                push(@implContent, "    thisObject->indexSetter(exec, propertyName, value);\n");
                push(@implContent, "    return;\n");
                push(@implContent, "}\n\n");
            }

            if ($hasReadWriteProperties) {
                foreach my $attribute (@{$dataNode->attributes}) {
                    if ($attribute->type !~ /^readonly/) {
                        my $name = $attribute->signature->name;
                        my $type = $codeGenerator->StripModule($attribute->signature->type);
                        my $putFunctionName = GetAttributeSetterName($interfaceName, $className, $attribute);
                        my $implSetterFunctionName = $codeGenerator->WK_ucfirst($name);

                        my $attributeConditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
                        push(@implContent, "#if ${attributeConditionalString}\n") if $attributeConditionalString;

                        push(@implContent, "void ${putFunctionName}(ExecState* exec, JSObject*");
                        push(@implContent, " thisObject") if !$attribute->isStatic;
                        push(@implContent, ", JSValue value)\n");
                        push(@implContent, "{\n");

                            push(@implContent, "    UNUSED_PARAM(exec);\n");

                            if ($dataNode->extendedAttributes->{"CheckSecurity"} && !$attribute->signature->extendedAttributes->{"DoNotCheckSecurity"}) {
                                if ($interfaceName eq "DOMWindow") {
                                    push(@implContent, "    if (!jsCast<$className*>(thisObject)->allowsAccessFrom(exec))\n");
                                } else {
                                    push(@implContent, "    if (!shouldAllowAccessToFrame(exec, jsCast<$className*>(thisObject)->impl()->frame()))\n");
                                }
                                push(@implContent, "        return;\n");
                            }

                            if ($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCustom"} || $attribute->signature->extendedAttributes->{"CustomSetter"} || $attribute->signature->extendedAttributes->{"JSCustomSetter"}) {
                                push(@implContent, "    jsCast<$className*>(thisObject)->set$implSetterFunctionName(exec, value);\n");
                            } elsif ($type eq "EventListener") {
                                $implIncludes{"JSEventListener.h"} = 1;
                                push(@implContent, "    UNUSED_PARAM(exec);\n");
                                push(@implContent, "    ${className}* castedThis = jsCast<${className}*>(thisObject);\n");
                                my $windowEventListener = $attribute->signature->extendedAttributes->{"JSWindowEventListener"};
                                if ($windowEventListener) {
                                    push(@implContent, "    JSDOMGlobalObject* globalObject = castedThis->globalObject();\n");
                                }
                                push(@implContent, "    $implClassName* impl = static_cast<$implClassName*>(castedThis->impl());\n");
                                if ((($interfaceName eq "DOMWindow") or ($interfaceName eq "WorkerContext")) and $name eq "onerror") {
                                    $implIncludes{"JSErrorHandler.h"} = 1;
                                    push(@implContent, "    impl->set$implSetterFunctionName(createJSErrorHandler(exec, value, thisObject));\n");
                                } else {
                                    push(@implContent, GenerateAttributeEventListenerCall($className, $implSetterFunctionName, $windowEventListener));
                                }
                            } elsif ($attribute->signature->type =~ /Constructor$/) {
                                my $constructorType = $attribute->signature->type;
                                $constructorType =~ s/Constructor$//;
                                # $constructorType ~= /Constructor$/ indicates that it is NamedConstructor.
                                # We do not generate the header file for NamedConstructor of class XXXX,
                                # since we generate the NamedConstructor declaration into the header file of class XXXX.
                                if ($constructorType ne "DOMObject" and $constructorType !~ /Constructor$/) {
                                    AddToImplIncludes("JS" . $constructorType . ".h", $attribute->signature->extendedAttributes->{"Conditional"});
                                }
                                push(@implContent, "    // Shadowing a built-in constructor\n");
                                if ($interfaceName eq "DOMWindow" && $className eq "JSblah") {
                                    # FIXME: This branch never executes and should be removed.
                                    push(@implContent, "    jsCast<$className*>(thisObject)->putDirect(exec->globalData(), exec->propertyNames().constructor, value);\n");
                                } else {
                                    push(@implContent, "    jsCast<$className*>(thisObject)->putDirect(exec->globalData(), Identifier(exec, \"$name\"), value);\n");
                                }
                            } elsif ($attribute->signature->extendedAttributes->{"Replaceable"}) {
                                push(@implContent, "    // Shadowing a built-in object\n");
                                push(@implContent, "    jsCast<$className*>(thisObject)->putDirect(exec->globalData(), Identifier(exec, \"$name\"), value);\n");
                            } else {
                                if (!$attribute->isStatic) {
                                    push(@implContent, "    $className* castedThis = jsCast<$className*>(thisObject);\n");
                                    push(@implContent, "    $implType* impl = static_cast<$implType*>(castedThis->impl());\n");
                                }
                                push(@implContent, "    ExceptionCode ec = 0;\n") if @{$attribute->setterExceptions};

                                # If the "StrictTypeChecking" extended attribute is present, and the attribute's type is an
                                # interface type, then if the incoming value does not implement that interface, a TypeError
                                # is thrown rather than silently passing NULL to the C++ code.
                                # Per the Web IDL and ECMAScript specifications, incoming values can always be converted to
                                # both strings and numbers, so do not throw TypeError if the attribute is of these types.
                                if ($attribute->signature->extendedAttributes->{"StrictTypeChecking"}) {
                                    $implIncludes{"<runtime/Error.h>"} = 1;

                                    my $argType = $attribute->signature->type;
                                    if (!IsNativeType($argType)) {
                                        push(@implContent, "    if (!value.isUndefinedOrNull() && !value.inherits(&JS${argType}::s_info)) {\n");
                                        push(@implContent, "        throwVMTypeError(exec);\n");
                                        push(@implContent, "        return;\n");
                                        push(@implContent, "    };\n");
                                    }
                                }

                                my $nativeValue = JSValueToNative($attribute->signature, "value");
                                if ($svgPropertyOrListPropertyType) {
                                    if ($svgPropertyType) {
                                        push(@implContent, "    if (impl->role() == AnimValRole) {\n");
                                        push(@implContent, "        setDOMException(exec, NO_MODIFICATION_ALLOWED_ERR);\n");
                                        push(@implContent, "        return;\n");
                                        push(@implContent, "    }\n");
                                        $implIncludes{"ExceptionCode.h"} = 1;
                                    }
                                    push(@implContent, "    $svgPropertyOrListPropertyType& podImpl = impl->propertyReference();\n");
                                    if ($svgPropertyOrListPropertyType eq "float") { # Special case for JSSVGNumber
                                        push(@implContent, "    podImpl = $nativeValue;\n");
                                    } else {
                                        push(@implContent, "    podImpl.set$implSetterFunctionName($nativeValue");
                                        push(@implContent, ", ec") if @{$attribute->setterExceptions};
                                        push(@implContent, ");\n");
                                        push(@implContent, "    setDOMException(exec, ec);\n") if @{$attribute->setterExceptions};
                                    }
                                    if ($svgPropertyType) {
                                        if (@{$attribute->setterExceptions}) {
                                            push(@implContent, "    if (!ec)\n");
                                            push(@implContent, "        impl->commitChange();\n");
                                        } else {
                                            push(@implContent, "    impl->commitChange();\n");
                                        }
                                    }
                                } else {
                                    my ($functionName, @arguments) = $codeGenerator->SetterExpression(\%implIncludes, $interfaceName, $attribute);
                                    push(@arguments, $nativeValue);
                                    if ($attribute->signature->extendedAttributes->{"ImplementedBy"}) {
                                        my $implementedBy = $attribute->signature->extendedAttributes->{"ImplementedBy"};
                                        $implIncludes{"${implementedBy}.h"} = 1;
                                        unshift(@arguments, "impl");
                                        $functionName = "${implementedBy}::${functionName}";
                                    } elsif ($attribute->isStatic) {
                                        $functionName = "${implClassName}::${functionName}";
                                    } else {
                                        $functionName = "impl->${functionName}";
                                    }

                                    unshift(@arguments, GenerateCallWith($attribute->signature->extendedAttributes->{"CallWith"}, \@implContent, ""));

                                    push(@arguments, "ec") if @{$attribute->setterExceptions};
                                    push(@implContent, "    ${functionName}(" . join(", ", @arguments) . ");\n");
                                    push(@implContent, "    setDOMException(exec, ec);\n") if @{$attribute->setterExceptions};
                                }
                            }

                        push(@implContent, "}\n\n");
                        push(@implContent, "#endif\n") if $attributeConditionalString;
                        push(@implContent, "\n");
                    }
                }
            }

            if ($dataNode->extendedAttributes->{"ReplaceableConstructor"}) {
                my $constructorFunctionName = "setJS" . $interfaceName . "Constructor";

                push(@implContent, "void ${constructorFunctionName}(ExecState* exec, JSObject* thisObject, JSValue value)\n");
                push(@implContent, "{\n");
                if ($dataNode->extendedAttributes->{"CheckSecurity"}) {
                    if ($interfaceName eq "DOMWindow") {
                        push(@implContent, "    if (!jsCast<$className*>(thisObject)->allowsAccessFrom(exec))\n");
                    } else {
                        push(@implContent, "    if (!shouldAllowAccessToFrame(exec, jsCast<$className*>(thisObject)->impl()->frame()))\n");
                    }
                    push(@implContent, "        return;\n");
                }

                push(@implContent, "    // Shadowing a built-in constructor\n");

                if ($interfaceName eq "DOMWindow") {
                    push(@implContent, "    jsCast<$className*>(thisObject)->putDirect(exec->globalData(), exec->propertyNames().constructor, value);\n");
                } else {
                    die "No way to handle interface with ReplaceableConstructor extended attribute: $interfaceName";
                }
                push(@implContent, "}\n\n");
            }        
        }
    }

    if (($dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"}) && !$dataNode->extendedAttributes->{"CustomEnumerateProperty"}) {
        push(@implContent, "void ${className}::getOwnPropertyNames(JSObject* object, ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)\n");
        push(@implContent, "{\n");
        push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(object);\n");
        push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
        if ($dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
            push(@implContent, "    for (unsigned i = 0; i < static_cast<${implClassName}*>(thisObject->impl())->length(); ++i)\n");
            push(@implContent, "        propertyNames.add(Identifier::from(exec, i));\n");
        }
        push(@implContent, "     Base::getOwnPropertyNames(thisObject, exec, propertyNames, mode);\n");
        push(@implContent, "}\n\n");
    }

    if (!$dataNode->extendedAttributes->{"OmitConstructor"}) {
        push(@implContent, "JSValue ${className}::getConstructor(ExecState* exec, JSGlobalObject* globalObject)\n{\n");
        push(@implContent, "    return getDOMConstructor<${className}Constructor>(exec, jsCast<JSDOMGlobalObject*>(globalObject));\n");
        push(@implContent, "}\n\n");
    }

    # Functions
    if ($numFunctions > 0) {
        foreach my $function (@{$dataNode->functions}) {
            AddIncludesForTypeInImpl($function->signature->type);

            my $isCustom = $function->signature->extendedAttributes->{"Custom"} || $function->signature->extendedAttributes->{"JSCustom"};
            my $isOverloaded = $function->{overloads} && @{$function->{overloads}} > 1;

            next if $isCustom && $isOverloaded && $function->{overloadIndex} > 1;

            my $functionName = GetFunctionName($className, $function);

            my $conditional = $function->signature->extendedAttributes->{"Conditional"};
            if ($conditional) {
                my $conditionalString = $codeGenerator->GenerateConditionalStringFromAttributeValue($conditional);
                push(@implContent, "#if ${conditionalString}\n");
            }


            if (!$isCustom && $isOverloaded) {
                # Append a number to an overloaded method's name to make it unique:
                $functionName = $functionName . $function->{overloadIndex};
                # Make this function static to avoid compiler warnings, since we
                # don't generate a prototype for it in the header.
                push(@implContent, "static ");
            }

            my $functionImplementationName = $function->signature->extendedAttributes->{"ImplementedAs"} || $codeGenerator->WK_lcfirst($function->signature->name);

            push(@implContent, "EncodedJSValue JSC_HOST_CALL ${functionName}(ExecState* exec)\n");
            push(@implContent, "{\n");

            $implIncludes{"<runtime/Error.h>"} = 1;

            if ($function->isStatic) {
                if ($isCustom) {
                    GenerateArgumentsCountCheck(\@implContent, $function, $dataNode);
                    push(@implContent, "    return JSValue::encode(${className}::" . $functionImplementationName . "(exec));\n");
                } else {
                    GenerateArgumentsCountCheck(\@implContent, $function, $dataNode);

                    if (@{$function->raisesExceptions}) {
                        push(@implContent, "    ExceptionCode ec = 0;\n");
                    }

                    my $numParameters = @{$function->parameters};
                    my ($functionString, $dummy) = GenerateParametersCheck(\@implContent, $function, $dataNode, $numParameters, $implClassName, $functionImplementationName, $svgPropertyType, $svgPropertyOrListPropertyType, $svgListPropertyType);
                    GenerateImplementationFunctionCall($function, $functionString, "    ", $svgPropertyType, $implClassName);
                }
            } else {
                if ($interfaceName eq "DOMWindow") {
                    push(@implContent, "    $className* castedThis = toJSDOMWindow(exec->hostThisValue().toThisObject(exec));\n");
                    push(@implContent, "    if (!castedThis)\n");
                    push(@implContent, "        return throwVMTypeError(exec);\n");
                } elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
                    push(@implContent, "    $className* castedThis = to${className}(exec->hostThisValue().toThisObject(exec));\n");
                    push(@implContent, "    if (!castedThis)\n");
                    push(@implContent, "        return throwVMTypeError(exec);\n");
                } else {
                    push(@implContent, "    JSValue thisValue = exec->hostThisValue();\n");
                    push(@implContent, "    if (!thisValue.inherits(&${className}::s_info))\n");
                    push(@implContent, "        return throwVMTypeError(exec);\n");
                    push(@implContent, "    $className* castedThis = jsCast<$className*>(asObject(thisValue));\n");
                }

                push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(castedThis, &${className}::s_info);\n");

                if ($dataNode->extendedAttributes->{"CheckSecurity"} and
                    !$function->signature->extendedAttributes->{"DoNotCheckSecurity"}) {
                    push(@implContent, "    if (!castedThis->allowsAccessFrom(exec))\n");
                    push(@implContent, "        return JSValue::encode(jsUndefined());\n");
                }

                if ($isCustom) {
                    push(@implContent, "    return JSValue::encode(castedThis->" . $functionImplementationName . "(exec));\n");
                } else {
                    push(@implContent, "    $implType* impl = static_cast<$implType*>(castedThis->impl());\n");
                    if ($svgPropertyType) {
                        push(@implContent, "    if (impl->role() == AnimValRole) {\n");
                        push(@implContent, "        setDOMException(exec, NO_MODIFICATION_ALLOWED_ERR);\n");
                        push(@implContent, "        return JSValue::encode(jsUndefined());\n");
                        push(@implContent, "    }\n");
                        push(@implContent, "    $svgPropertyType& podImpl = impl->propertyReference();\n");
                        $implIncludes{"ExceptionCode.h"} = 1;
                    }

                    # For compatibility with legacy content, the EventListener calls are generated without GenerateArgumentsCountCheck.
                    if ($function->signature->name eq "addEventListener") {
                        push(@implContent, GenerateEventListenerCall($className, "add"));
                    } elsif ($function->signature->name eq "removeEventListener") {
                        push(@implContent, GenerateEventListenerCall($className, "remove"));
                    } else {
                        GenerateArgumentsCountCheck(\@implContent, $function, $dataNode);

                        if (@{$function->raisesExceptions}) {
                            push(@implContent, "    ExceptionCode ec = 0;\n");
                        }

                        if ($function->signature->extendedAttributes->{"CheckSecurityForNode"}) {
                            push(@implContent, "    if (!shouldAllowAccessToNode(exec, impl->" . $function->signature->name . "(" . (@{$function->raisesExceptions} ? "ec" : "") .")))\n");
                            push(@implContent, "        return JSValue::encode(jsNull());\n");
                            $implIncludes{"JSDOMBinding.h"} = 1;
                        }

                        my $numParameters = @{$function->parameters};
                        my ($functionString, $dummy) = GenerateParametersCheck(\@implContent, $function, $dataNode, $numParameters, $implClassName, $functionImplementationName, $svgPropertyType, $svgPropertyOrListPropertyType, $svgListPropertyType);
                        GenerateImplementationFunctionCall($function, $functionString, "    ", $svgPropertyType, $implClassName);
                    }
                }
            }

            push(@implContent, "}\n\n");

            if (!$isCustom && $isOverloaded && $function->{overloadIndex} == @{$function->{overloads}}) {
                # Generate a function dispatching call to the rest of the overloads.
                GenerateOverloadedFunction($function, $dataNode, $implClassName);
            }

            push(@implContent, "#endif\n\n") if $conditional;
        }
    }

    if ($numFunctions > 0 || $numCachedAttributes > 0) {
        if ($needsMarkChildren && !$dataNode->extendedAttributes->{"JSCustomMarkFunction"}) {
            push(@implContent, "void ${className}::visitChildren(JSCell* cell, SlotVisitor& visitor)\n");
            push(@implContent, "{\n");
            push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
            push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
            push(@implContent, "    COMPILE_ASSERT(StructureFlags & OverridesVisitChildren, OverridesVisitChildrenWithoutSettingFlag);\n");
            push(@implContent, "    ASSERT(thisObject->structure()->typeInfo().overridesVisitChildren());\n");
            push(@implContent, "    Base::visitChildren(thisObject, visitor);\n");
            if ($dataNode->extendedAttributes->{"EventTarget"}) {
                push(@implContent, "    thisObject->impl()->visitJSEventListeners(visitor);\n");
            }
            if ($numCachedAttributes > 0) {
                foreach (@{$dataNode->attributes}) {
                    my $attribute = $_;
                    if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) {
                        push(@implContent, "    if (thisObject->m_" . $attribute->signature->name . ")\n");
                        push(@implContent, "        visitor.append(&thisObject->m_" . $attribute->signature->name . ");\n");
                    }
                }
            }
            push(@implContent, "}\n\n");
        }
    }

    # Cached attributes are indeed allowed when there is a custom mark/visitChildren function.
    # The custom function must make sure to account for the cached attribute.
    # Uncomment the below line to temporarily enforce generated mark functions when cached attributes are present.
    # die "Can't generate binding for class with cached attribute and custom mark." if (($numCachedAttributes > 0) and ($dataNode->extendedAttributes->{"JSCustomMarkFunction"}));

    if ($numConstants > 0) {
        push(@implContent, "// Constant getters\n\n");

        foreach my $constant (@{$dataNode->constants}) {
            my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($constant->name);
            my $conditional = $constant->extendedAttributes->{"Conditional"};

            if ($conditional) {
                my $conditionalString = $codeGenerator->GenerateConditionalStringFromAttributeValue($conditional);
                push(@implContent, "#if ${conditionalString}\n");
            }

            # FIXME: this casts into int to match our previous behavior which turned 0xFFFFFFFF in -1 for NodeFilter.SHOW_ALL
            push(@implContent, "JSValue ${getter}(ExecState* exec, JSValue, const Identifier&)\n");
            push(@implContent, "{\n");
            if ($constant->type eq "DOMString") {
                push(@implContent, "    return jsStringOrNull(exec, String(" . $constant->value . "));\n");
            } else {
                push(@implContent, "    UNUSED_PARAM(exec);\n");
                push(@implContent, "    return jsNumber(static_cast<int>(" . $constant->value . "));\n");
            }
            push(@implContent, "}\n\n");
            push(@implContent, "#endif\n") if $conditional;
        }
    }

    if ($dataNode->extendedAttributes->{"IndexedGetter"}) {
        push(@implContent, "\nJSValue ${className}::indexGetter(ExecState* exec, JSValue slotBase, unsigned index)\n");
        push(@implContent, "{\n");
        push(@implContent, "    ${className}* thisObj = jsCast<$className*>(asObject(slotBase));\n");
        push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObj, &s_info);\n");
        if (IndexGetterReturnsStrings($implClassName)) {
            $implIncludes{"KURL.h"} = 1;
            push(@implContent, "    return jsStringOrNull(exec, thisObj->impl()->item(index));\n");
        } else {
            push(@implContent, "    return toJS(exec, thisObj->globalObject(), static_cast<$implClassName*>(thisObj->impl())->item(index));\n");
        }
        push(@implContent, "}\n\n");
        if ($interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection") {
            $implIncludes{"JSNode.h"} = 1;
            $implIncludes{"Node.h"} = 1;
        }
    }

    if ($dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
        push(@implContent, "\nJSValue ${className}::getByIndex(ExecState*, unsigned index)\n");
        push(@implContent, "{\n");
        push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(this, &s_info);\n");
        push(@implContent, "    double result = static_cast<$implClassName*>(impl())->item(index);\n");
        # jsNumber conversion doesn't suppress signalling NaNs, so enforce that here.
        push(@implContent, "    if (isnan(result))\n");
        push(@implContent, "        return jsNaN();\n");
        push(@implContent, "    return JSValue(result);\n");
        push(@implContent, "}\n\n");
        if ($interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection") {
            $implIncludes{"JSNode.h"} = 1;
            $implIncludes{"Node.h"} = 1;
        }
    }

    if ($interfaceName eq "HTMLPropertiesCollection") {
        if ($dataNode->extendedAttributes->{"NamedGetter"}) {
            push(@implContent, "bool ${className}::canGetItemsForName(ExecState*, $implClassName* collection, const Identifier& propertyName)\n");
            push(@implContent, "{\n");
            push(@implContent, "    return collection->hasNamedItem(identifierToAtomicString(propertyName));\n");
            push(@implContent, "}\n\n");
            push(@implContent, "JSValue ${className}::nameGetter(ExecState* exec, JSValue slotBase, const Identifier& propertyName)\n");
            push(@implContent, "{\n");
            push(@implContent, "    ${className}* thisObj = jsCast<$className*>(asObject(slotBase));\n");
            push(@implContent, "    return toJS(exec, thisObj->globalObject(), static_cast<$implClassName*>(thisObj->impl())->namedItem(identifierToAtomicString(propertyName)));\n");
            push(@implContent, "}\n\n");
        }
    }

    if ((!$hasParent && !$dataNode->extendedAttributes->{"JSCustomIsReachable"})|| $dataNode->extendedAttributes->{"JSGenerateIsReachable"} || $dataNode->extendedAttributes->{"ActiveDOMObject"}) {
        push(@implContent, "static inline bool isObservable(JS${implClassName}* js${implClassName})\n");
        push(@implContent, "{\n");
        push(@implContent, "    if (js${implClassName}->hasCustomProperties())\n");
        push(@implContent, "        return true;\n");
        if ($eventTarget) {
            push(@implContent, "    if (js${implClassName}->impl()->hasEventListeners())\n");
            push(@implContent, "        return true;\n");
        }
        push(@implContent, "    return false;\n");
        push(@implContent, "}\n\n");

        push(@implContent, "bool JS${implClassName}Owner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor)\n");
        push(@implContent, "{\n");
        push(@implContent, "    JS${implClassName}* js${implClassName} = jsCast<JS${implClassName}*>(handle.get().asCell());\n");
        # All ActiveDOMObjects implement hasPendingActivity(), but not all of them
        # increment their C++ reference counts when hasPendingActivity() becomes
        # true. As a result, ActiveDOMObjects can be prematurely destroyed before
        # their pending activities complete. To wallpaper over this bug, JavaScript
        # wrappers unconditionally keep ActiveDOMObjects with pending activity alive.
        # FIXME: Fix this lifetime issue in the DOM, and move this hasPendingActivity
        # check below the isObservable check.
        if ($dataNode->extendedAttributes->{"ActiveDOMObject"}) {
            push(@implContent, "    if (js${implClassName}->impl()->hasPendingActivity())\n");
            push(@implContent, "        return true;\n");
        }
        push(@implContent, "    if (!isObservable(js${implClassName}))\n");
        push(@implContent, "        return false;\n");
        if ($dataNode->extendedAttributes->{"JSGenerateIsReachable"}) {
            my $rootString;
            if ($dataNode->extendedAttributes->{"JSGenerateIsReachable"} eq "Impl") {
                $rootString  = "    ${implType}* root = js${implClassName}->impl();\n";
            } elsif ($dataNode->extendedAttributes->{"JSGenerateIsReachable"} eq "ImplContext") {
                $rootString  = "    WebGLRenderingContext* root = js${implClassName}->impl()->context();\n";
            } elsif ($dataNode->extendedAttributes->{"JSGenerateIsReachable"} eq "ImplFrame") {
                $rootString  = "    Frame* root = js${implClassName}->impl()->frame();\n";
                $rootString .= "    if (!root)\n";
                $rootString .= "        return false;\n";
            } elsif ($dataNode->extendedAttributes->{"JSGenerateIsReachable"} eq "ImplDocument") {
                $rootString  = "    Document* root = js${implClassName}->impl()->document();\n";
                $rootString .= "    if (!root)\n";
                $rootString .= "        return false;\n";
            } elsif ($dataNode->extendedAttributes->{"JSGenerateIsReachable"} eq "ImplElementRoot") {
                $rootString  = "    Element* element = js${implClassName}->impl()->element();\n";
                $rootString .= "    if (!element)\n";
                $rootString .= "        return false;\n";
                $rootString .= "    void* root = WebCore::root(element);\n";
            } elsif ($interfaceName eq "CanvasRenderingContext") {
                $rootString  = "    void* root = WebCore::root(js${implClassName}->impl()->canvas());\n";
            } elsif ($interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection") {
                $rootString  = "    void* root = WebCore::root(js${implClassName}->impl()->base());\n";
            } else {
                $rootString  = "    void* root = WebCore::root(js${implClassName}->impl());\n";
            }

            push(@implContent, $rootString);
            push(@implContent, "    return visitor.containsOpaqueRoot(root);\n");
        } else {
            push(@implContent, "    UNUSED_PARAM(visitor);\n");
            push(@implContent, "    return false;\n");
        }
        push(@implContent, "}\n\n");
    }

    if (!$dataNode->extendedAttributes->{"JSCustomFinalize"} &&
        (!$hasParent ||
         $dataNode->extendedAttributes->{"JSGenerateIsReachable"} ||
         $dataNode->extendedAttributes->{"JSCustomIsReachable"} ||
         $dataNode->extendedAttributes->{"ActiveDOMObject"})) {
        push(@implContent, "void JS${implClassName}Owner::finalize(JSC::Handle<JSC::Unknown> handle, void* context)\n");
        push(@implContent, "{\n");
        push(@implContent, "    JS${implClassName}* js${implClassName} = jsCast<JS${implClassName}*>(handle.get().asCell());\n");
        push(@implContent, "    DOMWrapperWorld* world = static_cast<DOMWrapperWorld*>(context);\n");
        push(@implContent, "    uncacheWrapper(world, js${implClassName}->impl(), js${implClassName});\n");
        push(@implContent, "    js${implClassName}->releaseImpl();\n");
        push(@implContent, "}\n\n");
    }

    if ((!$hasParent or $dataNode->extendedAttributes->{"JSGenerateToJSObject"}) and !($dataNode->extendedAttributes->{"CustomToJSObject"} or $dataNode->extendedAttributes->{"JSCustomToJSObject"})) {
        push(@implContent, "JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, $implType* impl)\n");
        push(@implContent, "{\n");
        if ($svgPropertyType) {
            push(@implContent, "    return wrap<$className, $implType>(exec, globalObject, impl);\n");
        } else {
            push(@implContent, "    return wrap<$className>(exec, globalObject, impl);\n");
        }
        push(@implContent, "}\n\n");
    }

    if ((!$hasParent or $dataNode->extendedAttributes->{"JSGenerateToNativeObject"}) and !$dataNode->extendedAttributes->{"JSCustomToNativeObject"}) {
        push(@implContent, "$implType* to${interfaceName}(JSC::JSValue value)\n");
        push(@implContent, "{\n");
        push(@implContent, "    return value.inherits(&${className}::s_info) ? jsCast<$className*>(asObject(value))->impl() : 0");
        push(@implContent, ";\n}\n");
    }

    push(@implContent, "\n}\n");

    my $conditionalString = $codeGenerator->GenerateConditionalString($dataNode);
    push(@implContent, "\n#endif // ${conditionalString}\n") if $conditionalString;
}

sub GenerateCallWith
{
    my $callWith = shift;
    return () unless $callWith;
    my $outputArray = shift;
    my $returnValue = shift;
    my $function = shift;

    my @callWithArgs;
    if ($codeGenerator->ExtendedAttributeContains($callWith, "ScriptState")) {
        push(@callWithArgs, "exec");
    }
    if ($codeGenerator->ExtendedAttributeContains($callWith, "ScriptExecutionContext")) {
        push(@$outputArray, "    ScriptExecutionContext* scriptContext = jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject())->scriptExecutionContext();\n");
        push(@$outputArray, "    if (!scriptContext)\n");
        push(@$outputArray, "        return" . ($returnValue ? " " . $returnValue : "") . ";\n");
        push(@callWithArgs, "scriptContext");
    }
    if ($function and $codeGenerator->ExtendedAttributeContains($callWith, "ScriptArguments")) {
        push(@$outputArray, "    RefPtr<ScriptArguments> scriptArguments(createScriptArguments(exec, " . @{$function->parameters} . "));\n");
        $implIncludes{"ScriptArguments.h"} = 1;
        push(@callWithArgs, "scriptArguments");
    }
    if ($codeGenerator->ExtendedAttributeContains($callWith, "CallStack")) {
        push(@$outputArray, "    RefPtr<ScriptCallStack> callStack(createScriptCallStackForInspector(exec));\n");
        $implIncludes{"ScriptCallStack.h"} = 1;
        $implIncludes{"ScriptCallStackFactory.h"} = 1;
        push(@callWithArgs, "callStack");
    }
    return @callWithArgs;
}

sub GenerateArgumentsCountCheck
{
    my $outputArray = shift;
    my $function = shift;
    my $dataNode = shift;

    my $numMandatoryParams = @{$function->parameters};
    foreach my $param (reverse(@{$function->parameters})) {
        if ($param->extendedAttributes->{"Optional"}) {
            $numMandatoryParams--;
        } else {
            last;
        }
    }
    if ($numMandatoryParams >= 1)
    {
        push(@$outputArray, "    if (exec->argumentCount() < $numMandatoryParams)\n");
        push(@$outputArray, "        return throwVMError(exec, createNotEnoughArgumentsError(exec));\n");
    }
}

sub GenerateParametersCheck
{
    my $outputArray = shift;
    my $function = shift;
    my $dataNode = shift;
    my $numParameters = shift;
    my $implClassName = shift;
    my $functionImplementationName = shift;
    my $svgPropertyType = shift;
    my $svgPropertyOrListPropertyType = shift;
    my $svgListPropertyType = shift;

    my $argsIndex = 0;
    my $hasOptionalArguments = 0;

    my @arguments;
    my $functionName;
    my $implementedBy = $function->signature->extendedAttributes->{"ImplementedBy"};
    if ($implementedBy) {
        AddToImplIncludes("${implementedBy}.h");
        unshift(@arguments, "impl") if !$function->isStatic;
        $functionName = "${implementedBy}::${functionImplementationName}";
    } elsif ($function->isStatic) {
        $functionName = "${implClassName}::${functionImplementationName}";
    } elsif ($svgPropertyOrListPropertyType and !$svgListPropertyType) {
        $functionName = "podImpl.${functionImplementationName}";
    } else {
        $functionName = "impl->${functionImplementationName}";
    }

    if (!$function->signature->extendedAttributes->{"Constructor"}) {
        push(@arguments, GenerateCallWith($function->signature->extendedAttributes->{"CallWith"}, \@$outputArray, "JSValue::encode(jsUndefined())", $function));
    }

    $implIncludes{"ExceptionCode.h"} = 1;
    $implIncludes{"JSDOMBinding.h"} = 1;

    foreach my $parameter (@{$function->parameters}) {
        # Optional arguments with [Optional] should generate an early call with fewer arguments.
        # Optional arguments with [Optional=...] should not generate the early call.
        my $optional = $parameter->extendedAttributes->{"Optional"};
        if ($optional && $optional ne "DefaultIsUndefined" && $optional ne "DefaultIsNullString" && !$parameter->extendedAttributes->{"Callback"}) {
            # Generate early call if there are enough parameters.
            if (!$hasOptionalArguments) {
                push(@$outputArray, "\n    size_t argsCount = exec->argumentCount();\n");
                $hasOptionalArguments = 1;
            }
            push(@$outputArray, "    if (argsCount <= $argsIndex) {\n");

            my @optionalCallbackArguments = @arguments;
            if (@{$function->raisesExceptions}) {
                push @optionalCallbackArguments, "ec";
            }
            my $functionString = "$functionName(" . join(", ", @optionalCallbackArguments) . ")";
            GenerateImplementationFunctionCall($function, $functionString, "    " x 2, $svgPropertyType, $implClassName);
            push(@$outputArray, "    }\n\n");
        }

        my $name = $parameter->name;
        my $argType = $codeGenerator->StripModule($parameter->type);

        if ($argType eq "XPathNSResolver") {
            push(@$outputArray, "    RefPtr<XPathNSResolver> customResolver;\n");
            push(@$outputArray, "    XPathNSResolver* resolver = toXPathNSResolver(exec->argument($argsIndex));\n");
            push(@$outputArray, "    if (!resolver) {\n");
            push(@$outputArray, "        customResolver = JSCustomXPathNSResolver::create(exec, exec->argument($argsIndex));\n");
            push(@$outputArray, "        if (exec->hadException())\n");
            push(@$outputArray, "            return JSValue::encode(jsUndefined());\n");
            push(@$outputArray, "        resolver = customResolver.get();\n");
            push(@$outputArray, "    }\n");
        } elsif ($parameter->extendedAttributes->{"Callback"}) {
            my $callbackClassName = GetCallbackClassName($argType);
            $implIncludes{"$callbackClassName.h"} = 1;
            if ($optional) {
                push(@$outputArray, "    RefPtr<$argType> $name;\n");
                push(@$outputArray, "    if (exec->argumentCount() > $argsIndex && !exec->argument($argsIndex).isUndefinedOrNull()) {\n");
                push(@$outputArray, "        if (!exec->argument($argsIndex).isFunction()) {\n");
                push(@$outputArray, "            setDOMException(exec, TYPE_MISMATCH_ERR);\n");
                push(@$outputArray, "            return JSValue::encode(jsUndefined());\n");
                push(@$outputArray, "        }\n");
                push(@$outputArray, "        $name = ${callbackClassName}::create(asObject(exec->argument($argsIndex)), castedThis->globalObject());\n");
                push(@$outputArray, "    }\n");
            } else {
                push(@$outputArray, "    if (exec->argumentCount() <= $argsIndex || !exec->argument($argsIndex).isFunction()) {\n");
                push(@$outputArray, "        setDOMException(exec, TYPE_MISMATCH_ERR);\n");
                push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
                push(@$outputArray, "    }\n");
                push(@$outputArray, "    RefPtr<$argType> $name = ${callbackClassName}::create(asObject(exec->argument($argsIndex)), castedThis->globalObject());\n");
            }
        } else {
            # If the "StrictTypeChecking" extended attribute is present, and the argument's type is an
            # interface type, then if the incoming value does not implement that interface, a TypeError
            # is thrown rather than silently passing NULL to the C++ code.
            # Per the Web IDL and ECMAScript semantics, incoming values can always be converted to both
            # strings and numbers, so do not throw TypeError if the argument is of these types.
            if ($function->signature->extendedAttributes->{"StrictTypeChecking"}) {
                $implIncludes{"<runtime/Error.h>"} = 1;

                my $argValue = "exec->argument($argsIndex)";
                if (!IsNativeType($argType)) {
                    push(@$outputArray, "    if (exec->argumentCount() > $argsIndex && !${argValue}.isUndefinedOrNull() && !${argValue}.inherits(&JS${argType}::s_info))\n");
                    push(@$outputArray, "        return throwVMTypeError(exec);\n");
                }
            }

            my $parameterDefaultPolicy = "DefaultIsUndefined";
            if ($optional and $optional eq "DefaultIsNullString") {
                $parameterDefaultPolicy = "DefaultIsNullString";
            }

            push(@$outputArray, "    " . GetNativeTypeFromSignature($parameter) . " $name(" . JSValueToNative($parameter, "MAYBE_MISSING_PARAMETER(exec, $argsIndex, $parameterDefaultPolicy)") . ");\n");

            # If a parameter is "an index" and it's negative it should throw an INDEX_SIZE_ERR exception.
            # But this needs to be done in the bindings, because the type is unsigned and the fact that it
            # was negative will be lost by the time we're inside the DOM.
            if ($parameter->extendedAttributes->{"IsIndex"}) {
                push(@$outputArray, "    if ($name < 0) {\n");
                push(@$outputArray, "        setDOMException(exec, INDEX_SIZE_ERR);\n");
                push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
                push(@$outputArray, "    }\n");
            }

            # Check if the type conversion succeeded.
            push(@$outputArray, "    if (exec->hadException())\n");
            push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");

            if ($codeGenerator->IsSVGTypeNeedingTearOff($argType) and not $implClassName =~ /List$/) {
                push(@$outputArray, "    if (!$name) {\n");
                push(@$outputArray, "        setDOMException(exec, TYPE_MISMATCH_ERR);\n");
                push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
                push(@$outputArray, "    }\n");
            }
        }

        if ($argType eq "NodeFilter") {
            push @arguments, "$name.get()";
        } elsif ($codeGenerator->IsSVGTypeNeedingTearOff($argType) and not $implClassName =~ /List$/) {
            push @arguments, "$name->propertyReference()";
        } else {
            push @arguments, $name;
        }
        $argsIndex++;
    }

    if (@{$function->raisesExceptions}) {
        push @arguments, "ec";
    }
    return ("$functionName(" . join(", ", @arguments) . ")", scalar @arguments);
}

sub GenerateCallbackHeader
{
    my $object = shift;
    my $dataNode = shift;

    my $interfaceName = $dataNode->name;
    my $className = "JS$interfaceName";

    # - Add default header template and header protection
    push(@headerContentHeader, GenerateHeaderContentHeader($dataNode));

    $headerIncludes{"ActiveDOMCallback.h"} = 1;
    $headerIncludes{"$interfaceName.h"} = 1;
    $headerIncludes{"JSCallbackData.h"} = 1;
    $headerIncludes{"<wtf/Forward.h>"} = 1;

    push(@headerContent, "\nnamespace WebCore {\n\n");
    push(@headerContent, "class $className : public $interfaceName, public ActiveDOMCallback {\n");
    push(@headerContent, "public:\n");

    # The static create() method.
    push(@headerContent, "    static PassRefPtr<$className> create(JSC::JSObject* callback, JSDOMGlobalObject* globalObject)\n");
    push(@headerContent, "    {\n");
    push(@headerContent, "        return adoptRef(new $className(callback, globalObject));\n");
    push(@headerContent, "    }\n\n");

    # Destructor
    push(@headerContent, "    virtual ~$className();\n");

    # Functions
    my $numFunctions = @{$dataNode->functions};
    if ($numFunctions > 0) {
        push(@headerContent, "\n    // Functions\n");
        foreach my $function (@{$dataNode->functions}) {
            my @params = @{$function->parameters};
            if (!$function->signature->extendedAttributes->{"Custom"} &&
                !(GetNativeType($function->signature->type) eq "bool")) {
                push(@headerContent, "    COMPILE_ASSERT(false)");
            }

            push(@headerContent, "    virtual " . GetNativeType($function->signature->type) . " " . $function->signature->name . "(");

            my @args = ();
            foreach my $param (@params) {
                push(@args, GetNativeType($param->type) . " " . $param->name);
            }
            push(@headerContent, join(", ", @args));

            push(@headerContent, ");\n");
        }
    }

    push(@headerContent, "\nprivate:\n");

    # Constructor
    push(@headerContent, "    $className(JSC::JSObject* callback, JSDOMGlobalObject*);\n\n");

    # Private members
    push(@headerContent, "    JSCallbackData* m_data;\n");
    push(@headerContent, "};\n\n");

    push(@headerContent, "} // namespace WebCore\n\n");
    my $conditionalString = $codeGenerator->GenerateConditionalString($dataNode);
    push(@headerContent, "#endif // ${conditionalString}\n\n") if $conditionalString;
    push(@headerContent, "#endif\n");
}

sub GenerateCallbackImplementation
{
    my ($object, $dataNode) = @_;

    my $interfaceName = $dataNode->name;
    my $className = "JS$interfaceName";

    # - Add default header template
    push(@implContentHeader, GenerateImplementationContentHeader($dataNode));

    $implIncludes{"ScriptExecutionContext.h"} = 1;
    $implIncludes{"<runtime/JSLock.h>"} = 1;

    @implContent = ();

    push(@implContent, "\nusing namespace JSC;\n\n");
    push(@implContent, "namespace WebCore {\n\n");

    # Constructor
    push(@implContent, "${className}::${className}(JSObject* callback, JSDOMGlobalObject* globalObject)\n");
    push(@implContent, "    : ActiveDOMCallback(globalObject->scriptExecutionContext())\n");
    push(@implContent, "    , m_data(new JSCallbackData(callback, globalObject))\n");
    push(@implContent, "{\n");
    push(@implContent, "}\n\n");

    # Destructor
    push(@implContent, "${className}::~${className}()\n");
    push(@implContent, "{\n");
    push(@implContent, "    ScriptExecutionContext* context = scriptExecutionContext();\n");
    push(@implContent, "    // When the context is destroyed, all tasks with a reference to a callback\n");
    push(@implContent, "    // should be deleted. So if the context is 0, we are on the context thread.\n");
    push(@implContent, "    if (!context || context->isContextThread())\n");
    push(@implContent, "        delete m_data;\n");
    push(@implContent, "    else\n");
    push(@implContent, "        context->postTask(DeleteCallbackDataTask::create(m_data));\n");
    push(@implContent, "#ifndef NDEBUG\n");
    push(@implContent, "    m_data = 0;\n");
    push(@implContent, "#endif\n");
    push(@implContent, "}\n");

    # Functions
    my $numFunctions = @{$dataNode->functions};
    if ($numFunctions > 0) {
        push(@implContent, "\n// Functions\n");
        foreach my $function (@{$dataNode->functions}) {
            my @params = @{$function->parameters};
            if ($function->signature->extendedAttributes->{"Custom"} ||
                !(GetNativeType($function->signature->type) eq "bool")) {
                next;
            }

            AddIncludesForTypeInImpl($function->signature->type);
            push(@implContent, "\n" . GetNativeType($function->signature->type) . " ${className}::" . $function->signature->name . "(");

            my @args = ();
            my @argsCheck = ();
            my $thisType = $function->signature->extendedAttributes->{"PassThisToCallback"};
            foreach my $param (@params) {
                my $paramName = $param->name;
                AddIncludesForTypeInImpl($param->type, 1);
                push(@args, GetNativeType($param->type) . " " . $paramName);
                if ($thisType and $thisType eq $param->type) {
                    push(@argsCheck, <<END);
    ASSERT(${paramName});

END
                }
            }
            push(@implContent, join(", ", @args));
            push(@implContent, ")\n");

            push(@implContent, "{\n");
            push(@implContent, @argsCheck) if @argsCheck;
            push(@implContent, "    if (!canInvokeCallback())\n");
            push(@implContent, "        return true;\n\n");
            push(@implContent, "    RefPtr<$className> protect(this);\n\n");
            push(@implContent, "    JSLockHolder lock(m_data->globalObject()->globalData());\n\n");
            push(@implContent, "    ExecState* exec = m_data->globalObject()->globalExec();\n");
            push(@implContent, "    MarkedArgumentBuffer args;\n");

            foreach my $param (@params) {
                my $paramName = $param->name;
                if ($param->type eq "DOMString") {
                    push(@implContent, "    args.append(jsString(exec, ${paramName}));\n");
                } elsif ($param->type eq "boolean") {
                    push(@implContent, "    args.append(jsBoolean(${paramName}));\n");
                } else {
                    push(@implContent, "    args.append(toJS(exec, m_data->globalObject(), ${paramName}));\n");
                }
            }

            push(@implContent, "\n    bool raisedException = false;\n");
            if ($thisType) {
                foreach my $param (@params) {
                    next if $param->type ne $thisType;
                    my $paramName = $param->name;
                    push(@implContent, <<END);
    JSValue js${paramName} = toJS(exec, m_data->globalObject(), ${paramName});
    m_data->invokeCallback(js${paramName}, args, &raisedException);

END
                    last;
                }
            } else {
                push(@implContent, "    m_data->invokeCallback(args, &raisedException);\n");
            }
            push(@implContent, "    return !raisedException;\n");
            push(@implContent, "}\n");
        }
    }

    push(@implContent, "\n}\n");
    my $conditionalString = $codeGenerator->GenerateConditionalString($dataNode);
    push(@implContent, "\n#endif // ${conditionalString}\n") if $conditionalString;
}

sub GenerateImplementationFunctionCall()
{
    my $function = shift;
    my $functionString = shift;
    my $indent = shift;
    my $svgPropertyType = shift;
    my $implClassName = shift;

    if ($function->signature->type eq "void") {
        push(@implContent, $indent . "$functionString;\n");
        push(@implContent, $indent . "setDOMException(exec, ec);\n") if @{$function->raisesExceptions};

        if ($svgPropertyType and !$function->isStatic) {
            if (@{$function->raisesExceptions}) {
                push(@implContent, $indent . "if (!ec)\n"); 
                push(@implContent, $indent . "    impl->commitChange();\n");
            } else {
                push(@implContent, $indent . "impl->commitChange();\n");
            }
        }

        push(@implContent, $indent . "return JSValue::encode(jsUndefined());\n");
    } else {
        my $thisObject = $function->isStatic ? 0 : "castedThis";
        push(@implContent, "\n" . $indent . "JSC::JSValue result = " . NativeToJSValue($function->signature, 1, $implClassName, $functionString, $thisObject) . ";\n");
        push(@implContent, $indent . "setDOMException(exec, ec);\n") if @{$function->raisesExceptions};

        if ($codeGenerator->ExtendedAttributeContains($function->signature->extendedAttributes->{"CallWith"}, "ScriptState")) {
            push(@implContent, $indent . "if (exec->hadException())\n");
            push(@implContent, $indent . "    return JSValue::encode(jsUndefined());\n");
        }

        push(@implContent, $indent . "return JSValue::encode(result);\n");
    }
}

sub GetNativeTypeFromSignature
{
    my $signature = shift;
    my $type = $codeGenerator->StripModule($signature->type);

    if ($type eq "unsigned long" and $signature->extendedAttributes->{"IsIndex"}) {
        # Special-case index arguments because we need to check that they aren't < 0.
        return "int";
    }

    return GetNativeType($type);
}

my %nativeType = (
    "CompareHow" => "Range::CompareHow",
    "DOMString" => "const String&",
    # FIXME: Add proper support for T[], T[]?, sequence<T>
    "DOMString[]" => "DOMStringList*",
    "DOMObject" => "ScriptValue",
    "NodeFilter" => "RefPtr<NodeFilter>",
    "SerializedScriptValue" => "RefPtr<SerializedScriptValue>",
    "IDBKey" => "PassRefPtr<IDBKey>",
    "Dictionary" => "Dictionary",
    "boolean" => "bool",
    "double" => "double",
    "float" => "float",
    "short" => "short",
    "long" => "int",
    "unsigned long" => "unsigned",
    "unsigned short" => "unsigned short",
    "long long" => "long long",
    "unsigned long long" => "unsigned long long",
    "MediaQueryListListener" => "RefPtr<MediaQueryListListener>",
    "DOMTimeStamp" => "DOMTimeStamp",
    "unsigned long[]" => "Vector<unsigned long>"
);

sub GetNativeType
{
    my $type = shift;

    my $svgNativeType = $codeGenerator->GetSVGTypeNeedingTearOff($type);
    return "${svgNativeType}*" if $svgNativeType;
    return $nativeType{$type} if exists $nativeType{$type};

    # For all other types, the native type is a pointer with same type name as the IDL type.
    return "${type}*";
}

sub GetSVGPropertyTypes
{
    my $implType = shift;

    my $svgPropertyType;
    my $svgListPropertyType;
    my $svgNativeType;

    return ($svgPropertyType, $svgListPropertyType, $svgNativeType) if not $implType =~ /SVG/;
    
    $svgNativeType = $codeGenerator->GetSVGTypeNeedingTearOff($implType);
    return ($svgPropertyType, $svgListPropertyType, $svgNativeType) if not $svgNativeType;

    # Append space to avoid compilation errors when using  PassRefPtr<$svgNativeType>
    $svgNativeType = "$svgNativeType ";

    my $svgWrappedNativeType = $codeGenerator->GetSVGWrappedTypeNeedingTearOff($implType);
    if ($svgNativeType =~ /SVGPropertyTearOff/) {
        $svgPropertyType = $svgWrappedNativeType;
        $headerIncludes{"$svgWrappedNativeType.h"} = 1;
        $headerIncludes{"SVGAnimatedPropertyTearOff.h"} = 1;
    } elsif ($svgNativeType =~ /SVGListPropertyTearOff/ or $svgNativeType =~ /SVGStaticListPropertyTearOff/) {
        $svgListPropertyType = $svgWrappedNativeType;
        $headerIncludes{"$svgWrappedNativeType.h"} = 1;
        $headerIncludes{"SVGAnimatedListPropertyTearOff.h"} = 1;
    } elsif ($svgNativeType =~ /SVGTransformListPropertyTearOff/) {
        $svgListPropertyType = $svgWrappedNativeType;
        $headerIncludes{"$svgWrappedNativeType.h"} = 1;
        $headerIncludes{"SVGAnimatedListPropertyTearOff.h"} = 1;
        $headerIncludes{"SVGTransformListPropertyTearOff.h"} = 1;
    } elsif ($svgNativeType =~ /SVGPathSegListPropertyTearOff/) {
        $svgListPropertyType = $svgWrappedNativeType;
        $headerIncludes{"$svgWrappedNativeType.h"} = 1;
        $headerIncludes{"SVGAnimatedListPropertyTearOff.h"} = 1;
        $headerIncludes{"SVGPathSegListPropertyTearOff.h"} = 1;
    }

    return ($svgPropertyType, $svgListPropertyType, $svgNativeType);
}

sub IsNativeType
{
    my $type = shift;
    return exists $nativeType{$type};
}

sub IsArrayType
{
    my $type = shift;
    # FIXME: Add proper support for T[], T[]?, sequence<T>.
    return $type =~ m/\[\]$/;
}

sub JSValueToNative
{
    my $signature = shift;
    my $value = shift;

    my $conditional = $signature->extendedAttributes->{"Conditional"};
    my $type = $codeGenerator->StripModule($signature->type);

    return "$value.toBoolean(exec)" if $type eq "boolean";
    return "$value.toNumber(exec)" if $type eq "double";
    return "$value.toFloat(exec)" if $type eq "float";
    return "$value.toInt32(exec)" if $type eq "long" or $type eq "short";
    return "$value.toUInt32(exec)" if $type eq "unsigned long" or $type eq "unsigned short";
    return "static_cast<$type>($value.toInteger(exec))" if $type eq "long long" or $type eq "unsigned long long";

    return "valueToDate(exec, $value)" if $type eq "Date";
    return "static_cast<Range::CompareHow>($value.toInt32(exec))" if $type eq "CompareHow";

    if ($type eq "DOMString") {
        # FIXME: This implements [TreatNullAs=NullString] and [TreatUndefinedAs=NullString],
        # but the Web IDL spec requires [TreatNullAs=EmptyString] and [TreatUndefinedAs=EmptyString].
        if (($signature->extendedAttributes->{"TreatNullAs"} and $signature->extendedAttributes->{"TreatNullAs"} eq "NullString") and ($signature->extendedAttributes->{"TreatUndefinedAs"} and $signature->extendedAttributes->{"TreatUndefinedAs"} eq "NullString")) {
            return "valueToStringWithUndefinedOrNullCheck(exec, $value)"
        }
        if (($signature->extendedAttributes->{"TreatNullAs"} and $signature->extendedAttributes->{"TreatNullAs"} eq "NullString") or $signature->extendedAttributes->{"Reflect"}) {
            return "valueToStringWithNullCheck(exec, $value)"
        }
        # FIXME: Add the case for 'if ($signature->extendedAttributes->{"TreatUndefinedAs"} and $signature->extendedAttributes->{"TreatUndefinedAs"} eq "NullString"))'.
        return "ustringToString($value.isEmpty() ? UString() : $value.toString(exec)->value(exec))";
    }

    if ($type eq "DOMObject") {
        return "exec->globalData(), $value";
    }

    if ($type eq "NodeFilter") {
        AddToImplIncludes("JS$type.h", $conditional);
        return "to$type(exec->globalData(), $value)";
    }

    if ($type eq "MediaQueryListListener") {
        AddToImplIncludes("MediaQueryListListener.h", $conditional);
        return "MediaQueryListListener::create(ScriptValue(exec->globalData(), " . $value ."))";
    }

    if ($type eq "SerializedScriptValue" or $type eq "any") {
        AddToImplIncludes("SerializedScriptValue.h", $conditional);
        return "SerializedScriptValue::create(exec, $value)";
    }

    if ($type eq "IDBKey") {
        AddToImplIncludes("IDBBindingUtilities.h", $conditional);
        AddToImplIncludes("IDBKey.h", $conditional);
        return "createIDBKeyFromValue(exec, $value)";
    }

    if ($type eq "Dictionary") {
        AddToImplIncludes("Dictionary.h", $conditional);
        return "exec, $value";
    }

    if ($type eq "DOMString[]") {
        AddToImplIncludes("JSDOMStringList.h", $conditional);
        return "toDOMStringList($value)";
    }

    if ($type eq "unsigned long[]") {
        AddToImplIncludes("JSDOMBinding.h", $conditional);
        return "jsUnsignedLongArrayToVector(exec, $value)";
    }

    AddToImplIncludes("HTMLOptionElement.h", $conditional) if $type eq "HTMLOptionElement";
    AddToImplIncludes("JSCustomVoidCallback.h", $conditional) if $type eq "VoidCallback";
    AddToImplIncludes("Event.h", $conditional) if $type eq "Event";

    my $arrayType = $codeGenerator->GetArrayType($type);
    if ($arrayType) {
        return "toNativeArray<$arrayType>(exec, $value)";
    }

    # Default, assume autogenerated type conversion routines
    AddToImplIncludes("JS$type.h", $conditional);
    return "to$type($value)";
}

sub NativeToJSValue
{
    my $signature = shift;
    my $inFunctionCall = shift;
    my $implClassName = shift;
    my $value = shift;
    my $thisValue = shift;

    my $conditional = $signature->extendedAttributes->{"Conditional"};
    my $type = $codeGenerator->StripModule($signature->type);

    return "jsBoolean($value)" if $type eq "boolean";

    # Need to check Date type before IsPrimitiveType().
    if ($type eq "Date") {
        return "jsDateOrNull(exec, $value)";
    }

    if ($signature->extendedAttributes->{"Reflect"} and ($type eq "unsigned long" or $type eq "unsigned short")) {
        $value =~ s/getUnsignedIntegralAttribute/getIntegralAttribute/g;
        return "jsNumber(std::max(0, " . $value . "))";
    }

    if ($codeGenerator->IsPrimitiveType($type) or $type eq "DOMTimeStamp") {
        return "jsNumber($value)";
    }

    if ($codeGenerator->IsStringType($type)) {
        AddToImplIncludes("KURL.h", $conditional);
        my $conv = $signature->extendedAttributes->{"TreatReturnedNullStringAs"};
        if (defined $conv) {
            return "jsStringOrNull(exec, $value)" if $conv eq "Null";
            return "jsStringOrUndefined(exec, $value)" if $conv eq "Undefined";
            return "jsStringOrFalse(exec, $value)" if $conv eq "False";

            die "Unknown value for TreatReturnedNullStringAs extended attribute";
        }
        AddToImplIncludes("<runtime/JSString.h>", $conditional);
        return "jsString(exec, $value)";
    }

    my $globalObject;
    if ($thisValue) {
        $globalObject = "$thisValue->globalObject()";
    }

    if ($type eq "CSSStyleDeclaration") {
        AddToImplIncludes("StylePropertySet.h", $conditional);
    }

    if ($type eq "NodeList") {
        AddToImplIncludes("NameNodeList.h", $conditional);
    }

    my $arrayType = $codeGenerator->GetArrayType($type);
    if ($arrayType) {
        if (!$codeGenerator->SkipIncludeHeader($arrayType)) {
            AddToImplIncludes("JS$arrayType.h", $conditional);
            AddToImplIncludes("$arrayType.h", $conditional);
        }
        AddToImplIncludes("<runtime/JSArray.h>", $conditional);
        return "jsArray(exec, $thisValue->globalObject(), $value)";
    }

    if ($type eq "DOMObject") {
        if ($implClassName eq "Document") {
            AddToImplIncludes("JSCanvasRenderingContext2D.h", $conditional);
        } else {
            return "($value.hasNoValue() ? jsNull() : $value.jsValue())";
        }
    } elsif ($type =~ /SVGPathSeg/) {
        AddToImplIncludes("JS$type.h", $conditional);
        my $joinedName = $type;
        $joinedName =~ s/Abs|Rel//;
        AddToImplIncludes("$joinedName.h", $conditional);
    } elsif ($type eq "SerializedScriptValue" or $type eq "any") {
        AddToImplIncludes("SerializedScriptValue.h", $conditional);
        return "$value ? $value->deserialize(exec, castedThis->globalObject(), 0) : jsNull()";
    } elsif ($type eq "unsigned long[]") {
        AddToImplIncludes("<wrt/Vector.h>", $conditional);
    } else {
        # Default, include header with same name.
        AddToImplIncludes("JS$type.h", $conditional);
        if (IsTypedArrayType($type)) {
            AddToImplIncludes("<wtf/$type.h>", $conditional) if not $codeGenerator->SkipIncludeHeader($type);
        } else {
            AddToImplIncludes("$type.h", $conditional) if not $codeGenerator->SkipIncludeHeader($type);
        }
    }

    return $value if $codeGenerator->IsSVGAnimatedType($type);

    if ($signature->extendedAttributes->{"ReturnNewObject"}) {
        return "toJSNewlyCreated(exec, $globalObject, WTF::getPtr($value))";
    }

    if ($codeGenerator->IsSVGAnimatedType($implClassName)) {
        # Convert from abstract SVGProperty to real type, so the right toJS() method can be invoked.
        $value = "static_cast<" . GetNativeType($type) . ">($value)";
    } elsif ($codeGenerator->IsSVGTypeNeedingTearOff($type) and not $implClassName =~ /List$/) {
        my $tearOffType = $codeGenerator->GetSVGTypeNeedingTearOff($type);
        if ($codeGenerator->IsSVGTypeWithWritablePropertiesNeedingTearOff($type) and $inFunctionCall eq 0 and not defined $signature->extendedAttributes->{"Immutable"}) {
            my $getter = $value;
            $getter =~ s/impl\.//;
            $getter =~ s/impl->//;
            $getter =~ s/\(\)//;
            my $updateMethod = "&${implClassName}::update" . $codeGenerator->WK_ucfirst($getter);

            my $selfIsTearOffType = $codeGenerator->IsSVGTypeNeedingTearOff($implClassName);
            if ($selfIsTearOffType) {
                AddToImplIncludes("SVGStaticPropertyWithParentTearOff.h", $conditional);
                $tearOffType =~ s/SVGPropertyTearOff</SVGStaticPropertyWithParentTearOff<$implClassName, /;

                if ($value =~ /matrix/ and $implClassName eq "SVGTransform") {
                    # SVGTransform offers a matrix() method for internal usage that returns an AffineTransform
                    # and a svgMatrix() method returning a SVGMatrix, used for the bindings.
                    $value =~ s/matrix/svgMatrix/;
                }

                $value = "${tearOffType}::create(castedThis->impl(), $value, $updateMethod)";
            } else {
                AddToImplIncludes("SVGStaticPropertyTearOff.h", $conditional);
                $tearOffType =~ s/SVGPropertyTearOff</SVGStaticPropertyTearOff<$implClassName, /;
                $value = "${tearOffType}::create(impl, $value, $updateMethod)";
            }
        } elsif ($tearOffType =~ /SVGStaticListPropertyTearOff/) {
            $value = "${tearOffType}::create(impl, $value)";
        } elsif (not $tearOffType =~ /SVG(Point|PathSeg)List/) {
            $value = "${tearOffType}::create($value)";
        }
    }
    if ($globalObject) {
        return "toJS(exec, $globalObject, WTF::getPtr($value))";
    } else {
        return "toJS(exec, jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject()), WTF::getPtr($value))";
    }
}

sub ceilingToPowerOf2
{
    my ($size) = @_;

    my $powerOf2 = 1;
    while ($size > $powerOf2) {
        $powerOf2 <<= 1;
    }

    return $powerOf2;
}

# Internal Helper
sub GenerateHashTable
{
    my $object = shift;

    my $name = shift;
    my $size = shift;
    my $keys = shift;
    my $specials = shift;
    my $value1 = shift;
    my $value2 = shift;
    my $conditionals = shift;

    # Generate size data for compact' size hash table

    my @table = ();
    my @links = ();

    my $compactSize = ceilingToPowerOf2($size * 2);

    my $maxDepth = 0;
    my $collisions = 0;
    my $numEntries = $compactSize;

    my $i = 0;
    foreach (@{$keys}) {
        my $depth = 0;
        my $h = $object->GenerateHashValue($_) % $numEntries;

        while (defined($table[$h])) {
            if (defined($links[$h])) {
                $h = $links[$h];
                $depth++;
            } else {
                $collisions++;
                $links[$h] = $compactSize;
                $h = $compactSize;
                $compactSize++;
            }
        }

        $table[$h] = $i;

        $i++;
        $maxDepth = $depth if ($depth > $maxDepth);
    }

    # Start outputing the hashtables
    my $nameEntries = "${name}Values";
    $nameEntries =~ s/:/_/g;

    if (($name =~ /Prototype/) or ($name =~ /Constructor/)) {
        my $type = $name;
        my $implClass;

        if ($name =~ /Prototype/) {
            $type =~ s/Prototype.*//;
            $implClass = $type; $implClass =~ s/Wrapper$//;
            push(@implContent, "/* Hash table for prototype */\n");
        } else {
            $type =~ s/Constructor.*//;
            $implClass = $type; $implClass =~ s/Constructor$//;
            push(@implContent, "/* Hash table for constructor */\n");
        }
    } else {
        push(@implContent, "/* Hash table */\n");
    }

    # Dump the hash table
    push(@implContent, "\nstatic const HashTableValue $nameEntries\[\] =\n\{\n");
    $i = 0;
    foreach my $key (@{$keys}) {
        my $conditional;
        my $targetType;

        if ($conditionals) {
            $conditional = $conditionals->{$key};
        }
        if ($conditional) {
            my $conditionalString = $codeGenerator->GenerateConditionalStringFromAttributeValue($conditional);
            push(@implContent, "#if ${conditionalString}\n");
        }
        
        if ("@$specials[$i]" =~ m/Function/) {
            $targetType = "static_cast<NativeFunction>";
        } else {
            $targetType = "static_cast<PropertySlot::GetValueFunc>";
        }
        push(@implContent, "    { \"$key\", @$specials[$i], (intptr_t)" . $targetType . "(@$value1[$i]), (intptr_t)@$value2[$i], NoIntrinsic },\n");
        push(@implContent, "#endif\n") if $conditional;
        ++$i;
    }
    push(@implContent, "    { 0, 0, 0, 0, NoIntrinsic }\n");
    push(@implContent, "};\n\n");
    my $compactSizeMask = $numEntries - 1;
    push(@implContent, "static const HashTable $name = { $compactSize, $compactSizeMask, $nameEntries, 0 };\n");
}

# Paul Hsieh's SuperFastHash
# http://www.azillionmonkeys.com/qed/hash.html
sub GenerateHashValue
{
    my $object = shift;

    my @chars = split(/ */, $_[0]);

    # This hash is designed to work on 16-bit chunks at a time. But since the normal case
    # (above) is to hash UTF-16 characters, we just treat the 8-bit chars as if they
    # were 16-bit chunks, which should give matching results
    
    my $EXP2_32 = 4294967296;
    
    my $hash = 0x9e3779b9;
    my $l    = scalar @chars; #I wish this was in Ruby --- Maks
    my $rem  = $l & 1;
    $l = $l >> 1;
    
    my $s = 0;
    
    # Main loop
    for (; $l > 0; $l--) {
        $hash   += ord($chars[$s]);
        my $tmp = leftShift(ord($chars[$s+1]), 11) ^ $hash;
        $hash   = (leftShift($hash, 16)% $EXP2_32) ^ $tmp;
        $s += 2;
        $hash += $hash >> 11;
        $hash %= $EXP2_32;
    }
    
    # Handle end case
    if ($rem != 0) {
        $hash += ord($chars[$s]);
        $hash ^= (leftShift($hash, 11)% $EXP2_32);
        $hash += $hash >> 17;
    }
    
    # Force "avalanching" of final 127 bits
    $hash ^= leftShift($hash, 3);
    $hash += ($hash >> 5);
    $hash = ($hash% $EXP2_32);
    $hash ^= (leftShift($hash, 2)% $EXP2_32);
    $hash += ($hash >> 15);
    $hash = $hash% $EXP2_32;
    $hash ^= (leftShift($hash, 10)% $EXP2_32);
    
    # Save 8 bits for StringImpl to use as flags.
    $hash &= 0xffffff;
    
    # This avoids ever returning a hash code of 0, since that is used to
    # signal "hash not computed yet". Setting the high bit maintains
    # reasonable fidelity to a hash code of 0 because it is likely to yield
    # exactly 0 when hash lookup masks out the high bits.
    $hash = (0x80000000 >> 8) if ($hash == 0);
    
    return $hash;
}

# Internal helper
sub WriteData
{
    my $object = shift;
    my $dataNode = shift;

    my $name = $dataNode->name;
    my $prefix = FileNamePrefix;
    my $headerFileName = "$outputDir/$prefix$name.h";
    my $implFileName = "$outputDir/$prefix$name.cpp";
    my $depsFileName = "$outputDir/$prefix$name.dep";

    # Update a .cpp file if the contents are changed.
    my $contents = join "", @implContentHeader;

    my @includes = ();
    my %implIncludeConditions = ();
    foreach my $include (keys %implIncludes) {
        my $condition = $implIncludes{$include};
        my $checkType = $include;
        $checkType =~ s/\.h//;
        next if $codeGenerator->IsSVGAnimatedType($checkType);

        $include = "\"$include\"" unless $include =~ /^["<]/; # "

        if ($condition eq 1) {
            push @includes, $include;
        } else {
            push @{$implIncludeConditions{$condition}}, $include;
        }
    }
    foreach my $include (sort @includes) {
        $contents .= "#include $include\n";
    }
    foreach my $condition (sort keys %implIncludeConditions) {
        $contents .= "\n#if " . $codeGenerator->GenerateConditionalStringFromAttributeValue($condition) . "\n";
        foreach my $include (sort @{$implIncludeConditions{$condition}}) {
            $contents .= "#include $include\n";
        }
        $contents .= "#endif\n";
    }

    $contents .= join "", @implContent;
    $codeGenerator->UpdateFile($implFileName, $contents);

    @implContentHeader = ();
    @implContent = ();
    %implIncludes = ();

    # Update a .h file if the contents are changed.
    $contents = join "", @headerContentHeader;

    @includes = ();
    foreach my $include (keys %headerIncludes) {
        $include = "\"$include\"" unless $include =~ /^["<]/; # "
        push @includes, $include;
    }
    foreach my $include (sort @includes) {
        $contents .= "#include $include\n";
    }

    $contents .= join "", @headerContent;

    @includes = ();
    foreach my $include (keys %headerTrailingIncludes) {
        $include = "\"$include\"" unless $include =~ /^["<]/; # "
        push @includes, $include;
    }
    foreach my $include (sort @includes) {
        $contents .= "#include $include\n";
    }
    $codeGenerator->UpdateFile($headerFileName, $contents);

    @headerContentHeader = ();
    @headerContent = ();
    %headerIncludes = ();
    %headerTrailingIncludes = ();

    if (@depsContent) {
        # Update a .dep file if the contents are changed.
        $contents = join "", @depsContent;
        $codeGenerator->UpdateFile($depsFileName, $contents);

        @depsContent = ();
    }
}

sub GenerateConstructorDeclaration
{
    my $outputArray = shift;
    my $className = shift;
    my $dataNode = shift;
    my $interfaceName = shift;

    my $constructorClassName = "${className}Constructor";

    push(@$outputArray, "class ${constructorClassName} : public DOMConstructorObject {\n");
    push(@$outputArray, "private:\n");
    push(@$outputArray, "    ${constructorClassName}(JSC::Structure*, JSDOMGlobalObject*);\n");
    push(@$outputArray, "    void finishCreation(JSC::ExecState*, JSDOMGlobalObject*);\n\n");

    push(@$outputArray, "public:\n");
    push(@$outputArray, "    typedef DOMConstructorObject Base;\n");
    push(@$outputArray, "    static $constructorClassName* create(JSC::ExecState* exec, JSC::Structure* structure, JSDOMGlobalObject* globalObject)\n");
    push(@$outputArray, "    {\n");
    push(@$outputArray, "        $constructorClassName* ptr = new (NotNull, JSC::allocateCell<$constructorClassName>(*exec->heap())) $constructorClassName(structure, globalObject);\n");
    push(@$outputArray, "        ptr->finishCreation(exec, globalObject);\n");
    push(@$outputArray, "        return ptr;\n");
    push(@$outputArray, "    }\n\n");

    push(@$outputArray, "    static bool getOwnPropertySlot(JSC::JSCell*, JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);\n");
    push(@$outputArray, "    static bool getOwnPropertyDescriptor(JSC::JSObject*, JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);\n");
    push(@$outputArray, "    static const JSC::ClassInfo s_info;\n");

    push(@$outputArray, "    static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)\n");
    push(@$outputArray, "    {\n");
    push(@$outputArray, "        return JSC::Structure::create(globalData, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), &s_info);\n");
    push(@$outputArray, "    }\n");

    push(@$outputArray, "protected:\n");
    push(@$outputArray, "    static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags;\n");

    if (IsConstructable($dataNode) && !$dataNode->extendedAttributes->{"NamedConstructor"}) {
        push(@$outputArray, "    static JSC::EncodedJSValue JSC_HOST_CALL construct${className}(JSC::ExecState*);\n");
        push(@$outputArray, "    static JSC::ConstructType getConstructData(JSC::JSCell*, JSC::ConstructData&);\n");
    }
    push(@$outputArray, "};\n\n");

    if (IsConstructorTemplate($dataNode, "Event")) {
        push(@$outputArray, "bool fill${interfaceName}Init(${interfaceName}Init&, JSDictionary&);\n\n");
    }

    if ($dataNode->extendedAttributes->{"NamedConstructor"}) {
        push(@$outputArray, <<END);
class JS${interfaceName}NamedConstructor : public DOMConstructorWithDocument {
public:
    typedef DOMConstructorWithDocument Base;

    static JS${interfaceName}NamedConstructor* create(JSC::ExecState* exec, JSC::Structure* structure, JSDOMGlobalObject* globalObject)
    {
        JS${interfaceName}NamedConstructor* constructor = new (NotNull, JSC::allocateCell<JS${interfaceName}NamedConstructor>(*exec->heap())) JS${interfaceName}NamedConstructor(structure, globalObject);
        constructor->finishCreation(exec, globalObject);
        return constructor;
    }

    static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)
    {
        return JSC::Structure::create(globalData, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), &s_info);
    }

    static const JSC::ClassInfo s_info;

private:
    JS${interfaceName}NamedConstructor(JSC::Structure*, JSDOMGlobalObject*);
    static JSC::EncodedJSValue JSC_HOST_CALL constructJS${interfaceName}(JSC::ExecState*);
    static JSC::ConstructType getConstructData(JSC::JSCell*, JSC::ConstructData&);
    void finishCreation(JSC::ExecState*, JSDOMGlobalObject*);
};

END
    }
}

sub GenerateConstructorDefinition
{
    my $outputArray = shift;

    my $className = shift;
    my $protoClassName = shift;
    my $interfaceName = shift;
    my $visibleInterfaceName = shift;
    my $dataNode = shift;
    my $generatingNamedConstructor = shift;

    my $constructorClassName = $generatingNamedConstructor ? "${className}NamedConstructor" : "${className}Constructor";
    my $numberOfConstructorParameters = $dataNode->extendedAttributes->{"ConstructorParameters"};
    if (!defined $numberOfConstructorParameters) {
        if (IsConstructorTemplate($dataNode, "Event")) {
            $numberOfConstructorParameters = 2;
        } elsif ($dataNode->extendedAttributes->{"Constructor"}) {
            $numberOfConstructorParameters = @{$dataNode->constructor->parameters};
        }
    }

    if ($generatingNamedConstructor) {
        push(@$outputArray, "const ClassInfo ${constructorClassName}::s_info = { \"${visibleInterfaceName}Constructor\", &Base::s_info, 0, 0, CREATE_METHOD_TABLE($constructorClassName) };\n\n");
        push(@$outputArray, "${constructorClassName}::${constructorClassName}(Structure* structure, JSDOMGlobalObject* globalObject)\n");
        push(@$outputArray, "    : DOMConstructorWithDocument(structure, globalObject)\n");
        push(@$outputArray, "{\n");
        push(@$outputArray, "}\n\n");
    } else {
        push(@$outputArray, "const ClassInfo ${constructorClassName}::s_info = { \"${visibleInterfaceName}Constructor\", &Base::s_info, &${constructorClassName}Table, 0, CREATE_METHOD_TABLE($constructorClassName) };\n\n");
        push(@$outputArray, "${constructorClassName}::${constructorClassName}(Structure* structure, JSDOMGlobalObject* globalObject)\n");
        push(@$outputArray, "    : DOMConstructorObject(structure, globalObject)\n");
        push(@$outputArray, "{\n");
        push(@$outputArray, "}\n\n");
    }

    push(@$outputArray, "void ${constructorClassName}::finishCreation(ExecState* exec, JSDOMGlobalObject* globalObject)\n");
    push(@$outputArray, "{\n");
    if ($interfaceName eq "DOMWindow") {
        push(@$outputArray, "    Base::finishCreation(exec->globalData());\n");
        push(@$outputArray, "    ASSERT(inherits(&s_info));\n");
        push(@$outputArray, "    putDirect(exec->globalData(), exec->propertyNames().prototype, globalObject->prototype(), DontDelete | ReadOnly);\n");
    } elsif ($generatingNamedConstructor) {
        push(@$outputArray, "    Base::finishCreation(globalObject);\n");
        push(@$outputArray, "    ASSERT(inherits(&s_info));\n");
        push(@$outputArray, "    putDirect(exec->globalData(), exec->propertyNames().prototype, ${className}Prototype::self(exec, globalObject), None);\n");
    } else {
        push(@$outputArray, "    Base::finishCreation(exec->globalData());\n");
        push(@$outputArray, "    ASSERT(inherits(&s_info));\n");
        push(@$outputArray, "    putDirect(exec->globalData(), exec->propertyNames().prototype, ${protoClassName}::self(exec, globalObject), DontDelete | ReadOnly);\n");
    }
    push(@$outputArray, "    putDirect(exec->globalData(), exec->propertyNames().length, jsNumber(${numberOfConstructorParameters}), ReadOnly | DontDelete | DontEnum);\n") if defined $numberOfConstructorParameters;
    push(@$outputArray, "}\n\n");

    if (!$generatingNamedConstructor) {
        my $hasStaticFunctions = 0;
        foreach my $function (@{$dataNode->functions}) {
            if ($function->isStatic) {
                $hasStaticFunctions = 1;
                last;
            }
        }

        my $kind = $hasStaticFunctions ? "Property" : "Value";

        push(@$outputArray, "bool ${constructorClassName}::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot)\n");
        push(@$outputArray, "{\n");
        push(@$outputArray, "    return getStatic${kind}Slot<${constructorClassName}, JSDOMWrapper>(exec, &${constructorClassName}Table, jsCast<${constructorClassName}*>(cell), propertyName, slot);\n");
        push(@$outputArray, "}\n\n");

        push(@$outputArray, "bool ${constructorClassName}::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)\n");
        push(@$outputArray, "{\n");
        push(@$outputArray, "    return getStatic${kind}Descriptor<${constructorClassName}, JSDOMWrapper>(exec, &${constructorClassName}Table, jsCast<${constructorClassName}*>(object), propertyName, descriptor);\n");
        push(@$outputArray, "}\n\n");
    }

    if (IsConstructable($dataNode)) {
        if (IsConstructorTemplate($dataNode, "Event")) {
            $implIncludes{"JSDictionary.h"} = 1;
            $implIncludes{"<runtime/Error.h>"} = 1;

            push(@$outputArray, <<END);
EncodedJSValue JSC_HOST_CALL ${constructorClassName}::construct${className}(ExecState* exec)
{
    ${constructorClassName}* jsConstructor = jsCast<${constructorClassName}*>(exec->callee());

    ScriptExecutionContext* executionContext = jsConstructor->scriptExecutionContext();
    if (!executionContext)
        return throwVMError(exec, createReferenceError(exec, "Constructor associated execution context is unavailable"));

    AtomicString eventType = ustringToAtomicString(exec->argument(0).toString(exec)->value(exec));
    if (exec->hadException())
        return JSValue::encode(jsUndefined());

    ${interfaceName}Init eventInit;

    JSValue initializerValue = exec->argument(1);
    if (!initializerValue.isUndefinedOrNull()) {
        // Given the above test, this will always yield an object.
        JSObject* initializerObject = initializerValue.toObject(exec);

        // Create the dictionary wrapper from the initializer object.
        JSDictionary dictionary(exec, initializerObject);

        // Attempt to fill in the EventInit.
        if (!fill${interfaceName}Init(eventInit, dictionary))
            return JSValue::encode(jsUndefined());
    }

    RefPtr<${interfaceName}> event = ${interfaceName}::create(eventType, eventInit);
    return JSValue::encode(toJS(exec, jsConstructor->globalObject(), event.get()));
}

bool fill${interfaceName}Init(${interfaceName}Init& eventInit, JSDictionary& dictionary)
{
END

            foreach my $interfaceBase (@{$dataNode->parents}) {
                push(@implContent, <<END);
    if (!fill${interfaceBase}Init(eventInit, dictionary))
        return false;

END
            }

            for (my $index = 0; $index < @{$dataNode->attributes}; $index++) {
                my $attribute = @{$dataNode->attributes}[$index];
                if ($attribute->signature->extendedAttributes->{"InitializedByEventConstructor"}) {
                    my $attributeName = $attribute->signature->name;
                    push(@implContent, <<END);
    if (!dictionary.tryGetProperty("${attributeName}", eventInit.${attributeName}))
        return false;
END
                }
            }

            push(@$outputArray, <<END);
    return true;
}

END
        } elsif (!($dataNode->extendedAttributes->{"JSCustomConstructor"} || $dataNode->extendedAttributes->{"CustomConstructor"}) && (!$dataNode->extendedAttributes->{"NamedConstructor"} || $generatingNamedConstructor)) {
            push(@$outputArray, "EncodedJSValue JSC_HOST_CALL ${constructorClassName}::construct${className}(ExecState* exec)\n");
            push(@$outputArray, "{\n");

            push(@$outputArray, "    ${constructorClassName}* castedThis = jsCast<${constructorClassName}*>(exec->callee());\n");

            my $function = $dataNode->constructor;
            my @constructorArgList;

            $implIncludes{"<runtime/Error.h>"} = 1;

            GenerateArgumentsCountCheck($outputArray, $function, $dataNode);

            if (@{$function->raisesExceptions} || $dataNode->extendedAttributes->{"ConstructorRaisesException"}) {
                $implIncludes{"ExceptionCode.h"} = 1;
                push(@$outputArray, "    ExceptionCode ec = 0;\n");
            }

            # FIXME: For now, we do not support SVG constructors.
            # FIXME: Currently [Constructor(...)] does not yet support [Optional] arguments.
            # It just supports [Optional=DefaultIsUndefined] or [Optional=DefaultIsNullString].
            my $numParameters = @{$function->parameters};
            my ($dummy, $paramIndex) = GenerateParametersCheck($outputArray, $function, $dataNode, $numParameters, $interfaceName, "constructorCallback", undef, undef, undef);

            if ($codeGenerator->ExtendedAttributeContains($dataNode->extendedAttributes->{"CallWith"}, "ScriptExecutionContext")) {
                push(@constructorArgList, "context");
                push(@$outputArray, "    ScriptExecutionContext* context = castedThis->scriptExecutionContext();\n");
                push(@$outputArray, "    if (!context)\n");
                push(@$outputArray, "        return throwVMError(exec, createReferenceError(exec, \"${interfaceName} constructor associated document is unavailable\"));\n");
            }
            if ($generatingNamedConstructor) {
                push(@constructorArgList, "castedThis->document()");
            }

            my $index = 0;
            foreach my $parameter (@{$function->parameters}) {
                last if $index eq $paramIndex;
                push(@constructorArgList, $parameter->name);
                $index++;
            }

            if ($dataNode->extendedAttributes->{"ConstructorRaisesException"}) {
                push(@constructorArgList, "ec");
            }
            my $constructorArg = join(", ", @constructorArgList);
            if ($generatingNamedConstructor) {
                push(@$outputArray, "    RefPtr<${interfaceName}> object = ${interfaceName}::createForJSConstructor(${constructorArg});\n");
            } else {
                push(@$outputArray, "    RefPtr<${interfaceName}> object = ${interfaceName}::create(${constructorArg});\n");
            }

            if ($dataNode->extendedAttributes->{"ConstructorRaisesException"}) {
                push(@$outputArray, "    if (ec) {\n");
                push(@$outputArray, "        setDOMException(exec, ec);\n");
                push(@$outputArray, "        return JSValue::encode(JSValue());\n");
                push(@$outputArray, "    }\n");
            }

            push(@$outputArray, "    return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get())));\n");
            push(@$outputArray, "}\n\n");
        }

        if (!$dataNode->extendedAttributes->{"NamedConstructor"} || $generatingNamedConstructor) {
            push(@$outputArray, "ConstructType ${constructorClassName}::getConstructData(JSCell*, ConstructData& constructData)\n");
            push(@$outputArray, "{\n");
            push(@$outputArray, "    constructData.native.function = construct${className};\n");
            push(@$outputArray, "    return ConstructTypeHost;\n");
            push(@$outputArray, "}\n\n");
        }
    }
}

sub IsConstructable
{
    my $dataNode = shift;

    return $dataNode->extendedAttributes->{"CustomConstructor"} || $dataNode->extendedAttributes->{"JSCustomConstructor"} || $dataNode->extendedAttributes->{"Constructor"} || $dataNode->extendedAttributes->{"NamedConstructor"} || $dataNode->extendedAttributes->{"ConstructorTemplate"};
}

sub IsConstructorTemplate
{
    my $dataNode = shift;
    my $template = shift;

    return $dataNode->extendedAttributes->{"ConstructorTemplate"} && $dataNode->extendedAttributes->{"ConstructorTemplate"} eq $template;
}

1;