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, 2013, 2014 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>
# Copyright (C) 2012 Ericsson AB. All rights reserved.
# Copyright (C) 2007, 2008, 2009, 2012 Google Inc.
# Copyright (C) 2013 Samsung Electronics. All rights reserved.
#
# 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";
use Hasher;

my $codeGenerator;

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

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

my $beginAppleCopyrightForHeaderFiles = <<END;
// ------- Begin Apple Copyright -------
/*
 * Copyright (C) 2008, Apple Inc. All rights reserved.
 *
 * Permission is granted by Apple to use this file to the extent
 * necessary to relink with LGPL WebKit files.
 *
 * No license or rights are granted by Apple expressly or by
 * implication, estoppel, or otherwise, to Apple patents and
 * trademarks. For the sake of clarity, no license or rights are
 * granted by Apple expressly or by implication, estoppel, or otherwise,
 * under any Apple patents, copyrights and trademarks to underlying
 * implementations of any application programming interfaces (APIs)
 * or to any functionality that is invoked by calling any API.
 */

END
my $beginAppleCopyrightForSourceFiles = <<END;
// ------- Begin Apple Copyright -------
/*
 * Copyright (C) 2008, Apple Inc. All rights reserved.
 *
 * No license or rights are granted by Apple expressly or by implication,
 * estoppel, or otherwise, to Apple copyrights, patents, trademarks, trade
 * secrets or other rights.
 */

END
my $endAppleCopyright   = <<END;
// ------- End Apple Copyright   -------

END

# 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;

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

sub GenerateInterface
{
    my $object = shift;
    my $interface = shift;
    my $defines = shift;

    $codeGenerator->LinkOverloadedFunctions($interface);

    # Start actual generation
    if ($interface->isCallback) {
        $object->GenerateCallbackHeader($interface);
        $object->GenerateCallbackImplementation($interface);
    } else {
        $object->GenerateHeader($interface);
        $object->GenerateImplementation($interface);
    }
}

sub EventHandlerAttributeEventName
{
    my $attribute = shift;

    # Remove the "on" prefix.
    my $eventType = substr($attribute->signature->name, 2);

    # FIXME: Consider adding a property in the IDL file instead of hard coding these names.

    $eventType = "show" if $eventType eq "display";

    # Note: These four names exist in HTMLElement.cpp.
    $eventType = "webkitAnimationEnd" if $eventType eq "webkitanimationend";
    $eventType = "webkitAnimationIteration" if $eventType eq "webkitanimationiteration";
    $eventType = "webkitAnimationStart" if $eventType eq "webkitanimationstart";
    $eventType = "webkitTransitionEnd" if $eventType eq "webkittransitionend";

    return "eventNames().${eventType}Event";
}

sub GenerateEventListenerCall
{
    my $functionName = shift;
    my $suffix = ucfirst $functionName;
    my $passRefPtrHandling = ($functionName eq "add") ? "" : ".ptr()";

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

    my @GenerateEventListenerImpl = ();

    push(@GenerateEventListenerImpl, <<END);
    JSValue listener = exec->argument(1);
    if (UNLIKELY(!listener.isObject()))
        return JSValue::encode(jsUndefined());
    impl.${functionName}EventListener(exec->argument(0).toString(exec)->toAtomicString(exec), createJSEventListenerFor$suffix(*exec, *asObject(listener), *castedThis)$passRefPtrHandling, exec->argument(2).toBoolean(exec));
    return JSValue::encode(jsUndefined());
END
    return @GenerateEventListenerImpl;
}

sub GetParentClassName
{
    my $interface = shift;

    return $interface->extendedAttributes->{"JSLegacyParent"} if $interface->extendedAttributes->{"JSLegacyParent"};
    return "JSDOMWrapper" unless $interface->parent;
    return "JS" . $interface->parent;
}

sub GetCallbackClassName
{
    my $className = shift;

    return "JS$className";
}

sub AddIncludesForTypeInImpl
{
    my $type = shift;
    my $isCallback = @_ ? shift : 0;
    
    AddIncludesForType($type, $isCallback, \%implIncludes);
}

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

my %typesWithoutHeader = (
    "Array" => 1,
    "DOMString" => 1,
    "DOMTimeStamp" => 1,
    "any" => 1
);

sub SkipIncludeHeader
{
    my $type = shift;

    return 1 if $codeGenerator->SkipIncludeHeader($type);
    return $typesWithoutHeader{$type};
}

my %testSupportClasses = (
    "JSInternals" => 1,
    "JSInternalSettings" => 1,
    "JSInternalSettingsGenerated" => 1,
    "JSMallocStatistics" => 1,
    "JSMemoryInfo" => 1,
    "JSTypeConversions" => 1,

    # This is for the bindings tests.
    "JSTestNode" => 1,
);

my %classesNeedingWebCoreExport = (
    "JSAudioContext" => 1,
    "JSClientRect" => 1,
    "JSClientRectList" => 1,
    "JSCSSStyleDeclaration" => 1,
    "JSDocument" => 1,
    "JSDOMPath" => 1,
    "JSDOMWindow" => 1,
    "JSElement" => 1,
    "JSFile" => 1,
    "JSHTMLElement" => 1,
    "JSHTMLMediaElement" => 1,
    "JSNode" => 1,
    "JSNotification" => 1,
    "JSRange" => 1,
    "JSScriptProfile" => 1,
    "JSScriptProfileNode" => 1,
    "JSSourceBuffer" => 1,
    "JSTimeRanges" => 1,
    "JSXMLHttpRequest" => 1,

    # This is for the bindings tests.
    "JSTestInterface" => 1,
);

sub ExportLabelForClass
{
    my $class = shift;

    return "WEBCORE_TESTSUPPORT_EXPORT " if $testSupportClasses{$class};
    return "WEBCORE_EXPORT " if $classesNeedingWebCoreExport{$class};
    return "";
}

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

    return if SkipIncludeHeader($type);
    
    # When we're finished with the one-file-per-class
    # reorganization, we won't need these special cases.
    if ($type eq "XPathNSResolver") {
        $includesRef->{"JSXPathNSResolver.h"} = 1;
        $includesRef->{"JSCustomXPathNSResolver.h"} = 1;
    } elsif ($isCallback && $codeGenerator->IsWrapperType($type)) {
        $includesRef->{"JS${type}.h"} = 1;
    } elsif ($codeGenerator->GetSequenceType($type) or $codeGenerator->GetArrayType($type)) {
        my $arrayType = $codeGenerator->GetArrayType($type);
        my $sequenceType = $codeGenerator->GetSequenceType($type);
        my $arrayOrSequenceType = $arrayType || $sequenceType;

        if ($arrayType eq "DOMString") {
            $includesRef->{"JSDOMStringList.h"} = 1;
            $includesRef->{"DOMStringList.h"} = 1;
        } elsif ($codeGenerator->IsRefPtrType($arrayOrSequenceType)) {
            $includesRef->{"JS${arrayOrSequenceType}.h"} = 1;
            $includesRef->{"${arrayOrSequenceType}.h"} = 1;
        }
        $includesRef->{"<runtime/JSArray.h>"} = 1;
    } else {
        # default, include the same named file
        $includesRef->{"${type}.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};
        $implIncludes{$header} = "$oldValue|$conditional" if $oldValue ne 1;
    }
}

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

sub IsReadonly
{
    my $attribute = shift;
    return $attribute->isReadOnly && !$attribute->signature->extendedAttributes->{"Replaceable"};
}

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

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

sub AddClassForwardIfNeeded
{
    my $interfaceName = shift;

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

sub GetGenerateIsReachable
{
    my $interface = shift;
    return $interface->extendedAttributes->{"GenerateIsReachable"};
}

sub GetCustomIsReachable
{
    my $interface = shift;
    return $interface->extendedAttributes->{"CustomIsReachable"};
}

sub IsDOMGlobalObject
{
    my $interface = shift;
    return $interface->name eq "DOMWindow" || $codeGenerator->InheritsInterface($interface, "WorkerGlobalScope");
}

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

    my $namespaceMaybe = ($inlined ? "JSC::" : "");
    my $namedGetterFunction = GetNamedGetterFunction($interface);
    my $indexedGetterFunction = GetIndexedGetterFunction($interface);

    my @getOwnPropertySlotImpl = ();

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

    my $manualLookupGetterGeneration = sub {
        my $requiresManualLookup = $indexedGetterFunction || $namedGetterFunction;
        if ($requiresManualLookup) {
            push(@getOwnPropertySlotImpl, "    const ${namespaceMaybe}HashTableValue* entry = getStaticValueSlotEntryWithoutCaching<$className>(exec, propertyName);\n");
            push(@getOwnPropertySlotImpl, "    if (entry) {\n");
            push(@getOwnPropertySlotImpl, "        slot.setCacheableCustom(thisObject, entry->attributes(), entry->propertyGetter());\n");
            push(@getOwnPropertySlotImpl, "        return true;\n");
            push(@getOwnPropertySlotImpl, "    }\n");
        }
    };

    if (!$interface->extendedAttributes->{"CustomNamedGetter"} and InstanceAttributeCount($interface) > 0) {
        &$manualLookupGetterGeneration();
    }

    if ($indexedGetterFunction) {
        push(@getOwnPropertySlotImpl, "    Optional<uint32_t> optionalIndex = parseIndex(propertyName);\n");

        # If the item function returns a string then we let the TreatReturnedNullStringAs handle the cases
        # where the index is out of range.
        if ($indexedGetterFunction->signature->type eq "DOMString") {
            push(@getOwnPropertySlotImpl, "    if (optionalIndex) {\n");
        } else {
            push(@getOwnPropertySlotImpl, "    if (optionalIndex && optionalIndex.value() < thisObject->impl().length()) {\n");
        }
        push(@getOwnPropertySlotImpl, "        unsigned index = optionalIndex.value();\n");
        # Assume that if there's a setter, the index will be writable
        if ($interface->extendedAttributes->{"CustomIndexedSetter"}) {
            push(@getOwnPropertySlotImpl, "        unsigned attributes = ${namespaceMaybe}DontDelete;\n");
        } else {
            push(@getOwnPropertySlotImpl, "        unsigned attributes = ${namespaceMaybe}DontDelete | ${namespaceMaybe}ReadOnly;\n");
        }
        push(@getOwnPropertySlotImpl, "        slot.setValue(thisObject, attributes, " . GetIndexedGetterExpression($indexedGetterFunction) . ");\n");
        push(@getOwnPropertySlotImpl, "        return true;\n");
        push(@getOwnPropertySlotImpl, "    }\n");
    }

    if ($namedGetterFunction || $interface->extendedAttributes->{"CustomNamedGetter"}) {
        push(@getOwnPropertySlotImpl, "    if (canGetItemsForName(exec, &thisObject->impl(), propertyName)) {\n");
        push(@getOwnPropertySlotImpl, "        slot.setCustom(thisObject, ReadOnly | DontDelete | DontEnum, 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 ($interface->extendedAttributes->{"CustomNamedGetter"}) {
        &$manualLookupGetterGeneration();
    }

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

    if ($hasAttributes) {
        if ($inlined) {
            push(@getOwnPropertySlotImpl, "    return ${namespaceMaybe}getStaticValueSlot<$className, Base>(exec, *info()->staticPropHashTable, thisObject, propertyName, slot);\n");
        } else {
            push(@getOwnPropertySlotImpl, "    return ${namespaceMaybe}getStaticValueSlot<$className, Base>(exec, ${className}Table, thisObject, propertyName, slot);\n");
        }
    } else {
        push(@getOwnPropertySlotImpl, "    return Base::getOwnPropertySlot(thisObject, exec, propertyName, slot);\n");
    }

    return @getOwnPropertySlotImpl;
}

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

    my @headerContentHeader;
    if ($interface->extendedAttributes->{"AppleCopyright"}) {
        @headerContentHeader = split("\r", $beginAppleCopyrightForHeaderFiles);
    } else {
        @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($interface);
    push(@headerContentHeader, "#if ${conditionalString}\n\n") if $conditionalString;
    return @headerContentHeader;
}

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

    my @implContentHeader;
    if ($interface->extendedAttributes->{"AppleCopyright"}) {
        @implContentHeader = split("\r", $beginAppleCopyrightForSourceFiles);
    } else {
        @implContentHeader = split("\r", $headerTemplate);
    }

    push(@implContentHeader, "\n#include \"config.h\"\n");
    my $conditionalString = $codeGenerator->GenerateConditionalString($interface);
    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 ShouldGenerateToJSDeclaration
{
    my ($hasParent, $interface) = @_;
    return 0 if ($interface->extendedAttributes->{"SuppressToJSObject"});
    return 0 if $interface->name eq "AbstractView";
    return 1 if (!$hasParent or $interface->extendedAttributes->{"JSGenerateToJSObject"} or $interface->extendedAttributes->{"CustomToJSObject"});
    return 0;
}

sub ShouldGenerateToJSImplementation
{
    my ($hasParent, $interface) = @_;
    return 0 if ($interface->extendedAttributes->{"SuppressToJSObject"});
    return 0 if $interface->name eq "AbstractView";
    return 1 if ((!$hasParent or $interface->extendedAttributes->{"JSGenerateToJSObject"}) and !$interface->extendedAttributes->{"CustomToJSObject"});
    return 0;
}

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 GetSpecialAccessorFunctionForType
{
    my $interface = shift;
    my $special = shift;
    my $firstParameterType = shift;
    my $numberOfParameters = shift;

    foreach my $function (@{$interface->functions}, @{$interface->anonymousFunctions}) {
        my $specials = $function->signature->specials;
        my $specialExists = grep { $_ eq $special } @$specials;
        my $parameters = $function->parameters;
        if ($specialExists and scalar(@$parameters) == $numberOfParameters and $parameters->[0]->type eq $firstParameterType) {
            return $function;
        }
    }

    return 0;
}

sub HasComplexGetOwnProperty
{
    my $interface = shift;

    my $namedGetterFunction = GetNamedGetterFunction($interface);
    my $indexedGetterFunction = GetIndexedGetterFunction($interface);

    my $hasImpureNamedGetter = $namedGetterFunction
        || $interface->extendedAttributes->{"CustomNamedGetter"};

    my $hasComplexGetter = $indexedGetterFunction
        || $interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}
        || $interface->extendedAttributes->{"CustomGetOwnPropertySlot"}
        || $hasImpureNamedGetter;

    return 1 if $interface->extendedAttributes->{"CheckSecurity"};
    return 1 if IsDOMGlobalObject($interface);
    return 1 if $hasComplexGetter;
    return 0;
}


sub InterfaceRequiresAttributesOnInstanceForCompatibility
{
    my $interface = shift;
    my $interfaceName = $interface->name;

    # Needed for compatibility with existing content
    return 1 if $interfaceName =~ "Touch";
    return 1 if $interfaceName =~ "Navigator";
    return 1 if $interfaceName =~ "ClientRect";
    # FIXME: Once https://bugs.webkit.org/show_bug.cgi?id=134364 is fixed, we can remove this.
    return 1 if $interfaceName =~ "XMLHttpRequest";

    return 0;
}

sub InterfaceRequiresAttributesOnInstance
{
    my $interface = shift;
    my $interfaceName = $interface->name;
    my $namedGetterFunction = GetNamedGetterFunction($interface);
    my $indexedGetterFunction = GetIndexedGetterFunction($interface);

    # FIXME: All these return 1 if ... should ideally be removed.
    # Some of them are unavoidable due to DOM weirdness, in which case we should
    # add an IDL attribute for them

    # FIXME: We should rearrange how custom named getters and getOwnPropertySlot
    # overrides are handled so that we get the correct semantics and lookup ordering
    my $hasImpureNamedGetter = $namedGetterFunction
        || $interface->extendedAttributes->{"CustomNamedGetter"};
    return 1 if $hasImpureNamedGetter
        || $interface->extendedAttributes->{"CustomGetOwnPropertySlot"};

    # FIXME: These two should be fixed by removing the custom override of message, etc
    return 1 if $interfaceName =~ "Exception";
    return 1 if $interfaceName =~ "Error";

    return 1 if IsDOMGlobalObject($interface);

    return 1 if InterfaceRequiresAttributesOnInstanceForCompatibility($interface);

    #FIXME: We currently clobber performance for a number of the list types
    return 1 if $interfaceName =~ "List" && !($interfaceName =~ "Element");

    return 0;
}

sub ConstructorShouldBeOnInstance
{
    my $interface = shift;
    return 1 if $interface->extendedAttributes->{"CheckSecurity"};
    return HasComplexGetOwnProperty($interface);
}

sub AttributeShouldBeOnInstanceForCompatibility
{
    my $interface = shift;
    my $attribute = shift;
    my $interfaceName = $interface->name;
    return 0;
}

sub AttributeShouldBeOnInstance
{
    my $interface = shift;
    my $attribute = shift;

    return 1 if InterfaceRequiresAttributesOnInstance($interface);
    return 1 if $attribute->signature->type =~ /Constructor$/;
    return 1 if HasCustomGetter($attribute->signature->extendedAttributes);
    return 1 if HasCustomSetter($attribute->signature->extendedAttributes);

    # FIXME: Length is a tricky attribute to handle correctly as it is frequently tied to
    # objects which also have magic named attributes that can end up being named "length"
    # and so interfere with lookup ordering.  I'm not sure what the correct solution is
    # here.
    return 1 if ($attribute->signature->name eq "length") && $interface->name ne "CharacterData";
    
    # It becomes hard to reason about attributes that require security checks if we push
    # them down the prototype chain, so before we do these we'll need to carefully consider
    # the possible pitfalls.
    return 1 if $attribute->signature->extendedAttributes->{"CheckSecurityForNode"};

    return 1 if AttributeShouldBeOnInstanceForCompatibility($interface, $attribute);

    if ($interface->extendedAttributes->{"CheckSecurity"}) {
        if ($attribute->signature->extendedAttributes->{"DoNotCheckSecurity"} or
            $attribute->signature->extendedAttributes->{"DoNotCheckSecurityOnGetter"}) {
            return 0;
        }
        return 1;
    }
    return 0;
}

sub GetIndexedGetterFunction
{
    my $interface = shift;
    return GetSpecialAccessorFunctionForType($interface, "getter", "unsigned long", 1);
}

sub GetNamedGetterFunction
{
    my $interface = shift;
    return GetSpecialAccessorFunctionForType($interface, "getter", "DOMString", 1);
}

sub InstanceAttributeCount
{
    my $interface = shift;
    my $count = 0;
    foreach my $attribute (@{$interface->attributes}) {
        $count = $count + AttributeShouldBeOnInstance($interface, $attribute);
    }
    $count = $count + 1 if ConstructorShouldBeOnInstance($interface);
    return $count;
}

sub PrototypeAttributeCount
{
    my $interface = shift;
    my $count = 0;
    foreach my $attribute (@{$interface->attributes}) {
        $count = $count + 1 if !AttributeShouldBeOnInstance($interface, $attribute);
    }
    $count = $count + 1 if !ConstructorShouldBeOnInstance($interface);
    return $count;
}

sub InstanceOverridesGetOwnPropertySlot
{
    my $interface = shift;
    my $numInstanceAttributes = InstanceAttributeCount($interface);

    my $namedGetterFunction = GetNamedGetterFunction($interface);
    my $indexedGetterFunction = GetIndexedGetterFunction($interface);

    my $hasImpureNamedGetter = $namedGetterFunction
        || $interface->extendedAttributes->{"CustomNamedGetter"};

    my $hasComplexGetter = $indexedGetterFunction
        || $interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}
        || $interface->extendedAttributes->{"CustomGetOwnPropertySlot"}
        || $hasImpureNamedGetter;

    return $numInstanceAttributes > 0 || $hasComplexGetter;

}

sub PrototypeOverridesGetOwnPropertySlot
{
    my $interface = shift;
    my $numPrototypeAttributes = PrototypeAttributeCount($interface);
    my $numConstants = @{$interface->constants};
    my $numFunctions = @{$interface->functions};
    return $numFunctions > 0 || $numConstants > 0 || $numPrototypeAttributes > 0;
}

sub InstanceOverridesPutImplementation
{
    my $interface = shift;
    return $interface->extendedAttributes->{"CustomNamedSetter"}
        || $interface->extendedAttributes->{"CustomIndexedSetter"};
}

sub InstanceOverridesPutDeclaration
{
    my $interface = shift;
    return $interface->extendedAttributes->{"CustomPutFunction"}
        || $interface->extendedAttributes->{"CustomNamedSetter"}
        || $interface->extendedAttributes->{"CustomIndexedSetter"};
}

sub InstanceNeedsVisitChildren
{
    my $interface = shift;
    return $interface->extendedAttributes->{"JSCustomMarkFunction"}
        || $interface->extendedAttributes->{"EventTarget"}
        || $interface->name eq "EventTarget"
        || $interface->extendedAttributes->{"ReportExtraMemoryCost"};
}

sub GetImplClassName
{
    my $name = shift;

    return "DOMWindow" if $name eq "AbstractView";
    return $name;
}

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

    my $interfaceName = $interface->name;
    my $className = "JS$interfaceName";
    my %structureFlags = ();

    my $hasLegacyParent = $interface->extendedAttributes->{"JSLegacyParent"};
    my $hasRealParent = $interface->parent;
    my $hasParent = $hasLegacyParent || $hasRealParent;
    my $parentClassName = GetParentClassName($interface);
    my $needsVisitChildren = InstanceNeedsVisitChildren($interface);

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

    if ($hasParent) {
        $headerIncludes{"$parentClassName.h"} = 1;
    } else {
        $headerIncludes{"JSDOMWrapper.h"} = 1;
        if ($interface->isException) {
            $headerIncludes{"<runtime/ErrorPrototype.h>"} = 1;
        }
    }

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

    if ($hasParent && $interface->extendedAttributes->{"JSGenerateToNativeObject"}) {
        $headerIncludes{"$interfaceName.h"} = 1;
    }
    
    $headerIncludes{"SVGElement.h"} = 1 if $className =~ /^JSSVG/;

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

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

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

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

    if ($codeGenerator->IsSVGAnimatedType($interfaceName)) {
        $headerIncludes{"$interfaceName.h"} = 1;
    } else {
        # Implementation class forward declaration
        if (IsDOMGlobalObject($interface)) {
            AddClassForwardIfNeeded($interfaceName) unless $svgPropertyOrListPropertyType;
        }
    }

    AddClassForwardIfNeeded("JSDOMWindowShell") if $interfaceName eq "DOMWindow";
    AddClassForwardIfNeeded("JSDictionary") if $codeGenerator->IsConstructorTemplate($interface, "Event");

    my $exportLabel = ExportLabelForClass($className);

    # Class declaration
    push(@headerContent, "class $exportLabel$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::VM& vm, JSC::Structure* structure, Ref<$implType>&& impl, JSDOMWindowShell* windowShell)\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(vm.heap)) ${className}(vm, structure, WTF::move(impl), windowShell);\n");
        push(@headerContent, "        ptr->finishCreation(vm, windowShell);\n");
        push(@headerContent, "        vm.heap.addFinalizer(ptr, destroy);\n");
        push(@headerContent, "        return ptr;\n");
        push(@headerContent, "    }\n\n");
    } elsif ($codeGenerator->InheritsInterface($interface, "WorkerGlobalScope")) {
        push(@headerContent, "    static $className* create(JSC::VM& vm, JSC::Structure* structure, Ref<$implType>&& impl)\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(vm.heap)) ${className}(vm, structure, WTF::move(impl));\n");
        push(@headerContent, "        ptr->finishCreation(vm);\n");
        push(@headerContent, "        vm.heap.addFinalizer(ptr, destroy);\n");
        push(@headerContent, "        return ptr;\n");
        push(@headerContent, "    }\n\n");
    } elsif ($interface->extendedAttributes->{"MasqueradesAsUndefined"}) {
        AddIncludesForTypeInHeader($implType) unless $svgPropertyOrListPropertyType;
        push(@headerContent, "    static $className* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject, Ref<$implType>&& impl)\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        globalObject->masqueradesAsUndefinedWatchpoint()->fireAll(\"Allocated masquerading object\");\n");
        push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalObject->vm().heap)) $className(structure, globalObject, WTF::move(impl));\n");
        push(@headerContent, "        ptr->finishCreation(globalObject->vm());\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, Ref<$implType>&& impl)\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalObject->vm().heap)) $className(structure, globalObject, WTF::move(impl));\n");
        push(@headerContent, "        ptr->finishCreation(globalObject->vm());\n");
        push(@headerContent, "        return ptr;\n");
        push(@headerContent, "    }\n\n");
    }

    if (IsDOMGlobalObject($interface)) {
        push(@headerContent, "    static const bool needsDestruction = false;\n\n");
    }

    # Prototype
    unless (IsDOMGlobalObject($interface)) {
        push(@headerContent, "    static JSC::JSObject* createPrototype(JSC::VM&, JSC::JSGlobalObject*);\n");
        push(@headerContent, "    static JSC::JSObject* getPrototype(JSC::VM&, JSC::JSGlobalObject*);\n");
    }

    # JSValue to implementation type
    if (!$hasParent || $interface->extendedAttributes->{"JSGenerateToNativeObject"}) {
        if ($interfaceName eq "NodeFilter") {
            push(@headerContent, "    static PassRefPtr<NodeFilter> toWrapped(JSC::VM&, JSC::JSValue);\n");
        } elsif ($interfaceName eq "DOMStringList") {
            push(@headerContent, "    static PassRefPtr<DOMStringList> toWrapped(JSC::ExecState*, JSC::JSValue);\n");
        } else {
            push(@headerContent, "    static $implType* toWrapped(JSC::JSValue);\n");
        }
    }

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

    my $namedGetterFunction = GetNamedGetterFunction($interface);
    my $indexedGetterFunction = GetIndexedGetterFunction($interface);

    my $hasImpureNamedGetter = $namedGetterFunction
        || $interface->extendedAttributes->{"CustomNamedGetter"};

    my $hasComplexGetter =
        $indexedGetterFunction
        || $interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}
        || $interface->extendedAttributes->{"CustomGetOwnPropertySlot"}
        || $hasImpureNamedGetter;
    
    my $hasGetter = InstanceOverridesGetOwnPropertySlot($interface);

    if ($hasImpureNamedGetter) {
        $structureFlags{"JSC::HasImpureGetOwnPropertySlot"} = 1;
    }
    if ($interface->extendedAttributes->{"NewImpurePropertyFiresWatchpoints"}) {
        $structureFlags{"JSC::NewImpurePropertyFiresWatchpoints"} = 1;
    }
    if ($interface->extendedAttributes->{"CustomCall"}) {
        $structureFlags{"JSC::TypeOfShouldCallGetCallData"} = 1;
    }

    # Getters
    if ($hasGetter) {
        push(@headerContent, "    static bool getOwnPropertySlot(JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&);\n");
        push(@headerContent, "    bool getOwnPropertySlotDelegate(JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&);\n") if $interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"};
        $structureFlags{"JSC::OverridesGetOwnPropertySlot"} = 1;

        if ($hasComplexGetter) {
            push(@headerContent, "    static bool getOwnPropertySlotByIndex(JSC::JSObject*, JSC::ExecState*, unsigned propertyName, JSC::PropertySlot&);\n");
            $structureFlags{"JSC::InterceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero"} = 1;
        }
    }

    my $overridesPut = InstanceOverridesPutDeclaration($interface);

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

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

    # Class info
    if ($interfaceName eq "Node") {
        push(@headerContent, "\n");
        push(@headerContent, "protected:\n");
        push(@headerContent, "    static const JSC::ClassInfo s_info;\n");
        push(@headerContent, "public:\n");
        push(@headerContent, "    static const JSC::ClassInfo* info() { return &s_info; }\n\n");
    } else {
        push(@headerContent, "\n");
        push(@headerContent, "    DECLARE_INFO;\n\n");
    }
    # Structure ID
    if ($interfaceName eq "DOMWindow") {
        $structureFlags{"JSC::ImplementsHasInstance"} = 1;
    }
    push(@headerContent, "    static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)\n");
    push(@headerContent, "    {\n");
    if (IsDOMGlobalObject($interface)) {
        push(@headerContent, "        return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::GlobalObjectType, StructureFlags), info());\n");
    } elsif ($codeGenerator->InheritsInterface($interface, "Document")) {
        push(@headerContent, "        return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::JSType(JSDocumentWrapperType), StructureFlags), info());\n");
    } elsif ($codeGenerator->InheritsInterface($interface, "Element")) {
        push(@headerContent, "        return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::JSType(JSElementType), StructureFlags), info());\n");
    } elsif ($codeGenerator->InheritsInterface($interface, "Node")) {
        push(@headerContent, "        return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::JSType(JSNodeType), StructureFlags), info());\n");
    } else {
        push(@headerContent, "        return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info());\n");
    }
    push(@headerContent, "    }\n\n");

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

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

    # Custom deleteProperty function
    push(@headerContent, "    static bool deleteProperty(JSC::JSCell*, JSC::ExecState*, JSC::PropertyName);\n") if $interface->extendedAttributes->{"CustomDeleteProperty"};
    push(@headerContent, "    static bool deletePropertyByIndex(JSC::JSCell*, JSC::ExecState*, unsigned);\n") if $interface->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 = JSC::EnumerationMode());\n");
        push(@headerContent, "    static void getGenericPropertyNames(JSC::JSObject*, JSC::ExecState*, JSC::PropertyNameArray&, JSC::EnumerationMode = JSC::EnumerationMode());\n");
        push(@headerContent, "    static void getStructurePropertyNames(JSC::JSObject*, JSC::ExecState*, JSC::PropertyNameArray&, JSC::EnumerationMode = JSC::EnumerationMode());\n");
        push(@headerContent, "    static uint32_t getEnumerableLength(JSC::ExecState*, JSC::JSObject*);\n");
        $structureFlags{"JSC::OverridesGetPropertyNames"} = 1;
    }

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

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

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

    # Constructor object getter
    unless ($interface->extendedAttributes->{"NoInterfaceObject"}) {
        push(@headerContent, "    static JSC::JSValue getConstructor(JSC::VM&, JSC::JSGlobalObject*);\n");
        push(@headerContent, "    static JSC::JSValue getNamedConstructor(JSC::VM&, JSC::JSGlobalObject*);\n") if $interface->extendedAttributes->{"NamedConstructor"};
    }

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

    my $hasForwardDeclaringFunctions = 0;
    my $hasForwardDeclaringAttributes = 0;

    # Attribute and function enums
    if ($numAttributes > 0) {
        foreach (@{$interface->attributes}) {
            my $attribute = $_;
            $numCustomAttributes++ if HasCustomGetter($attribute->signature->extendedAttributes);
            $numCustomAttributes++ if HasCustomSetter($attribute->signature->extendedAttributes);
            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++;
                $needsVisitChildren = 1;
                push(@headerContent, "#endif\n") if $conditionalString;
            }
            elsif (IsReturningPromise($attribute)) {
                $headerIncludes{"JSDOMPromise.h"} = 1;

                my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
                push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
                push(@headerContent, "    JSC::Strong<JSC::JSPromiseDeferred> m_" . $attribute->signature->name . "PromiseDeferred;\n");
                push(@headerContent, "#endif\n") if $conditionalString;
            }
            if ($attribute->signature->extendedAttributes->{"ForwardDeclareInHeader"}) {
                $hasForwardDeclaringAttributes = 1;
            }
        }
    }

    # visit function
    if ($needsVisitChildren) {
        push(@headerContent, "    static void visitChildren(JSCell*, JSC::SlotVisitor&);\n");
        push(@headerContent, "    void visitAdditionalChildren(JSC::SlotVisitor&);\n") if $interface->extendedAttributes->{"JSCustomMarkFunction"};
        push(@headerContent, "\n");
    }

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

        foreach my $attribute (@{$interface->attributes}) {
            my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
            if (HasCustomGetter($attribute->signature->extendedAttributes)) {
                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 (HasCustomSetter($attribute->signature->extendedAttributes) && !IsReadonly($attribute)) {
                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 (@{$interface->functions}) {
        $numCustomFunctions++ if HasCustomMethod($function->signature->extendedAttributes);

        if ($function->signature->extendedAttributes->{"ForwardDeclareInHeader"}) {
            $hasForwardDeclaringFunctions = 1;
        }
    }

    if ($numCustomFunctions > 0) {
        my $inAppleCopyright = 0;
        push(@headerContent, "\n    // Custom functions\n");
        foreach my $function (@{$interface->functions}) {
            # PLATFORM_IOS
            my $needsAppleCopyright = $function->signature->extendedAttributes->{"AppleCopyright"};
            if ($needsAppleCopyright) {
                if (!$inAppleCopyright) {
                    push(@headerContent, $beginAppleCopyrightForHeaderFiles);
                    $inAppleCopyright = 1;
                }
            } elsif ($inAppleCopyright) {
                push(@headerContent, $endAppleCopyright);
                $inAppleCopyright = 0;
            }
            # end PLATFORM_IOS
            next unless HasCustomMethod($function->signature->extendedAttributes);
            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;
        }
        push(@headerContent, $endAppleCopyright) if $inAppleCopyright;
    }

    if (!$hasParent) {
        push(@headerContent, "    $implType& impl() const { return *m_impl; }\n");
        push(@headerContent, "    void releaseImpl() { std::exchange(m_impl, nullptr)->deref(); }\n\n");
        push(@headerContent, "private:\n");
        push(@headerContent, "    $implType* m_impl;\n");
    } else {
        push(@headerContent, "    $interfaceName& impl() const\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        return static_cast<$interfaceName&>(Base::impl());\n");
        push(@headerContent, "    }\n");
    }

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

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

    # Constructor
    if ($interfaceName eq "DOMWindow") {
        push(@headerContent, "    $className(JSC::VM&, JSC::Structure*, Ref<$implType>&&, JSDOMWindowShell*);\n");
    } elsif ($codeGenerator->InheritsInterface($interface, "WorkerGlobalScope")) {
        push(@headerContent, "    $className(JSC::VM&, JSC::Structure*, Ref<$implType>&&);\n");
    } else {
        push(@headerContent, "    $className(JSC::Structure*, JSDOMGlobalObject*, Ref<$implType>&&);\n\n");
        push(@headerContent, "    void finishCreation(JSC::VM& vm)\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        Base::finishCreation(vm);\n");
        push(@headerContent, "        ASSERT(inherits(info()));\n");
        push(@headerContent, "    }\n\n");
    }

    # Index setter
    if ($interface->extendedAttributes->{"CustomIndexedSetter"}) {
        push(@headerContent, "    void indexSetter(JSC::ExecState*, unsigned index, JSC::JSValue);\n");
    }
    # Name getter
    if ($namedGetterFunction || $interface->extendedAttributes->{"CustomNamedGetter"}) {
        push(@headerContent, "private:\n");
        push(@headerContent, "    static bool canGetItemsForName(JSC::ExecState*, $interfaceName*, JSC::PropertyName);\n");
        push(@headerContent, "    static JSC::EncodedJSValue nameGetter(JSC::ExecState*, JSC::JSObject*, JSC::EncodedJSValue, JSC::PropertyName);\n");
    }

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

    if (!$hasParent ||
        GetGenerateIsReachable($interface) ||
        GetCustomIsReachable($interface) ||
        $interface->extendedAttributes->{"JSCustomFinalize"} ||
        $codeGenerator->InheritsExtendedAttribute($interface, "ActiveDOMObject")) {
        if ($interfaceName ne "Node" && $codeGenerator->InheritsInterface($interface, "Node")) {
            $headerIncludes{"JSNode.h"} = 1;
            push(@headerContent, "class JS${interfaceName}Owner : public JSNodeOwner {\n");
        } else {
            push(@headerContent, "class JS${interfaceName}Owner : public JSC::WeakHandleOwner {\n");
        }
        $headerIncludes{"<wtf/NeverDestroyed.h>"} = 1;
        push(@headerContent, "public:\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, "    static NeverDestroyed<JS${interfaceName}Owner> owner;\n");
        push(@headerContent, "    return &owner.get();\n");
        push(@headerContent, "}\n");
        push(@headerContent, "\n");
    }
    if (ShouldGenerateToJSDeclaration($hasParent, $interface)) {
        # Node and NodeList have custom inline implementations which thus cannot be exported.
        # FIXME: The special case for Node and NodeList should probably be implemented via an IDL attribute.
        if ($implType eq "Node" or $implType eq "NodeList") {
            push(@headerContent, "JSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject*, $implType*);\n");
        } else {
            push(@headerContent, $exportLabel."JSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject*, $implType*);\n");
        }
        push(@headerContent, "inline JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, $implType& impl) { return toJS(exec, globalObject, &impl); }\n");
    }
    if ($usesToJSNewlyCreated{$interfaceName}) {
        push(@headerContent, "JSC::JSValue toJSNewlyCreated(JSC::ExecState*, JSDOMGlobalObject*, $interfaceName*);\n");
    }
    
    push(@headerContent, "\n");

    # Add prototype declaration.
    if (HeaderNeedsPrototypeDeclaration($interface)) {
        GeneratePrototypeDeclaration(\@headerContent, $className, $interface, $interfaceName);
    }

    if ($hasForwardDeclaringFunctions) {
        my $inAppleCopyright = 0;
        push(@headerContent,"// Functions\n\n");
        foreach my $function (@{$interface->functions}) {
            next if $function->{overloadIndex} && $function->{overloadIndex} > 1;
            next unless $function->signature->extendedAttributes->{"ForwardDeclareInHeader"};

            my $needsAppleCopyright = $function->signature->extendedAttributes->{"AppleCopyright"};
            if ($needsAppleCopyright) {
                if (!$inAppleCopyright) {
                    push(@headerContent, $beginAppleCopyrightForHeaderFiles);
                    $inAppleCopyright = 1;
                }
            } elsif ($inAppleCopyright) {
                push(@headerContent, $endAppleCopyright);
                $inAppleCopyright = 0;
            }

            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;
        }

        push(@headerContent, $endAppleCopyright) if $inAppleCopyright;
    }

    if ($hasForwardDeclaringAttributes) {
        push(@headerContent,"// Attributes\n\n");
        foreach my $attribute (@{$interface->attributes}) {
            next unless $attribute->signature->extendedAttributes->{"ForwardDeclareInHeader"};

            my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
            push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
            my $getter = GetAttributeGetterName($interfaceName, $className, $attribute);
            push(@headerContent, "JSC::EncodedJSValue ${getter}(JSC::ExecState*, JSC::JSObject*, JSC::EncodedJSValue, JSC::PropertyName);\n");
            if (!IsReadonly($attribute)) {
                my $setter = GetAttributeSetterName($interfaceName, $className, $attribute);
                push(@headerContent, "void ${setter}(JSC::ExecState*, JSC::JSObject*, JSC::EncodedJSValue, JSC::EncodedJSValue);\n");
            }
            push(@headerContent, "#endif\n") if $conditionalString;
        }
    }

    if (HasCustomConstructor($interface)) {
        push(@headerContent, "// Custom constructor\n");
        push(@headerContent, "JSC::EncodedJSValue JSC_HOST_CALL construct${className}(JSC::ExecState*);\n\n");
    }

    if ($codeGenerator->IsConstructorTemplate($interface, "Event")) {
        push(@headerContent, "bool fill${interfaceName}Init(${interfaceName}Init&, JSDictionary&);\n\n");
    }

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

    if ($interface->extendedAttributes->{"AppleCopyright"}) {
        push(@headerContent, split("\r", $endAppleCopyright));
    }
}

sub GenerateAttributesHashTable
{
    my ($object, $interface, $isInstance, $hashKeys, $hashSpecials, $hashValue1, $hashValue2, $conditionals, $entries) = @_;

    # FIXME: These should be functions on $interface.
    my $interfaceName = $interface->name;
    my $className = "JS$interfaceName";
    
    # - Add all attributes in a hashtable definition
    my $numAttributes = 0;
    if ($isInstance) {
        $numAttributes = InstanceAttributeCount($interface);
    } else {
        $numAttributes = PrototypeAttributeCount($interface);
    }


    if (ConstructorShouldBeOnInstance($interface) == $isInstance) {

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

    return 0 if !$numAttributes;

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

        my @specials = ();
        # As per Web IDL specification, constructor properties on the ECMAScript global object should be
        # configurable and should not be enumerable.
        my $is_global_constructor = $attribute->signature->type =~ /Constructor$/;
        push(@specials, "DontDelete") unless ($attribute->signature->extendedAttributes->{"Deletable"} || $is_global_constructor);
        push(@specials, "DontEnum") if ($attribute->signature->extendedAttributes->{"NotEnumerable"} || $is_global_constructor);
        push(@specials, "ReadOnly") if IsReadonly($attribute);
        push(@specials, "CustomAccessor") unless $is_global_constructor;
        my $special = (@specials > 0) ? join(" | ", @specials) : "0";
        push(@$hashSpecials, $special);

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

        if (IsReadonly($attribute)) {
            push(@$hashValue2, "0");
        } else {
            my $setter = GetAttributeSetterName($interfaceName, $className, $attribute);
            push(@$hashValue2, $setter);
        }

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

    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 = $parameter->type;

        # Only DOMString or wrapper types are checked.
        # For DOMString with StrictTypeChecking only Null, Undefined and Object
        # are accepted for compatibility. Otherwise, no restrictions are made to
        # match the non-overloaded behavior.
        # FIXME: Implement WebIDL overload resolution algorithm.
        if ($codeGenerator->IsStringType($type) || $codeGenerator->IsEnumType($type)) {
            if ($parameter->extendedAttributes->{"StrictTypeChecking"}) {
                push(@andExpression, "(${value}.isUndefinedOrNull() || ${value}.isString() || ${value}.isObject())");
                $usedArguments{$parameterIndex} = 1;
            }
        } elsif ($codeGenerator->IsCallbackInterface($parameter->type)) {
            # For Callbacks only checks if the value is null or object.
            push(@andExpression, "(${value}.isNull() || ${value}.isFunction())");
            $usedArguments{$parameterIndex} = 1;
        } elsif (!IsNativeType($type)) {
            my $condition = "";
            $condition .= "${value}.isUndefined() || " if $parameter->isOptional;

            # FIXME: WebIDL says that undefined is also acceptable for nullable parameters and
            # should be converted to null:
            # http://heycam.github.io/webidl/#es-nullable-type
            $condition .= "${value}.isNull() || " if $parameter->isNullable;

            if ($codeGenerator->GetArrayType($type) || $codeGenerator->GetSequenceType($type)) {
                # FIXME: Add proper support for T[], T[]?, sequence<T>.
                $condition .= "(${value}.isObject() && isJSArray(${value}))";
            } else {
                $condition .= "(${value}.isObject() && asObject(${value})->inherits(JS${type}::info()))";
            }
            push(@andExpression, "(" . $condition . ")");
            $usedArguments{$parameterIndex} = 1;
        }
        $parameterIndex++;
    }
    my $res = join(" && ", @andExpression);
    $res = "($res)" if @andExpression > 1;
    return ($res, sort {$a <=> $b} (keys %usedArguments));
}

# As per Web IDL specification, the length of a function Object is
# its number of mandatory parameters.
sub GetFunctionLength
{
  my $function = shift;

  my $numMandatoryParams = 0;
  foreach my $parameter (@{$function->parameters}) {
    # Abort as soon as we find the first optional parameter as no mandatory
    # parameter can follow an optional one.
    last if $parameter->isOptional;
    $numMandatoryParams++;
  }
  return $numMandatoryParams;
}

sub GenerateFunctionParametersCheck
{
    my $function = shift;

    my @orExpression = ();
    my $numParameters = 0;
    my @neededArguments = ();
    my $hasVariadic = 0;
    my $numMandatoryParams = @{$function->parameters};

    foreach my $parameter (@{$function->parameters}) {
        if ($parameter->isOptional) {
            my ($expression, @usedArguments) = GenerateParametersCheckExpression($numParameters, $function);
            push(@orExpression, $expression);
            push(@neededArguments, @usedArguments);
            $numMandatoryParams--;
        }
        if ($parameter->isVariadic) {
            $hasVariadic = 1;
            last;
        }
        $numParameters++;
    }
    if (!$hasVariadic) {
        my ($expression, @usedArguments) = GenerateParametersCheckExpression($numParameters, $function);
        push(@orExpression, $expression);
        push(@neededArguments, @usedArguments);
    }
    return ($numMandatoryParams, join(" || ", @orExpression), @neededArguments);
}

sub LengthOfLongestFunctionParameterList
{
    my ($overloads) = @_;
    my $result = 0;
    foreach my $overload (@{$overloads}) {
        my @parameters = @{$overload->parameters};
        $result = @parameters if $result < @parameters;
    }
    return $result;
}

sub GenerateOverloadedFunction
{
    my $function = shift;
    my $interface = shift;
    my $interfaceName = 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${interfaceName}${kind}Function" . $codeGenerator->WK_ucfirst($function->signature->name);

    # FIXME: Implement support for overloaded functions with variadic arguments.
    my $lengthOfLongestOverloadedFunctionParameterList = LengthOfLongestFunctionParameterList($function->{overloads});

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

    my %fetchedArguments = ();
    my $leastNumMandatoryParams = 255;

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

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

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

        push(@implContent, "    if ($parametersCheck)\n");
        push(@implContent, "        return ${functionName}$overload->{overloadIndex}(exec);\n");
        push(@implContent, "#endif\n\n") if $conditionalString;

    }
    if ($leastNumMandatoryParams >= 1) {
        push(@implContent, "    if (argsCount < $leastNumMandatoryParams)\n");
        push(@implContent, "        return throwVMError(exec, createNotEnoughArgumentsError(exec));\n");
    }
    push(@implContent, <<END);
    return throwVMTypeError(exec);
}

END
}

sub GetNativeTypeForConversions
{
    my $interface = shift;
    my $interfaceName = $interface->name;
    $interfaceName = $codeGenerator->GetSVGTypeNeedingTearOff($interfaceName) if $codeGenerator->IsSVGTypeNeedingTearOff($interfaceName);
    return $interfaceName;
}

# See http://refspecs.linux-foundation.org/cxxabi-1.83.html.
sub GetGnuVTableRefForInterface
{
    my $interface = shift;
    my $vtableName = GetGnuVTableNameForInterface($interface);
    if (!$vtableName) {
        return "0";
    }
    my $typename = GetNativeTypeForConversions($interface);
    my $offset = GetGnuVTableOffsetForType($typename);
    return "&" . $vtableName . "[" . $offset . "]";
}

sub GetGnuVTableNameForInterface
{
    my $interface = shift;
    my $typename = GetNativeTypeForConversions($interface);
    my $templatePosition = index($typename, "<");
    return "" if $templatePosition != -1;
    return "" if GetImplementationLacksVTableForInterface($interface);
    return "" if GetSkipVTableValidationForInterface($interface);
    return "_ZTV" . GetGnuMangledNameForInterface($interface);
}

sub GetGnuMangledNameForInterface
{
    my $interface = shift;
    my $typename = GetNativeTypeForConversions($interface);
    my $templatePosition = index($typename, "<");
    if ($templatePosition != -1) {
        return "";
    }
    my $mangledType = length($typename) . $typename;
    my $namespace = GetNamespaceForInterface($interface);
    my $mangledNamespace =  "N" . length($namespace) . $namespace;
    return $mangledNamespace . $mangledType . "E";
}

sub GetGnuVTableOffsetForType
{
    my $typename = shift;
    if ($typename eq "SVGAElement"
        || $typename eq "SVGCircleElement"
        || $typename eq "SVGClipPathElement"
        || $typename eq "SVGDefsElement"
        || $typename eq "SVGEllipseElement"
        || $typename eq "SVGForeignObjectElement"
        || $typename eq "SVGGElement"
        || $typename eq "SVGImageElement"
        || $typename eq "SVGLineElement"
        || $typename eq "SVGPathElement"
        || $typename eq "SVGPolyElement"
        || $typename eq "SVGPolygonElement"
        || $typename eq "SVGPolylineElement"
        || $typename eq "SVGRectElement"
        || $typename eq "SVGSVGElement"
        || $typename eq "SVGGraphicsElement"
        || $typename eq "SVGSwitchElement"
        || $typename eq "SVGTextElement"
        || $typename eq "SVGUseElement") {
        return "3";
    }
    return "2";
}

# See http://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B_Name_Mangling.
sub GetWinVTableRefForInterface
{
    my $interface = shift;
    my $vtableName = GetWinVTableNameForInterface($interface);
    return 0 if !$vtableName;
    return "__identifier(\"" . $vtableName . "\")";
}

sub GetWinVTableNameForInterface
{
    my $interface = shift;
    my $typename = GetNativeTypeForConversions($interface);
    my $templatePosition = index($typename, "<");
    return "" if $templatePosition != -1;
    return "" if GetImplementationLacksVTableForInterface($interface);
    return "" if GetSkipVTableValidationForInterface($interface);
    return "??_7" . GetWinMangledNameForInterface($interface) . "6B@";
}

sub GetWinMangledNameForInterface
{
    my $interface = shift;
    my $typename = GetNativeTypeForConversions($interface);
    my $namespace = GetNamespaceForInterface($interface);
    return $typename . "@" . $namespace . "@@";
}

sub GetNamespaceForInterface
{
    my $interface = shift;
    return $interface->extendedAttributes->{"ImplementationNamespace"} || "WebCore";
}

sub GetImplementationLacksVTableForInterface
{
    my $interface = shift;
    return $interface->extendedAttributes->{"ImplementationLacksVTable"};
}

sub GetSkipVTableValidationForInterface
{
    my $interface = shift;
    return $interface->extendedAttributes->{"SkipVTableValidation"};
}

# URL becomes url, but SetURL becomes setURL.
sub ToMethodName
{
    my $param = shift;
    my $ret = lcfirst($param);
    $ret =~ s/hTML/html/ if $ret =~ /^hTML/;
    $ret =~ s/uRL/url/ if $ret =~ /^uRL/;
    $ret =~ s/jS/js/ if $ret =~ /^jS/;
    $ret =~ s/xML/xml/ if $ret =~ /^xML/;
    $ret =~ s/xSLT/xslt/ if $ret =~ /^xSLT/;
    $ret =~ s/cSS/css/ if $ret =~ /^cSS/;

    # For HTML5 FileSystem API Flags attributes.
    # (create is widely used to instantiate an object and must be avoided.)
    $ret =~ s/^create/isCreate/ if $ret =~ /^create$/;
    $ret =~ s/^exclusive/isExclusive/ if $ret =~ /^exclusive$/;

    return $ret;
}

# Returns the RuntimeEnabledFeatures function name that is hooked up to check if a method/attribute is enabled.
sub GetRuntimeEnableFunctionName
{
    my $signature = shift;

    # If a parameter is given (e.g. "EnabledAtRuntime=FeatureName") return the RuntimeEnabledFeatures::sharedFeatures().{FeatureName}Enabled() method.
    return "RuntimeEnabledFeatures::sharedFeatures()." . ToMethodName($signature->extendedAttributes->{"EnabledAtRuntime"}) . "Enabled" if ($signature->extendedAttributes->{"EnabledAtRuntime"} && $signature->extendedAttributes->{"EnabledAtRuntime"} ne "VALUE_IS_MISSING");

    # Otherwise return a function named RuntimeEnabledFeatures::sharedFeatures().{methodName}Enabled().
    return "RuntimeEnabledFeatures::sharedFeatures()." . ToMethodName($signature->name) . "Enabled";
}

sub GetCastingHelperForThisObject
{
    my $interface = shift;

    if ($interface->name eq "Node") {
        return "jsNodeCast";
    }
    if ($interface->name eq "Element") {
        return "jsElementCast";
    }
    if ($interface->name eq "Document") {
        return "jsDocumentCast";
    }
    return "jsDynamicCast<JS" . $interface->name . "*>";
}

sub GetIndexedGetterExpression
{
    my $indexedGetterFunction = shift;
    if ($indexedGetterFunction->signature->type eq "DOMString") {
        return "jsStringOrUndefined(exec, thisObject->impl().item(index))";
    }
    return "toJS(exec, thisObject->globalObject(), thisObject->impl().item(index))";
}

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

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

    my $hasLegacyParent = $interface->extendedAttributes->{"JSLegacyParent"};
    my $hasRealParent = $interface->parent;
    my $hasParent = $hasLegacyParent || $hasRealParent;
    my $parentClassName = GetParentClassName($interface);
    my $visibleInterfaceName = $codeGenerator->GetVisibleInterfaceName($interface);
    my $eventTarget = $interface->extendedAttributes->{"EventTarget"} || ($codeGenerator->InheritsInterface($interface, "EventTarget") && $interface->name ne "EventTarget");
    my $needsVisitChildren = InstanceNeedsVisitChildren($interface);

    my $namedGetterFunction = GetNamedGetterFunction($interface);
    my $indexedGetterFunction = GetIndexedGetterFunction($interface);

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

    $implIncludes{"JSDOMBinding.h"} = 1;
    $implIncludes{"<wtf/GetPtr.h>"} = 1;
    $implIncludes{"<runtime/PropertyNameArray.h>"} = 1 if $indexedGetterFunction;

    my $implType = GetImplClassName($interfaceName);
    AddIncludesForTypeInImpl($implType);

    @implContent = ();

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

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

    if ($numFunctions > 0) {
        my $inAppleCopyright = 0;
        push(@implContent,"// Functions\n\n");
        foreach my $function (@{$interface->functions}) {
            next if $function->{overloadIndex} && $function->{overloadIndex} > 1;
            next if $function->signature->extendedAttributes->{"ForwardDeclareInHeader"};

            my $needsAppleCopyright = $function->signature->extendedAttributes->{"AppleCopyright"};
            if ($needsAppleCopyright) {
                if (!$inAppleCopyright) {
                    push(@implContent, $beginAppleCopyrightForHeaderFiles);
                    $inAppleCopyright = 1;
                }
            } elsif ($inAppleCopyright) {
                push(@implContent, $endAppleCopyright);
                $inAppleCopyright = 0;
            }

            my $conditionalString = $codeGenerator->GenerateConditionalString($function->signature);
            push(@implContent, "#if ${conditionalString}\n") if $conditionalString;
            my $functionName = GetFunctionName($className, $function);
            push(@implContent, "JSC::EncodedJSValue JSC_HOST_CALL ${functionName}(JSC::ExecState*);\n");
            push(@implContent, "#endif\n") if $conditionalString;
        }

        push(@implContent, $endAppleCopyright) if $inAppleCopyright;

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

    if ($numAttributes > 0 || NeedsConstructorProperty($interface)) {
        push(@implContent, "// Attributes\n\n");
        foreach my $attribute (@{$interface->attributes}) {
            next if $attribute->signature->extendedAttributes->{"ForwardDeclareInHeader"};

            my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
            push(@implContent, "#if ${conditionalString}\n") if $conditionalString;
            my $getter = GetAttributeGetterName($interfaceName, $className, $attribute);
            push(@implContent, "JSC::EncodedJSValue ${getter}(JSC::ExecState*, JSC::JSObject*, JSC::EncodedJSValue, JSC::PropertyName);\n");
            if (!IsReadonly($attribute)) {
                my $setter = GetAttributeSetterName($interfaceName, $className, $attribute);
                push(@implContent, "void ${setter}(JSC::ExecState*, JSC::JSObject*, JSC::EncodedJSValue, JSC::EncodedJSValue);\n");
            }
            push(@implContent, "#endif\n") if $conditionalString;
        }
        
        if (NeedsConstructorProperty($interface)) {
            my $getter = "js" . $interfaceName . "Constructor";
            push(@implContent, "JSC::EncodedJSValue ${getter}(JSC::ExecState*, JSC::JSObject*, JSC::EncodedJSValue, JSC::PropertyName);\n");
        }

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

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

    # Add prototype declaration.
    if (!HeaderNeedsPrototypeDeclaration($interface)) {
        GeneratePrototypeDeclaration(\@implContent, $className, $interface, $interfaceName);
    }

    # Add constructor declaration
    if (NeedsConstructorProperty($interface)) {
        $implIncludes{"JSDOMBinding.h"} = 1;
        if ($interface->extendedAttributes->{"NamedConstructor"}) {
            $implIncludes{"DOMConstructorWithDocument.h"} = 1;
        }
        GenerateConstructorDeclaration(\@implContent, $className, $interface, $interfaceName);
    }


    my @hashKeys = ();
    my @hashValue1 = ();
    my @hashValue2 = ();
    my @hashSpecials = ();
    my %conditionals = ();
    my $hashName = $className . "Table";

    my $numInstanceAttributes = GenerateAttributesHashTable($object, $interface, 1,
        \@hashKeys, \@hashSpecials,
        \@hashValue1, \@hashValue2,
        \%conditionals);

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

    # - Add all constants
    if (NeedsConstructorProperty($interface)) {
        my $hashSize = 0;
        my $hashName = $className . "ConstructorTable";

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

        my $needsConstructorTable = 0;

        foreach my $constant (@{$interface->constants}) {
            my $name = $constant->name;
            push(@hashKeys, $name);
            push(@hashValue1, $constant->value);
            push(@hashValue2, "0");
            push(@hashSpecials, "DontDelete | ReadOnly | ConstantInteger");

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

        foreach my $attribute (@{$interface->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 IsReadonly($attribute);
            my $special = (@specials > 0) ? join(" | ", @specials) : "0";
            push(@hashSpecials, $special);

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

            if (IsReadonly($attribute)) {
                push(@hashValue2, "0");
            } else {
                my $setter = GetAttributeSetterName($interfaceName, $className, $attribute);
                push(@hashValue2, $setter);
            }

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

            $hashSize++;
        }

        foreach my $function (@{$interface->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 $functionLength = GetFunctionLength($function);
            push(@hashValue2, $functionLength);

            my @specials = ();
            push(@specials, "DontDelete") if $interface->extendedAttributes->{"OperationsNotDeletable"}
                || $function->signature->extendedAttributes->{"NotDeletable"};
            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;
            }
            
            $hashSize++;
        }

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

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

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

    # - Add functions and constants to a hashtable definition

    $hashName = $className . "PrototypeTable";

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


    my $numPrototypeAttributes = GenerateAttributesHashTable($object, $interface, 0,
        \@hashKeys, \@hashSpecials,
        \@hashValue1, \@hashValue2,
        \%conditionals);
    my $hashSize = $numPrototypeAttributes;

    foreach my $constant (@{$interface->constants}) {
        my $name = $constant->name;

        push(@hashKeys, $name);
        push(@hashValue1, $constant->value);
        push(@hashValue2, "0");
        push(@hashSpecials, "DontDelete | ReadOnly | ConstantInteger");

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

    my @runtimeEnabledFunctions = ();

    foreach my $function (@{$interface->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 $functionLength = GetFunctionLength($function);
        push(@hashValue2, $functionLength);

        my @specials = ();
        push(@specials, "DontDelete") if $interface->extendedAttributes->{"OperationsNotDeletable"}
            || $function->signature->extendedAttributes->{"NotDeletable"};
        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;
        }

        push(@runtimeEnabledFunctions, $function) if $function->signature->extendedAttributes->{"EnabledAtRuntime"};

        $hashSize++;
    }

    my $justGenerateValueArray = !IsDOMGlobalObject($interface);

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

    if ($justGenerateValueArray) {
        push(@implContent, "const ClassInfo ${className}Prototype::s_info = { \"${visibleInterfaceName}Prototype\", &Base::s_info, 0, CREATE_METHOD_TABLE(${className}Prototype) };\n\n");
    } else {
        push(@implContent, "const ClassInfo ${className}Prototype::s_info = { \"${visibleInterfaceName}Prototype\", &Base::s_info, &${className}PrototypeTable, CREATE_METHOD_TABLE(${className}Prototype) };\n\n");
    }

    if (PrototypeOverridesGetOwnPropertySlot($interface)) {
        my $numPrototypeAttributes = PrototypeAttributeCount($interface);
        if (IsDOMGlobalObject($interface)) {
            push(@implContent, "bool ${className}Prototype::getOwnPropertySlot(JSObject* object, ExecState* exec, PropertyName propertyName, PropertySlot& slot)\n");
            push(@implContent, "{\n");
            push(@implContent, "    VM& vm = exec->vm();\n");
            push(@implContent, "    UNUSED_PARAM(vm);\n");
            push(@implContent, "    auto* thisObject = jsCast<${className}Prototype*>(object);\n");

            if ($numConstants eq 0 && $numFunctions eq 0 && $numPrototypeAttributes eq 0) {
                push(@implContent, "    return Base::getOwnPropertySlot(thisObject, exec, propertyName, slot);\n");        
            } elsif ($numConstants eq 0 && $numPrototypeAttributes eq 0) {
                push(@implContent, "    return getStaticFunctionSlot<JSObject>(exec, ${className}PrototypeTable, thisObject, propertyName, slot);\n");
            } elsif ($numFunctions eq 0 && $numPrototypeAttributes eq 0) {
                push(@implContent, "    return getStaticValueSlot<${className}Prototype, JSObject>(exec, ${className}PrototypeTable, thisObject, propertyName, slot);\n");
            } else {
                push(@implContent, "    return getStaticPropertySlot<${className}Prototype, JSObject>(exec, ${className}PrototypeTable, thisObject, propertyName, slot);\n");
            }
            push(@implContent, "}\n\n");
        } elsif ($numConstants > 0 || $numFunctions > 0 || $numPrototypeAttributes > 0) {
            push(@implContent, "void ${className}Prototype::finishCreation(VM& vm)\n");
            push(@implContent, "{\n");
            push(@implContent, "    Base::finishCreation(vm);\n");
            push(@implContent, "    reifyStaticProperties(vm, ${className}PrototypeTableValues, *this);\n");

            foreach my $function (@runtimeEnabledFunctions) {
                my $conditionalString = $codeGenerator->GenerateConditionalString($function->signature);
                push(@implContent, "#if ${conditionalString}\n") if $conditionalString;
                AddToImplIncludes("RuntimeEnabledFeatures.h");
                my $signature = $function->signature;
                my $enable_function = GetRuntimeEnableFunctionName($signature);
                my $name = $signature->name;
                push(@implContent, "    if (!${enable_function}()) {\n");
                push(@implContent, "        Identifier propertyName = Identifier::fromString(&vm, reinterpret_cast<const LChar*>(\"$name\"), strlen(\"$name\"));\n");
                push(@implContent, "        removeDirect(vm, propertyName);\n");
                push(@implContent, "    }\n");
                push(@implContent, "#endif\n") if $conditionalString;
            }
            push(@implContent, "}\n\n");
        } else {
            push(@implContent, "void ${className}Prototype::finishCreation(VM& vm)\n");
            push(@implContent, "{\n");
            push(@implContent, "    Base::finishCreation(vm);\n");
            push(@implContent, "}\n\n");
        }
    }

    if ($interface->extendedAttributes->{"JSCustomNamedGetterOnPrototype"}) {
        push(@implContent, "void ${className}Prototype::put(JSCell* cell, ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)\n");
        push(@implContent, "{\n");
        push(@implContent, "    auto* 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
    push(@implContent, "const ClassInfo $className" . "::s_info = { \"${visibleInterfaceName}\", &Base::s_info, ");

    if ($numInstanceAttributes > 0) {
        push(@implContent, "&${className}Table");
    } else {
        push(@implContent, "0");
    }
    push(@implContent, ", CREATE_METHOD_TABLE($className) };\n\n");

    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(VM& vm, Structure* structure, Ref<$implType>&& impl, JSDOMWindowShell* shell)\n");
        push(@implContent, "    : $parentClassName(vm, structure, WTF::move(impl), shell)\n");
        push(@implContent, "{\n");
        push(@implContent, "}\n\n");
    } elsif ($codeGenerator->InheritsInterface($interface, "WorkerGlobalScope")) {
        AddIncludesForTypeInImpl($interfaceName);
        push(@implContent, "${className}::$className(VM& vm, Structure* structure, Ref<$implType>&& impl)\n");
        push(@implContent, "    : $parentClassName(vm, structure, WTF::move(impl))\n");
        push(@implContent, "{\n");
        push(@implContent, "}\n\n");
    } else {
        push(@implContent, "${className}::$className(Structure* structure, JSDOMGlobalObject* globalObject, Ref<$implType>&& impl)\n");
        if ($hasParent) {
            push(@implContent, "    : $parentClassName(structure, globalObject, WTF::move(impl))\n");
        } else {
            push(@implContent, "    : $parentClassName(structure, globalObject)\n");
            push(@implContent, "    , m_impl(&impl.leakRef())\n");
        }
        push(@implContent, "{\n");
        push(@implContent, "}\n\n");
    }

    unless (IsDOMGlobalObject($interface)) {
        push(@implContent, "JSObject* ${className}::createPrototype(VM& vm, JSGlobalObject* globalObject)\n");
        push(@implContent, "{\n");
        if ($hasParent && $parentClassName ne "JSC::DOMNodeFilter") {
            push(@implContent, "    return ${className}Prototype::create(vm, globalObject, ${className}Prototype::createStructure(vm, globalObject, ${parentClassName}::getPrototype(vm, globalObject)));\n");
        } else {
            my $prototype = $interface->isException ? "errorPrototype" : "objectPrototype";
            push(@implContent, "    return ${className}Prototype::create(vm, globalObject, ${className}Prototype::createStructure(vm, globalObject, globalObject->${prototype}()));\n");
        }
        push(@implContent, "}\n\n");

        push(@implContent, "JSObject* ${className}::getPrototype(VM& vm, JSGlobalObject* globalObject)\n");
        push(@implContent, "{\n");
        push(@implContent, "    return getDOMPrototype<${className}>(vm, globalObject);\n");
        push(@implContent, "}\n\n");
    }

    if (!$hasParent) {
        push(@implContent, "void ${className}::destroy(JSC::JSCell* cell)\n");
        push(@implContent, "{\n");
        push(@implContent, "    ${className}* thisObject = static_cast<${className}*>(cell);\n");
        push(@implContent, "    thisObject->${className}::~${className}();\n");
        push(@implContent, "}\n\n");

        push(@implContent, "${className}::~${className}()\n");
        push(@implContent, "{\n");
        push(@implContent, "    releaseImpl();\n");
        push(@implContent, "}\n\n");
    }

    my $hasGetter = InstanceOverridesGetOwnPropertySlot($interface);

    # Attributes
    if ($hasGetter) {
        if (!$interface->extendedAttributes->{"CustomGetOwnPropertySlot"}) {
            push(@implContent, "bool ${className}::getOwnPropertySlot(JSObject* object, ExecState* exec, PropertyName propertyName, PropertySlot& slot)\n");
            push(@implContent, "{\n");
            push(@implContent, "    auto* thisObject = jsCast<${className}*>(object);\n");
            push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n");
            push(@implContent, GenerateGetOwnPropertySlotBody($interface, $interfaceName, $className, $numInstanceAttributes > 0, 0));
            push(@implContent, "}\n\n");
        }

        if ($indexedGetterFunction || $namedGetterFunction
                || $interface->extendedAttributes->{"CustomNamedGetter"}
                || $interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}) {
            push(@implContent, "bool ${className}::getOwnPropertySlotByIndex(JSObject* object, ExecState* exec, unsigned index, PropertySlot& slot)\n");
            push(@implContent, "{\n");
            push(@implContent, "    auto* thisObject = jsCast<${className}*>(object);\n");
            push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n");

            # Sink the int-to-string conversion that happens when we create a PropertyName
            # to the point where we actually need it.
            my $generatedPropertyName = 0;
            my $propertyNameGeneration = sub {
                if ($generatedPropertyName) {
                    return;
                }
                push(@implContent, "    Identifier propertyName = Identifier::from(exec, index);\n");
                $generatedPropertyName = 1;
            };

            if ($indexedGetterFunction) {
                if ($indexedGetterFunction->signature->type eq "DOMString") {
                    push(@implContent, "    if (index <= MAX_ARRAY_INDEX) {\n");
                } else {
                    push(@implContent, "    if (index < thisObject->impl().length()) {\n");
                }
                # Assume that if there's a setter, the index will be writable
                if ($interface->extendedAttributes->{"CustomIndexedSetter"}) {
                    push(@implContent, "        unsigned attributes = DontDelete;\n");
                } else {
                    push(@implContent, "        unsigned attributes = DontDelete | ReadOnly;\n");
                }
                push(@implContent, "        slot.setValue(thisObject, attributes, " . GetIndexedGetterExpression($indexedGetterFunction) . ");\n");
                push(@implContent, "        return true;\n");
                push(@implContent, "    }\n");
            }

            if ($namedGetterFunction || $interface->extendedAttributes->{"CustomNamedGetter"}) {
                &$propertyNameGeneration();
                push(@implContent, "    if (canGetItemsForName(exec, &thisObject->impl(), propertyName)) {\n");
                push(@implContent, "        slot.setCustom(thisObject, ReadOnly | DontDelete | DontEnum, thisObject->nameGetter);\n");
                push(@implContent, "        return true;\n");
                push(@implContent, "    }\n");
                $implIncludes{"wtf/text/AtomicString.h"} = 1;
            }

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

            push(@implContent, "    return Base::getOwnPropertySlotByIndex(thisObject, exec, index, slot);\n");
            push(@implContent, "}\n\n");
        }

    }
    $numAttributes = $numAttributes + 1 if NeedsConstructorProperty($interface);
    if ($numAttributes > 0) {
        foreach my $attribute (@{$interface->attributes}) {
            my $name = $attribute->signature->name;
            my $type = $attribute->signature->type;
            my $isNullable = $attribute->signature->isNullable;
            $codeGenerator->AssertNotSequenceType($type);
            my $getFunctionName = GetAttributeGetterName($interfaceName, $className, $attribute);
            my $implGetterFunctionName = $codeGenerator->WK_lcfirst($attribute->signature->extendedAttributes->{"ImplementedAs"} || $name);
            my $getterExceptions = $attribute->signature->extendedAttributes->{"GetterRaisesException"};

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

            push(@implContent, "EncodedJSValue ${getFunctionName}(ExecState* exec, JSObject* slotBase, EncodedJSValue thisValue, PropertyName)\n");
            push(@implContent, "{\n");

            push(@implContent, "    UNUSED_PARAM(exec);\n");
            push(@implContent, "    UNUSED_PARAM(slotBase);\n");
            push(@implContent, "    UNUSED_PARAM(thisValue);\n");
            if (!$attribute->isStatic || $attribute->signature->type =~ /Constructor$/) {
                if ($interface->extendedAttributes->{"CustomProxyToJSObject"}) {
                    push(@implContent, "    auto* castedThis = to${className}(JSValue::decode(thisValue));\n");
                } elsif (AttributeShouldBeOnInstance($interface, $attribute)) {
                    push(@implContent, "    auto* castedThis = jsCast<JS${interfaceName}*>(slotBase);\n");
                    if (InterfaceRequiresAttributesOnInstanceForCompatibility($interface)) {
                        push(@implContent, "    ${className}* castedThisObject = " . GetCastingHelperForThisObject($interface) . "(JSValue::decode(thisValue));\n");
                        push(@implContent, "    if (UNLIKELY(!castedThisObject))\n");
                        push(@implContent, "        reportDeprecatedGetterError(*exec, \"$interfaceName\", \"$name\");\n");
                    }
                } else {
                    push(@implContent, "    ${className}* castedThis = " . GetCastingHelperForThisObject($interface) . "(JSValue::decode(thisValue));\n");
                    push(@implContent, "    if (UNLIKELY(!castedThis)) {\n");
                    push(@implContent, "        if (jsDynamicCast<${className}Prototype*>(slotBase))\n");
                    push(@implContent, "            return reportDeprecatedGetterError(*exec, \"$interfaceName\", \"$name\");\n");
                    push(@implContent, "        return throwGetterTypeError(*exec, \"$interfaceName\", \"$name\");\n");
                    push(@implContent, "    }\n");
                }
                $implIncludes{"ScriptExecutionContext.h"} = 1;
            }

            my @arguments = ();
            if ($getterExceptions && !HasCustomGetter($attribute->signature->extendedAttributes)) {
                push(@arguments, "ec");
                push(@implContent, "    ExceptionCode ec = 0;\n");
            }

            # Global constructors can be disabled at runtime.
            if ($attribute->signature->type =~ /Constructor$/) {
                if ($attribute->signature->extendedAttributes->{"EnabledAtRuntime"}) {
                    AddToImplIncludes("RuntimeEnabledFeatures.h");
                    my $enable_function = GetRuntimeEnableFunctionName($attribute->signature);
                    push(@implContent, "    if (!${enable_function}())\n");
                    push(@implContent, "        return JSValue::encode(jsUndefined());\n");
                } elsif ($attribute->signature->extendedAttributes->{"EnabledBySetting"}) {
                    AddToImplIncludes("Frame.h");
                    AddToImplIncludes("Settings.h");
                    my $enable_function = ToMethodName($attribute->signature->extendedAttributes->{"EnabledBySetting"}) . "Enabled";
                    push(@implContent, "    if (!castedThis->impl().frame())\n");
                    push(@implContent, "        return JSValue::encode(jsUndefined());\n");
                    push(@implContent, "    Settings& settings = castedThis->impl().frame()->settings();\n");
                    push(@implContent, "    if (!settings.$enable_function())\n");
                    push(@implContent, "        return JSValue::encode(jsUndefined());\n");
                }
            }

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

            if ($interface->extendedAttributes->{"CheckSecurity"} &&
                !$attribute->signature->extendedAttributes->{"DoNotCheckSecurity"} &&
                !$attribute->signature->extendedAttributes->{"DoNotCheckSecurityOnGetter"}) {
                push(@implContent, "    if (!BindingSecurity::shouldAllowAccessToDOMWindow(exec, castedThis->impl()))\n");
                push(@implContent, "        return JSValue::encode(jsUndefined());\n");
            }

            if ($attribute->signature->extendedAttributes->{"Nondeterministic"}) {
                AddToImplIncludes("MemoizedDOMResult.h", "WEB_REPLAY");
                AddToImplIncludes("<replay/InputCursor.h>", "WEB_REPLAY");
                AddToImplIncludes("<wtf/NeverDestroyed.h>", "WEB_REPLAY");

                push(@implContent, "#if ENABLE(WEB_REPLAY)\n");
                push(@implContent, "    JSGlobalObject* globalObject = exec->lexicalGlobalObject();\n");
                push(@implContent, "    InputCursor& cursor = globalObject->inputCursor();\n");

                my $nativeType = GetNativeType($type);
                my $memoizedType = GetNativeTypeForMemoization($type);
                my $exceptionCode = $getterExceptions ? "ec" : "0";
                push(@implContent, "    static NeverDestroyed<const AtomicString> bindingName(\"$interfaceName.$name\", AtomicString::ConstructFromLiteral);\n");
                push(@implContent, "    if (cursor.isCapturing()) {\n");
                push(@implContent, "        $memoizedType memoizedResult = castedThis->impl().$implGetterFunctionName(" . join(", ", @arguments) . ");\n");
                push(@implContent, "        cursor.appendInput<MemoizedDOMResult<$memoizedType>>(bindingName.get().string(), memoizedResult, $exceptionCode);\n");
                push(@implContent, "        JSValue result = " . NativeToJSValue($attribute->signature, 0, $interfaceName, "memoizedResult", "castedThis") . ";\n");
                push(@implContent, "        setDOMException(exec, ec);\n") if $getterExceptions;
                push(@implContent, "        return JSValue::encode(result);\n");
                push(@implContent, "    }\n");
                push(@implContent, "\n");
                push(@implContent, "    if (cursor.isReplaying()) {\n");
                push(@implContent, "        $memoizedType memoizedResult;\n");
                push(@implContent, "        MemoizedDOMResultBase* input = cursor.fetchInput<MemoizedDOMResultBase>();\n");
                push(@implContent, "        if (input && input->convertTo<$memoizedType>(memoizedResult)) {\n");
                # FIXME: the generated code should report an error if an input cannot be fetched or converted.
                push(@implContent, "            JSValue result = " . NativeToJSValue($attribute->signature, 0, $interfaceName, "memoizedResult", "castedThis") . ";\n");
                push(@implContent, "            setDOMException(exec, input->exceptionCode());\n") if $getterExceptions;
                push(@implContent, "            return JSValue::encode(result);\n");
                push(@implContent, "        }\n");
                push(@implContent, "    }\n");
                push(@implContent, "#endif\n");
            } # attribute Nondeterministic

            if (HasCustomGetter($attribute->signature->extendedAttributes)) {
                push(@implContent, "    return JSValue::encode(castedThis->$implGetterFunctionName(exec));\n");
            } elsif ($attribute->signature->extendedAttributes->{"CheckSecurityForNode"}) {
                $implIncludes{"JSDOMBinding.h"} = 1;
                push(@implContent, "    auto& impl = castedThis->impl();\n");
                push(@implContent, "    return JSValue::encode(shouldAllowAccessToNode(exec, impl." . $attribute->signature->name . "()) ? " . NativeToJSValue($attribute->signature, 0, $interfaceName, "impl.$implGetterFunctionName()", "castedThis") . " : jsNull());\n");
            } elsif ($type eq "EventHandler") {
                my $getter = $attribute->signature->extendedAttributes->{"WindowEventHandler"} ? "windowEventHandlerAttribute"
                    : $attribute->signature->extendedAttributes->{"DocumentEventHandler"} ? "documentEventHandlerAttribute"
                    : "eventHandlerAttribute";
                my $eventName = EventHandlerAttributeEventName($attribute);
                push(@implContent, "    UNUSED_PARAM(exec);\n");
                push(@implContent, "    return JSValue::encode($getter(castedThis->impl(), $eventName));\n");
            } elsif ($attribute->signature->type =~ /Constructor$/) {
                my $constructorType = $attribute->signature->type;
                $constructorType =~ s/Constructor$//;
                # When Constructor attribute is used by DOMWindow.idl, it's correct to pass castedThis as the global object
                # When JSDOMWrappers have a back-pointer to the globalObject we can pass castedThis->globalObject()
                if ($interfaceName eq "DOMWindow") {
                    my $named = ($constructorType =~ /Named$/) ? "Named" : "";
                    $constructorType =~ s/Named$//;
                    push(@implContent, "    return JSValue::encode(JS" . $constructorType . "::get${named}Constructor(exec->vm(), castedThis));\n");
                } else {
                    AddToImplIncludes("JS" . $constructorType . ".h", $attribute->signature->extendedAttributes->{"Conditional"});
                    push(@implContent, "    return JSValue::encode(JS" . $constructorType . "::getConstructor(exec->vm(), castedThis->globalObject()));\n");
                }
            } elsif (!$attribute->signature->extendedAttributes->{"GetterRaisesException"}) {
                push(@implContent, "    bool isNull = false;\n") if $isNullable;

                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 JSValue::encode(cachedValue);\n");
                }

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

                if ($svgListPropertyType) {
                    push(@implContent, "    JSValue result =  " . NativeToJSValue($attribute->signature, 0, $interfaceName, "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, $interfaceName, "impl", "castedThis") . ";\n");
                    } else {
                        push(@implContent, "    JSValue result = " . NativeToJSValue($attribute->signature, 0, $interfaceName, "impl.$implGetterFunctionName(" . (join ", ", @callWithArgs) . ")", "castedThis") . ";\n");

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

                    unshift(@arguments, @callWithArgs);
                    my $jsType = NativeToJSValue($attribute->signature, 0, $interfaceName, "${functionName}(" . join(", ", @arguments) . ")", "castedThis");
                    push(@implContent, "    auto& impl = 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");
                    }

                    if ($isNullable) {
                        push(@implContent, "    if (isNull)\n");
                        push(@implContent, "        return JSValue::encode(jsNull());\n");
                    }
                }

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

            } else {
                if ($isNullable) {
                    push(@implContent, "    bool isNull = false;\n");
                    unshift(@arguments, "isNull");
                }

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

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

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

                if ($isNullable) {
                    push(@implContent, "    if (isNull)\n");
                    push(@implContent, "        return JSValue::encode(jsNull());\n");
                }

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

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

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

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

        if (NeedsConstructorProperty($interface)) {
            my $constructorFunctionName = "js" . $interfaceName . "Constructor";

            if ($interface->extendedAttributes->{"CustomProxyToJSObject"}) {
                push(@implContent, "EncodedJSValue ${constructorFunctionName}(ExecState* exec, JSObject*, EncodedJSValue thisValue, PropertyName)\n");
                push(@implContent, "{\n");
                push(@implContent, "    ${className}* domObject = to${className}(JSValue::decode(thisValue));\n");
            } elsif (ConstructorShouldBeOnInstance($interface)) {
                push(@implContent, "EncodedJSValue ${constructorFunctionName}(ExecState* exec, JSObject*, EncodedJSValue thisValue, PropertyName)\n");
                push(@implContent, "{\n");
                push(@implContent, "    ${className}* domObject = " . GetCastingHelperForThisObject($interface) . "(JSValue::decode(thisValue));\n");
            } else {
                push(@implContent, "EncodedJSValue ${constructorFunctionName}(ExecState* exec, JSObject* baseValue, EncodedJSValue, PropertyName)\n");
                push(@implContent, "{\n");
                push(@implContent, "    ${className}Prototype* domObject = jsDynamicCast<${className}Prototype*>(baseValue);\n");
            }
            push(@implContent, "    if (!domObject)\n");
            push(@implContent, "        return throwVMTypeError(exec);\n");

            if ($interface->extendedAttributes->{"CheckSecurity"}) {
                die if !ConstructorShouldBeOnInstance($interface);
                push(@implContent, "    if (!BindingSecurity::shouldAllowAccessToDOMWindow(exec, domObject->impl()))\n");
                push(@implContent, "        return JSValue::encode(jsUndefined());\n");
            }

            if (!$interface->extendedAttributes->{"NoInterfaceObject"}) {
                push(@implContent, "    return JSValue::encode(${className}::getConstructor(exec->vm(), domObject->globalObject()));\n");
            } else {
                push(@implContent, "    JSValue constructor = ${className}Constructor::create(exec->vm(), ${className}Constructor::createStructure(exec->vm(), domObject->globalObject(), domObject->globalObject()->objectPrototype()), jsCast<JSDOMGlobalObject*>(domObject->globalObject()));\n");
                push(@implContent, "    // Shadowing constructor property to ensure reusing the same constructor object\n");
                push(@implContent, "    domObject->putDirect(exec->vm(), exec->propertyNames().constructor, constructor, DontEnum | ReadOnly);\n");
                push(@implContent, "    return JSValue::encode(constructor);\n");
            }
            push(@implContent, "}\n\n");
        }

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

            push(@implContent, "void ${constructorFunctionName}(ExecState* exec, JSObject*, EncodedJSValue thisValue, EncodedJSValue encodedValue)\n");
            push(@implContent, "{\n");
            push(@implContent, "    JSValue value = JSValue::decode(encodedValue);");
            if ($interface->extendedAttributes->{"CustomProxyToJSObject"}) {
                push(@implContent, "    ${className}* castedThis = to${className}(JSValue::decode(thisValue));\n");
            } else {
                push(@implContent, "    ${className}* castedThis = " . GetCastingHelperForThisObject($interface) . "(JSValue::decode(thisValue));\n");
            }
            push(@implContent, "    if (UNLIKELY(!castedThis)) {\n");
            push(@implContent, "        throwVMTypeError(exec);\n");
            push(@implContent, "        return;\n");
            push(@implContent, "    }\n");
            if ($interface->extendedAttributes->{"CheckSecurity"}) {
                if ($interfaceName eq "DOMWindow") {
                    push(@implContent, "    if (!BindingSecurity::shouldAllowAccessToDOMWindow(exec, castedThis->impl()))\n");
                } else {
                    push(@implContent, "    if (!shouldAllowAccessToFrame(exec, castedThis->impl().frame()))\n");
                }
                push(@implContent, "        return;\n");
            }

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

            if ($interfaceName eq "DOMWindow") {
                push(@implContent, "    castedThis->putDirect(exec->vm(), exec->propertyNames().constructor, value);\n");
            } else {
                die "No way to handle interface with ReplaceableConstructor extended attribute: $interfaceName";
            }
            push(@implContent, "}\n\n");
        }
    }
    my $hasCustomSetter = $interface->extendedAttributes->{"CustomNamedSetter"}
                          || $interface->extendedAttributes->{"CustomIndexedSetter"};

    if ($hasCustomSetter) {
        if (!$interface->extendedAttributes->{"CustomPutFunction"}) {
            push(@implContent, "void ${className}::put(JSCell* cell, ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)\n");
            push(@implContent, "{\n");
            push(@implContent, "    auto* thisObject = jsCast<${className}*>(cell);\n");
            push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n");
            if ($interface->extendedAttributes->{"CustomIndexedSetter"}) {
                push(@implContent, "    if (Optional<uint32_t> index = parseIndex(propertyName)) {\n");
                push(@implContent, "        thisObject->indexSetter(exec, index.value(), value);\n");
                push(@implContent, "        return;\n");
                push(@implContent, "    }\n");
            }
            if ($interface->extendedAttributes->{"CustomNamedSetter"}) {
                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");

            if ($interface->extendedAttributes->{"CustomIndexedSetter"} || $interface->extendedAttributes->{"CustomNamedSetter"}) {
                push(@implContent, "void ${className}::putByIndex(JSCell* cell, ExecState* exec, unsigned index, JSValue value, bool shouldThrow)\n");
                push(@implContent, "{\n");
                push(@implContent, "    auto* thisObject = jsCast<${className}*>(cell);\n");
                push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n");

                if ($interface->extendedAttributes->{"CustomIndexedSetter"}) {
                    push(@implContent, "    if (index <= MAX_ARRAY_INDEX) {\n");
                    push(@implContent, "        thisObject->indexSetter(exec, index, value);\n");
                    push(@implContent, "        return;\n");
                    push(@implContent, "    }\n");
                }

                if ($interface->extendedAttributes->{"CustomNamedSetter"}) {
                    push(@implContent, "    Identifier propertyName = Identifier::from(exec, index);\n");
                    push(@implContent, "    PutPropertySlot slot(thisObject, shouldThrow);\n");
                    push(@implContent, "    if (thisObject->putDelegate(exec, propertyName, value, slot))\n");
                    push(@implContent, "        return;\n");
                }

                push(@implContent, "    Base::putByIndex(cell, exec, index, value, shouldThrow);\n");
                push(@implContent, "}\n\n");
            }
        }
    }

    foreach my $attribute (@{$interface->attributes}) {
        if (!IsReadonly($attribute)) {
            my $name = $attribute->signature->name;
            my $type = $attribute->signature->type;
            my $putFunctionName = GetAttributeSetterName($interfaceName, $className, $attribute);
            my $implSetterFunctionName = $codeGenerator->WK_ucfirst($name);
            my $setterRaisesException = $attribute->signature->extendedAttributes->{"SetterRaisesException"};

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

            push(@implContent, "void ${putFunctionName}(ExecState* exec, JSObject* baseObject, EncodedJSValue");
            push(@implContent, " thisValue") if !$attribute->isStatic;
            push(@implContent, ", EncodedJSValue encodedValue)\n");
            push(@implContent, "{\n");
            push(@implContent, "    JSValue value = JSValue::decode(encodedValue);\n");
            push(@implContent, "    UNUSED_PARAM(baseObject);\n");
            if (!$attribute->isStatic) {
                if ($interface->extendedAttributes->{"CustomProxyToJSObject"}) {
                    push(@implContent, "    ${className}* castedThis = to${className}(JSValue::decode(thisValue));\n");
                } elsif (AttributeShouldBeOnInstance($interface, $attribute)) {
                    push(@implContent, "    UNUSED_PARAM(thisValue);\n");
                    push(@implContent, "    auto* castedThis = jsCast<JS${interfaceName}*>(baseObject);\n");
                    if (InterfaceRequiresAttributesOnInstanceForCompatibility($interface)) {
                        push(@implContent, "    ${className}* castedThisObject = " . GetCastingHelperForThisObject($interface) . "(JSValue::decode(thisValue));\n");
                        push(@implContent, "    if (UNLIKELY(!castedThisObject))\n");
                        push(@implContent, "        reportDeprecatedSetterError(*exec, \"$interfaceName\", \"$name\");\n");
                    } else {
                        push(@implContent, "    UNUSED_PARAM(thisValue);\n");
                        push(@implContent, "    UNUSED_PARAM(exec);\n");
                    }
                } else {
                    push(@implContent, "    ${className}* castedThis = " . GetCastingHelperForThisObject($interface) . "(JSValue::decode(thisValue));\n");
                    push(@implContent, "    if (UNLIKELY(!castedThis)) {\n");
                    push(@implContent, "        if (jsDynamicCast<${className}Prototype*>(JSValue::decode(thisValue)))\n");
                    push(@implContent, "            reportDeprecatedSetterError(*exec, \"$interfaceName\", \"$name\");\n");
                    push(@implContent, "        else\n");
                    push(@implContent, "            throwSetterTypeError(*exec, \"$interfaceName\", \"$name\");\n");
                    push(@implContent, "        return;\n");
                    push(@implContent, "    }\n");
                }
            }
            if ($interface->extendedAttributes->{"CheckSecurity"} && !$attribute->signature->extendedAttributes->{"DoNotCheckSecurity"}) {
                if ($interfaceName eq "DOMWindow") {
                    push(@implContent, "    if (!BindingSecurity::shouldAllowAccessToDOMWindow(exec, castedThis->impl()))\n");
                } else {
                    push(@implContent, "    if (!shouldAllowAccessToFrame(exec, castedThis->impl().frame()))\n");
                }
                push(@implContent, "        return;\n");
            }

            if (HasCustomSetter($attribute->signature->extendedAttributes)) {
                push(@implContent, "    castedThis->set$implSetterFunctionName(exec, value);\n");
            } elsif ($type eq "EventHandler") {
                $implIncludes{"JSEventListener.h"} = 1;
                my $eventName = EventHandlerAttributeEventName($attribute);
                # FIXME: Find a way to do this special case without hardcoding the class and attribute names here.
                if ((($interfaceName eq "DOMWindow") or ($interfaceName eq "WorkerGlobalScope")) and $name eq "onerror") {
                    $implIncludes{"JSErrorHandler.h"} = 1;
                    push(@implContent, "    castedThis->impl().setAttributeEventListener($eventName, createJSErrorHandler(exec, value, castedThis));\n");
                } else {
                    $implIncludes{"JSEventListener.h"} = 1;
                    my $setter = $attribute->signature->extendedAttributes->{"WindowEventHandler"} ? "setWindowEventHandlerAttribute"
                        : $attribute->signature->extendedAttributes->{"DocumentEventHandler"} ? "setDocumentEventHandlerAttribute"
                        : "setEventHandlerAttribute";
                    push(@implContent, "    $setter(*exec, *castedThis, castedThis->impl(), $eventName, value);\n");
                }
            } 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 "any" and $constructorType !~ /Named$/) {
                    AddToImplIncludes("JS" . $constructorType . ".h", $attribute->signature->extendedAttributes->{"Conditional"});
                }
                push(@implContent, "    // Shadowing a built-in constructor.\n");
                push(@implContent, "    castedThis->putDirect(exec->vm(), Identifier::fromString(exec, \"$name\"), value);\n");
            } elsif ($attribute->signature->extendedAttributes->{"Replaceable"}) {
                push(@implContent, "    // Shadowing a built-in object.\n");
                push(@implContent, "    castedThis->putDirect(exec->vm(), Identifier::fromString(exec, \"$name\"), value);\n");
            } else {
                if (!$attribute->isStatic) {
                    push(@implContent, "    auto& impl = castedThis->impl();\n");
                }
                push(@implContent, "    ExceptionCode ec = 0;\n") if $setterRaisesException;

                # 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 ($codeGenerator->IsWrapperType($argType)) {
                        push(@implContent, "    if (!value.isUndefinedOrNull() && !value.inherits(JS${argType}::info())) {\n");
                        push(@implContent, "        throwAttributeTypeError(*exec, \"$interfaceName\", \"$name\", \"$argType\");\n");
                        push(@implContent, "        return;\n");
                        push(@implContent, "    };\n");
                    }
                }

                push(@implContent, "    " . GetNativeTypeFromSignature($attribute->signature) . " nativeValue = " . JSValueToNative($attribute->signature, "value", $attribute->signature->extendedAttributes->{"Conditional"}) . ";\n");
                push(@implContent, "    if (UNLIKELY(exec->hadException()))\n");
                push(@implContent, "        return;\n");

                if ($codeGenerator->IsEnumType($type)) {
                    my @enumValues = $codeGenerator->ValidEnumValues($type);
                    my @enumChecks = ();
                    foreach my $enumValue (@enumValues) {
                        push(@enumChecks, "nativeValue != \"$enumValue\"");
                    }
                    push (@implContent, "    if (" . join(" && ", @enumChecks) . ")\n");
                    push (@implContent, "        return;\n");
                }

                if ($attribute->signature->type eq "double" or $attribute->signature->type eq "float") {
                    push(@implContent, "    if (!std::isfinite(nativeValue)) {\n");
                    push(@implContent, "        setDOMException(exec, TypeError);\n");
                    push(@implContent, "        return;\n");
                    push(@implContent, "    }\n");
                }

                if ($svgPropertyOrListPropertyType) {
                    if ($svgPropertyType) {
                        push(@implContent, "    if (impl.isReadOnly()) {\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 $setterRaisesException;
                        push(@implContent, ");\n");
                        push(@implContent, "    setDOMException(exec, ec);\n") if $setterRaisesException;
                    }
                    if ($svgPropertyType) {
                        if ($setterRaisesException) {
                            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);
                    if ($codeGenerator->IsTypedArrayType($attribute->signature->type) and not $attribute->signature->type eq "ArrayBuffer") {
                        push(@arguments, "nativeValue.get()");
                    } else {
                        push(@arguments, "nativeValue");
                    }
                    if ($attribute->signature->extendedAttributes->{"ImplementedBy"}) {
                        my $implementedBy = $attribute->signature->extendedAttributes->{"ImplementedBy"};
                        AddToImplIncludes("${implementedBy}.h", $attribute->signature->extendedAttributes->{"Conditional"});
                        unshift(@arguments, "&impl") if !$attribute->isStatic;
                        $functionName = "${implementedBy}::${functionName}";
                    } elsif ($attribute->isStatic) {
                        $functionName = "${interfaceName}::${functionName}";
                    } else {
                        $functionName = "impl.${functionName}";
                    }

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

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

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

    if ($indexedGetterFunction && !$interface->extendedAttributes->{"CustomEnumerateProperty"}) {
        push(@implContent, "void ${className}::getOwnPropertyNames(JSObject* object, ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)\n");
        push(@implContent, "{\n");
        push(@implContent, "    auto* thisObject = jsCast<${className}*>(object);\n");
        push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n");
        push(@implContent, "    for (unsigned i = 0, count = thisObject->impl().length(); i < count; ++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 (!$interface->extendedAttributes->{"NoInterfaceObject"}) {
        push(@implContent, "JSValue ${className}::getConstructor(VM& vm, JSGlobalObject* globalObject)\n{\n");
        push(@implContent, "    return getDOMConstructor<${className}Constructor>(vm, jsCast<JSDOMGlobalObject*>(globalObject));\n");
        push(@implContent, "}\n\n");
        if ($interface->extendedAttributes->{"NamedConstructor"}) {
            push(@implContent, "JSValue ${className}::getNamedConstructor(VM& vm, JSGlobalObject* globalObject)\n{\n");
            push(@implContent, "    return getDOMConstructor<${className}NamedConstructor>(vm, jsCast<JSDOMGlobalObject*>(globalObject));\n");
            push(@implContent, "}\n\n");
        }
    }

    # Functions
    if ($numFunctions > 0) {
        my $inAppleCopyright = 0;
        foreach my $function (@{$interface->functions}) {
            my $needsAppleCopyright = $function->signature->extendedAttributes->{"AppleCopyright"};
            if ($needsAppleCopyright) {
                if (!$inAppleCopyright) {
                    push(@implContent, $beginAppleCopyrightForSourceFiles);
                    $inAppleCopyright = 1;
                }
            } elsif ($inAppleCopyright) {
                push(@implContent, $endAppleCopyright);
                $inAppleCopyright = 0;
            }

            my $isCustom = HasCustomMethod($function->signature->extendedAttributes);
            my $isOverloaded = $function->{overloads} && @{$function->{overloads}} > 1;
            my $raisesException = $function->signature->extendedAttributes->{"RaisesException"};

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

            AddIncludesForTypeInImpl($function->signature->type) unless $isCustom or IsReturningPromise($function);

            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);

            if (IsReturningPromise($function) && !$isCustom) {
                AddToImplIncludes("JSDOMPromise.h");

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

                push(@implContent, "    return JSValue::encode(callPromiseFunction(*exec, ${functionName}Promise));\n");

                push(@implContent, "}\n");
                push(@implContent, "\nstatic inline EncodedJSValue ${functionName}Promise(ExecState* exec, JSPromiseDeferred* promiseDeferred)\n");
            }
            else {
                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, $interface);
                    push(@implContent, "    return JSValue::encode(${className}::" . $functionImplementationName . "(exec));\n");
                } else {
                    GenerateArgumentsCountCheck(\@implContent, $function, $interface);

                    push(@implContent, "    ExceptionCode ec = 0;\n") if $raisesException;

                    my $numParameters = @{$function->parameters};
                    my ($functionString, $dummy) = GenerateParametersCheck(\@implContent, $function, $interface, $numParameters, $interfaceName, $functionImplementationName, $svgPropertyType, $svgPropertyOrListPropertyType, $svgListPropertyType);
                    GenerateImplementationFunctionCall($function, $functionString, "    ", $svgPropertyType, $interfaceName);
                }
            } else {
                GenerateFunctionCastedThis($interface, $interfaceName, $className, $function);

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

                if ($isCustom) {
                    push(@implContent, "    return JSValue::encode(castedThis->" . $functionImplementationName . "(exec));\n");
                } else {
                    push(@implContent, "    auto& impl = castedThis->impl();\n");
                    if ($svgPropertyType) {
                        push(@implContent, "    if (impl.isReadOnly()) {\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("add"));
                    } elsif ($function->signature->name eq "removeEventListener") {
                        push(@implContent, GenerateEventListenerCall("remove"));
                    } else {
                        GenerateArgumentsCountCheck(\@implContent, $function, $interface);

                        push(@implContent, "    ExceptionCode ec = 0;\n") if $raisesException;

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

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

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

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

        }

        push(@implContent, $endAppleCopyright) if $inAppleCopyright;

    }

    if ($needsVisitChildren) {
        push(@implContent, "void ${className}::visitChildren(JSCell* cell, SlotVisitor& visitor)\n");
        push(@implContent, "{\n");
        push(@implContent, "    auto* thisObject = jsCast<${className}*>(cell);\n");
        push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, info());\n");
        push(@implContent, "    Base::visitChildren(thisObject, visitor);\n");
        if ($interface->extendedAttributes->{"EventTarget"} || $interface->name eq "EventTarget") {
            push(@implContent, "    thisObject->impl().visitJSEventListeners(visitor);\n");
        }
        push(@implContent, "    thisObject->visitAdditionalChildren(visitor);\n") if $interface->extendedAttributes->{"JSCustomMarkFunction"};
        if ($interface->extendedAttributes->{"ReportExtraMemoryCost"}) {
            push(@implContent, "    visitor.reportExtraMemoryVisited(cell, thisObject->impl().memoryCost());\n");
        }
        if ($numCachedAttributes > 0) {
            foreach (@{$interface->attributes}) {
                my $attribute = $_;
                if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) {
                    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 ($interface->extendedAttributes->{"JSCustomMarkFunction"}));

    if ($indexedGetterFunction) {
        if ($indexedGetterFunction->signature->type eq "DOMString") {
            $implIncludes{"URL.h"} = 1;
        }
        if ($interfaceName =~ /^HTML\w*Collection$/ or $interfaceName eq "RadioNodeList") {
            $implIncludes{"JSNode.h"} = 1;
            $implIncludes{"Node.h"} = 1;
        }
    }

    if ($interfaceName eq "DOMNamedFlowCollection") {
        if ($namedGetterFunction) {
            push(@implContent, "bool ${className}::canGetItemsForName(ExecState*, $interfaceName* collection, PropertyName propertyName)\n");
            push(@implContent, "{\n");
            push(@implContent, "    return collection->hasNamedItem(propertyNameToAtomicString(propertyName));\n");
            push(@implContent, "}\n\n");
            push(@implContent, "EncodedJSValue ${className}::nameGetter(ExecState* exec, JSObject* slotBase, EncodedJSValue, PropertyName propertyName)\n");
            push(@implContent, "{\n");
            push(@implContent, "    auto* thisObject = jsCast<$className*>(slotBase);\n");
            push(@implContent, "    return JSValue::encode(toJS(exec, thisObject->globalObject(), thisObject->impl().namedItem(propertyNameToAtomicString(propertyName))));\n");
            push(@implContent, "}\n\n");
        }
    }

    if ((!$hasParent && !GetCustomIsReachable($interface)) || GetGenerateIsReachable($interface) || $codeGenerator->InheritsExtendedAttribute($interface, "ActiveDOMObject")) {

        push(@implContent, "bool JS${interfaceName}Owner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor)\n");
        push(@implContent, "{\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 just above the (GetGenerateIsReachable($interface) eq "Impl") check below.
        my $emittedJSCast = 0;
        if ($codeGenerator->InheritsExtendedAttribute($interface, "ActiveDOMObject")) {
            push(@implContent, "    auto* js${interfaceName} = jsCast<JS${interfaceName}*>(handle.slot()->asCell());\n");
            $emittedJSCast = 1;
            push(@implContent, "    if (js${interfaceName}->impl().hasPendingActivity())\n");
            push(@implContent, "        return true;\n");
        }
        if ($codeGenerator->InheritsExtendedAttribute($interface, "EventTarget")) {
            if (!$emittedJSCast) {
                push(@implContent, "    auto* js${interfaceName} = jsCast<JS${interfaceName}*>(handle.slot()->asCell());\n");
                $emittedJSCast = 1;
            }
            push(@implContent, "    if (js${interfaceName}->impl().isFiringEventListeners())\n");
            push(@implContent, "        return true;\n");
        }
        if ($codeGenerator->InheritsInterface($interface, "Node")) {
            if (!$emittedJSCast) {
                push(@implContent, "    auto* js${interfaceName} = jsCast<JS${interfaceName}*>(handle.slot()->asCell());\n");
                $emittedJSCast = 1;
            }
            push(@implContent, "    if (JSNodeOwner::isReachableFromOpaqueRoots(handle, 0, visitor))\n");
            push(@implContent, "        return true;\n");
        }
        if (GetGenerateIsReachable($interface)) {
            if (!$emittedJSCast) {
                push(@implContent, "    auto* js${interfaceName} = jsCast<JS${interfaceName}*>(handle.slot()->asCell());\n");
                $emittedJSCast = 1;
            }

            my $rootString;
            if (GetGenerateIsReachable($interface) eq "Impl") {
                $rootString  = "    ${implType}* root = &js${interfaceName}->impl();\n";
            } elsif (GetGenerateIsReachable($interface) eq "ImplWebGLRenderingContext") {
                $rootString  = "    WebGLRenderingContextBase* root = WTF::getPtr(js${interfaceName}->impl().context());\n";
            } elsif (GetGenerateIsReachable($interface) eq "ImplFrame") {
                $rootString  = "    Frame* root = WTF::getPtr(js${interfaceName}->impl().frame());\n";
                $rootString .= "    if (!root)\n";
                $rootString .= "        return false;\n";
            } elsif (GetGenerateIsReachable($interface) eq "ImplDocument") {
                $rootString  = "    Document* root = WTF::getPtr(js${interfaceName}->impl().document());\n";
                $rootString .= "    if (!root)\n";
                $rootString .= "        return false;\n";
            } elsif (GetGenerateIsReachable($interface) eq "ImplElementRoot") {
                $implIncludes{"Element.h"} = 1;
                $implIncludes{"JSNodeCustom.h"} = 1;
                $rootString  = "    Element* element = WTF::getPtr(js${interfaceName}->impl().element());\n";
                $rootString .= "    if (!element)\n";
                $rootString .= "        return false;\n";
                $rootString .= "    void* root = WebCore::root(element);\n";
            } elsif ($interfaceName eq "CanvasRenderingContext") {
                $implIncludes{"Element.h"} = 1;
                $implIncludes{"JSNodeCustom.h"} = 1;
                $rootString  = "    void* root = WebCore::root(js${interfaceName}->impl().canvas());\n";
            } elsif (GetGenerateIsReachable($interface) eq "ImplOwnerNodeRoot") {
                $implIncludes{"Element.h"} = 1;
                $implIncludes{"JSNodeCustom.h"} = 1;
                $rootString  = "    void* root = WebCore::root(js${interfaceName}->impl().ownerNode());\n";
            } else {
                $rootString  = "    void* root = WebCore::root(&js${interfaceName}->impl());\n";
            }

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

    if (!$interface->extendedAttributes->{"JSCustomFinalize"} &&
        (!$hasParent ||
         GetGenerateIsReachable($interface) ||
         GetCustomIsReachable($interface) ||
         $codeGenerator->InheritsExtendedAttribute($interface, "ActiveDOMObject"))) {
        push(@implContent, "void JS${interfaceName}Owner::finalize(JSC::Handle<JSC::Unknown> handle, void* context)\n");
        push(@implContent, "{\n");
        push(@implContent, "    auto* js${interfaceName} = jsCast<JS${interfaceName}*>(handle.slot()->asCell());\n");
        push(@implContent, "    auto& world = *static_cast<DOMWrapperWorld*>(context);\n");
        push(@implContent, "    uncacheWrapper(world, &js${interfaceName}->impl(), js${interfaceName});\n");
        push(@implContent, "}\n\n");
    }

    if (ShouldGenerateToJSImplementation($hasParent, $interface)) {
        my $vtableNameGnu = GetGnuVTableNameForInterface($interface);
        my $vtableRefGnu = GetGnuVTableRefForInterface($interface);
        my $vtableRefWin = GetWinVTableRefForInterface($interface);

        push(@implContent, <<END) if $vtableNameGnu;
#if ENABLE(BINDING_INTEGRITY)
#if PLATFORM(WIN)
#pragma warning(disable: 4483)
extern "C" { extern void (*const ${vtableRefWin}[])(); }
#else
extern "C" { extern void* ${vtableNameGnu}[]; }
#endif
#endif
END

        push(@implContent, "JSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject* globalObject, $implType* impl)\n");
        push(@implContent, "{\n");
        push(@implContent, <<END);
    if (!impl)
        return jsNull();
END

        if ($svgPropertyType) {
            push(@implContent, "    if (JSValue result = getExistingWrapper<$className, $implType>(globalObject, impl))\n");
            push(@implContent, "        return result;\n");
        } else {
            push(@implContent, "    if (JSValue result = getExistingWrapper<$className>(globalObject, impl))\n");
            push(@implContent, "        return result;\n");
        }
        push(@implContent, <<END) if $vtableNameGnu;

#if ENABLE(BINDING_INTEGRITY)
    void* actualVTablePointer = *(reinterpret_cast<void**>(impl));
#if PLATFORM(WIN)
    void* expectedVTablePointer = reinterpret_cast<void*>(${vtableRefWin});
#else
    void* expectedVTablePointer = ${vtableRefGnu};
#if COMPILER(CLANG)
    // If this fails $implType does not have a vtable, so you need to add the
    // ImplementationLacksVTable attribute to the interface definition
    COMPILE_ASSERT(__is_polymorphic($implType), ${implType}_is_not_polymorphic);
#endif
#endif
    // If you hit this assertion you either have a use after free bug, or
    // $implType has subclasses. If $implType has subclasses that get passed
    // to toJS() we currently require $interfaceName you to opt out of binding hardening
    // by adding the SkipVTableValidation attribute to the interface IDL definition
    RELEASE_ASSERT(actualVTablePointer == expectedVTablePointer);
#endif
END
        push(@implContent, <<END) if $interface->extendedAttributes->{"ImplementationLacksVTable"};
#if COMPILER(CLANG)
    // If you hit this failure the interface definition has the ImplementationLacksVTable
    // attribute. You should remove that attribute. If the class has subclasses
    // that may be passed through this toJS() function you should use the SkipVTableValidation
    // attribute to $interfaceName.
    COMPILE_ASSERT(!__is_polymorphic($implType), ${implType}_is_polymorphic_but_idl_claims_not_to_be);
#endif
END
        push(@implContent, <<END) if $interface->extendedAttributes->{"ReportExtraMemoryCost"};
    globalObject->vm().heap.reportExtraMemoryAllocated(impl->memoryCost());
END

        if ($svgPropertyType) {
            push(@implContent, "    return createNewWrapper<$className, $implType>(globalObject, impl);\n");
        } else {
            push(@implContent, "    return createNewWrapper<$className>(globalObject, impl);\n");
        }

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

    if ((!$hasParent or $interface->extendedAttributes->{"JSGenerateToNativeObject"}) and !$interface->extendedAttributes->{"JSCustomToNativeObject"}) {
        push(@implContent, "$implType* ${className}::toWrapped(JSC::JSValue value)\n");
        push(@implContent, "{\n");
        push(@implContent, "    if (auto* wrapper = " . GetCastingHelperForThisObject($interface) . "(value))\n");
        push(@implContent, "        return &wrapper->impl();\n");
        push(@implContent, "    return nullptr;\n");
        push(@implContent, "}\n");
    }

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

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

sub GenerateFunctionCastedThis
{
    my $interface = shift;
    my $interfaceName = shift;
    my $className = shift;
    my $function = shift;
    if ($interface->extendedAttributes->{"CustomProxyToJSObject"}) {
        push(@implContent, "    $className* castedThis = to${className}(exec->thisValue().toThis(exec, NotStrictMode));\n");
        push(@implContent, "    if (UNLIKELY(!castedThis))\n");
        push(@implContent, "        return throwVMTypeError(exec);\n");
    } elsif ($interface->extendedAttributes->{"WorkerGlobalScope"}) {
        push(@implContent, "    $className* castedThis = to${className}(exec->thisValue().toThis(exec, NotStrictMode));\n");
        push(@implContent, "    if (UNLIKELY(!castedThis))\n");
        push(@implContent, "        return throwVMTypeError(exec);\n");
    } else {
        push(@implContent, "    JSValue thisValue = exec->thisValue();\n");
        push(@implContent, "    $className* castedThis = " . GetCastingHelperForThisObject($interface) . "(thisValue);\n");
        my $domFunctionName = $function->signature->name;
        push(@implContent, "    if (UNLIKELY(!castedThis))\n");
        push(@implContent, "        return throwThisTypeError(*exec, \"$interfaceName\", \"$domFunctionName\");\n");
    }

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

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, "    auto* 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<Inspector::ScriptArguments> scriptArguments(Inspector::createScriptArguments(exec, " . @{$function->parameters} . "));\n");
        $implIncludes{"<inspector/ScriptArguments.h>"} = 1;
        $implIncludes{"<inspector/ScriptCallStackFactory.h>"} = 1;
        push(@callWithArgs, "scriptArguments.release()");
    }
    return @callWithArgs;
}

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

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

sub GenerateParametersCheck
{
    my $outputArray = shift;
    my $function = shift;
    my $interface = shift;
    my $numParameters = shift;
    my $interfaceName = shift;
    my $functionImplementationName = shift;
    my $svgPropertyType = shift;
    my $svgPropertyOrListPropertyType = shift;
    my $svgListPropertyType = shift;

    my $argsIndex = 0;
    my $hasOptionalArguments = 0;
    my $raisesException = $function->signature->extendedAttributes->{"RaisesException"};
    
    my $className = $interface->name;
    my @arguments;
    my $functionName;
    my $implementedBy = $function->signature->extendedAttributes->{"ImplementedBy"};
    if ($implementedBy) {
        AddToImplIncludes("${implementedBy}.h", $function->signature->extendedAttributes->{"Conditional"});
        unshift(@arguments, "&impl") if !$function->isStatic;
        $functionName = "${implementedBy}::${functionImplementationName}";
    } elsif ($function->isStatic) {
        $functionName = "${interfaceName}::${functionImplementationName}";
    } elsif ($svgPropertyOrListPropertyType and !$svgListPropertyType) {
        $functionName = "podImpl.${functionImplementationName}";
    } else {
        $functionName = "impl.${functionImplementationName}";
    }
    
    my $quotedFunctionName;
    if (!$function->signature->extendedAttributes->{"Constructor"}) {
        my $name = $function->signature->name;
        $quotedFunctionName = "\"$name\"";
        push(@arguments, GenerateCallWith($function->signature->extendedAttributes->{"CallWith"}, \@$outputArray, "JSValue::encode(jsUndefined())", $function));
    } else {
        $quotedFunctionName = "nullptr";
    }

    $implIncludes{"ExceptionCode.h"} = 1;
    $implIncludes{"JSDOMBinding.h"} = 1;
    foreach my $parameter (@{$function->parameters}) {
        my $argType = $parameter->type;
        # Optional arguments with [Optional] should generate an early call with fewer arguments.
        # Optional arguments with [Optional=...] should not generate the early call.
        # Optional Dictionary arguments always considered to have default of empty dictionary.
        my $optional = $parameter->isOptional;
        my $defaultAttribute = $parameter->extendedAttributes->{"Default"};
        if ($optional && !$defaultAttribute && $argType ne "Dictionary" && !$codeGenerator->IsCallbackInterface($parameter->type)) {
            # 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;
            push @optionalCallbackArguments, GenerateReturnParameters($function);
            my $functionString = "$functionName(" . join(", ", @optionalCallbackArguments) . ")";
            GenerateImplementationFunctionCall($function, $functionString, "    " x 2, $svgPropertyType, $interfaceName);
            push(@$outputArray, "    }\n\n");
        }

        my $name = $parameter->name;

        if ($argType eq "XPathNSResolver") {
            push(@$outputArray, "    RefPtr<XPathNSResolver> customResolver;\n");
            push(@$outputArray, "    XPathNSResolver* resolver = JSXPathNSResolver::toWrapped(exec->argument($argsIndex));\n");
            push(@$outputArray, "    if (!resolver) {\n");
            push(@$outputArray, "        customResolver = JSCustomXPathNSResolver::create(exec, exec->argument($argsIndex));\n");
            push(@$outputArray, "        if (UNLIKELY(exec->hadException()))\n");
            push(@$outputArray, "            return JSValue::encode(jsUndefined());\n");
            push(@$outputArray, "        resolver = customResolver.get();\n");
            push(@$outputArray, "    }\n");
        } elsif ($codeGenerator->IsCallbackInterface($parameter->type)) {
            my $callbackClassName = GetCallbackClassName($argType);
            $implIncludes{"$callbackClassName.h"} = 1;
            if ($optional) {
                push(@$outputArray, "    RefPtr<$argType> $name;\n");
                push(@$outputArray, "    if (!exec->argument($argsIndex).isUndefinedOrNull()) {\n");
                push(@$outputArray, "        if (!exec->uncheckedArgument($argsIndex).isFunction())\n");
                push(@$outputArray, "            return throwArgumentMustBeFunctionError(*exec, $argsIndex, \"$name\", \"$interfaceName\", $quotedFunctionName);\n");
                if ($function->isStatic) {
                    AddToImplIncludes("CallbackFunction.h");
                    push(@$outputArray, "        $name = createFunctionOnlyCallback<${callbackClassName}>(exec, jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject()), exec->uncheckedArgument($argsIndex));\n");
                } else {
                    push(@$outputArray, "        $name = ${callbackClassName}::create(asObject(exec->uncheckedArgument($argsIndex)), castedThis->globalObject());\n");
                }
                push(@$outputArray, "    }\n");
            } else {
                push(@$outputArray, "    if (!exec->argument($argsIndex).isFunction())\n");
                push(@$outputArray, "        return throwArgumentMustBeFunctionError(*exec, $argsIndex, \"$name\", \"$interfaceName\", $quotedFunctionName);\n");
                if ($function->isStatic) {
                    AddToImplIncludes("CallbackFunction.h");
                    push(@$outputArray, "    RefPtr<$argType> $name = createFunctionOnlyCallback<${callbackClassName}>(exec, jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject()), exec->uncheckedArgument($argsIndex));\n");
                } else {
                    push(@$outputArray, "    RefPtr<$argType> $name = ${callbackClassName}::create(asObject(exec->uncheckedArgument($argsIndex)), castedThis->globalObject());\n");
                }
            }
        } elsif ($parameter->extendedAttributes->{"Clamp"}) {
            my $nativeValue = "${name}NativeValue";
            push(@$outputArray, "    $argType $name = 0;\n");
            push(@$outputArray, "    double $nativeValue = exec->argument($argsIndex).toNumber(exec);\n");
            push(@$outputArray, "    if (UNLIKELY(exec->hadException()))\n");
            push(@$outputArray, "        return JSValue::encode(jsUndefined());\n\n");
            push(@$outputArray, "    if (!std::isnan($nativeValue))\n");
            push(@$outputArray, "        $name = clampTo<$argType>($nativeValue);\n\n");
        } elsif ($parameter->isVariadic) {
            my $nativeElementType;
            if ($argType eq "DOMString") {
                $nativeElementType = "String";
            } else {
                $nativeElementType = GetNativeType($argType);
            }

            if (!IsNativeType($argType)) {
                push(@$outputArray, "    Vector<$nativeElementType> $name;\n");
                push(@$outputArray, "    for (unsigned i = $argsIndex, count = exec->argumentCount(); i < count; ++i) {\n");
                push(@$outputArray, "        if (!exec->uncheckedArgument(i).inherits(JS${argType}::info()))\n");
                push(@$outputArray, "            return throwArgumentTypeError(*exec, i, \"$name\", \"$interfaceName\", $quotedFunctionName, \"$argType\");\n");
                push(@$outputArray, "        $name.append(JS${argType}::toWrapped(exec->uncheckedArgument(i)));\n");
                push(@$outputArray, "    }\n")
            } else {
                push(@$outputArray, "    Vector<$nativeElementType> $name = toNativeArguments<$nativeElementType>(exec, $argsIndex);\n");
                # Check if the type conversion succeeded.
                push(@$outputArray, "    if (UNLIKELY(exec->hadException()))\n");
                push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
            }

        } elsif ($codeGenerator->IsEnumType($argType)) {
            $implIncludes{"<runtime/Error.h>"} = 1;

            my $argValue = "exec->argument($argsIndex)";
            push(@$outputArray, "    // Keep pointer to the JSString in a local so we don't need to ref the String.\n");
            push(@$outputArray, "    auto* ${name}String = ${argValue}.toString(exec);\n");
            push(@$outputArray, "    if (UNLIKELY(exec->hadException()))\n");
            push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
            push(@$outputArray, "    auto& $name = ${name}String->value(exec);\n");

            my @enumValues = $codeGenerator->ValidEnumValues($argType);
            my @enumChecks = ();
            my $enums = 0;
            foreach my $enumValue (@enumValues) {
                push(@enumChecks, "${name} != \"$enumValue\"");
                if (!$enums) {
                    $enums = "\\\"$enumValue\\\"";
                } else {
                    $enums = $enums . ", \\\"" . $enumValue . "\\\"";
                }
            }
            push (@$outputArray, "    if (" . join(" && ", @enumChecks) . ")\n");
            push (@$outputArray, "        return throwArgumentMustBeEnumError(*exec, $argsIndex, \"$name\", \"$interfaceName\", $quotedFunctionName, \"$enums\");\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 ($codeGenerator->IsWrapperType($argType)) {
                    push(@$outputArray, "    if (!${argValue}.isUndefinedOrNull() && !${argValue}.inherits(JS${argType}::info()))\n");
                    push(@$outputArray, "        return throwArgumentTypeError(*exec, $argsIndex, \"$name\", \"$interfaceName\", $quotedFunctionName, \"$argType\");\n");
                }
            }

            if ($parameter->extendedAttributes->{"RequiresExistingAtomicString"}) {
                # FIXME: This could be made slightly more efficient if we added an AtomicString(RefPtr<AtomicStringImpl>&&) constructor and removed the call to get() here.
                push(@$outputArray, "    AtomicString $name = exec->argument($argsIndex).toString(exec)->toExistingAtomicString(exec).get();\n");
                push(@$outputArray, "    if ($name.isNull())\n");
                push(@$outputArray, "        return JSValue::encode(jsNull());\n");
            } else {
                my $outer;
                my $inner;
                if ($optional && $defaultAttribute && $defaultAttribute eq "NullString") {
                    $outer = "exec->argumentCount() <= $argsIndex ? String() : ";
                    $inner = "exec->uncheckedArgument($argsIndex)";
                } else {
                    $outer = "";
                    $inner = "exec->argument($argsIndex)";
                }
                push(@$outputArray, "    " . GetNativeTypeFromSignature($parameter) . " $name = $outer" . JSValueToNative($parameter, $inner, $function->signature->extendedAttributes->{"Conditional"}) . ";\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 (UNLIKELY(exec->hadException()))\n");
            push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");

            if ($codeGenerator->IsSVGTypeNeedingTearOff($argType) and not $interfaceName =~ /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 ($parameter->type eq "double" or $parameter->type eq "float") {
                push(@$outputArray, "    if (!std::isfinite($name)) {\n");
                push(@$outputArray, "        setDOMException(exec, TypeError);\n");
                push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
                push(@$outputArray, "    }\n");
            }
        }

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

    push @arguments, GenerateReturnParameters($function);

    return ("$functionName(" . join(", ", @arguments) . ")", scalar @arguments);
}

sub GenerateReturnParameters
{
    my $function = shift;
    my @arguments;

    push(@arguments, "DeferredWrapper(exec, castedThis->globalObject(), promiseDeferred)") if IsReturningPromise($function);
    push(@arguments, "ec") if $function->signature->extendedAttributes->{"RaisesException"};
    return @arguments;
}

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

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

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

    $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 Ref<$className> create(JSC::JSObject* callback, JSDOMGlobalObject* globalObject)\n");
    push(@headerContent, "    {\n");
    push(@headerContent, "        return adoptRef(*new $className(callback, globalObject));\n");
    push(@headerContent, "    }\n\n");

    # ScriptExecutionContext
    push(@headerContent, "    virtual ScriptExecutionContext* scriptExecutionContext() const { return ContextDestructionObserver::scriptExecutionContext(); }\n\n");

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

    if ($interface->extendedAttributes->{"CallbackNeedsOperatorEqual"}) {
        push(@headerContent, "    virtual bool operator==(const $interfaceName&) const;\n\n")
    }

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

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

            my @args = ();
            foreach my $param (@params) {
                push(@args, GetNativeTypeForCallbacks($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($interface);
    push(@headerContent, "#endif // ${conditionalString}\n\n") if $conditionalString;
    push(@headerContent, "#endif\n");
}

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

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

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

    $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");
    if ($interface->extendedAttributes->{"CallbackNeedsOperatorEqual"}) {
        push(@implContent, "    : ${interfaceName}(${className}Type)\n");
    } else {
        push(@implContent, "    : ${interfaceName}()\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(m_data));\n");
    push(@implContent, "#ifndef NDEBUG\n");
    push(@implContent, "    m_data = 0;\n");
    push(@implContent, "#endif\n");
    push(@implContent, "}\n\n");

    if ($interface->extendedAttributes->{"CallbackNeedsOperatorEqual"}) {
        push(@implContent, "bool ${className}::operator==(const ${interfaceName}& other) const\n");
        push(@implContent, "{\n");
        push(@implContent, "    if (other.type() != type())\n");
        push(@implContent, "        return false;\n");
        push(@implContent, "    return static_cast<const ${className}*>(&other)->m_data->callback() == m_data->callback();\n");
        push(@implContent, "}\n\n");
    }
    # Functions
    my $numFunctions = @{$interface->functions};
    if ($numFunctions > 0) {
        push(@implContent, "\n// Functions\n");
        foreach my $function (@{$interface->functions}) {
            my @params = @{$function->parameters};
            if ($function->signature->extendedAttributes->{"Custom"} ||
                !(GetNativeType($function->signature->type) eq "bool")) {
                next;
            }

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

            my @args = ();
            my @argsCheck = ();
            foreach my $param (@params) {
                my $paramName = $param->name;
                AddIncludesForTypeInImpl($param->type, 1);
                push(@args, GetNativeTypeForCallbacks($param->type) . " " . $paramName);
            }
            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, "    Ref<$className> protect(*this);\n\n");
            push(@implContent, "    JSLockHolder lock(m_data->globalObject()->vm());\n\n");
            if (@params) {
                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(jsStringWithCache(exec, ${paramName}));\n");
                } elsif ($param->type eq "boolean") {
                    push(@implContent, "    args.append(jsBoolean(${paramName}));\n");
                } elsif ($param->type eq "SerializedScriptValue") {
                    push(@implContent, "    args.append($paramName ? $paramName->deserialize(exec, m_data->globalObject(), 0) : jsNull());\n");
                } else {
                    push(@implContent, "    args.append(toJS(exec, m_data->globalObject(), ${paramName}));\n");
                }
            }

            push(@implContent, "\n    bool raisedException = false;\n");
            push(@implContent, "    m_data->invokeCallback(args, &raisedException);\n");
            push(@implContent, "    return !raisedException;\n");
            push(@implContent, "}\n");
        }
    }

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

    if ($interface->extendedAttributes->{"AppleCopyright"}) {
        push(@implContent, split("\r", $endAppleCopyright));
    }
}

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

    my $nondeterministic = $function->signature->extendedAttributes->{"Nondeterministic"};
    my $raisesException = $function->signature->extendedAttributes->{"RaisesException"};

    if ($function->signature->type eq "void" || IsReturningPromise($function)) {
        if ($nondeterministic) {
            AddToImplIncludes("<replay/InputCursor.h>", "WEB_REPLAY");
            push(@implContent, "#if ENABLE(WEB_REPLAY)\n");
            push(@implContent, $indent . "InputCursor& cursor = exec->lexicalGlobalObject()->inputCursor();\n");
            push(@implContent, $indent . "if (!cursor.isReplaying()) {\n");
            push(@implContent, $indent . "    $functionString;\n");
            push(@implContent, $indent . "    setDOMException(exec, ec);\n") if $raisesException;
            push(@implContent, $indent . "}\n");
            push(@implContent, "#else\n");
            push(@implContent, $indent . "$functionString;\n");
            push(@implContent, $indent . "setDOMException(exec, ec);\n") if $raisesException;
            push(@implContent, "#endif\n");
        } else {
            push(@implContent, $indent . "$functionString;\n");
            push(@implContent, $indent . "setDOMException(exec, ec);\n") if $raisesException;
        }

        if ($svgPropertyType and !$function->isStatic) {
            if ($raisesException) {
                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";
        if ($nondeterministic) {
            AddToImplIncludes("MemoizedDOMResult.h", "WEB_REPLAY");
            AddToImplIncludes("<replay/InputCursor.h>", "WEB_REPLAY");
            AddToImplIncludes("<wtf/NeverDestroyed.h>", "WEB_REPLAY");

            my $nativeType = GetNativeTypeFromSignature($function->signature);
            my $memoizedType = GetNativeTypeForMemoization($function->signature->type);
            my $bindingName = $interfaceName . "." . $function->signature->name;
            push(@implContent, $indent . "JSValue result;\n");
            push(@implContent, "#if ENABLE(WEB_REPLAY)\n");
            push(@implContent, $indent . "InputCursor& cursor = exec->lexicalGlobalObject()->inputCursor();\n");
            push(@implContent, $indent . "static NeverDestroyed<const AtomicString> bindingName(\"$bindingName\", AtomicString::ConstructFromLiteral);\n");
            push(@implContent, $indent . "if (cursor.isCapturing()) {\n");
            push(@implContent, $indent . "    $nativeType memoizedResult = $functionString;\n");
            my $exceptionCode = $raisesException ? "ec" : "0";
            push(@implContent, $indent . "    cursor.appendInput<MemoizedDOMResult<$memoizedType>>(bindingName.get().string(), memoizedResult, $exceptionCode);\n");
            push(@implContent, $indent . "    result = " . NativeToJSValue($function->signature, 1, $interfaceName, "memoizedResult", $thisObject) . ";\n");
            push(@implContent, $indent . "} else if (cursor.isReplaying()) {\n");
            push(@implContent, $indent . "    MemoizedDOMResultBase* input = cursor.fetchInput<MemoizedDOMResultBase>();\n");
            push(@implContent, $indent . "    $memoizedType memoizedResult;\n");
            # FIXME: the generated code should report an error if an input cannot be fetched or converted.
            push(@implContent, $indent . "    if (input && input->convertTo<$memoizedType>(memoizedResult)) {\n");
            push(@implContent, $indent . "        result = " . NativeToJSValue($function->signature, 1, $interfaceName, "memoizedResult", $thisObject) . ";\n");
            push(@implContent, $indent . "        ec = input->exceptionCode();\n") if $raisesException;
            push(@implContent, $indent . "    } else\n");
            push(@implContent, $indent . "        result = " . NativeToJSValue($function->signature, 1, $interfaceName, $functionString, $thisObject) . ";\n");
            push(@implContent, $indent . "} else\n");
            push(@implContent, $indent . "    result = " . NativeToJSValue($function->signature, 1, $interfaceName, $functionString, $thisObject) . ";\n");
            push(@implContent, "#else\n");
            push(@implContent, $indent . "result = " . NativeToJSValue($function->signature, 1, $interfaceName, $functionString, $thisObject) . ";\n");
            push(@implContent, "#endif\n");
        } else {
            push(@implContent, $indent . "JSValue result = " . NativeToJSValue($function->signature, 1, $interfaceName, $functionString, $thisObject) . ";\n");
        }
        push(@implContent, "\n" . $indent . "setDOMException(exec, ec);\n") if $raisesException;

        if ($codeGenerator->ExtendedAttributeContains($function->signature->extendedAttributes->{"CallWith"}, "ScriptState")) {
            push(@implContent, $indent . "if (UNLIKELY(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 = $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" => "String",
    "NodeFilter" => "RefPtr<NodeFilter>",
    "SerializedScriptValue" => "RefPtr<SerializedScriptValue>",
    "Date" => "double",
    "Dictionary" => "Dictionary",
    "any" => "Deprecated::ScriptValue",
    "boolean" => "bool",
    "double" => "double",
    "float" => "float",
    "unrestricted double" => "double",
    "unrestricted float" => "float",
    "short" => "int16_t",
    "long" => "int",
    "unsigned long" => "unsigned",
    "unsigned short" => "uint16_t",
    "long long" => "long long",
    "unsigned long long" => "unsigned long long",
    "byte" => "int8_t",
    "octet" => "uint8_t",
    "DOMTimeStamp" => "DOMTimeStamp",
);

sub GetNativeType
{
    my $type = shift;

    my $svgNativeType = $codeGenerator->GetSVGTypeNeedingTearOff($type);
    return "${svgNativeType}*" if $svgNativeType;
    return "RefPtr<DOMStringList>" if $type eq "DOMStringList";
    return "RefPtr<${type}>" if $codeGenerator->IsTypedArrayType($type) and not $type eq "ArrayBuffer";
    return $nativeType{$type} if exists $nativeType{$type};

    my $arrayType = $codeGenerator->GetArrayType($type);
    my $sequenceType = $codeGenerator->GetSequenceType($type);
    my $arrayOrSequenceType = $arrayType || $sequenceType;

    return "Vector<" . GetNativeVectorInnerType($arrayOrSequenceType) . ">" if $arrayOrSequenceType;

    if ($codeGenerator->IsEnumType($type)) {
        return "String";
    }

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

sub GetNativeVectorInnerType
{
    my $arrayOrSequenceType = shift;

    return "String" if $arrayOrSequenceType eq "DOMString";
    return $nativeType{$arrayOrSequenceType} if exists $nativeType{$arrayOrSequenceType};
    return "RefPtr<${arrayOrSequenceType}>";
}

sub GetNativeTypeForCallbacks
{
    my $type = shift;
    return "PassRefPtr<SerializedScriptValue>" if $type eq "SerializedScriptValue";
    return "PassRefPtr<DOMStringList>" if $type eq "DOMStringList";
    return "const String&" if $type eq "DOMString";

    return GetNativeType($type);
}

sub GetNativeTypeForMemoization
{
    my $type = shift;
    return "String" if $type eq "DOMString";

    return GetNativeType($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;

    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 JSValueToNative
{
    my $signature = shift;
    my $value = shift;
    my $conditional = shift;

    my $type = $signature->type;

    return "$value.toBoolean(exec)" if $type eq "boolean";
    return "$value.toNumber(exec)" if $type eq "double" or $type eq "unrestricted double" ;
    return "$value.toFloat(exec)" if $type eq "float" or $type eq "unrestricted float" ;

    my $intConversion = $signature->extendedAttributes->{"EnforceRange"} ? "EnforceRange" : "NormalConversion";
    return "toInt8(exec, $value, $intConversion)" if $type eq "byte";
    return "toUInt8(exec, $value, $intConversion)" if $type eq "octet";
    return "toInt16(exec, $value, $intConversion)" if $type eq "short";
    return "toUInt16(exec, $value, $intConversion)" if $type eq "unsigned short";
    return "toInt32(exec, $value, $intConversion)" if $type eq "long";
    return "toUInt32(exec, $value, $intConversion)" if $type eq "unsigned long";
    return "toInt64(exec, $value, $intConversion)" if $type eq "long long";
    return "toUInt64(exec, $value, $intConversion)" if $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)"
        }
        if ($signature->extendedAttributes->{"AtomicString"}) {
            return "$value.toString(exec)->toAtomicString(exec)";
        }
        # FIXME: Add the case for 'if ($signature->extendedAttributes->{"TreatUndefinedAs"} and $signature->extendedAttributes->{"TreatUndefinedAs"} eq "NullString"))'.
        return "$value.toString(exec)->value(exec)";
    }

    if ($type eq "any") {
        AddToImplIncludes("<bindings/ScriptValue.h>");
        return "{ exec->vm(), $value }";
    }

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

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

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

    if ($type eq "DOMStringList" ) {
        AddToImplIncludes("JSDOMStringList.h", $conditional);
        return "toDOMStringList(exec, $value)";
    }
    
    if ($codeGenerator->IsTypedArrayType($type)) {
        return "to$type($value)";
    }

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

    my $arrayType = $codeGenerator->GetArrayType($type);
    my $sequenceType = $codeGenerator->GetSequenceType($type);
    my $arrayOrSequenceType = $arrayType || $sequenceType;

    if ($arrayOrSequenceType) {
        if ($codeGenerator->IsRefPtrType($arrayOrSequenceType)) {
            AddToImplIncludes("JS${arrayOrSequenceType}.h");
            return "(toRefPtrNativeArray<${arrayOrSequenceType}, JS${arrayOrSequenceType}>(exec, $value, &JS${arrayOrSequenceType}::toWrapped))";
        }
        return "toNativeArray<" . GetNativeVectorInnerType($arrayOrSequenceType) . ">(exec, $value)";
    }

    if ($codeGenerator->IsEnumType($type)) {
        return "$value.toString(exec)->value(exec)";
    }

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

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

    my $conditional = $signature->extendedAttributes->{"Conditional"};
    my $type = $signature->type;

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

    # Need to check Date type before IsPrimitiveType().
    if ($type eq "Date") {
        my $conv = $signature->extendedAttributes->{"TreatReturnedNaNDateAs"};
        if (defined $conv) {
            return "jsDateOrNull(exec, $value)" if $conv eq "Null";
            return "jsDateOrNaN(exec, $value)" if $conv eq "NaN";
            
            die "Unknown value for TreatReturnedNaNDateAs extended attribute";
        }
        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->IsEnumType($type)) {
        AddToImplIncludes("<runtime/JSString.h>", $conditional);
        return "jsStringWithCache(exec, $value)";
    }

    if ($codeGenerator->IsStringType($type)) {
        AddToImplIncludes("URL.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";

            die "Unknown value for TreatReturnedNullStringAs extended attribute";
        }
        AddToImplIncludes("<runtime/JSString.h>", $conditional);
        return "jsStringWithCache(exec, $value)";
    }
    
    my $globalObject;
    if ($thisValue) {
        $globalObject = "$thisValue->globalObject()";
    }

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

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

    my $arrayType = $codeGenerator->GetArrayType($type);
    my $sequenceType = $codeGenerator->GetSequenceType($type);
    my $arrayOrSequenceType = $arrayType || $sequenceType;

    if ($arrayOrSequenceType) {
        if ($arrayType eq "DOMString") {
            AddToImplIncludes("JSDOMStringList.h", $conditional);
            AddToImplIncludes("DOMStringList.h", $conditional);

        } elsif ($codeGenerator->IsRefPtrType($arrayOrSequenceType)) {
            AddToImplIncludes("JS${arrayOrSequenceType}.h", $conditional);
            AddToImplIncludes("${arrayOrSequenceType}.h", $conditional);
        }
        AddToImplIncludes("<runtime/JSArray.h>", $conditional);

        return "jsArray(exec, $thisValue->globalObject(), $value)";
    }

    if ($type eq "any") {
        if ($interfaceName eq "Document") {
            AddToImplIncludes("JSCanvasRenderingContext2D.h", $conditional);
        } else {
            return "($value.hasNoValue() ? jsNull() : $value.jsValue())";
        }
    } elsif ($type eq "SerializedScriptValue" or $type eq "any") {
        AddToImplIncludes("SerializedScriptValue.h", $conditional);
        return "$value ? $value->deserialize(exec, castedThis->globalObject(), 0) : jsNull()";
    } elsif ($codeGenerator->IsTypedArrayType($type)) {
        # Do nothing - all headers are already included.
    } else {
        # Default, include header with same name.
        AddToImplIncludes("JS$type.h", $conditional);
        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($interfaceName) or ($interfaceName eq "SVGViewSpec" and $type eq "SVGTransformList")) {
        # Convert from abstract RefPtr<ListProperty> to real type, so the right toJS() method can be invoked.
        $value = "static_cast<" . GetNativeType($type) . ">($value" . ".get())";
    } elsif ($interfaceName eq "SVGViewSpec") {
        # 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 $interfaceName =~ /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 = "&${interfaceName}::update" . $codeGenerator->WK_ucfirst($getter);

            my $selfIsTearOffType = $codeGenerator->IsSVGTypeNeedingTearOff($interfaceName);
            if ($selfIsTearOffType) {
                AddToImplIncludes("SVGMatrixTearOff.h", $conditional);
                # FIXME: Blink: Don't create a new one everytime we access the matrix property. This means, e.g, === won't work.
                $value = "SVGMatrixTearOff::create(castedThis->impl(), $value)";
            } else {
                AddToImplIncludes("SVGStaticPropertyTearOff.h", $conditional);
                $tearOffType =~ s/SVGPropertyTearOff</SVGStaticPropertyTearOff<$interfaceName, /;
                $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 GenerateHashTableValueArray
{
    my $keys = shift;
    my $specials = shift;
    my $value1 = shift;
    my $value2 = shift;
    my $conditionals = shift;
    my $nameEntries = shift;

    my $packedSize = scalar @{$keys};
    push(@implContent, "\nstatic const HashTableValue $nameEntries\[\] =\n\{\n");

    my $hasSetter = "false";

    my $i = 0;
    foreach my $key (@{$keys}) {
        my $conditional;
        my $firstTargetType;
        my $secondTargetType = "";

        if ($conditionals) {
            $conditional = $conditionals->{$key};
        }
        if ($conditional) {
            my $conditionalString = $codeGenerator->GenerateConditionalStringFromAttributeValue($conditional);
            push(@implContent, "#if ${conditionalString}\n");
        }
        
        if ("@$specials[$i]" =~ m/Function/) {
            $firstTargetType = "static_cast<NativeFunction>";
        } elsif ("@$specials[$i]" =~ m/ConstantInteger/) {
            $firstTargetType = "";
        } else {
            $firstTargetType = "static_cast<PropertySlot::GetValueFunc>";
            $secondTargetType = "static_cast<PutPropertySlot::PutValueFunc>";
            $hasSetter = "true";
        }
        push(@implContent, "    { \"$key\", @$specials[$i], NoIntrinsic, (intptr_t)" . $firstTargetType . "(@$value1[$i]), (intptr_t) " . $secondTargetType . "(@$value2[$i]) },\n");
        if ($conditional) {
            push(@implContent, "#else\n") ;
            push(@implContent, "    { 0, 0, NoIntrinsic, 0, 0 },\n");
            push(@implContent, "#endif\n") ;
        }
        ++$i;
    }

    push(@implContent, "    { 0, 0, NoIntrinsic, 0, 0 }\n") if (!$packedSize);
    push(@implContent, "};\n\n");

    return $hasSetter;
}

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;
    my $justGenerateValueArray = shift;

    my $nameEntries = "${name}Values";
    $nameEntries =~ s/:/_/g;
    my $nameIndex = "${name}Index";
    $nameIndex =~ 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");
    }

    if ($justGenerateValueArray) {
        GenerateHashTableValueArray($keys, $specials, $value1, $value2, $conditionals, $nameEntries) if $size;
        return;
    }

    # 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 = Hasher::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);
    }

    push(@implContent, "\nstatic const struct CompactHashIndex ${nameIndex}\[$compactSize\] = {\n");
    for (my $i = 0; $i < $compactSize; $i++) {
        my $T = -1;
        if (defined($table[$i])) { $T = $table[$i]; }
        my $L = -1;
        if (defined($links[$i])) { $L = $links[$i]; }
        push(@implContent, "    { $T, $L },\n");
    }
    push(@implContent, "};\n\n");

    # Dump the hash table
    my $hasSetter = GenerateHashTableValueArray($keys, $specials, $value1, $value2, $conditionals, $nameEntries);
    my $packedSize = scalar @{$keys};

    my $compactSizeMask = $numEntries - 1;
    push(@implContent, "static const HashTable $name = { $packedSize, $compactSizeMask, $hasSetter, $nameEntries, 0, $nameIndex };\n");
}

sub WriteData
{
    my $object = shift;
    my $interface = shift;
    my $outputDir = shift;

    my $name = $interface->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{$codeGenerator->GenerateConditionalStringFromAttributeValue($condition)}}, $include;
        }
    }
    foreach my $include (sort @includes) {
        $contents .= "#include $include\n";
    }
    foreach my $condition (sort keys %implIncludeConditions) {
        $contents .= "\n#if " . $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) {
        # "JSClassName.h" is already included right after config.h.
        next if $include eq "\"$prefix$name.h\"";
        $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 GeneratePrototypeDeclaration
{
    my $outputArray = shift;
    my $className = shift;
    my $interface = shift;
    my $interfaceName = shift;

    my $prototypeClassName = "${className}Prototype";

    my %structureFlags = ();
    push(@$outputArray, "class ${prototypeClassName} : public JSC::JSNonFinalObject {\n");
    push(@$outputArray, "public:\n");
    push(@$outputArray, "    typedef JSC::JSNonFinalObject Base;\n");

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

    push(@$outputArray, "    DECLARE_INFO;\n");

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

    push(@$outputArray, "\nprivate:\n");
    push(@$outputArray, "    ${prototypeClassName}(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure)\n");
    push(@$outputArray, "        : JSC::JSNonFinalObject(vm, structure)\n");
    push(@$outputArray, "    {\n");
    push(@$outputArray, "    }\n");

    if (PrototypeOverridesGetOwnPropertySlot($interface)) {
        push(@$outputArray, "\n");
        if (IsDOMGlobalObject($interface)) {
            push(@$outputArray, "    static bool getOwnPropertySlot(JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&);\n");
            $structureFlags{"JSC::OverridesGetOwnPropertySlot"} = 1;
        } else {
            push(@$outputArray, "    void finishCreation(JSC::VM&);\n");
        }
    }

    if ($interface->extendedAttributes->{"JSCustomNamedGetterOnPrototype"}) {
        push(@$outputArray, "\n");
        push(@$outputArray, "    static void put(JSC::JSCell*, JSC::ExecState*, JSC::PropertyName, JSC::JSValue, JSC::PutPropertySlot&);\n");
        push(@$outputArray, "    bool putDelegate(JSC::ExecState*, JSC::PropertyName, JSC::JSValue, JSC::PutPropertySlot&);\n");
    }

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

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

    push(@$outputArray, "};\n\n");
}

sub GenerateConstructorDeclaration
{
    my $outputArray = shift;
    my $className = shift;
    my $interface = 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::VM&, JSDOMGlobalObject*);\n\n");

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

    push(@$outputArray, "    DECLARE_INFO;\n");

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

    if (IsConstructable($interface) && !$interface->extendedAttributes->{"NamedConstructor"}) {
        if (!HasCustomConstructor($interface)) {
            push(@$outputArray, "protected:\n");
            push(@$outputArray, "    static JSC::EncodedJSValue JSC_HOST_CALL construct${className}(JSC::ExecState*);\n");
            my @constructors = @{$interface->constructors};
            if (@constructors > 1) {
                foreach my $constructor (@constructors) {
                    my $overloadedIndex = "" . $constructor->{overloadedIndex};
                    push(@$outputArray, "    static JSC::EncodedJSValue JSC_HOST_CALL construct${className}${overloadedIndex}(JSC::ExecState*);\n");
                }
            }
        }

        my $conditionalString = $codeGenerator->GenerateConstructorConditionalString($interface);
        push(@$outputArray, "#if $conditionalString\n") if $conditionalString;
        push(@$outputArray, "    static JSC::ConstructType getConstructData(JSC::JSCell*, JSC::ConstructData&);\n");
        push(@$outputArray, "#endif // $conditionalString\n") if $conditionalString;
    }
    push(@$outputArray, "};\n\n");

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

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

    static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)
    {
        return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info());
    }

    DECLARE_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::VM&, JSDOMGlobalObject*);
};

END
    }
}

sub GenerateConstructorDefinitions
{
    my $outputArray = shift;
    my $className = shift;
    my $protoClassName = shift;
    my $interfaceName = shift;
    my $visibleInterfaceName = shift;
    my $interface = shift;
    my $generatingNamedConstructor = shift;

    if (IsConstructable($interface)) {
        my @constructors = @{$interface->constructors};
        if (@constructors > 1) {
            foreach my $constructor (@constructors) {
                GenerateConstructorDefinition($outputArray, $className, $protoClassName, $interfaceName, $visibleInterfaceName, $interface, $generatingNamedConstructor, $constructor);
            }
            GenerateOverloadedConstructorDefinition($outputArray, $className, $interface);
        } elsif (@constructors == 1) {
            GenerateConstructorDefinition($outputArray, $className, $protoClassName, $interfaceName, $visibleInterfaceName, $interface, $generatingNamedConstructor, $constructors[0]);
        } else {
            GenerateConstructorDefinition($outputArray, $className, $protoClassName, $interfaceName, $visibleInterfaceName, $interface, $generatingNamedConstructor);
        }
    }

    GenerateConstructorHelperMethods($outputArray, $className, $protoClassName, $interfaceName, $visibleInterfaceName, $interface, $generatingNamedConstructor);
}

sub GenerateOverloadedConstructorDefinition
{
    my $outputArray = shift;
    my $className = shift;
    my $interface = shift;

    my $functionName = "${className}Constructor::construct${className}";

    # FIXME: Implement support for overloaded constructors with variadic arguments.
    my $lengthOfLongestOverloadedConstructorParameterList = LengthOfLongestFunctionParameterList($interface->constructors);

    push(@$outputArray, <<END);
EncodedJSValue JSC_HOST_CALL ${functionName}(ExecState* exec)
{
    size_t argsCount = std::min<size_t>($lengthOfLongestOverloadedConstructorParameterList, exec->argumentCount());
END

    my %fetchedArguments = ();
    my $leastNumMandatoryParams = 255;

    my @constructors = @{$interface->constructors};
    foreach my $overload (@constructors) {
        my ($numMandatoryParams, $parametersCheck, @neededArguments) = GenerateFunctionParametersCheck($overload);
        $leastNumMandatoryParams = $numMandatoryParams if ($numMandatoryParams < $leastNumMandatoryParams);

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

        push(@$outputArray, "    if ($parametersCheck)\n");
        push(@$outputArray, "        return ${functionName}$overload->{overloadedIndex}(exec);\n");
    }

    if ($leastNumMandatoryParams >= 1) {
        push(@$outputArray, "    if (argsCount < $leastNumMandatoryParams)\n");
        push(@$outputArray, "        return throwVMError(exec, createNotEnoughArgumentsError(exec));\n");
    }
    push(@$outputArray, <<END);
    return throwVMTypeError(exec);
}

END
}

sub GenerateConstructorDefinition
{
    my $outputArray = shift;
    my $className = shift;
    my $protoClassName = shift;
    my $interfaceName = shift;
    my $visibleInterfaceName = shift;
    my $interface = shift;
    my $generatingNamedConstructor = shift;
    my $function = shift;

    my $constructorClassName = $generatingNamedConstructor ? "${className}NamedConstructor" : "${className}Constructor";

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

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

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

    AtomicString eventType = exec->argument(0).toString(exec)->toAtomicString(exec);
    if (UNLIKELY(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

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

END
            }

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

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

END
        } elsif (!HasCustomConstructor($interface) && (!$interface->extendedAttributes->{"NamedConstructor"} || $generatingNamedConstructor)) {
            my $overloadedIndexString = "";
            if ($function->{overloadedIndex} && $function->{overloadedIndex} > 0) {
                $overloadedIndexString .= $function->{overloadedIndex};
            }

            push(@$outputArray, "EncodedJSValue JSC_HOST_CALL ${constructorClassName}::construct${className}${overloadedIndexString}(ExecState* exec)\n");
            push(@$outputArray, "{\n");
            push(@$outputArray, "    auto* castedThis = jsCast<${constructorClassName}*>(exec->callee());\n");

            my @constructorArgList;

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

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

            if ($function->signature->extendedAttributes->{"RaisesException"} || $interface->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 without [Default=...]
            my $numParameters = @{$function->parameters};
            my ($dummy, $paramIndex) = GenerateParametersCheck($outputArray, $function, $interface, $numParameters, $interfaceName, "constructorCallback", undef, undef, undef);

            if ($codeGenerator->ExtendedAttributeContains($interface->extendedAttributes->{"ConstructorCallWith"}, "ScriptState")) {
                push(@constructorArgList, "*exec");
            }
            if ($codeGenerator->ExtendedAttributeContains($interface->extendedAttributes->{"ConstructorCallWith"}, "ScriptExecutionContext")) {
                push(@constructorArgList, "*context");
                push(@$outputArray, "    ScriptExecutionContext* context = castedThis->scriptExecutionContext();\n");
                push(@$outputArray, "    if (!context)\n");
                push(@$outputArray, "        return throwConstructorDocumentUnavailableError(*exec, \"${interfaceName}\");\n");
            }
            if ($codeGenerator->ExtendedAttributeContains($interface->extendedAttributes->{"ConstructorCallWith"}, "Document")) {
                $implIncludes{"Document.h"} = 1;
                push(@constructorArgList, "document");
                push(@$outputArray, "    ScriptExecutionContext* context = castedThis->scriptExecutionContext();\n");
                push(@$outputArray, "    if (!context)\n");
                push(@$outputArray, "        return throwConstructorDocumentUnavailableError(*exec, \"${interfaceName}\");\n");
                push(@$outputArray, "    auto& document = downcast<Document>(*context);\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 ($interface->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 ($interface->extendedAttributes->{"ConstructorRaisesException"}) {
                push(@$outputArray, "    if (ec) {\n");
                push(@$outputArray, "        setDOMException(exec, ec);\n");
                push(@$outputArray, "        return JSValue::encode(JSValue());\n");
                push(@$outputArray, "    }\n");
            }

            if ($codeGenerator->ExtendedAttributeContains($interface->extendedAttributes->{"ConstructorCallWith"}, "ScriptState")) {
                 push(@$outputArray, "    if (UNLIKELY(exec->hadException()))\n");
                 push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
            }

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

sub ConstructorHasProperties
{
    my $interface = shift;

    foreach my $constant (@{$interface->constants}) {
        return 1;
    }

    foreach my $attribute (@{$interface->attributes}) {
        next unless ($attribute->isStatic);
        return 1;
    }

    foreach my $function (@{$interface->functions}) {
        next unless ($function->isStatic);
        return 1;
    }

    return 0;
}

sub GenerateConstructorHelperMethods
{
    my $outputArray = shift;
    my $className = shift;
    my $protoClassName = shift;
    my $interfaceName = shift;
    my $visibleInterfaceName = shift;
    my $interface = shift;
    my $generatingNamedConstructor = shift;

    my $constructorClassName = $generatingNamedConstructor ? "${className}NamedConstructor" : "${className}Constructor";
    my $constructorParentClassName = $generatingNamedConstructor ? "DOMConstructorWithDocument" : "DOMConstructorObject";
    my $leastConstructorLength = 0;
    if ($codeGenerator->IsConstructorTemplate($interface, "Event")) {
        $leastConstructorLength = 1;
    } elsif ($interface->extendedAttributes->{"Constructor"} || $interface->extendedAttributes->{"CustomConstructor"}) {
        my @constructors = @{$interface->constructors};
        my @customConstructors = @{$interface->customConstructors};
        $leastConstructorLength = 255;
        foreach my $constructor (@constructors, @customConstructors) {
            my $constructorLength = GetFunctionLength($constructor);
            $leastConstructorLength = $constructorLength if ($constructorLength < $leastConstructorLength);
        }
    } else {
        $leastConstructorLength = 0;
    }

    push(@$outputArray, "const ClassInfo ${constructorClassName}::s_info = { \"${visibleInterfaceName}Constructor\", &Base::s_info, 0, CREATE_METHOD_TABLE($constructorClassName) };\n\n");

    push(@$outputArray, "${constructorClassName}::${constructorClassName}(Structure* structure, JSDOMGlobalObject* globalObject)\n");
    push(@$outputArray, "    : ${constructorParentClassName}(structure, globalObject)\n");
    push(@$outputArray, "{\n");
    push(@$outputArray, "}\n\n");

    push(@$outputArray, "void ${constructorClassName}::finishCreation(VM& vm, JSDOMGlobalObject* globalObject)\n");
    push(@$outputArray, "{\n");
    if (IsDOMGlobalObject($interface)) {
        push(@$outputArray, "    Base::finishCreation(vm);\n");
        push(@$outputArray, "    ASSERT(inherits(info()));\n");
        push(@$outputArray, "    putDirect(vm, vm.propertyNames->prototype, globalObject->prototype(), DontDelete | ReadOnly);\n");
    } elsif ($generatingNamedConstructor) {
        push(@$outputArray, "    Base::finishCreation(globalObject);\n");
        push(@$outputArray, "    ASSERT(inherits(info()));\n");
        push(@$outputArray, "    putDirect(vm, vm.propertyNames->prototype, ${className}::getPrototype(vm, globalObject), None);\n");
    } else {
        push(@$outputArray, "    Base::finishCreation(vm);\n");
        push(@$outputArray, "    ASSERT(inherits(info()));\n");
        push(@$outputArray, "    putDirect(vm, vm.propertyNames->prototype, ${className}::getPrototype(vm, globalObject), DontDelete | ReadOnly);\n");
    }

    if (defined $leastConstructorLength) {
        push(@$outputArray, "    putDirect(vm, vm.propertyNames->length, jsNumber(${leastConstructorLength}), ReadOnly | DontDelete | DontEnum);\n");
    }

    if (ConstructorHasProperties($interface)) {
        push(@$outputArray, "    reifyStaticProperties(vm, ${className}ConstructorTableValues, *this);\n");
    }

    push(@$outputArray, "}\n\n");

    if (IsConstructable($interface)) {
        if (!$interface->extendedAttributes->{"NamedConstructor"} || $generatingNamedConstructor) {
            my $conditionalString = $codeGenerator->GenerateConstructorConditionalString($interface);
            push(@$outputArray, "#if $conditionalString\n") if $conditionalString;
            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");
            push(@$outputArray, "#endif // $conditionalString\n") if $conditionalString;
            push(@$outputArray, "\n");
        }
    }
}

sub HasCustomConstructor
{
    my $interface = shift;

    return $interface->extendedAttributes->{"CustomConstructor"};
}

sub HasCustomGetter
{
    my $attrExt = shift;
    return $attrExt->{"Custom"} || $attrExt->{"CustomGetter"} ;
}

sub HasCustomSetter
{
    my $attrExt = shift;
    return $attrExt->{"Custom"} || $attrExt->{"CustomSetter"};
}

sub HasCustomMethod
{
    my $attrExt = shift;
    return $attrExt->{"Custom"};
}

sub NeedsConstructorProperty
{
    my $interface = shift;

    return !$interface->extendedAttributes->{"NoInterfaceObject"} || $interface->extendedAttributes->{"CustomConstructor"};
}

sub IsReturningPromise
{
    my $function = shift;

    return $function->signature->type eq "Promise" if ($function->signature->type);
}

sub IsConstructable
{
    my $interface = shift;

    return HasCustomConstructor($interface) || $interface->extendedAttributes->{"Constructor"} || $interface->extendedAttributes->{"NamedConstructor"} || $interface->extendedAttributes->{"ConstructorTemplate"};
}

sub HeaderNeedsPrototypeDeclaration
{
    my $interface = shift;

    return IsDOMGlobalObject($interface) || $interface->extendedAttributes->{"JSCustomNamedGetterOnPrototype"} || $interface->extendedAttributes->{"JSCustomDefineOwnPropertyOnPrototype"};
}

1;