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
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
module Language.Haskell.Stylish.Printer
( Printer(..)
, PrinterConfig(..)
, PrinterState(..)
-- * Alias
, P
-- * Functions to use the printer
, runPrinter
, runPrinter_
-- ** Combinators
, comma
, dot
, getAnnot
, getCurrentLine
, getCurrentLineLength
, getDocstrPrev
, newline
, parenthesize
, peekNextCommentPos
, prefix
, putComment
, putEolComment
, putOutputable
, putAllSpanComments
, putCond
, putType
, putRdrName
, putText
, removeCommentTo
, removeCommentToEnd
, removeLineComment
, sep
, groupAttachedComments
, space
, spaces
, suffix
, pad
-- ** Advanced combinators
, withColumns
, modifyCurrentLine
, wrapping
) where
--------------------------------------------------------------------------------
import Prelude hiding (lines)
--------------------------------------------------------------------------------
import ApiAnnotation (AnnKeywordId(..), AnnotationComment(..))
import GHC.Hs.Extension (GhcPs, NoExtField(..))
import GHC.Hs.Types (HsType(..))
import Module (ModuleName, moduleNameString)
import RdrName (RdrName(..))
import SrcLoc (GenLocated(..), RealLocated)
import SrcLoc (Located, SrcSpan(..))
import SrcLoc (srcSpanStartLine, srcSpanEndLine)
import Outputable (Outputable)
--------------------------------------------------------------------------------
import Control.Monad (forM_, replicateM_)
import Control.Monad.Reader (MonadReader, ReaderT(..), asks, local)
import Control.Monad.State (MonadState, State)
import Control.Monad.State (runState)
import Control.Monad.State (get, gets, modify, put)
import Data.Foldable (find)
import Data.Functor ((<&>))
import Data.List (delete, isPrefixOf)
import Data.List.NonEmpty (NonEmpty(..))
--------------------------------------------------------------------------------
import Language.Haskell.Stylish.Module (Module, Lines, lookupAnnotation)
import Language.Haskell.Stylish.GHC (showOutputable, unLocated)
-- | Shorthand for 'Printer' monad
type P = Printer
-- | Printer that keeps state of file
newtype Printer a = Printer (ReaderT PrinterConfig (State PrinterState) a)
deriving (Applicative, Functor, Monad, MonadReader PrinterConfig, MonadState PrinterState)
-- | Configuration for printer, currently empty
data PrinterConfig = PrinterConfig
{ columns :: !(Maybe Int)
}
-- | State of printer
data PrinterState = PrinterState
{ lines :: !Lines
, linePos :: !Int
, currentLine :: !String
, pendingComments :: ![RealLocated AnnotationComment]
, parsedModule :: !Module
}
-- | Run printer to get printed lines out of module as well as return value of monad
runPrinter :: PrinterConfig -> [RealLocated AnnotationComment] -> Module -> Printer a -> (a, Lines)
runPrinter cfg comments m (Printer printer) =
let
(a, PrinterState parsedLines _ startedLine _ _) = runReaderT printer cfg `runState` PrinterState [] 0 "" comments m
in
(a, parsedLines <> if startedLine == [] then [] else [startedLine])
-- | Run printer to get printed lines only
runPrinter_ :: PrinterConfig -> [RealLocated AnnotationComment] -> Module -> Printer a -> Lines
runPrinter_ cfg comments m printer = snd (runPrinter cfg comments m printer)
-- | Print text
putText :: String -> P ()
putText txt = do
l <- gets currentLine
modify \s -> s { currentLine = l <> txt }
-- | Check condition post action, and use fallback if false
putCond :: (PrinterState -> Bool) -> P b -> P b -> P b
putCond p action fallback = do
prevState <- get
res <- action
currState <- get
if p currState then pure res
else put prevState >> fallback
-- | Print an 'Outputable'
putOutputable :: Outputable a => a -> P ()
putOutputable = putText . showOutputable
-- | Put all comments that has positions within 'SrcSpan' and separate by
-- passed @P ()@
putAllSpanComments :: P () -> SrcSpan -> P ()
putAllSpanComments suff = \case
UnhelpfulSpan _ -> pure ()
RealSrcSpan rspan -> do
cmts <- removeComments \(L rloc _) ->
srcSpanStartLine rloc >= srcSpanStartLine rspan &&
srcSpanEndLine rloc <= srcSpanEndLine rspan
forM_ cmts (\c -> putComment c >> suff)
-- | Print any comment
putComment :: AnnotationComment -> P ()
putComment = \case
AnnLineComment s -> putText s
AnnDocCommentNext s -> putText s
AnnDocCommentPrev s -> putText s
AnnDocCommentNamed s -> putText s
AnnDocSection _ s -> putText s
AnnDocOptions s -> putText s
AnnBlockComment s -> putText s
-- | Given the current start line of 'SrcSpan', remove and put EOL comment for same line
putEolComment :: SrcSpan -> P ()
putEolComment = \case
RealSrcSpan rspan -> do
cmt <- removeComment \case
L rloc (AnnLineComment s) ->
and
[ srcSpanStartLine rspan == srcSpanStartLine rloc
, not ("-- ^" `isPrefixOf` s)
, not ("-- |" `isPrefixOf` s)
]
_ -> False
forM_ cmt (\c -> space >> putComment c)
UnhelpfulSpan _ -> pure ()
-- | Print a 'RdrName'
putRdrName :: Located RdrName -> P ()
putRdrName (L pos n) = case n of
Unqual name -> do
annots <- getAnnot pos
if AnnOpenP `elem` annots then do
putText "("
putText (showOutputable name)
putText ")"
else if AnnBackquote `elem` annots then do
putText "`"
putText (showOutputable name)
putText "`"
else if AnnSimpleQuote `elem` annots then do
putText "'"
putText (showOutputable name)
else
putText (showOutputable name)
Qual modulePrefix name ->
putModuleName modulePrefix >> dot >> putText (showOutputable name)
Orig _ name ->
putText (showOutputable name)
Exact name ->
putText (showOutputable name)
-- | Print module name
putModuleName :: ModuleName -> P ()
putModuleName = putText . moduleNameString
-- | Print type
putType :: Located (HsType GhcPs) -> P ()
putType ltp = case unLocated ltp of
HsFunTy NoExtField argTp funTp -> do
putOutputable argTp
space
putText "->"
space
putType funTp
HsAppTy NoExtField t1 t2 ->
putType t1 >> space >> putType t2
HsExplicitListTy NoExtField _ xs -> do
putText "'["
sep
(comma >> space)
(fmap putType xs)
putText "]"
HsExplicitTupleTy NoExtField xs -> do
putText "'("
sep
(comma >> space)
(fmap putType xs)
putText ")"
HsOpTy NoExtField lhs op rhs -> do
putType lhs
space
putRdrName op
space
putType rhs
HsTyVar NoExtField _ rdrName ->
putRdrName rdrName
HsTyLit _ tp ->
putOutputable tp
HsParTy _ tp -> do
putText "("
putType tp
putText ")"
HsTupleTy NoExtField _ xs -> do
putText "("
sep
(comma >> space)
(fmap putType xs)
putText ")"
HsForAllTy NoExtField _ _ _ ->
putOutputable ltp
HsQualTy NoExtField _ _ ->
putOutputable ltp
HsAppKindTy _ _ _ ->
putOutputable ltp
HsListTy _ _ ->
putOutputable ltp
HsSumTy _ _ ->
putOutputable ltp
HsIParamTy _ _ _ ->
putOutputable ltp
HsKindSig _ _ _ ->
putOutputable ltp
HsStarTy _ _ ->
putOutputable ltp
HsSpliceTy _ _ ->
putOutputable ltp
HsDocTy _ _ _ ->
putOutputable ltp
HsBangTy _ _ _ ->
putOutputable ltp
HsRecTy _ _ ->
putOutputable ltp
HsWildCardTy _ ->
putOutputable ltp
XHsType _ ->
putOutputable ltp
-- | Get a docstring on the start line of 'SrcSpan' that is a @-- ^@ comment
getDocstrPrev :: SrcSpan -> P (Maybe AnnotationComment)
getDocstrPrev = \case
UnhelpfulSpan _ -> pure Nothing
RealSrcSpan rspan -> do
removeComment \case
L rloc (AnnLineComment s) ->
and
[ srcSpanStartLine rspan == srcSpanStartLine rloc
, "-- ^" `isPrefixOf` s
]
_ -> False
-- | Print a newline
newline :: P ()
newline = do
l <- gets currentLine
modify \s -> s { currentLine = "", linePos = 0, lines = lines s <> [l] }
-- | Print a space
space :: P ()
space = putText " "
-- | Print a number of spaces
spaces :: Int -> P ()
spaces i = replicateM_ i space
-- | Print a dot
dot :: P ()
dot = putText "."
-- | Print a comma
comma :: P ()
comma = putText ","
-- | Add parens around a printed action
parenthesize :: P a -> P a
parenthesize action = putText "(" *> action <* putText ")"
-- | Add separator between each element of the given printers
sep :: P a -> [P a] -> P ()
sep _ [] = pure ()
sep s (first : rest) = first >> forM_ rest ((>>) s)
-- | Prefix a printer with another one
prefix :: P a -> P b -> P b
prefix pa pb = pa >> pb
-- | Suffix a printer with another one
suffix :: P a -> P b -> P a
suffix pa pb = pb >> pa
-- | Indent to a given number of spaces. If the current line already exceeds
-- that number in length, nothing happens.
pad :: Int -> P ()
pad n = do
len <- length <$> getCurrentLine
spaces $ n - len
-- | Gets comment on supplied 'line' and removes it from the state
removeLineComment :: Int -> P (Maybe AnnotationComment)
removeLineComment line =
removeComment (\(L rloc _) -> srcSpanStartLine rloc == line)
-- | Removes comments from the state up to start line of 'SrcSpan' and returns
-- the ones that were removed
removeCommentTo :: SrcSpan -> P [AnnotationComment]
removeCommentTo = \case
UnhelpfulSpan _ -> pure []
RealSrcSpan rspan -> removeCommentTo' (srcSpanStartLine rspan)
-- | Removes comments from the state up to end line of 'SrcSpan' and returns
-- the ones that were removed
removeCommentToEnd :: SrcSpan -> P [AnnotationComment]
removeCommentToEnd = \case
UnhelpfulSpan _ -> pure []
RealSrcSpan rspan -> removeCommentTo' (srcSpanEndLine rspan)
-- | Removes comments to the line number given and returns the ones removed
removeCommentTo' :: Int -> P [AnnotationComment]
removeCommentTo' line =
removeComment (\(L rloc _) -> srcSpanStartLine rloc < line) >>= \case
Nothing -> pure []
Just c -> do
rest <- removeCommentTo' line
pure (c : rest)
-- | Removes comments from the state while given predicate 'p' is true
removeComments :: (RealLocated AnnotationComment -> Bool) -> P [AnnotationComment]
removeComments p =
removeComment p >>= \case
Just c -> do
rest <- removeComments p
pure (c : rest)
Nothing -> pure []
-- | Remove a comment from the state given predicate 'p'
removeComment :: (RealLocated AnnotationComment -> Bool) -> P (Maybe AnnotationComment)
removeComment p = do
comments <- gets pendingComments
let
foundComment =
find p comments
newPendingComments =
maybe comments (`delete` comments) foundComment
modify \s -> s { pendingComments = newPendingComments }
pure $ fmap (\(L _ c) -> c) foundComment
-- | Get all annotations for 'SrcSpan'
getAnnot :: SrcSpan -> P [AnnKeywordId]
getAnnot spn = gets (lookupAnnotation spn . parsedModule)
-- | Get current line
getCurrentLine :: P String
getCurrentLine = gets currentLine
-- | Get current line length
getCurrentLineLength :: P Int
getCurrentLineLength = fmap length getCurrentLine
-- | Peek at the next comment in the state
peekNextCommentPos :: P (Maybe SrcSpan)
peekNextCommentPos = do
gets pendingComments <&> \case
(L next _ : _) -> Just (RealSrcSpan next)
[] -> Nothing
-- | Get attached comments belonging to '[Located a]' given
groupAttachedComments :: [Located a] -> P [([AnnotationComment], NonEmpty (Located a))]
groupAttachedComments = go
where
go :: [Located a] -> P [([AnnotationComment], NonEmpty (Located a))]
go (L rspan x : xs) = do
comments <- removeCommentTo rspan
nextGroupStartM <- peekNextCommentPos
let
sameGroupOf = maybe xs \nextGroupStart ->
takeWhile (\(L p _)-> p < nextGroupStart) xs
restOf = maybe [] \nextGroupStart ->
dropWhile (\(L p _) -> p <= nextGroupStart) xs
restGroups <- go (restOf nextGroupStartM)
pure $ (comments, L rspan x :| sameGroupOf nextGroupStartM) : restGroups
go _ = pure []
modifyCurrentLine :: (String -> String) -> P ()
modifyCurrentLine f = do
s0 <- get
put s0 {currentLine = f $ currentLine s0}
wrapping
:: P a -- ^ First printer to run
-> P a -- ^ Printer to run if first printer violates max columns
-> P a -- ^ Result of either the first or the second printer
wrapping p1 p2 = do
maxCols <- asks columns
case maxCols of
-- No wrapping
Nothing -> p1
Just c -> do
s0 <- get
x <- p1
s1 <- get
if length (currentLine s1) <= c
-- No need to wrap
then pure x
else do
put s0
y <- p2
s2 <- get
if length (currentLine s1) == length (currentLine s2)
-- Wrapping didn't help!
then put s1 >> pure x
-- Wrapped
else pure y
withColumns :: Maybe Int -> P a -> P a
withColumns c = local $ \pc -> pc {columns = c}
|