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