summaryrefslogtreecommitdiff
path: root/Source/WebCore/bindings/scripts/CodeGeneratorJS.pm
blob: df4234e239c02deb7c4a45311c5d91ff85091d16 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
#
# Copyright (C) 2005, 2006, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
# Copyright (C) 2006 Anders Carlsson <andersca@mac.com>
# Copyright (C) 2006, 2007 Samuel Weinig <sam@webkit.org>
# Copyright (C) 2006 Alexey Proskuryakov <ap@webkit.org>
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
# Copyright (C) 2009 Cameron McCormack <cam@mcc.id.au>
# Copyright (C) Research In Motion Limited 2010. All rights reserved.
# Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
# Copyright (C) 2011 Patrick Gansterer <paroga@webkit.org>
# Copyright (C) 2012 Ericsson AB. All rights reserved.
# Copyright (C) 2007, 2008, 2009, 2012 Google Inc.
# Copyright (C) 2013 Samsung Electronics. All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with this library; see the file COPYING.LIB.  If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.

package CodeGeneratorJS;

use strict;
use constant FileNamePrefix => "JS";
use Hasher;

my $codeGenerator;

my $writeDependencies = 0;

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

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

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

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

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

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

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

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

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

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

    $codeGenerator->LinkOverloadedFunctions($interface);

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

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

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

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

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

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

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

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

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

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

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

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

sub GetParentClassName
{
    my $interface = shift;

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

sub GetCallbackClassName
{
    my $className = shift;

    return "JS$className";
}

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

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

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

sub SkipIncludeHeader
{
    my $type = shift;

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

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

    return if SkipIncludeHeader($type);

    # When we're finished with the one-file-per-class
    # reorganization, we won't need these special cases.
    if ($type eq "XPathNSResolver") {
        $includesRef->{"JSXPathNSResolver.h"} = 1;
        $includesRef->{"JSCustomXPathNSResolver.h"} = 1;
    } elsif ($isCallback && $codeGenerator->IsWrapperType($type)) {
        $includesRef->{"JS${type}.h"} = 1;
    } elsif ($codeGenerator->IsTypedArrayType($type)) {
        $includesRef->{"<wtf/${type}.h>"} = 1;
    } else {
        # default, include the same named file
        $includesRef->{"${type}.h"} = 1;
    }
}

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

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

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

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

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

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

sub AddClassForwardIfNeeded
{
    my $interfaceName = shift;

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

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

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

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

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

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

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

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

    my $namespaceMaybe = ($inlined ? "JSC::" : "");
    my $namedGetterFunction = GetNamedGetterFunction($interface);
    my $indexedGetterFunction = GetIndexedGetterFunction($interface);
    my $hasNumericIndexedGetter = $indexedGetterFunction ? $codeGenerator->IsNumericType($indexedGetterFunction->signature->type) : 0;

    my @getOwnPropertySlotImpl = ();

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

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

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

    if ($indexedGetterFunction) {
        push(@getOwnPropertySlotImpl, "    unsigned index = propertyName.asIndex();\n");

        # If the item function returns a string then we let the TreatReturnedNullStringAs handle the cases
        # where the index is out of range.
        if ($indexedGetterFunction->signature->type eq "DOMString") {
            push(@getOwnPropertySlotImpl, "    if (index != PropertyName::NotAnIndex) {\n");
        } else {
            push(@getOwnPropertySlotImpl, "    if (index != PropertyName::NotAnIndex && index < static_cast<$interfaceName*>(thisObject->impl())->length()) {\n");
        }
        if ($hasNumericIndexedGetter) {
            push(@getOwnPropertySlotImpl, "        slot.setValue(thisObject->getByIndex(exec, index));\n");
        } else {
            push(@getOwnPropertySlotImpl, "        slot.setCustomIndex(thisObject, index, indexGetter);\n");
        }
        push(@getOwnPropertySlotImpl, "        return true;\n");
        push(@getOwnPropertySlotImpl, "    }\n");
    }

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

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

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

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

    return @getOwnPropertySlotImpl;
}

sub GenerateGetOwnPropertyDescriptorBody
{
    my ($interface, $interfaceName, $className, $hasAttributes, $inlined) = @_;
    
    my $namespaceMaybe = ($inlined ? "JSC::" : "");
    my $namedGetterFunction = GetNamedGetterFunction($interface);
    my $indexedGetterFunction = GetIndexedGetterFunction($interface);
    my $hasNumericIndexedGetter = $indexedGetterFunction ? $codeGenerator->IsNumericType($indexedGetterFunction->signature->type) : 0;

    
    my @getOwnPropertyDescriptorImpl = ();
    if ($interface->extendedAttributes->{"CheckSecurity"}) {
        if ($interfaceName eq "DOMWindow") {
            $implIncludes{"BindingSecurity.h"} = 1;
            push(@implContent, "    if (!BindingSecurity::shouldAllowAccessToDOMWindow(exec, jsCast<$className*>(thisObject)->impl()))\n");
        } else {
            push(@implContent, "    if (!shouldAllowAccessToFrame(exec, thisObject->impl()->frame()))\n");
        }
        push(@implContent, "        return false;\n");
    }
    
    if ($interfaceName eq "NamedNodeMap" or $interfaceName =~ /^HTML\w*Collection$/) {
        push(@getOwnPropertyDescriptorImpl, "    ${namespaceMaybe}JSValue proto = thisObject->prototype();\n");
        push(@getOwnPropertyDescriptorImpl, "    if (proto.isObject() && jsCast<${namespaceMaybe}JSObject*>(asObject(proto))->hasProperty(exec, propertyName))\n");
        push(@getOwnPropertyDescriptorImpl, "        return false;\n\n");
    }
    
    my $manualLookupGetterGeneration = sub {
        my $requiresManualLookup = ($indexedGetterFunction && !$hasNumericIndexedGetter) || $namedGetterFunction;
        if ($requiresManualLookup) {
            push(@getOwnPropertyDescriptorImpl, "    const ${namespaceMaybe}HashEntry* entry = ${className}Table.entry(exec, propertyName);\n");
            push(@getOwnPropertyDescriptorImpl, "    if (entry) {\n");
            push(@getOwnPropertyDescriptorImpl, "        PropertySlot slot;\n");
            push(@getOwnPropertyDescriptorImpl, "        slot.setCustom(thisObject, entry->propertyGetter());\n");
            push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(slot.getValue(exec, propertyName), entry->attributes());\n");
            push(@getOwnPropertyDescriptorImpl, "        return true;\n");
            push(@getOwnPropertyDescriptorImpl, "    }\n");
        }
    };

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

    if ($indexedGetterFunction) {
        push(@getOwnPropertyDescriptorImpl, "    unsigned index = propertyName.asIndex();\n");
        push(@getOwnPropertyDescriptorImpl, "    if (index != PropertyName::NotAnIndex && index < static_cast<$interfaceName*>(thisObject->impl())->length()) {\n");
        if ($hasNumericIndexedGetter) {
            # Assume that if there's a setter, the index will be writable
            if ($interface->extendedAttributes->{"CustomIndexedSetter"}) {
                push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(thisObject->getByIndex(exec, index), ${namespaceMaybe}DontDelete);\n");
            } else {
                push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(thisObject->getByIndex(exec, index), ${namespaceMaybe}DontDelete | ${namespaceMaybe}ReadOnly);\n");
            }
        } else {
            push(@getOwnPropertyDescriptorImpl, "        ${namespaceMaybe}PropertySlot slot;\n");
            push(@getOwnPropertyDescriptorImpl, "        slot.setCustomIndex(thisObject, index, indexGetter);\n");
            # Assume that if there's a setter, the index will be writable
            if ($interface->extendedAttributes->{"CustomIndexedSetter"}) {
                push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(slot.getValue(exec, propertyName), ${namespaceMaybe}DontDelete);\n");
            } else {
                push(@getOwnPropertyDescriptorImpl, "        descriptor.setDescriptor(slot.getValue(exec, propertyName), ${namespaceMaybe}DontDelete | ${namespaceMaybe}ReadOnly);\n");
            }
        }
        push(@getOwnPropertyDescriptorImpl, "        return true;\n");
        push(@getOwnPropertyDescriptorImpl, "    }\n");
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

sub GetSpecialAccessorFunctionForType
{
    my $interface = shift;
    my $special = shift;
    my $firstParameterType = shift;
    my $numberOfParameters = shift;

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

    return 0;
}

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

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

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

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

    my $hasLegacyParent = $interface->extendedAttributes->{"JSLegacyParent"};
    my $hasRealParent = $interface->parent;
    my $hasParent = $hasLegacyParent || $hasRealParent;
    my $parentClassName = GetParentClassName($interface);
    my $needsMarkChildren = $interface->extendedAttributes->{"JSCustomMarkFunction"} || $interface->extendedAttributes->{"EventTarget"} || $interface->name eq "EventTarget";

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

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

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

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

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

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

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

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

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

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

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

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

    # Static create methods
    push(@headerContent, "public:\n");
    push(@headerContent, "    typedef $parentClassName Base;\n");
    if ($interfaceName eq "DOMWindow") {
        push(@headerContent, "    static $className* create(JSC::VM& vm, JSC::Structure* structure, PassRefPtr<$implType> impl, JSDOMWindowShell* windowShell)\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(vm.heap)) ${className}(vm, structure, impl, windowShell);\n");
        push(@headerContent, "        ptr->finishCreation(vm, windowShell);\n");
        push(@headerContent, "        vm.heap.addFinalizer(ptr, destroy);\n");
        push(@headerContent, "        return ptr;\n");
        push(@headerContent, "    }\n\n");
    } elsif ($codeGenerator->InheritsInterface($interface, "WorkerGlobalScope")) {
        push(@headerContent, "    static $className* create(JSC::VM& vm, JSC::Structure* structure, PassRefPtr<$implType> impl)\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(vm.heap)) ${className}(vm, structure, impl);\n");
        push(@headerContent, "        ptr->finishCreation(vm);\n");
        push(@headerContent, "        vm.heap.addFinalizer(ptr, destroy);\n");
        push(@headerContent, "        return ptr;\n");
        push(@headerContent, "    }\n\n");
    } elsif ($interface->extendedAttributes->{"MasqueradesAsUndefined"}) {
        AddIncludesForTypeInHeader($implType) unless $svgPropertyOrListPropertyType;
        push(@headerContent, "    static $className* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<$implType> impl)\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        globalObject->masqueradesAsUndefinedWatchpoint()->notifyWrite();\n");
        push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalObject->vm().heap)) $className(structure, globalObject, impl);\n");
        push(@headerContent, "        ptr->finishCreation(globalObject->vm());\n");
        push(@headerContent, "        return ptr;\n");
        push(@headerContent, "    }\n\n");
    } else {
        AddIncludesForTypeInHeader($implType) unless $svgPropertyOrListPropertyType;
        push(@headerContent, "    static $className* create(JSC::Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<$implType> impl)\n");
        push(@headerContent, "    {\n");
        push(@headerContent, "        $className* ptr = new (NotNull, JSC::allocateCell<$className>(globalObject->vm().heap)) $className(structure, globalObject, impl);\n");
        push(@headerContent, "        ptr->finishCreation(globalObject->vm());\n");
        push(@headerContent, "        return ptr;\n");
        push(@headerContent, "    }\n\n");
    }

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

    # Prototype
    push(@headerContent, "    static JSC::JSObject* createPrototype(JSC::ExecState*, JSC::JSGlobalObject*);\n") unless IsDOMGlobalObject($interface);

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

    my $namedGetterFunction = GetNamedGetterFunction($interface);
    my $indexedGetterFunction = GetIndexedGetterFunction($interface);
    my $hasNumericIndexedGetter = $indexedGetterFunction ? $codeGenerator->IsNumericType($indexedGetterFunction->signature->type) : 0;

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

    my $hasComplexGetter =
        $indexedGetterFunction
        || $interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}
        || $hasImpureNamedGetter;
    
    my $hasGetter = $numAttributes > 0 || !$interface->extendedAttributes->{"NoInterfaceObject"} || $hasComplexGetter;

    if ($hasImpureNamedGetter) {
        $structureFlags{"JSC::HasImpureGetOwnPropertySlot"} = 1;
    }

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

    # Check if we have any writable properties
    my $hasReadWriteProperties = 0;
    foreach (@{$interface->attributes}) {
        if (!IsReadonly($_) && !$_->isStatic) {
            $hasReadWriteProperties = 1;
        }
    }

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

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

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

    # Class info
    if ($interfaceName eq "Node") {
        push(@headerContent, "    static WEBKIT_EXPORTDATA const JSC::ClassInfo s_info;\n\n");
    } else {
        push(@headerContent, "    static const JSC::ClassInfo s_info;\n\n");
    }
    # Structure ID
    if ($interfaceName eq "DOMWindow") {
        $structureFlags{"JSC::ImplementsHasInstance"} = 1;
    }
    push(@headerContent, "    static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype)\n");
    push(@headerContent, "    {\n");
    if (IsDOMGlobalObject($interface)) {
        push(@headerContent, "        return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::GlobalObjectType, StructureFlags), &s_info);\n");
    } else {
        push(@headerContent, "        return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), &s_info);\n");
    }
    push(@headerContent, "    }\n\n");

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

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

    # Custom deleteProperty function
    push(@headerContent, "    static bool deleteProperty(JSC::JSCell*, JSC::ExecState*, JSC::PropertyName);\n") if $interface->extendedAttributes->{"CustomDeleteProperty"};
    push(@headerContent, "    static bool deletePropertyByIndex(JSC::JSCell*, JSC::ExecState*, unsigned);\n") if $interface->extendedAttributes->{"CustomDeleteProperty"};

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

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

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

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

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

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

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

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

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

        foreach my $attribute (@{$interface->attributes}) {
            my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
            if (HasCustomGetter($attribute->signature->extendedAttributes)) {
                push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
                my $methodName = $codeGenerator->WK_lcfirst($attribute->signature->name);
                push(@headerContent, "    JSC::JSValue " . $methodName . "(JSC::ExecState*) const;\n");
                push(@headerContent, "#endif\n") if $conditionalString;
            }
            if (HasCustomSetter($attribute->signature->extendedAttributes) && !IsReadonly($attribute)) {
                push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
                push(@headerContent, "    void set" . $codeGenerator->WK_ucfirst($attribute->signature->name) . "(JSC::ExecState*, JSC::JSValue);\n");
                push(@headerContent, "#endif\n") if $conditionalString;
            }
        }
    }

    foreach my $function (@{$interface->functions}) {
        $numCustomFunctions++ if HasCustomMethod($function->signature->extendedAttributes);
    }

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

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

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

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

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

    # Index getter
    if ($indexedGetterFunction) {
        if ($hasNumericIndexedGetter) {
            push(@headerContent, "    JSC::JSValue getByIndex(JSC::ExecState*, unsigned index);\n");
        } else {
            push(@headerContent, "    static JSC::JSValue indexGetter(JSC::ExecState*, JSC::JSValue, unsigned);\n");
        }
    }

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

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

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

    if (!$hasParent ||
        GetGenerateIsReachable($interface) ||
        GetCustomIsReachable($interface) ||
        $interface->extendedAttributes->{"JSCustomFinalize"} ||
        $codeGenerator->InheritsExtendedAttribute($interface, "ActiveDOMObject")) {
        if ($interfaceName ne "Node" && $codeGenerator->InheritsInterface($interface, "Node")) {
            $headerIncludes{"JSNode.h"} = 1;
            push(@headerContent, "class JS${interfaceName}Owner : public JSNodeOwner {\n");
        } else {
            push(@headerContent, "class JS${interfaceName}Owner : public JSC::WeakHandleOwner {\n");
        }
        push(@headerContent, "public:\n");
        push(@headerContent, "    virtual bool isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown>, void* context, JSC::SlotVisitor&);\n");
        push(@headerContent, "    virtual void finalize(JSC::Handle<JSC::Unknown>, void* context);\n");
        push(@headerContent, "};\n");
        push(@headerContent, "\n");
        push(@headerContent, "inline JSC::WeakHandleOwner* wrapperOwner(DOMWrapperWorld*, $implType*)\n");
        push(@headerContent, "{\n");
        push(@headerContent, "    DEFINE_STATIC_LOCAL(JS${interfaceName}Owner, js${interfaceName}Owner, ());\n");
        push(@headerContent, "    return &js${interfaceName}Owner;\n");
        push(@headerContent, "}\n");
        push(@headerContent, "\n");
        push(@headerContent, "inline void* wrapperContext(DOMWrapperWorld* world, $implType*)\n");
        push(@headerContent, "{\n");
        push(@headerContent, "    return world;\n");
        push(@headerContent, "}\n");
        push(@headerContent, "\n");
    }
    if (ShouldGenerateToJSDeclaration($hasParent, $interface)) {
        push(@headerContent, "JSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject*, $implType*);\n");
    }
    if (!$hasParent || $interface->extendedAttributes->{"JSGenerateToNativeObject"}) {
        if ($interfaceName eq "NodeFilter") {
            push(@headerContent, "PassRefPtr<NodeFilter> toNodeFilter(JSC::VM&, JSC::JSValue);\n");
        } elsif ($interfaceName eq "DOMStringList") {
            push(@headerContent, "PassRefPtr<DOMStringList> toDOMStringList(JSC::ExecState*, JSC::JSValue);\n");
        } else {
            push(@headerContent, "$implType* to${interfaceName}(JSC::JSValue);\n");
        }
    }
    if ($usesToJSNewlyCreated{$interfaceName}) {
        push(@headerContent, "JSC::JSValue toJSNewlyCreated(JSC::ExecState*, JSDOMGlobalObject*, $interfaceName*);\n");
    }
    
    push(@headerContent, "\n");

    # Add prototype declaration.
    %structureFlags = ();
    push(@headerContent, "class ${className}Prototype : public JSC::JSNonFinalObject {\n");
    push(@headerContent, "public:\n");
    push(@headerContent, "    typedef JSC::JSNonFinalObject Base;\n");
    unless (IsDOMGlobalObject($interface)) {
        push(@headerContent, "    static JSC::JSObject* self(JSC::ExecState*, JSC::JSGlobalObject*);\n");
    }

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

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

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

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

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

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

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

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

    if ($numAttributes > 0 || !$interface->extendedAttributes->{"NoInterfaceObject"}) {
        push(@headerContent,"// Attributes\n\n");
        foreach my $attribute (@{$interface->attributes}) {
            my $conditionalString = $codeGenerator->GenerateConditionalString($attribute->signature);
            push(@headerContent, "#if ${conditionalString}\n") if $conditionalString;
            my $getter = GetAttributeGetterName($interfaceName, $className, $attribute);
            push(@headerContent, "JSC::JSValue ${getter}(JSC::ExecState*, JSC::JSValue, JSC::PropertyName);\n");
            if (!IsReadonly($attribute)) {
                my $setter = GetAttributeSetterName($interfaceName, $className, $attribute);
                push(@headerContent, "void ${setter}(JSC::ExecState*, JSC::JSObject*, JSC::JSValue);\n");
            }
            push(@headerContent, "#endif\n") if $conditionalString;
        }
        
        if (!$interface->extendedAttributes->{"NoInterfaceObject"}) {
            my $getter = "js" . $interfaceName . "Constructor";
            push(@headerContent, "JSC::JSValue ${getter}(JSC::ExecState*, JSC::JSValue, JSC::PropertyName);\n");
        }

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

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

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

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

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

    return 0  if !$numAttributes;

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

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

    my @entries = ();

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

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

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

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

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

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

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

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

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

        # Only DOMString or wrapper types are checked.
        # For DOMString with StrictTypeChecking only Null, Undefined and Object
        # are accepted for compatibility. Otherwise, no restrictions are made to
        # match the non-overloaded behavior.
        # FIXME: Implement WebIDL overload resolution algorithm.
        if ($codeGenerator->IsStringType($type)) {
            if ($parameter->extendedAttributes->{"StrictTypeChecking"}) {
                push(@andExpression, "(${value}.isUndefinedOrNull() || ${value}.isString() || ${value}.isObject())");
                $usedArguments{$parameterIndex} = 1;
            }
        } elsif ($codeGenerator->IsCallbackInterface($parameter->type)) {
            # For Callbacks only checks if the value is null or object.
            push(@andExpression, "(${value}.isNull() || ${value}.isFunction())");
            $usedArguments{$parameterIndex} = 1;
        } elsif ($codeGenerator->GetArrayType($type) || $codeGenerator->GetSequenceType($type)) {
            # FIXME: Add proper support for T[], T[]?, sequence<T>
            if ($parameter->isNullable) {
                push(@andExpression, "(${value}.isNull() || (${value}.isObject() && isJSArray(${value})))");
            } else {
                push(@andExpression, "(${value}.isObject() && isJSArray(${value}))");
            }
            $usedArguments{$parameterIndex} = 1;
        } elsif (!IsNativeType($type)) {
            if ($parameter->isNullable) {
                push(@andExpression, "(${value}.isNull() || (${value}.isObject() && asObject(${value})->inherits(&JS${type}::s_info)))");
            } else {
                push(@andExpression, "(${value}.isObject() && asObject(${value})->inherits(&JS${type}::s_info))");
            }
            $usedArguments{$parameterIndex} = 1;
        }
        $parameterIndex++;
    }
    my $res = join(" && ", @andExpression);
    $res = "($res)" if @andExpression > 1;
    return ($res, keys %usedArguments);
}

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

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

sub GenerateFunctionParametersCheck
{
    my $function = shift;

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

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

sub GenerateOverloadedFunction
{
    my $function = shift;
    my $interface = shift;
    my $interfaceName = shift;

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

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

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

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

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

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

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

END
}

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

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

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

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

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

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

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

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

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

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

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

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

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

    return $ret;
}

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

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

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

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

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

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

    my $namedGetterFunction = GetNamedGetterFunction($interface);
    my $indexedGetterFunction = GetIndexedGetterFunction($interface);
    my $hasNumericIndexedGetter = $indexedGetterFunction ? $codeGenerator->IsNumericType($indexedGetterFunction->signature->type) : 0;

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

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

    AddIncludesForTypeInImpl($interfaceName);

    @implContent = ();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            my $functionLength = GetFunctionLength($function);
            push(@hashValue2, $functionLength);

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

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

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

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

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

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

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

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

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

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

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

        my $functionLength = GetFunctionLength($function);
        push(@hashValue2, $functionLength);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    # Constructor
    if ($interfaceName eq "DOMWindow") {
        AddIncludesForTypeInImpl("JSDOMWindowShell");
        push(@implContent, "${className}::$className(VM& vm, Structure* structure, PassRefPtr<$implType> impl, JSDOMWindowShell* shell)\n");
        push(@implContent, "    : $parentClassName(vm, structure, impl, shell)\n");
        push(@implContent, "{\n");
        push(@implContent, "}\n\n");
    } elsif ($codeGenerator->InheritsInterface($interface, "WorkerGlobalScope")) {
        AddIncludesForTypeInImpl($interfaceName);
        push(@implContent, "${className}::$className(VM& vm, Structure* structure, PassRefPtr<$implType> impl)\n");
        push(@implContent, "    : $parentClassName(vm, structure, impl)\n");
        push(@implContent, "{\n");
        push(@implContent, "}\n\n");
    } else {
        push(@implContent, "${className}::$className(Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<$implType> impl)\n");
        if ($hasParent) {
            push(@implContent, "    : $parentClassName(structure, globalObject, impl)\n");
        } else {
            push(@implContent, "    : $parentClassName(structure, globalObject)\n");
            push(@implContent, "    , m_impl(impl.leakRef())\n");
        }
        push(@implContent, "{\n");
        push(@implContent, "}\n\n");

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

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

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

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

    my $hasGetter = $numAttributes > 0
                 || !$interface->extendedAttributes->{"NoInterfaceObject"}
                 || $indexedGetterFunction
                 || $interface->extendedAttributes->{"JSCustomGetOwnPropertySlotAndDescriptor"}
                 || $interface->extendedAttributes->{"CustomGetOwnPropertySlot"}
                 || $namedGetterFunction
                 || $interface->extendedAttributes->{"CustomNamedGetter"};

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

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

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

            if ($indexedGetterFunction) {
                if ($indexedGetterFunction->signature->type eq "DOMString") {
                    push(@implContent, "    if (index <= MAX_ARRAY_INDEX) {\n");
                } else {
                    push(@implContent, "    if (index < static_cast<$interfaceName*>(thisObject->impl())->length()) {\n");
                }
                if ($hasNumericIndexedGetter) {
                    push(@implContent, "        slot.setValue(thisObject->getByIndex(exec, index));\n");
                } else {
                    push(@implContent, "        slot.setCustomIndex(thisObject, index, thisObject->indexGetter);\n");
                }
                push(@implContent, "        return true;\n");
                push(@implContent, "    }\n");
            }

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

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

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

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

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

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

                if (!$attribute->isStatic || $attribute->signature->type =~ /Constructor$/) {
                    push(@implContent, "    ${className}* castedThis = jsCast<$className*>(asObject(slotBase));\n");
                } else {
                    push(@implContent, "    UNUSED_PARAM(slotBase);\n");
                }

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

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

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

                if (HasCustomGetter($attribute->signature->extendedAttributes)) {
                    push(@implContent, "    return castedThis->$implGetterFunctionName(exec);\n");
                } elsif ($attribute->signature->extendedAttributes->{"CheckSecurityForNode"}) {
                    $implIncludes{"JSDOMBinding.h"} = 1;
                    push(@implContent, "    $interfaceName* impl = static_cast<$interfaceName*>(castedThis->impl());\n");
                    push(@implContent, "    return shouldAllowAccessToNode(exec, impl->" . $attribute->signature->name . "()) ? " . NativeToJSValue($attribute->signature, 0, $interfaceName, "impl->$implGetterFunctionName()", "castedThis") . " : jsNull();\n");
                } elsif ($type eq "EventListener") {
                    $implIncludes{"EventListener.h"} = 1;
                    push(@implContent, "    UNUSED_PARAM(exec);\n");
                    push(@implContent, "    $interfaceName* impl = static_cast<$interfaceName*>(castedThis->impl());\n");
                    push(@implContent, "    if (EventListener* listener = impl->$implGetterFunctionName()) {\n");
                    push(@implContent, "        if (const JSEventListener* jsListener = JSEventListener::cast(listener)) {\n");
                    if ($interfaceName eq "Document" || $codeGenerator->InheritsInterface($interface, "WorkerGlobalScope")) {
                        push(@implContent, "            if (JSObject* jsFunction = jsListener->jsFunction(impl))\n");
                    } else {
                        push(@implContent, "            if (JSObject* jsFunction = jsListener->jsFunction(impl->scriptExecutionContext()))\n");
                    }
                    push(@implContent, "                return jsFunction;\n");
                    push(@implContent, "        }\n");
                    push(@implContent, "    }\n");
                    push(@implContent, "    return jsNull();\n");
                } elsif ($attribute->signature->type =~ /Constructor$/) {
                    my $constructorType = $attribute->signature->type;
                    $constructorType =~ s/Constructor$//;
                    # When Constructor attribute is used by DOMWindow.idl, it's correct to pass castedThis as the global object
                    # When JSDOMWrappers have a back-pointer to the globalObject we can pass castedThis->globalObject()
                    if ($interfaceName eq "DOMWindow") {
                        my $named = ($constructorType =~ /Named$/) ? "Named" : "";
                        $constructorType =~ s/Named$//;
                        push(@implContent, "    return JS" . $constructorType . "::get${named}Constructor(exec, castedThis);\n");
                    } else {
                       AddToImplIncludes("JS" . $constructorType . ".h", $attribute->signature->extendedAttributes->{"Conditional"});
                       push(@implContent, "    return JS" . $constructorType . "::getConstructor(exec, castedThis->globalObject());\n");
                    }
                } elsif (!$attribute->signature->extendedAttributes->{"GetterRaisesException"}) {
                    push(@implContent, "    UNUSED_PARAM(exec);\n") if !$attribute->signature->extendedAttributes->{"CallWith"};
                    push(@implContent, "    bool isNull = false;\n") if $isNullable;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if ($interface->extendedAttributes->{"CheckSecurity"}) {
                    $implIncludes{"BindingSecurity.h"} = 1;
                    push(@implContent, "    if (!BindingSecurity::shouldAllowAccessToDOMWindow(exec, domObject->impl()))\n");
                    push(@implContent, "        return jsUndefined();\n");
                }

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

        # Check if we have any writable attributes
        my $hasReadWriteProperties = 0;
        foreach my $attribute (@{$interface->attributes}) {
            $hasReadWriteProperties = 1 if !IsReadonly($attribute) && !$attribute->isStatic;
        }

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

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

                if ($hasReadWriteProperties) {
                    push(@implContent, "    lookupPut<$className, Base>(exec, propertyName, value, " . hashTableAccessor($interface->extendedAttributes->{"JSNoStaticTables"}, $className) . ", thisObject, slot);\n");
                } else {
                    push(@implContent, "    Base::put(thisObject, exec, propertyName, value, slot);\n");
                }
                push(@implContent, "}\n\n");
                
                if ($interface->extendedAttributes->{"CustomIndexedSetter"} || $interface->extendedAttributes->{"CustomNamedSetter"}) {
                    push(@implContent, "void ${className}::putByIndex(JSCell* cell, ExecState* exec, unsigned index, JSValue value, bool shouldThrow)\n");
                    push(@implContent, "{\n");
                    push(@implContent, "    ${className}* thisObject = jsCast<${className}*>(cell);\n");
                    push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);\n");
                    if ($interface->extendedAttributes->{"CustomIndexedSetter"}) {
                        push(@implContent, "    if (index <= MAX_ARRAY_INDEX) {\n");
                        push(@implContent, "        UNUSED_PARAM(shouldThrow);\n");
                        push(@implContent, "        thisObject->indexSetter(exec, index, value);\n");
                        push(@implContent, "        return;\n");
                        push(@implContent, "    }\n");
                    }
                    
                    if ($interface->extendedAttributes->{"CustomNamedSetter"}) {
                        push(@implContent, "    PropertyName propertyName = Identifier::from(exec, index);\n");
                        push(@implContent, "    PutPropertySlot slot(shouldThrow);\n");
                        push(@implContent, "    if (thisObject->putDelegate(exec, propertyName, value, slot))\n");
                        push(@implContent, "        return;\n");
                    }
    
                    push(@implContent, "    Base::putByIndex(cell, exec, index, value, shouldThrow);\n");
                    push(@implContent, "}\n\n");
                }
            }

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

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

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

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

                            if ($interface->extendedAttributes->{"CheckSecurity"} && !$attribute->signature->extendedAttributes->{"DoNotCheckSecurity"}) {
                                if ($interfaceName eq "DOMWindow") {
                                    $implIncludes{"BindingSecurity.h"} = 1;
                                    push(@implContent, "    if (!BindingSecurity::shouldAllowAccessToDOMWindow(exec, jsCast<$className*>(thisObject)->impl()))\n");
                                } else {
                                    push(@implContent, "    if (!shouldAllowAccessToFrame(exec, jsCast<$className*>(thisObject)->impl()->frame()))\n");
                                }
                                push(@implContent, "        return;\n");
                            }

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

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

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

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

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

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

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

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

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

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

                push(@implContent, "void ${constructorFunctionName}(ExecState* exec, JSObject* thisObject, JSValue value)\n");
                push(@implContent, "{\n");
                if ($interface->extendedAttributes->{"CheckSecurity"}) {
                    if ($interfaceName eq "DOMWindow") {
                        $implIncludes{"BindingSecurity.h"} = 1;
                        push(@implContent, "    if (!BindingSecurity::shouldAllowAccessToDOMWindow(exec, jsCast<$className*>(thisObject)->impl()))\n");
                    } else {
                        push(@implContent, "    if (!shouldAllowAccessToFrame(exec, jsCast<$className*>(thisObject)->impl()->frame()))\n");
                    }
                    push(@implContent, "        return;\n");
                }

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

                if ($isCustom) {
                    push(@implContent, "    return JSValue::encode(castedThis->" . $functionImplementationName . "(exec));\n");
                } else {
                    if ($function->signature->name eq "set" and $interface->extendedAttributes->{"TypedArray"}) {
                        my $viewType = $interface->extendedAttributes->{"TypedArray"};
                        push(@implContent, "    return JSValue::encode(setWebGLArrayHelper<$implType, $viewType>(exec, castedThis->impl()));\n");
                        push(@implContent, "}\n\n");
                        next;
                    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    if ($indexedGetterFunction && !$hasNumericIndexedGetter) {
        push(@implContent, "\nJSValue ${className}::indexGetter(ExecState* exec, JSValue slotBase, unsigned index)\n");
        push(@implContent, "{\n");
        push(@implContent, "    ${className}* thisObj = jsCast<$className*>(asObject(slotBase));\n");
        push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(thisObj, &s_info);\n");
        if ($indexedGetterFunction->signature->type eq "DOMString") {
            $implIncludes{"KURL.h"} = 1;
            push(@implContent, "    return jsStringOrUndefined(exec, thisObj->impl()->item(index));\n");
        } else {
            push(@implContent, "    return toJS(exec, thisObj->globalObject(), static_cast<$interfaceName*>(thisObj->impl())->item(index));\n");
        }
        push(@implContent, "}\n\n");
        if ($interfaceName =~ /^HTML\w*Collection$/ or $interfaceName eq "RadioNodeList") {
            $implIncludes{"JSNode.h"} = 1;
            $implIncludes{"Node.h"} = 1;
        }
    }

    if ($hasNumericIndexedGetter) {
        push(@implContent, "\nJSValue ${className}::getByIndex(ExecState*, unsigned index)\n");
        push(@implContent, "{\n");
        push(@implContent, "    ASSERT_GC_OBJECT_INHERITS(this, &s_info);\n");
        push(@implContent, "    double result = static_cast<$interfaceName*>(impl())->item(index);\n");
        # jsNumber conversion doesn't suppress signalling NaNs, so enforce that here.
        push(@implContent, "    if (std::isnan(result))\n");
        push(@implContent, "        return jsNaN();\n");
        push(@implContent, "    return JSValue(result);\n");
        push(@implContent, "}\n\n");
        if ($interfaceName =~ /^HTML\w*Collection$/) {
            $implIncludes{"JSNode.h"} = 1;
            $implIncludes{"Node.h"} = 1;
        }
    }

    if ($interfaceName eq "HTMLPropertiesCollection" or $interfaceName eq "DOMNamedFlowCollection") {
        if ($namedGetterFunction) {
            push(@implContent, "bool ${className}::canGetItemsForName(ExecState*, $interfaceName* collection, PropertyName propertyName)\n");
            push(@implContent, "{\n");
            push(@implContent, "    return collection->hasNamedItem(propertyNameToAtomicString(propertyName));\n");
            push(@implContent, "}\n\n");
            push(@implContent, "JSValue ${className}::nameGetter(ExecState* exec, JSValue slotBase, PropertyName propertyName)\n");
            push(@implContent, "{\n");
            push(@implContent, "    ${className}* thisObj = jsCast<$className*>(asObject(slotBase));\n");
            if ($interfaceName eq "HTMLPropertiesCollection") {
                push(@implContent, "    return toJS(exec, thisObj->globalObject(), WTF::getPtr(static_cast<$interfaceName*>(thisObj->impl())->propertyNodeList(propertyNameToAtomicString(propertyName))));\n");
            } else {
                push(@implContent, "    return toJS(exec, thisObj->globalObject(), static_cast<$interfaceName*>(thisObj->impl())->namedItem(propertyNameToAtomicString(propertyName)));\n");
            }
            push(@implContent, "}\n\n");
        }
    }

    if ((!$hasParent && !GetCustomIsReachable($interface))|| GetGenerateIsReachable($interface) || $codeGenerator->InheritsExtendedAttribute($interface, "ActiveDOMObject")) {
        push(@implContent, "static inline bool isObservable(JS${interfaceName}* js${interfaceName})\n");
        push(@implContent, "{\n");
        push(@implContent, "    if (js${interfaceName}->hasCustomProperties())\n");
        push(@implContent, "        return true;\n");
        if ($eventTarget) {
            push(@implContent, "    if (js${interfaceName}->impl()->hasEventListeners())\n");
            push(@implContent, "        return true;\n");
        }
        push(@implContent, "    return false;\n");
        push(@implContent, "}\n\n");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    my $argsIndex = 0;
    my $hasOptionalArguments = 0;
    my $raisesException = $function->signature->extendedAttributes->{"RaisesException"};

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

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

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

    foreach my $parameter (@{$function->parameters}) {
        my $argType = $parameter->type;

        # Optional arguments with [Optional] should generate an early call with fewer arguments.
        # Optional arguments with [Optional=...] should not generate the early call.
        # Optional Dictionary arguments always considered to have default of empty dictionary.
        my $optional = $parameter->isOptional;
        my $defaultAttribute = $parameter->extendedAttributes->{"Default"};
        if ($optional && !$defaultAttribute && $argType ne "Dictionary" && !$codeGenerator->IsCallbackInterface($parameter->type)) {
            # Generate early call if there are enough parameters.
            if (!$hasOptionalArguments) {
                push(@$outputArray, "\n    size_t argsCount = exec->argumentCount();\n");
                $hasOptionalArguments = 1;
            }
            push(@$outputArray, "    if (argsCount <= $argsIndex) {\n");

            my @optionalCallbackArguments = @arguments;
            push(@optionalCallbackArguments, "ec") if $raisesException;
            my $functionString = "$functionName(" . join(", ", @optionalCallbackArguments) . ")";
            GenerateImplementationFunctionCall($function, $functionString, "    " x 2, $svgPropertyType, $interfaceName);
            push(@$outputArray, "    }\n\n");
        }

        my $name = $parameter->name;

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

            if (!IsNativeType($argType)) {
                push(@$outputArray, "    Vector<$nativeElementType> $name;\n");
                push(@$outputArray, "    for (unsigned i = $argsIndex; i < exec->argumentCount(); ++i) {\n");
                push(@$outputArray, "        if (!exec->argument(i).inherits(&JS${argType}::s_info))\n");
                push(@$outputArray, "            return throwVMTypeError(exec);\n");
                push(@$outputArray, "        $name.append(to$argType(exec->argument(i)));\n");
                push(@$outputArray, "    }\n")
            } else {
                push(@$outputArray, "    Vector<$nativeElementType> $name = toNativeArguments<$nativeElementType>(exec, $argsIndex);\n");
                # Check if the type conversion succeeded.
                push(@$outputArray, "    if (exec->hadException())\n");
                push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");
            }

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

            my $argValue = "exec->argument($argsIndex)";
            push(@$outputArray, "    const String ${name}(${argValue}.isEmpty() ? String() : ${argValue}.toString(exec)->value(exec));\n");
            push(@$outputArray, "    if (exec->hadException())\n");
            push(@$outputArray, "        return JSValue::encode(jsUndefined());\n");

            my @enumValues = $codeGenerator->ValidEnumValues($argType);
            my @enumChecks = ();
            foreach my $enumValue (@enumValues) {
                push(@enumChecks, "${name} != \"$enumValue\"");
            }
            push (@$outputArray, "    if (" . join(" && ", @enumChecks) . ")\n");
            push (@$outputArray, "        return throwVMTypeError(exec);\n");
        } else {
            # If the "StrictTypeChecking" extended attribute is present, and the argument's type is an
            # interface type, then if the incoming value does not implement that interface, a TypeError
            # is thrown rather than silently passing NULL to the C++ code.
            # Per the Web IDL and ECMAScript semantics, incoming values can always be converted to both
            # strings and numbers, so do not throw TypeError if the argument is of these types.
            if ($function->signature->extendedAttributes->{"StrictTypeChecking"}) {
                $implIncludes{"<runtime/Error.h>"} = 1;

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

            push(@$outputArray, "    " . GetNativeTypeFromSignature($parameter) . " $name(" . JSValueToNative($parameter, $optional && $defaultAttribute && $defaultAttribute eq "NullString" ? "argumentOrNull(exec, $argsIndex)" : "exec->argument($argsIndex)") . ");\n");

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

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

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

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

    push(@arguments, "ec") if $raisesException;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    @implContent = ();

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

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

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

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

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

            my @args = ();
            my @argsCheck = ();
            foreach my $param (@params) {
                my $paramName = $param->name;
                AddIncludesForTypeInImpl($param->type, 1);
                push(@args, GetNativeTypeForCallbacks($param->type) . " " . $paramName);
            }
            push(@implContent, join(", ", @args));
            push(@implContent, ")\n");

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

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

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

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

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

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

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

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

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

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

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

sub GetNativeTypeFromSignature
{
    my $signature = shift;
    my $type = $signature->type;

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

    return GetNativeType($type);
}

my %nativeType = (
    "CompareHow" => "Range::CompareHow",
    "DOMString" => "const String&",
    "NodeFilter" => "RefPtr<NodeFilter>",
    "SerializedScriptValue" => "RefPtr<SerializedScriptValue>",
    "Date" => "double",
    "Dictionary" => "Dictionary",
    "any" => "ScriptValue",
    "boolean" => "bool",
    "double" => "double",
    "float" => "float",
    "short" => "short",
    "long" => "int",
    "unsigned long" => "unsigned",
    "unsigned short" => "unsigned short",
    "long long" => "long long",
    "unsigned long long" => "unsigned long long",
    "byte" => "int8_t",
    "octet" => "uint8_t",
    "MediaQueryListListener" => "RefPtr<MediaQueryListListener>",
    "DOMTimeStamp" => "DOMTimeStamp",    
);

sub GetNativeType
{
    my $type = shift;

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

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

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

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

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

sub GetNativeVectorInnerType
{
    my $arrayOrSequenceType = shift;

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

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

    return GetNativeType($type);
}

sub GetSVGPropertyTypes
{
    my $implType = shift;

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

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

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

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

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

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

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

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

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

    my $intConversion = $signature->extendedAttributes->{"EnforceRange"} ? "EnforceRange" : "NormalConversion";
    return "toInt8(exec, $value, $intConversion)" if $type eq "byte";
    return "toUInt8(exec, $value, $intConversion)" if $type eq "octet";
    return "toInt32(exec, $value, $intConversion)" if $type eq "long" or $type eq "short";
    return "toUInt32(exec, $value, $intConversion)" if $type eq "unsigned long" or $type eq "unsigned short";
    return "toInt64(exec, $value, $intConversion)" if $type eq "long long";
    return "toUInt64(exec, $value, $intConversion)" if $type eq "unsigned long long";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    if ($codeGenerator->IsEnumType($type)) {
        AddToImplIncludes("<runtime/JSString.h>", $conditional);
        return "jsStringWithCache(exec, $value)";
    }

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

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

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

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

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

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

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

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

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

    if ($type eq "any") {
        if ($interfaceName eq "Document") {
            AddToImplIncludes("JSCanvasRenderingContext2D.h", $conditional);
        } else {
            return "($value.hasNoValue() ? jsNull() : $value.jsValue())";
        }
    } elsif ($type eq "SerializedScriptValue" or $type eq "any") {
        AddToImplIncludes("SerializedScriptValue.h", $conditional);
        return "$value ? $value->deserialize(exec, castedThis->globalObject(), 0) : jsNull()";
    } else {
        # Default, include header with same name.
        AddToImplIncludes("JS$type.h", $conditional);
        if ($codeGenerator->IsTypedArrayType($type)) {
            AddToImplIncludes("<wtf/$type.h>", $conditional) if not $codeGenerator->SkipIncludeHeader($type);
        } else {
            AddToImplIncludes("$type.h", $conditional) if not $codeGenerator->SkipIncludeHeader($type);
        }
    }

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

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

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

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

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

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

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

    return $powerOf2;
}

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

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

    # Generate size data for compact' size hash table

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

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

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

    my $i = 0;
    foreach (@{$keys}) {
        my $depth = 0;
        my $h = Hasher::GenerateHashValue($_) % $numEntries;

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

        $table[$h] = $i;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    @includes = ();
    foreach my $include (keys %headerIncludes) {
        $include = "\"$include\"" unless $include =~ /^["<]/; # "
        push @includes, $include;
    }
    foreach my $include (sort @includes) {
        # "JSClassName.h" is already included right after config.h.
        next if $include eq "\"$prefix$name.h\"";
        $contents .= "#include $include\n";
    }

    $contents .= join "", @headerContent;

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

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

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

        @depsContent = ();
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    static const JSC::ClassInfo s_info;

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

END
    }
}

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

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

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

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

    my $functionName = "${className}Constructor::construct${className}";
    push(@$outputArray, <<END);
EncodedJSValue JSC_HOST_CALL ${functionName}(ExecState* exec)
{
    size_t argsCount = exec->argumentCount();
END

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

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

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

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

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

END
}

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

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

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

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

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

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

    ${interfaceName}Init eventInit;

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

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

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

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

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

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

END
            }

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

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

END
        } elsif ($codeGenerator->IsConstructorTemplate($interface, "TypedArray")) {
            $implIncludes{"JSArrayBufferViewHelper.h"} = 1;
            my $viewType = $interface->extendedAttributes->{"TypedArray"};
            push(@$outputArray, "EncodedJSValue JSC_HOST_CALL ${constructorClassName}::construct${className}(ExecState* exec)\n");
            push(@$outputArray, "{\n");
            push(@$outputArray, "    ${constructorClassName}* jsConstructor = jsCast<${constructorClassName}*>(exec->callee());\n");
            push(@$outputArray, "    RefPtr<$interfaceName> array = constructArrayBufferView<$interfaceName, $viewType>(exec);\n");
            push(@$outputArray, "    if (!array.get())\n");
            push(@$outputArray, "        // Exception has already been thrown.\n");
            push(@$outputArray, "        return JSValue::encode(JSValue());\n");
            push(@$outputArray, "    return JSValue::encode(asObject(toJS(exec, jsConstructor->globalObject(), array.get())));\n");
            push(@$outputArray, "}\n\n");

            push(@$outputArray, "JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, ${interfaceName}* object)\n");
            push(@$outputArray, "{\n");
            push(@$outputArray, "    return toJSArrayBufferView<${className}>(exec, globalObject, object);\n");
            push(@$outputArray, "}\n\n");

            if ($interface->extendedAttributes->{"CustomIndexedSetter"}) {
                push(@$outputArray, "void ${className}::indexSetter(JSC::ExecState* exec, unsigned index, JSC::JSValue value)\n");
                push(@$outputArray, "{\n");
                push(@$outputArray, "    impl()->set(index, value.toNumber(exec));\n");
                push(@$outputArray, "}\n\n");
            }
        } elsif (!HasCustomConstructor($interface) && (!$interface->extendedAttributes->{"NamedConstructor"} || $generatingNamedConstructor)) {
            my $overloadedIndexString = "";
            if ($function->{overloadedIndex} && $function->{overloadedIndex} > 0) {
                $overloadedIndexString .= $function->{overloadedIndex};
            }

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

            my @constructorArgList;

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

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

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

            # FIXME: For now, we do not support SVG constructors.
            # FIXME: Currently [Constructor(...)] does not yet support optional arguments without [Default=...]
            my $numParameters = @{$function->parameters};
            my ($dummy, $paramIndex) = GenerateParametersCheck($outputArray, $function, $interface, $numParameters, $interfaceName, "constructorCallback", undef, undef, undef);

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

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

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

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

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

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

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

    if ($generatingNamedConstructor) {
        push(@$outputArray, "const ClassInfo ${constructorClassName}::s_info = { \"${visibleInterfaceName}Constructor\", &Base::s_info, 0, 0, CREATE_METHOD_TABLE($constructorClassName) };\n\n");
        push(@$outputArray, "${constructorClassName}::${constructorClassName}(Structure* structure, JSDOMGlobalObject* globalObject)\n");
        push(@$outputArray, "    : DOMConstructorWithDocument(structure, globalObject)\n");
        push(@$outputArray, "{\n");
        push(@$outputArray, "}\n\n");
    } else {
        if ($interface->extendedAttributes->{"JSNoStaticTables"}) {
            push(@$outputArray, "static const HashTable* get${constructorClassName}Table(ExecState* exec)\n");
            push(@$outputArray, "{\n");
            push(@$outputArray, "    return getHashTableForGlobalData(exec->vm(), &${constructorClassName}Table);\n");
            push(@$outputArray, "}\n\n");
            push(@$outputArray, "const ClassInfo ${constructorClassName}::s_info = { \"${visibleInterfaceName}Constructor\", &Base::s_info, 0, get${constructorClassName}Table, CREATE_METHOD_TABLE($constructorClassName) };\n\n");
        } else {
            push(@$outputArray, "const ClassInfo ${constructorClassName}::s_info = { \"${visibleInterfaceName}Constructor\", &Base::s_info, &${constructorClassName}Table, 0, CREATE_METHOD_TABLE($constructorClassName) };\n\n");
        }

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

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

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

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

        push(@$outputArray, "bool ${constructorClassName}::getOwnPropertySlot(JSCell* cell, ExecState* exec, PropertyName propertyName, PropertySlot& slot)\n");
        push(@$outputArray, "{\n");
        push(@$outputArray, "    return getStatic${kind}Slot<${constructorClassName}, JSDOMWrapper>(exec, " . constructorHashTableAccessor($interface->extendedAttributes->{"JSNoStaticTables"}, $constructorClassName) . ", jsCast<${constructorClassName}*>(cell), propertyName, slot);\n");
        push(@$outputArray, "}\n\n");

        push(@$outputArray, "bool ${constructorClassName}::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, PropertyName propertyName, PropertyDescriptor& descriptor)\n");
        push(@$outputArray, "{\n");
        push(@$outputArray, "    return getStatic${kind}Descriptor<${constructorClassName}, JSDOMWrapper>(exec, " . constructorHashTableAccessor($interface->extendedAttributes->{"JSNoStaticTables"}, $constructorClassName) . ", jsCast<${constructorClassName}*>(object), propertyName, descriptor);\n");
        push(@$outputArray, "}\n\n");
    }

    if (IsConstructable($interface)) {
        if (!$interface->extendedAttributes->{"NamedConstructor"} || $generatingNamedConstructor) {
            my $conditionalString = $codeGenerator->GenerateConstructorConditionalString($interface);
            push(@$outputArray, "#if $conditionalString\n") if $conditionalString;
            push(@$outputArray, "ConstructType ${constructorClassName}::getConstructData(JSCell*, ConstructData& constructData)\n");
            push(@$outputArray, "{\n");
            push(@$outputArray, "    constructData.native.function = construct${className};\n");
            push(@$outputArray, "    return ConstructTypeHost;\n");
            push(@$outputArray, "}\n");
            push(@$outputArray, "#endif // $conditionalString\n") if $conditionalString;
            push(@$outputArray, "\n");
        }
    }
}

sub HasCustomConstructor
{
    my $interface = shift;

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

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

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

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

sub IsConstructable
{
    my $interface = shift;

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

1;