-
Notifications
You must be signed in to change notification settings - Fork 3
/
domconv-webkit.hs
1512 lines (1314 loc) · 73.1 KB
/
domconv-webkit.hs
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
{-# LANGUAGE FlexibleContexts #-}
-- DOM interface converter: a tool to convert Haskell files produced by
-- H/Direct into properly structured DOM wrapper
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Prelude
import System.Directory
import System.Environment
import System.FilePath
import System.Exit
import System.IO (stderr, openFile, hClose, IOMode (..), hPutStrLn)
import Control.Monad
import Data.Maybe
import Data.Either
import Data.List
import Data.Char
import Language.Haskell.Pretty
import Language.Preprocessor.Cpphs
import BrownPLT.JavaScript
import qualified Language.Haskell.Syntax as H
import qualified Language.Haskell.Pretty as H
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.List as L
import qualified Utils as U
import qualified OmgParser
import LexM
import Literal
import qualified IDLSyn as I
import qualified IDLUtils
import IDLUtils hiding (getDef)
import BasicTypes
import SplitBounds
import Paths_domconv_webkit
import Control.Applicative ((<$>))
import qualified Data.Text as T
import Data.Monoid ((<>))
import Debug.Trace
import Data.List.Split
import Common
import Control.Arrow (Arrow(..))
getDef = jsname' . IDLUtils.getDef
webkitType "CSS" = "DOMWindowCSS"
webkitType "Window" = "DOMWindow"
webkitType "ApplicationCache" = "DOMApplicationCache"
webkitType "MimeType" = "DOMMimeType"
webkitType "MimeTypeArray" = "DOMMimeTypeArray"
webkitType "Plugin" = "DOMPlugin"
webkitType "PluginArray" = "DOMPluginArray"
webkitType "SecurityPolicy" = "DOMSecurityPolicy"
webkitType "Selection" = "DOMSelection"
webkitType t = t
main = do
putStrLn "domconv-webkit : Makes Gtk2Hs Haskell bindings for webkitgtk"
p <- getProgName
args <- getArgs
case args of
[] -> putStrLn "Usage: domconv-webkit webkit.idl -Iwebkit-1.8.0/Source/WebCore"
idl:args -> makeWebkitBindings idl args
makeWebkitBindings idl args = do
putStrLn
"The package will be created in the current directory which has to be empty."
putStrLn $ "Processing IDL: " ++ idl ++ " args " ++ show args
prntmap <- processIDL idl args
let reversedMap = M.fromListWith S.union $ map (second S.singleton) prntmap
fixHierarchy stripGtk reversedMap "hierarchy.list"
fixHierarchy id reversedMap "hierarchy3.list"
exitSuccess
where
stripGtk x = maybe x ("webkit-"++) $ stripPrefix "webkitgtk-" x
fixHierarchy stripGtk reversedMap hierarchyFile = do
hh <- openFile (hierarchyFile ++ ".new") WriteMode
current <- readFile hierarchyFile
mapM_ (hPutStrLn hh) . filter (\line -> not ((" if webkit-dom" `isSuffixOf` line) || (" if webkitgtk-" `isInfixOf` line) || (" if webkit-" `isInfixOf` line))) $ lines current
let underscore "HTMLIFrameElement" = "html_iframe_element"
underscore "XPathExpression" = "xpath_expression"
underscore "XPathNSResolver" = "xpath_ns_resolver"
underscore "XPathResult" = "xpath_result"
underscore "WebKitNamedFlow" = "webkit_named_flow"
underscore "WebKitPoint" = "webkit_point"
underscore "WebKitAnimation" = "webkit_animation"
underscore "WebKitAnimationList" = "webkit_animation_list"
underscore c = U.toUnderscoreCamel c
hierarchy n parent =
case M.lookup parent reversedMap of
Just s ->
forM_ (S.toList s) $ \child -> do
hPutStrLn hh $ replicate n ' ' ++ "WebKitDOM" ++ webkitType child ++ " as " ++ typeFor child
++ ", webkit_dom_" ++ map toLower (underscore $ webkitType child) ++ "_get_type if " ++ stripGtk (webkitTypeGuard $ typeFor child)
hierarchy (n+4) child
_ -> return ()
hierarchy 8 ""
hClose hh
renameFile hierarchyFile (hierarchyFile ++ ".old")
renameFile (hierarchyFile ++ ".new") hierarchyFile
processIDL idl args = do
let epopts = parseOptions args -- ("-DLANGUAGE_GOBJECT=1":args)
case epopts of
Left s -> do
hPutStrLn stderr $ "domconv: command line parse error " ++ s
exitWith (ExitFailure 1)
Right opts -> procopts idl opts
interfaceName "AbstractView" = "Window"
interfaceName n = n
procopts idl opts = do
let (hsrc, inclfile) = (readFile idl, idl)
baseopt = [("boolean", "Bool")]
optsb = opts{defines = defines opts ++ baseopt,
boolopts = (boolopts opts){pragma = True}}
hsrc' <- hsrc
hsrcpr <- runCpphs optsb inclfile hsrc'
x <- runLexM [] inclfile hsrcpr OmgParser.parseIDL
let prntmap = mkParentMap x
let valmsg = valParentMap prntmap
allParents = nub $ concatMap (rights . snd) $ M.toList prntmap
unless (null valmsg) $ do
mapM_ (hPutStrLn stderr) valmsg
exitWith (ExitFailure 2)
let modst = DOMState {
pm = prntmap
,imp = []
,ns = "Graphics.UI.Gtk.WebKit.DOM." -- this will be the default namespace unless a pragma namespace is used.
,procmod = []
,convlog = []
}
modst' = domLoop modst x
-- mapM_ (putStrLn .show) $ (procmod modst')
mapM_ (mapM_ putSplit . splitModule) (procmod modst')
let getParent (a, Right b : _) = (b, a)
getParent (a, _) = ("", a)
filterSupported = filter (inWebKitGtk . fst)
return . map getParent . filterSupported $ M.toList prntmap
getEnums (I.TypeDecl (I.TyEnum (Just (I.Id typename)) _)) = [typename]
getEnums (I.Module _ defs) = concatMap getEnums defs
getEnums _ = []
getAllInterfaces (I.Interface (I.Id name) _ _ _ _) = [name]
getAllInterfaces (I.Module _ defs) = concatMap getAllInterfaces defs
getAllInterfaces _ = []
getParents (I.Interface _ names _ _ _) = names
getParents (I.Module _ defs) = concatMap getParents defs
getParents _ = []
-- Write a module surrounded by split begin/end comments
--
--newtype DomMod = DomMod H.HsModule
--
--ppHsModuleHeader :: H.Module -> Maybe [H.HsExportSpec] -> H.Doc
--ppHsModuleHeader m mbExportList = H.mySep [
-- H.text "module (",
-- pretty m,
-- H.maybePP (H.parenList . map pretty) mbExportList,
-- text ") where"]
-- where
-- sameGuard a b = declGuard' a == declGuard' b
-- declGroups = groupBy sameGuard decls
--
--instance H.Pretty DomMod where
-- pretty (DomMod (H.HsModule pos m mbExports imp decls)) =
-- H.topLevel (ppHsModuleHeader m mbExports)
-- (map pretty imp ++ map pretty decls)
putSplit :: (H.HsModule, String -> Maybe String) -> IO ()
putSplit (mod@(H.HsModule _ modid _ _ _), comment) = do
let components = U.split '.' $ modName modid
name = components !! 2
fixMods "import Graphics.UI.Gtk.WebKit.Types" = "{#import Graphics.UI.Gtk.WebKit.Types#}"
fixMods l = l
createDirectoryIfMissing True (intercalate "/" (init components))
let ext = if last components == "Enums" then ".hs" else ".chs"
when (inWebKitGtk (last components)) $
Prelude.writeFile (intercalate "/" components ++ ext) . unlines . map fixMods . lines $ prettyJS mod comment
prettyJS (H.HsModule pos (H.Module m) (Just exports) imp decls) comment = fixRenamedFunctions $
-- prettyPrint ((H.HsEVar . H.UnQual $ H.HsIdent "\n#if WEBKIT_CHECK_VERSION(2,2,2)\n "):exports) ++ (concat . intersperse "\n" $ map prettyDecl decls)
intercalate "\n" $ ("module " ++ m ++ "(") : withModuleGuard (map prettyExportGroupWithGuard exportGroups) ++ ") where" : withModuleGuard (map prettyPrint imp ++ map prettyDeclGroupWithGuard declGroups)
where
prettyExportGroupWithGuard :: [H.HsExportSpec] -> String
prettyExportGroupWithGuard decls@(a:_) = prettyExportGroupWithGuard' (exportGuard a) decls
prettyExportGroupWithGuard' :: String -> [H.HsExportSpec] -> String
prettyExportGroupWithGuard' "" decls = prettyExportGroup decls
prettyExportGroupWithGuard' guard decls = "#if " ++ guard ++ "\n" ++ prettyExportGroup decls ++ "\n#endif"
prettyExportGroup :: [H.HsExportSpec] -> String
prettyExportGroup = intercalate "\n" . map ((++ ",") . prettyPrint)
prettyDecl d@(H.HsForeignImport nullLoc "javascript" H.HsUnsafe _ (H.HsIdent defop) tpsig) = prettyPrint d
prettyDecl d@(H.HsTypeSig _ [H.HsIdent n] _) = prettyPrint d
prettyDecl d = prettyPrint d
prettyDeclGroupWithGuard :: [H.HsDecl] -> String
prettyDeclGroupWithGuard decls@(a:_) = prettyDeclGroupWithGuard' (declGuard a) decls
prettyDeclGroupWithGuard' :: String -> [H.HsDecl] -> String
prettyDeclGroupWithGuard' "" decls = prettyDeclGroup decls
prettyDeclGroupWithGuard' guard decls = "\n#if " ++ guard ++ prettyDeclGroup decls ++ "\n#endif"
prettyDeclGroup :: [H.HsDecl] -> String
prettyDeclGroup = intercalate "\n" . map prettyDecl
declName :: H.HsDecl -> String
declName (H.HsTypeSig _ [H.HsIdent n] _) = n
declName (H.HsFunBind (H.HsMatch _ (H.HsIdent n) _ _ _ : _)) = n
declName _ = ""
declGuard :: H.HsDecl -> String
declGuard a = declGuard' (stripPrefix "Graphics.UI.Gtk.WebKit.DOM." m) (declName a)
sameGuard a b = declGuard a == declGuard b
declGroups = groupBy sameGuard decls
exportGuard :: H.HsExportSpec -> String
exportGuard (H.HsEVar (H.UnQual (H.HsIdent s))) = declGuard' (stripPrefix "Graphics.UI.Gtk.WebKit.DOM." m) s
exportGuard _ = ""
sameGuardExp a b = exportGuard a == exportGuard b
exportGroups = groupBy sameGuardExp exports
withModuleGuard = withModuleGuard' . moduleGuard$ stripPrefix "Graphics.UI.Gtk.WebKit.DOM." m
withModuleGuard' :: String -> [String] -> [String]
withModuleGuard' "" l = l
withModuleGuard' guard l = ("#if " ++ guard) : l ++ ["#endif"]
moduleGuard (Just "AudioTrack") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "AudioTrackList") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "BarProp") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "BatteryManager") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "CSS") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "DOMNamedFlowCollection") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "KeyboardEvent") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "Performance") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "PerformanceNavigation") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "PerformanceTiming") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "SecurityPolicy") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "StorageInfo") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "StorageQuota") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "TextTrack") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "TextTrackCue") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "TextTrackCueList") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "TextTrackList") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "Touch") = "WEBKIT_CHECK_VERSION(2,4,0)"
moduleGuard (Just "VideoTrack") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "VideoTrackList") = "WEBKIT_CHECK_VERSION(2,2,2)"
moduleGuard (Just "WheelEvent") = "WEBKIT_CHECK_VERSION(2,4,0)"
moduleGuard _ = ""
declGuard' (Just "Document") "webkitExitPointerLock" = "WEBKIT_CHECK_VERSION(2,2,2) && !WEBKIT_CHECK_VERSION(2,5,1)"
declGuard' (Just "Document") "webkitGetNamedFlows" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Document") "hasFocus" = "WEBKIT_CHECK_VERSION(2,5,1)"
declGuard' (Just "Document") "getSecurityPolicy" = "WEBKIT_CHECK_VERSION(1,10,0)"
declGuard' (Just "Document") "getCurrentScript" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Document") "webkitExitFullscreen" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Document") "createTouch" = "WEBKIT_CHECK_VERSION(2,4,2)"
declGuard' (Just "Document") "getWebkitFullscreenEnabled" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Document") "getWebkitFullscreenElement" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Document") "wheel" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "Document") "keyDown" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Document") "keyPress" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Document") "keyUp" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "DOMTokenList") "toggle" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "hasAttributes" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "getAttributes" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "setId" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "getId" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "setClassName" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "getClassName" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "getClassList" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "matches" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "Element") "closest" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "Element") "requestPointerLock" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "webkitRequestFullScreen" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "webkitRequestFullscreen" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "wheel" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "Element") "keyDown" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "keyPress" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "keyUp" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "getWebkitRegionOverset" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Element") "webkitGetRegionFlowRanges" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "EventTarget") "addEventListenerWithClosure" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "File") "getLastModifiedDate" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLAnchorElement") "setText" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLAnchorElement") "getRelList" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLAreaElement") "getRel" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLAreaElement") "setRel" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLAreaElement") "getRelList" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLFieldSetElement") "setDisabled" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLFieldSetElement") "getDisabled" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLFieldSetElement") "setName" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLFieldSetElement") "getName" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLFieldSetElement") "getElements" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLFormElement") "setAutocapitalize" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLFormElement") "getAutocapitalize" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLFormElement") "setAutocorrect" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLFormElement") "getAutocorrect" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLFormElement") "requestAutocomplete" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLIFrameElement") "setSrcdoc" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLIFrameElement") "getSrcdoc" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLImageElement") "getSizes" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLImageElement") "setSizes" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLImageElement") "getCurrentSrc" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLImageElement") "setSrcset" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLImageElement") "getSrcset" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLInputElement") "setAutocapitalize" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLInputElement") "getAutocapitalize" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLInputElement") "setAutocorrect" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLInputElement") "getAutocorrect" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLInputElement") "setRangeText4" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLInputElement") "setFiles" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLInputElement") "setHeight" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLInputElement") "getHeight" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLInputElement") "setWidth" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLInputElement") "getWidth" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLInputElement") "setSize" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLLinkElement") "getRelList" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLOptionsCollection") "add" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLOptionsCollection") "addBefore" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLOptionsCollection") "namedItem" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "KeyboardEvent") "getKeyCode" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "KeyboardEvent") "getCharCode" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLMediaElement") "addTextTrack" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLMediaElement") "canPlayType" = "WEBKIT_CHECK_VERSION(2,7,0)"
declGuard' (Just "HTMLMediaElement") "webkitGenerateKeyRequest" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLMediaElement") "webkitAddKey" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLMediaElement") "webkitCancelKeyRequest" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLMediaElement") "webkitSetMediaKeys" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLMediaElement") "getAudioTracks" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLMediaElement") "getTextTracks" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLMediaElement") "getVideoTracks" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLMediaElement") "getVideoPlaybackQuality" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLMediaElement") "getWebkitKeys" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLMediaElement") "getSrcObject" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLMediaElement") "setSrcObject" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLMediaElement") "fastSeek" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLMediaElement") "webkitShowPlaybackTargetPicker" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLMediaElement") "getWebkitCurrentPlaybackTargetIsWireless" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLMediaElement") "load" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLScriptElement") "setCrossOrigin" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLScriptElement") "getCrossOrigin" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLScriptElement") "setNonce" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLScriptElement") "getNonce" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLSelectElement") "getSelectedOptions" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLTableElement") "createTBody" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLTextAreaElement") "setAutocapitalize" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLTextAreaElement") "getAutocapitalize" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLTextAreaElement") "setAutocorrect" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLTextAreaElement") "getAutocorrect" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLTextAreaElement") "setRangeText4" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "HTMLVideoElement") "webkitSupportsPresentationMode" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLVideoElement") "webkitSetPresentationMode" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLVideoElement") "getWebkitPresentationMode" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "HTMLVideoElement") "setWebkitWirelessVideoPlaybackDisabled" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLVideoElement") "getWebkitWirelessVideoPlaybackDisabled" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "HTMLInputElement") "getCapture" = "WEBKIT_CHECK_VERSION(2,7,0)"
declGuard' (Just "HTMLInputElement") "setCapture" = "WEBKIT_CHECK_VERSION(2,7,0)"
declGuard' (Just "Location") "getAncestorOrigins" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Navigator") "getWebkitBattery" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Navigator") "registerProtocolHandler" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Navigator") "isProtocolHandlerRegistered" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Navigator") "unregisterProtocolHandler" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Navigator") "getWebkitTemporaryStorage" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Navigator") "getWebkitPersistentStorage" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Storage") "key" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Storage") "getItem" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Storage") "removeItem" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Storage") "clear" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Storage") "getLength" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "TextTrack") "addCue" = "WEBKIT_CHECK_VERSION(2,7,0)"
declGuard' (Just "TextTrack") "getId" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "TextTrack") "getInBandMetadataTrackDispatchType" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "TextTrackList") "getTrackById" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "ValidityState") "getBadInput" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "VideoTrackList") "getSelectedIndex" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "FocusEvent") "getRelatedTarget" = "WEBKIT_CHECK_VERSION(99,0,0)" -- TODO find out when/if this is being added
declGuard' (Just "WebKitNamedFlow") "getRegionsByContent" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "WebKitNamedFlow") "getRegions" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "WebKitNamedFlow") "getContent" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "WebKitNamedFlow") "getName" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "WebKitNamedFlow") "getOverset" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "WebKitNamedFlow") "getFirstEmptyRegionIndex" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Window") "getCSS" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Window") "getPerformance" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Window") "wheel" = "WEBKIT_CHECK_VERSION(2,4,0)"
declGuard' (Just "Window") "getWebkitStorageInfo" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Window") "getLocationbar" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Window") "getMenubar" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Window") "getPersonalbar" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Window") "getScrollbars" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Window") "getStatusbar" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Window") "getToolbar" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Window") "keyDown" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Window") "keyPress" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' (Just "Window") "keyUp" = "WEBKIT_CHECK_VERSION(2,2,2)"
declGuard' _ _ = ""
-- interfaceName = stripPrefix "GHCJS.DOM." $ modName m
-- prefix = U.toLowerInitCamel <$> interfaceName
-- stripCamelPrefix p s = case stripPrefix p s of
-- Just r@(x:xs) | isUpper x -> r
-- _ -> s
-- stripGetSet = stripCamelPrefix "Get" . stripCamelPrefix "Set"
-- fix' pre s = case stripPrefix pre s of
-- Just rest | all isDigit rest -> ""
-- Just ('\'':_) -> ""
-- _ -> s
-- fix = fix' "new" . fix' "newSync" . fix' "newAsync"
--
-- Split a proto-module created by domLoop. All class, data, and instance definitions
-- remain in the "head" class. All methods are grouped by their `this' argument
-- context and placed into modules with the name of that context (first character removed).
-- All modules get the same imports that the "head" module has plus the "head" module itself.
fixRenamedFunctions l = T.unpack $ T.unlines ( T.lines (T.pack l) >>= fixLine)
where
fixLine :: T.Text -> [T.Text]
fixLine line | "{# call " `T.isInfixOf` line = fix line
fixLine line = [line]
fix :: T.Text -> [T.Text]
fix line = foldl applyFix [line] fixups
applyFix :: [T.Text] -> (T.Text, T.Text, T.Text) -> [T.Text]
applyFix [line] (findString, replaceString, guard) | findString `T.isInfixOf` line =
[ "#if " <> guard
, line
, "#else"
, T.replace findString replaceString line
, "#endif"]
applyFix x _ = x
fixups :: [(T.Text, T.Text, T.Text)]
fixups =
[ ("webkit_dom_document_get_visibility_state", "webkit_dom_document_get_webkit_visibility_state", "WEBKIT_CHECK_VERSION(2,2,2)")
, ("webkit_dom_document_get_hidden", "webkit_dom_document_get_webkit_hidden", "WEBKIT_CHECK_VERSION(2,2,2)")
, ("webkit_dom_element_request_pointer_lock", "webkit_dom_element_webkit_request_pointer_lock", "WEBKIT_CHECK_VERSION(2,6,0)")
, ("webkit_dom_mouse_event_get_movement_x", "webkit_dom_mouse_event_get_webkit_movement_x", "WEBKIT_CHECK_VERSION(2,6,0)")
, ("webkit_dom_mouse_event_get_movement_y", "webkit_dom_mouse_event_get_webkit_movement_y", "WEBKIT_CHECK_VERSION(2,6,0)")
, ("{# call webkit_dom_element_set_inner_html #}", "({# call webkit_dom_html_element_set_inner_html #} . castToHTMLElement)", "WEBKIT_CHECK_VERSION(2,8,0)")
, ("{# call webkit_dom_element_get_inner_html #}", "({# call webkit_dom_html_element_get_inner_html #} . castToHTMLElement)", "WEBKIT_CHECK_VERSION(2,8,0)")
, ("{# call webkit_dom_element_set_outer_html #}", "({# call webkit_dom_html_element_set_outer_html #} . castToHTMLElement)", "WEBKIT_CHECK_VERSION(2,8,0)")
, ("{# call webkit_dom_element_get_outer_html #}", "({# call webkit_dom_html_element_get_outer_html #} . castToHTMLElement)", "WEBKIT_CHECK_VERSION(2,8,0)")
, ("{# call webkit_dom_event_target_add_event_listener_closure #}", "{# call webkit_dom_event_target_add_event_listener_with_closure #}", "!WEBKIT_CHECK_VERSION(2,4,0)")
, ("{# call webkit_dom_event_target_remove_event_listener_closure #}", "{# call webkit_dom_event_target_remove_event_listener_with_closure #}", "!WEBKIT_CHECK_VERSION(2,4,0)")
]
splitModule :: H.HsModule -> [(H.HsModule, String -> Maybe String)]
splitModule (H.HsModule _ modid mbexp imps decls) = submods where
headns = modNS $ modName modid
-- headmod = H.HsModule nullLoc modid headexp imps headdecls
headdecls = filter (null . nsOf) decls
-- headexp = Just $ map (mkEIdent . declname) (classes)
-- datas = filter datadecl decls
-- datadecl (H.HsDataDecl _ _ _ _ _ _) = True
-- datadecl (H.HsNewTypeDecl _ _ _ _ _ _) = True
-- datadecl _ = False
classes = filter classdecl headdecls
classdecl (H.HsClassDecl{}) = True
classdecl _ = False
-- instances = filter instdecl decls
-- instdecl (H.HsInstDecl _ _ _ _ _) = True
-- instdecl _ = False
expname (H.HsEVar (H.UnQual (H.HsIdent s))) = s
expname _ = ""
declname (H.HsForeignImport _ _ _ _ (H.HsIdent s) _) = s
declname (H.HsDataDecl _ _ (H.HsIdent s) _ _ _) = s
declname (H.HsNewTypeDecl _ _ (H.HsIdent s) _ _ _) = s
declname (H.HsClassDecl _ _ (H.HsIdent s) _ _) = s
declname (H.HsTypeSig _ [H.HsIdent s] _) = s
declname (H.HsFunBind [H.HsMatch _ (H.HsIdent s) _ _ _]) = s
declname (H.HsInstDecl _ _ (H.UnQual (H.HsIdent s)) _ _) = s
declname _ = ""
mkEIdent (H.HsDataDecl _ _ (H.HsIdent s) _ _ _) = H.HsEThingAll . H.UnQual $ H.HsIdent s
mkEIdent (H.HsClassDecl _ _ (H.HsIdent s) _ _) = H.HsEThingAll . H.UnQual $ H.HsIdent s
mkEIdent decl = H.HsEVar . H.UnQual . H.HsIdent $ declname decl
mtsigs = filter (not . null . nsOf) (reverse decls)
corrn = drop 1 . dropWhile (/= '|') . drop 1 . dropWhile (/= '|')
renameMap s = [(corrn s, takeWhile (/= '|') . drop 1 $ dropWhile (/= '|') s)]
methcorrn (H.HsForeignImport a b c d (H.HsIdent s) f) = (H.HsForeignImport a b c d (H.HsIdent (corrn s)) f, renameMap s)
methcorrn (H.HsTypeSig x [H.HsIdent s] y) = (H.HsTypeSig x [H.HsIdent (corrn s)] y, renameMap s)
methcorrn (H.HsFunBind [H.HsMatch x (H.HsIdent s) y z t]) =
(H.HsFunBind [H.HsMatch x (H.HsIdent (corrn s)) y z t], renameMap s)
methcorrn (H.HsDataDecl a b (H.HsIdent s) c d e) = (H.HsDataDecl a b (H.HsIdent (corrn s)) c d e, renameMap s)
methcorrn (H.HsClassDecl a b (H.HsIdent s) c d) = (H.HsClassDecl a b (H.HsIdent (corrn s)) c d, renameMap s)
methcorrn (H.HsInstDecl a b (H.UnQual (H.HsIdent s)) c d) = (H.HsInstDecl a b (H.UnQual (H.HsIdent (corrn s))) c d, renameMap s)
methcorrn z = (z, [])
nsOf x = case span (/= '|') (declname x) of
(_, "") -> ""
(ns, _) -> ns
methassoc meth =
let i = ns ++ nsOf meth
ns = case headns of
"" -> ""
mns -> mns ++ "."
in (i, methcorrn meth)
methmap = mkmethmap M.empty (map methassoc mtsigs)
-- mkmethmap :: M.Map String (H.HsDecl, [(String, String)]) -> [(String, (H.HsDecl, [(String, String)]))] -> M.Map String (H.HsDecl, [(String, String)])
mkmethmap m [] = m
mkmethmap m ((i, meth) : ims) = mkmethmap addmeth ims where
addmeth = case M.lookup i m of
Nothing -> M.insert i [meth] m
(Just meths) -> M.insert i (meth : meths) m
submods :: [(H.HsModule, String -> Maybe String)]
submods = M.elems $ M.mapWithKey mksubmod methmap
mksubmod :: String -> [(H.HsDecl, [(String, String)])] -> (H.HsModule, String -> Maybe String)
mksubmod iid smdecls =
(H.HsModule nullLoc (H.Module iid) (Just subexp)
-- (mkModImport modid : (imps ++ docimp))
(map (mkModImport . H.Module) ([
"Prelude hiding (drop, error, print)"
, "Data.Typeable (Typeable)"
, "Foreign.Marshal (maybePeek, maybeWith)"
, "System.Glib.FFI (maybeNull, withForeignPtr, nullForeignPtr, Ptr, nullPtr, castPtr, Word, Int64, Word64, CChar(..), CInt(..), CUInt(..), CLong(..), CULong(..), CLLong(..), CULLong(..), CShort(..), CUShort(..), CFloat(..), CDouble(..), toBool, fromBool)"
, "System.Glib.UTFString (GlibString(..), readUTFString)"
, "Control.Applicative ((<$>))"
, "Control.Monad (void)"
, "Control.Monad.IO.Class (MonadIO(..))"
, "System.Glib.GError"
, "Graphics.UI.Gtk.WebKit.DOM.EventTargetClosures"
] ++ if name == "Enums"
then []
else eventImp iid ++ ["Graphics.UI.Gtk.WebKit.Types", "Graphics.UI.Gtk.WebKit.DOM.Enums"]))
(H.HsFunBind [] : map fst smdecls), comment) where
renameMap :: M.Map String String
renameMap = M.fromList $ concatMap snd smdecls
realName :: String -> String
realName s = case M.lookup s renameMap of
Just "" -> ""
Just n -> "." ++ n
Nothing -> ""
comment :: String -> Maybe String
comment n = do
iname <- stripPrefix "GHCJS.DOM." iid
return $ "\n-- | <https://developer.mozilla.org/en-US/docs/Web/API/"
++ jsname iname ++ realName n ++ " Mozilla " ++ jsname iname ++ realName n ++ " documentation>"
name = typeFor . reverse . takeWhile (/= '.') $ reverse iid
-- subexp = map mkEIdent . nub $ (filter (not . isSuffixOf "'") $ map declname smdecls) ++
subexp = nub $ map (mkEIdent . fst) smdecls ++
if name == "Enums"
then []
else map (H.HsEVar . H.UnQual . H.HsIdent) ([name, "castTo" ++ name, "gType" ++ name] ++ parentExp)
parentExp = [name ++ "Class", "to" ++ name]
eventImp "Graphics.UI.Gtk.WebKit.DOM.Event" = []
eventImp "Graphics.UI.Gtk.WebKit.DOM.UIEvent" = []
eventImp "Graphics.UI.Gtk.WebKit.DOM.MouseEvent" = []
eventImp "Graphics.UI.Gtk.WebKit.DOM.EventTarget" = []
eventImp _ = ["Graphics.UI.Gtk.WebKit.DOM.EventM"]
docimp = []
-- docimp = case "createElement" `elem` (map declname smdecls) of
-- True -> []
-- _ -> [(mkModImport (H.Module docmod))
-- {H.importSpecs = Just (False, [H.HsIVar $ H.HsIdent "createElement"])}] where
-- docmod = concat $ intersperse "." $ reverse
-- ("Document" : tail (reverse $ parts (== '.') iid))
-- Loop through the list of toplevel parse results (modules, pragmas).
-- Pragmas modify state, modules don't.
domLoop :: DOMState -> [I.Defn] -> DOMState
domLoop st [] = st
domLoop st (def : defs) = case def of
I.Pragma prgm -> domLoop (prgm2State st (dropWhile isSpace prgm)) defs
I.Module id moddef ->
let prmod = mod2mod st (I.Module id' moddef)
modn = ns st ++
renameMod
(intercalate "." (reverse $ parts (== '.') (getDef def)))
id' = I.Id modn
imp' = modn : imp st
modl = prmod : procmod st in
domLoop st {procmod = modl, imp = imp'} defs
z ->
let logmsg = "Expected a Module or a Pragma; found " ++ show z in
domLoop st {convlog = convlog st ++ [logmsg]} defs
-- Modify DOMState based on a pragma encountered
prgm2State :: DOMState -> String -> DOMState
prgm2State st ('n':'a':'m':'e':'s':'p':'a':'c':'e':nns) =
let nnsst = read (dropWhile isSpace nns)
dot = if null nnsst then "" else "." in
st {ns = nnsst ++ dot}
prgm2State st upgm =
let logmsg = "Unknown pragma " ++ upgm in
st {convlog = convlog st ++ [logmsg]}
-- Validate a map of interface inheritance. Any "Left" parent identifier
-- causes a log message to be produced. It is also checked that an interface
-- does not have itself as a parent. Circular inheritance is not checked.
valParentMap :: M.Map String [Either String String] -> [String]
valParentMap pm = concat (M.elems m2) where
m2 = M.mapWithKey lefts pm
lefts intf = concatMap (leftmsg intf)
leftmsg intf (Right _) = []
leftmsg "InternalSettings" _ = []
leftmsg intf (Left p) = ["Interface " ++ intf ++ " has " ++ p ++ " as a parent, but " ++
p ++ " is not defined anywhere"]
-- Prepare a complete map of interfaces inheritance. All ancestors
-- must be defined in the IDL module being processed plus in other
-- modules it includes.
mkParentMap :: [I.Defn] -> M.Map String [Either String String]
mkParentMap defns = m2 where
allintfs = nub $ concatMap getintfs defns
getintfs (I.Module _ moddefs) = filter intfOnly moddefs
getintfs _ = []
m1 = M.fromList $ zip (map getDef allintfs) allintfs
m2 = M.fromList (map getparents allintfs)
getparents i@(I.Interface (I.Id intf) supers _ extAttrs _) = (getDef i, concatMap parent allSupers)
where
allSupers | intf /= "EventTarget" && I.ExtAttr (I.Id "EventTarget") [] `elem` extAttrs = "EventTarget" : supers
| otherwise = supers
parent pidf = if pidf `M.member` m1 then
Right pidf : snd (getparents (fromJust $ M.lookup pidf m1)) else
[Left pidf]
-- Fake source location
nullLoc = H.SrcLoc {H.srcFilename = "", H.srcLine = 0, H.srcColumn = 0}
-- A list of single-letter formal argument names (max. 26)
azList = map (: []) ['a' .. 'z']
azHIList = map H.HsIdent azList
-- Rename a module. First character of module name is uppercased. Each
-- underscore followed by a character causes that character uppercased.
renameMod :: String -> String
renameMod "" = ""
renameMod (m:odule) = toUpper m : renameMod' odule where
renameMod' "" = ""
renameMod' ('_':o:dule) = '.' : toUpper o : renameMod' dule
renameMod' ('.':o:dule) = '.' : toUpper o : renameMod' dule
renameMod' (o:dule) = o : renameMod' dule
-- Module converter mutable state (kind of)
data DOMState = DOMState {
pm :: M.Map String [Either String String] -- inheritance map
,imp :: [String] -- import list
,ns :: String -- output module namespace (#pragma namespace)
,procmod :: [H.HsModule] -- modules already processed
,convlog :: [String] -- conversion messages
} deriving (Show)
-- Helpers to produce class and datatype identifiers out of DOM identifiers
classFor s = typeFor s ++ "Class"
--typeFor "Range" = "DOMRange"
--typeFor "Screen" = "DOMScreen"
--typeFor "Attr" = "DOMAttr"
typeFor "Key" = "CryptoKey"
typeFor "AlgorithmIdentifier" = "DOMString"
typeFor "KeyFormat" = "DOMString"
-- typeFor "XMLHttpRequestResponseType" = "DOMString"
typeFor "custom" = "CanvasStyle"
typeFor s = jsname' s
fixType (I.TyName s x) = I.TyName (typeFor s) x
fixType (I.TyOptional a) = I.TyOptional (fixType a)
fixType x = x
fixDefn (I.Attribute a b c d e) = I.Attribute a b (fixType c) d e
fixDefn (I.Operation a b c d e) = I.Operation (fixId a) (fixType b) c d e
fixDefn (I.Interface a b c d e) = I.Interface a b (map fixDefn c) d e
fixDefn x = x
fixId (I.FunId a b c) = I.FunId (fixId a) b (map fixParam c)
fixId x = x
fixParam (I.Param a b c d e) = I.Param a b (fixType c) d e
-- Convert an IDL module definition into Haskell module syntax
mod2mod :: DOMState -> I.Defn -> H.HsModule
mod2mod st md@(I.Module _ moddefs') =
H.HsModule nullLoc (H.Module modid') (Just []) imps decls where
moddefs = map fixDefn moddefs'
enums = concatMap getEnums moddefs
all = concatMap getAllInterfaces moddefs
parents = nub $ concatMap getParents moddefs
leaves = map typeFor $ filter (`notElem` parents) all
isLeaf = flip elem leaves . typeFor
modlst = ["Control.Monad"]
modid' = renameMod $ getDef md
imps = [] -- map mkModImport (map H.Module (modlst ++ imp st))
intfs = filter intfOnly moddefs
eqop op1 op2 = getDef op1 == getDef op2
decls = types ++ classes ++ instances ++ methods ++ attrs ++ makers
makers = concatMap intf2maker intfs
classes = concatMap intf2class intfs
methods = concatMap (intf2meth enums) intfs
types = domEnumClass : concatMap intf2type moddefs
attrs = concatMap (intf2attr enums) intfs
instances = concatMap (intf2inst $ pm st) intfs
mod2mod _ z = error $ "Input of mod2mod should be a Module but is " ++ show z
domEnumClass = H.HsClassDecl nullLoc [] (H.HsIdent "Enums||DomEnum") [H.HsIdent "e"] [
H.HsTypeSig nullLoc [H.HsIdent "enumToString"] (H.HsQualType [] (H.HsTyFun (mkTIdent "e") (mkTIdent "String"))),
H.HsTypeSig nullLoc [H.HsIdent "stringToEnum"] (H.HsQualType [] (H.HsTyFun (mkTIdent "String") (mkTIdent "e")))]
-- Create a module import declaration
mkModImport :: H.Module -> H.HsImportDecl
mkModImport s = H.HsImportDecl {H.importLoc = nullLoc
,H.importQualified = False
,H.importModule = s
,H.importAs = Nothing
,H.importSpecs = Nothing}
-- For each interface, locate it in the inheritance map,
-- and produce instance declarations for the corresponding datatype.
intf2inst :: M.Map String [Either String String] -> I.Defn -> [H.HsDecl]
intf2inst pm intf@(I.Interface{}) = self : parents where
sid = getDef intf
self = mkInstDecl sid sid
parents = case M.lookup sid pm of
Nothing -> []
Just ess -> map (flip mkInstDecl sid . either id id) ess
intf2inst _ _ = []
-- For each interface found, define a newtype with the same name
intf2type :: I.Defn -> [H.HsDecl]
--intf2type intf@(I.Interface _ _ _ _ _) =
-- let typename = H.HsIdent (typeFor $ getDef intf) in
-- [H.HsDataDecl nullLoc [] typename []
-- [H.HsConDecl nullLoc typename []] []]
intf2type (I.TypeDecl (I.TyEnum (Just (I.Id typename)) vals)) =
[H.HsDataDecl nullLoc [] (H.HsIdent $ "Enums||" ++ typename) []
(map constructor vals) (map (H.UnQual . H.HsIdent) ["Show", "Read", "Eq", "Ord", "Typeable"]),
H.HsInstDecl nullLoc [] (H.UnQual $ H.HsIdent "Enums||DomEnum")
[H.HsTyCon . H.UnQual $ H.HsIdent typename]
[H.HsFunBind (map toString vals), H.HsFunBind (map fromString vals)]
]
where
constructor (Right n, _, Nothing) = H.HsConDecl nullLoc (H.HsIdent $ typename ++ conName n) []
constructor val = error $ "Unhandled enum value " ++ show val
toString (Right n, _, Nothing) =
H.HsMatch nullLoc (H.HsIdent "enumToString") [H.HsPVar . H.HsIdent $ typename ++ conName n]
(H.HsUnGuardedRhs . H.HsLit $ H.HsString n) []
toString val = error $ "Unhandled enum value " ++ show val
fromString (Right n, _, Nothing) =
H.HsMatch nullLoc (H.HsIdent "stringToEnum") [H.HsPLit $ H.HsString n]
(H.HsUnGuardedRhs . H.HsVar . H.UnQual . H.HsIdent $ typename ++ conName n) []
fromString val = error $ "Unhandled enum value " ++ show val
conName = concatMap conPart . splitOn "-"
conPart (initial : rest) = toUpper initial : rest
conPart [] = ""
intf2type _ = []
-- Convert an Interface specification into a class specification
intf2class :: I.Defn -> [H.HsDecl]
intf2class intf@(I.Interface _ supers _ _ _) =
[H.HsClassDecl nullLoc sups (H.HsIdent (classFor $ getDef intf)) (take 1 azHIList) []] where
sups = map name2ctxt supers
intf2class _ = []
-- Convert a name to a type context assertion (assume single parameter class)
name2ctxt name = (mkUIdent $ classFor name, [H.HsTyVar $ head azHIList])
-- A helper function to produce an unqualified identifier
mkUIdent = H.UnQual . H.HsIdent
mkSymbol = H.UnQual . H.HsSymbol
-- A filter to select only operations (methods)
opsOnly :: I.Defn -> Bool
opsOnly (I.Operation{}) = True
opsOnly _ = False
-- A filter to select only attributes
attrOnly :: I.Defn -> Bool
attrOnly (I.Attribute{}) = True
attrOnly _ = False
-- A filter to select only interfaces (classes)
intfOnly :: I.Defn -> Bool
intfOnly (I.Interface _ _ cldefs _ _) = True
intfOnly _ = False
-- A filter to select only constant definitions
constOnly :: I.Defn -> Bool
constOnly (I.Constant{}) = True
constOnly _ = False
-- Collect all operations defined in an interface
collectOps :: I.Defn -> [I.Defn]
collectOps (I.Interface _ _ cldefs _ _) =
filter opsOnly cldefs
collectOps _ = []
-- Collect all constants defined in an interface
collectConst :: I.Defn -> [I.Defn]
collectConst (I.Interface _ _ cldefs _ _) =
filter constOnly cldefs
collectConst _ = []
-- Collect all attributes defined in an interface
collectAttrs :: I.Defn -> [I.Defn]
collectAttrs (I.Interface _ _ cldefs _ _) =
filter attrOnly cldefs
collectAttrs _ = []
-- Declare an instance (very simple case, no context, no methods only one class parameter)
mkInstDecl :: String -> String -> H.HsDecl
mkInstDecl clname typename =
H.HsInstDecl nullLoc [] (mkUIdent $ classFor clname) [mkTIdent $ typeFor typename] []
-- For certain interfaces (ancestors of HTMLElement), special maker functions
-- are introduced to simplify creation of the formers.
intf2maker :: I.Defn -> [H.HsDecl]
--intf2maker intf@(I.Interface (I.Id iid) _ _) =
-- case (tagFor iid) of
-- "" -> []
-- tag -> [mktsig, mkimpl] where
-- mkimpl =
-- let defmaker = iid ++ "|mk" ++ renameMod tag
-- flipv = mkVar "flip"
-- crelv = mkVar "createElement"
-- exprv = mkVar "StringLit"
-- tags = H.HsLit (H.HsString tag)
-- tagv = H.HsApp (H.HsApp exprv tags) tags
-- rhs = H.HsUnGuardedRhs (H.HsApp crelv $ H.HsParen tagv)
-- match = H.HsMatch nullLoc (H.HsIdent defmaker) [] rhs [] in
-- H.HsFunBind [match]
-- mktsig =
-- let monadtv = mkTIdent "IO"
-- -- exprtv = mkTIdent "Expression"
-- defmaker = iid ++ "|mk" ++ renameMod tag
-- parms = [H.HsIdent "a"]
-- actx = (mkUIdent (classFor "HTMLDocument"),[mkTIdent "a"])
-- -- monadctx = (mkUIdent "Monad",[monadtv])
-- tpsig = mkTsig (map (H.HsTyVar) parms)
-- (H.HsTyApp monadtv (mkTIdent (typeFor iid)))
-- retts = H.HsQualType (actx : []) tpsig in
-- H.HsTypeSig nullLoc [H.HsIdent defmaker] retts
intf2maker _ = []
-- Tag values corresponding to certain HTML element interfaces
tagFor "HTMLButtonElement" = "button"
tagFor "HTMLDivElement" = "div"
tagFor "HTMLImageElement" = "img"
tagFor "HTMLAppletElement" = "applet"
tagFor "HTMLFontElement" = "font"
tagFor "HTMLFormElement" = "form"
tagFor "HTMLFrameElement" = "frame"
tagFor "HTMLInputElement" = "input"
tagFor "HTMLObjectElement" = "object"
tagFor "HTMLParagraphElement" = "p"
tagFor "HTMLParamElement" = "param"
tagFor "HTMLPreElement" = "pre"
tagFor "HTMLScriptElement" = "script"
tagFor "HTMLTableCellElement" = "td"
tagFor "HTMLTableColElement" = "col"
tagFor "HTMLTableElement" = "table"
tagFor "HTMLTableRowElement" = "tr"
tagFor "HTMLTextAreaElement" = "textarea"
tagFor "HTMLBRElement" = "br"
tagFor "HTMLHRElement" = "hr"
tagFor "HTMLLIElement" = "li"
tagFor "HTMLDListElement" = "dl"
tagFor "HTMLOListElement" = "ol"
tagFor "HTMLUListElement" = "ul"
tagFor _ = ""
-- Attributes are represented by methods with proper type signatures.
-- These methods are wrappers around type-neutral unsafe get/set property
-- functions.
intf2attr :: [String] -> I.Defn -> [H.HsDecl]
intf2attr enums intf@(I.Interface (I.Id iid') _ cldefs _ _) =
concatMap mkattr (collectAttrs intf) where
iid = jsname' iid'
mkattr (I.Attribute [] _ _ _ _) = []
mkattr (I.Attribute _ _ (I.TyName "MediaQueryListListener" _) _ _) = []
mkattr (I.Attribute _ _ (I.TyName "Crypto" _) _ _) = []
mkattr (I.Attribute [I.Id "type"] _ _ _ _) = []
mkattr (I.Attribute [I.Id "URL"] _ _ _ _) = []
mkattr (I.Attribute [I.Id "location"] _ _ _ _) = []
mkattr (I.Attribute [I.Id "valueAsDate"] _ _ _ _) = []
mkattr (I.Attribute [I.Id "webkitPeerConnection"] _ _ _ _) = []
mkattr (I.Attribute [I.Id "contentType"] _ _ _ _) | iid == "Document" = []
mkattr (I.Attribute [I.Id "pointerLockElement"] _ _ _ _) | iid == "Document" = []
mkattr (I.Attribute [I.Id "origin"] _ _ _ _) | iid == "Document" = []
mkattr (I.Attribute _ _ _ _ ext) | I.ExtAttr (I.Id "Custom") [] `elem` ext = []
mkattr (I.Attribute _ _ _ _ ext) | I.ExtAttr (I.Id "CustomSetter") [] `elem` ext = []
mkattr (I.Attribute _ _ _ _ ext) | I.ExtAttr (I.Id "CustomGetter") [] `elem` ext = []
mkattr (I.Attribute [I.Id iat] _ (I.TyName "EventListener" _) _ _) = mkevent iid iat
mkattr (I.Attribute [I.Id iat] False tat raises ext) =
(if I.ExtAttr (I.Id "Replaceable") [] `elem` ext
then []
else mksetter iid iat tat raises ext)
++ mkgetter iid iat tat raises ext
mkattr (I.Attribute [I.Id iat] True tat raises ext) = mkgetter iid iat tat raises ext
mkattr (I.Attribute (iatt:iats) b tat raises ext) =
mkattr (I.Attribute [iatt] b tat raises ext) ++ mkattr (I.Attribute iats b tat raises ext)
mksetter iid iat tat r ext = [stsig iid iat tat ext, simpl iid iat tat r ext]
monadtv = mkTIdent "m"
setf intf iat = "set" ++ U.toUpperHead iat
getf intf iat = "get" ++ U.toUpperHead iat
eventName iat = fromMaybe iat (stripPrefix "on" iat)
eventf intf iat = U.toLowerInitCamel $ fixEventName (getDef intf) iat
simpl iid iat tat raises ext =
let defset = iid ++ "|" ++ iat ++ "|" ++ setf intf iat
ffi = foldl H.HsApp (mkVar "{#") [H.HsVar . H.UnQual . H.HsIdent $ "call",
H.HsVar . H.UnQual . H.HsIdent $ "webkit_dom_" ++ gtkName iid (setf intf iat),
mkVar "#}"]
parms = [H.HsPVar $ H.HsIdent "self", H.HsPVar $ H.HsIdent "val"]
call = (H.HsApp ffi . H.HsParen $ H.HsApp
(H.HsVar . H.UnQual . H.HsIdent $ "to" ++ typeFor (getDef intf))
(H.HsVar . H.UnQual $ H.HsIdent "self"))
val = I.Param I.Required (I.Id "val") tat [I.Mode In] ext
canRaise = not (null (I.setterRaises raises)) ||
I.ExtAttr (I.Id "SetterRaisesException") [] `elem` ext
rhs = H.HsUnGuardedRhs $ H.HsApp (mkVar "liftIO") . H.HsParen $ propExcept canRaise $ applyParam enums val call
match = H.HsMatch nullLoc (H.HsIdent defset) parms rhs [] in
H.HsFunBind [match]
stsig iid iat tat ext =
let ityp = I.TyName iid Nothing
defset = iid ++ "|" ++ iat ++ "|" ++ setf intf iat
parm = [I.Param I.Required (I.Id "val") tat [I.Mode In] ext]
parms = mkTIdent "self" : map (fst . tyParm enums) parm
contxt = (mkUIdent "MonadIO", [mkTIdent "m"]) : concatMap (snd . tyParm enums) parm ++
ctxRet enums ityp ++ ctxString (ityp : map paramType parm)
tpsig = mkTsig parms (H.HsTyApp monadtv $ H.HsTyCon (H.Special H.HsUnitCon))
retts = H.HsQualType contxt tpsig in
H.HsTypeSig nullLoc [H.HsIdent defset] retts
mkgetter iid iat tat r ext = [gtsig iid iat tat ext, gimpl iid iat tat r ext]
gimpl iid iat tat raises ext =
let defget = iid ++ "|" ++ iat ++ "|" ++ getf intf iat
ffi = foldl H.HsApp (mkVar "{#") [H.HsVar . H.UnQual . H.HsIdent $ "call",
H.HsVar . H.UnQual . H.HsIdent $ "webkit_dom_" ++ gtkName iid (getf intf iat),
mkVar "#}"]
parm = H.HsPVar $ H.HsIdent "self"
call = (H.HsApp ffi . H.HsParen $ H.HsApp
(H.HsVar . H.UnQual . H.HsIdent $ "to" ++ typeFor (getDef intf))
(H.HsVar . H.UnQual $ H.HsIdent "self"))
canRaise = not (null (I.getterRaises raises)) ||
I.ExtAttr (I.Id "GetterRaisesException") [] `elem` ext
rhs = H.HsUnGuardedRhs $ H.HsApp (mkVar "liftIO") . H.HsParen $ returnType enums tat ext $ propExcept canRaise call