This repository has been archived by the owner on Apr 29, 2024. It is now read-only.
forked from mihaimaruseac/hindent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pretty.hs
2151 lines (2007 loc) · 65.9 KB
/
Pretty.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 ScopedTypeVariables #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
-- | Pretty printing.
module HIndent.Pretty
(pretty)
where
import Control.Applicative
import Control.Monad.State.Strict hiding (state)
import qualified Data.ByteString.Builder as S
import Data.Foldable (for_, forM_, traverse_)
import Data.Int
import Data.List
import Data.Maybe
import Data.Monoid ((<>))
import Data.Typeable
import HIndent.Types
import qualified Language.Haskell.Exts as P
import Language.Haskell.Exts.SrcLoc
import Language.Haskell.Exts.Syntax
import Prelude hiding (exp)
--------------------------------------------------------------------------------
-- * Pretty printing class
-- | Pretty printing class.
class (Annotated ast,Typeable ast) => Pretty ast where
prettyInternal :: ast NodeInfo -> Printer ()
-- | Pretty print including comments.
pretty :: (Pretty ast,Show (ast NodeInfo))
=> ast NodeInfo -> Printer ()
pretty a = do
mapM_
(\c' -> do
case c' of
CommentBeforeLine _ c -> do
case c of
EndOfLine s -> write ("--" ++ s)
MultiLine s -> write ("{-" ++ s ++ "-}")
newline
_ -> return ())
comments
prettyInternal a
mapM_
(\(i, c') -> do
case c' of
CommentSameLine spn c -> do
col <- gets psColumn
if col == 0
then do
-- write comment keeping original indentation
let col' = fromIntegral $ srcSpanStartColumn spn - 1
column col' $ writeComment c
else do
space
writeComment c
CommentAfterLine spn c -> do
when (i == 0) newline
-- write comment keeping original indentation
let col = fromIntegral $ srcSpanStartColumn spn - 1
column col $ writeComment c
_ -> return ())
(zip [0 :: Int ..] comments)
where
comments = nodeInfoComments (ann a)
writeComment =
\case
EndOfLine cs -> do
write ("--" ++ cs)
modify
(\s ->
s
{ psEolComment = True
})
MultiLine cs -> do
write ("{-" ++ cs ++ "-}")
modify
(\s ->
s
{ psEolComment = True
})
-- | Pretty print using HSE's own printer. The 'P.Pretty' class here
-- is HSE's.
pretty' :: (Pretty ast,P.Pretty (ast SrcSpanInfo))
=> ast NodeInfo -> Printer ()
pretty' = write . P.prettyPrint . fmap nodeInfoSpan
--------------------------------------------------------------------------------
-- * Combinators
-- | Increase indentation level by n spaces for the given printer.
indented :: Int64 -> Printer a -> Printer a
indented i p =
do level <- gets psIndentLevel
modify (\s -> s {psIndentLevel = level + i})
m <- p
modify (\s -> s {psIndentLevel = level})
return m
indentedBlock :: Printer a -> Printer a
indentedBlock p =
do indentSpaces <- getIndentSpaces
indented indentSpaces p
-- | Print all the printers separated by spaces.
spaced :: [Printer ()] -> Printer ()
spaced = inter space
-- | Print all the printers separated by commas.
commas :: [Printer ()] -> Printer ()
commas = inter (write ", ")
-- | Print all the printers separated by sep.
inter :: Printer () -> [Printer ()] -> Printer ()
inter sep ps =
foldr
(\(i,p) next ->
depend
(do p
if i < length ps
then sep
else return ())
next)
(return ())
(zip [1 ..] ps)
-- | Print all the printers separated by newlines.
lined :: [Printer ()] -> Printer ()
lined ps = sequence_ (intersperse newline ps)
-- | Print all the printers separated newlines and optionally a line
-- prefix.
prefixedLined :: String -> [Printer ()] -> Printer ()
prefixedLined pref ps' =
case ps' of
[] -> return ()
(p:ps) ->
do p
indented (fromIntegral
(length pref *
(-1)))
(mapM_ (\p' ->
do newline
depend (write pref) p')
ps)
-- | Set the (newline-) indent level to the given column for the given
-- printer.
column :: Int64 -> Printer a -> Printer a
column i p =
do level <- gets psIndentLevel
modify (\s -> s {psIndentLevel = i})
m <- p
modify (\s -> s {psIndentLevel = level})
return m
-- | Output a newline.
newline :: Printer ()
newline =
do write "\n"
modify (\s -> s {psNewline = True})
-- | Set the context to a case context, where RHS is printed with -> .
withCaseContext :: Bool -> Printer a -> Printer a
withCaseContext bool pr =
do original <- gets psInsideCase
modify (\s -> s {psInsideCase = bool})
result <- pr
modify (\s -> s {psInsideCase = original})
return result
-- | Get the current RHS separator, either = or -> .
rhsSeparator :: Printer ()
rhsSeparator =
do inCase <- gets psInsideCase
if inCase
then write "->"
else write "="
-- | Make the latter's indentation depend upon the end column of the
-- former.
depend :: Printer () -> Printer b -> Printer b
depend maker dependent =
do state' <- get
maker
st <- get
col <- gets psColumn
if psLine state' /= psLine st || psColumn state' /= psColumn st
then column col dependent
else dependent
-- | Wrap.
wrap :: String -> String -> Printer a -> Printer a
wrap open close p = depend (write open) $ p <* write close
-- | Wrap in parens.
parens :: Printer a -> Printer a
parens = wrap "(" ")"
-- | Wrap in braces.
braces :: Printer a -> Printer a
braces = wrap "{" "}"
-- | Wrap in brackets.
brackets :: Printer a -> Printer a
brackets = wrap "[" "]"
-- | Write a space.
space :: Printer ()
space = write " "
-- | Write a comma.
comma :: Printer ()
comma = write ","
-- | Write an integral.
int :: Integer -> Printer ()
int = write . show
-- | Write out a string, updating the current position information.
write :: String -> Printer ()
write x =
do eol <- gets psEolComment
hardFail <- gets psFitOnOneLine
let addingNewline = eol && x /= "\n"
when addingNewline newline
state <- get
let writingNewline = x == "\n"
out :: String
out =
if psNewline state && not writingNewline
then (replicate (fromIntegral (psIndentLevel state))
' ') <>
x
else x
psColumn' =
if additionalLines > 0
then fromIntegral (length (concat (take 1 (reverse srclines))))
else psColumn state + fromIntegral (length out)
when
hardFail
(guard
(additionalLines == 0 &&
(psColumn' <= configMaxColumns (psConfig state))))
modify (\s ->
s {psOutput = psOutput state <> S.stringUtf8 out
,psNewline = False
,psLine = psLine state + fromIntegral additionalLines
,psEolComment= False
,psColumn = psColumn'})
where srclines = lines x
additionalLines =
length (filter (== '\n') x)
-- | Write a string.
string :: String -> Printer ()
string = write
-- | Indent spaces, e.g. 2.
getIndentSpaces :: Printer Int64
getIndentSpaces =
gets (configIndentSpaces . psConfig)
-- | Play with a printer and then restore the state to what it was
-- before.
sandbox :: Printer a -> Printer (a,PrintState)
sandbox p =
do orig <- get
a <- p
new <- get
put orig
return (a,new)
-- | Render a type with a context, or not.
withCtx :: (Pretty ast,Show (ast NodeInfo))
=> Maybe (ast NodeInfo) -> Printer b -> Printer b
withCtx Nothing m = m
withCtx (Just ctx) m =
do pretty ctx
write " =>"
newline
m
-- | Maybe render an overlap definition.
maybeOverlap :: Maybe (Overlap NodeInfo) -> Printer ()
maybeOverlap =
maybe (return ())
(\p ->
pretty p >>
space)
-- | Swing the second printer below and indented with respect to the first.
swing :: Printer () -> Printer b -> Printer ()
swing a b =
do orig <- gets psIndentLevel
a
mst <- fitsOnOneLine (do space
b)
case mst of
Just st -> put st
Nothing -> do newline
indentSpaces <- getIndentSpaces
_ <- column (orig + indentSpaces) b
return ()
-- | Swing the second printer below and indented with respect to the first by
-- the specified amount.
swingBy :: Int64 -> Printer() -> Printer b -> Printer b
swingBy i a b =
do orig <- gets psIndentLevel
a
newline
column (orig + i) b
--------------------------------------------------------------------------------
-- * Instances
instance Pretty Context where
prettyInternal ctx@(CxTuple _ asserts) = do
mst <- fitsOnOneLine (parens (inter (comma >> space) (map pretty asserts)))
case mst of
Nothing -> context ctx
Just st -> put st
prettyInternal ctx = context ctx
instance Pretty Pat where
prettyInternal x =
case x of
PLit _ sign l -> pretty sign >> pretty l
PNPlusK _ n k ->
depend (do pretty n
write "+")
(int k)
PInfixApp _ a op b ->
case op of
Special{} ->
depend (pretty a)
(depend (prettyInfixOp op)
(pretty b))
_ ->
depend (do pretty a
space)
(depend (do prettyInfixOp op
space)
(pretty b))
PApp _ f args ->
depend (do pretty f
unless (null args) space)
(spaced (map pretty args))
PTuple _ boxed pats ->
depend (write (case boxed of
Unboxed -> "(# "
Boxed -> "("))
(do commas (map pretty pats)
write (case boxed of
Unboxed -> " #)"
Boxed -> ")"))
PList _ ps ->
brackets (commas (map pretty ps))
PParen _ e -> parens (pretty e)
PRec _ qname fields -> do
let horVariant = do
pretty qname
space
braces $ commas $ map pretty fields
verVariant =
depend (pretty qname >> space) $ do
case fields of
[] -> write "{}"
[field] -> braces $ pretty field
_ -> do
depend (write "{") $
prefixedLined "," $ map (depend space . pretty) fields
newline
write "}"
horVariant `ifFitsOnOneLineOrElse` verVariant
PAsPat _ n p ->
depend (do pretty n
write "@")
(pretty p)
PWildCard _ -> write "_"
PIrrPat _ p ->
depend (write "~")
(pretty p)
PatTypeSig _ p ty ->
depend (do pretty p
write " :: ")
(pretty ty)
PViewPat _ e p ->
depend (do pretty e
write " -> ")
(pretty p)
PQuasiQuote _ name str -> quotation name (string str)
PBangPat _ p ->
depend (write "!")
(pretty p)
PRPat{} -> pretty' x
PXTag{} -> pretty' x
PXETag{} -> pretty' x
PXPcdata{} -> pretty' x
PXPatTag{} -> pretty' x
PXRPats{} -> pretty' x
PVar{} -> pretty' x
PSplice _ s -> pretty s
-- | Pretty infix application of a name (identifier or symbol).
prettyInfixName :: Name NodeInfo -> Printer ()
prettyInfixName (Ident _ n) = do write "`"; string n; write "`";
prettyInfixName (Symbol _ s) = string s
-- | Pretty print a name for being an infix operator.
prettyInfixOp :: QName NodeInfo -> Printer ()
prettyInfixOp x =
case x of
Qual _ mn n ->
case n of
Ident _ i -> do write "`"; pretty mn; write "."; string i; write "`";
Symbol _ s -> do pretty mn; write "."; string s;
UnQual _ n -> prettyInfixName n
Special _ s -> pretty s
prettyQuoteName :: Name NodeInfo -> Printer ()
prettyQuoteName x =
case x of
Ident _ i -> string i
Symbol _ s -> string ("(" ++ s ++ ")")
instance Pretty Type where
prettyInternal = typ
instance Pretty Exp where
prettyInternal = exp
-- | Render an expression.
exp :: Exp NodeInfo -> Printer ()
-- | Do after lambda should swing.
exp (Lambda _ pats (Do l stmts)) =
do
mst <-
fitsOnOneLine
(do write "\\"
spaced (map pretty pats)
write " -> "
pretty (Do l stmts))
case mst of
Nothing -> swing (do write "\\"
spaced (map pretty pats)
write " -> do")
(lined (map pretty stmts))
Just st -> put st
-- | Space out tuples.
exp (Tuple _ boxed exps) = do
let horVariant = parensHorB boxed $ inter (write ", ") (map pretty exps)
verVariant = parensVerB boxed $ prefixedLined "," (map (depend space . pretty) exps)
mst <- fitsOnOneLine horVariant
case mst of
Nothing -> verVariant
Just st -> put st
where
parensHorB Boxed = parens
parensHorB Unboxed = wrap "(# " " #)"
parensVerB Boxed = parens
parensVerB Unboxed = wrap "(#" "#)"
-- | Space out tuples.
exp (TupleSection _ boxed mexps) = do
let horVariant = parensHorB boxed $ inter (write ", ") (map (maybe (return ()) pretty) mexps)
verVariant =
parensVerB boxed $ prefixedLined "," (map (maybe (return ()) (depend space . pretty)) mexps)
mst <- fitsOnOneLine horVariant
case mst of
Nothing -> verVariant
Just st -> put st
where
parensHorB Boxed = parens
parensHorB Unboxed = wrap "(# " " #)"
parensVerB Boxed = parens
parensVerB Unboxed = wrap "(#" "#)"
exp (UnboxedSum{}) = error "FIXME: No implementation for UnboxedSum."
-- | Infix apps, same algorithm as ChrisDone at the moment.
exp e@(InfixApp _ a op b) =
infixApp e a op b Nothing
-- | If bodies are indented 4 spaces. Handle also do-notation.
exp (If _ if' then' else') =
do depend (write "if ")
(pretty if')
newline
indentSpaces <- getIndentSpaces
indented indentSpaces
(do branch "then " then'
newline
branch "else " else')
-- Special handling for do.
where branch str e =
case e of
Do _ stmts ->
do write str
write "do"
newline
indentSpaces <- getIndentSpaces
indented indentSpaces (lined (map pretty stmts))
_ ->
depend (write str)
(pretty e)
-- | Render on one line, or otherwise render the op with the arguments
-- listed line by line.
exp (App _ op arg) = do
let flattened = flatten op ++ [arg]
mst <- fitsOnOneLine (spaced (map pretty flattened))
case mst of
Nothing -> do
let (f:args) = flattened
col <- gets psColumn
spaces <- getIndentSpaces
pretty f
col' <- gets psColumn
let diff = col' - col - if col == 0 then spaces else 0
if diff + 1 <= spaces
then space
else newline
spaces' <- getIndentSpaces
indented spaces' (lined (map pretty args))
Just st -> put st
where
flatten (App label' op' arg') = flatten op' ++ [amap (addComments label') arg']
flatten x = [x]
addComments n1 n2 =
n2
{ nodeInfoComments = nub (nodeInfoComments n2 ++ nodeInfoComments n1)
}
-- | Space out commas in list.
exp (List _ es) =
do mst <- fitsOnOneLine p
case mst of
Nothing -> do
depend
(write "[")
(prefixedLined "," (map (depend space . pretty) es))
newline
write "]"
Just st -> put st
where p =
brackets (inter (write ", ")
(map pretty es))
exp (RecUpdate _ exp' updates) = recUpdateExpr (pretty exp') updates
exp (RecConstr _ qname updates) = recUpdateExpr (pretty qname) updates
exp (Let _ binds e) =
depend (write "let ")
(do pretty binds
newline
indented (-3) (depend (write "in ")
(pretty e)))
exp (ListComp _ e qstmt) = do
let horVariant = brackets $ do
pretty e
write " | "
commas $ map pretty qstmt
verVariant = do
write "[ "
pretty e
newline
depend (write "| ") $ prefixedLined ", " $ map pretty qstmt
newline
write "]"
horVariant `ifFitsOnOneLineOrElse` verVariant
exp (ParComp _ e qstmts) = do
let horVariant = brackets $ do
pretty e
for_ qstmts $ \qstmt -> do
write " | "
commas $ map pretty qstmt
verVariant = do
depend (write "[ ") $ pretty e
newline
for_ qstmts $ \qstmt -> do
depend (write "| ") $ prefixedLined ", " $ map pretty qstmt
newline
write "]"
horVariant `ifFitsOnOneLineOrElse` verVariant
exp (TypeApp _ t) = do
write "@"
pretty t
exp (NegApp _ e) =
depend (write "-")
(pretty e)
exp (Lambda _ ps e) = do
write "\\"
spaced [ do case (i, x) of
(0, PIrrPat {}) -> space
(0, PBangPat {}) -> space
_ -> return ()
pretty x
| (i, x) <- zip [0 :: Int ..] ps
]
swing (write " ->") $ pretty e
exp (Paren _ e) = parens (pretty e)
exp (Case _ e alts) =
do depend (write "case ")
(do pretty e
write " of")
if null alts
then write " {}"
else do newline
indentedBlock (lined (map (withCaseContext True . pretty) alts))
exp (Do _ stmts) =
depend (write "do ")
(lined (map pretty stmts))
exp (MDo _ stmts) =
depend (write "mdo ")
(lined (map pretty stmts))
exp (LeftSection _ e op) =
parens (depend (do pretty e
space)
(pretty op))
exp (RightSection _ e op) =
parens (depend (do pretty e
space)
(pretty op))
exp (EnumFrom _ e) =
brackets (do pretty e
write " ..")
exp (EnumFromTo _ e f) =
brackets (depend (do pretty e
write " .. ")
(pretty f))
exp (EnumFromThen _ e t) =
brackets (depend (do pretty e
write ",")
(do pretty t
write " .."))
exp (EnumFromThenTo _ e t f) =
brackets (depend (do pretty e
write ",")
(depend (do pretty t
write " .. ")
(pretty f)))
exp (ExpTypeSig _ e t) =
depend (do pretty e
write " :: ")
(pretty t)
exp (VarQuote _ x) =
depend (write "'")
(pretty x)
exp (TypQuote _ x) =
depend (write "''")
(pretty x)
exp (BracketExp _ b) = pretty b
exp (SpliceExp _ s) = pretty s
exp (QuasiQuote _ n s) = quotation n (string s)
exp (LCase _ alts) =
do write "\\case"
if null alts
then write " {}"
else do newline
indentedBlock (lined (map (withCaseContext True . pretty) alts))
exp (MultiIf _ alts) =
withCaseContext
True
(depend
(write "if ")
(lined
(map
(\p -> do
write "| "
prettyG p)
alts)))
where
prettyG (GuardedRhs _ stmts e) = do
indented
1
(do (lined (map
(\(i,p) -> do
unless (i == 1)
space
pretty p
unless (i == length stmts)
(write ","))
(zip [1..] stmts))))
swing (write " " >> rhsSeparator) (pretty e)
exp (Lit _ lit) = prettyInternal lit
exp (Var _ q) = pretty q
exp (IPVar _ q) = pretty q
exp (Con _ q) = pretty q
exp x@XTag{} = pretty' x
exp x@XETag{} = pretty' x
exp x@XPcdata{} = pretty' x
exp x@XExpTag{} = pretty' x
exp x@XChildTag{} = pretty' x
exp x@CorePragma{} = pretty' x
exp x@SCCPragma{} = pretty' x
exp x@GenPragma{} = pretty' x
exp x@Proc{} = pretty' x
exp x@LeftArrApp{} = pretty' x
exp x@RightArrApp{} = pretty' x
exp x@LeftArrHighApp{} = pretty' x
exp x@RightArrHighApp{} = pretty' x
exp x@ParArray{} = pretty' x
exp x@ParArrayFromTo{} = pretty' x
exp x@ParArrayFromThenTo{} = pretty' x
exp x@ParArrayComp{} = pretty' x
exp (OverloadedLabel _ label) = string ('#' : label)
instance Pretty IPName where
prettyInternal = pretty'
instance Pretty Stmt where
prettyInternal =
stmt
instance Pretty QualStmt where
prettyInternal x =
case x of
QualStmt _ s -> pretty s
ThenTrans _ s -> do
write "then "
pretty s
ThenBy _ s t -> do
write "then "
pretty s
write " by "
pretty t
GroupBy _ s -> do
write "then group by "
pretty s
GroupUsing _ s -> do
write "then group using "
pretty s
GroupByUsing _ s t -> do
write "then group by "
pretty s
write " using "
pretty t
instance Pretty Decl where
prettyInternal = decl'
-- | Render a declaration.
decl :: Decl NodeInfo -> Printer ()
decl (InstDecl _ moverlap dhead decls) =
do depend (write "instance ")
(depend (maybeOverlap moverlap)
(depend (pretty dhead)
(unless (null (fromMaybe [] decls))
(write " where"))))
unless (null (fromMaybe [] decls))
(do newline
indentedBlock (lined (map pretty (fromMaybe [] decls))))
decl (SpliceDecl _ e) = pretty e
decl (TypeSig _ names ty) =
depend (do inter (write ", ")
(map pretty names)
write " :: ")
(pretty ty)
decl (FunBind _ matches) =
lined (map pretty matches)
decl (ClassDecl _ ctx dhead fundeps decls) =
do classHead ctx dhead fundeps decls
unless (null (fromMaybe [] decls))
(do newline
indentedBlock (lined (map pretty (fromMaybe [] decls))))
decl (TypeDecl _ typehead typ') = do
write "type "
pretty typehead
ifFitsOnOneLineOrElse
(depend (write " = ") (pretty typ'))
(do newline
indentedBlock (depend (write " = ") (pretty typ')))
decl (TypeFamDecl _ declhead result injectivity) = do
write "type family "
pretty declhead
case result of
Just r -> do
space
let sep = case r of
KindSig _ _ -> "::"
TyVarSig _ _ -> "="
write sep
space
pretty r
Nothing -> return ()
case injectivity of
Just i -> do
space
pretty i
Nothing -> return ()
decl (ClosedTypeFamDecl _ declhead result injectivity instances) = do
write "type family "
pretty declhead
for_ result $ \r -> do
space
let sep = case r of
KindSig _ _ -> "::"
TyVarSig _ _ -> "="
write sep
space
pretty r
for_ injectivity $ \i -> do
space
pretty i
space
write "where"
newline
indentedBlock (lined (map pretty instances))
decl (DataDecl _ dataornew ctx dhead condecls mderivs) =
do depend (do pretty dataornew
space)
(withCtx ctx
(do pretty dhead
case condecls of
[] -> return ()
[x] -> singleCons x
xs -> multiCons xs))
indentSpaces <- getIndentSpaces
forM_ mderivs $ \deriv -> newline >> column indentSpaces (pretty deriv)
where singleCons x =
do write " ="
indentSpaces <- getIndentSpaces
column indentSpaces
(do newline
pretty x)
multiCons xs =
do newline
indentSpaces <- getIndentSpaces
column indentSpaces
(depend (write "=")
(prefixedLined "|"
(map (depend space . pretty) xs)))
decl (GDataDecl _ dataornew ctx dhead mkind condecls mderivs) =
do depend (pretty dataornew >> space)
(withCtx ctx
(do pretty dhead
case mkind of
Nothing -> return ()
Just kind -> do write " :: "
pretty kind
write " where"))
indentedBlock $ do
case condecls of
[] -> return ()
_ -> do
newline
lined (map pretty condecls)
forM_ mderivs $ \deriv -> newline >> pretty deriv
decl (InlineSig _ inline active name) = do
write "{-# "
unless inline $ write "NO"
write "INLINE "
case active of
Nothing -> return ()
Just (ActiveFrom _ x) -> write ("[" ++ show x ++ "] ")
Just (ActiveUntil _ x) -> write ("[~" ++ show x ++ "] ")
pretty name
write " #-}"
decl (MinimalPragma _ (Just formula)) =
wrap "{-# " " #-}" $ do
depend (write "MINIMAL ") $ pretty formula
decl (ForImp _ callconv maybeSafety maybeName name ty) = do
string "foreign import "
pretty' callconv >> space
case maybeSafety of
Just safety -> pretty' safety >> space
Nothing -> return ()
case maybeName of
Just namestr -> string (show namestr) >> space
Nothing -> return ()
pretty' name
tyline <- fitsOnOneLine $ do string " :: "
pretty' ty
case tyline of
Just line -> put line
Nothing -> do newline
indentedBlock $ do string ":: "
pretty' ty
decl (ForExp _ callconv maybeName name ty) = do
string "foreign export "
pretty' callconv >> space
case maybeName of
Just namestr -> string (show namestr) >> space
Nothing -> return ()
pretty' name
tyline <- fitsOnOneLine $ do string " :: "
pretty' ty
case tyline of
Just line -> put line
Nothing -> do newline
indentedBlock $ do string ":: "
pretty' ty
decl x' = pretty' x'
classHead
:: Maybe (Context NodeInfo)
-> DeclHead NodeInfo
-> [FunDep NodeInfo]
-> Maybe [ClassDecl NodeInfo]
-> Printer ()
classHead ctx dhead fundeps decls = shortHead `ifFitsOnOneLineOrElse` longHead
where
shortHead =
depend
(write "class ")
(withCtx ctx $
depend
(pretty dhead)
(depend (unless (null fundeps) (write " | " >> commas (map pretty fundeps)))
(unless (null (fromMaybe [] decls)) (write " where"))))
longHead = do
depend (write "class ") (withCtx ctx $ pretty dhead)
newline
indentedBlock $ do
unless (null fundeps) $ do
depend (write "| ") (prefixedLined ", " $ map pretty fundeps)
newline
unless (null (fromMaybe [] decls)) (write "where")
instance Pretty TypeEqn where
prettyInternal (TypeEqn _ in_ out_) = do
pretty in_
write " = "
pretty out_
instance Pretty Deriving where
prettyInternal (Deriving _ strategy heads) =
depend (write "deriving" >> space >> writeStrategy) $ do
let heads' =
if length heads == 1
then map stripParens heads
else heads
maybeDerives <- fitsOnOneLine $ parens (commas (map pretty heads'))
case maybeDerives of
Nothing -> formatMultiLine heads'
Just derives -> put derives
where
writeStrategy = case strategy of
Nothing -> return ()
Just st -> pretty st >> space
stripParens (IParen _ iRule) = stripParens iRule
stripParens x = x
formatMultiLine derives = do
depend (write "( ") $ prefixedLined ", " (map pretty derives)
newline
write ")"
instance Pretty DerivStrategy where
prettyInternal x =
case x of
DerivStock _ -> return ()
DerivAnyclass _ -> write "anyclass"
DerivNewtype _ -> write "newtype"
instance Pretty Alt where
prettyInternal x =
case x of
Alt _ p galts mbinds ->
do pretty p
pretty galts
case mbinds of
Nothing -> return ()
Just binds ->
do newline
indentedBlock (depend (write "where ")
(pretty binds))
instance Pretty Asst where
prettyInternal x =
case x of
IParam _ name ty -> do
pretty name
write " :: "
pretty ty
ParenA _ asst -> parens (pretty asst)
#if MIN_VERSION_haskell_src_exts(1,21,0)
TypeA _ ty -> pretty ty
#else
ClassA _ name types -> spaced (pretty name : map pretty types)
i@InfixA {} -> pretty' i
EqualP _ a b -> do
pretty a
write " ~ "
pretty b
AppA _ name tys ->
spaced (pretty name : map pretty tys)
WildCardA _ name ->
case name of
Nothing -> write "_"