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
|
{-# OPTIONS_CYMAKE -Wno-incomplete-patterns #-}
module CurryDoc.Html where
import Prelude hiding ( empty )
import System.FilePath
import System.Directory ( getFileWithSuffix )
import Data.List
import Data.Char
import Data.Time
import Data.Maybe
import AbstractCurry.Types
import AbstractCurry.Files
import AbstractCurry.Select
import AbstractCurry.Build
import AbstractCurry.Pretty
import Analysis.TotallyDefined(Completeness(..))
import qualified FlatCurry.Types as FC
import qualified FlatCurry.Goodies as FCG
import HTML.Base
import HTML.Styles.Bootstrap3 ( bootstrapPage, glyphicon, homeIcon )
import HTML.CategorizedList
import System.CurryPath ( getLoadPathForModule )
import System.FrontendExec ( FrontendTarget (..), callFrontendWithParams
, defaultParams, setHtmlDir, setQuiet )
import Text.Markdown
import Text.Pretty ( showWidth, empty )
import CurryDoc.AnaInfo
import CurryDoc.Options
import CurryDoc.Read
import CurryDoc.Config
infixl 0 `withTitle`
generateHtmlDocs :: DocOptions -> AnaInfo -> String -> String
-> [(SourceLine,String)] -> IO String
generateHtmlDocs opts anainfo modname modcmts progcmts = do
acyname <- getLoadPathForModule modname >>=
getFileWithSuffix (abstractCurryFileName modname) [""]
putStrLn $ "Reading AbstractCurry program \""++acyname++"\"..."
(CurryProg _ imports _ _ _ types functions ops) <-
readAbstractCurryFile acyname
let
exptypes = filter isExportedType types
expfuns = filter isExportedFun functions
propspecs = map cmtFunc2Func
(filter (\fd -> isProperty fd || isSpecFunc fd) functions)
navigation =
[ bold [htxt "Exported names:"]
, genHtmlExportIndex (map tName exptypes)
(getExportedCons types)
(getExportedFields types)
(map fName expfuns)
, anchored "imported_modules" [bold [htxt "Imported modules:"]]
, ulist (map (\i -> [href (docURL opts i ++ ".html") [htxt i]])
(nub (if modname /= "Prelude" then "Prelude" : imports
else imports)))
`addClass` "nav nav-sidebar"
]
content =
genHtmlModule opts modcmts ++
[ h2 [htxt "Summary of exported operations:"]
, borderedTable (map (genHtmlFuncShort opts progcmts anainfo) expfuns)
] ++
ifNotNull exptypes (\tys ->
[anchoredSection "exported_datatypes"
(h2 [htxt "Exported datatypes:"] : hrule :
concatMap (genHtmlType opts progcmts) tys)]) ++
[anchoredSection "exported_operations"
(h2 [htxt "Exported operations:"] :
map (genHtmlFunc opts modname progcmts
(attachProperties2Funcs propspecs progcmts) anainfo ops)
expfuns)
]
mainPage title [htmltitle] (lefttopmenu types functions) rightTopMenu
navigation content
where
title = "Module " ++ modname
htmltitle = h1 [ htxt "Module "
, href (modname ++ "_curry.html") [htxt modname]
]
lefttopmenu :: [CTypeDecl] -> [CFuncDecl] -> [[BaseHtml]]
ts fs =
[[href "?" [htxt title]], [href "#imported_modules" [htxt "Imports"]]] ++
ifNotNull ts (const [[href "#exported_datatypes" [htxt "Datatypes" ]]]) ++
ifNotNull fs (const [[href "#exported_operations" [htxt "Operations"]]])
cmtFunc2Func fdecl = case fdecl of
CmtFunc _ qn a v tExp rs -> CFunc qn a v tExp rs
_ -> fdecl
data FuncAttachment = Property | PreCond | PostCond | SpecFun
deriving Eq
attachProperties2Funcs :: [CFuncDecl] -> [(SourceLine,String)]
-> [(String,[(FuncAttachment,String,[BaseHtml])])]
attachProperties2Funcs _ [] = []
attachProperties2Funcs props ((sourceline,_) : slines) =
case sourceline of
FuncDef fn -> let (fprops,rslines) = span isPropFuncDef slines
in (fn, showContracts fn ++ concatMap showProp fprops) :
attachProperties2Funcs props rslines
_ -> attachProperties2Funcs props slines
where
propNames = map (snd . funcName) props
showProp (FuncDef fn,_) =
let propdecl = fromJust (find (\fd -> snd (funcName fd) == fn) props)
in if isProperty propdecl
then map (\rhs -> (Property, fn,
[code [htxt $ prettyWith (ppCRhs empty) rhs]]))
(map ruleRHS (funcRules propdecl))
else []
showContracts fn =
showContract (fn++"'pre") showPreCond ++
showContract (fn++"'post") showPostCond ++
showContract (fn++"'spec") showSpec
showContract fnsuff formatrule =
maybe []
(\contractdecl -> showRulesWith formatrule fnsuff contractdecl)
(find (\fd -> snd (funcName fd) == fnsuff) props)
showRulesWith formatrule fnsuff (CFunc qn@(mn,fn) ar _ ftype rules) =
let stripSuffix = reverse . tail . dropWhile (/='\'') . reverse
in map (formatrule fnsuff qn (mn,stripSuffix fn)
. etaExpand ar (length (argTypes (typeOfQualType ftype)))) rules
etaExpand arity tarity rule = case rule of
CRule ps (CSimpleRhs exp ldecls) ->
if arity == tarity
then rule
else let evars = map (\i -> (i,"x"++show i)) [(arity+1) .. tarity]
in CRule (ps ++ map CPVar evars)
(CSimpleRhs (foldl CApply exp (map CVar evars)) ldecls)
_ -> rule
showPreCond fnpre qp qn rule = case rule of
CRule _ (CSimpleRhs _ _) ->
let (lhs,rhs) = break (=='=') (prettyRule qn rule)
in (PreCond, fnpre, [code [htxt $ "(" ++ stripSpaces lhs ++ ")"],
italic [htxt " requires "],
code [htxt (safeTail rhs)]])
_ ->
(PreCond, fnpre, [code [htxt $ prettyRule qp rule]])
showPostCond fnpost qp qn rule = case rule of
CRule ps (CSimpleRhs _ _) ->
let (_,rhs) = break (=='=') (prettyRule qn rule)
in (PostCond, fnpost,
[code [htxt $ prettyWith ppCPattern (last ps) ++ " = " ++
prettyWith ppCPattern
(CPComb qn (take (length ps - 1) ps)) ],
italic [htxt " satisfies "],
code [htxt (safeTail rhs)]])
_ ->
(PostCond, fnpost, [code [htxt $ prettyRule qp rule]])
showSpec fnspec qp qn rule = case rule of
CRule _ (CSimpleRhs _ _) ->
let (lhs,rhs) = break (=='=') (prettyRule qn rule)
in (SpecFun, fnspec, [code [htxt $ "(" ++ stripSpaces lhs ++ ")"],
italic [htxt " is equivalent to "],
code [htxt (safeTail rhs)]])
_ ->
(SpecFun, fnspec, [code [htxt $ prettyRule qp rule]])
prettyWith ppfun = showWidth 78 . ppfun prettyOpts
prettyRule qn rl = showWidth 78 (ppCRule prettyOpts qn rl)
prettyOpts = setNoQualification defaultOptions
safeTail xs = if null xs then xs else tail xs
isPropFuncDef (sline,_) =
case sline of FuncDef fn -> fn `elem` propNames
_ -> False
docComment2HTML :: DocOptions -> String -> [BaseHtml]
opts cmt
| null cmt = []
| withMarkdown opts = markdownText2HTML (replaceIdLinks opts cmt)
| otherwise = [par [BaseText (replaceIdLinks opts cmt)]]
replaceIdLinks :: DocOptions -> String -> String
replaceIdLinks opts str = case str of
[] -> []
('\\':'\'':cs) -> '\'' : replaceIdLinks opts cs
(c:cs) -> if c=='\'' then tryReplaceIdLink [] cs
else c : replaceIdLinks opts cs
where
tryReplaceIdLink ltxt [] = '\'' : reverse ltxt
tryReplaceIdLink ltxt (c:cs)
| isSpace c
= '\'' : reverse ltxt ++ c : replaceIdLinks opts cs
| c == '\''
= checkId (reverse ltxt) ++ replaceIdLinks opts cs
| otherwise
= tryReplaceIdLink (c:ltxt) cs
checkId s =
if ' ' `elem` s
then '\'' : s ++ ['\'']
else let (md,dotfun) = break (=='.') s
in "<code><a href=\"" ++
(if null dotfun then '#':s
else docURL opts md ++ ".html#" ++ tail dotfun) ++
"\">"++s++"</a></code>"
genHtmlExportIndex :: [String] -> [String] -> [String] -> [String] -> BaseHtml
genHtmlExportIndex exptypes expcons expfields expfuns =
BaseStruct "ul" [("class","nav nav-sidebar")]
(concatMap (\ (htmlnames,cattitle) ->
if null htmlnames
then []
else BaseStruct "li" [("class","nav-header")] [htxt cattitle] :
map (BaseStruct "li" []) htmlnames)
[(htmltypes,"Datatypes:"),
(htmlcons ,"Constructors:"),
(htmlfields,"Fields:"),
(htmlfuns ,"Operations:")])
where
htmltypes = map (\n->[href ('#':n) [htxt n]])
(nub (sortStrings exptypes))
htmlcons = map (\n->[href ('#':n++"_CONS") [htxt n]])
(nub (sortStrings expcons))
htmlfields = map (\n->[href ('#':n++"_FIELD") [htxt n]])
(nub (sortStrings expfields))
htmlfuns = map (\n->[href ('#':n) [htxt n]])
(nub (sortStrings expfuns))
tName :: CTypeDecl -> String
tName = snd . typeName
fName :: CFuncDecl -> String
fName = snd . funcName
cName :: CConsDecl -> String
cName = snd . consName
fldName :: CFieldDecl -> String
fldName (CField (_,name) _ _) = name
isExportedType :: CTypeDecl -> Bool
isExportedType = (== Public) . typeVis
isExportedCons :: CConsDecl -> Bool
isExportedCons = (== Public) . consVis
isExportedFun :: CFuncDecl -> Bool
isExportedFun = (== Public) . funcVis
isExportedField :: CFieldDecl -> Bool
isExportedField (CField _ vis _) = vis == Public
getExportedCons :: [CTypeDecl] -> [String]
getExportedCons = map cName . filter isExportedCons . concatMap typeCons
getExportedFields :: [CTypeDecl] -> [String]
getExportedFields = map fldName . filter isExportedField . concatMap getFields
. concatMap typeCons
where
getFields (CCons _ _ _ ) = []
getFields (CRecord _ _ fs) = fs
isProperty :: CFuncDecl -> Bool
isProperty fdecl = fst (funcName fdecl)
`notElem` [easyCheckModule, propModule, propTypesModule]
&& isPropType (typeOfQualType (funcType fdecl))
where
isPropType :: CTypeExpr -> Bool
isPropType ct = ct == baseType (propTypesModule,"PropIO")
|| resultType ct == baseType (propTypesModule,"Prop")
easyCheckModule = "Test.EasyCheck"
propModule = "Test.Prop"
propTypesModule = "Test.Prop.Types"
isSpecFunc :: CFuncDecl -> Bool
isSpecFunc fdecl =
let rfname = reverse (snd (funcName fdecl))
in any (`isPrefixOf` rfname) ["ceps'","erp'","tsop'"]
genHtmlModule :: DocOptions -> String -> [BaseHtml]
genHtmlModule docopts modcmts =
let (maincmt,avcmts) = splitComment modcmts
in docComment2HTML docopts maincmt ++
map (\a->par [bold [htxt "Author: "], htxt a])
(getCommentType "author" avcmts) ++
map (\a->par [bold [htxt "Version: "], htxt a])
(getCommentType "version" avcmts)
ulistOrEmpty :: [[BaseHtml]] -> [BaseHtml]
ulistOrEmpty items | null items = []
| otherwise = [ulist items]
ifNotNull :: [a] -> ([a] -> [b]) -> [b]
ifNotNull cmt genDoc
| null cmt = []
| otherwise = genDoc cmt
genHtmlType :: DocOptions -> [(SourceLine,String)] -> CTypeDecl -> [BaseHtml]
genHtmlType docopts progcmts (CType (_,tcons) _ tvars constrs _) =
let (datacmt,consfldcmts) = splitComment (getDataComment tcons progcmts)
in [ anchored tcons [style "typeheader" [htxt tcons]] ]
++ docComment2HTML docopts datacmt
++ [par [explainCat "Constructors:"]]
++ ulistOrEmpty (map (genHtmlCons docopts consfldcmts tcons tvars fldCons)
(filter isExportedCons constrs))
++ [hrule]
where
expFields = [f | CRecord _ _ fs <- constrs, f <- fs, isExportedField f]
fldCons = [ (fn,cn) | f@(CField (_,fn) _ _) <- expFields
, CRecord (_,cn) _ fs <- constrs, f `elem` fs
]
genHtmlType docopts progcmts (CTypeSyn (tcmod,tcons) _ tvars texp) =
let (typecmt,_) = splitComment (getDataComment tcons progcmts)
in [ anchored tcons [style "typeheader" [htxt tcons]] ]
++ docComment2HTML docopts typecmt
++ [ par [explainCat "Type synonym:"
, nbsp
,
if tcons=="String" && tcmod=="Prelude"
then code [htxt "String = [Char]"]
else code [BaseText
(tcons ++ concatMap (\(i,_) -> [' ',chr (97+i)]) tvars ++
" = " ++ showType docopts tcmod False texp)]]
, hrule
]
genHtmlType docopts progcmts t@(CNewType (_,tcons) _ tvars constr _) =
let (datacmt,consfldcmts) = splitComment (getDataComment tcons progcmts)
in if isExportedCons constr
then [anchored tcons [style "typeheader" [htxt tcons]] ]
++ docComment2HTML docopts datacmt
++ [par [explainCat "Constructor:"]]
++ ulistOrEmpty [genHtmlCons docopts consfldcmts tcons tvars fldCons constr]
++ [hrule]
else []
where
cn = cName constr
fldCons = map (\fn -> (fn,cn)) (getExportedFields [t])
genHtmlCons :: DocOptions -> [(String,String)] -> String -> [CTVarIName]
-> [(String,String)] -> CConsDecl -> [BaseHtml]
genHtmlCons docopts consfldcmts tcons tvars _
(CCons (cmod,cname) _ argtypes) =
anchored (cname ++ "_CONS")
[code [opnameDoc [htxt cname],
BaseText (" :: " ++
concatMap (\t -> " "++showType docopts cmod True t++" -> ")
argtypes ++
tcons ++ concatMap (\(i,_) -> [' ',chr (97+i)]) tvars)]] :
maybe []
(\ (_,cmt) -> htxt " : " : removeTopPar (docComment2HTML docopts
(removeDash cmt)))
(getConsComment conscmts cname)
where
conscmts = getCommentType "cons" consfldcmts
genHtmlCons docopts consfldcmts tcons tvars fldCons
(CRecord (cmod,cname) _ fields) =
anchored (cname ++ "_CONS")
[code [opnameDoc [htxt cname],
BaseText (" :: " ++
concatMap (\t -> " " ++ showType docopts cmod True t ++
" -> ")
argtypes ++
tcons ++ concatMap (\(i,_) -> [' ',chr (97+i)]) tvars)]] :
(maybe []
(\ (_,cmt) -> htxt " : " : removeTopPar (docComment2HTML docopts
(removeDash cmt)))
(getConsComment conscmts cname)) ++
par [explainCat "Fields:"] :
ulistOrEmpty (map (genHtmlField docopts fldcmts cname fldCons)
(filter isExportedField fields))
where
argtypes = map (\(CField _ _ t) -> t) fields
conscmts = getCommentType "cons" consfldcmts
fldcmts = getCommentType "field" consfldcmts
genHtmlField :: DocOptions -> [String] -> String -> [(String,String)]
-> CFieldDecl -> [BaseHtml]
genHtmlField docopts fldcmts cname fldCons (CField (fmod,fname) _ ty)
| withAnchor fname = [anchored (fname ++ "_FIELD") html]
| otherwise = html
where
withAnchor f = maybe False (== cname) (lookup f fldCons)
html = [ code [opnameDoc [htxt fname]
, BaseText (" :: " ++ showType docopts fmod True ty)]
] ++ maybe []
(\ (_,cmt) -> htxt " : " : removeTopPar
(docComment2HTML docopts (removeDash cmt)))
(getConsComment fldcmts fname)
genHtmlFuncShort :: DocOptions -> [(SourceLine,String)] -> AnaInfo -> CFuncDecl
-> [[BaseHtml]]
genHtmlFuncShort docopts progcmts anainfo
(CFunc (fmod,fname) _ _ ftype _) =
[[code [opnameDoc
[anchored (fname ++ "_SHORT")
[href ('#':fname) [htxt (showId fname)]]],
BaseText (" :: " ++ showQualType docopts fmod ftype)],
nbsp, nbsp]
++ genFuncPropIcons anainfo (fmod,fname) ++
[breakline] ++
removeTopPar
(docComment2HTML docopts
(firstSentence (fst (splitComment
(getFuncComment fname progcmts)))))]
genHtmlFuncShort docopts progcmts anainfo (CmtFunc _ n a vis ftype rules) =
genHtmlFuncShort docopts progcmts anainfo (CFunc n a vis ftype rules)
genHtmlFunc :: DocOptions -> String -> [(SourceLine,String)]
-> [(String,[(FuncAttachment,String,[BaseHtml])])] -> AnaInfo
-> [COpDecl] -> CFuncDecl -> BaseHtml
genHtmlFunc docopts modname progcmts funcattachments anainfo ops
(CmtFunc _ n a vis ftype rules) =
genHtmlFunc docopts modname progcmts funcattachments anainfo ops
(CFunc n a vis ftype rules)
genHtmlFunc docopts modname progcmts funcattachments anainfo ops
(CFunc (fmod,fname) _ _ ftype rules) =
let (funcmt,paramcmts) = splitComment (getFuncComment fname progcmts)
in anchoredDiv fname
[borderedTable [[
[par $
[code [opnameDoc [showCodeHRef fname],
BaseText (" :: "++ showQualType docopts fmod ftype)],
nbsp, nbsp] ++
genFuncPropIcons anainfo (fmod,fname)] ++
docComment2HTML docopts funcmt ++
genParamComment paramcmts ++
showAttachments "Precondition" PreCond ++
showAttachments "Postcondition" PostCond ++
showAttachments "Specification" SpecFun ++
showAttachments "Properties" Property ++
(if null furtherInfos
then []
else [dlist [([explainCat "Further infos:"],
[ulist furtherInfos])]] )]]]
where
showCodeHRef fn = href (modname++"_curry.html#"++fn) [htxt (showId fn)]
showAttachments aname attachkind =
let attachfuns = filter (\ (k,_,_) -> k==attachkind)
(maybe [] id (lookup fname funcattachments))
in if null attachfuns then [] else
[dlist [([explainCat (aname++":")],
[par (intercalate [breakline]
(map (\ (_,pn,pc) -> pc ++
[nbsp, htxt "(", showCodeHRef pn, htxt ")"])
attachfuns))])]]
furtherInfos = genFuncPropComments anainfo (fmod,fname) rules ops
paramcmts =
let params = map (span isIdChar) (getCommentType "param" paramcmts)
ret = getCommentType "return" paramcmts
in ifNotNull params (\parCmts ->
[ dlist [([explainCat "Example call:"],
[code [htxt (showCall fname (map fst params))]])
]
, dlist [([explainCat "Parameters:"],
[ulist (map (\ (parid,parcmt) ->
[code [htxt parid], htxt " : "] ++
removeTopPar (docComment2HTML docopts
(removeDash parcmt)))
parCmts)])]
])
++ ifNotNull ret (\retCmt -> [dlist (map (\rescmt ->
([explainCat "Returns:"],
removeTopPar (docComment2HTML docopts rescmt))) retCmt)])
showCall f params =
if isAlpha (head f) || length params /= 2
then "(" ++ showId f ++ concatMap (" "++) params ++ ")"
else "(" ++ params!!0 ++ " " ++ f ++ " " ++ params!!1 ++ ")"
removeDash :: String -> String
removeDash s = let ds = dropWhile isSpace s in
if take 2 ds == "- " then dropWhile isSpace (drop 2 ds)
else ds
removeTopPar :: [BaseHtml] -> [BaseHtml]
removeTopPar hexps = case hexps of
[BaseStruct "p" [] hs] -> hs
_ -> hexps
genFuncPropIcons :: AnaInfo -> QName -> [BaseHtml]
genFuncPropIcons anainfo fname =
[detPropIcon, nbsp]
where
detPropIcon =
if getNondetInfo anainfo fname
then href "index.html#nondet_explain" [nondetIcon]
else href "index.html#det_explain" [detIcon]
genFuncPropComments :: AnaInfo -> QName -> [CRule] -> [COpDecl] -> [[BaseHtml]]
anainfo fname rules ops =
filter (not . null)
[genFixityInfo fname ops,
completenessInfo,
indeterminismInfo,
opcompleteInfo,
externalInfo rules]
where
completenessInfo = let ci = getCompleteInfo anainfo fname in
if ci == Complete
then []
else [htxt (if ci == InComplete
then "partially defined"
else
"partially defined in each disjunction (but might be complete)")]
indeterminismInfo = if getIndetInfo anainfo fname
then [htxt "might behave indeterministically"]
else []
opcompleteInfo =
if getOpCompleteInfo anainfo fname
then [htxt "solution complete, i.e., able to compute all solutions"]
else []
externalInfo [] = [htxt "externally defined"]
externalInfo (_:_) = []
genFixityInfo :: QName -> [COpDecl] -> [BaseHtml]
genFixityInfo fname ops =
concatMap (\(COp n fix prec)->
if n == fname
then [htxt ("defined as "++showFixity fix++
" infix operator with precedence "++show prec)]
else [])
ops
where
showFixity CInfixOp = "non-associative"
showFixity CInfixlOp = "left-associative"
showFixity CInfixrOp = "right-associative"
showQualType :: DocOptions -> String -> CQualTypeExpr -> String
showQualType opts mod (CQualType ctxt texp) =
unwords [showContext opts mod ctxt, showType opts mod False texp]
showContext :: DocOptions -> String -> CContext -> String
showContext _ _ (CContext []) = ""
showContext opts mod (CContext [clscon]) =
showConstraint opts mod clscon ++ " =>"
showContext opts mod (CContext ctxt@(_:_:_)) =
brackets True (intercalate ", " (map (showConstraint opts mod) ctxt)) ++ " =>"
showConstraint :: DocOptions -> String -> CConstraint -> String
showConstraint opts mod (cn,texp) =
showTypeCons opts mod cn ++ " " ++ showType opts mod True texp
showType :: DocOptions -> String -> Bool -> CTypeExpr -> String
showType opts mod nested texp = case texp of
CTVar (i,_) -> [chr (97+i)]
CFuncType t1 t2 ->
brackets nested (showType opts mod (isFunctionalType t1) t1 ++ " -> " ++
showType opts mod False t2)
CTCons tc -> showTConsType opts mod nested tc []
CTApply t1 t2 ->
maybe (brackets nested $
showType opts mod True t1 ++ " " ++ showType opts mod True t2)
(\ (tc,ts) -> showTConsType opts mod nested tc ts)
(tconsArgsOfType texp)
showTConsType :: DocOptions -> String -> Bool -> QName -> [CTypeExpr] -> String
showTConsType opts mod nested tc ts
| ts==[] = showTypeCons opts mod tc
| tc==("Prelude","[]") && (head ts == CTCons ("Prelude","Char"))
= "String"
| tc==("Prelude","[]")
= "[" ++ showType opts mod False (head ts) ++ "]"
| take 2 (snd tc) == "(,"
= "(" ++ concat (intersperse "," (map (showType opts mod False) ts)) ++ ")"
| otherwise
= brackets nested
(showTypeCons opts mod tc ++ " " ++
concat (intersperse " " (map (showType opts mod True) ts)))
showTypeCons :: DocOptions -> String -> QName -> String
showTypeCons opts mod (mtc,tc) =
if mtc == "Prelude"
then tc
else
if mod == mtc
then "<a href=\"#"++tc++"\">"++tc++"</a>"
else "<a href=\""++docURL opts mtc++".html#"++tc++"\">"++tc++"</a>"
translateSource2ColoredHtml :: String -> String -> IO ()
translateSource2ColoredHtml docdir modname = do
let output = docdir </> modname++"_curry.html"
putStrLn ("Writing source file as HTML to \""++output++"\"...")
callFrontendWithParams HTML
(setQuiet True (setHtmlDir docdir defaultParams)) modname
translateSource2AnchoredHtml :: String -> String -> IO ()
translateSource2AnchoredHtml docdir modname =
do putStrLn ("Writing source file as HTML to \""++docdir++"/"++modname++"_curry.html\"...")
prog <- readFile (modname++".curry")
writeFile (docdir </> modname++"_curry.html")
(showPageWithDocStyle (modname++".curry")
[BaseStruct "pre" []
[BaseText (addFuncAnchors [] (lines prog))]])
addFuncAnchors :: [String] -> [String] -> String
addFuncAnchors _ [] = ""
addFuncAnchors ancs (sl : sls) = let id1 = getFirstId sl in
if id1=="" ||
id1 `elem` ["data","type","import","module","infix","infixl","infixr"]
then htmlQuote (sl++"\n") ++ addFuncAnchors ancs sls
else if id1 `elem` ancs
then (sl++"\n") ++ addFuncAnchors ancs sls
else "<a name=\""++id1++"\"></a>"
++ htmlQuote (sl++"\n")
++ addFuncAnchors (id1:ancs) sls
genMainIndexPage :: DocOptions -> String -> [String] -> IO ()
genMainIndexPage docopts docdir modnames =
do putStrLn ("Writing index page to \""++docdir++"/index.html\"...")
simplePage "Documentation of Curry modules"
(Just pageTitle)
allConsFuncsMenu (indexPage modnames)
>>= writeFile (docdir++"/index.html")
where
pageTitle = if not (null (mainTitle docopts))
then [htxt (mainTitle docopts)]
else if length modnames == 1
then [htxt "Documentation of the Curry program ",
href (head modnames ++ ".html")
[htxt (head modnames)]]
else [htxt "Documentation of Curry programs"]
allConsFuncsMenu :: [[BaseHtml]]
=
[[href "findex.html" [htxt "All operations"]],
[href "cindex.html" [htxt "All constructors"]]]
indexPage :: [String] -> [BaseHtml]
indexPage modnames =
(if null modnames
then []
else [h2 [htxt "Modules:"],
ulist (map (\m->[href (m++".html") [htxt m]])
(sortBy leqStringIgnoreCase modnames))])
++ [explainIcons]
explainIcons :: BaseHtml
explainIcons =
anchoredSection "explain_icons"
[h2 [htxt "Explanations of the icons used in the documentation:"],
table
[[[anchor "det_explain" [detIcon]],[nbsp],
[htxt " Operation is deterministic, i.e., defined by exclusive rules",
htxt " and depend only on deterministic operations"]]
,[[anchor "nondet_explain" [nondetIcon]],[nbsp],
[htxt " Operation might be non-deterministic, i.e., it is defined by",
htxt " overlapping rules or depend on non-deterministic operations"]]
]
]
genFunctionIndexPage :: DocOptions -> String -> [FC.FuncDecl] -> IO ()
genFunctionIndexPage opts docdir funs = do
putStrLn ("Writing operation index page to \""++docdir++"/findex.html\"...")
simplePage "Index to all operations" Nothing allConsFuncsMenu
(htmlFuncIndex opts (sortNames expfuns))
>>= writeFile (docdir++"/findex.html")
where
expfuns = map FCG.funcName $ filter ((== FC.Public) . FCG.funcVisibility) funs
htmlFuncIndex :: DocOptions -> [QName] -> [BaseHtml]
htmlFuncIndex opts = categorizeByItemKey . map (showModNameRef opts)
showModNameRef :: DocOptions -> QName -> (String,[BaseHtml])
showModNameRef opts (modname,name) =
(name,
[href (docURL opts modname ++ ".html#"++name) [htxt name], nbsp, nbsp,
htxt "(", href (docURL opts modname ++ ".html") [htxt modname], htxt ")"]
)
sortNames :: [(a,String)] -> [(a,String)]
sortNames names = sortBy (\(_,n1) (_,n2)->leqStringIgnoreCase n1 n2) names
genConsIndexPage :: DocOptions -> String -> [FC.TypeDecl] -> IO ()
genConsIndexPage opts docdir types = do
putStrLn ("Writing constructor index page to \""++docdir++"/cindex.html\"...")
simplePage "Index to all constructors" Nothing allConsFuncsMenu
(htmlConsIndex opts (sortNames expcons))
>>= writeFile (docdir++"/cindex.html")
where
consDecls (FC.Type _ _ _ cs) = cs
consDecls (FC.TypeSyn _ _ _ _ ) = []
expcons = map FCG.consName $ filter ((== FC.Public) . FCG.consVisibility) $
concatMap consDecls types
htmlConsIndex :: DocOptions -> [QName] -> [BaseHtml]
htmlConsIndex opts = categorizeByItemKey . map (showModNameRef opts)
genSystemLibsPage :: String -> [Category] -> [[ModInfo]] -> IO ()
genSystemLibsPage docdir cats modInfos = do
putStrLn $ "Writing main index page for " ++ currySystem ++
" to \"" ++ fname ++ "\"..."
mainPage (currySystem ++ " Libraries")
[h1 [htxt $ currySystem ++ ": System Libraries"]]
syslibsLeftTopMenu
syslibsRightTopMenu
(syslibsSideMenu cats)
([infoTxt, hrule] ++ genHtmlLibCats modInfos ++ [hrule, explainIcons])
>>= writeFile fname
where
fname = docdir ++ "/" ++ currySystem ++ "_libs.html"
syslibsLeftTopMenu :: [[BaseHtml]]
syslibsLeftTopMenu =
[ [href (currySystemURL ++ "/Manual.pdf") [htxt "Manual (PDF)"]]
, [href (currySystemURL ++ "/lib/") [htxt "Libraries"]]
, [ehref currygleURL [extLinkIcon, htxt " API Search"]]
, [href (currySystemURL ++ "/download.html") [htxt "Download"]]
]
syslibsRightTopMenu :: [[BaseHtml]]
syslibsRightTopMenu =
[ curryHomeItem
, [ehref (curryWikiURL ++ "/documentation/report")
[extLinkIcon, htxt " Curry Report"]]
]
syslibsSideMenu :: [Category] -> [BaseHtml]
syslibsSideMenu cats = map par $
[[ehref currygleURL [extLinkIcon, htxt " Search with Curr(y)gle"]]]
++ [[href ("#" ++ genCatLink c) [ htxt (showCategory c)]] | c <- cats]
++ [ [href "findex.html" [htxt "Index to all library functions"]]
, [href "cindex.html" [htxt "Index to all library constructors"]]
, [href "#explain_icons" [htxt "Icons used in the documentation"]]
]
infoTxt :: BaseHtml
infoTxt = par
[ htxt "Here is the collection of libraries contained in the distribution of "
, href currySystemURL [htxt currySystem]
, htxt $ ". Most of these libraries have been implemented during the "
++ "development of larger Curry applications. If you have suggestions "
++ "for changes/improvements or if you want to contribute your own "
++ "library, please contact "
, href "http://www.informatik.uni-kiel.de/~mh/" [htxt "Michael Hanus"]
, htxt "."
]
genCatLink :: Category -> String
genCatLink cat = getCategoryID cat
genHtmlLibCats :: [[ModInfo]] -> [BaseHtml]
genHtmlLibCats = concatMap gen
where
gen [] = []
gen cat@((c,_,_):_) = [anchoredSection (getCategoryID c)
(h2 [htxt (showCategory c ++ ":")] : genHtmlLibCat cat)]
genHtmlLibCat :: [ModInfo] -> [BaseHtml]
genHtmlLibCat category =
[dlist [(genHtmlName modname, docComment2HTML defaultCurryDocOptions modcmt)
| (_,modname,modcmt) <- category ]
]
where
genHtmlName modname = [code [href (modname ++ ".html") [htxt modname]]]
mainPage :: String -> [BaseHtml] -> [[BaseHtml]] -> [[BaseHtml]]
-> [BaseHtml] -> [BaseHtml] -> IO String
mainPage title htmltitle lefttopmenu righttopmenu sidemenu maindoc = do
time <- getLocalTime
return $ showHtmlPage $
bootstrapPage styleBaseURL cssIncludes title homeBrand
lefttopmenu righttopmenu 3 sidemenu htmltitle maindoc
(curryDocFooter time)
cssIncludes :: [String]
cssIncludes = ["bootstrap.min", "currydoc"]
homeBrand :: (String,[BaseHtml])
homeBrand = (curryPackagesURL, [homeIcon, nbsp, htxt "Curry Packages"])
showPageWithDocStyle :: String -> [BaseHtml] -> String
showPageWithDocStyle title body =
showHtmlPage $ HtmlPage title
(map (\f -> pageCSS $ styleBaseURL ++ "/css/" ++ f ++ ".css") cssIncludes)
body
rightTopMenu :: [[BaseHtml]]
rightTopMenu =
[ curryHomeItem
, [ehref baseLibsURL [extLinkIcon, nbsp, htxt "Base Libraries"]]
, [ehref curryDocURL [extLinkIcon, nbsp, htxt "About CurryDoc"]]
]
extLinkIcon :: BaseHtml
extLinkIcon = glyphicon "new-window"
detIcon :: BaseHtml
detIcon = glyphicon "arrow-right"
`withTitle` "This operation is deterministic"
nondetIcon :: BaseHtml
nondetIcon = glyphicon "random"
`withTitle` "This operation might be non-deterministic"
withTitle :: BaseHtml -> String -> BaseHtml
withTitle he t = he `addAttr` ("title",t)
curryDocFooter :: CalendarTime -> [BaseHtml]
curryDocFooter time =
[italic [htxt "Generated by ",
bold [htxt "CurryDoc"],
htxt (" (" ++ currydocVersion ++ ") at "),
htxt (calendarTimeToString time)]]
curryHomeItem :: [BaseHtml]
curryHomeItem = [ehref curryHomeURL [extLinkIcon, htxt " Curry Homepage"]]
simplePage :: String -> Maybe [BaseHtml] -> [[BaseHtml]] -> [BaseHtml]
-> IO String
simplePage title htmltitle lefttopmenu maindoc = do
time <- getLocalTime
return $ showHtmlPage $
bootstrapPage styleBaseURL cssIncludes title homeBrand
lefttopmenu rightTopMenu 0 []
[h1 (maybe [htxt title] id htmltitle)]
maindoc
(curryDocFooter time)
anchoredSection :: String -> [BaseHtml] -> BaseHtml
anchoredSection tag doc = section doc `addAttr` ("id",tag)
anchored :: String -> [BaseHtml] -> BaseHtml
anchored tag doc = style "anchored" doc `addAttr` ("id",tag)
anchoredDiv :: String -> [BaseHtml] -> BaseHtml
anchoredDiv tag doc = block doc `addAttr` ("class", "anchored")
`addAttr` ("id",tag)
borderedTable :: [[[BaseHtml]]] -> BaseHtml
borderedTable rows = table rows `addClass` "table table-bordered table-hover"
ehref :: String -> [BaseHtml] -> BaseHtml
ehref url desc = href url desc `addAttr` ("target","_blank")
leqList :: Eq a => (a -> a -> Bool) -> [a] -> [a] -> Bool
leqList _ [] _ = True
leqList _ (_:_) [] = False
leqList leq (x:xs) (y:ys) | x == y = leqList leq xs ys
| otherwise = leq x y
leqCharIgnoreCase :: Char -> Char -> Bool
leqCharIgnoreCase c1 c2 = (toUpper c1) <= (toUpper c2)
leqStringIgnoreCase :: String -> String -> Bool
leqStringIgnoreCase = leqList leqCharIgnoreCase
stripSpaces :: String -> String
stripSpaces = reverse . dropWhile isSpace . reverse . dropWhile isSpace
explainCat :: String -> BaseHtml
explainCat s = textstyle "explaincat" s
opnameDoc :: [BaseHtml] -> BaseHtml
opnameDoc = style "opname"
sortStrings :: [String] -> [String]
sortStrings strings = sortBy leqStringIgnoreCase strings
firstSentence :: String -> String
firstSentence s = let (fs,ls) = break (=='.') s in
if null ls
then fs
else if tail ls /= "" && isWhiteSpace (head (tail ls))
then fs ++ "."
else fs ++ "." ++ firstSentence (tail ls)
firstPassage :: String -> String
firstPassage = unlines . takeWhile (\s -> s /= "" && not (all isWhiteSpace s))
. lines
|