Fix the issue that Web Audio test case fails on PR3.
[framework/web/webkit-efl.git] / Source / WebCore / bindings / scripts / CodeGeneratorJS.pm
1 #
2 # Copyright (C) 2005, 2006, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
3 # Copyright (C) 2006 Anders Carlsson <andersca@mac.com>
4 # Copyright (C) 2006, 2007 Samuel Weinig <sam@webkit.org>
5 # Copyright (C) 2006 Alexey Proskuryakov <ap@webkit.org>
6 # Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
7 # Copyright (C) 2009 Cameron McCormack <cam@mcc.id.au>
8 # Copyright (C) Research In Motion Limited 2010. All rights reserved.
9 # Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
10 # Copyright (C) 2011 Patrick Gansterer <paroga@webkit.org>
11 #
12 # This library is free software; you can redistribute it and/or
13 # modify it under the terms of the GNU Library General Public
14 # License as published by the Free Software Foundation; either
15 # version 2 of the License, or (at your option) any later version.
16 #
17 # This library is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 # Library General Public License for more details.
21 #
22 # You should have received a copy of the GNU Library General Public License
23 # along with this library; see the file COPYING.LIB.  If not, write to
24 # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 # Boston, MA 02110-1301, USA.
26
27 package CodeGeneratorJS;
28
29 use strict;
30
31 use constant FileNamePrefix => "JS";
32
33 my $codeGenerator;
34
35 my $module = "";
36 my $outputDir = "";
37 my $writeDependencies = 0;
38
39 my @headerContentHeader = ();
40 my @headerContent = ();
41 my %headerIncludes = ();
42 my %headerTrailingIncludes = ();
43
44 my @implContentHeader = ();
45 my @implContent = ();
46 my %implIncludes = ();
47 my @depsContent = ();
48 my $numCachedAttributes = 0;
49 my $currentCachedAttribute = 0;
50
51 # Default .h template
52 my $headerTemplate = << "EOF";
53 /*
54     This file is part of the WebKit open source project.
55     This file has been generated by generate-bindings.pl. DO NOT MODIFY!
56
57     This library is free software; you can redistribute it and/or
58     modify it under the terms of the GNU Library General Public
59     License as published by the Free Software Foundation; either
60     version 2 of the License, or (at your option) any later version.
61
62     This library is distributed in the hope that it will be useful,
63     but WITHOUT ANY WARRANTY; without even the implied warranty of
64     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
65     Library General Public License for more details.
66
67     You should have received a copy of the GNU Library General Public License
68     along with this library; see the file COPYING.LIB.  If not, write to
69     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
70     Boston, MA 02110-1301, USA.
71 */
72 EOF
73
74 # Default constructor
75 sub new
76 {
77     my $object = shift;
78     my $reference = { };
79
80     $codeGenerator = shift;
81     $outputDir = shift;
82     shift; # $outputHeadersDir
83     shift; # $useLayerOnTop
84     shift; # $preprocessor
85     $writeDependencies = shift;
86
87     bless($reference, $object);
88     return $reference;
89 }
90
91 sub leftShift($$) {
92     my ($value, $distance) = @_;
93     return (($value << $distance) & 0xFFFFFFFF);
94 }
95
96 # Params: 'domClass' struct
97 sub GenerateInterface
98 {
99     my $object = shift;
100     my $dataNode = shift;
101     my $defines = shift;
102
103     $codeGenerator->LinkOverloadedFunctions($dataNode);
104
105     # Start actual generation
106     if ($dataNode->extendedAttributes->{"Callback"}) {
107         $object->GenerateCallbackHeader($dataNode);
108         $object->GenerateCallbackImplementation($dataNode);
109     } else {
110         $object->GenerateHeader($dataNode);
111         $object->GenerateImplementation($dataNode);
112     }
113
114     $object->WriteData($dataNode);
115 }
116
117 sub GenerateAttributeEventListenerCall
118 {
119     my $className = shift;
120     my $implSetterFunctionName = shift;
121     my $windowEventListener = shift;
122
123     my $wrapperObject = $windowEventListener ? "globalObject" : "thisObject";
124     my @GenerateEventListenerImpl = ();
125
126     if ($className eq "JSSVGElementInstance") {
127         # SVGElementInstances have to create JSEventListeners with the wrapper equal to the correspondingElement
128         $wrapperObject = "asObject(correspondingElementWrapper)";
129
130         push(@GenerateEventListenerImpl, <<END);
131     JSValue correspondingElementWrapper = toJS(exec, castedThis->globalObject(), impl->correspondingElement());
132     if (correspondingElementWrapper.isObject())
133 END
134
135         # Add leading whitespace to format the impl->set... line correctly
136         push(@GenerateEventListenerImpl, "    ");
137     }
138
139     push(@GenerateEventListenerImpl, "    impl->set$implSetterFunctionName(createJSAttributeEventListener(exec, value, $wrapperObject));\n");
140     return @GenerateEventListenerImpl;
141 }
142
143 sub GenerateEventListenerCall
144 {
145     my $className = shift;
146     my $functionName = shift;
147     my $passRefPtrHandling = ($functionName eq "add") ? "" : ".get()";
148
149     $implIncludes{"JSEventListener.h"} = 1;
150
151     my @GenerateEventListenerImpl = ();
152     my $wrapperObject = "castedThis";
153     if ($className eq "JSSVGElementInstance") {
154         # SVGElementInstances have to create JSEventListeners with the wrapper equal to the correspondingElement
155         $wrapperObject = "asObject(correspondingElementWrapper)";
156
157         push(@GenerateEventListenerImpl, <<END);
158     JSValue correspondingElementWrapper = toJS(exec, castedThis->globalObject(), impl->correspondingElement());
159     if (!correspondingElementWrapper.isObject())
160         return JSValue::encode(jsUndefined());
161 END
162     }
163
164     push(@GenerateEventListenerImpl, <<END);
165     JSValue listener = exec->argument(1);
166     if (!listener.isObject())
167         return JSValue::encode(jsUndefined());
168     impl->${functionName}EventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), $wrapperObject, false, currentWorld(exec))$passRefPtrHandling, exec->argument(2).toBoolean());
169     return JSValue::encode(jsUndefined());
170 END
171     return @GenerateEventListenerImpl;
172 }
173
174 # Params: 'idlDocument' struct
175 sub GenerateModule
176 {
177     my $object = shift;
178     my $dataNode = shift;
179
180     $module = $dataNode->module;
181 }
182
183 sub GetParentClassName
184 {
185     my $dataNode = shift;
186
187     return $dataNode->extendedAttributes->{"JSLegacyParent"} if $dataNode->extendedAttributes->{"JSLegacyParent"};
188     return "JSDOMWrapper" if (@{$dataNode->parents} eq 0);
189     return "JS" . $codeGenerator->StripModule($dataNode->parents(0));
190 }
191
192 sub GetCallbackClassName
193 {
194     my $className = shift;
195
196     return "JSCustomVoidCallback" if $className eq "VoidCallback";
197     return "JS$className";
198 }
199
200 sub IndexGetterReturnsStrings
201 {
202     my $type = shift;
203
204     return 1 if $type eq "CSSStyleDeclaration" or $type eq "MediaList" or $type eq "DOMStringList" or $type eq "DOMString[]"  or $type eq "DOMTokenList" or $type eq "DOMSettableTokenList";
205     return 0;
206 }
207
208 sub AddIncludesForTypeInImpl
209 {
210     my $type = $codeGenerator->StripModule(shift);
211     my $isCallback = @_ ? shift : 0;
212     
213     AddIncludesForType($type, $isCallback, \%implIncludes);
214     
215     # additional includes (things needed to compile the bindings but not the header)
216     if ($type eq "CanvasRenderingContext2D") {
217         $implIncludes{"CanvasGradient.h"} = 1;
218         $implIncludes{"CanvasPattern.h"} = 1;
219         $implIncludes{"CanvasStyle.h"} = 1;
220     }
221
222     if ($type eq "CanvasGradient" or $type eq "XPathNSResolver" or $type eq "MessagePort") {
223         $implIncludes{"PlatformString.h"} = 1;
224     }
225
226     if ($type eq "Document") {
227         $implIncludes{"NodeFilter.h"} = 1;
228     }
229
230     if ($type eq "MediaQueryListListener") {
231         $implIncludes{"MediaQueryListListener.h"} = 1;
232     }
233 }
234
235 sub AddIncludesForTypeInHeader
236 {
237     my $type = $codeGenerator->StripModule(shift);
238     my $isCallback = @_ ? shift : 0;
239     
240     AddIncludesForType($type, $isCallback, \%headerIncludes);
241 }
242
243 sub AddIncludesForType
244 {
245     my $type = shift;
246     my $isCallback = shift;
247     my $includesRef = shift;
248
249     # When we're finished with the one-file-per-class
250     # reorganization, we won't need these special cases.
251     if ($codeGenerator->IsPrimitiveType($type) or $codeGenerator->SkipIncludeHeader($type)
252         or $type eq "DOMString" or $type eq "DOMObject" or $type eq "any" or $type eq "Array" or $type eq "DOMTimeStamp") {
253     } elsif ($type =~ /SVGPathSeg/) {
254         my $joinedName = $type;
255         $joinedName =~ s/Abs|Rel//;
256         $includesRef->{"${joinedName}.h"} = 1;
257     } elsif ($type eq "XPathNSResolver") {
258         $includesRef->{"JSXPathNSResolver.h"} = 1;
259         $includesRef->{"JSCustomXPathNSResolver.h"} = 1;
260     } elsif ($type eq "DOMString[]") {
261         # FIXME: Add proper support for T[], T[]?, sequence<T>
262         $includesRef->{"JSDOMStringList.h"} = 1;
263     } elsif ($type eq "SerializedScriptValue") {
264         $includesRef->{"SerializedScriptValue.h"} = 1;
265     } elsif ($isCallback) {
266         $includesRef->{"JS${type}.h"} = 1;
267     } elsif (IsTypedArrayType($type)) {
268         $includesRef->{"<wtf/${type}.h>"} = 1;
269     } elsif ($codeGenerator->GetSequenceType($type)) {
270     } else {
271         # default, include the same named file
272         $includesRef->{"${type}.h"} = 1;
273     }
274 }
275
276 # FIXME: This method will go away once all SVG animated properties are converted to the new scheme.
277 sub AddIncludesForSVGAnimatedType
278 {
279     my $type = shift;
280     $type =~ s/SVGAnimated//;
281
282     if ($type eq "Point" or $type eq "Rect") {
283         $implIncludes{"Float$type.h"} = 1;
284     } elsif ($type eq "String") {
285         $implIncludes{"PlatformString.h"} = 1;
286     }
287 }
288
289 sub AddToImplIncludes
290 {
291     my $header = shift;
292     my $conditional = shift;
293
294     if (not $conditional) {
295         $implIncludes{$header} = 1;
296     } elsif (not exists($implIncludes{$header})) {
297         $implIncludes{$header} = $conditional;
298     } else {
299         my $oldValue = $implIncludes{$header};
300         if ($oldValue ne 1) {
301             my %newValue = ();
302             $newValue{$conditional} = 1;
303             foreach my $condition (split(/\|/, $oldValue)) {
304                 $newValue{$condition} = 1;
305             }
306             $implIncludes{$header} = join("|", sort keys %newValue);
307         }
308     }
309 }
310
311 sub IsScriptProfileType
312 {
313     my $type = shift;
314     return 1 if ($type eq "ScriptProfileNode");
315     return 0;
316 }
317
318 sub IsTypedArrayType
319 {
320     my $type = shift;
321     return 1 if (($type eq "ArrayBuffer") or ($type eq "ArrayBufferView"));
322     return 1 if (($type eq "Uint8Array") or ($type eq "Uint8ClampedArray") or ($type eq "Uint16Array") or ($type eq "Uint32Array"));
323     return 1 if (($type eq "Int8Array") or ($type eq "Int16Array") or ($type eq "Int32Array"));
324     return 1 if (($type eq "Float32Array") or ($type eq "Float64Array"));
325     return 0;
326 }
327
328 sub AddTypedefForScriptProfileType
329 {
330     my $type = shift;
331     (my $jscType = $type) =~ s/Script//;
332
333     push(@headerContent, "typedef JSC::$jscType $type;\n\n");
334 }
335
336 sub AddClassForwardIfNeeded
337 {
338     my $implClassName = shift;
339
340     # SVGAnimatedLength/Number/etc. are typedefs to SVGAnimatedTemplate, so don't use class forwards for them!
341     unless ($codeGenerator->IsSVGAnimatedType($implClassName) or IsScriptProfileType($implClassName) or IsTypedArrayType($implClassName)) {
342         push(@headerContent, "class $implClassName;\n\n");
343     # ScriptProfile and ScriptProfileNode are typedefs to JSC::Profile and JSC::ProfileNode.
344     } elsif (IsScriptProfileType($implClassName)) {
345         $headerIncludes{"<profiler/ProfileNode.h>"} = 1;
346         AddTypedefForScriptProfileType($implClassName);
347     }
348 }
349
350 sub HashValueForClassAndName
351 {
352     my $class = shift;
353     my $name = shift;
354
355     # SVG Filter enums live in WebCore namespace (platform/graphics/)
356     if ($class =~ /^SVGFE*/ or $class =~ /^SVGComponentTransferFunctionElement$/) {
357         return "WebCore::$name";
358     }
359
360     return "${class}::$name";
361 }
362
363 sub hashTableAccessor
364 {
365     my $noStaticTables = shift;
366     my $className = shift;
367     if ($noStaticTables) {
368         return "get${className}Table(exec)";
369     } else {
370         return "&${className}Table";
371     }
372 }
373
374 sub prototypeHashTableAccessor
375 {
376     my $noStaticTables = shift;
377     my $className = shift;
378     if ($noStaticTables) {
379         return "get${className}PrototypeTable(exec)";
380     } else {
381         return "&${className}PrototypeTable";
382     }
383 }
384
385 sub GetGenerateIsReachable
386 {
387     my $dataNode = shift;
388     return $dataNode->extendedAttributes->{"GenerateIsReachable"} || $dataNode->extendedAttributes->{"JSGenerateIsReachable"};
389 }
390
391 sub GetCustomIsReachable
392 {
393     my $dataNode = shift;
394     return $dataNode->extendedAttributes->{"CustomIsReachable"} || $dataNode->extendedAttributes->{"JSCustomIsReachable"};
395 }
396
397 sub GenerateGetOwnPropertySlotBody
398 {
399     my ($dataNode, $interfaceName, $className, $implClassName, $hasAttributes, $inlined) = @_;
400
401     my $namespaceMaybe = ($inlined ? "JSC::" : "");
402
403     my @getOwnPropertySlotImpl = ();
404
405     if ($interfaceName eq "NamedNodeMap" or $interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection" or $interfaceName eq "HTMLPropertiesCollection") {
406         push(@getOwnPropertySlotImpl, "    ${namespaceMaybe}JSValue proto = thisObject->prototype();\n");
407         push(@getOwnPropertySlotImpl, "    if (proto.isObject() && jsCast<${namespaceMaybe}JSObject*>(asObject(proto))->hasProperty(exec, propertyName))\n");
408         push(@getOwnPropertySlotImpl, "        return false;\n\n");
409     }
410
411     my $manualLookupGetterGeneration = sub {
412         my $requiresManualLookup = $dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NamedGetter"};
413         if ($requiresManualLookup) {
414             push(@getOwnPropertySlotImpl, "    const ${namespaceMaybe}HashEntry* entry = ${className}Table.entry(exec, propertyName);\n");
415             push(@getOwnPropertySlotImpl, "    if (entry) {\n");
416             push(@getOwnPropertySlotImpl, "        slot.setCustom(thisObject, entry->propertyGetter());\n");
417             push(@getOwnPropertySlotImpl, "        return true;\n");
418             push(@getOwnPropertySlotImpl, "    }\n");
419         }
420     };
421
422     if (!$dataNode->extendedAttributes->{"CustomNamedGetter"}) {
423         &$manualLookupGetterGeneration();
424     }
425
426     if ($dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
427         push(@getOwnPropertySlotImpl, "    unsigned index = propertyName.asIndex();\n");
428
429         # If the item function returns a string then we let the TreatReturnedNullStringAs handle the cases
430         # where the index is out of range.
431         if (IndexGetterReturnsStrings($implClassName)) {
432             push(@getOwnPropertySlotImpl, "    if (index != PropertyName::NotAnIndex) {\n");
433         } else {
434             push(@getOwnPropertySlotImpl, "    if (index != PropertyName::NotAnIndex && index < static_cast<$implClassName*>(thisObject->impl())->length()) {\n");
435         }
436         if ($dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
437             push(@getOwnPropertySlotImpl, "        slot.setValue(thisObject->getByIndex(exec, index));\n");
438         } else {
439             push(@getOwnPropertySlotImpl, "        slot.setCustomIndex(thisObject, index, indexGetter);\n");
440         }
441         push(@getOwnPropertySlotImpl, "        return true;\n");
442         push(@getOwnPropertySlotImpl, "    }\n");
443     }
444
445     if ($dataNode->extendedAttributes->{"NamedGetter"} || $dataNode->extendedAttributes->{"CustomNamedGetter"}) {
446         push(@getOwnPropertySlotImpl, "    if (canGetItemsForName(exec, static_cast<$implClassName*>(thisObject->impl()), propertyName)) {\n");
447         push(@getOwnPropertySlotImpl, "        slot.setCustom(thisObject, thisObject->nameGetter);\n");
448         push(@getOwnPropertySlotImpl, "        return true;\n");
449         push(@getOwnPropertySlotImpl, "    }\n");
450         if ($inlined) {
451             $headerIncludes{"wtf/text/AtomicString.h"} = 1;
452         } else {
453             $implIncludes{"wtf/text/AtomicString.h"} = 1;
454         }
455     }
456
457     if ($dataNode->extendedAttributes->{"CustomNamedGetter"}) {
458         &$manualLookupGetterGeneration();
459     }
460
461     if ($dataNode->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}) {
462         push(@getOwnPropertySlotImpl, "    if (thisObject->getOwnPropertySlotDelegate(exec, propertyName, slot))\n");
463         push(@getOwnPropertySlotImpl, "        return true;\n");
464     }
465
466     if ($hasAttributes) {
467         if ($inlined) {
468             die "Cannot inline if NoStaticTables is set." if ($dataNode->extendedAttributes->{"JSNoStaticTables"});
469             push(@getOwnPropertySlotImpl, "    return ${namespaceMaybe}getStaticValueSlot<$className, Base>(exec, s_info.staticPropHashTable, thisObject, propertyName, slot);\n");
470         } else {
471             push(@getOwnPropertySlotImpl, "    return ${namespaceMaybe}getStaticValueSlot<$className, Base>(exec, " . hashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, slot);\n");
472         }
473     } else {
474         push(@getOwnPropertySlotImpl, "    return Base::getOwnPropertySlot(thisObject, exec, propertyName, slot);\n");
475     }
476
477     return @getOwnPropertySlotImpl;
478 }
479
480 sub GenerateGetOwnPropertyDescriptorBody
481 {
482     my ($dataNode, $interfaceName, $className, $implClassName, $hasAttributes, $inlined) = @_;
483     
484     my $namespaceMaybe = ($inlined ? "JSC::" : "");
485     
486     my @getOwnPropertyDescriptorImpl = ();
487     if ($dataNode->extendedAttributes->{"CheckSecurity"}) {
488         if ($interfaceName eq "DOMWindow") {
489             push(@implContent, "    if (!thisObject->allowsAccessFrom(exec))\n");
490         } else {
491             push(@implContent, "    if (!shouldAllowAccessToFrame(exec, thisObject->impl()->frame()))\n");
492         }
493         push(@implContent, "        return false;\n");
494     }
495     
496     if ($interfaceName eq "NamedNodeMap" or $interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection" or $interfaceName eq "HTMLPropertiesCollection") {
497         push(@getOwnPropertyDescriptorImpl, "    ${namespaceMaybe}JSValue proto = thisObject->prototype();\n");
498         push(@getOwnPropertyDescriptorImpl, "    if (proto.isObject() && jsCast<${namespaceMaybe}JSObject*>(asObject(proto))->hasProperty(exec, propertyName))\n");
499         push(@getOwnPropertyDescriptorImpl, "        return false;\n\n");
500     }
501     
502     my $manualLookupGetterGeneration = sub {
503         my $requiresManualLookup = $dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NamedGetter"};
504         if ($requiresManualLookup) {
505             push(@getOwnPropertyDescriptorImpl, "    const ${namespaceMaybe}HashEntry* entry = ${className}Table.entry(exec, propertyName);\n");
506             push(@getOwnPropertyDescriptorImpl, "    if (entry) {\n");
507             push(@getOwnPropertyDescriptorImpl, "        PropertySlot slot;\n");
508             push(@getOwnPropertyDescriptorImpl, "        slot.setCustom(thisObject, entry->propertyGetter());\n");
509             push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(slot.getValue(exec, propertyName), entry->attributes());\n");
510             push(@getOwnPropertyDescriptorImpl, "        return true;\n");
511             push(@getOwnPropertyDescriptorImpl, "    }\n");
512         }
513     };
514
515     if (!$dataNode->extendedAttributes->{"CustomNamedGetter"}) {
516         &$manualLookupGetterGeneration();
517     }
518
519     if ($dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
520         push(@getOwnPropertyDescriptorImpl, "    unsigned index = propertyName.asIndex();\n");
521         push(@getOwnPropertyDescriptorImpl, "    if (index != PropertyName::NotAnIndex && index < static_cast<$implClassName*>(thisObject->impl())->length()) {\n");
522         if ($dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
523             # Assume that if there's a setter, the index will be writable
524             if ($dataNode->extendedAttributes->{"CustomIndexedSetter"}) {
525                 push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(thisObject->getByIndex(exec, index), ${namespaceMaybe}DontDelete);\n");
526             } else {
527                 push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(thisObject->getByIndex(exec, index), ${namespaceMaybe}DontDelete | ${namespaceMaybe}ReadOnly);\n");
528             }
529         } else {
530             push(@getOwnPropertyDescriptorImpl, "        ${namespaceMaybe}PropertySlot slot;\n");
531             push(@getOwnPropertyDescriptorImpl, "        slot.setCustomIndex(thisObject, index, indexGetter);\n");
532             # Assume that if there's a setter, the index will be writable
533             if ($dataNode->extendedAttributes->{"CustomIndexedSetter"}) {
534                 push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(slot.getValue(exec, propertyName), ${namespaceMaybe}DontDelete);\n");
535             } else {
536                 push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(slot.getValue(exec, propertyName), ${namespaceMaybe}DontDelete | ${namespaceMaybe}ReadOnly);\n");
537             }
538         }
539         push(@getOwnPropertyDescriptorImpl, "        return true;\n");
540         push(@getOwnPropertyDescriptorImpl, "    }\n");
541     }
542
543     if ($dataNode->extendedAttributes->{"NamedGetter"} || $dataNode->extendedAttributes->{"CustomNamedGetter"}) {
544         push(@getOwnPropertyDescriptorImpl, "    if (canGetItemsForName(exec, static_cast<$implClassName*>(thisObject->impl()), propertyName)) {\n");
545         push(@getOwnPropertyDescriptorImpl, "        ${namespaceMaybe}PropertySlot slot;\n");
546         push(@getOwnPropertyDescriptorImpl, "        slot.setCustom(thisObject, nameGetter);\n");
547         push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(slot.getValue(exec, propertyName), ReadOnly | DontDelete | DontEnum);\n");
548         push(@getOwnPropertyDescriptorImpl, "        return true;\n");
549         push(@getOwnPropertyDescriptorImpl, "    }\n");
550         if ($inlined) {
551             $headerIncludes{"wtf/text/AtomicString.h"} = 1;
552         } else {
553             $implIncludes{"wtf/text/AtomicString.h"} = 1;
554         }
555     }
556
557     if ($dataNode->extendedAttributes->{"CustomNamedGetter"}) {
558         &$manualLookupGetterGeneration();
559     }
560
561     if ($dataNode->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}) {
562         push(@getOwnPropertyDescriptorImpl, "    if (thisObject->getOwnPropertyDescriptorDelegate(exec, propertyName, descriptor))\n");
563         push(@getOwnPropertyDescriptorImpl, "        return true;\n");
564     }
565
566     if ($hasAttributes) {
567         if ($inlined) {
568             die "Cannot inline if NoStaticTables is set." if ($dataNode->extendedAttributes->{"JSNoStaticTables"});
569             push(@getOwnPropertyDescriptorImpl, "    return ${namespaceMaybe}getStaticValueDescriptor<$className, Base>(exec, s_info.staticPropHashTable, thisObject, propertyName, descriptor);\n");
570         } else {
571             push(@getOwnPropertyDescriptorImpl, "    return ${namespaceMaybe}getStaticValueDescriptor<$className, Base>(exec, " . hashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, descriptor);\n");
572         }
573     } else {
574         push(@getOwnPropertyDescriptorImpl, "    return Base::getOwnPropertyDescriptor(thisObject, exec, propertyName, descriptor);\n");
575     }
576     
577     return @getOwnPropertyDescriptorImpl;
578 }
579
580 sub GenerateHeaderContentHeader
581 {
582     my $dataNode = shift;
583     my $className = "JS" . $dataNode->name;
584
585     my @headerContentHeader = split("\r", $headerTemplate);
586
587     # - Add header protection
588     push(@headerContentHeader, "\n#ifndef $className" . "_h");
589     push(@headerContentHeader, "\n#define $className" . "_h\n\n");
590
591     my $conditionalString = $codeGenerator->GenerateConditionalString($dataNode);
592     push(@headerContentHeader, "#if ${conditionalString}\n\n") if $conditionalString;
593     return @headerContentHeader;
594 }
595
596 sub GenerateImplementationContentHeader
597 {
598     my $dataNode = shift;
599     my $className = "JS" . $dataNode->name;
600
601     my @implContentHeader = split("\r", $headerTemplate);
602
603     push(@implContentHeader, "\n#include \"config.h\"\n");
604     my $conditionalString = $codeGenerator->GenerateConditionalString($dataNode);
605     push(@implContentHeader, "\n#if ${conditionalString}\n\n") if $conditionalString;
606     push(@implContentHeader, "#include \"$className.h\"\n\n");
607     return @implContentHeader;
608 }
609
610 my %usesToJSNewlyCreated = (
611     "CDATASection" => 1,
612     "Element" => 1,
613     "Node" => 1,
614     "Text" => 1,
615     "Touch" => 1,
616     "TouchList" => 1
617 );
618
619 sub ShouldGenerateToJSDeclaration
620 {
621     my ($hasParent, $dataNode) = @_;
622     return 0 if ($dataNode->extendedAttributes->{"SuppressToJSObject"});
623     return 1 if (!$hasParent or $dataNode->extendedAttributes->{"JSGenerateToJSObject"} or ($dataNode->extendedAttributes->{"CustomToJSObject"} or $dataNode->extendedAttributes->{"JSCustomToJSObject"}));
624     return 0;
625 }
626
627 sub ShouldGenerateToJSImplementation
628 {
629     my ($hasParent, $dataNode) = @_;
630     return 0 if ($dataNode->extendedAttributes->{"SuppressToJSObject"});
631     return 1 if ((!$hasParent or $dataNode->extendedAttributes->{"JSGenerateToJSObject"}) and !($dataNode->extendedAttributes->{"CustomToJSObject"} or $dataNode->extendedAttributes->{"JSCustomToJSObject"}));
632     return 0;
633 }
634
635 sub GetAttributeGetterName
636 {
637     my ($interfaceName, $className, $attribute) = @_;
638     if ($attribute->isStatic) {
639         return $codeGenerator->WK_lcfirst($className) . "Constructor" . $codeGenerator->WK_ucfirst($attribute->signature->name);
640     }
641     return "js" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "");
642 }
643
644 sub GetAttributeSetterName
645 {
646     my ($interfaceName, $className, $attribute) = @_;
647     if ($attribute->isStatic) {
648         return "set" . $codeGenerator->WK_ucfirst($className) . "Constructor" . $codeGenerator->WK_ucfirst($attribute->signature->name);
649     }
650     return "setJS" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "");
651 }
652
653 sub GetFunctionName
654 {
655     my ($className, $function) = @_;
656     my $kind = $function->isStatic ? "Constructor" : "Prototype";
657     return $codeGenerator->WK_lcfirst($className) . $kind . "Function" . $codeGenerator->WK_ucfirst($function->signature->name);
658 }
659
660 sub GenerateHeader
661 {
662     my $object = shift;
663     my $dataNode = shift;
664
665     my $interfaceName = $dataNode->name;
666     my $className = "JS$interfaceName";
667     my $implClassName = $interfaceName;
668     my @ancestorInterfaceNames = ();
669     my %structureFlags = ();
670
671     # We only support multiple parents with SVG (for now).
672     if (@{$dataNode->parents} > 1) {
673         die "A class can't have more than one parent" unless $interfaceName =~ /SVG/;
674         $codeGenerator->AddMethodsConstantsAndAttributesFromParentClasses($dataNode, \@ancestorInterfaceNames);
675     }
676
677     my $hasLegacyParent = $dataNode->extendedAttributes->{"JSLegacyParent"};
678     my $hasRealParent = @{$dataNode->parents} > 0;
679     my $hasParent = $hasLegacyParent || $hasRealParent;
680     my $parentClassName = GetParentClassName($dataNode);
681     my $eventTarget = $dataNode->extendedAttributes->{"EventTarget"};
682     my $needsMarkChildren = $dataNode->extendedAttributes->{"JSCustomMarkFunction"} || $dataNode->extendedAttributes->{"EventTarget"};
683
684     # - Add default header template and header protection
685     push(@headerContentHeader, GenerateHeaderContentHeader($dataNode));
686
687     if ($hasParent) {
688         $headerIncludes{"$parentClassName.h"} = 1;
689     } else {
690         $headerIncludes{"JSDOMBinding.h"} = 1;
691         $headerIncludes{"<runtime/JSGlobalObject.h>"} = 1;
692         if ($dataNode->isException) {
693             $headerIncludes{"<runtime/ErrorPrototype.h>"} = 1;
694         } else {
695             $headerIncludes{"<runtime/ObjectPrototype.h>"} = 1;
696         }
697     }
698
699     if ($dataNode->extendedAttributes->{"CustomCall"}) {
700         $headerIncludes{"<runtime/CallData.h>"} = 1;
701     }
702
703     if ($dataNode->extendedAttributes->{"JSInlineGetOwnPropertySlot"}) {
704         $headerIncludes{"<runtime/Lookup.h>"} = 1;
705         $headerIncludes{"<wtf/AlwaysInline.h>"} = 1;
706     }
707
708     if ($hasParent && $dataNode->extendedAttributes->{"JSGenerateToNativeObject"}) {
709         if (IsTypedArrayType($implClassName)) {
710             $headerIncludes{"<wtf/$implClassName.h>"} = 1;
711         } else {
712             $headerIncludes{"$implClassName.h"} = 1;
713         }
714     }
715     
716     $headerIncludes{"<runtime/JSObject.h>"} = 1;
717     $headerIncludes{"SVGElement.h"} = 1 if $className =~ /^JSSVG/;
718
719     my $implType = $implClassName;
720     my ($svgPropertyType, $svgListPropertyType, $svgNativeType) = GetSVGPropertyTypes($implType);
721     $implType = $svgNativeType if $svgNativeType;
722
723     my $svgPropertyOrListPropertyType;
724     $svgPropertyOrListPropertyType = $svgPropertyType if $svgPropertyType;
725     $svgPropertyOrListPropertyType = $svgListPropertyType if $svgListPropertyType;
726
727     my $numConstants = @{$dataNode->constants};
728     my $numAttributes = @{$dataNode->attributes};
729     my $numFunctions = @{$dataNode->functions};
730
731     push(@headerContent, "\nnamespace WebCore {\n\n");
732
733     if ($codeGenerator->IsSVGAnimatedType($implClassName)) {
734         $headerIncludes{"$implClassName.h"} = 1;
735     } else {
736         # Implementation class forward declaration
737         if ($interfaceName eq "DOMWindow" || $dataNode->extendedAttributes->{"IsWorkerContext"}) {
738             AddClassForwardIfNeeded($implClassName) unless $svgPropertyOrListPropertyType;
739         }
740     }
741
742     AddClassForwardIfNeeded("JSDOMWindowShell") if $interfaceName eq "DOMWindow";
743     AddClassForwardIfNeeded("JSDictionary") if IsConstructorTemplate($dataNode, "Event");
744
745     # Class declaration
746     push(@headerContent, "class $className : public $parentClassName {\n");
747
748     # Static create methods
749     push(@headerContent, "public:\n");
750     push(@headerContent, "    typedef $parentClassName Base;\n");
751     if ($interfaceName eq "DOMWindow") {
752         push(@headerContent, "    static $className* create(JSC::JSGlobalData& globalData, JSC::Structure* structure, PassRefPtr<$implType> impl, JSDOMWindowShell* windowShell)\n");
753         push(@headerContent, "    {\n");
754         push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalData.heap)) ${className}(globalData, structure, impl, windowShell);\n");
755         push(@headerContent, "        ptr->finishCreation(globalData, windowShell);\n");
756         push(@headerContent, "        return ptr;\n");
757         push(@headerContent, "    }\n\n");
758     } elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
759         push(@headerContent, "    static $className* create(JSC::JSGlobalData& globalData, JSC::Structure* structure, PassRefPtr<$implType> impl)\n");
760         push(@headerContent, "    {\n");
761         push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalData.heap)) ${className}(globalData, structure, impl);\n");
762         push(@headerContent, "        ptr->finishCreation(globalData);\n");
763         push(@headerContent, "        return ptr;\n");
764         push(@headerContent, "    }\n\n");
765     } else {
766         AddIncludesForTypeInHeader($implType) unless $svgPropertyOrListPropertyType;
767         push(@headerContent, "    static $className* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<$implType> impl)\n");
768         push(@headerContent, "    {\n");
769         push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalObject->globalData().heap)) $className(structure, globalObject, impl);\n");
770         push(@headerContent, "        ptr->finishCreation(globalObject->globalData());\n");
771         push(@headerContent, "        return ptr;\n");
772         push(@headerContent, "    }\n\n");
773     }
774
775     # Prototype
776     push(@headerContent, "    static JSC::JSObject* createPrototype(JSC::ExecState*, JSC::JSGlobalObject*);\n") unless ($dataNode->extendedAttributes->{"ExtendsDOMGlobalObject"});
777
778     $headerTrailingIncludes{"${className}Custom.h"} = 1 if $dataNode->extendedAttributes->{"JSCustomHeader"};
779
780     $implIncludes{"${className}Custom.h"} = 1 if !$dataNode->extendedAttributes->{"JSCustomHeader"} && ($dataNode->extendedAttributes->{"CustomPutFunction"} || $dataNode->extendedAttributes->{"CustomNamedSetter"});
781
782     my $hasGetter = $numAttributes > 0
783                  || !$dataNode->extendedAttributes->{"OmitConstructor"}
784                  || $dataNode->extendedAttributes->{"IndexedGetter"}
785                  || $dataNode->extendedAttributes->{"NumericIndexedGetter"}
786                  || $dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}
787                  || $dataNode->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}
788                  || $dataNode->extendedAttributes->{"NamedGetter"}
789                  || $dataNode->extendedAttributes->{"CustomNamedGetter"};
790
791     # Getters
792     if ($hasGetter) {
793         push(@headerContent, "    static bool getOwnPropertySlot(JSC::JSCell*, JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&);\n");
794         push(@headerContent, "    static bool getOwnPropertyDescriptor(JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, JSC::PropertyDescriptor&);\n");
795         push(@headerContent, "    static bool getOwnPropertySlotByIndex(JSC::JSCell*, JSC::ExecState*, unsigned propertyName, JSC::PropertySlot&);\n") if ($dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"}) && !$dataNode->extendedAttributes->{"CustomNamedGetter"};
796         push(@headerContent, "    bool getOwnPropertySlotDelegate(JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&);\n") if $dataNode->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"};
797         push(@headerContent, "    bool getOwnPropertyDescriptorDelegate(JSC::ExecState*, JSC::PropertyName, JSC::PropertyDescriptor&);\n") if $dataNode->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"};
798         $structureFlags{"JSC::OverridesGetOwnPropertySlot"} = 1;
799     }
800
801     # Check if we have any writable properties
802     my $hasReadWriteProperties = 0;
803     foreach (@{$dataNode->attributes}) {
804         if ($_->type !~ /^readonly\ attribute$/ && !$_->isStatic) {
805             $hasReadWriteProperties = 1;
806         }
807     }
808
809     my $hasSetter = $hasReadWriteProperties
810                  || $dataNode->extendedAttributes->{"CustomPutFunction"}
811                  || $dataNode->extendedAttributes->{"CustomNamedSetter"}
812                  || $dataNode->extendedAttributes->{"CustomIndexedSetter"};
813
814     # Getters
815     if ($hasSetter) {
816         push(@headerContent, "    static void put(JSC::JSCell*, JSC::ExecState*, JSC::PropertyName, JSC::JSValue, JSC::PutPropertySlot&);\n");
817         push(@headerContent, "    static void putByIndex(JSC::JSCell*, JSC::ExecState*, unsigned propertyName, JSC::JSValue, bool shouldThrow);\n") if $dataNode->extendedAttributes->{"CustomIndexedSetter"};
818         push(@headerContent, "    bool putDelegate(JSC::ExecState*, JSC::PropertyName, JSC::JSValue, JSC::PutPropertySlot&);\n") if $dataNode->extendedAttributes->{"CustomNamedSetter"};
819     }
820
821     if (!$hasParent) {
822         push(@headerContent, "    static void destroy(JSC::JSCell*);\n");
823         push(@headerContent, "    ~${className}();\n");
824     }
825
826     # Class info
827     if ($interfaceName eq "Node") {
828         push(@headerContent, "    static WEBKIT_EXPORTDATA const JSC::ClassInfo s_info;\n\n");
829     } else {
830         push(@headerContent, "    static const JSC::ClassInfo s_info;\n\n");
831     }
832     # Structure ID
833     if ($interfaceName eq "DOMWindow") {
834         $structureFlags{"JSC::ImplementsHasInstance"} = 1;
835     }
836     push(@headerContent, "    static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)\n");
837     push(@headerContent, "    {\n");
838     if ($interfaceName eq "DOMWindow" || $dataNode->extendedAttributes->{"IsWorkerContext"}) {
839         push(@headerContent, "        return JSC::Structure::create(globalData, globalObject, prototype, JSC::TypeInfo(JSC::GlobalObjectType, StructureFlags), &s_info);\n");
840     } else {
841         push(@headerContent, "        return JSC::Structure::create(globalData, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), &s_info);\n");
842     }
843     push(@headerContent, "    }\n\n");
844
845     # Custom pushEventHandlerScope function
846     push(@headerContent, "    JSC::ScopeChainNode* pushEventHandlerScope(JSC::ExecState*, JSC::ScopeChainNode*) const;\n\n") if $dataNode->extendedAttributes->{"JSCustomPushEventHandlerScope"};
847
848     # Custom call functions
849     push(@headerContent, "    static JSC::CallType getCallData(JSC::JSCell*, JSC::CallData&);\n\n") if $dataNode->extendedAttributes->{"CustomCall"};
850
851     # Custom deleteProperty function
852     push(@headerContent, "    static bool deleteProperty(JSC::JSCell*, JSC::ExecState*, JSC::PropertyName);\n") if $dataNode->extendedAttributes->{"CustomDeleteProperty"};
853
854     # Custom getPropertyNames function exists on DOMWindow
855     if ($interfaceName eq "DOMWindow") {
856         push(@headerContent, "    static void getPropertyNames(JSC::JSObject*, JSC::ExecState*, JSC::PropertyNameArray&, JSC::EnumerationMode mode = JSC::ExcludeDontEnumProperties);\n");
857         $structureFlags{"JSC::OverridesGetPropertyNames"} = 1;
858     }
859
860     # Custom getOwnPropertyNames function
861     if ($dataNode->extendedAttributes->{"CustomEnumerateProperty"} || $dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
862         push(@headerContent, "    static void getOwnPropertyNames(JSC::JSObject*, JSC::ExecState*, JSC::PropertyNameArray&, JSC::EnumerationMode mode = JSC::ExcludeDontEnumProperties);\n");
863         $structureFlags{"JSC::OverridesGetPropertyNames"} = 1;       
864     }
865
866     # Custom defineOwnProperty function
867     push(@headerContent, "    static bool defineOwnProperty(JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, JSC::PropertyDescriptor&, bool shouldThrow);\n") if $dataNode->extendedAttributes->{"JSCustomDefineOwnProperty"};
868
869     # Override toBoolean to return false for objects that want to 'MasqueradesAsUndefined'.
870     if ($dataNode->extendedAttributes->{"MasqueradesAsUndefined"}) {
871         $structureFlags{"JSC::MasqueradesAsUndefined"} = 1;
872     }
873
874     # Constructor object getter
875     push(@headerContent, "    static JSC::JSValue getConstructor(JSC::ExecState*, JSC::JSGlobalObject*);\n") if !$dataNode->extendedAttributes->{"OmitConstructor"};
876
877     my $numCustomFunctions = 0;
878     my $numCustomAttributes = 0;
879
880     # Attribute and function enums
881     if ($numAttributes > 0) {
882         foreach (@{$dataNode->attributes}) {
883             my $attribute = $_;
884             $numCustomAttributes++ if $attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCustom"};
885             $numCustomAttributes++ if ($attribute->signature->extendedAttributes->{"CustomGetter"} || $attribute->signature->extendedAttributes->{"JSCustomGetter"});
886             $numCustomAttributes++ if ($attribute->signature->extendedAttributes->{"CustomSetter"} || $attribute->signature->extendedAttributes->{"JSCustomSetter"});
887             if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) {
888                 my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
889                 push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
890                 push(@headerContent, "    JSC::WriteBarrier<JSC::Unknown> m_" . $attribute->signature->name . ";\n");
891                 $numCachedAttributes++;
892                 $needsMarkChildren = 1;
893                 push(@headerContent, "#endif\n") if $conditionalString;
894             }
895         }
896     }
897
898     # visit function
899     if ($needsMarkChildren) {
900         push(@headerContent, "    static void visitChildren(JSCell*, JSC::SlotVisitor&);\n\n");
901         $structureFlags{"JSC::OverridesVisitChildren"} = 1;
902     }
903
904     if ($numCustomAttributes > 0) {
905         push(@headerContent, "\n    // Custom attributes\n");
906
907         foreach my $attribute (@{$dataNode->attributes}) {
908             my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
909             if ($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCustom"} || $attribute->signature->extendedAttributes->{"CustomGetter"} || $attribute->signature->extendedAttributes->{"JSCustomGetter"}) {
910                 push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
911                 my $methodName = $codeGenerator->WK_lcfirst($attribute->signature->name);
912                 push(@headerContent, "    JSC::JSValue " . $methodName . "(JSC::ExecState*) const;\n");
913                 push(@headerContent, "#endif\n") if $conditionalString;
914             }
915             if (($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCustom"} || $attribute->signature->extendedAttributes->{"CustomSetter"} || $attribute->signature->extendedAttributes->{"JSCustomSetter"}) && $attribute->type !~ /^readonly/) {
916                 push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
917                 push(@headerContent, "    void set" . $codeGenerator->WK_ucfirst($attribute->signature->name) . "(JSC::ExecState*, JSC::JSValue);\n");
918                 push(@headerContent, "#endif\n") if $conditionalString;
919             }
920         }
921     }
922
923     foreach my $function (@{$dataNode->functions}) {
924         $numCustomFunctions++ if $function->signature->extendedAttributes->{"Custom"} || $function->signature->extendedAttributes->{"JSCustom"};
925     }
926
927     if ($numCustomFunctions > 0) {
928         push(@headerContent, "\n    // Custom functions\n");
929         foreach my $function (@{$dataNode->functions}) {
930             next unless $function->signature->extendedAttributes->{"Custom"} or $function->signature->extendedAttributes->{"JSCustom"};
931             next if $function->{overloads} && $function->{overloadIndex} != 1;
932             my $conditionalString = $codeGenerator->GenerateConditionalString($function->signature);
933             push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
934             my $functionImplementationName = $function->signature->extendedAttributes->{"ImplementedAs"} || $codeGenerator->WK_lcfirst($function->signature->name);
935             push(@headerContent, "    " . ($function->isStatic ? "static " : "") . "JSC::JSValue " . $functionImplementationName . "(JSC::ExecState*);\n");
936             push(@headerContent, "#endif\n") if $conditionalString;
937         }
938     }
939
940     if (!$hasParent) {
941         push(@headerContent, "    $implType* impl() const { return m_impl; }\n");
942         push(@headerContent, "    void releaseImpl() { m_impl->deref(); m_impl = 0; }\n\n");
943         push(@headerContent, "    void releaseImplIfNotNull() { if (m_impl) { m_impl->deref(); m_impl = 0; } }\n\n");
944         push(@headerContent, "private:\n");
945         push(@headerContent, "    $implType* m_impl;\n");
946     } elsif ($dataNode->extendedAttributes->{"JSGenerateToNativeObject"}) {
947         push(@headerContent, "    $implClassName* impl() const\n");
948         push(@headerContent, "    {\n");
949         push(@headerContent, "        return static_cast<$implClassName*>(Base::impl());\n");
950         push(@headerContent, "    }\n");
951     }
952
953     if (IsTypedArrayType($implType) and ($implType ne "ArrayBufferView") and ($implType ne "ArrayBuffer")) {
954         push(@headerContent, "    static const JSC::TypedArrayType TypedArrayStorageType = JSC::");
955         push(@headerContent, "TypedArrayInt8") if $implType eq "Int8Array";
956         push(@headerContent, "TypedArrayInt16") if $implType eq "Int16Array";
957         push(@headerContent, "TypedArrayInt32") if $implType eq "Int32Array";
958         push(@headerContent, "TypedArrayUint8") if $implType eq "Uint8Array";
959         push(@headerContent, "TypedArrayUint8Clamped") if $implType eq "Uint8ClampedArray";
960         push(@headerContent, "TypedArrayUint16") if $implType eq "Uint16Array";
961         push(@headerContent, "TypedArrayUint32") if $implType eq "Uint32Array";
962         push(@headerContent, "TypedArrayFloat32") if $implType eq "Float32Array";
963         push(@headerContent, "TypedArrayFloat64") if $implType eq "Float64Array";
964         push(@headerContent, ";\n");
965         push(@headerContent, "    intptr_t m_storageLength;\n");
966         push(@headerContent, "    void* m_storage;\n");
967     }
968
969     push(@headerContent, "protected:\n");
970     # Constructor
971     if ($interfaceName eq "DOMWindow") {
972         push(@headerContent, "    $className(JSC::JSGlobalData&, JSC::Structure*, PassRefPtr<$implType>, JSDOMWindowShell*);\n");
973     } elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
974         push(@headerContent, "    $className(JSC::JSGlobalData&, JSC::Structure*, PassRefPtr<$implType>);\n");
975     } else {
976         push(@headerContent, "    $className(JSC::Structure*, JSDOMGlobalObject*, PassRefPtr<$implType>);\n");
977         push(@headerContent, "    void finishCreation(JSC::JSGlobalData&);\n");
978     }
979
980     # structure flags
981     push(@headerContent, "    static const unsigned StructureFlags = ");
982     foreach my $structureFlag (keys %structureFlags) {
983         push(@headerContent, $structureFlag . " | ");
984     }
985     push(@headerContent, "Base::StructureFlags;\n");
986
987     # Index getter
988     if ($dataNode->extendedAttributes->{"IndexedGetter"}) {
989         push(@headerContent, "    static JSC::JSValue indexGetter(JSC::ExecState*, JSC::JSValue, unsigned);\n");
990     }
991     if ($dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
992         push(@headerContent, "    JSC::JSValue getByIndex(JSC::ExecState*, unsigned index);\n");
993     }
994
995     # Index setter
996     if ($dataNode->extendedAttributes->{"CustomIndexedSetter"}) {
997         push(@headerContent, "    void indexSetter(JSC::ExecState*, unsigned index, JSC::JSValue);\n");
998     }
999     # Name getter
1000     if ($dataNode->extendedAttributes->{"NamedGetter"} || $dataNode->extendedAttributes->{"CustomNamedGetter"}) {
1001         push(@headerContent, "private:\n");
1002         push(@headerContent, "    static bool canGetItemsForName(JSC::ExecState*, $implClassName*, JSC::PropertyName);\n");
1003         push(@headerContent, "    static JSC::JSValue nameGetter(JSC::ExecState*, JSC::JSValue, JSC::PropertyName);\n");
1004     }
1005
1006     push(@headerContent, "};\n\n");
1007
1008     if ($dataNode->extendedAttributes->{"JSInlineGetOwnPropertySlot"} && !$dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}) {
1009         push(@headerContent, "ALWAYS_INLINE bool ${className}::getOwnPropertySlot(JSC::JSCell* cell, JSC::ExecState* exec, JSC::PropertyName propertyName, JSC::PropertySlot& slot)\n");
1010         push(@headerContent, "{\n");
1011         push(@headerContent, "    ${className}* thisObject = JSC::jsCast<${className}*>(cell);\n");
1012         push(@headerContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
1013         push(@headerContent, GenerateGetOwnPropertySlotBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 1));
1014         push(@headerContent, "}\n\n");
1015         push(@headerContent, "ALWAYS_INLINE bool ${className}::getOwnPropertyDescriptor(JSC::JSObject* object, JSC::ExecState* exec, JSC::PropertyName propertyName, JSC::PropertyDescriptor& descriptor)\n");
1016         push(@headerContent, "{\n");
1017         push(@headerContent, "    ${className}* thisObject = JSC::jsCast<${className}*>(object);\n");
1018         push(@headerContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
1019         push(@headerContent, GenerateGetOwnPropertyDescriptorBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 1));
1020         push(@headerContent, "}\n\n");
1021     }
1022
1023     if (!$hasParent ||
1024         GetGenerateIsReachable($dataNode) ||
1025         GetCustomIsReachable($dataNode) ||
1026         $dataNode->extendedAttributes->{"JSCustomFinalize"} ||
1027         $dataNode->extendedAttributes->{"ActiveDOMObject"}) {
1028         push(@headerContent, "class JS${implClassName}Owner : public JSC::WeakHandleOwner {\n");
1029         push(@headerContent, "    virtual bool isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown>, void* context, JSC::SlotVisitor&);\n");
1030         push(@headerContent, "    virtual void finalize(JSC::Handle<JSC::Unknown>, void* context);\n");
1031         push(@headerContent, "};\n");
1032         push(@headerContent, "\n");
1033         push(@headerContent, "inline JSC::WeakHandleOwner* wrapperOwner(DOMWrapperWorld*, $implType*)\n");
1034         push(@headerContent, "{\n");
1035         push(@headerContent, "    DEFINE_STATIC_LOCAL(JS${implClassName}Owner, js${implClassName}Owner, ());\n");
1036         push(@headerContent, "    return &js${implClassName}Owner;\n");
1037         push(@headerContent, "}\n");
1038         push(@headerContent, "\n");
1039         push(@headerContent, "inline void* wrapperContext(DOMWrapperWorld* world, $implType*)\n");
1040         push(@headerContent, "{\n");
1041         push(@headerContent, "    return world;\n");
1042         push(@headerContent, "}\n");
1043         push(@headerContent, "\n");
1044     }
1045     if (ShouldGenerateToJSDeclaration($hasParent, $dataNode)) {
1046         push(@headerContent, "JSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject*, $implType*);\n");
1047     }
1048     if (!$hasParent || $dataNode->extendedAttributes->{"JSGenerateToNativeObject"}) {
1049         if ($interfaceName eq "NodeFilter") {
1050             push(@headerContent, "PassRefPtr<NodeFilter> toNodeFilter(JSC::JSGlobalData&, JSC::JSValue);\n");
1051         } elsif ($interfaceName eq "DOMStringList") {
1052             push(@headerContent, "PassRefPtr<DOMStringList> toDOMStringList(JSC::ExecState*, JSC::JSValue);\n");
1053         } else {
1054             push(@headerContent, "$implType* to${interfaceName}(JSC::JSValue);\n");
1055         }
1056     }
1057     if ($usesToJSNewlyCreated{$interfaceName}) {
1058         push(@headerContent, "JSC::JSValue toJSNewlyCreated(JSC::ExecState*, JSDOMGlobalObject*, $interfaceName*);\n");
1059     }
1060     
1061     push(@headerContent, "\n");
1062
1063     # Add prototype declaration.
1064     %structureFlags = ();
1065     push(@headerContent, "class ${className}Prototype : public JSC::JSNonFinalObject {\n");
1066     push(@headerContent, "public:\n");
1067     push(@headerContent, "    typedef JSC::JSNonFinalObject Base;\n");
1068     if ($interfaceName ne "DOMWindow" && !$dataNode->extendedAttributes->{"IsWorkerContext"}) {
1069         push(@headerContent, "    static JSC::JSObject* self(JSC::ExecState*, JSC::JSGlobalObject*);\n");
1070     }
1071
1072     push(@headerContent, "    static ${className}Prototype* create(JSC::JSGlobalData& globalData, JSC::JSGlobalObject* globalObject, JSC::Structure* structure)\n");
1073     push(@headerContent, "    {\n");
1074     push(@headerContent, "        ${className}Prototype* ptr = new (NotNull, JSC::allocateCell<${className}Prototype>(globalData.heap)) ${className}Prototype(globalData, globalObject, structure);\n");
1075     push(@headerContent, "        ptr->finishCreation(globalData);\n");
1076     push(@headerContent, "        return ptr;\n");
1077     push(@headerContent, "    }\n\n");
1078
1079     push(@headerContent, "    static const JSC::ClassInfo s_info;\n");
1080     if ($numFunctions > 0 || $numConstants > 0) {
1081         push(@headerContent, "    static bool getOwnPropertySlot(JSC::JSCell*, JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&);\n");
1082         push(@headerContent, "    static bool getOwnPropertyDescriptor(JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, JSC::PropertyDescriptor&);\n");
1083         $structureFlags{"JSC::OverridesGetOwnPropertySlot"} = 1;
1084     }
1085     if ($dataNode->extendedAttributes->{"JSCustomMarkFunction"} or $needsMarkChildren) {
1086         $structureFlags{"JSC::OverridesVisitChildren"} = 1;
1087     }
1088     push(@headerContent,
1089         "    static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)\n" .
1090         "    {\n" .
1091         "        return JSC::Structure::create(globalData, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), &s_info);\n" .
1092         "    }\n");
1093     if ($dataNode->extendedAttributes->{"JSCustomNamedGetterOnPrototype"}) {
1094         push(@headerContent, "    static void put(JSC::JSCell*, JSC::ExecState*, JSC::PropertyName, JSC::JSValue, JSC::PutPropertySlot&);\n");
1095         push(@headerContent, "    bool putDelegate(JSC::ExecState*, JSC::PropertyName, JSC::JSValue, JSC::PutPropertySlot&);\n");
1096     }
1097
1098     # Custom defineOwnProperty function
1099     push(@headerContent, "    static bool defineOwnProperty(JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, JSC::PropertyDescriptor&, bool shouldThrow);\n") if $dataNode->extendedAttributes->{"JSCustomDefineOwnPropertyOnPrototype"};
1100
1101     push(@headerContent, "\nprivate:\n");
1102     push(@headerContent, "    ${className}Prototype(JSC::JSGlobalData& globalData, JSC::JSGlobalObject*, JSC::Structure* structure) : JSC::JSNonFinalObject(globalData, structure) { }\n");
1103
1104     # structure flags
1105     push(@headerContent, "protected:\n");
1106     push(@headerContent, "    static const unsigned StructureFlags = ");
1107     foreach my $structureFlag (keys %structureFlags) {
1108         push(@headerContent, $structureFlag . " | ");
1109     }
1110     push(@headerContent, "Base::StructureFlags;\n");
1111
1112     push(@headerContent, "};\n\n");
1113
1114     if (!$dataNode->extendedAttributes->{"OmitConstructor"}) {
1115         $headerIncludes{"JSDOMBinding.h"} = 1;
1116         GenerateConstructorDeclaration(\@headerContent, $className, $dataNode, $interfaceName);
1117     }
1118
1119     if ($numFunctions > 0) {
1120         push(@headerContent,"// Functions\n\n");
1121         foreach my $function (@{$dataNode->functions}) {
1122             next if $function->{overloadIndex} && $function->{overloadIndex} > 1;
1123             my $conditionalString = $codeGenerator->GenerateConditionalString($function->signature);
1124             push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
1125             my $functionName = GetFunctionName($className, $function);
1126             push(@headerContent, "JSC::EncodedJSValue JSC_HOST_CALL ${functionName}(JSC::ExecState*);\n");
1127             push(@headerContent, "#endif\n") if $conditionalString;
1128         }
1129     }
1130
1131     if ($numAttributes > 0 || !$dataNode->extendedAttributes->{"OmitConstructor"}) {
1132         push(@headerContent,"// Attributes\n\n");
1133         foreach my $attribute (@{$dataNode->attributes}) {
1134             my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
1135             push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
1136             my $getter = GetAttributeGetterName($interfaceName, $className, $attribute);
1137             push(@headerContent, "JSC::JSValue ${getter}(JSC::ExecState*, JSC::JSValue, JSC::PropertyName);\n");
1138             unless ($attribute->type =~ /readonly/) {
1139                 my $setter = GetAttributeSetterName($interfaceName, $className, $attribute);
1140                 push(@headerContent, "void ${setter}(JSC::ExecState*, JSC::JSObject*, JSC::JSValue);\n");
1141             }
1142             push(@headerContent, "#endif\n") if $conditionalString;
1143         }
1144         
1145         if (!$dataNode->extendedAttributes->{"OmitConstructor"}) {
1146             my $getter = "js" . $interfaceName . "Constructor";
1147             push(@headerContent, "JSC::JSValue ${getter}(JSC::ExecState*, JSC::JSValue, JSC::PropertyName);\n");
1148         }
1149
1150         if ($dataNode->extendedAttributes->{"ReplaceableConstructor"}) {
1151             my $constructorFunctionName = "setJS" . $interfaceName . "Constructor";
1152             push(@headerContent, "void ${constructorFunctionName}(JSC::ExecState*, JSC::JSObject*, JSC::JSValue);\n");
1153         }
1154     }
1155
1156     if ($numConstants > 0) {
1157         push(@headerContent,"// Constants\n\n");
1158         foreach my $constant (@{$dataNode->constants}) {
1159             my $conditionalString = $codeGenerator->GenerateConditionalString($constant);
1160             push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
1161             my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($constant->name);
1162             push(@headerContent, "JSC::JSValue ${getter}(JSC::ExecState*, JSC::JSValue, JSC::PropertyName);\n");
1163             push(@headerContent, "#endif\n") if $conditionalString;
1164         }
1165     }
1166
1167     my $conditionalString = $codeGenerator->GenerateConditionalString($dataNode);
1168     push(@headerContent, "\n} // namespace WebCore\n\n");
1169     push(@headerContent, "#endif // ${conditionalString}\n\n") if $conditionalString;
1170     push(@headerContent, "#endif\n");
1171
1172     # - Generate dependencies.
1173     if ($writeDependencies && @ancestorInterfaceNames) {
1174         push(@depsContent, "$className.h : ", join(" ", map { "$_.idl" } @ancestorInterfaceNames), "\n");
1175         push(@depsContent, map { "$_.idl :\n" } @ancestorInterfaceNames); 
1176     }
1177 }
1178
1179 sub GenerateAttributesHashTable($$)
1180 {
1181     my ($object, $dataNode) = @_;
1182
1183     # FIXME: These should be functions on $dataNode.
1184     my $interfaceName = $dataNode->name;
1185     my $className = "JS$interfaceName";
1186     
1187     # - Add all attributes in a hashtable definition
1188     my $numAttributes = @{$dataNode->attributes};
1189     $numAttributes++ if !$dataNode->extendedAttributes->{"OmitConstructor"};
1190
1191     return 0  if !$numAttributes;
1192
1193     my $hashSize = $numAttributes;
1194     my $hashName = $className . "Table";
1195
1196     my @hashKeys = ();
1197     my @hashSpecials = ();
1198     my @hashValue1 = ();
1199     my @hashValue2 = ();
1200     my %conditionals = ();
1201
1202     my @entries = ();
1203
1204     foreach my $attribute (@{$dataNode->attributes}) {
1205         next if ($attribute->isStatic);
1206         my $name = $attribute->signature->name;
1207         push(@hashKeys, $name);
1208
1209         my @specials = ();
1210         push(@specials, "DontDelete") unless $attribute->signature->extendedAttributes->{"Deletable"};
1211         push(@specials, "DontEnum") if $attribute->signature->extendedAttributes->{"NotEnumerable"};
1212         push(@specials, "ReadOnly") if $attribute->type =~ /readonly/;
1213         my $special = (@specials > 0) ? join(" | ", @specials) : "0";
1214         push(@hashSpecials, $special);
1215
1216         my $getter = GetAttributeGetterName($interfaceName, $className, $attribute);
1217         push(@hashValue1, $getter);
1218
1219         if ($attribute->type =~ /readonly/) {
1220             push(@hashValue2, "0");
1221         } else {
1222             my $setter = GetAttributeSetterName($interfaceName, $className, $attribute);
1223             push(@hashValue2, $setter);
1224         }
1225
1226         my $conditional = $attribute->signature->extendedAttributes->{"Conditional"};
1227         if ($conditional) {
1228             $conditionals{$name} = $conditional;
1229         }
1230     }
1231
1232     if (!$dataNode->extendedAttributes->{"OmitConstructor"}) {
1233         push(@hashKeys, "constructor");
1234         my $getter = "js" . $interfaceName . "Constructor";
1235         push(@hashValue1, $getter);
1236         if ($dataNode->extendedAttributes->{"ReplaceableConstructor"}) {
1237             my $setter = "setJS" . $interfaceName . "Constructor";
1238             push(@hashValue2, $setter);
1239             push(@hashSpecials, "DontEnum | DontDelete");
1240         } else {            
1241             push(@hashValue2, "0");
1242             push(@hashSpecials, "DontEnum | ReadOnly");
1243         }
1244     }
1245
1246     $object->GenerateHashTable($hashName, $hashSize,
1247                                \@hashKeys, \@hashSpecials,
1248                                \@hashValue1, \@hashValue2,
1249                                \%conditionals);
1250     return $numAttributes;
1251 }
1252
1253 sub GenerateParametersCheckExpression
1254 {
1255     my $numParameters = shift;
1256     my $function = shift;
1257
1258     my @andExpression = ();
1259     push(@andExpression, "argsCount == $numParameters");
1260     my $parameterIndex = 0;
1261     my %usedArguments = ();
1262     foreach my $parameter (@{$function->parameters}) {
1263         last if $parameterIndex >= $numParameters;
1264         my $value = "arg$parameterIndex";
1265         my $type = $codeGenerator->StripModule($parameter->type);
1266
1267         # Only DOMString or wrapper types are checked.
1268         # For DOMString, Null, Undefined and any Object are accepted too, as
1269         # these are acceptable values for a DOMString argument (any Object can
1270         # be converted to a string via .toString).
1271         if ($codeGenerator->IsStringType($type)) {
1272             push(@andExpression, "(${value}.isUndefinedOrNull() || ${value}.isString() || ${value}.isObject())");
1273             $usedArguments{$parameterIndex} = 1;
1274         } elsif ($parameter->extendedAttributes->{"Callback"}) {
1275             # For Callbacks only checks if the value is null or object.
1276             push(@andExpression, "(${value}.isNull() || ${value}.isFunction())");
1277             $usedArguments{$parameterIndex} = 1;
1278         } elsif (IsArrayType($type) || $codeGenerator->GetSequenceType($type)) {
1279             # FIXME: Add proper support for T[], T[]?, sequence<T>
1280             if ($parameter->isNullable) {
1281                 push(@andExpression, "(${value}.isNull() || (${value}.isObject() && isJSArray(${value})))");
1282             } else {
1283                 push(@andExpression, "(${value}.isObject() && isJSArray(${value}))");
1284             }
1285             $usedArguments{$parameterIndex} = 1;
1286         } elsif (!IsNativeType($type)) {
1287             if ($parameter->isNullable) {
1288                 push(@andExpression, "(${value}.isNull() || (${value}.isObject() && asObject(${value})->inherits(&JS${type}::s_info)))");
1289             } else {
1290                 push(@andExpression, "(${value}.isObject() && asObject(${value})->inherits(&JS${type}::s_info))");
1291             }
1292             $usedArguments{$parameterIndex} = 1;
1293         }
1294         $parameterIndex++;
1295     }
1296     my $res = join(" && ", @andExpression);
1297     $res = "($res)" if @andExpression > 1;
1298     return ($res, keys %usedArguments);
1299 }
1300
1301 sub GenerateFunctionParametersCheck
1302 {
1303     my $function = shift;
1304
1305     my @orExpression = ();
1306     my $numParameters = 0;
1307     my @neededArguments = ();
1308
1309     foreach my $parameter (@{$function->parameters}) {
1310         if ($parameter->extendedAttributes->{"Optional"}) {
1311             my ($expression, @usedArguments) = GenerateParametersCheckExpression($numParameters, $function);
1312             push(@orExpression, $expression);
1313             push(@neededArguments, @usedArguments);
1314         }
1315         $numParameters++;
1316     }
1317     my ($expression, @usedArguments) = GenerateParametersCheckExpression($numParameters, $function);
1318     push(@orExpression, $expression);
1319     push(@neededArguments, @usedArguments);
1320     return (join(" || ", @orExpression), @neededArguments);
1321 }
1322
1323 sub GenerateOverloadedFunction
1324 {
1325     my $function = shift;
1326     my $dataNode = shift;
1327     my $implClassName = shift;
1328
1329     # Generate code for choosing the correct overload to call. Overloads are
1330     # chosen based on the total number of arguments passed and the type of
1331     # values passed in non-primitive argument slots. When more than a single
1332     # overload is applicable, precedence is given according to the order of
1333     # declaration in the IDL.
1334
1335     my $kind = $function->isStatic ? "Constructor" : "Prototype";
1336     my $functionName = "js${implClassName}${kind}Function" . $codeGenerator->WK_ucfirst($function->signature->name);
1337
1338     push(@implContent, "EncodedJSValue JSC_HOST_CALL ${functionName}(ExecState* exec)\n");
1339     push(@implContent, <<END);
1340 {
1341     size_t argsCount = exec->argumentCount();
1342 END
1343
1344     my %fetchedArguments = ();
1345
1346     foreach my $overload (@{$function->{overloads}}) {
1347         my ($parametersCheck, @neededArguments) = GenerateFunctionParametersCheck($overload);
1348
1349         foreach my $parameterIndex (@neededArguments) {
1350             next if exists $fetchedArguments{$parameterIndex};
1351             push(@implContent, "    JSValue arg$parameterIndex(exec->argument($parameterIndex));\n");
1352             $fetchedArguments{$parameterIndex} = 1;
1353         }
1354
1355         push(@implContent, "    if ($parametersCheck)\n");
1356         push(@implContent, "        return ${functionName}$overload->{overloadIndex}(exec);\n");
1357     }
1358     push(@implContent, <<END);
1359     return throwVMTypeError(exec);
1360 }
1361
1362 END
1363 }
1364
1365 sub GenerateImplementation
1366 {
1367     my ($object, $dataNode) = @_;
1368
1369     my $interfaceName = $dataNode->name;
1370     my $className = "JS$interfaceName";
1371     my $implClassName = $interfaceName;
1372
1373     my $hasLegacyParent = $dataNode->extendedAttributes->{"JSLegacyParent"};
1374     my $hasRealParent = @{$dataNode->parents} > 0;
1375     my $hasParent = $hasLegacyParent || $hasRealParent;
1376     my $parentClassName = GetParentClassName($dataNode);
1377     my $visibleInterfaceName = $codeGenerator->GetVisibleInterfaceName($dataNode);
1378     my $eventTarget = $dataNode->extendedAttributes->{"EventTarget"};
1379     my $needsMarkChildren = $dataNode->extendedAttributes->{"JSCustomMarkFunction"} || $dataNode->extendedAttributes->{"EventTarget"};
1380
1381     # - Add default header template
1382     push(@implContentHeader, GenerateImplementationContentHeader($dataNode));
1383
1384     AddIncludesForSVGAnimatedType($interfaceName) if $className =~ /^JSSVGAnimated/;
1385
1386     $implIncludes{"<wtf/GetPtr.h>"} = 1;
1387     $implIncludes{"<runtime/PropertyNameArray.h>"} = 1 if $dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"};
1388
1389     AddIncludesForTypeInImpl($interfaceName);
1390
1391     @implContent = ();
1392
1393     push(@implContent, "\nusing namespace JSC;\n\n");
1394     push(@implContent, "namespace WebCore {\n\n");
1395
1396     push(@implContent, "ASSERT_CLASS_FITS_IN_CELL($className);\n");
1397
1398     my $numAttributes = GenerateAttributesHashTable($object, $dataNode);
1399
1400     my $numConstants = @{$dataNode->constants};
1401     my $numFunctions = @{$dataNode->functions};
1402
1403     # - Add all constants
1404     if (!$dataNode->extendedAttributes->{"OmitConstructor"}) {
1405         my $hashSize = $numConstants;
1406         my $hashName = $className . "ConstructorTable";
1407
1408         my @hashKeys = ();
1409         my @hashValue1 = ();
1410         my @hashValue2 = ();
1411         my @hashSpecials = ();
1412         my %conditionals = ();
1413
1414         # FIXME: we should not need a function for every constant.
1415         foreach my $constant (@{$dataNode->constants}) {
1416             my $name = $constant->name;
1417             push(@hashKeys, $name);
1418             my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($name);
1419             push(@hashValue1, $getter);
1420             push(@hashValue2, "0");
1421             push(@hashSpecials, "DontDelete | ReadOnly");
1422
1423             my $implementedBy = $constant->extendedAttributes->{"ImplementedBy"};
1424             if ($implementedBy) {
1425                 $implIncludes{"${implementedBy}.h"} = 1;
1426             }
1427             my $conditional = $constant->extendedAttributes->{"Conditional"};
1428             if ($conditional) {
1429                 $conditionals{$name} = $conditional;
1430             }
1431         }
1432
1433         foreach my $attribute (@{$dataNode->attributes}) {
1434             next unless ($attribute->isStatic);
1435             my $name = $attribute->signature->name;
1436             push(@hashKeys, $name);
1437
1438             my @specials = ();
1439             push(@specials, "DontDelete") unless $attribute->signature->extendedAttributes->{"Deletable"};
1440             push(@specials, "ReadOnly") if $attribute->type =~ /readonly/;
1441             my $special = (@specials > 0) ? join(" | ", @specials) : "0";
1442             push(@hashSpecials, $special);
1443
1444             my $getter = GetAttributeGetterName($interfaceName, $className, $attribute);
1445             push(@hashValue1, $getter);
1446
1447             if ($attribute->type =~ /readonly/) {
1448                 push(@hashValue2, "0");
1449             } else {
1450                 my $setter = GetAttributeSetterName($interfaceName, $className, $attribute);
1451                 push(@hashValue2, $setter);
1452             }
1453
1454             my $conditional = $attribute->signature->extendedAttributes->{"Conditional"};
1455             if ($conditional) {
1456                 $conditionals{$name} = $conditional;
1457             }
1458         }
1459
1460         foreach my $function (@{$dataNode->functions}) {
1461             next unless ($function->isStatic);
1462             next if $function->{overloadIndex} && $function->{overloadIndex} > 1;
1463             my $name = $function->signature->name;
1464             push(@hashKeys, $name);
1465
1466             my $functionName = GetFunctionName($className, $function);
1467             push(@hashValue1, $functionName);
1468
1469             my $numParameters = @{$function->parameters};
1470             push(@hashValue2, $numParameters);
1471
1472             my @specials = ();
1473             push(@specials, "DontDelete") unless $function->signature->extendedAttributes->{"Deletable"};
1474             push(@specials, "DontEnum") if $function->signature->extendedAttributes->{"NotEnumerable"};
1475             push(@specials, "JSC::Function");
1476             my $special = (@specials > 0) ? join(" | ", @specials) : "0";
1477             push(@hashSpecials, $special);
1478
1479             my $conditional = $function->signature->extendedAttributes->{"Conditional"};
1480             if ($conditional) {
1481                 $conditionals{$name} = $conditional;
1482             }
1483         }
1484
1485         $object->GenerateHashTable($hashName, $hashSize,
1486                                    \@hashKeys, \@hashSpecials,
1487                                    \@hashValue1, \@hashValue2,
1488                                    \%conditionals);
1489
1490         push(@implContent, $codeGenerator->GenerateCompileTimeCheckForEnumsIfNeeded($dataNode));
1491
1492         my $protoClassName = "${className}Prototype";
1493         GenerateConstructorDefinition(\@implContent, $className, $protoClassName, $interfaceName, $visibleInterfaceName, $dataNode);
1494         if ($dataNode->extendedAttributes->{"NamedConstructor"}) {
1495             GenerateConstructorDefinition(\@implContent, $className, $protoClassName, $interfaceName, $dataNode->extendedAttributes->{"NamedConstructor"}, $dataNode, "GeneratingNamedConstructor");
1496         }
1497     }
1498
1499     # - Add functions and constants to a hashtable definition
1500     my $hashSize = $numFunctions + $numConstants;
1501     my $hashName = $className . "PrototypeTable";
1502
1503     my @hashKeys = ();
1504     my @hashValue1 = ();
1505     my @hashValue2 = ();
1506     my @hashSpecials = ();
1507     my %conditionals = ();
1508
1509     # FIXME: we should not need a function for every constant.
1510     foreach my $constant (@{$dataNode->constants}) {
1511         my $name = $constant->name;
1512         push(@hashKeys, $name);
1513         my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($name);
1514         push(@hashValue1, $getter);
1515         push(@hashValue2, "0");
1516         push(@hashSpecials, "DontDelete | ReadOnly");
1517
1518         my $conditional = $constant->extendedAttributes->{"Conditional"};
1519         if ($conditional) {
1520             $conditionals{$name} = $conditional;
1521         }
1522     }
1523
1524     foreach my $function (@{$dataNode->functions}) {
1525         next if ($function->isStatic);
1526         next if $function->{overloadIndex} && $function->{overloadIndex} > 1;
1527         my $name = $function->signature->name;
1528         push(@hashKeys, $name);
1529
1530         my $functionName = GetFunctionName($className, $function);
1531         push(@hashValue1, $functionName);
1532
1533         my $numParameters = @{$function->parameters};
1534         push(@hashValue2, $numParameters);
1535
1536         my @specials = ();
1537         push(@specials, "DontDelete") unless $function->signature->extendedAttributes->{"Deletable"};
1538         push(@specials, "DontEnum") if $function->signature->extendedAttributes->{"NotEnumerable"};
1539         push(@specials, "JSC::Function");
1540         my $special = (@specials > 0) ? join(" | ", @specials) : "0";
1541         push(@hashSpecials, $special);
1542
1543         my $conditional = $function->signature->extendedAttributes->{"Conditional"};
1544         if ($conditional) {
1545             $conditionals{$name} = $conditional;
1546         }
1547     }
1548
1549     $object->GenerateHashTable($hashName, $hashSize,
1550                                \@hashKeys, \@hashSpecials,
1551                                \@hashValue1, \@hashValue2,
1552                                \%conditionals);
1553
1554     if ($dataNode->extendedAttributes->{"JSNoStaticTables"}) {
1555         push(@implContent, "static const HashTable* get${className}PrototypeTable(ExecState* exec)\n");
1556         push(@implContent, "{\n");
1557         push(@implContent, "    return getHashTableForGlobalData(exec->globalData(), &${className}PrototypeTable);\n");
1558         push(@implContent, "}\n\n");
1559         push(@implContent, "const ClassInfo ${className}Prototype::s_info = { \"${visibleInterfaceName}Prototype\", &Base::s_info, 0, get${className}PrototypeTable, CREATE_METHOD_TABLE(${className}Prototype) };\n\n");
1560     } else {
1561         push(@implContent, "const ClassInfo ${className}Prototype::s_info = { \"${visibleInterfaceName}Prototype\", &Base::s_info, &${className}PrototypeTable, 0, CREATE_METHOD_TABLE(${className}Prototype) };\n\n");
1562     }
1563     if ($interfaceName ne "DOMWindow" && !$dataNode->extendedAttributes->{"IsWorkerContext"}) {
1564         push(@implContent, "JSObject* ${className}Prototype::self(ExecState* exec, JSGlobalObject* globalObject)\n");
1565         push(@implContent, "{\n");
1566         push(@implContent, "    return getDOMPrototype<${className}>(exec, globalObject);\n");
1567         push(@implContent, "}\n\n");
1568     }
1569
1570     if ($numConstants > 0 || $numFunctions > 0) {
1571         push(@implContent, "bool ${className}Prototype::getOwnPropertySlot(JSCell* cell, ExecState* exec, PropertyName propertyName, PropertySlot& slot)\n");
1572         push(@implContent, "{\n");
1573         push(@implContent, "    ${className}Prototype* thisObject = jsCast<${className}Prototype*>(cell);\n");
1574
1575         if ($numConstants eq 0 && $numFunctions eq 0) {
1576             push(@implContent, "    return Base::getOwnPropertySlot(thisObject, exec, propertyName, slot);\n");        
1577         } elsif ($numConstants eq 0) {
1578             push(@implContent, "    return getStaticFunctionSlot<JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, slot);\n");
1579         } elsif ($numFunctions eq 0) {
1580             push(@implContent, "    return getStaticValueSlot<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, slot);\n");
1581         } else {
1582             push(@implContent, "    return getStaticPropertySlot<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, slot);\n");
1583         }
1584         push(@implContent, "}\n\n");
1585
1586         push(@implContent, "bool ${className}Prototype::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, PropertyName propertyName, PropertyDescriptor& descriptor)\n");
1587         push(@implContent, "{\n");
1588         push(@implContent, "    ${className}Prototype* thisObject = jsCast<${className}Prototype*>(object);\n");
1589
1590         if ($numConstants eq 0 && $numFunctions eq 0) {
1591             push(@implContent, "    return Base::getOwnPropertyDescriptor(thisObject, exec, propertyName, descriptor);\n");        
1592         } elsif ($numConstants eq 0) {
1593             push(@implContent, "    return getStaticFunctionDescriptor<JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, descriptor);\n");
1594         } elsif ($numFunctions eq 0) {
1595             push(@implContent, "    return getStaticValueDescriptor<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, descriptor);\n");
1596         } else {
1597             push(@implContent, "    return getStaticPropertyDescriptor<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, propertyName, descriptor);\n");
1598         }
1599         push(@implContent, "}\n\n");
1600     }
1601
1602     if ($dataNode->extendedAttributes->{"JSCustomNamedGetterOnPrototype"}) {
1603         push(@implContent, "void ${className}Prototype::put(JSCell* cell, ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)\n");
1604         push(@implContent, "{\n");
1605         push(@implContent, "    ${className}Prototype* thisObject = jsCast<${className}Prototype*>(cell);\n");
1606         push(@implContent, "    if (thisObject->putDelegate(exec, propertyName, value, slot))\n");
1607         push(@implContent, "        return;\n");
1608         push(@implContent, "    Base::put(thisObject, exec, propertyName, value, slot);\n");
1609         push(@implContent, "}\n\n");
1610     }
1611
1612     # - Initialize static ClassInfo object
1613     if ($numAttributes > 0 && $dataNode->extendedAttributes->{"JSNoStaticTables"}) {
1614         push(@implContent, "static const HashTable* get${className}Table(ExecState* exec)\n");
1615         push(@implContent, "{\n");
1616         push(@implContent, "    return getHashTableForGlobalData(exec->globalData(), &${className}Table);\n");
1617         push(@implContent, "}\n\n");
1618     }
1619
1620     push(@implContent, "const ClassInfo $className" . "::s_info = { \"${visibleInterfaceName}\", &Base::s_info, ");
1621
1622     if ($numAttributes > 0 && !$dataNode->extendedAttributes->{"JSNoStaticTables"}) {
1623         push(@implContent, "&${className}Table");
1624     } else {
1625         push(@implContent, "0");
1626     }
1627     if ($numAttributes > 0 && $dataNode->extendedAttributes->{"JSNoStaticTables"}) {
1628         push(@implContent, ", get${className}Table ");
1629     } else {
1630         push(@implContent, ", 0 ");
1631     }
1632     push(@implContent, ", CREATE_METHOD_TABLE($className) };\n\n");
1633
1634     my $implType = $implClassName;
1635     my ($svgPropertyType, $svgListPropertyType, $svgNativeType) = GetSVGPropertyTypes($implType);
1636     $implType = $svgNativeType if $svgNativeType;
1637
1638     my $svgPropertyOrListPropertyType;
1639     $svgPropertyOrListPropertyType = $svgPropertyType if $svgPropertyType;
1640     $svgPropertyOrListPropertyType = $svgListPropertyType if $svgListPropertyType;
1641
1642     # Constructor
1643     if ($interfaceName eq "DOMWindow") {
1644         AddIncludesForTypeInImpl("JSDOMWindowShell");
1645         push(@implContent, "${className}::$className(JSGlobalData& globalData, Structure* structure, PassRefPtr<$implType> impl, JSDOMWindowShell* shell)\n");
1646         push(@implContent, "    : $parentClassName(globalData, structure, impl, shell)\n");
1647         push(@implContent, "{\n");
1648         push(@implContent, "}\n\n");
1649     } elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
1650         AddIncludesForTypeInImpl($interfaceName);
1651         push(@implContent, "${className}::$className(JSGlobalData& globalData, Structure* structure, PassRefPtr<$implType> impl)\n");
1652         push(@implContent, "    : $parentClassName(globalData, structure, impl)\n");
1653         push(@implContent, "{\n");
1654         push(@implContent, "}\n\n");
1655     } else {
1656         push(@implContent, "${className}::$className(Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<$implType> impl)\n");
1657         if ($hasParent) {
1658             push(@implContent, "    : $parentClassName(structure, globalObject, impl)\n");
1659         } else {
1660             push(@implContent, "    : $parentClassName(structure, globalObject)\n");
1661             push(@implContent, "    , m_impl(impl.leakRef())\n");
1662         }
1663         push(@implContent, "{\n");
1664         push(@implContent, "}\n\n");
1665
1666         push(@implContent, "void ${className}::finishCreation(JSGlobalData& globalData)\n");
1667         push(@implContent, "{\n");
1668         push(@implContent, "    Base::finishCreation(globalData);\n");
1669         if (IsTypedArrayType($implType) and ($implType ne "ArrayBufferView") and ($implType ne "ArrayBuffer")) {
1670             push(@implContent, "    TypedArrayDescriptor descriptor(&${className}::s_info, OBJECT_OFFSETOF(${className}, m_storage), OBJECT_OFFSETOF(${className}, m_storageLength));\n");
1671             push(@implContent, "    globalData.registerTypedArrayDescriptor(impl(), descriptor);\n");
1672             push(@implContent, "    m_storage = impl()->data();\n");
1673             push(@implContent, "    m_storageLength = impl()->length();\n");
1674         }
1675         push(@implContent, "    ASSERT(inherits(&s_info));\n");
1676         push(@implContent, "}\n\n");
1677     }
1678
1679     if (!$dataNode->extendedAttributes->{"ExtendsDOMGlobalObject"}) {
1680         push(@implContent, "JSObject* ${className}::createPrototype(ExecState* exec, JSGlobalObject* globalObject)\n");
1681         push(@implContent, "{\n");
1682         if ($hasParent && $parentClassName ne "JSC::DOMNodeFilter") {
1683             push(@implContent, "    return ${className}Prototype::create(exec->globalData(), globalObject, ${className}Prototype::createStructure(exec->globalData(), globalObject, ${parentClassName}Prototype::self(exec, globalObject)));\n");
1684         } else {
1685             my $prototype = $dataNode->isException ? "errorPrototype" : "objectPrototype";
1686             push(@implContent, "    return ${className}Prototype::create(exec->globalData(), globalObject, ${className}Prototype::createStructure(globalObject->globalData(), globalObject, globalObject->${prototype}()));\n");
1687         }
1688         push(@implContent, "}\n\n");
1689     }
1690
1691     if (!$hasParent) {
1692         # FIXME: This destroy function should not be necessary, as 
1693         # a finalizer should be called for each DOM object wrapper.
1694         # However, that seems not to be the case, so this has been
1695         # added back to avoid leaking while we figure out why the
1696         # finalizers are not always getting called. The work tracking
1697         # the finalizer issue is being tracked in http://webkit.org/b/75451
1698         push(@implContent, "void ${className}::destroy(JSC::JSCell* cell)\n");
1699         push(@implContent, "{\n");
1700         push(@implContent, "    ${className}* thisObject = static_cast<${className}*>(cell);\n");
1701         push(@implContent, "    thisObject->${className}::~${className}();\n");
1702         push(@implContent, "}\n\n");
1703
1704         # We also need a destructor for the allocateCell to work properly with the destructor-free part of the heap.
1705         # Otherwise, these destroy functions/destructors won't get called.
1706         push(@implContent, "${className}::~${className}()\n");
1707         push(@implContent, "{\n");
1708         push(@implContent, "    releaseImplIfNotNull();\n");
1709         push(@implContent, "}\n\n");
1710     }
1711
1712     my $hasGetter = $numAttributes > 0
1713                  || !$dataNode->extendedAttributes->{"OmitConstructor"} 
1714                  || $dataNode->extendedAttributes->{"IndexedGetter"}
1715                  || $dataNode->extendedAttributes->{"NumericIndexedGetter"}
1716                  || $dataNode->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}
1717                  || $dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}
1718                  || $dataNode->extendedAttributes->{"NamedGetter"}
1719                  || $dataNode->extendedAttributes->{"CustomNamedGetter"};
1720
1721     # Attributes
1722     if ($hasGetter) {
1723         if (!$dataNode->extendedAttributes->{"JSInlineGetOwnPropertySlot"} && !$dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}) {
1724             push(@implContent, "bool ${className}::getOwnPropertySlot(JSCell* cell, ExecState* exec, PropertyName propertyName, PropertySlot& slot)\n");
1725             push(@implContent, "{\n");
1726             push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
1727             push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
1728             push(@implContent, GenerateGetOwnPropertySlotBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 0));
1729             push(@implContent, "}\n\n");
1730             push(@implContent, "bool ${className}::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, PropertyName propertyName, PropertyDescriptor& descriptor)\n");
1731             push(@implContent, "{\n");
1732             push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(object);\n");
1733             push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
1734             push(@implContent, GenerateGetOwnPropertyDescriptorBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 0));
1735             push(@implContent, "}\n\n");
1736         }
1737
1738         if (($dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"})
1739                 && !$dataNode->extendedAttributes->{"CustomNamedGetter"}) {
1740             push(@implContent, "bool ${className}::getOwnPropertySlotByIndex(JSCell* cell, ExecState* exec, unsigned propertyName, PropertySlot& slot)\n");
1741             push(@implContent, "{\n");
1742             push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
1743             push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
1744             push(@implContent, "    if (propertyName < static_cast<$implClassName*>(thisObject->impl())->length()) {\n");
1745             if ($dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
1746                 push(@implContent, "        slot.setValue(thisObject->getByIndex(exec, propertyName));\n");
1747             } else {
1748                 push(@implContent, "        slot.setCustomIndex(thisObject, propertyName, thisObject->indexGetter);\n");
1749             }
1750             push(@implContent, "        return true;\n");
1751             push(@implContent, "    }\n");
1752             push(@implContent, "    return thisObject->methodTable()->getOwnPropertySlot(thisObject, exec, Identifier::from(exec, propertyName), slot);\n");
1753             push(@implContent, "}\n\n");
1754         }
1755
1756         if ($numAttributes > 0) {
1757             foreach my $attribute (@{$dataNode->attributes}) {
1758                 my $name = $attribute->signature->name;
1759                 my $type = $codeGenerator->StripModule($attribute->signature->type);                
1760                 $codeGenerator->AssertNotSequenceType($type);
1761                 my $getFunctionName = GetAttributeGetterName($interfaceName, $className, $attribute);
1762                 my $implGetterFunctionName = $codeGenerator->WK_lcfirst($name);
1763
1764                 my $attributeConditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
1765                 push(@implContent, "#if ${attributeConditionalString}\n") if $attributeConditionalString;
1766
1767                 push(@implContent, "JSValue ${getFunctionName}(ExecState* exec, JSValue slotBase, PropertyName)\n");
1768                 push(@implContent, "{\n");
1769
1770                 if (!$attribute->isStatic || $attribute->signature->type =~ /Constructor$/) {
1771                     push(@implContent, "    ${className}* castedThis = jsCast<$className*>(asObject(slotBase));\n");
1772                 } else {
1773                     push(@implContent, "    UNUSED_PARAM(slotBase);\n");
1774                 }
1775
1776                 if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) {
1777                     $needsMarkChildren = 1;
1778                 }
1779
1780                 if ($dataNode->extendedAttributes->{"CheckSecurity"} &&
1781                     !$attribute->signature->extendedAttributes->{"DoNotCheckSecurity"} &&
1782                     !$attribute->signature->extendedAttributes->{"DoNotCheckSecurityOnGetter"}) {
1783                     push(@implContent, "    if (!castedThis->allowsAccessFrom(exec))\n");
1784                     push(@implContent, "        return jsUndefined();\n");
1785                 }
1786
1787                 if ($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCustom"} || $attribute->signature->extendedAttributes->{"CustomGetter"} || $attribute->signature->extendedAttributes->{"JSCustomGetter"}) {
1788                     push(@implContent, "    return castedThis->$implGetterFunctionName(exec);\n");
1789                 } elsif ($attribute->signature->extendedAttributes->{"CheckSecurityForNode"}) {
1790                     $implIncludes{"JSDOMBinding.h"} = 1;
1791                     push(@implContent, "    $implClassName* impl = static_cast<$implClassName*>(castedThis->impl());\n");
1792                     push(@implContent, "    return shouldAllowAccessToNode(exec, impl->" . $attribute->signature->name . "()) ? " . NativeToJSValue($attribute->signature, 0, $implClassName, "impl->$implGetterFunctionName()", "castedThis") . " : jsNull();\n");
1793                 } elsif ($type eq "EventListener") {
1794                     $implIncludes{"EventListener.h"} = 1;
1795                     push(@implContent, "    UNUSED_PARAM(exec);\n");
1796                     push(@implContent, "    $implClassName* impl = static_cast<$implClassName*>(castedThis->impl());\n");
1797                     push(@implContent, "    if (EventListener* listener = impl->$implGetterFunctionName()) {\n");
1798                     push(@implContent, "        if (const JSEventListener* jsListener = JSEventListener::cast(listener)) {\n");
1799                     if ($implClassName eq "Document" || $implClassName eq "WorkerContext" || $implClassName eq "SharedWorkerContext" || $implClassName eq "DedicatedWorkerContext") {
1800                         push(@implContent, "            if (JSObject* jsFunction = jsListener->jsFunction(impl))\n");
1801                     } else {
1802                         push(@implContent, "            if (JSObject* jsFunction = jsListener->jsFunction(impl->scriptExecutionContext()))\n");
1803                     }
1804                     push(@implContent, "                return jsFunction;\n");
1805                     push(@implContent, "        }\n");
1806                     push(@implContent, "    }\n");
1807                     push(@implContent, "    return jsNull();\n");
1808                 } elsif ($attribute->signature->type =~ /Constructor$/) {
1809                     my $constructorType = $codeGenerator->StripModule($attribute->signature->type);
1810                     $constructorType =~ s/Constructor$//;
1811                     # Constructor attribute is only used by DOMWindow.idl, so it's correct to pass castedThis as the global object
1812                     # Once JSDOMWrappers have a back-pointer to the globalObject we can pass castedThis->globalObject()
1813                     push(@implContent, "    return JS" . $constructorType . "::getConstructor(exec, castedThis);\n");
1814                 } elsif (!@{$attribute->getterExceptions}) {
1815                     push(@implContent, "    UNUSED_PARAM(exec);\n") if !$attribute->signature->extendedAttributes->{"CallWith"};
1816
1817                     my $cacheIndex = 0;
1818                     if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) {
1819                         $cacheIndex = $currentCachedAttribute;
1820                         $currentCachedAttribute++;
1821                         push(@implContent, "    if (JSValue cachedValue = castedThis->m_" . $attribute->signature->name . ".get())\n");
1822                         push(@implContent, "        return cachedValue;\n");
1823                     }
1824
1825                     my @callWithArgs = GenerateCallWith($attribute->signature->extendedAttributes->{"CallWith"}, \@implContent, "jsUndefined()");
1826
1827                     if ($svgListPropertyType) {
1828                         push(@implContent, "    JSValue result =  " . NativeToJSValue($attribute->signature, 0, $implClassName, "castedThis->impl()->$implGetterFunctionName(" . (join ", ", @callWithArgs) . ")", "castedThis") . ";\n");
1829                     } elsif ($svgPropertyOrListPropertyType) {
1830                         push(@implContent, "    $svgPropertyOrListPropertyType& impl = castedThis->impl()->propertyReference();\n");
1831                         if ($svgPropertyOrListPropertyType eq "float") { # Special case for JSSVGNumber
1832                             push(@implContent, "    JSValue result =  " . NativeToJSValue($attribute->signature, 0, $implClassName, "impl", "castedThis") . ";\n");
1833                         } else {
1834                             push(@implContent, "    JSValue result =  " . NativeToJSValue($attribute->signature, 0, $implClassName, "impl.$implGetterFunctionName(" . (join ", ", @callWithArgs) . ")", "castedThis") . ";\n");
1835
1836                         }
1837                     } else {
1838                         my ($functionName, @arguments) = $codeGenerator->GetterExpression(\%implIncludes, $interfaceName, $attribute);
1839                         if ($attribute->signature->extendedAttributes->{"ImplementedBy"}) {
1840                             my $implementedBy = $attribute->signature->extendedAttributes->{"ImplementedBy"};
1841                             $implIncludes{"${implementedBy}.h"} = 1;
1842                             $functionName = "${implementedBy}::${functionName}";
1843                             unshift(@arguments, "impl") if !$attribute->isStatic;
1844                         } elsif ($attribute->isStatic) {
1845                             $functionName = "${implClassName}::${functionName}";
1846                         } else {
1847                             $functionName = "impl->${functionName}";
1848                         }
1849
1850                         unshift(@arguments, @callWithArgs);
1851
1852                         my $jsType = NativeToJSValue($attribute->signature, 0, $implClassName, "${functionName}(" . join(", ", @arguments) . ")", "castedThis");
1853                         push(@implContent, "    $implClassName* impl = static_cast<$implClassName*>(castedThis->impl());\n") if !$attribute->isStatic;
1854                         if ($codeGenerator->IsSVGAnimatedType($type)) {
1855                             push(@implContent, "    RefPtr<$type> obj = $jsType;\n");
1856                             push(@implContent, "    JSValue result =  toJS(exec, castedThis->globalObject(), obj.get());\n");
1857                         } else {
1858                             push(@implContent, "    JSValue result = $jsType;\n");
1859                         }
1860                     }
1861
1862                     push(@implContent, "    castedThis->m_" . $attribute->signature->name . ".set(exec->globalData(), castedThis, result);\n") if ($attribute->signature->extendedAttributes->{"CachedAttribute"});
1863                     push(@implContent, "    return result;\n");
1864
1865                 } else {
1866                     my @arguments = ("ec");
1867                     push(@implContent, "    ExceptionCode ec = 0;\n");
1868
1869                     unshift(@arguments, GenerateCallWith($attribute->signature->extendedAttributes->{"CallWith"}, \@implContent, "jsUndefined()"));
1870
1871                     if ($svgPropertyOrListPropertyType) {
1872                         push(@implContent, "    $svgPropertyOrListPropertyType impl(*castedThis->impl());\n");
1873                         push(@implContent, "    JSC::JSValue result = " . NativeToJSValue($attribute->signature, 0, $implClassName, "impl.$implGetterFunctionName(" . join(", ", @arguments) . ")", "castedThis") . ";\n");
1874                     } else {
1875                         push(@implContent, "    $implClassName* impl = static_cast<$implClassName*>(castedThis->impl());\n");
1876                         push(@implContent, "    JSC::JSValue result = " . NativeToJSValue($attribute->signature, 0, $implClassName, "impl->$implGetterFunctionName(" . join(", ", @arguments) . ")", "castedThis") . ";\n");
1877                     }
1878
1879                     push(@implContent, "    setDOMException(exec, ec);\n");
1880                     push(@implContent, "    return result;\n");
1881                 }
1882
1883                 push(@implContent, "}\n\n");
1884
1885                 push(@implContent, "#endif\n") if $attributeConditionalString;
1886
1887                 push(@implContent, "\n");
1888             }
1889
1890             if (!$dataNode->extendedAttributes->{"OmitConstructor"}) {
1891                 my $constructorFunctionName = "js" . $interfaceName . "Constructor";
1892
1893                 push(@implContent, "JSValue ${constructorFunctionName}(ExecState* exec, JSValue slotBase, PropertyName)\n");
1894                 push(@implContent, "{\n");
1895                 push(@implContent, "    ${className}* domObject = jsCast<$className*>(asObject(slotBase));\n");
1896
1897                 if ($dataNode->extendedAttributes->{"CheckSecurity"}) {
1898                     push(@implContent, "    if (!domObject->allowsAccessFrom(exec))\n");
1899                     push(@implContent, "        return jsUndefined();\n");
1900                 }
1901
1902                 push(@implContent, "    return ${className}::getConstructor(exec, domObject->globalObject());\n");
1903                 push(@implContent, "}\n\n");
1904             }
1905         }
1906
1907         # Check if we have any writable attributes
1908         my $hasReadWriteProperties = 0;
1909         foreach my $attribute (@{$dataNode->attributes}) {
1910             $hasReadWriteProperties = 1 if $attribute->type !~ /^readonly/ && !$attribute->isStatic;
1911         }
1912
1913         my $hasSetter = $hasReadWriteProperties
1914                      || $dataNode->extendedAttributes->{"CustomNamedSetter"}
1915                      || $dataNode->extendedAttributes->{"CustomIndexedSetter"};
1916
1917         if ($hasSetter) {
1918             if (!$dataNode->extendedAttributes->{"CustomPutFunction"}) {
1919                 push(@implContent, "void ${className}::put(JSCell* cell, ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)\n");
1920                 push(@implContent, "{\n");
1921                 push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
1922                 push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
1923                 if ($dataNode->extendedAttributes->{"CustomIndexedSetter"}) {
1924                     push(@implContent, "    unsigned index = propertyName.asIndex();\n");
1925                     push(@implContent, "    if (index != PropertyName::NotAnIndex) {\n");
1926                     push(@implContent, "        thisObject->indexSetter(exec, index, value);\n");
1927                     push(@implContent, "        return;\n");
1928                     push(@implContent, "    }\n");
1929                 }
1930                 if ($dataNode->extendedAttributes->{"CustomNamedSetter"}) {
1931                     push(@implContent, "    if (thisObject->putDelegate(exec, propertyName, value, slot))\n");
1932                     push(@implContent, "        return;\n");
1933                 }
1934
1935                 if ($hasReadWriteProperties) {
1936                     push(@implContent, "    lookupPut<$className, Base>(exec, propertyName, value, " . hashTableAccessor($dataNode->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, slot);\n");
1937                 } else {
1938                     push(@implContent, "    Base::put(thisObject, exec, propertyName, value, slot);\n");
1939                 }
1940                 push(@implContent, "}\n\n");
1941             }
1942
1943             if ($dataNode->extendedAttributes->{"CustomIndexedSetter"}) {
1944                 push(@implContent, "void ${className}::putByIndex(JSCell* cell, ExecState* exec, unsigned propertyName, JSValue value, bool)\n");
1945                 push(@implContent, "{\n");
1946                 push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
1947                 push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
1948                 push(@implContent, "    thisObject->indexSetter(exec, propertyName, value);\n");
1949                 push(@implContent, "    return;\n");
1950                 push(@implContent, "}\n\n");
1951             }
1952
1953             if ($hasReadWriteProperties) {
1954                 foreach my $attribute (@{$dataNode->attributes}) {
1955                     if ($attribute->type !~ /^readonly/) {
1956                         my $name = $attribute->signature->name;
1957                         my $type = $codeGenerator->StripModule($attribute->signature->type);
1958                         my $putFunctionName = GetAttributeSetterName($interfaceName, $className, $attribute);
1959                         my $implSetterFunctionName = $codeGenerator->WK_ucfirst($name);
1960
1961                         my $attributeConditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
1962                         push(@implContent, "#if ${attributeConditionalString}\n") if $attributeConditionalString;
1963
1964                         push(@implContent, "void ${putFunctionName}(ExecState* exec, JSObject*");
1965                         push(@implContent, " thisObject") if !$attribute->isStatic;
1966                         push(@implContent, ", JSValue value)\n");
1967                         push(@implContent, "{\n");
1968
1969                             push(@implContent, "    UNUSED_PARAM(exec);\n");
1970
1971                             if ($dataNode->extendedAttributes->{"CheckSecurity"} && !$attribute->signature->extendedAttributes->{"DoNotCheckSecurity"}) {
1972                                 if ($interfaceName eq "DOMWindow") {
1973                                     push(@implContent, "    if (!jsCast<$className*>(thisObject)->allowsAccessFrom(exec))\n");
1974                                 } else {
1975                                     push(@implContent, "    if (!shouldAllowAccessToFrame(exec, jsCast<$className*>(thisObject)->impl()->frame()))\n");
1976                                 }
1977                                 push(@implContent, "        return;\n");
1978                             }
1979
1980                             if ($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCustom"} || $attribute->signature->extendedAttributes->{"CustomSetter"} || $attribute->signature->extendedAttributes->{"JSCustomSetter"}) {
1981                                 push(@implContent, "    jsCast<$className*>(thisObject)->set$implSetterFunctionName(exec, value);\n");
1982                             } elsif ($type eq "EventListener") {
1983                                 $implIncludes{"JSEventListener.h"} = 1;
1984                                 push(@implContent, "    UNUSED_PARAM(exec);\n");
1985                                 push(@implContent, "    ${className}* castedThis = jsCast<${className}*>(thisObject);\n");
1986                                 my $windowEventListener = $attribute->signature->extendedAttributes->{"JSWindowEventListener"};
1987                                 if ($windowEventListener) {
1988                                     push(@implContent, "    JSDOMGlobalObject* globalObject = castedThis->globalObject();\n");
1989                                 }
1990                                 push(@implContent, "    $implClassName* impl = static_cast<$implClassName*>(castedThis->impl());\n");
1991                                 if ((($interfaceName eq "DOMWindow") or ($interfaceName eq "WorkerContext")) and $name eq "onerror") {
1992                                     $implIncludes{"JSErrorHandler.h"} = 1;
1993                                     push(@implContent, "    impl->set$implSetterFunctionName(createJSErrorHandler(exec, value, thisObject));\n");
1994                                 } else {
1995                                     push(@implContent, GenerateAttributeEventListenerCall($className, $implSetterFunctionName, $windowEventListener));
1996                                 }
1997                             } elsif ($attribute->signature->type =~ /Constructor$/) {
1998                                 my $constructorType = $attribute->signature->type;
1999                                 $constructorType =~ s/Constructor$//;
2000                                 # $constructorType ~= /Constructor$/ indicates that it is NamedConstructor.
2001                                 # We do not generate the header file for NamedConstructor of class XXXX,
2002                                 # since we generate the NamedConstructor declaration into the header file of class XXXX.
2003                                 if ($constructorType ne "DOMObject" and $constructorType !~ /Constructor$/) {
2004                                     AddToImplIncludes("JS" . $constructorType . ".h", $attribute->signature->extendedAttributes->{"Conditional"});
2005                                 }
2006                                 push(@implContent, "    // Shadowing a built-in constructor\n");
2007                                 if ($interfaceName eq "DOMWindow" && $className eq "JSblah") {
2008                                     # FIXME: This branch never executes and should be removed.
2009                                     push(@implContent, "    jsCast<$className*>(thisObject)->putDirect(exec->globalData(), exec->propertyNames().constructor, value);\n");
2010                                 } else {
2011                                     push(@implContent, "    jsCast<$className*>(thisObject)->putDirect(exec->globalData(), Identifier(exec, \"$name\"), value);\n");
2012                                 }
2013                             } elsif ($attribute->signature->extendedAttributes->{"Replaceable"}) {
2014                                 push(@implContent, "    // Shadowing a built-in object\n");
2015                                 push(@implContent, "    jsCast<$className*>(thisObject)->putDirect(exec->globalData(), Identifier(exec, \"$name\"), value);\n");
2016                             } else {
2017                                 if (!$attribute->isStatic) {
2018                                     push(@implContent, "    $className* castedThis = jsCast<$className*>(thisObject);\n");
2019                                     push(@implContent, "    $implType* impl = static_cast<$implType*>(castedThis->impl());\n");
2020                                 }
2021                                 push(@implContent, "    ExceptionCode ec = 0;\n") if @{$attribute->setterExceptions};
2022
2023                                 # If the "StrictTypeChecking" extended attribute is present, and the attribute's type is an
2024                                 # interface type, then if the incoming value does not implement that interface, a TypeError
2025                                 # is thrown rather than silently passing NULL to the C++ code.
2026                                 # Per the Web IDL and ECMAScript specifications, incoming values can always be converted to
2027                                 # both strings and numbers, so do not throw TypeError if the attribute is of these types.
2028                                 if ($attribute->signature->extendedAttributes->{"StrictTypeChecking"}) {
2029                                     $implIncludes{"<runtime/Error.h>"} = 1;
2030
2031                                     my $argType = $attribute->signature->type;
2032                                     if (!IsNativeType($argType)) {
2033                                         push(@implContent, "    if (!value.isUndefinedOrNull() && !value.inherits(&JS${argType}::s_info)) {\n");
2034                                         push(@implContent, "        throwVMTypeError(exec);\n");
2035                                         push(@implContent, "        return;\n");
2036                                         push(@implContent, "    };\n");
2037                                     }
2038                                 }
2039
2040                                 my $nativeValue = JSValueToNative($attribute->signature, "value");
2041                                 if ($svgPropertyOrListPropertyType) {
2042                                     if ($svgPropertyType) {
2043                                         push(@implContent, "    if (impl->isReadOnly()) {\n");
2044                                         push(@implContent, "        setDOMException(exec, NO_MODIFICATION_ALLOWED_ERR);\n");
2045                                         push(@implContent, "        return;\n");
2046                                         push(@implContent, "    }\n");
2047                                         $implIncludes{"ExceptionCode.h"} = 1;
2048                                     }
2049                                     push(@implContent, "    $svgPropertyOrListPropertyType& podImpl = impl->propertyReference();\n");
2050                                     if ($svgPropertyOrListPropertyType eq "float") { # Special case for JSSVGNumber
2051                                         push(@implContent, "    podImpl = $nativeValue;\n");
2052                                     } else {
2053                                         push(@implContent, "    podImpl.set$implSetterFunctionName($nativeValue");
2054                                         push(@implContent, ", ec") if @{$attribute->setterExceptions};
2055                                         push(@implContent, ");\n");
2056                                         push(@implContent, "    setDOMException(exec, ec);\n") if @{$attribute->setterExceptions};
2057                                     }
2058                                     if ($svgPropertyType) {
2059                                         if (@{$attribute->setterExceptions}) {
2060                                             push(@implContent, "    if (!ec)\n");
2061                                             push(@implContent, "        impl->commitChange();\n");
2062                                         } else {
2063                                             push(@implContent, "    impl->commitChange();\n");
2064                                         }
2065                                     }
2066                                 } else {
2067                                     my ($functionName, @arguments) = $codeGenerator->SetterExpression(\%implIncludes, $interfaceName, $attribute);
2068                                     push(@arguments, $nativeValue);
2069                                     if ($attribute->signature->extendedAttributes->{"ImplementedBy"}) {
2070                                         my $implementedBy = $attribute->signature->extendedAttributes->{"ImplementedBy"};
2071                                         $implIncludes{"${implementedBy}.h"} = 1;
2072                                         unshift(@arguments, "impl") if !$attribute->isStatic;
2073                                         $functionName = "${implementedBy}::${functionName}";
2074                                     } elsif ($attribute->isStatic) {
2075                                         $functionName = "${implClassName}::${functionName}";
2076                                     } else {
2077                                         $functionName = "impl->${functionName}";
2078                                     }
2079
2080                                     unshift(@arguments, GenerateCallWith($attribute->signature->extendedAttributes->{"CallWith"}, \@implContent, ""));
2081
2082                                     push(@arguments, "ec") if @{$attribute->setterExceptions};
2083                                     push(@implContent, "    ${functionName}(" . join(", ", @arguments) . ");\n");
2084                                     push(@implContent, "    setDOMException(exec, ec);\n") if @{$attribute->setterExceptions};
2085                                 }
2086                             }
2087
2088                         push(@implContent, "}\n\n");
2089                         push(@implContent, "#endif\n") if $attributeConditionalString;
2090                         push(@implContent, "\n");
2091                     }
2092                 }
2093             }
2094
2095             if ($dataNode->extendedAttributes->{"ReplaceableConstructor"}) {
2096                 my $constructorFunctionName = "setJS" . $interfaceName . "Constructor";
2097
2098                 push(@implContent, "void ${constructorFunctionName}(ExecState* exec, JSObject* thisObject, JSValue value)\n");
2099                 push(@implContent, "{\n");
2100                 if ($dataNode->extendedAttributes->{"CheckSecurity"}) {
2101                     if ($interfaceName eq "DOMWindow") {
2102                         push(@implContent, "    if (!jsCast<$className*>(thisObject)->allowsAccessFrom(exec))\n");
2103                     } else {
2104                         push(@implContent, "    if (!shouldAllowAccessToFrame(exec, jsCast<$className*>(thisObject)->impl()->frame()))\n");
2105                     }
2106                     push(@implContent, "        return;\n");
2107                 }
2108
2109                 push(@implContent, "    // Shadowing a built-in constructor\n");
2110
2111                 if ($interfaceName eq "DOMWindow") {
2112                     push(@implContent, "    jsCast<$className*>(thisObject)->putDirect(exec->globalData(), exec->propertyNames().constructor, value);\n");
2113                 } else {
2114                     die "No way to handle interface with ReplaceableConstructor extended attribute: $interfaceName";
2115                 }
2116                 push(@implContent, "}\n\n");
2117             }        
2118         }
2119     }
2120
2121     if (($dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"}) && !$dataNode->extendedAttributes->{"CustomEnumerateProperty"}) {
2122         push(@implContent, "void ${className}::getOwnPropertyNames(JSObject* object, ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)\n");
2123         push(@implContent, "{\n");
2124         push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(object);\n");
2125         push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
2126         if ($dataNode->extendedAttributes->{"IndexedGetter"} || $dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
2127             push(@implContent, "    for (unsigned i = 0; i < static_cast<${implClassName}*>(thisObject->impl())->length(); ++i)\n");
2128             push(@implContent, "        propertyNames.add(Identifier::from(exec, i));\n");
2129         }
2130         push(@implContent, "     Base::getOwnPropertyNames(thisObject, exec, propertyNames, mode);\n");
2131         push(@implContent, "}\n\n");
2132     }
2133
2134     if (!$dataNode->extendedAttributes->{"OmitConstructor"}) {
2135         push(@implContent, "JSValue ${className}::getConstructor(ExecState* exec, JSGlobalObject* globalObject)\n{\n");
2136         push(@implContent, "    return getDOMConstructor<${className}Constructor>(exec, jsCast<JSDOMGlobalObject*>(globalObject));\n");
2137         push(@implContent, "}\n\n");
2138     }
2139
2140     # Functions
2141     if ($numFunctions > 0) {
2142         foreach my $function (@{$dataNode->functions}) {
2143             AddIncludesForTypeInImpl($function->signature->type);
2144
2145             my $isCustom = $function->signature->extendedAttributes->{"Custom"} || $function->signature->extendedAttributes->{"JSCustom"};
2146             my $isOverloaded = $function->{overloads} && @{$function->{overloads}} > 1;
2147
2148             next if $isCustom && $isOverloaded && $function->{overloadIndex} > 1;
2149
2150             my $functionName = GetFunctionName($className, $function);
2151
2152             my $conditional = $function->signature->extendedAttributes->{"Conditional"};
2153             if ($conditional) {
2154                 my $conditionalString = $codeGenerator->GenerateConditionalStringFromAttributeValue($conditional);
2155                 push(@implContent, "#if ${conditionalString}\n");
2156             }
2157
2158
2159             if (!$isCustom && $isOverloaded) {
2160                 # Append a number to an overloaded method's name to make it unique:
2161                 $functionName = $functionName . $function->{overloadIndex};
2162                 # Make this function static to avoid compiler warnings, since we
2163                 # don't generate a prototype for it in the header.
2164                 push(@implContent, "static ");
2165             }
2166
2167             my $functionImplementationName = $function->signature->extendedAttributes->{"ImplementedAs"} || $codeGenerator->WK_lcfirst($function->signature->name);
2168
2169             push(@implContent, "EncodedJSValue JSC_HOST_CALL ${functionName}(ExecState* exec)\n");
2170             push(@implContent, "{\n");
2171
2172             $implIncludes{"<runtime/Error.h>"} = 1;
2173
2174             if ($function->isStatic) {
2175                 if ($isCustom) {
2176                     GenerateArgumentsCountCheck(\@implContent, $function, $dataNode);
2177                     push(@implContent, "    return JSValue::encode(${className}::" . $functionImplementationName . "(exec));\n");
2178                 } else {
2179                     GenerateArgumentsCountCheck(\@implContent, $function, $dataNode);
2180
2181                     if (@{$function->raisesExceptions}) {
2182                         push(@implContent, "    ExceptionCode ec = 0;\n");
2183                     }
2184
2185                     my $numParameters = @{$function->parameters};
2186                     my ($functionString, $dummy) = GenerateParametersCheck(\@implContent, $function, $dataNode, $numParameters, $implClassName, $functionImplementationName, $svgPropertyType, $svgPropertyOrListPropertyType, $svgListPropertyType);
2187                     GenerateImplementationFunctionCall($function, $functionString, "    ", $svgPropertyType, $implClassName);
2188                 }
2189             } else {
2190                 if ($interfaceName eq "DOMWindow") {
2191                     push(@implContent, "    $className* castedThis = toJSDOMWindow(exec->hostThisValue().toThisObject(exec));\n");
2192                     push(@implContent, "    if (!castedThis)\n");
2193                     push(@implContent, "        return throwVMTypeError(exec);\n");
2194                 } elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
2195                     push(@implContent, "    $className* castedThis = to${className}(exec->hostThisValue().toThisObject(exec));\n");
2196                     push(@implContent, "    if (!castedThis)\n");
2197                     push(@implContent, "        return throwVMTypeError(exec);\n");
2198                 } else {
2199                     push(@implContent, "    JSValue thisValue = exec->hostThisValue();\n");
2200                     push(@implContent, "    if (!thisValue.inherits(&${className}::s_info))\n");
2201                     push(@implContent, "        return throwVMTypeError(exec);\n");
2202                     push(@implContent, "    $className* castedThis = jsCast<$className*>(asObject(thisValue));\n");
2203                 }
2204
2205                 push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(castedThis, &${className}::s_info);\n");
2206
2207                 if ($dataNode->extendedAttributes->{"CheckSecurity"} and
2208                     !$function->signature->extendedAttributes->{"DoNotCheckSecurity"}) {
2209                     push(@implContent, "    if (!castedThis->allowsAccessFrom(exec))\n");
2210                     push(@implContent, "        return JSValue::encode(jsUndefined());\n");
2211                 }
2212
2213                 if ($isCustom) {
2214                     push(@implContent, "    return JSValue::encode(castedThis->" . $functionImplementationName . "(exec));\n");
2215                 } else {
2216                     push(@implContent, "    $implType* impl = static_cast<$implType*>(castedThis->impl());\n");
2217                     if ($svgPropertyType) {
2218                         push(@implContent, "    if (impl->isReadOnly()) {\n");
2219                         push(@implContent, "        setDOMException(exec, NO_MODIFICATION_ALLOWED_ERR);\n");
2220                         push(@implContent, "        return JSValue::encode(jsUndefined());\n");
2221                         push(@implContent, "    }\n");
2222                         push(@implContent, "    $svgPropertyType& podImpl = impl->propertyReference();\n");
2223                         $implIncludes{"ExceptionCode.h"} = 1;
2224                     }
2225
2226                     # For compatibility with legacy content, the EventListener calls are generated without GenerateArgumentsCountCheck.
2227                     if ($function->signature->name eq "addEventListener") {
2228                         push(@implContent, GenerateEventListenerCall($className, "add"));
2229                     } elsif ($function->signature->name eq "removeEventListener") {
2230                         push(@implContent, GenerateEventListenerCall($className, "remove"));
2231                     } else {
2232                         GenerateArgumentsCountCheck(\@implContent, $function, $dataNode);
2233
2234                         if (@{$function->raisesExceptions}) {
2235                             push(@implContent, "    ExceptionCode ec = 0;\n");
2236                         }
2237
2238                         if ($function->signature->extendedAttributes->{"CheckSecurityForNode"}) {
2239                             push(@implContent, "    if (!shouldAllowAccessToNode(exec, impl->" . $function->signature->name . "(" . (@{$function->raisesExceptions} ? "ec" : "") .")))\n");
2240                             push(@implContent, "        return JSValue::encode(jsNull());\n");
2241                             $implIncludes{"JSDOMBinding.h"} = 1;
2242                         }
2243
2244                         my $numParameters = @{$function->parameters};
2245                         my ($functionString, $dummy) = GenerateParametersCheck(\@implContent, $function, $dataNode, $numParameters, $implClassName, $functionImplementationName, $svgPropertyType, $svgPropertyOrListPropertyType, $svgListPropertyType);
2246                         GenerateImplementationFunctionCall($function, $functionString, "    ", $svgPropertyType, $implClassName);
2247                     }
2248                 }
2249             }
2250
2251             push(@implContent, "}\n\n");
2252
2253             if (!$isCustom && $isOverloaded && $function->{overloadIndex} == @{$function->{overloads}}) {
2254                 # Generate a function dispatching call to the rest of the overloads.
2255                 GenerateOverloadedFunction($function, $dataNode, $implClassName);
2256             }
2257
2258             push(@implContent, "#endif\n\n") if $conditional;
2259         }
2260         
2261 #if ENABLE(TIZEN_INDEXED_DATABASE)
2262     }
2263     if ($needsMarkChildren && !$dataNode->extendedAttributes->{"JSCustomMarkFunction"}) {
2264         push(@implContent, "void ${className}::visitChildren(JSCell* cell, SlotVisitor& visitor)\n");
2265         push(@implContent, "{\n");
2266         push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
2267         push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
2268         push(@implContent, "    COMPILE_ASSERT(StructureFlags & OverridesVisitChildren, OverridesVisitChildrenWithoutSettingFlag);\n");
2269         push(@implContent, "    ASSERT(thisObject->structure()->typeInfo().overridesVisitChildren());\n");
2270         push(@implContent, "    Base::visitChildren(thisObject, visitor);\n");
2271         if ($dataNode->extendedAttributes->{"EventTarget"}) {
2272             push(@implContent, "    thisObject->impl()->visitJSEventListeners(visitor);\n");
2273         }
2274         if ($numCachedAttributes > 0) {
2275             foreach (@{$dataNode->attributes}) {
2276                 my $attribute = $_;
2277                 if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) {
2278                     push(@implContent, "    if (thisObject->m_" . $attribute->signature->name . ")\n");
2279                     push(@implContent, "        visitor.append(&thisObject->m_" . $attribute->signature->name . ");\n");
2280                 }
2281             }
2282         }
2283         push(@implContent, "}\n\n");
2284         # Cached attributes are indeed allowed when there is a custom mark/visitChildren function.
2285         # The custom function must make sure to account for the cached attribute.
2286         # Uncomment the below line to temporarily enforce generated mark functions when cached attributes are present.
2287         # die "Can't generate binding for class with cached attribute and custom mark." if (($numCachedAttributes > 0) and ($dataNode->extendedAttributes->{"JSCustomMarkFunction"}));
2288     }
2289 #else
2290 #        if ($needsMarkChildren && !$dataNode->extendedAttributes->{"JSCustomMarkFunction"}) {
2291 #           push(@implContent, "void ${className}::visitChildren(JSCell* cell, SlotVisitor& visitor)\n");
2292 #           push(@implContent, "{\n");
2293 #           push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
2294 #           push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
2295 #           push(@implContent, "    COMPILE_ASSERT(StructureFlags & OverridesVisitChildren, OverridesVisitChildrenWithoutSettingFlag);\n");
2296 #           push(@implContent, "    ASSERT(thisObject->structure()->typeInfo().overridesVisitChildren());\n");
2297 #           push(@implContent, "    Base::visitChildren(thisObject, visitor);\n");
2298 #           if ($dataNode->extendedAttributes->{"EventTarget"}) {
2299 #               push(@implContent, "    thisObject->impl()->visitJSEventListeners(visitor);\n");
2300 #           }
2301 #           if ($numCachedAttributes > 0) {
2302 #               foreach (@{$dataNode->attributes}) {
2303 #                   my $attribute = $_;
2304 #                   if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) {
2305 #                       push(@implContent, "    if (thisObject->m_" . $attribute->signature->name . ")\n");
2306 #                       push(@implContent, "        visitor.append(&thisObject->m_" . $attribute->signature->name . ");\n");
2307 #                   }
2308 #               }
2309 #           }
2310 #           push(@implContent, "}\n\n");
2311 #       }
2312 #       # Cached attributes are indeed allowed when there is a custom mark/visitChildren function.
2313 #       # The custom function must make sure to account for the cached attribute.
2314 #       # Uncomment the below line to temporarily enforce generated mark functions when cached attributes are present.
2315 #       # die "Can't generate binding for class with cached attribute and custom mark." if (($numCachedAttributes > 0) and ($dataNode->extendedAttributes->{"JSCustomMarkFunction"}));
2316 #   }
2317 #endif // TIZEN_INDEXED_DATABASE
2318
2319     # Cached attributes are indeed allowed when there is a custom mark/visitChildren function.
2320     # The custom function must make sure to account for the cached attribute.
2321     # Uncomment the below line to temporarily enforce generated mark functions when cached attributes are present.
2322     # die "Can't generate binding for class with cached attribute and custom mark." if (($numCachedAttributes > 0) and ($dataNode->extendedAttributes->{"JSCustomMarkFunction"}));
2323
2324     if ($numConstants > 0) {
2325         push(@implContent, "// Constant getters\n\n");
2326
2327         foreach my $constant (@{$dataNode->constants}) {
2328             my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($constant->name);
2329             my $conditional = $constant->extendedAttributes->{"Conditional"};
2330
2331             if ($conditional) {
2332                 my $conditionalString = $codeGenerator->GenerateConditionalStringFromAttributeValue($conditional);
2333                 push(@implContent, "#if ${conditionalString}\n");
2334             }
2335
2336             # FIXME: this casts into int to match our previous behavior which turned 0xFFFFFFFF in -1 for NodeFilter.SHOW_ALL
2337             push(@implContent, "JSValue ${getter}(ExecState* exec, JSValue, PropertyName)\n");
2338             push(@implContent, "{\n");
2339             if ($constant->type eq "DOMString") {
2340                 push(@implContent, "    return jsStringOrNull(exec, String(" . $constant->value . "));\n");
2341             } else {
2342                 push(@implContent, "    UNUSED_PARAM(exec);\n");
2343                 push(@implContent, "    return jsNumber(static_cast<int>(" . $constant->value . "));\n");
2344             }
2345             push(@implContent, "}\n\n");
2346             push(@implContent, "#endif\n") if $conditional;
2347         }
2348     }
2349
2350     if ($dataNode->extendedAttributes->{"IndexedGetter"}) {
2351         push(@implContent, "\nJSValue ${className}::indexGetter(ExecState* exec, JSValue slotBase, unsigned index)\n");
2352         push(@implContent, "{\n");
2353         push(@implContent, "    ${className}* thisObj = jsCast<$className*>(asObject(slotBase));\n");
2354         push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObj, &s_info);\n");
2355         if (IndexGetterReturnsStrings($implClassName)) {
2356             $implIncludes{"KURL.h"} = 1;
2357             push(@implContent, "    return jsStringOrUndefined(exec, thisObj->impl()->item(index));\n");
2358         } else {
2359             push(@implContent, "    return toJS(exec, thisObj->globalObject(), static_cast<$implClassName*>(thisObj->impl())->item(index));\n");
2360         }
2361         push(@implContent, "}\n\n");
2362         if ($interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection" or $interfaceName eq "RadioNodeList") {
2363             $implIncludes{"JSNode.h"} = 1;
2364             $implIncludes{"Node.h"} = 1;
2365         }
2366     }
2367
2368     if ($dataNode->extendedAttributes->{"NumericIndexedGetter"}) {
2369         push(@implContent, "\nJSValue ${className}::getByIndex(ExecState*, unsigned index)\n");
2370         push(@implContent, "{\n");
2371         push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(this, &s_info);\n");
2372         push(@implContent, "    double result = static_cast<$implClassName*>(impl())->item(index);\n");
2373         # jsNumber conversion doesn't suppress signalling NaNs, so enforce that here.
2374         push(@implContent, "    if (isnan(result))\n");
2375         push(@implContent, "        return jsNaN();\n");
2376         push(@implContent, "    return JSValue(result);\n");
2377         push(@implContent, "}\n\n");
2378         if ($interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection") {
2379             $implIncludes{"JSNode.h"} = 1;
2380             $implIncludes{"Node.h"} = 1;
2381         }
2382     }
2383
2384     if ($interfaceName eq "HTMLPropertiesCollection") {
2385         if ($dataNode->extendedAttributes->{"NamedGetter"}) {
2386             push(@implContent, "bool ${className}::canGetItemsForName(ExecState*, $implClassName* collection, PropertyName propertyName)\n");
2387             push(@implContent, "{\n");
2388             push(@implContent, "    return collection->hasNamedItem(propertyNameToAtomicString(propertyName));\n");
2389             push(@implContent, "}\n\n");
2390             push(@implContent, "JSValue ${className}::nameGetter(ExecState* exec, JSValue slotBase, PropertyName propertyName)\n");
2391             push(@implContent, "{\n");
2392             push(@implContent, "    ${className}* thisObj = jsCast<$className*>(asObject(slotBase));\n");
2393             push(@implContent, "    return toJS(exec, thisObj->globalObject(), static_cast<$implClassName*>(thisObj->impl())->namedItem(propertyNameToAtomicString(propertyName)));\n");
2394             push(@implContent, "}\n\n");
2395         }
2396     }
2397
2398     if ((!$hasParent && !GetCustomIsReachable($dataNode))|| GetGenerateIsReachable($dataNode) || $dataNode->extendedAttributes->{"ActiveDOMObject"}) {
2399         push(@implContent, "static inline bool isObservable(JS${implClassName}* js${implClassName})\n");
2400         push(@implContent, "{\n");
2401         push(@implContent, "    if (js${implClassName}->hasCustomProperties())\n");
2402         push(@implContent, "        return true;\n");
2403         if ($eventTarget) {
2404             push(@implContent, "    if (js${implClassName}->impl()->hasEventListeners())\n");
2405             push(@implContent, "        return true;\n");
2406         }
2407         push(@implContent, "    return false;\n");
2408         push(@implContent, "}\n\n");
2409
2410         push(@implContent, "bool JS${implClassName}Owner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor)\n");
2411         push(@implContent, "{\n");
2412         push(@implContent, "    JS${implClassName}* js${implClassName} = jsCast<JS${implClassName}*>(handle.get().asCell());\n");
2413         # All ActiveDOMObjects implement hasPendingActivity(), but not all of them
2414         # increment their C++ reference counts when hasPendingActivity() becomes
2415         # true. As a result, ActiveDOMObjects can be prematurely destroyed before
2416         # their pending activities complete. To wallpaper over this bug, JavaScript
2417         # wrappers unconditionally keep ActiveDOMObjects with pending activity alive.
2418         # FIXME: Fix this lifetime issue in the DOM, and move this hasPendingActivity
2419         # check below the isObservable check.
2420         if ($dataNode->extendedAttributes->{"ActiveDOMObject"}) {
2421             push(@implContent, "    if (js${implClassName}->impl()->hasPendingActivity())\n");
2422             push(@implContent, "        return true;\n");
2423         }
2424         push(@implContent, "    if (!isObservable(js${implClassName}))\n");
2425         push(@implContent, "        return false;\n");
2426         if (GetGenerateIsReachable($dataNode)) {
2427             my $rootString;
2428             if (GetGenerateIsReachable($dataNode) eq "Impl") {
2429                 $rootString  = "    ${implType}* root = js${implClassName}->impl();\n";
2430             } elsif (GetGenerateIsReachable($dataNode) eq "ImplContext") {
2431                 $rootString  = "    WebGLRenderingContext* root = js${implClassName}->impl()->context();\n";
2432             } elsif (GetGenerateIsReachable($dataNode) eq "ImplFrame") {
2433                 $rootString  = "    Frame* root = js${implClassName}->impl()->frame();\n";
2434                 $rootString .= "    if (!root)\n";
2435                 $rootString .= "        return false;\n";
2436             } elsif (GetGenerateIsReachable($dataNode) eq "ImplDocument") {
2437                 $rootString  = "    Document* root = js${implClassName}->impl()->document();\n";
2438                 $rootString .= "    if (!root)\n";
2439                 $rootString .= "        return false;\n";
2440             } elsif (GetGenerateIsReachable($dataNode) eq "ImplElementRoot") {
2441                 $rootString  = "    Element* element = js${implClassName}->impl()->element();\n";
2442                 $rootString .= "    if (!element)\n";
2443                 $rootString .= "        return false;\n";
2444                 $rootString .= "    void* root = WebCore::root(element);\n";
2445             } elsif ($interfaceName eq "CanvasRenderingContext") {
2446                 $rootString  = "    void* root = WebCore::root(js${implClassName}->impl()->canvas());\n";
2447             } elsif (GetGenerateIsReachable($dataNode) eq "ImplBaseRoot") {
2448                 $rootString  = "    void* root = WebCore::root(js${implClassName}->impl()->base());\n";
2449             } else {
2450                 $rootString  = "    void* root = WebCore::root(js${implClassName}->impl());\n";
2451             }
2452
2453             push(@implContent, $rootString);
2454             push(@implContent, "    return visitor.containsOpaqueRoot(root);\n");
2455         } else {
2456             push(@implContent, "    UNUSED_PARAM(visitor);\n");
2457             push(@implContent, "    return false;\n");
2458         }
2459         push(@implContent, "}\n\n");
2460     }
2461
2462     if (!$dataNode->extendedAttributes->{"JSCustomFinalize"} &&
2463         (!$hasParent ||
2464          GetGenerateIsReachable($dataNode) ||
2465          GetCustomIsReachable($dataNode) ||
2466          $dataNode->extendedAttributes->{"ActiveDOMObject"})) {
2467         push(@implContent, "void JS${implClassName}Owner::finalize(JSC::Handle<JSC::Unknown> handle, void* context)\n");
2468         push(@implContent, "{\n");
2469         push(@implContent, "    JS${implClassName}* js${implClassName} = jsCast<JS${implClassName}*>(handle.get().asCell());\n");
2470         push(@implContent, "    DOMWrapperWorld* world = static_cast<DOMWrapperWorld*>(context);\n");
2471         push(@implContent, "    uncacheWrapper(world, js${implClassName}->impl(), js${implClassName});\n");
2472         push(@implContent, "    js${implClassName}->releaseImpl();\n");
2473         push(@implContent, "}\n\n");
2474     }
2475
2476     if (ShouldGenerateToJSImplementation($hasParent, $dataNode)) {
2477         push(@implContent, "JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, $implType* impl)\n");
2478         push(@implContent, "{\n");
2479         if ($svgPropertyType) {
2480             push(@implContent, "    return wrap<$className, $implType>(exec, globalObject, impl);\n");
2481         } else {
2482             push(@implContent, "    return wrap<$className>(exec, globalObject, impl);\n");
2483         }
2484         push(@implContent, "}\n\n");
2485     }
2486
2487     if ((!$hasParent or $dataNode->extendedAttributes->{"JSGenerateToNativeObject"}) and !$dataNode->extendedAttributes->{"JSCustomToNativeObject"}) {
2488         push(@implContent, "$implType* to${interfaceName}(JSC::JSValue value)\n");
2489         push(@implContent, "{\n");
2490         push(@implContent, "    return value.inherits(&${className}::s_info) ? jsCast<$className*>(asObject(value))->impl() : 0");
2491         push(@implContent, ";\n}\n");
2492     }
2493
2494     push(@implContent, "\n}\n");
2495
2496     my $conditionalString = $codeGenerator->GenerateConditionalString($dataNode);
2497     push(@implContent, "\n#endif // ${conditionalString}\n") if $conditionalString;
2498 }
2499
2500 sub GenerateCallWith
2501 {
2502     my $callWith = shift;
2503     return () unless $callWith;
2504     my $outputArray = shift;
2505     my $returnValue = shift;
2506     my $function = shift;
2507
2508     my @callWithArgs;
2509     if ($codeGenerator->ExtendedAttributeContains($callWith, "ScriptState")) {
2510         push(@callWithArgs, "exec");
2511     }
2512     if ($codeGenerator->ExtendedAttributeContains($callWith, "ScriptExecutionContext")) {
2513         push(@$outputArray, "    ScriptExecutionContext* scriptContext = jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject())->scriptExecutionContext();\n");
2514         push(@$outputArray, "    if (!scriptContext)\n");
2515         push(@$outputArray, "        return" . ($returnValue ? " " . $returnValue : "") . ";\n");
2516         push(@callWithArgs, "scriptContext");
2517     }
2518     if ($function and $codeGenerator->ExtendedAttributeContains($callWith, "ScriptArguments")) {
2519         push(@$outputArray, "    RefPtr<ScriptArguments> scriptArguments(createScriptArguments(exec, " . @{$function->parameters} . "));\n");
2520         $implIncludes{"ScriptArguments.h"} = 1;
2521         push(@callWithArgs, "scriptArguments");
2522     }
2523     if ($codeGenerator->ExtendedAttributeContains($callWith, "CallStack")) {
2524         push(@$outputArray, "    RefPtr<ScriptCallStack> callStack(createScriptCallStackForInspector(exec));\n");
2525         $implIncludes{"ScriptCallStack.h"} = 1;
2526         $implIncludes{"ScriptCallStackFactory.h"} = 1;
2527         push(@callWithArgs, "callStack");
2528     }
2529     return @callWithArgs;
2530 }
2531
2532 sub GenerateArgumentsCountCheck
2533 {
2534     my $outputArray = shift;
2535     my $function = shift;
2536     my $dataNode = shift;
2537
2538     my $numMandatoryParams = @{$function->parameters};
2539     foreach my $param (reverse(@{$function->parameters})) {
2540         if ($param->extendedAttributes->{"Optional"}) {
2541             $numMandatoryParams--;
2542         } else {
2543             last;
2544         }
2545     }
2546     if ($numMandatoryParams >= 1)
2547     {
2548         push(@$outputArray, "    if (exec->argumentCount() < $numMandatoryParams)\n");
2549         push(@$outputArray, "        return throwVMError(exec, createNotEnoughArgumentsError(exec));\n");
2550     }
2551 }
2552
2553 sub GenerateParametersCheck
2554 {
2555     my $outputArray = shift;
2556     my $function = shift;
2557     my $dataNode = shift;
2558     my $numParameters = shift;
2559     my $implClassName = shift;
2560     my $functionImplementationName = shift;
2561     my $svgPropertyType = shift;
2562     my $svgPropertyOrListPropertyType = shift;
2563     my $svgListPropertyType = shift;
2564
2565     my $argsIndex = 0;
2566     my $hasOptionalArguments = 0;
2567
2568     my @arguments;
2569     my $functionName;
2570     my $implementedBy = $function->signature->extendedAttributes->{"ImplementedBy"};
2571     if ($implementedBy) {
2572         AddToImplIncludes("${implementedBy}.h");
2573         unshift(@arguments, "impl") if !$function->isStatic;
2574         $functionName = "${implementedBy}::${functionImplementationName}";
2575     } elsif ($function->isStatic) {
2576         $functionName = "${implClassName}::${functionImplementationName}";
2577     } elsif ($svgPropertyOrListPropertyType and !$svgListPropertyType) {
2578         $functionName = "podImpl.${functionImplementationName}";
2579     } else {
2580         $functionName = "impl->${functionImplementationName}";
2581     }
2582
2583     if (!$function->signature->extendedAttributes->{"Constructor"}) {
2584         push(@arguments, GenerateCallWith($function->signature->extendedAttributes->{"CallWith"}, \@$outputArray, "JSValue::encode(jsUndefined())", $function));
2585     }
2586
2587     $implIncludes{"ExceptionCode.h"} = 1;
2588     $implIncludes{"JSDOMBinding.h"} = 1;
2589
2590     foreach my $parameter (@{$function->parameters}) {
2591         # Optional arguments with [Optional] should generate an early call with fewer arguments.
2592         # Optional arguments with [Optional=...] should not generate the early call.
2593         my $optional = $parameter->extendedAttributes->{"Optional"};
2594         if ($optional && $optional ne "DefaultIsUndefined" && $optional ne "DefaultIsNullString" && !$parameter->extendedAttributes->{"Callback"}) {
2595             # Generate early call if there are enough parameters.
2596             if (!$hasOptionalArguments) {
2597                 push(@$outputArray, "\n    size_t argsCount = exec->argumentCount();\n");
2598                 $hasOptionalArguments = 1;
2599             }
2600             push(@$outputArray, "    if (argsCount <= $argsIndex) {\n");
2601
2602             my @optionalCallbackArguments = @arguments;
2603             if (@{$function->raisesExceptions}) {
2604                 push @optionalCallbackArguments, "ec";
2605             }
2606             my $functionString = "$functionName(" . join(", ", @optionalCallbackArguments) . ")";
2607             GenerateImplementationFunctionCall($function, $functionString, "    " x 2, $svgPropertyType, $implClassName);
2608             push(@$outputArray, "    }\n\n");
2609         }
2610
2611         my $name = $parameter->name;
2612         my $argType = $codeGenerator->StripModule($parameter->type);
2613
2614         if ($argType eq "XPathNSResolver") {
2615             push(@$outputArray, "    RefPtr<XPathNSResolver> customResolver;\n");
2616             push(@$outputArray, "    XPathNSResolver* resolver = toXPathNSResolver(exec->argument($argsIndex));\n");
2617             push(@$outputArray, "    if (!resolver) {\n");
2618             push(@$outputArray, "        customResolver = JSCustomXPathNSResolver::create(exec, exec->argument($argsIndex));\n");
2619             push(@$outputArray, "        if (exec->hadException())\n");
2620             push(@$outputArray, "            return JSValue::encode(jsUndefined());\n");
2621             push(@$outputArray, "        resolver = customResolver.get();\n");
2622             push(@$outputArray, "    }\n");
2623         } elsif ($parameter->extendedAttributes->{"Callback"}) {
2624             my $callbackClassName = GetCallbackClassName($argType);
2625             $implIncludes{"$callbackClassName.h"} = 1;
2626             if ($optional) {
2627                 push(@$outputArray, "    RefPtr<$argType> $name;\n");
2628                 push(@$outputArray, "    if (exec->argumentCount() > $argsIndex && !exec->argument($argsIndex).isUndefinedOrNull()) {\n");
2629                 push(@$outputArray, "        if (!exec->argument($argsIndex).isFunction()) {\n");
2630                 push(@$outputArray, "            setDOMException(exec, TYPE_MISMATCH_ERR);\n");
2631                 push(@$outputArray, "            return JSValue::encode(jsUndefined());\n");
2632                 push(@$outputArray, "        }\n");
2633                 push(@$outputArray, "        $name = ${callbackClassName}::create(asObject(exec->argument($argsIndex)), castedThis->globalObject());\n");
2634                 push(@$outputArray, "    }\n");
2635             } else {
2636                 push(@$outputArray, "    if (exec->argumentCount() <= $argsIndex || !exec->argument($argsIndex).isFunction()) {\n");
2637                 push(@$outputArray, "        setDOMException(exec, TYPE_MISMATCH_ERR);\n");
2638                 push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
2639                 push(@$outputArray, "    }\n");
2640                 push(@$outputArray, "    RefPtr<$argType> $name = ${callbackClassName}::create(asObject(exec->argument($argsIndex)), castedThis->globalObject());\n");
2641             }
2642         } elsif ($parameter->extendedAttributes->{"Clamp"}) {
2643                 my $nativeValue = "${name}NativeValue";
2644                 push(@$outputArray, "    $argType $name = 0;\n");
2645                 push(@$outputArray, "    double $nativeValue = exec->argument($argsIndex).toNumber(exec);\n");
2646                 push(@$outputArray, "    if (exec->hadException())\n");
2647                 push(@$outputArray, "        return JSValue::encode(jsUndefined());\n\n");
2648                 push(@$outputArray, "    if (!isnan(objArgsShortNativeValue))\n");
2649                 push(@$outputArray, "        $name = clampTo<$argType>($nativeValue);\n\n");
2650         } else {
2651             # If the "StrictTypeChecking" extended attribute is present, and the argument's type is an
2652             # interface type, then if the incoming value does not implement that interface, a TypeError
2653             # is thrown rather than silently passing NULL to the C++ code.
2654             # Per the Web IDL and ECMAScript semantics, incoming values can always be converted to both
2655             # strings and numbers, so do not throw TypeError if the argument is of these types.
2656             if ($function->signature->extendedAttributes->{"StrictTypeChecking"}) {
2657                 $implIncludes{"<runtime/Error.h>"} = 1;
2658
2659                 my $argValue = "exec->argument($argsIndex)";
2660                 if (!IsNativeType($argType)) {
2661                     push(@$outputArray, "    if (exec->argumentCount() > $argsIndex && !${argValue}.isUndefinedOrNull() && !${argValue}.inherits(&JS${argType}::s_info))\n");
2662                     push(@$outputArray, "        return throwVMTypeError(exec);\n");
2663                 }
2664             }
2665
2666             my $parameterDefaultPolicy = "DefaultIsUndefined";
2667             if ($optional and $optional eq "DefaultIsNullString") {
2668                 $parameterDefaultPolicy = "DefaultIsNullString";
2669             }
2670
2671             push(@$outputArray, "    " . GetNativeTypeFromSignature($parameter) . " $name(" . JSValueToNative($parameter, "MAYBE_MISSING_PARAMETER(exec, $argsIndex, $parameterDefaultPolicy)") . ");\n");
2672
2673             # If a parameter is "an index" and it's negative it should throw an INDEX_SIZE_ERR exception.
2674             # But this needs to be done in the bindings, because the type is unsigned and the fact that it
2675             # was negative will be lost by the time we're inside the DOM.
2676             if ($parameter->extendedAttributes->{"IsIndex"}) {
2677                 push(@$outputArray, "    if ($name < 0) {\n");
2678                 push(@$outputArray, "        setDOMException(exec, INDEX_SIZE_ERR);\n");
2679                 push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
2680                 push(@$outputArray, "    }\n");
2681             }
2682
2683 #if ENABLE(TIZEN_INDEXED_DATABASE)
2684             if (TypeCanFailConversion($parameter)) {
2685                 push(@implContent, "    if (!$name) {\n");
2686                 push(@implContent, "        setDOMException(exec, TYPE_MISMATCH_ERR);\n");
2687                 push(@implContent, "        return JSValue::encode(jsUndefined());\n");
2688                 push(@implContent, "    }\n");
2689             } else {
2690                 # Check if the type conversion succeeded.
2691                 push(@$outputArray, "    if (exec->hadException())\n");
2692                 push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
2693             }
2694 #else
2695 #            # Check if the type conversion succeeded.
2696 #            push(@$outputArray, "    if (exec->hadException())\n");
2697 #            push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
2698 #endif // TIZEN_INDEXED_DATABASE
2699
2700             if ($codeGenerator->IsSVGTypeNeedingTearOff($argType) and not $implClassName =~ /List$/) {
2701                 push(@$outputArray, "    if (!$name) {\n");
2702                 push(@$outputArray, "        setDOMException(exec, TYPE_MISMATCH_ERR);\n");
2703                 push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
2704                 push(@$outputArray, "    }\n");
2705             }
2706         }
2707
2708 #if ENABLE(TIZEN_INDEXED_DATABASE)
2709         if ($argType eq "IDBKey" or $argType eq "NodeFilter") {
2710 #else
2711 #        if ($argType eq "NodeFilter") {
2712 #endif // TIZEN_INDEXED_DATABASE
2713             push @arguments, "$name.get()";
2714         } elsif ($codeGenerator->IsSVGTypeNeedingTearOff($argType) and not $implClassName =~ /List$/) {
2715             push @arguments, "$name->propertyReference()";
2716         } else {
2717             push @arguments, $name;
2718         }
2719         $argsIndex++;
2720     }
2721
2722     if (@{$function->raisesExceptions}) {
2723         push @arguments, "ec";
2724     }
2725     return ("$functionName(" . join(", ", @arguments) . ")", scalar @arguments);
2726 }
2727
2728 sub GenerateCallbackHeader
2729 {
2730     my $object = shift;
2731     my $dataNode = shift;
2732
2733     my $interfaceName = $dataNode->name;
2734     my $className = "JS$interfaceName";
2735
2736     # - Add default header template and header protection
2737     push(@headerContentHeader, GenerateHeaderContentHeader($dataNode));
2738
2739     $headerIncludes{"ActiveDOMCallback.h"} = 1;
2740     $headerIncludes{"$interfaceName.h"} = 1;
2741     $headerIncludes{"JSCallbackData.h"} = 1;
2742     $headerIncludes{"<wtf/Forward.h>"} = 1;
2743
2744     push(@headerContent, "\nnamespace WebCore {\n\n");
2745     push(@headerContent, "class $className : public $interfaceName, public ActiveDOMCallback {\n");
2746     push(@headerContent, "public:\n");
2747
2748     # The static create() method.
2749     push(@headerContent, "    static PassRefPtr<$className> create(JSC::JSObject* callback, JSDOMGlobalObject* globalObject)\n");
2750     push(@headerContent, "    {\n");
2751     push(@headerContent, "        return adoptRef(new $className(callback, globalObject));\n");
2752     push(@headerContent, "    }\n\n");
2753
2754     # Destructor
2755     push(@headerContent, "    virtual ~$className();\n");
2756
2757     # Functions
2758     my $numFunctions = @{$dataNode->functions};
2759     if ($numFunctions > 0) {
2760         push(@headerContent, "\n    // Functions\n");
2761         foreach my $function (@{$dataNode->functions}) {
2762             my @params = @{$function->parameters};
2763             if (!$function->signature->extendedAttributes->{"Custom"} &&
2764                 !(GetNativeType($function->signature->type) eq "bool")) {
2765                 push(@headerContent, "    COMPILE_ASSERT(false)");
2766             }
2767
2768             push(@headerContent, "    virtual " . GetNativeTypeForCallbacks($function->signature->type) . " " . $function->signature->name . "(");
2769
2770             my @args = ();
2771             foreach my $param (@params) {
2772                 push(@args, GetNativeTypeForCallbacks($param->type) . " " . $param->name);
2773             }
2774             push(@headerContent, join(", ", @args));
2775
2776             push(@headerContent, ");\n");
2777         }
2778     }
2779
2780     push(@headerContent, "\nprivate:\n");
2781
2782     # Constructor
2783     push(@headerContent, "    $className(JSC::JSObject* callback, JSDOMGlobalObject*);\n\n");
2784
2785     # Private members
2786     push(@headerContent, "    JSCallbackData* m_data;\n");
2787     push(@headerContent, "};\n\n");
2788
2789     push(@headerContent, "} // namespace WebCore\n\n");
2790     my $conditionalString = $codeGenerator->GenerateConditionalString($dataNode);
2791     push(@headerContent, "#endif // ${conditionalString}\n\n") if $conditionalString;
2792     push(@headerContent, "#endif\n");
2793 }
2794
2795 sub GenerateCallbackImplementation
2796 {
2797     my ($object, $dataNode) = @_;
2798
2799     my $interfaceName = $dataNode->name;
2800     my $className = "JS$interfaceName";
2801
2802     # - Add default header template
2803     push(@implContentHeader, GenerateImplementationContentHeader($dataNode));
2804
2805     $implIncludes{"ScriptExecutionContext.h"} = 1;
2806     $implIncludes{"<runtime/JSLock.h>"} = 1;
2807
2808     @implContent = ();
2809
2810     push(@implContent, "\nusing namespace JSC;\n\n");
2811     push(@implContent, "namespace WebCore {\n\n");
2812
2813     # Constructor
2814     push(@implContent, "${className}::${className}(JSObject* callback, JSDOMGlobalObject* globalObject)\n");
2815     push(@implContent, "    : ActiveDOMCallback(globalObject->scriptExecutionContext())\n");
2816     push(@implContent, "    , m_data(new JSCallbackData(callback, globalObject))\n");
2817     push(@implContent, "{\n");
2818     push(@implContent, "}\n\n");
2819
2820     # Destructor
2821     push(@implContent, "${className}::~${className}()\n");
2822     push(@implContent, "{\n");
2823     push(@implContent, "    ScriptExecutionContext* context = scriptExecutionContext();\n");
2824     push(@implContent, "    // When the context is destroyed, all tasks with a reference to a callback\n");
2825     push(@implContent, "    // should be deleted. So if the context is 0, we are on the context thread.\n");
2826     push(@implContent, "    if (!context || context->isContextThread())\n");
2827     push(@implContent, "        delete m_data;\n");
2828     push(@implContent, "    else\n");
2829     push(@implContent, "        context->postTask(DeleteCallbackDataTask::create(m_data));\n");
2830     push(@implContent, "#ifndef NDEBUG\n");
2831     push(@implContent, "    m_data = 0;\n");
2832     push(@implContent, "#endif\n");
2833     push(@implContent, "}\n");
2834
2835     # Functions
2836     my $numFunctions = @{$dataNode->functions};
2837     if ($numFunctions > 0) {
2838         push(@implContent, "\n// Functions\n");
2839         foreach my $function (@{$dataNode->functions}) {
2840             my @params = @{$function->parameters};
2841             if ($function->signature->extendedAttributes->{"Custom"} ||
2842                 !(GetNativeType($function->signature->type) eq "bool")) {
2843                 next;
2844             }
2845
2846             AddIncludesForTypeInImpl($function->signature->type);
2847             push(@implContent, "\n" . GetNativeTypeForCallbacks($function->signature->type) . " ${className}::" . $function->signature->name . "(");
2848
2849             my @args = ();
2850             my @argsCheck = ();
2851             my $thisType = $function->signature->extendedAttributes->{"PassThisToCallback"};
2852             foreach my $param (@params) {
2853                 my $paramName = $param->name;
2854                 AddIncludesForTypeInImpl($param->type, 1);
2855                 push(@args, GetNativeTypeForCallbacks($param->type) . " " . $paramName);
2856                 if ($thisType and $thisType eq $param->type) {
2857                     push(@argsCheck, <<END);
2858     ASSERT(${paramName});
2859
2860 END
2861                 }
2862             }
2863             push(@implContent, join(", ", @args));
2864             push(@implContent, ")\n");
2865
2866             push(@implContent, "{\n");
2867             push(@implContent, @argsCheck) if @argsCheck;
2868             push(@implContent, "    if (!canInvokeCallback())\n");
2869             push(@implContent, "        return true;\n\n");
2870             push(@implContent, "    RefPtr<$className> protect(this);\n\n");
2871             push(@implContent, "    JSLockHolder lock(m_data->globalObject()->globalData());\n\n");
2872             push(@implContent, "    ExecState* exec = m_data->globalObject()->globalExec();\n");
2873             push(@implContent, "    MarkedArgumentBuffer args;\n");
2874
2875             foreach my $param (@params) {
2876                 my $paramName = $param->name;
2877                 if ($param->type eq "DOMString") {
2878                     push(@implContent, "    args.append(jsString(exec, ${paramName}));\n");
2879                 } elsif ($param->type eq "boolean") {
2880                     push(@implContent, "    args.append(jsBoolean(${paramName}));\n");
2881                 } elsif ($param->type eq "SerializedScriptValue") {
2882                     push(@implContent, "    args.append($paramName ? $paramName->deserialize(exec, m_data->globalObject(), 0) : jsNull());\n");
2883                 } else {
2884                     push(@implContent, "    args.append(toJS(exec, m_data->globalObject(), ${paramName}));\n");
2885                 }
2886             }
2887
2888             push(@implContent, "\n    bool raisedException = false;\n");
2889             if ($thisType) {
2890                 foreach my $param (@params) {
2891                     next if $param->type ne $thisType;
2892                     my $paramName = $param->name;
2893                     push(@implContent, <<END);
2894     JSValue js${paramName} = toJS(exec, m_data->globalObject(), ${paramName});
2895     m_data->invokeCallback(js${paramName}, args, &raisedException);
2896
2897 END
2898                     last;
2899                 }
2900             } else {
2901                 push(@implContent, "    m_data->invokeCallback(args, &raisedException);\n");
2902             }
2903             push(@implContent, "    return !raisedException;\n");
2904             push(@implContent, "}\n");
2905         }
2906     }
2907
2908     push(@implContent, "\n}\n");
2909     my $conditionalString = $codeGenerator->GenerateConditionalString($dataNode);
2910     push(@implContent, "\n#endif // ${conditionalString}\n") if $conditionalString;
2911 }
2912
2913 sub GenerateImplementationFunctionCall()
2914 {
2915     my $function = shift;
2916     my $functionString = shift;
2917     my $indent = shift;
2918     my $svgPropertyType = shift;
2919     my $implClassName = shift;
2920
2921     if ($function->signature->type eq "void") {
2922         push(@implContent, $indent . "$functionString;\n");
2923         push(@implContent, $indent . "setDOMException(exec, ec);\n") if @{$function->raisesExceptions};
2924
2925         if ($svgPropertyType and !$function->isStatic) {
2926             if (@{$function->raisesExceptions}) {
2927                 push(@implContent, $indent . "if (!ec)\n"); 
2928                 push(@implContent, $indent . "    impl->commitChange();\n");
2929             } else {
2930                 push(@implContent, $indent . "impl->commitChange();\n");
2931             }
2932         }
2933
2934         push(@implContent, $indent . "return JSValue::encode(jsUndefined());\n");
2935     } else {
2936         my $thisObject = $function->isStatic ? 0 : "castedThis";
2937         push(@implContent, "\n" . $indent . "JSC::JSValue result = " . NativeToJSValue($function->signature, 1, $implClassName, $functionString, $thisObject) . ";\n");
2938         push(@implContent, $indent . "setDOMException(exec, ec);\n") if @{$function->raisesExceptions};
2939
2940         if ($codeGenerator->ExtendedAttributeContains($function->signature->extendedAttributes->{"CallWith"}, "ScriptState")) {
2941             push(@implContent, $indent . "if (exec->hadException())\n");
2942             push(@implContent, $indent . "    return JSValue::encode(jsUndefined());\n");
2943         }
2944
2945         push(@implContent, $indent . "return JSValue::encode(result);\n");
2946     }
2947 }
2948
2949 sub GetNativeTypeFromSignature
2950 {
2951     my $signature = shift;
2952     my $type = $codeGenerator->StripModule($signature->type);
2953
2954     if ($type eq "unsigned long" and $signature->extendedAttributes->{"IsIndex"}) {
2955         # Special-case index arguments because we need to check that they aren't < 0.
2956         return "int";
2957     }
2958
2959     return GetNativeType($type);
2960 }
2961
2962 my %nativeType = (
2963     "CompareHow" => "Range::CompareHow",
2964     "DOMString" => "const String&",
2965     # FIXME: Add proper support for T[], T[]?, sequence<T>
2966     "DOMString[]" => "RefPtr<DOMStringList>",
2967     "DOMObject" => "ScriptValue",
2968     "NodeFilter" => "RefPtr<NodeFilter>",
2969     "SerializedScriptValue" => "RefPtr<SerializedScriptValue>",
2970     "IDBKey" => "PassRefPtr<IDBKey>",
2971     "Dictionary" => "Dictionary",
2972     "any" => "ScriptValue",
2973     "boolean" => "bool",
2974     "double" => "double",
2975     "float" => "float",
2976     "short" => "short",
2977     "long" => "int",
2978     "unsigned long" => "unsigned",
2979     "unsigned short" => "unsigned short",
2980     "long long" => "long long",
2981     "unsigned long long" => "unsigned long long",
2982     "MediaQueryListListener" => "RefPtr<MediaQueryListListener>",
2983     "DOMTimeStamp" => "DOMTimeStamp",    
2984 );
2985
2986 sub GetNativeType
2987 {
2988     my $type = shift;
2989
2990     my $svgNativeType = $codeGenerator->GetSVGTypeNeedingTearOff($type);
2991     return "${svgNativeType}*" if $svgNativeType;
2992     return "RefPtr<DOMStringList>" if $type eq "DOMStringList" or $type eq "DOMString[]";
2993     return $nativeType{$type} if exists $nativeType{$type};
2994
2995     my $sequenceType = $codeGenerator->GetSequenceType($type);
2996     return "Vector<${sequenceType}>" if $sequenceType;
2997
2998     # For all other types, the native type is a pointer with same type name as the IDL type.
2999     return "${type}*";
3000 }
3001
3002 sub GetNativeTypeForCallbacks
3003 {
3004     my $type = shift;
3005     return "SerializedScriptValue*" if $type eq "SerializedScriptValue";
3006     return "PassRefPtr<DOMStringList>" if $type eq "DOMStringList" or $type eq "DOMString[]";
3007
3008     return GetNativeType($type);
3009 }
3010
3011 sub GetSVGPropertyTypes
3012 {
3013     my $implType = shift;
3014
3015     my $svgPropertyType;
3016     my $svgListPropertyType;
3017     my $svgNativeType;
3018
3019     return ($svgPropertyType, $svgListPropertyType, $svgNativeType) if not $implType =~ /SVG/;
3020     
3021     $svgNativeType = $codeGenerator->GetSVGTypeNeedingTearOff($implType);
3022     return ($svgPropertyType, $svgListPropertyType, $svgNativeType) if not $svgNativeType;
3023
3024     # Append space to avoid compilation errors when using  PassRefPtr<$svgNativeType>
3025     $svgNativeType = "$svgNativeType ";
3026
3027     my $svgWrappedNativeType = $codeGenerator->GetSVGWrappedTypeNeedingTearOff($implType);
3028     if ($svgNativeType =~ /SVGPropertyTearOff/) {
3029         $svgPropertyType = $svgWrappedNativeType;
3030         $headerIncludes{"$svgWrappedNativeType.h"} = 1;
3031         $headerIncludes{"SVGAnimatedPropertyTearOff.h"} = 1;
3032     } elsif ($svgNativeType =~ /SVGListPropertyTearOff/ or $svgNativeType =~ /SVGStaticListPropertyTearOff/) {
3033         $svgListPropertyType = $svgWrappedNativeType;
3034         $headerIncludes{"$svgWrappedNativeType.h"} = 1;
3035         $headerIncludes{"SVGAnimatedListPropertyTearOff.h"} = 1;
3036     } elsif ($svgNativeType =~ /SVGTransformListPropertyTearOff/) {
3037         $svgListPropertyType = $svgWrappedNativeType;
3038         $headerIncludes{"$svgWrappedNativeType.h"} = 1;
3039         $headerIncludes{"SVGAnimatedListPropertyTearOff.h"} = 1;
3040         $headerIncludes{"SVGTransformListPropertyTearOff.h"} = 1;
3041     } elsif ($svgNativeType =~ /SVGPathSegListPropertyTearOff/) {
3042         $svgListPropertyType = $svgWrappedNativeType;
3043         $headerIncludes{"$svgWrappedNativeType.h"} = 1;
3044         $headerIncludes{"SVGAnimatedListPropertyTearOff.h"} = 1;
3045         $headerIncludes{"SVGPathSegListPropertyTearOff.h"} = 1;
3046     }
3047
3048     return ($svgPropertyType, $svgListPropertyType, $svgNativeType);
3049 }
3050
3051 sub IsNativeType
3052 {
3053     my $type = shift;
3054     return exists $nativeType{$type};
3055 }
3056
3057 sub IsArrayType
3058 {
3059     my $type = shift;
3060     # FIXME: Add proper support for T[], T[]?, sequence<T>.
3061     return $type =~ m/\[\]$/;
3062 }
3063
3064 #if ENABLE(TIZEN_INDEXED_DATABASE)
3065 sub TypeCanFailConversion
3066 {
3067     my $signature = shift;
3068
3069     my $type = $codeGenerator->StripModule($signature->type);
3070
3071     return 1 if $type eq "IDBKey";
3072     return 1 if $type eq "SerializedScriptValue";
3073     return 0;
3074 }
3075 #endif // TIZEN_INDEXED_DATABASE
3076
3077 sub JSValueToNative
3078 {
3079     my $signature = shift;
3080     my $value = shift;
3081
3082     my $conditional = $signature->extendedAttributes->{"Conditional"};
3083     my $type = $codeGenerator->StripModule($signature->type);
3084
3085     return "$value.toBoolean()" if $type eq "boolean";
3086     return "$value.toNumber(exec)" if $type eq "double";
3087     return "$value.toFloat(exec)" if $type eq "float";
3088     return "$value.toInt32(exec)" if $type eq "long" or $type eq "short";
3089     return "$value.toUInt32(exec)" if $type eq "unsigned long" or $type eq "unsigned short";
3090     return "static_cast<$type>($value.toInteger(exec))" if $type eq "long long" or $type eq "unsigned long long";
3091
3092     return "valueToDate(exec, $value)" if $type eq "Date";
3093     return "static_cast<Range::CompareHow>($value.toInt32(exec))" if $type eq "CompareHow";
3094
3095     if ($type eq "DOMString") {
3096         # FIXME: This implements [TreatNullAs=NullString] and [TreatUndefinedAs=NullString],
3097         # but the Web IDL spec requires [TreatNullAs=EmptyString] and [TreatUndefinedAs=EmptyString].
3098         if (($signature->extendedAttributes->{"TreatNullAs"} and $signature->extendedAttributes->{"TreatNullAs"} eq "NullString") and ($signature->extendedAttributes->{"TreatUndefinedAs"} and $signature->extendedAttributes->{"TreatUndefinedAs"} eq "NullString")) {
3099             return "valueToStringWithUndefinedOrNullCheck(exec, $value)"
3100         }
3101         if (($signature->extendedAttributes->{"TreatNullAs"} and $signature->extendedAttributes->{"TreatNullAs"} eq "NullString") or $signature->extendedAttributes->{"Reflect"}) {
3102             return "valueToStringWithNullCheck(exec, $value)"
3103         }
3104         # FIXME: Add the case for 'if ($signature->extendedAttributes->{"TreatUndefinedAs"} and $signature->extendedAttributes->{"TreatUndefinedAs"} eq "NullString"))'.
3105         return "ustringToString($value.isEmpty() ? UString() : $value.toString(exec)->value(exec))";
3106     }
3107
3108     if ($type eq "DOMObject" or $type eq "any") {
3109         return "exec->globalData(), $value";
3110     }
3111
3112     if ($type eq "NodeFilter") {
3113         AddToImplIncludes("JS$type.h", $conditional);
3114         return "to$type(exec->globalData(), $value)";
3115     }
3116
3117     if ($type eq "MediaQueryListListener") {
3118         AddToImplIncludes("MediaQueryListListener.h", $conditional);
3119         return "MediaQueryListListener::create(ScriptValue(exec->globalData(), " . $value ."))";
3120     }
3121
3122     if ($type eq "SerializedScriptValue") {
3123         AddToImplIncludes("SerializedScriptValue.h", $conditional);
3124         return "SerializedScriptValue::create(exec, $value, 0, 0)";
3125     }
3126
3127     if ($type eq "IDBKey") {
3128         AddToImplIncludes("IDBBindingUtilities.h", $conditional);
3129         AddToImplIncludes("IDBKey.h", $conditional);
3130         return "createIDBKeyFromValue(exec, $value)";
3131     }
3132
3133     if ($type eq "Dictionary") {
3134         AddToImplIncludes("Dictionary.h", $conditional);
3135         return "exec, $value";
3136     }
3137
3138     if ($type eq "DOMString[]" or $type eq "DOMStringList" ) {
3139 #if ENABLE(TIZEN_INDEXED_DATABASE)
3140         AddToImplIncludes("JSDOMBinding.h", $conditional);
3141         return "jsValueToWebCoreDOMStringList(exec, $value)";
3142 #else
3143         #AddToImplIncludes("JSDOMStringList.h", $conditional);
3144         #return "toDOMStringList($value)";
3145 #endif // TIZEN_INDEXED_DATABASE
3146     }
3147
3148     AddToImplIncludes("HTMLOptionElement.h", $conditional) if $type eq "HTMLOptionElement";
3149     AddToImplIncludes("JSCustomVoidCallback.h", $conditional) if $type eq "VoidCallback";
3150     AddToImplIncludes("Event.h", $conditional) if $type eq "Event";
3151
3152     my $arrayType = $codeGenerator->GetArrayType($type);
3153     if ($arrayType) {
3154         return "toNativeArray<$arrayType>(exec, $value)";
3155     }
3156
3157     my $sequenceType = $codeGenerator->GetSequenceType($type);
3158     if ($sequenceType) {
3159         return "toNativeArray<$sequenceType>(exec, $value)";
3160     }
3161
3162     # Default, assume autogenerated type conversion routines
3163     AddToImplIncludes("JS$type.h", $conditional);
3164     return "to$type($value)";
3165 }
3166
3167 sub NativeToJSValue
3168 {
3169     my $signature = shift;
3170     my $inFunctionCall = shift;
3171     my $implClassName = shift;
3172     my $value = shift;
3173     my $thisValue = shift;
3174
3175     my $conditional = $signature->extendedAttributes->{"Conditional"};
3176     my $type = $codeGenerator->StripModule($signature->type);
3177
3178     return "jsBoolean($value)" if $type eq "boolean";
3179
3180     # Need to check Date type before IsPrimitiveType().
3181     if ($type eq "Date") {
3182         return "jsDateOrNull(exec, $value)";
3183     }
3184
3185     if ($signature->extendedAttributes->{"Reflect"} and ($type eq "unsigned long" or $type eq "unsigned short")) {
3186         $value =~ s/getUnsignedIntegralAttribute/getIntegralAttribute/g;
3187         return "jsNumber(std::max(0, " . $value . "))";
3188     }
3189
3190     if ($codeGenerator->IsPrimitiveType($type) or $type eq "DOMTimeStamp") {
3191         return "jsNumber($value)";
3192     }
3193
3194     if ($codeGenerator->IsStringType($type)) {
3195         AddToImplIncludes("KURL.h", $conditional);
3196         my $conv = $signature->extendedAttributes->{"TreatReturnedNullStringAs"};
3197         if (defined $conv) {
3198             return "jsStringOrNull(exec, $value)" if $conv eq "Null";
3199             return "jsStringOrUndefined(exec, $value)" if $conv eq "Undefined";
3200             return "jsStringOrFalse(exec, $value)" if $conv eq "False";
3201
3202             die "Unknown value for TreatReturnedNullStringAs extended attribute";
3203         }
3204         AddToImplIncludes("<runtime/JSString.h>", $conditional);
3205         return "jsString(exec, $value)";
3206     }
3207
3208     my $globalObject;
3209     if ($thisValue) {
3210         $globalObject = "$thisValue->globalObject()";
3211     }
3212
3213     if ($type eq "CSSStyleDeclaration") {
3214         AddToImplIncludes("StylePropertySet.h", $conditional);
3215     }
3216
3217     if ($type eq "NodeList") {
3218         AddToImplIncludes("NameNodeList.h", $conditional);
3219     }
3220
3221     my $arrayType = $codeGenerator->GetArrayType($type);
3222     if ($arrayType) {
3223         if ($type eq "DOMString[]") {
3224             AddToImplIncludes("JSDOMStringList.h", $conditional);
3225             AddToImplIncludes("DOMStringList.h", $conditional);
3226         } elsif (!$codeGenerator->SkipIncludeHeader($arrayType)) {
3227             AddToImplIncludes("JS$arrayType.h", $conditional);
3228             AddToImplIncludes("$arrayType.h", $conditional);
3229         }
3230         AddToImplIncludes("<runtime/JSArray.h>", $conditional);
3231         return "jsArray(exec, $thisValue->globalObject(), $value)";
3232     }
3233
3234     my $sequenceType = $codeGenerator->GetSequenceType($type);
3235     if ($sequenceType) {
3236         if (!$codeGenerator->SkipIncludeHeader($sequenceType)) {
3237             AddToImplIncludes("JS$sequenceType.h", $conditional);
3238             AddToImplIncludes("$sequenceType.h", $conditional);
3239         }
3240         AddToImplIncludes("<runtime/JSArray.h>", $conditional);
3241         return "jsArray(exec, $thisValue->globalObject(), $value)";
3242     }
3243
3244     if ($type eq "DOMObject" or $type eq "any") {
3245         if ($implClassName eq "Document") {
3246             AddToImplIncludes("JSCanvasRenderingContext2D.h", $conditional);
3247         } else {
3248             return "($value.hasNoValue() ? jsNull() : $value.jsValue())";
3249         }
3250     } elsif ($type =~ /SVGPathSeg/) {
3251         AddToImplIncludes("JS$type.h", $conditional);
3252         my $joinedName = $type;
3253         $joinedName =~ s/Abs|Rel//;
3254         AddToImplIncludes("$joinedName.h", $conditional);
3255     } elsif ($type eq "SerializedScriptValue" or $type eq "any") {
3256         AddToImplIncludes("SerializedScriptValue.h", $conditional);
3257         return "$value ? $value->deserialize(exec, castedThis->globalObject(), 0) : jsNull()";
3258     } elsif ($type eq "MessagePortArray") {
3259         AddToImplIncludes("MessagePort.h", $conditional);
3260         AddToImplIncludes("JSMessagePort.h", $conditional);
3261         AddToImplIncludes("<runtime/JSArray.h>", $conditional);
3262         return "jsArray(exec, $globalObject, *$value)";
3263     } else {
3264         # Default, include header with same name.
3265         AddToImplIncludes("JS$type.h", $conditional);
3266         if (IsTypedArrayType($type)) {
3267             AddToImplIncludes("<wtf/$type.h>", $conditional) if not $codeGenerator->SkipIncludeHeader($type);
3268         } else {
3269             AddToImplIncludes("$type.h", $conditional) if not $codeGenerator->SkipIncludeHeader($type);
3270         }
3271     }
3272
3273     return $value if $codeGenerator->IsSVGAnimatedType($type);
3274
3275     if ($signature->extendedAttributes->{"ReturnNewObject"}) {
3276         return "toJSNewlyCreated(exec, $globalObject, WTF::getPtr($value))";
3277     }
3278
3279     if ($codeGenerator->IsSVGAnimatedType($implClassName) or $implClassName eq "SVGViewSpec") {
3280         # Convert from abstract SVGProperty to real type, so the right toJS() method can be invoked.
3281         $value = "static_cast<" . GetNativeType($type) . ">($value)";
3282     } elsif ($codeGenerator->IsSVGTypeNeedingTearOff($type) and not $implClassName =~ /List$/) {
3283         my $tearOffType = $codeGenerator->GetSVGTypeNeedingTearOff($type);
3284         if ($codeGenerator->IsSVGTypeWithWritablePropertiesNeedingTearOff($type) and $inFunctionCall eq 0 and not defined $signature->extendedAttributes->{"Immutable"}) {
3285             my $getter = $value;
3286             $getter =~ s/impl\.//;
3287             $getter =~ s/impl->//;
3288             $getter =~ s/\(\)//;
3289             my $updateMethod = "&${implClassName}::update" . $codeGenerator->WK_ucfirst($getter);
3290
3291             my $selfIsTearOffType = $codeGenerator->IsSVGTypeNeedingTearOff($implClassName);
3292             if ($selfIsTearOffType) {
3293                 AddToImplIncludes("SVGStaticPropertyWithParentTearOff.h", $conditional);
3294                 $tearOffType =~ s/SVGPropertyTearOff</SVGStaticPropertyWithParentTearOff<$implClassName, /;
3295
3296                 if ($value =~ /matrix/ and $implClassName eq "SVGTransform") {
3297                     # SVGTransform offers a matrix() method for internal usage that returns an AffineTransform
3298                     # and a svgMatrix() method returning a SVGMatrix, used for the bindings.
3299                     $value =~ s/matrix/svgMatrix/;
3300                 }
3301
3302                 $value = "${tearOffType}::create(castedThis->impl(), $value, $updateMethod)";
3303             } else {
3304                 AddToImplIncludes("SVGStaticPropertyTearOff.h", $conditional);
3305                 $tearOffType =~ s/SVGPropertyTearOff</SVGStaticPropertyTearOff<$implClassName, /;
3306                 $value = "${tearOffType}::create(impl, $value, $updateMethod)";
3307             }
3308         } elsif ($tearOffType =~ /SVGStaticListPropertyTearOff/) {
3309             $value = "${tearOffType}::create(impl, $value)";
3310         } elsif (not $tearOffType =~ /SVG(Point|PathSeg)List/) {
3311             $value = "${tearOffType}::create($value)";
3312         }
3313     }
3314     if ($globalObject) {
3315         return "toJS(exec, $globalObject, WTF::getPtr($value))";
3316     } else {
3317         return "toJS(exec, jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject()), WTF::getPtr($value))";
3318     }
3319 }
3320
3321 sub ceilingToPowerOf2
3322 {
3323     my ($size) = @_;
3324
3325     my $powerOf2 = 1;
3326     while ($size > $powerOf2) {
3327         $powerOf2 <<= 1;
3328     }
3329
3330     return $powerOf2;
3331 }
3332
3333 # Internal Helper
3334 sub GenerateHashTable
3335 {
3336     my $object = shift;
3337
3338     my $name = shift;
3339     my $size = shift;
3340     my $keys = shift;
3341     my $specials = shift;
3342     my $value1 = shift;
3343     my $value2 = shift;
3344     my $conditionals = shift;
3345
3346     # Generate size data for compact' size hash table
3347
3348     my @table = ();
3349     my @links = ();
3350
3351     my $compactSize = ceilingToPowerOf2($size * 2);
3352
3353     my $maxDepth = 0;
3354     my $collisions = 0;
3355     my $numEntries = $compactSize;
3356
3357     my $i = 0;
3358     foreach (@{$keys}) {
3359         my $depth = 0;
3360         my $h = $object->GenerateHashValue($_) % $numEntries;
3361
3362         while (defined($table[$h])) {
3363             if (defined($links[$h])) {
3364                 $h = $links[$h];
3365                 $depth++;
3366             } else {
3367                 $collisions++;
3368                 $links[$h] = $compactSize;
3369                 $h = $compactSize;
3370                 $compactSize++;
3371             }
3372         }
3373
3374         $table[$h] = $i;
3375
3376         $i++;
3377         $maxDepth = $depth if ($depth > $maxDepth);
3378     }
3379
3380     # Start outputing the hashtables
3381     my $nameEntries = "${name}Values";
3382     $nameEntries =~ s/:/_/g;
3383
3384     if (($name =~ /Prototype/) or ($name =~ /Constructor/)) {
3385         my $type = $name;
3386         my $implClass;
3387
3388         if ($name =~ /Prototype/) {
3389             $type =~ s/Prototype.*//;
3390             $implClass = $type; $implClass =~ s/Wrapper$//;
3391             push(@implContent, "/* Hash table for prototype */\n");
3392         } else {
3393             $type =~ s/Constructor.*//;
3394             $implClass = $type; $implClass =~ s/Constructor$//;
3395             push(@implContent, "/* Hash table for constructor */\n");
3396         }
3397     } else {
3398         push(@implContent, "/* Hash table */\n");
3399     }
3400
3401     # Dump the hash table
3402     push(@implContent, "\nstatic const HashTableValue $nameEntries\[\] =\n\{\n");
3403     $i = 0;
3404     foreach my $key (@{$keys}) {
3405         my $conditional;
3406         my $targetType;
3407
3408         if ($conditionals) {
3409             $conditional = $conditionals->{$key};
3410         }
3411         if ($conditional) {
3412             my $conditionalString = $codeGenerator->GenerateConditionalStringFromAttributeValue($conditional);
3413             push(@implContent, "#if ${conditionalString}\n");
3414         }
3415         
3416         if ("@$specials[$i]" =~ m/Function/) {
3417             $targetType = "static_cast<NativeFunction>";
3418         } else {
3419             $targetType = "static_cast<PropertySlot::GetValueFunc>";
3420         }
3421         push(@implContent, "    { \"$key\", @$specials[$i], (intptr_t)" . $targetType . "(@$value1[$i]), (intptr_t)@$value2[$i], NoIntrinsic },\n");
3422         push(@implContent, "#endif\n") if $conditional;
3423         ++$i;
3424     }
3425     push(@implContent, "    { 0, 0, 0, 0, NoIntrinsic }\n");
3426     push(@implContent, "};\n\n");
3427     my $compactSizeMask = $numEntries - 1;
3428     push(@implContent, "static const HashTable $name = { $compactSize, $compactSizeMask, $nameEntries, 0 };\n");
3429 }
3430
3431 # Paul Hsieh's SuperFastHash
3432 # http://www.azillionmonkeys.com/qed/hash.html
3433 sub GenerateHashValue
3434 {
3435     my $object = shift;
3436
3437     my @chars = split(/ */, $_[0]);
3438
3439     # This hash is designed to work on 16-bit chunks at a time. But since the normal case
3440     # (above) is to hash UTF-16 characters, we just treat the 8-bit chars as if they
3441     # were 16-bit chunks, which should give matching results
3442     
3443     my $EXP2_32 = 4294967296;
3444     
3445     my $hash = 0x9e3779b9;
3446     my $l    = scalar @chars; #I wish this was in Ruby --- Maks
3447     my $rem  = $l & 1;
3448     $l = $l >> 1;
3449     
3450     my $s = 0;
3451     
3452     # Main loop
3453     for (; $l > 0; $l--) {
3454         $hash   += ord($chars[$s]);
3455         my $tmp = leftShift(ord($chars[$s+1]), 11) ^ $hash;
3456         $hash   = (leftShift($hash, 16)% $EXP2_32) ^ $tmp;
3457         $s += 2;
3458         $hash += $hash >> 11;
3459         $hash %= $EXP2_32;
3460     }
3461     
3462     # Handle end case
3463     if ($rem != 0) {
3464         $hash += ord($chars[$s]);
3465         $hash ^= (leftShift($hash, 11)% $EXP2_32);
3466         $hash += $hash >> 17;
3467     }
3468     
3469     # Force "avalanching" of final 127 bits
3470     $hash ^= leftShift($hash, 3);
3471     $hash += ($hash >> 5);
3472     $hash = ($hash% $EXP2_32);
3473     $hash ^= (leftShift($hash, 2)% $EXP2_32);
3474     $hash += ($hash >> 15);
3475     $hash = $hash% $EXP2_32;
3476     $hash ^= (leftShift($hash, 10)% $EXP2_32);
3477     
3478     # Save 8 bits for StringImpl to use as flags.
3479     $hash &= 0xffffff;
3480     
3481     # This avoids ever returning a hash code of 0, since that is used to
3482     # signal "hash not computed yet". Setting the high bit maintains
3483     # reasonable fidelity to a hash code of 0 because it is likely to yield
3484     # exactly 0 when hash lookup masks out the high bits.
3485     $hash = (0x80000000 >> 8) if ($hash == 0);
3486     
3487     return $hash;
3488 }
3489
3490 # Internal helper
3491 sub WriteData
3492 {
3493     my $object = shift;
3494     my $dataNode = shift;
3495
3496     my $name = $dataNode->name;
3497     my $prefix = FileNamePrefix;
3498     my $headerFileName = "$outputDir/$prefix$name.h";
3499     my $implFileName = "$outputDir/$prefix$name.cpp";
3500     my $depsFileName = "$outputDir/$prefix$name.dep";
3501
3502     # Update a .cpp file if the contents are changed.
3503     my $contents = join "", @implContentHeader;
3504
3505     my @includes = ();
3506     my %implIncludeConditions = ();
3507     foreach my $include (keys %implIncludes) {
3508         my $condition = $implIncludes{$include};
3509         my $checkType = $include;
3510         $checkType =~ s/\.h//;
3511         next if $codeGenerator->IsSVGAnimatedType($checkType);
3512
3513         $include = "\"$include\"" unless $include =~ /^["<]/; # "
3514
3515         if ($condition eq 1) {
3516             push @includes, $include;
3517         } else {
3518             push @{$implIncludeConditions{$condition}}, $include;
3519         }
3520     }
3521     foreach my $include (sort @includes) {
3522         $contents .= "#include $include\n";
3523     }
3524     foreach my $condition (sort keys %implIncludeConditions) {
3525         $contents .= "\n#if " . $codeGenerator->GenerateConditionalStringFromAttributeValue($condition) . "\n";
3526         foreach my $include (sort @{$implIncludeConditions{$condition}}) {
3527             $contents .= "#include $include\n";
3528         }
3529         $contents .= "#endif\n";
3530     }
3531
3532     $contents .= join "", @implContent;
3533     $codeGenerator->UpdateFile($implFileName, $contents);
3534
3535     @implContentHeader = ();
3536     @implContent = ();
3537     %implIncludes = ();
3538
3539     # Update a .h file if the contents are changed.
3540     $contents = join "", @headerContentHeader;
3541
3542     @includes = ();
3543     foreach my $include (keys %headerIncludes) {
3544         $include = "\"$include\"" unless $include =~ /^["<]/; # "
3545         push @includes, $include;
3546     }
3547     foreach my $include (sort @includes) {
3548         $contents .= "#include $include\n";
3549     }
3550
3551     $contents .= join "", @headerContent;
3552
3553     @includes = ();
3554     foreach my $include (keys %headerTrailingIncludes) {
3555         $include = "\"$include\"" unless $include =~ /^["<]/; # "
3556         push @includes, $include;
3557     }
3558     foreach my $include (sort @includes) {
3559         $contents .= "#include $include\n";
3560     }
3561     $codeGenerator->UpdateFile($headerFileName, $contents);
3562
3563     @headerContentHeader = ();
3564     @headerContent = ();
3565     %headerIncludes = ();
3566     %headerTrailingIncludes = ();
3567
3568     if (@depsContent) {
3569         # Update a .dep file if the contents are changed.
3570         $contents = join "", @depsContent;
3571         $codeGenerator->UpdateFile($depsFileName, $contents);
3572
3573         @depsContent = ();
3574     }
3575 }
3576
3577 sub GenerateConstructorDeclaration
3578 {
3579     my $outputArray = shift;
3580     my $className = shift;
3581     my $dataNode = shift;
3582     my $interfaceName = shift;
3583
3584     my $constructorClassName = "${className}Constructor";
3585
3586     push(@$outputArray, "class ${constructorClassName} : public DOMConstructorObject {\n");
3587     push(@$outputArray, "private:\n");
3588     push(@$outputArray, "    ${constructorClassName}(JSC::Structure*, JSDOMGlobalObject*);\n");
3589     push(@$outputArray, "    void finishCreation(JSC::ExecState*, JSDOMGlobalObject*);\n\n");
3590
3591     push(@$outputArray, "public:\n");
3592     push(@$outputArray, "    typedef DOMConstructorObject Base;\n");
3593     push(@$outputArray, "    static $constructorClassName* create(JSC::ExecState* exec, JSC::Structure* structure, JSDOMGlobalObject* globalObject)\n");
3594     push(@$outputArray, "    {\n");
3595     push(@$outputArray, "        $constructorClassName* ptr = new (NotNull, JSC::allocateCell<$constructorClassName>(*exec->heap())) $constructorClassName(structure, globalObject);\n");
3596     push(@$outputArray, "        ptr->finishCreation(exec, globalObject);\n");
3597     push(@$outputArray, "        return ptr;\n");
3598     push(@$outputArray, "    }\n\n");
3599
3600     push(@$outputArray, "    static bool getOwnPropertySlot(JSC::JSCell*, JSC::ExecState*, JSC::PropertyName, JSC::PropertySlot&);\n");
3601     push(@$outputArray, "    static bool getOwnPropertyDescriptor(JSC::JSObject*, JSC::ExecState*, JSC::PropertyName, JSC::PropertyDescriptor&);\n");
3602     push(@$outputArray, "    static const JSC::ClassInfo s_info;\n");
3603
3604     push(@$outputArray, "    static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)\n");
3605     push(@$outputArray, "    {\n");
3606     push(@$outputArray, "        return JSC::Structure::create(globalData, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), &s_info);\n");
3607     push(@$outputArray, "    }\n");
3608
3609     push(@$outputArray, "protected:\n");
3610     push(@$outputArray, "    static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags;\n");
3611
3612     if (IsConstructable($dataNode) && !$dataNode->extendedAttributes->{"NamedConstructor"}) {
3613         push(@$outputArray, "    static JSC::EncodedJSValue JSC_HOST_CALL construct${className}(JSC::ExecState*);\n");
3614         push(@$outputArray, "    static JSC::ConstructType getConstructData(JSC::JSCell*, JSC::ConstructData&);\n");
3615     }
3616     push(@$outputArray, "};\n\n");
3617
3618     if (IsConstructorTemplate($dataNode, "Event")) {
3619         push(@$outputArray, "bool fill${interfaceName}Init(${interfaceName}Init&, JSDictionary&);\n\n");
3620     }
3621
3622     if ($dataNode->extendedAttributes->{"NamedConstructor"}) {
3623         push(@$outputArray, <<END);
3624 class JS${interfaceName}NamedConstructor : public DOMConstructorWithDocument {
3625 public:
3626     typedef DOMConstructorWithDocument Base;
3627
3628     static JS${interfaceName}NamedConstructor* create(JSC::ExecState* exec, JSC::Structure* structure, JSDOMGlobalObject* globalObject)
3629     {
3630         JS${interfaceName}NamedConstructor* constructor = new (NotNull, JSC::allocateCell<JS${interfaceName}NamedConstructor>(*exec->heap())) JS${interfaceName}NamedConstructor(structure, globalObject);
3631         constructor->finishCreation(exec, globalObject);
3632         return constructor;
3633     }
3634
3635     static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)
3636     {
3637         return JSC::Structure::create(globalData, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), &s_info);
3638     }
3639
3640     static const JSC::ClassInfo s_info;
3641
3642 private:
3643     JS${interfaceName}NamedConstructor(JSC::Structure*, JSDOMGlobalObject*);
3644     static JSC::EncodedJSValue JSC_HOST_CALL constructJS${interfaceName}(JSC::ExecState*);
3645     static JSC::ConstructType getConstructData(JSC::JSCell*, JSC::ConstructData&);
3646     void finishCreation(JSC::ExecState*, JSDOMGlobalObject*);
3647 };
3648
3649 END
3650     }
3651 }
3652
3653 sub GenerateConstructorDefinition
3654 {
3655     my $outputArray = shift;
3656
3657     my $className = shift;
3658     my $protoClassName = shift;
3659     my $interfaceName = shift;
3660     my $visibleInterfaceName = shift;
3661     my $dataNode = shift;
3662     my $generatingNamedConstructor = shift;
3663
3664     my $constructorClassName = $generatingNamedConstructor ? "${className}NamedConstructor" : "${className}Constructor";
3665     my $numberOfConstructorParameters = $dataNode->extendedAttributes->{"ConstructorParameters"};
3666     if (!defined $numberOfConstructorParameters) {
3667         if (IsConstructorTemplate($dataNode, "Event")) {
3668             $numberOfConstructorParameters = 2;
3669         } elsif ($dataNode->extendedAttributes->{"Constructor"}) {
3670             $numberOfConstructorParameters = @{$dataNode->constructor->parameters};
3671         }
3672     }
3673
3674     if ($generatingNamedConstructor) {
3675         push(@$outputArray, "const ClassInfo ${constructorClassName}::s_info = { \"${visibleInterfaceName}Constructor\", &Base::s_info, 0, 0, CREATE_METHOD_TABLE($constructorClassName) };\n\n");
3676         push(@$outputArray, "${constructorClassName}::${constructorClassName}(Structure* structure, JSDOMGlobalObject* globalObject)\n");
3677         push(@$outputArray, "    : DOMConstructorWithDocument(structure, globalObject)\n");
3678         push(@$outputArray, "{\n");
3679         push(@$outputArray, "}\n\n");
3680     } else {
3681         push(@$outputArray, "const ClassInfo ${constructorClassName}::s_info = { \"${visibleInterfaceName}Constructor\", &Base::s_info, &${constructorClassName}Table, 0, CREATE_METHOD_TABLE($constructorClassName) };\n\n");
3682         push(@$outputArray, "${constructorClassName}::${constructorClassName}(Structure* structure, JSDOMGlobalObject* globalObject)\n");
3683         push(@$outputArray, "    : DOMConstructorObject(structure, globalObject)\n");
3684         push(@$outputArray, "{\n");
3685         push(@$outputArray, "}\n\n");
3686     }
3687
3688     push(@$outputArray, "void ${constructorClassName}::finishCreation(ExecState* exec, JSDOMGlobalObject* globalObject)\n");
3689     push(@$outputArray, "{\n");
3690     if ($interfaceName eq "DOMWindow") {
3691         push(@$outputArray, "    Base::finishCreation(exec->globalData());\n");
3692         push(@$outputArray, "    ASSERT(inherits(&s_info));\n");
3693         push(@$outputArray, "    putDirect(exec->globalData(), exec->propertyNames().prototype, globalObject->prototype(), DontDelete | ReadOnly);\n");
3694     } elsif ($generatingNamedConstructor) {
3695         push(@$outputArray, "    Base::finishCreation(globalObject);\n");
3696         push(@$outputArray, "    ASSERT(inherits(&s_info));\n");
3697         push(@$outputArray, "    putDirect(exec->globalData(), exec->propertyNames().prototype, ${className}Prototype::self(exec, globalObject), None);\n");
3698     } else {
3699         push(@$outputArray, "    Base::finishCreation(exec->globalData());\n");
3700         push(@$outputArray, "    ASSERT(inherits(&s_info));\n");
3701         push(@$outputArray, "    putDirect(exec->globalData(), exec->propertyNames().prototype, ${protoClassName}::self(exec, globalObject), DontDelete | ReadOnly);\n");
3702     }
3703     push(@$outputArray, "    putDirect(exec->globalData(), exec->propertyNames().length, jsNumber(${numberOfConstructorParameters}), ReadOnly | DontDelete | DontEnum);\n") if defined $numberOfConstructorParameters;
3704     push(@$outputArray, "}\n\n");
3705
3706     if (!$generatingNamedConstructor) {
3707         my $hasStaticFunctions = 0;
3708         foreach my $function (@{$dataNode->functions}) {
3709             if ($function->isStatic) {
3710                 $hasStaticFunctions = 1;
3711                 last;
3712             }
3713         }
3714
3715         my $kind = $hasStaticFunctions ? "Property" : "Value";
3716
3717         push(@$outputArray, "bool ${constructorClassName}::getOwnPropertySlot(JSCell* cell, ExecState* exec, PropertyName propertyName, PropertySlot& slot)\n");
3718         push(@$outputArray, "{\n");
3719         push(@$outputArray, "    return getStatic${kind}Slot<${constructorClassName}, JSDOMWrapper>(exec, &${constructorClassName}Table, jsCast<${constructorClassName}*>(cell), propertyName, slot);\n");
3720         push(@$outputArray, "}\n\n");
3721
3722         push(@$outputArray, "bool ${constructorClassName}::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, PropertyName propertyName, PropertyDescriptor& descriptor)\n");
3723         push(@$outputArray, "{\n");
3724         push(@$outputArray, "    return getStatic${kind}Descriptor<${constructorClassName}, JSDOMWrapper>(exec, &${constructorClassName}Table, jsCast<${constructorClassName}*>(object), propertyName, descriptor);\n");
3725         push(@$outputArray, "}\n\n");
3726     }
3727
3728     if (IsConstructable($dataNode)) {
3729         if (IsConstructorTemplate($dataNode, "Event")) {
3730             $implIncludes{"JSDictionary.h"} = 1;
3731             $implIncludes{"<runtime/Error.h>"} = 1;
3732
3733             push(@$outputArray, <<END);
3734 EncodedJSValue JSC_HOST_CALL ${constructorClassName}::construct${className}(ExecState* exec)
3735 {
3736     ${constructorClassName}* jsConstructor = jsCast<${constructorClassName}*>(exec->callee());
3737
3738     ScriptExecutionContext* executionContext = jsConstructor->scriptExecutionContext();
3739     if (!executionContext)
3740         return throwVMError(exec, createReferenceError(exec, "Constructor associated execution context is unavailable"));
3741
3742     AtomicString eventType = ustringToAtomicString(exec->argument(0).toString(exec)->value(exec));
3743     if (exec->hadException())
3744         return JSValue::encode(jsUndefined());
3745
3746     ${interfaceName}Init eventInit;
3747
3748     JSValue initializerValue = exec->argument(1);
3749     if (!initializerValue.isUndefinedOrNull()) {
3750         // Given the above test, this will always yield an object.
3751         JSObject* initializerObject = initializerValue.toObject(exec);
3752
3753         // Create the dictionary wrapper from the initializer object.
3754         JSDictionary dictionary(exec, initializerObject);
3755
3756         // Attempt to fill in the EventInit.
3757         if (!fill${interfaceName}Init(eventInit, dictionary))
3758             return JSValue::encode(jsUndefined());
3759     }
3760
3761     RefPtr<${interfaceName}> event = ${interfaceName}::create(eventType, eventInit);
3762     return JSValue::encode(toJS(exec, jsConstructor->globalObject(), event.get()));
3763 }
3764
3765 bool fill${interfaceName}Init(${interfaceName}Init& eventInit, JSDictionary& dictionary)
3766 {
3767 END
3768
3769             foreach my $interfaceBase (@{$dataNode->parents}) {
3770                 push(@implContent, <<END);
3771     if (!fill${interfaceBase}Init(eventInit, dictionary))
3772         return false;
3773
3774 END
3775             }
3776
3777             for (my $index = 0; $index < @{$dataNode->attributes}; $index++) {
3778                 my $attribute = @{$dataNode->attributes}[$index];
3779                 if ($attribute->signature->extendedAttributes->{"InitializedByEventConstructor"}) {
3780                     my $attributeName = $attribute->signature->name;
3781                     push(@implContent, <<END);
3782     if (!dictionary.tryGetProperty("${attributeName}", eventInit.${attributeName}))
3783         return false;
3784 END
3785                 }
3786             }
3787
3788             push(@$outputArray, <<END);
3789     return true;
3790 }
3791
3792 END
3793         } elsif (!($dataNode->extendedAttributes->{"JSCustomConstructor"} || $dataNode->extendedAttributes->{"CustomConstructor"}) && (!$dataNode->extendedAttributes->{"NamedConstructor"} || $generatingNamedConstructor)) {
3794             push(@$outputArray, "EncodedJSValue JSC_HOST_CALL ${constructorClassName}::construct${className}(ExecState* exec)\n");
3795             push(@$outputArray, "{\n");
3796             push(@$outputArray, "    ${constructorClassName}* castedThis = jsCast<${constructorClassName}*>(exec->callee());\n");
3797
3798             my $function = $dataNode->constructor;
3799             my @constructorArgList;
3800
3801             $implIncludes{"<runtime/Error.h>"} = 1;
3802
3803             GenerateArgumentsCountCheck($outputArray, $function, $dataNode);
3804
3805             if (@{$function->raisesExceptions} || $dataNode->extendedAttributes->{"ConstructorRaisesException"}) {
3806                 $implIncludes{"ExceptionCode.h"} = 1;
3807                 push(@$outputArray, "    ExceptionCode ec = 0;\n");
3808             }
3809
3810             # FIXME: For now, we do not support SVG constructors.
3811             # FIXME: Currently [Constructor(...)] does not yet support [Optional] arguments.
3812             # It just supports [Optional=DefaultIsUndefined] or [Optional=DefaultIsNullString].
3813             my $numParameters = @{$function->parameters};
3814             my ($dummy, $paramIndex) = GenerateParametersCheck($outputArray, $function, $dataNode, $numParameters, $interfaceName, "constructorCallback", undef, undef, undef);
3815
3816             if ($codeGenerator->ExtendedAttributeContains($dataNode->extendedAttributes->{"CallWith"}, "ScriptExecutionContext")) {
3817                 push(@constructorArgList, "context");
3818                 push(@$outputArray, "    ScriptExecutionContext* context = castedThis->scriptExecutionContext();\n");
3819                 push(@$outputArray, "    if (!context)\n");
3820                 push(@$outputArray, "        return throwVMError(exec, createReferenceError(exec, \"${interfaceName} constructor associated document is unavailable\"));\n");
3821             }
3822             if ($generatingNamedConstructor) {
3823                 push(@constructorArgList, "castedThis->document()");
3824             }
3825
3826             my $index = 0;
3827             foreach my $parameter (@{$function->parameters}) {
3828                 last if $index eq $paramIndex;
3829                 push(@constructorArgList, $parameter->name);
3830                 $index++;
3831             }
3832
3833             if ($dataNode->extendedAttributes->{"ConstructorRaisesException"}) {
3834                 push(@constructorArgList, "ec");
3835             }
3836             my $constructorArg = join(", ", @constructorArgList);
3837             if ($generatingNamedConstructor) {
3838                 push(@$outputArray, "    RefPtr<${interfaceName}> object = ${interfaceName}::createForJSConstructor(${constructorArg});\n");
3839             } else {
3840                 push(@$outputArray, "    RefPtr<${interfaceName}> object = ${interfaceName}::create(${constructorArg});\n");
3841             }
3842
3843             if ($dataNode->extendedAttributes->{"ConstructorRaisesException"}) {
3844                 push(@$outputArray, "    if (ec) {\n");
3845                 push(@$outputArray, "        setDOMException(exec, ec);\n");
3846                 push(@$outputArray, "        return JSValue::encode(JSValue());\n");
3847                 push(@$outputArray, "    }\n");
3848             }
3849
3850             push(@$outputArray, "    return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get())));\n");
3851             push(@$outputArray, "}\n\n");
3852         }
3853
3854         if (!$dataNode->extendedAttributes->{"NamedConstructor"} || $generatingNamedConstructor) {
3855             push(@$outputArray, "ConstructType ${constructorClassName}::getConstructData(JSCell*, ConstructData& constructData)\n");
3856             push(@$outputArray, "{\n");
3857             push(@$outputArray, "    constructData.native.function = construct${className};\n");
3858             push(@$outputArray, "    return ConstructTypeHost;\n");
3859             push(@$outputArray, "}\n\n");
3860         }
3861     }
3862 }
3863
3864 sub IsConstructable
3865 {
3866     my $dataNode = shift;
3867
3868     return $dataNode->extendedAttributes->{"CustomConstructor"} || $dataNode->extendedAttributes->{"JSCustomConstructor"} || $dataNode->extendedAttributes->{"Constructor"} || $dataNode->extendedAttributes->{"NamedConstructor"} || $dataNode->extendedAttributes->{"ConstructorTemplate"};
3869 }
3870
3871 sub IsConstructorTemplate
3872 {
3873     my $dataNode = shift;
3874     my $template = shift;
3875
3876     return $dataNode->extendedAttributes->{"ConstructorTemplate"} && $dataNode->extendedAttributes->{"ConstructorTemplate"} eq $template;
3877 }
3878
3879 1;