@@ -1,32 +1,43 @@
1−{-# LANGUAGE LambdaCase #-}
1+{-# LANGUAGE LambdaCase #-}
2+{-# LANGUAGE MultiWayIf #-}
23{-# LANGUAGE OverloadedStrings #-}
3−{-# LANGUAGE RecordWildCards #-}
4+{-# LANGUAGE RecordWildCards #-}
5+{-# LANGUAGE TypeApplications #-}
46
57module Ormolu.Printer.Meat.Declaration.Value
6− ( p_valDecl
7− , p_pat
8− , p_hsExpr
9− , p_hsSplice
8+ ( p_valDecl,
9+ p_pat,
10+ p_hsExpr,
11+ p_hsSplice,
12+ p_stringLit,
1013 )
1114where
1215
1316import Bag (bagToList)
1417import BasicTypes
1518import Control.Monad
16−import Data.Data
19+import Ctype (is_space)
20+import Data.Bool (bool)
21+import Data.Char (isPunctuation, isSymbol)
22+import Data.Data hiding (Infix, Prefix)
23+import Data.Functor ((<&>))
1724import Data.List (intersperse, sortOn)
25+import Data.List.NonEmpty (NonEmpty (..), (<|))
26+import qualified Data.List.NonEmpty as NE
1827import Data.Text (Text)
28+import qualified Data.Text as Text
1929import GHC
30+import OccName (occNameString)
2031import Ormolu.Printer.Combinators
32+import Ormolu.Printer.Internal
2133import Ormolu.Printer.Meat.Common
34+import {-# SOURCE #-} Ormolu.Printer.Meat.Declaration
2235import Ormolu.Printer.Meat.Declaration.Signature
2336import Ormolu.Printer.Meat.Type
37+import Ormolu.Printer.Operators
2438import Ormolu.Utils
25−import Outputable (Outputable (..))
26−import SrcLoc (combineSrcSpans, isOneLineSpan)
27−import qualified Data.List.NonEmpty as NE
28−import {-# SOURCE #-} Ormolu.Printer.Meat.Declaration
2939
40+-- | Style of a group of equations.
3041data MatchGroupStyle
3142 = Function (Located RdrName)
3243 | PatternBind
@@ -34,588 +45,1062 @@ data MatchGroupStyle
3445 | Lambda
3546 | LambdaCase
3647
48+-- | Style of equations in a group.
3749data GroupStyle
3850 = EqualSign
3951 | RightArrow
4052
4153-- | Expression placement. This marks the places where expressions that
4254-- implement handing forms may use them.
43−
4455data Placement
45− = Normal -- ^ Multi-line layout should cause
46− -- insertion of a newline and indentation
47− -- bump
48− | Hanging -- ^ Expressions that have hanging form
49− -- should use it and avoid bumping one level
50− -- of indentation
56+ = -- | Multi-line layout should cause
57+ -- insertion of a newline and indentation
58+ -- bump
59+ Normal
60+ | -- | Expressions that have hanging form
61+ -- should use it and avoid bumping one level
62+ -- of indentation
63+ Hanging
64+ deriving (Eq, Show)
5165
5266p_valDecl :: HsBindLR GhcPs GhcPs -> R ()
53−p_valDecl = line . p_valDecl'
54−
55−p_valDecl' :: HsBindLR GhcPs GhcPs -> R ()
56−p_valDecl' = \case
57− FunBind NoExt funId funMatches _ _ -> p_funBind funId funMatches
58− PatBind NoExt pat grhss _ -> p_match PatternBind False [pat] grhss
67+p_valDecl = \case
68+ FunBind NoExtField funId funMatches _ _ -> p_funBind funId funMatches
69+ PatBind NoExtField pat grhss _ -> p_match PatternBind False NoSrcStrict [pat] grhss
5970 VarBind {} -> notImplemented "VarBinds" -- introduced by the type checker
6071 AbsBinds {} -> notImplemented "AbsBinds" -- introduced by the type checker
61− PatSynBind NoExt psb -> p_patSynBind psb
62− XHsBindsLR NoExt -> notImplemented "XHsBindsLR"
63−
64−p_funBind
65− :: Located RdrName
66− -> MatchGroup GhcPs (LHsExpr GhcPs)
67− -> R ()
68−p_funBind name mgroup =
69− p_matchGroup (Function name) mgroup
70−
71−p_matchGroup
72− :: MatchGroupStyle
73− -> MatchGroup GhcPs (LHsExpr GhcPs)
74− -> R ()
75−p_matchGroup style MG {..} =
76− locatedVia Nothing mg_alts $
77− newlineSep (located' (\m@Match {..} ->
78− p_match style (isInfixMatch m) m_pats m_grhss))
79−p_matchGroup _ (XMatchGroup NoExt) = notImplemented "XMatchGroup"
80−
81−p_match
82− :: MatchGroupStyle
83− -> Bool -- ^ Is this an infix match?
84− -> [LPat GhcPs]
85− -> GRHSs GhcPs (LHsExpr GhcPs)
86− -> R ()
87−p_match style isInfix m_pats m_grhss = do
88− -- NOTE Normally, since patterns may be placed in a multi-line layout, it
89− -- is necessary to bump indentation for the pattern group so it's more
72+ PatSynBind NoExtField psb -> p_patSynBind psb
73+ XHsBindsLR x -> noExtCon x
74+
75+p_funBind ::
76+ Located RdrName ->
77+ MatchGroup GhcPs (LHsExpr GhcPs) ->
78+ R ()
79+p_funBind name = p_matchGroup (Function name)
80+
81+p_matchGroup ::
82+ MatchGroupStyle ->
83+ MatchGroup GhcPs (LHsExpr GhcPs) ->
84+ R ()
85+p_matchGroup = p_matchGroup' exprPlacement p_hsExpr
86+
87+p_matchGroup' ::
88+ Data body =>
89+ -- | How to get body placement
90+ (body -> Placement) ->
91+ -- | How to print body
92+ (body -> R ()) ->
93+ -- | Style of this group of equations
94+ MatchGroupStyle ->
95+ -- | Match group
96+ MatchGroup GhcPs (Located body) ->
97+ R ()
98+p_matchGroup' placer render style MG {..} = do
99+ let ob = case style of
100+ Case -> id
101+ LambdaCase -> id
102+ _ -> dontUseBraces
103+ -- Since we are forcing braces on 'sepSemi' based on 'ob', we have to
104+ -- restore the brace state inside the sepsemi.
105+ ub <- bool dontUseBraces useBraces <$> canUseBraces
106+ ob $ sepSemi (located' (ub . p_Match)) (unLoc mg_alts)
107+ where
108+ p_Match m@Match {..} =
109+ p_match'
110+ placer
111+ render
112+ (adjustMatchGroupStyle m style)
113+ (isInfixMatch m)
114+ (matchStrictness m)
115+ m_pats
116+ m_grhss
117+ p_Match (XMatch x) = noExtCon x
118+p_matchGroup' _ _ _ (XMatchGroup x) = noExtCon x
119+
120+-- | Function id obtained through pattern matching on 'FunBind' should not
121+-- be used to print the actual equations because the different ‘RdrNames’
122+-- used in the equations may have different “decorations” (such as backticks
123+-- and paretheses) associated with them. It is necessary to use per-equation
124+-- names obtained from 'm_ctxt' of 'Match'. This function replaces function
125+-- name inside of 'Function' accordingly.
126+adjustMatchGroupStyle ::
127+ Match GhcPs body ->
128+ MatchGroupStyle ->
129+ MatchGroupStyle
130+adjustMatchGroupStyle m = \case
131+ Function _ -> (Function . mc_fun . m_ctxt) m
132+ style -> style
133+
134+matchStrictness :: Match id body -> SrcStrictness
135+matchStrictness match =
136+ case m_ctxt match of
137+ FunRhs {mc_strictness = s} -> s
138+ _ -> NoSrcStrict
139+
140+p_match ::
141+ -- | Style of the group
142+ MatchGroupStyle ->
143+ -- | Is this an infix match?
144+ Bool ->
145+ -- | Strictness prefix (FunBind)
146+ SrcStrictness ->
147+ -- | Argument patterns
148+ [LPat GhcPs] ->
149+ -- | Equations
150+ GRHSs GhcPs (LHsExpr GhcPs) ->
151+ R ()
152+p_match = p_match' exprPlacement p_hsExpr
153+
154+p_match' ::
155+ Data body =>
156+ -- | How to get body placement
157+ (body -> Placement) ->
158+ -- | How to print body
159+ (body -> R ()) ->
160+ -- | Style of this group of equations
161+ MatchGroupStyle ->
162+ -- | Is this an infix match?
163+ Bool ->
164+ -- | Strictness prefix (FunBind)
165+ SrcStrictness ->
166+ -- | Argument patterns
167+ [LPat GhcPs] ->
168+ -- | Equations
169+ GRHSs GhcPs (Located body) ->
170+ R ()
171+p_match' placer render style isInfix strictness m_pats GRHSs {..} = do
172+ -- Normally, since patterns may be placed in a multi-line layout, it is
173+ -- necessary to bump indentation for the pattern group so it's more
90174 -- indented than function name. This in turn means that indentation for
91175 -- the body should also be bumped. Normally this would mean that bodies
92176 -- would start with two indentation steps applied, which is ugly, so we
93177 -- need to be a bit more clever here and bump indentation level only when
94178 -- pattern group is multiline.
95− inci' <- case NE.nonEmpty m_pats of
96− Nothing -> id <$ case style of
97− Function name -> p_rdrName name
98− _ -> return ()
179+ case strictness of
180+ NoSrcStrict -> return ()
181+ SrcStrict -> txt "!"
182+ SrcLazy -> txt "~"
183+ indentBody <- case NE.nonEmpty m_pats of
184+ Nothing ->
185+ False <$ case style of
186+ Function name -> p_rdrName name
187+ _ -> return ()
99188 Just ne_pats -> do
100− let combinedSpans = combineSrcSpans' $
101− getLoc <$> ne_pats
102− inci' = if isOneLineSpan combinedSpans
103− then id
104− else inci
105− switchLayout combinedSpans $ do
106− let stdCase = velt' (located' p_pat <$> m_pats)
189+ let combinedSpans = case style of
190+ Function name -> combineSrcSpans (getLoc name) patSpans
191+ _ -> patSpans
192+ patSpans = combineSrcSpans' (getLoc <$> ne_pats)
193+ indentBody = not (isOneLineSpan combinedSpans)
194+ switchLayout [combinedSpans] $ do
195+ let stdCase = sep breakpoint (located' p_pat) m_pats
107196 case style of
108197 Function name ->
109198 p_infixDefHelper
110199 isInfix
111− inci'
200+ indentBody
112201 (p_rdrName name)
113202 (located' p_pat <$> m_pats)
114203 PatternBind -> stdCase
115204 Case -> stdCase
116205 Lambda -> do
206+ let needsSpace = case unLoc (NE.head ne_pats) of
207+ LazyPat _ _ -> True
208+ BangPat _ _ -> True
209+ SplicePat _ _ -> True
210+ _ -> False
117211 txt "\\"
118− stdCase
212+ when needsSpace space
213+ sitcc stdCase
119214 LambdaCase -> stdCase
120− return inci'
121−
122− let
123− -- Calculate a 'SrcSpan' that captures the end of the name\/pattern part
124− -- of the match. This is used to tell if we need to have the body on a
125− -- newline.
126− endOfPatsSpan = srcLocSpan . srcSpanEnd <$> case NE.nonEmpty m_pats of
127− Nothing -> case style of
128− Function name -> Just $ getLoc name
129− _ -> Nothing
130− Just pats -> Just . getLoc $ NE.last pats
131− isCase = \case
132− Case -> True
133− LambdaCase -> True
134− _ -> False
135− inci' $ do
136− let GRHSs {..} = m_grhss
137− hasGuards = withGuards grhssGRHSs
138− unless (length grhssGRHSs > 1) $ do
139− case style of
140− Function _ -> txt " ="
141− PatternBind -> txt " ="
142− s | isCase s && hasGuards -> return ()
143− _ -> txt " ->"
144− let grhssSpan = combineSrcSpans' $
215+ return indentBody
216+ let -- Calculate position of end of patterns. This is useful when we decide
217+ -- about putting certain constructions in hanging positions.
218+ endOfPats = case NE.nonEmpty m_pats of
219+ Nothing -> case style of
220+ Function name -> Just (getLoc name)
221+ _ -> Nothing
222+ Just pats -> (Just . getLoc . NE.last) pats
223+ isCase = \case
224+ Case -> True
225+ LambdaCase -> True
226+ _ -> False
227+ hasGuards = withGuards grhssGRHSs
228+ grhssSpan =
229+ combineSrcSpans' $
145230 getGRHSSpan . unLoc <$> NE.fromList grhssGRHSs
146− patGrhssSpan = maybe grhssSpan (combineSrcSpans grhssSpan) endOfPatsSpan
147− placement = blockPlacement grhssGRHSs
148− inciLocalBinds = case placement of
149− Normal -> id
150− Hanging -> inci
151− p_body = do
152− let groupStyle =
153− if isCase style && hasGuards
231+ patGrhssSpan =
232+ maybe
233+ grhssSpan
234+ (combineSrcSpans grhssSpan . srcLocSpan . srcSpanEnd)
235+ endOfPats
236+ placement =
237+ case endOfPats of
238+ Nothing -> blockPlacement placer grhssGRHSs
239+ Just spn ->
240+ if onTheSameLine spn grhssSpan
241+ then blockPlacement placer grhssGRHSs
242+ else Normal
243+ p_body = do
244+ let groupStyle =
245+ if isCase style && hasGuards
154246 then RightArrow
155247 else EqualSign
156− newlineSep (located' (p_grhs groupStyle)) grhssGRHSs
157− unless
158− (GHC.isEmptyLocalBindsPR (unLoc grhssLocalBinds))
159− (inciLocalBinds $ do
160− newline
161− line (txt "where")
162− inci (located grhssLocalBinds p_hsLocalBinds)
163− )
164− case style of
165− Lambda -> placeHanging placement $
166− switchLayout patGrhssSpan p_body
167− _ -> switchLayout patGrhssSpan $
168− placeHanging placement p_body
248+ sep newline (located' (p_grhs' placer render groupStyle)) grhssGRHSs
249+ p_where = do
250+ let whereIsEmpty = GHC.isEmptyLocalBindsPR (unLoc grhssLocalBinds)
251+ unless (GHC.eqEmptyLocalBinds (unLoc grhssLocalBinds)) $ do
252+ breakpoint
253+ txt "where"
254+ unless whereIsEmpty breakpoint
255+ inci $ located grhssLocalBinds p_hsLocalBinds
256+ inciIf indentBody $ do
257+ unless (length grhssGRHSs > 1) $
258+ case style of
259+ Function _ | hasGuards -> return ()
260+ Function _ -> space >> inci equals
261+ PatternBind -> space >> inci equals
262+ s | isCase s && hasGuards -> return ()
263+ _ -> space >> txt "->"
264+ switchLayout [patGrhssSpan] $
265+ placeHanging placement p_body
266+ inci p_where
267+p_match' _ _ _ _ _ _ (XGRHSs x) = noExtCon x
169268
170269p_grhs :: GroupStyle -> GRHS GhcPs (LHsExpr GhcPs) -> R ()
171−p_grhs style (GRHS NoExt guards body) =
270+p_grhs = p_grhs' exprPlacement p_hsExpr
271+
272+p_grhs' ::
273+ Data body =>
274+ -- | How to get body placement
275+ (body -> Placement) ->
276+ -- | How to print body
277+ (body -> R ()) ->
278+ GroupStyle ->
279+ GRHS GhcPs (Located body) ->
280+ R ()
281+p_grhs' placer render style (GRHS NoExtField guards body) =
172282 case guards of
173283 [] -> p_body
174284 xs -> do
175− txt "| "
176− velt $ withSep comma (located' p_stmt) xs
285+ txt "|"
177286 space
178− txt $ case style of
179− EqualSign -> "="
180− RightArrow -> "->"
181− breakpoint
182− inci p_body
287+ sitcc (sep commaDel (sitcc . located' p_stmt) xs)
288+ space
289+ inci $ case style of
290+ EqualSign -> equals
291+ RightArrow -> txt "->"
292+ placeHanging placement p_body
183293 where
184− p_body = located body p_hsExpr
185−p_grhs _ (XGRHS NoExt) = notImplemented "XGRHS"
294+ placement =
295+ case endOfGuards of
296+ Nothing -> placer (unLoc body)
297+ Just spn ->
298+ if onTheSameLine spn (getLoc body)
299+ then placer (unLoc body)
300+ else Normal
301+ endOfGuards =
302+ case NE.nonEmpty guards of
303+ Nothing -> Nothing
304+ Just gs -> (Just . getLoc . NE.last) gs
305+ p_body = located body render
306+p_grhs' _ _ _ (XGRHS x) = noExtCon x
307+
308+p_hsCmd :: HsCmd GhcPs -> R ()
309+p_hsCmd = \case
310+ HsCmdArrApp NoExtField body input arrType _ -> do
311+ located body p_hsExpr
312+ breakpoint
313+ inci $ do
314+ case arrType of
315+ HsFirstOrderApp -> txt "-<"
316+ HsHigherOrderApp -> txt "-<<"
317+ placeHanging (exprPlacement (unLoc input)) $
318+ located input p_hsExpr
319+ HsCmdArrForm NoExtField form Prefix _ cmds -> banana $ do
320+ located form p_hsExpr
321+ unless (null cmds) $ do
322+ breakpoint
323+ inci (sequence_ (intersperse breakpoint (located' p_hsCmdTop <$> cmds)))
324+ HsCmdArrForm NoExtField form Infix _ [left, right] -> do
325+ located left p_hsCmdTop
326+ space
327+ located form p_hsExpr
328+ placeHanging (cmdTopPlacement (unLoc right)) $
329+ located right p_hsCmdTop
330+ HsCmdArrForm NoExtField _ Infix _ _ -> notImplemented "HsCmdArrForm"
331+ HsCmdApp {} ->
332+ -- XXX Does this ever occur in the syntax tree? It does not seem like it
333+ -- does. Open an issue and ping @yumiova if this ever occurs in output.
334+ notImplemented "HsCmdApp"
335+ HsCmdLam NoExtField mgroup -> p_matchGroup' cmdPlacement p_hsCmd Lambda mgroup
336+ HsCmdPar NoExtField c -> parens N (located c p_hsCmd)
337+ HsCmdCase NoExtField e mgroup ->
338+ p_case cmdPlacement p_hsCmd e mgroup
339+ HsCmdIf NoExtField _ if' then' else' ->
340+ p_if cmdPlacement p_hsCmd if' then' else'
341+ HsCmdLet NoExtField localBinds c ->
342+ p_let p_hsCmd localBinds c
343+ HsCmdDo NoExtField es -> do
344+ txt "do"
345+ newline
346+ inci . located es $
347+ sitcc . sep newline (sitcc . withSpacing (p_stmt' cmdPlacement p_hsCmd))
348+ HsCmdWrap {} -> notImplemented "HsCmdWrap"
349+ XCmd x -> noExtCon x
350+
351+p_hsCmdTop :: HsCmdTop GhcPs -> R ()
352+p_hsCmdTop = \case
353+ HsCmdTop NoExtField cmd -> located cmd p_hsCmd
354+ XCmdTop x -> noExtCon x
355+
356+-- | Render an expression preserving blank lines between such consecutive
357+-- expressions found in the original source code.
358+withSpacing ::
359+ -- | Rendering function
360+ (a -> R ()) ->
361+ -- | Entity to render
362+ Located a ->
363+ R ()
364+withSpacing f l = located l $ \x -> do
365+ case getLoc l of
366+ UnhelpfulSpan _ -> f x
367+ RealSrcSpan currentSpn -> do
368+ getSpanMark >>= \case
369+ -- Spacing before comments will be handled by the code
370+ -- that prints comments, so we just have to deal with
371+ -- blank lines between statements here.
372+ Just (StatementSpan lastSpn) ->
373+ if srcSpanStartLine currentSpn > srcSpanEndLine lastSpn + 1
374+ then newline
375+ else return ()
376+ _ -> return ()
377+ f x
378+ -- In some cases the (f x) expression may insert a new mark. We want
379+ -- to be careful not to override comment marks.
380+ getSpanMark >>= \case
381+ Just (HaddockSpan _ _) -> return ()
382+ Just (CommentSpan _) -> return ()
383+ _ -> setSpanMark (StatementSpan currentSpn)
186384
187385p_stmt :: Stmt GhcPs (LHsExpr GhcPs) -> R ()
188−p_stmt = \case
189− LastStmt NoExt body _ _ -> located body p_hsExpr
190− BindStmt NoExt l f _ _ -> do
191− located l p_pat
386+p_stmt = p_stmt' exprPlacement p_hsExpr
387+
388+p_stmt' ::
389+ Data body =>
390+ -- | Placer
391+ (body -> Placement) ->
392+ -- | Render
393+ (body -> R ()) ->
394+ -- | Statement to render
395+ Stmt GhcPs (Located body) ->
396+ R ()
397+p_stmt' placer render = \case
398+ LastStmt NoExtField body _ _ -> located body render
399+ BindStmt NoExtField p f _ _ -> do
400+ located p p_pat
192401 space
193402 txt "<-"
194− breakpoint
195− inci (located f p_hsExpr)
196− ApplicativeStmt {} -> notImplemented "ApplicativeStmt"
197− BodyStmt NoExt body _ _ -> located body p_hsExpr
198− LetStmt NoExt binds -> do
199− txt "let "
403+ let loc = getLoc p
404+ placement =
405+ case f of
406+ L l' x ->
407+ if isOneLineSpan
408+ (mkSrcSpan (srcSpanEnd loc) (srcSpanStart l'))
409+ then placer x
410+ else Normal
411+ switchLayout [loc, getLoc f] $
412+ placeHanging placement (located f render)
413+ ApplicativeStmt {} -> notImplemented "ApplicativeStmt" -- generated by renamer
414+ BodyStmt NoExtField body _ _ -> located body render
415+ LetStmt NoExtField binds -> do
416+ txt "let"
417+ space
200418 sitcc $ located binds p_hsLocalBinds
201− ParStmt NoExt stmts _ _ ->
202− sequence_ $ intersperse breakpoint $
203− withSep (txt "| ") p_parStmtBlock stmts
204− TransStmt {} -> notImplemented "TransStmt"
205− RecStmt {} -> notImplemented "RecStmt"
206− XStmtLR {} -> notImplemented "XStmtLR"
207−
208−p_parStmtBlock :: ParStmtBlock GhcPs GhcPs -> R ()
209−p_parStmtBlock = \case
210− ParStmtBlock NoExt stmts _ _ ->
211− velt $ withSep comma (located' (sitcc . p_stmt)) stmts
212− XParStmtBlock {} -> notImplemented "XParStmtBlock"
419+ ParStmt {} ->
420+ -- 'ParStmt' should always be eliminated in 'gatherStmt' already, such
421+ -- that it never occurs in 'p_stmt''. Consequently, handling it here
422+ -- would be redundant.
423+ notImplemented "ParStmt"
424+ TransStmt {..} ->
425+ -- 'TransStmt' only needs to account for render printing itself, since
426+ -- pretty printing of relevant statements (e.g., in 'trS_stmts') is
427+ -- handled through 'gatherStmt'.
428+ case (trS_form, trS_by) of
429+ (ThenForm, Nothing) -> do
430+ txt "then"
431+ breakpoint
432+ inci $ located trS_using p_hsExpr
433+ (ThenForm, Just e) -> do
434+ txt "then"
435+ breakpoint
436+ inci $ located trS_using p_hsExpr
437+ breakpoint
438+ txt "by"
439+ breakpoint
440+ inci $ located e p_hsExpr
441+ (GroupForm, Nothing) -> do
442+ txt "then group using"
443+ breakpoint
444+ inci $ located trS_using p_hsExpr
445+ (GroupForm, Just e) -> do
446+ txt "then group by"
447+ breakpoint
448+ inci $ located e p_hsExpr
449+ breakpoint
450+ txt "using"
451+ breakpoint
452+ inci $ located trS_using p_hsExpr
453+ RecStmt {..} -> do
454+ txt "rec"
455+ space
456+ sitcc $ sepSemi (withSpacing (p_stmt' placer render)) recS_stmts
457+ XStmtLR c -> noExtCon c
458+
459+gatherStmt :: ExprLStmt GhcPs -> [[ExprLStmt GhcPs]]
460+gatherStmt (L _ (ParStmt NoExtField block _ _)) =
461+ foldr ((<>) . gatherStmtBlock) [] block
462+gatherStmt (L s stmt@TransStmt {..}) =
463+ foldr liftAppend [] ((gatherStmt <$> trS_stmts) <> pure [[L s stmt]])
464+gatherStmt stmt = [[stmt]]
465+
466+gatherStmtBlock :: ParStmtBlock GhcPs GhcPs -> [[ExprLStmt GhcPs]]
467+gatherStmtBlock (ParStmtBlock _ stmts _ _) =
468+ foldr (liftAppend . gatherStmt) [] stmts
469+gatherStmtBlock (XParStmtBlock x) = noExtCon x
213470
214471p_hsLocalBinds :: HsLocalBindsLR GhcPs GhcPs -> R ()
215472p_hsLocalBinds = \case
216− HsValBinds NoExt (ValBinds NoExt bag lsigs) -> do
217− let ssStart = either
218− (srcSpanStart . getLoc)
219− (srcSpanStart . getLoc)
220− items =
221− (Left <$> bagToList bag) ++ (Right <$> lsigs)
222− p_item (Left x) = located x p_valDecl'
223− p_item (Right x) = located x p_sigDecl'
224− newlineSep p_item (sortOn ssStart items)
225− HsValBinds NoExt _ -> notImplemented "HsValBinds"
226− HsIPBinds NoExt _ -> notImplemented "HsIPBinds"
227− EmptyLocalBinds NoExt -> return ()
228− XHsLocalBindsLR _ -> notImplemented "XHsLocalBindsLR"
229−
230−p_hsRecField
231− :: (Data id, Outputable id)
232− => HsRecField' id (LHsExpr GhcPs)
233− -> R ()
234−p_hsRecField = \HsRecField {..} -> do
235− located hsRecFieldLbl atom
236− unless hsRecPun $ do
237− txt " = "
238− located hsRecFieldArg p_hsExpr
239−
240−p_hsTupArg :: HsTupArg GhcPs -> R ()
241−p_hsTupArg = \case
242− Present NoExt x -> located x p_hsExpr
243− Missing NoExt -> pure ()
244− XTupArg {} -> notImplemented "XTupArg"
473+ HsValBinds NoExtField (ValBinds NoExtField bag lsigs) -> do
474+ -- When in a single-line layout, there is a chance that the inner
475+ -- elements will also contain semicolons and they will confuse the
476+ -- parser. so we request braces around every element except the last.
477+ br <- layoutToBraces <$> getLayout
478+ let items =
479+ let injectLeft (L l x) = L l (Left x)
480+ injectRight (L l x) = L l (Right x)
481+ in (injectLeft <$> bagToList bag) ++ (injectRight <$> lsigs)
482+ positionToBracing = \case
483+ SinglePos -> id
484+ FirstPos -> br
485+ MiddlePos -> br
486+ LastPos -> id
487+ p_item' (p, item) =
488+ positionToBracing p $
489+ withSpacing (either p_valDecl p_sigDecl) item
490+ binds = sortOn (srcSpanStart . getLoc) items
491+ sitcc $ sepSemi p_item' (attachRelativePos binds)
492+ HsValBinds NoExtField _ -> notImplemented "HsValBinds"
493+ HsIPBinds NoExtField (IPBinds NoExtField xs) ->
494+ -- Second argument of IPBind is always Left before type-checking.
495+ let p_ipBind (IPBind NoExtField (Left name) expr) = do
496+ atom name
497+ space
498+ equals
499+ breakpoint
500+ useBraces $ inci $ located expr p_hsExpr
501+ p_ipBind (IPBind NoExtField (Right _) _) =
502+ -- Should only occur after the type checker
503+ notImplemented "IPBind _ (Right _) _"
504+ p_ipBind (XIPBind x) = noExtCon x
505+ in sepSemi (located' p_ipBind) xs
506+ HsIPBinds NoExtField _ -> notImplemented "HsIpBinds"
507+ EmptyLocalBinds NoExtField -> return ()
508+ XHsLocalBindsLR x -> noExtCon x
509+
510+p_hsRecField ::
511+ HsRecField' RdrName (LHsExpr GhcPs) ->
512+ R ()
513+p_hsRecField HsRecField {..} = do
514+ p_rdrName hsRecFieldLbl
515+ unless hsRecPun $ do
516+ space
517+ equals
518+ let placement =
519+ if onTheSameLine (getLoc hsRecFieldLbl) (getLoc hsRecFieldArg)
520+ then exprPlacement (unLoc hsRecFieldArg)
521+ else Normal
522+ placeHanging placement (located hsRecFieldArg p_hsExpr)
245523
246524p_hsExpr :: HsExpr GhcPs -> R ()
247−p_hsExpr = \case
248− HsVar NoExt name -> p_rdrName name
249− HsUnboundVar NoExt _ -> notImplemented "HsUnboundVar"
250− HsConLikeOut NoExt _ -> notImplemented "HsConLikeOut"
251− HsRecFld NoExt x ->
525+p_hsExpr = p_hsExpr' N
526+
527+p_hsExpr' :: BracketStyle -> HsExpr GhcPs -> R ()
528+p_hsExpr' s = \case
529+ HsVar NoExtField name -> p_rdrName name
530+ HsUnboundVar NoExtField v -> atom (unboundVarOcc v)
531+ HsConLikeOut NoExtField _ -> notImplemented "HsConLikeOut"
532+ HsRecFld NoExtField x ->
252533 case x of
253− Unambiguous NoExt name -> p_rdrName name
254− Ambiguous NoExt name -> p_rdrName name
255− XAmbiguousFieldOcc NoExt -> notImplemented "XAmbiguousFieldOcc"
256− HsOverLabel NoExt _ v -> do
534+ Unambiguous NoExtField name -> p_rdrName name
535+ Ambiguous NoExtField name -> p_rdrName name
536+ XAmbiguousFieldOcc xx -> noExtCon xx
537+ HsOverLabel NoExtField _ v -> do
257538 txt "#"
258539 atom v
259− HsIPVar NoExt (HsIPName name) -> do
540+ HsIPVar NoExtField (HsIPName name) -> do
260541 txt "?"
261542 atom name
262− HsOverLit NoExt v -> atom (ol_val v)
263− HsLit NoExt lit -> atom lit
264− HsLam NoExt mgroup ->
543+ HsOverLit NoExtField v -> atom (ol_val v)
544+ HsLit NoExtField lit ->
545+ case lit of
546+ HsString (SourceText stxt) _ -> p_stringLit stxt
547+ HsStringPrim (SourceText stxt) _ -> p_stringLit stxt
548+ r -> atom r
549+ HsLam NoExtField mgroup ->
265550 p_matchGroup Lambda mgroup
266− HsLamCase NoExt mgroup -> do
551+ HsLamCase NoExtField mgroup -> do
267552 txt "\\case"
268− newline
269− inci (p_matchGroup LambdaCase mgroup)
270− HsApp NoExt f x -> do
271− located f p_hsExpr
272553 breakpoint
273− inci (located x p_hsExpr)
274− HsAppType a e -> do
554+ inci (p_matchGroup LambdaCase mgroup)
555+ HsApp NoExtField f x -> do
556+ let -- In order to format function applications with multiple parameters
557+ -- nicer, traverse the AST to gather the function and all the
558+ -- parameters together.
559+ gatherArgs f' knownArgs =
560+ case f' of
561+ L _ (HsApp _ l r) -> gatherArgs l (r <| knownArgs)
562+ _ -> (f', knownArgs)
563+ (func, args) = gatherArgs f (x :| [])
564+ -- We need to handle the last argument specially if it is a
565+ -- hanging construct, so separate it from the rest.
566+ (initp, lastp) = (NE.init args, NE.last args)
567+ initSpan =
568+ combineSrcSpans' $
569+ getLoc f :| [(srcLocSpan . srcSpanStart . getLoc) lastp]
570+ -- Hang the last argument only if the initial arguments span one
571+ -- line.
572+ placement =
573+ if isOneLineSpan initSpan
574+ then exprPlacement (unLoc lastp)
575+ else Normal
576+ -- If the last argument is not hanging, just separate every argument as
577+ -- usual. If it is hanging, print the initial arguments and hang the
578+ -- last one. Also, use braces around the every argument except the last
579+ -- one.
580+ case placement of
581+ Normal -> do
582+ let -- Usually we want to bump indentation for arguments for the
583+ -- sake of readability. However, when the function itself is a
584+ -- do-block or case expression it is not a good idea. It seems
585+ -- to be safe to always bump indentation when the function
586+ -- expression is parenthesised.
587+ doIndent =
588+ case func of
589+ L _ (HsPar NoExtField _) -> True
590+ L _ (HsAppType NoExtField _ _) -> True
591+ L _ (HsMultiIf NoExtField _) -> True
592+ L spn _ -> isOneLineSpan spn
593+ ub <-
594+ getLayout <&> \case
595+ SingleLine -> useBraces
596+ MultiLine -> id
597+ ub $ do
598+ located func (p_hsExpr' s)
599+ breakpoint
600+ inciIf doIndent $ sep breakpoint (located' p_hsExpr) initp
601+ inciIf doIndent $ do
602+ unless (null initp) breakpoint
603+ located lastp p_hsExpr
604+ Hanging -> do
605+ useBraces . switchLayout [initSpan] $ do
606+ located func (p_hsExpr' s)
607+ breakpoint
608+ sep breakpoint (located' p_hsExpr) initp
609+ placeHanging placement $
610+ located lastp p_hsExpr
611+ HsAppType NoExtField e a -> do
275612 located e p_hsExpr
276613 breakpoint
277614 inci $ do
278615 txt "@"
616+ -- Insert a space when the type is represented as a TH splice to avoid
617+ -- gluing @ and $ together.
618+ case unLoc (hswc_body a) of
619+ HsSpliceTy {} -> space
620+ _ -> return ()
279621 located (hswc_body a) p_hsType
280− OpApp NoExt x op y -> do
281− located x p_hsExpr
282− space
283− located op p_hsExpr
284− placeHanging (exprPlacement (unLoc y)) $
285− located y p_hsExpr
286− NegApp NoExt e _ -> do
622+ OpApp NoExtField x op y -> do
623+ let opTree = OpBranch (exprOpTree x) op (exprOpTree y)
624+ p_exprOpTree s (reassociateOpTree getOpName opTree)
625+ NegApp NoExtField e _ -> do
287626 txt "-"
627+ space
288628 located e p_hsExpr
289− HsPar NoExt e -> parens (located e p_hsExpr)
290− SectionL NoExt x op -> do
629+ HsPar NoExtField e ->
630+ parens s (located e (dontUseBraces . p_hsExpr))
631+ SectionL NoExtField x op -> do
291632 located x p_hsExpr
292633 breakpoint
293634 inci (located op p_hsExpr)
294− SectionR NoExt op x -> do
635+ SectionR NoExtField op x -> do
295636 located op p_hsExpr
296− breakpoint
637+ useRecordDot' <- useRecordDot
638+ let isRecordDot' = isRecordDot (unLoc op) (getLoc x)
639+ unless (useRecordDot' && isRecordDot') breakpoint
297640 inci (located x p_hsExpr)
298− ExplicitTuple NoExt args boxity -> do
641+ ExplicitTuple NoExtField args boxity ->
299642 let isSection = any (isMissing . unLoc) args
300643 isMissing = \case
301− Missing NoExt -> True
644+ Missing NoExtField -> True
302645 _ -> False
303− let parens' =
646+ p_arg = \case
647+ Present NoExtField x -> located x p_hsExpr
648+ Missing NoExtField -> pure ()
649+ XTupArg x -> noExtCon x
650+ p_larg = sitcc . located' p_arg
651+ parens' =
304652 case boxity of
305653 Boxed -> parens
306654 Unboxed -> parensHash
307− parens' $ if isSection
308− then sequence_ (withSep (txt ",") (located' p_hsTupArg) args)
309− else velt (withSep comma (located' p_hsTupArg) args)
310− ExplicitSum NoExt tag arity e -> do
311− let before = tag - 1
312− after = arity - before - 1
313− args = replicate before Nothing <> [Just e] <> replicate after Nothing
314− f (x,i) = do
315− let isFirst = i == 0
316− isLast = i == arity - 1
317− case x of
318− Nothing ->
319− unless (isFirst || isLast) space
320− Just l -> do
321− unless isFirst space
322− located l p_hsExpr
323− unless isLast space
324− parensHash $ sequence_ (withSep (txt "|") f (zip args [0..]))
325− HsCase NoExt e mgroup -> do
326− txt "case "
327− located e p_hsExpr
328− txt " of"
329− breakpoint
330− inci (p_matchGroup Case mgroup)
331− HsIf NoExt _ if' then' else' -> do
332− txt "if "
333− located if' p_hsExpr
334− breakpoint
335− txt "then"
336− located then' $ \x -> do
337− breakpoint
338− inci (p_hsExpr x)
339− breakpoint
340− txt "else"
341− located else' $ \x -> do
342− breakpoint
343− inci (p_hsExpr x)
344− HsMultiIf NoExt guards -> do
345− txt "if "
346− sitcc $ newlineSep (located' (p_grhs RightArrow)) guards
347− HsLet NoExt localBinds e -> do
348− txt "let "
349− sitcc (located localBinds p_hsLocalBinds)
655+ in if isSection
656+ then
657+ switchLayout [] . parens' s $
658+ sep comma p_larg args
659+ else
660+ switchLayout (getLoc <$> args) . parens' s $
661+ sep commaDel p_larg args
662+ ExplicitSum NoExtField tag arity e ->
663+ p_unboxedSum N tag arity (located e p_hsExpr)
664+ HsCase NoExtField e mgroup ->
665+ p_case exprPlacement p_hsExpr e mgroup
666+ HsIf NoExtField _ if' then' else' ->
667+ p_if exprPlacement p_hsExpr if' then' else'
668+ HsMultiIf NoExtField guards -> do
669+ txt "if"
350670 breakpoint
351− txt "in "
352− sitcc (located e p_hsExpr)
353− HsDo NoExt ctx es -> do
671+ inci . inci $ sep newline (located' (p_grhs RightArrow)) guards
672+ HsLet NoExtField localBinds e ->
673+ p_let p_hsExpr localBinds e
674+ HsDo NoExtField ctx es -> do
354675 let doBody header = do
355676 txt header
356− newline
357− inci $ located es (newlineSep (located' (sitcc . p_stmt)))
358− compBody = brackets $ located es $ \xs -> do
359− let stmts = init xs
677+ breakpoint
678+ ub <- layoutToBraces <$> getLayout
679+ inci $
680+ sepSemi
681+ (ub . withSpacing (p_stmt' exprPlacement (p_hsExpr' S)))
682+ (unLoc es)
683+ compBody = brackets N . located es $ \xs -> do
684+ let p_parBody =
685+ sep
686+ (breakpoint >> txt "|" >> space)
687+ p_seqBody
688+ p_seqBody =
689+ sitcc
690+ . sep
691+ commaDel
692+ (located' (sitcc . p_stmt))
693+ stmts = init xs
360694 yield = last xs
695+ lists = foldr (liftAppend . gatherStmt) [] stmts
361696 located yield p_stmt
362697 breakpoint
363− txt "| "
364− case stmts of
365− [stmt] | ParStmt {} <- unLoc stmt -> located stmt p_stmt
366− _ -> velt $ withSep comma (located' (sitcc . p_stmt)) stmts
698+ txt "|"
699+ space
700+ p_parBody lists
367701 case ctx of
368702 DoExpr -> doBody "do"
369703 MDoExpr -> doBody "mdo"
370704 ListComp -> compBody
371705 MonadComp -> notImplemented "MonadComp"
372− ArrowExpr -> notImplemented "ArrowExpr"
706+ ArrowExpr -> notImplemented "ArrowExpr"
373707 GhciStmtCtxt -> notImplemented "GhciStmtCtxt"
374708 PatGuard _ -> notImplemented "PatGuard"
375709 ParStmtCtxt _ -> notImplemented "ParStmtCtxt"
376710 TransStmtCtxt _ -> notImplemented "TransStmtCtxt"
377711 ExplicitList _ _ xs ->
378− brackets $ velt (withSep comma (located' p_hsExpr) xs)
712+ brackets s $
713+ sep commaDel (sitcc . located' p_hsExpr) xs
379714 RecordCon {..} -> do
380715 located rcon_con_name atom
381716 breakpoint
382717 let HsRecFields {..} = rcon_flds
383− fields = located' p_hsRecField <$> rec_flds
718+ updName f =
719+ (f :: HsRecField GhcPs (LHsExpr GhcPs))
720+ { hsRecFieldLbl = case unLoc $ hsRecFieldLbl f of
721+ FieldOcc _ n -> n
722+ XFieldOcc x -> noExtCon x
723+ }
724+ fields = located' (p_hsRecField . updName) <$> rec_flds
384725 dotdot =
385726 case rec_dotdot of
386727 Just {} -> [txt ".."]
387728 Nothing -> []
388− inci $ braces $ velt (withSep comma id (fields <> dotdot))
729+ inci . braces N $
730+ sep commaDel sitcc (fields <> dotdot)
389731 RecordUpd {..} -> do
390732 located rupd_expr p_hsExpr
391− breakpoint
392− inci $ braces $ velt (withSep comma (located' p_hsRecField) rupd_flds)
393− ExprWithTySig affix x -> sitcc $ do
733+ useRecordDot' <- useRecordDot
734+ let mrs sp = case getLoc sp of
735+ RealSrcSpan r -> Just r
736+ _ -> Nothing
737+ let isPluginForm =
738+ ((1 +) . srcSpanEndCol <$> mrs rupd_expr)
739+ == (srcSpanStartCol <$> mrs (head rupd_flds))
740+ unless (useRecordDot' && isPluginForm) breakpoint
741+ let updName f =
742+ (f :: HsRecUpdField GhcPs)
743+ { hsRecFieldLbl = case unLoc $ hsRecFieldLbl f of
744+ Ambiguous _ n -> n
745+ Unambiguous _ n -> n
746+ XAmbiguousFieldOcc x -> noExtCon x
747+ }
748+ inci . braces N $
749+ sep
750+ commaDel
751+ (sitcc . located' (p_hsRecField . updName))
752+ rupd_flds
753+ ExprWithTySig NoExtField x HsWC {hswc_body = HsIB {..}} -> sitcc $ do
394754 located x p_hsExpr
755+ space
756+ txt "::"
395757 breakpoint
396− inci $ do
397− txt ":: "
398− let HsWC {..} = affix
399− HsIB {..} = hswc_body
400− located hsib_body p_hsType
401− ArithSeq NoExt _ x -> do
758+ inci $ located hsib_body p_hsType
759+ ExprWithTySig NoExtField _ HsWC {hswc_body = XHsImplicitBndrs x} -> noExtCon x
760+ ExprWithTySig NoExtField _ (XHsWildCardBndrs x) -> noExtCon x
761+ ArithSeq NoExtField _ x ->
402762 case x of
403− From from -> brackets $ do
763+ From from -> brackets s $ do
404764 located from p_hsExpr
405− breakpoint'
765+ breakpoint
406766 txt ".."
407− FromThen from next -> brackets $ do
408− velt (withSep comma (located' p_hsExpr) [from, next])
409− breakpoint'
767+ FromThen from next -> brackets s $ do
768+ sep commaDel (located' p_hsExpr) [from, next]
769+ breakpoint
410770 txt ".."
411− FromTo from to -> brackets $ do
771+ FromTo from to -> brackets s $ do
412772 located from p_hsExpr
413− breakpoint'
414− txt ".. "
773+ breakpoint
774+ txt ".."
775+ space
415776 located to p_hsExpr
416− FromThenTo from next to -> brackets $ do
417− velt (withSep comma (located' p_hsExpr) [from, next])
418− breakpoint'
419− txt ".. "
777+ FromThenTo from next to -> brackets s $ do
778+ sep commaDel (located' p_hsExpr) [from, next]
779+ breakpoint
780+ txt ".."
781+ space
420782 located to p_hsExpr
421− HsSCC NoExt _ name x -> do
783+ HsSCC NoExtField _ name x -> do
422784 txt "{-# SCC "
423785 atom name
424786 txt " #-}"
425787 breakpoint
426788 located x p_hsExpr
427− HsCoreAnn NoExt _ value x -> do
789+ HsCoreAnn NoExtField _ value x -> do
428790 txt "{-# CORE "
429791 atom value
430792 txt " #-}"
431793 breakpoint
432794 located x p_hsExpr
433− HsBracket NoExt x -> p_hsBracket x
795+ HsBracket NoExtField x -> p_hsBracket x
434796 HsRnBracketOut {} -> notImplemented "HsRnBracketOut"
435797 HsTcBracketOut {} -> notImplemented "HsTcBracketOut"
436− HsSpliceE NoExt splice -> p_hsSplice splice
437− HsProc {} -> notImplemented "HsProc"
438− HsStatic _ e -> do
798+ HsSpliceE NoExtField splice -> p_hsSplice splice
799+ HsProc NoExtField p e -> do
800+ txt "proc"
801+ located p $ \x -> do
802+ breakpoint
803+ inci (p_pat x)
804+ breakpoint
805+ txt "->"
806+ placeHanging (cmdTopPlacement (unLoc e)) $
807+ located e p_hsCmdTop
808+ HsStatic _ e -> do
439809 txt "static"
440810 breakpoint
441811 inci (located e p_hsExpr)
442− HsArrApp {} -> notImplemented "HsArrApp"
443− HsArrForm {} -> notImplemented "HsArrForm"
444812 HsTick {} -> notImplemented "HsTick"
445813 HsBinTick {} -> notImplemented "HsBinTick"
446814 HsTickPragma {} -> notImplemented "HsTickPragma"
447− EWildPat NoExt -> txt "_"
448− EAsPat {} -> notImplemented "EAsPat"
449− EViewPat {} -> notImplemented "EViewPat"
450− ELazyPat {} -> notImplemented "ELazyPat"
451815 HsWrap {} -> notImplemented "HsWrap"
452− XExpr {} -> notImplemented "XExpr"
816+ XExpr x -> noExtCon x
453817
454818p_patSynBind :: PatSynBind GhcPs GhcPs -> R ()
455819p_patSynBind PSB {..} = do
456− txt "pattern "
457− case psb_dir of
458− Unidirectional -> do
459− p_rdrName psb_id
820+ let rhs = do
821+ space
822+ case psb_dir of
823+ Unidirectional -> do
824+ txt "<-"
825+ breakpoint
826+ located psb_def p_pat
827+ ImplicitBidirectional -> do
828+ equals
829+ breakpoint
830+ located psb_def p_pat
831+ ExplicitBidirectional mgroup -> do
832+ txt "<-"
833+ breakpoint
834+ located psb_def p_pat
835+ newline
836+ txt "where"
837+ newline
838+ inci (p_matchGroup (Function psb_id) mgroup)
839+ txt "pattern"
840+ case psb_args of
841+ PrefixCon xs -> do
460842 space
461− p_patSynDetails psb_args
462− txt " <-"
463− breakpoint
464− inci (located psb_def p_pat)
465− ImplicitBidirectional -> do
466843 p_rdrName psb_id
844+ inci $ do
845+ switchLayout (getLoc <$> xs) $ do
846+ unless (null xs) breakpoint
847+ sitcc (sep breakpoint p_rdrName xs)
848+ rhs
849+ RecCon xs -> do
467850 space
468− p_patSynDetails psb_args
469− txt " ="
470− breakpoint
471− located psb_def p_pat
472− ExplicitBidirectional mgroup -> do
473851 p_rdrName psb_id
474− space
475− p_patSynDetails psb_args
476− txt " <-"
477− breakpoint
478− inci (located psb_def p_pat)
479− newline
480852 inci $ do
481− line (txt "where")
482− inci (p_matchGroup (Function psb_id) mgroup)
483−p_patSynBind (XPatSynBind NoExt) = notImplemented "XPatSynBind"
484−
485−p_patSynDetails :: HsPatSynDetails (Located RdrName) -> R ()
486−p_patSynDetails = \case
487− PrefixCon xs ->
488− velt' (p_rdrName <$> xs)
489− RecCon xs ->
490− velt' (p_rdrName . recordPatSynPatVar <$> xs)
491− InfixCon _ _ -> notImplemented "InfixCon"
853+ switchLayout (getLoc . recordPatSynPatVar <$> xs) $ do
854+ unless (null xs) breakpoint
855+ braces N $
856+ sep commaDel (p_rdrName . recordPatSynPatVar) xs
857+ rhs
858+ InfixCon l r -> do
859+ switchLayout [getLoc l, getLoc r] $ do
860+ space
861+ p_rdrName l
862+ breakpoint
863+ inci $ do
864+ p_rdrName psb_id
865+ space
866+ p_rdrName r
867+ inci rhs
868+p_patSynBind (XPatSynBind x) = noExtCon x
869+
870+p_case ::
871+ Data body =>
872+ -- | Placer
873+ (body -> Placement) ->
874+ -- | Render
875+ (body -> R ()) ->
876+ -- | Expression
877+ LHsExpr GhcPs ->
878+ -- | Match group
879+ MatchGroup GhcPs (Located body) ->
880+ R ()
881+p_case placer render e mgroup = do
882+ txt "case"
883+ space
884+ located e p_hsExpr
885+ space
886+ txt "of"
887+ breakpoint
888+ inci (p_matchGroup' placer render Case mgroup)
889+
890+p_if ::
891+ Data body =>
892+ -- | Placer
893+ (body -> Placement) ->
894+ -- | Render
895+ (body -> R ()) ->
896+ -- | If
897+ LHsExpr GhcPs ->
898+ -- | Then
899+ Located body ->
900+ -- | Else
901+ Located body ->
902+ R ()
903+p_if placer render if' then' else' = do
904+ txt "if"
905+ space
906+ located if' p_hsExpr
907+ breakpoint
908+ inci $ do
909+ txt "then"
910+ space
911+ located then' $ \x ->
912+ placeHanging (placer x) (render x)
913+ breakpoint
914+ txt "else"
915+ space
916+ located else' $ \x ->
917+ placeHanging (placer x) (render x)
918+
919+p_let ::
920+ Data body =>
921+ -- | Render
922+ (body -> R ()) ->
923+ Located (HsLocalBindsLR GhcPs GhcPs) ->
924+ Located body ->
925+ R ()
926+p_let render localBinds e = sitcc $ do
927+ txt "let"
928+ space
929+ dontUseBraces $ sitcc (located localBinds p_hsLocalBinds)
930+ vlayout space (newline >> txt " ")
931+ txt "in"
932+ space
933+ sitcc (located e render)
492934
493935p_pat :: Pat GhcPs -> R ()
494936p_pat = \case
495− WildPat NoExt -> txt "_"
496− VarPat NoExt name -> p_rdrName name
497− LazyPat NoExt pat -> do
937+ WildPat NoExtField -> txt "_"
938+ VarPat NoExtField name -> p_rdrName name
939+ LazyPat NoExtField pat -> do
498940 txt "~"
499941 located pat p_pat
500− AsPat NoExt name pat -> do
942+ AsPat NoExtField name pat -> do
501943 p_rdrName name
502944 txt "@"
503945 located pat p_pat
504− ParPat NoExt pat ->
505− located pat (parens . p_pat)
506− BangPat NoExt pat -> do
946+ ParPat NoExtField pat ->
947+ located pat (parens S . p_pat)
948+ BangPat NoExtField pat -> do
507949 txt "!"
508950 located pat p_pat
509− ListPat NoExt pats -> do
510− brackets $ velt (withSep comma (located' p_pat) pats)
511− TuplePat NoExt pats boxing -> do
512− let f =
951+ ListPat NoExtField pats ->
952+ brackets S $ sep commaDel (located' p_pat) pats
953+ TuplePat NoExtField pats boxing -> do
954+ let parens' =
513955 case boxing of
514− Boxed -> parens
515− Unboxed -> parensHash
516− f $ velt (withSep comma (located' p_pat) pats)
517− SumPat NoExt pat _ _ -> do
518− -- XXX I'm not sure about this one.
519− located pat p_pat
956+ Boxed -> parens S
957+ Unboxed -> parensHash S
958+ parens' $ sep commaDel (sitcc . located' p_pat) pats
959+ SumPat NoExtField pat tag arity ->
960+ p_unboxedSum S tag arity (located pat p_pat)
520961 ConPatIn pat details ->
521962 case details of
522963 PrefixCon xs -> sitcc $ do
523964 p_rdrName pat
524965 unless (null xs) $ do
525966 breakpoint
526− inci $ velt' (located' p_pat <$> xs)
967+ inci . sitcc $ sep breakpoint (sitcc . located' p_pat) xs
527968 RecCon (HsRecFields fields dotdot) -> do
528969 p_rdrName pat
529970 breakpoint
530971 let f = \case
531972 Nothing -> txt ".."
532973 Just x -> located x p_pat_hsRecField
533− inci . braces . velt . withSep comma f $ case dotdot of
534− Nothing -> Just <$> fields
535− Just n -> (Just <$> take n fields) ++ [Nothing]
536− InfixCon x y -> do
537− located x p_pat
538− space
539− p_rdrName pat
540− breakpoint
541− inci (located y p_pat)
974+ inci . braces N . sep commaDel f $
975+ case dotdot of
976+ Nothing -> Just <$> fields
977+ Just (L _ n) -> (Just <$> take n fields) ++ [Nothing]
978+ InfixCon l r -> do
979+ switchLayout [getLoc l, getLoc r] $ do
980+ located l p_pat
981+ breakpoint
982+ inci $ do
983+ p_rdrName pat
984+ space
985+ located r p_pat
542986 ConPatOut {} -> notImplemented "ConPatOut" -- presumably created by renamer?
543− ViewPat NoExt expr pat -> sitcc $ do
987+ ViewPat NoExtField expr pat -> sitcc $ do
544988 located expr p_hsExpr
545− txt " ->"
989+ space
990+ txt "->"
546991 breakpoint
547992 inci (located pat p_pat)
548− SplicePat NoExt splice -> p_hsSplice splice
549− LitPat NoExt p -> atom p
550− NPat NoExt v _ _ -> located v (atom . ol_val)
551− NPlusKPat NoExt n k _ _ _ -> sitcc $ do
993+ SplicePat NoExtField splice -> p_hsSplice splice
994+ LitPat NoExtField p -> atom p
995+ NPat NoExtField v _ _ -> located v (atom . ol_val)
996+ NPlusKPat NoExtField n k _ _ _ -> sitcc $ do
552997 p_rdrName n
553998 breakpoint
554999 inci $ do
555− txt "+ "
1000+ txt "+"
1001+ space
5561002 located k (atom . ol_val)
557− SigPat hswc pat -> do
1003+ SigPat NoExtField pat hswc -> do
5581004 located pat p_pat
5591005 p_typeAscription hswc
5601006 CoPat {} -> notImplemented "CoPat" -- apparently created at some later stage
561− XPat NoExt -> notImplemented "XPat"
1007+ XPat x -> noExtCon x
5621008
5631009p_pat_hsRecField :: HsRecField' (FieldOcc GhcPs) (LPat GhcPs) -> R ()
5641010p_pat_hsRecField HsRecField {..} = do
5651011 located hsRecFieldLbl $ \x ->
5661012 p_rdrName (rdrNameFieldOcc x)
5671013 unless hsRecPun $ do
568− txt " ="
1014+ space
1015+ equals
5691016 breakpoint
5701017 inci (located hsRecFieldArg p_pat)
5711018
1019+p_unboxedSum :: BracketStyle -> ConTag -> Arity -> R () -> R ()
1020+p_unboxedSum s tag arity m = do
1021+ let before = tag - 1
1022+ after = arity - before - 1
1023+ args = replicate before Nothing <> [Just m] <> replicate after Nothing
1024+ f x =
1025+ case x :: Maybe (R ()) of
1026+ Nothing ->
1027+ space
1028+ Just m' -> do
1029+ space
1030+ m'
1031+ space
1032+ parensHash s $ sep (txt "|") f args
1033+
5721034p_hsSplice :: HsSplice GhcPs -> R ()
5731035p_hsSplice = \case
574− HsTypedSplice NoExt deco _ expr -> p_hsSpliceTH True expr deco
575− HsUntypedSplice NoExt deco _ expr -> p_hsSpliceTH False expr deco
576− HsQuasiQuote NoExt _ quoterName srcSpan str -> do
1036+ HsTypedSplice NoExtField deco _ expr -> p_hsSpliceTH True expr deco
1037+ HsUntypedSplice NoExtField deco _ expr -> p_hsSpliceTH False expr deco
1038+ HsQuasiQuote NoExtField _ quoterName srcSpan str -> do
5771039 txt "["
5781040 p_rdrName (L srcSpan quoterName)
5791041 txt "|"
580− -- NOTE QuasiQuoters often rely on precise custom strings. We cannot do
581− -- any formatting here without potentially breaking someone's code.
1042+ -- QuasiQuoters often rely on precise custom strings. We cannot do any
1043+ -- formatting here without potentially breaking someone's code.
5821044 atom str
5831045 txt "|]"
5841046 HsSpliced {} -> notImplemented "HsSpliced"
585− XSplice {} -> notImplemented "XSplice"
1047+ HsSplicedT {} -> notImplemented "HsSplicedT"
1048+ XSplice x -> noExtCon x
5861049
587−p_hsSpliceTH
588− :: Bool -- ^ Typed splice?
589− -> LHsExpr GhcPs -- ^ Splice expression
590− -> SpliceDecoration -- ^ Splice decoration
591− -> R ()
1050+p_hsSpliceTH ::
1051+ -- | Typed splice?
1052+ Bool ->
1053+ -- | Splice expression
1054+ LHsExpr GhcPs ->
1055+ -- | Splice decoration
1056+ SpliceDecoration ->
1057+ R ()
5921058p_hsSpliceTH isTyped expr = \case
5931059 HasParens -> do
5941060 txt decoSymbol
595− parens (located expr (sitcc . p_hsExpr))
1061+ parens N (located expr (sitcc . p_hsExpr))
5961062 HasDollar -> do
5971063 txt decoSymbol
5981064 located expr (sitcc . p_hsExpr)
599− NoParens -> do
1065+ NoParens ->
6001066 located expr (sitcc . p_hsExpr)
6011067 where
6021068 decoSymbol = if isTyped then "$$" else "$"
6031069
6041070p_hsBracket :: HsBracket GhcPs -> R ()
6051071p_hsBracket = \case
606− ExpBr NoExt expr -> quote "e" (located expr p_hsExpr)
607− PatBr NoExt pat -> quote "p" (located pat p_pat)
608− DecBrL NoExt decls -> quote "d" (p_hsDecls decls)
609− DecBrG NoExt _ -> notImplemented "DecBrG" -- result of renamer
610− TypBr NoExt ty -> quote "t" (located ty p_hsType)
611− VarBr NoExt _ _ -> notImplemented "VarBr"
612− TExpBr NoExt expr -> do
1072+ ExpBr NoExtField expr -> do
1073+ anns <- getEnclosingAnns
1074+ let name = case anns of
1075+ AnnOpenEQ : _ -> ""
1076+ _ -> "e"
1077+ quote name (located expr p_hsExpr)
1078+ PatBr NoExtField pat -> located pat (quote "p" . p_pat)
1079+ DecBrL NoExtField decls -> quote "d" (p_hsDecls Free decls)
1080+ DecBrG NoExtField _ -> notImplemented "DecBrG" -- result of renamer
1081+ TypBr NoExtField ty -> quote "t" (located ty p_hsType)
1082+ VarBr NoExtField isSingleQuote name -> do
1083+ txt (bool "''" "'" isSingleQuote)
1084+ -- HACK As you can see we use 'noLoc' here to be able to pass name into
1085+ -- 'p_rdrName' since the latter expects a "located" thing. The problem
1086+ -- is that 'VarBr' doesn't provide us with location of the name. This in
1087+ -- turn makes it impossible to detect if there are parentheses around
1088+ -- it, etc. So we have to add parentheses manually assuming they are
1089+ -- necessary for all operators.
1090+ let isOperator =
1091+ all
1092+ (\i -> isPunctuation i || isSymbol i)
1093+ (showOutputable (rdrNameOcc name))
1094+ && not (doesNotNeedExtraParens name)
1095+ wrapper = if isOperator then parens N else id
1096+ wrapper $ p_rdrName (noLoc name)
1097+ TExpBr NoExtField expr -> do
6131098 txt "[||"
6141099 breakpoint'
6151100 located expr p_hsExpr
6161101 breakpoint'
6171102 txt "||]"
618− XBracket {} -> notImplemented "XBracket"
1103+ XBracket x -> noExtCon x
6191104 where
6201105 quote :: Text -> R () -> R ()
6211106 quote name body = do
@@ -623,23 +1108,86 @@ p_hsBracket = \case
6231108 txt name
6241109 txt "|"
6251110 breakpoint'
626− body
627− breakpoint'
628− txt "|]"
1111+ inci $ do
1112+ dontUseBraces body
1113+ breakpoint'
1114+ txt "|]"
1115+
1116+-- Print the source text of a string literal while indenting
1117+-- gaps correctly.
1118+
1119+p_stringLit :: String -> R ()
1120+p_stringLit src =
1121+ let s = splitGaps src
1122+ singleLine =
1123+ txt $ Text.pack (mconcat s)
1124+ multiLine =
1125+ sitcc $ sep breakpoint (txt . Text.pack) (backslashes s)
1126+ in vlayout singleLine multiLine
1127+ where
1128+ -- Split a string on gaps (backslash delimited whitespaces)
1129+ --
1130+ -- > splitGaps "bar\\ \\fo\\&o" == ["bar", "fo\\&o"]
1131+ splitGaps :: String -> [String]
1132+ splitGaps "" = []
1133+ splitGaps s =
1134+ let -- A backslash and a whitespace starts a "gap"
1135+ p (Just '\\', _, _) = True
1136+ p (_, '\\', Just c) | ghcSpace c = False
1137+ p _ = True
1138+ in case span p (zipPrevNext s) of
1139+ (l, r) ->
1140+ let -- drop the initial '\', any amount of 'ghcSpace', and another '\'
1141+ r' = drop 1 . dropWhile ghcSpace . drop 1 $ map orig r
1142+ in map orig l : splitGaps r'
1143+ -- GHC's definition of whitespaces in strings
1144+ -- See: https://gitlab.haskell.org/ghc/ghc/blob/86753475/compiler/parser/Lexer.x#L1653
1145+ ghcSpace :: Char -> Bool
1146+ ghcSpace c = c <= '\x7f' && is_space c
1147+ -- Add backslashes to the inner side of the strings
1148+ --
1149+ -- > backslashes ["a", "b", "c"] == ["a\\", "\\b\\", "\\c"]
1150+ backslashes :: [String] -> [String]
1151+ backslashes (x : y : xs) = (x ++ "\\") : backslashes (('\\' : y) : xs)
1152+ backslashes xs = xs
1153+ -- Attaches previous and next items to each list element
1154+ zipPrevNext :: [a] -> [(Maybe a, a, Maybe a)]
1155+ zipPrevNext xs =
1156+ let z =
1157+ zip
1158+ (zip (Nothing : map Just xs) xs)
1159+ (map Just (tail xs) ++ repeat Nothing)
1160+ in map (\((p, x), n) -> (p, x, n)) z
1161+ orig (_, x, _) = x
6291162
6301163----------------------------------------------------------------------------
6311164-- Helpers
6321165
633−getGRHSSpan :: GRHS GhcPs (LHsExpr GhcPs) -> SrcSpan
634−getGRHSSpan (GRHS NoExt _ body) = getLoc body
635−getGRHSSpan (XGRHS NoExt) = notImplemented "XGRHS"
1166+-- | Return the wrapping function controlling the use of braces according to
1167+-- the current layout.
1168+layoutToBraces :: Layout -> R () -> R ()
1169+layoutToBraces = \case
1170+ SingleLine -> useBraces
1171+ MultiLine -> id
1172+
1173+-- | Append each element in both lists with semigroups. If one list is shorter
1174+-- than the other, return the rest of the longer list unchanged.
1175+liftAppend :: Semigroup a => [a] -> [a] -> [a]
1176+liftAppend [] [] = []
1177+liftAppend [] (y : ys) = y : ys
1178+liftAppend (x : xs) [] = x : xs
1179+liftAppend (x : xs) (y : ys) = x <> y : liftAppend xs ys
1180+
1181+getGRHSSpan :: GRHS GhcPs (Located body) -> SrcSpan
1182+getGRHSSpan (GRHS NoExtField guards body) =
1183+ combineSrcSpans' $ getLoc body :| map getLoc guards
1184+getGRHSSpan (XGRHS x) = noExtCon x
6361185
6371186-- | Place a thing that may have a hanging form. This function handles how
6381187-- to separate it from preceding expressions and whether to bump indentation
6391188-- depending on what sort of expression we have.
640−
6411189placeHanging :: Placement -> R () -> R ()
642−placeHanging placement m = do
1190+placeHanging placement m =
6431191 case placement of
6441192 Hanging -> do
6451193 space
@@ -650,26 +1198,165 @@ placeHanging placement m = do
6501198
6511199-- | Check if given block contains single expression which has a hanging
6521200-- form.
1201+blockPlacement ::
1202+ (body -> Placement) ->
1203+ [LGRHS GhcPs (Located body)] ->
1204+ Placement
1205+blockPlacement placer [L _ (GRHS NoExtField _ (L _ x))] = placer x
1206+blockPlacement _ _ = Normal
6531207
654−blockPlacement :: [LGRHS GhcPs (LHsExpr GhcPs)] -> Placement
655−blockPlacement [(L _ (GRHS NoExt _ (L _ e)))] = exprPlacement e
656−blockPlacement _ = Normal
1208+-- | Check if given command has a hanging form.
1209+cmdPlacement :: HsCmd GhcPs -> Placement
1210+cmdPlacement = \case
1211+ HsCmdLam NoExtField _ -> Hanging
1212+ HsCmdCase NoExtField _ _ -> Hanging
1213+ HsCmdDo NoExtField _ -> Hanging
1214+ _ -> Normal
6571215
658−-- | Check if given expression has hinging a form.
1216+cmdTopPlacement :: HsCmdTop GhcPs -> Placement
1217+cmdTopPlacement = \case
1218+ HsCmdTop NoExtField (L _ x) -> cmdPlacement x
1219+ XCmdTop x -> noExtCon x
6591220
1221+-- | Check if given expression has a hanging form.
6601222exprPlacement :: HsExpr GhcPs -> Placement
6611223exprPlacement = \case
662− HsLam NoExt _ -> Hanging
663− HsLamCase NoExt _ -> Hanging
664− HsCase NoExt _ _ -> Hanging
665− HsDo NoExt DoExpr _ -> Hanging
666− HsDo NoExt MDoExpr _ -> Hanging
667− RecordCon NoExt _ _ -> Hanging
1224+ -- Only hang lambdas with single line parameter lists
1225+ HsLam NoExtField mg -> case mg of
1226+ MG _ (L _ [L _ (Match NoExtField _ (x : xs) _)]) _
1227+ | isOneLineSpan (combineSrcSpans' $ fmap getLoc (x :| xs)) ->
1228+ Hanging
1229+ _ -> Normal
1230+ HsLamCase NoExtField _ -> Hanging
1231+ HsCase NoExtField _ _ -> Hanging
1232+ HsDo NoExtField DoExpr _ -> Hanging
1233+ HsDo NoExtField MDoExpr _ -> Hanging
1234+ OpApp NoExtField _ op y ->
1235+ case (fmap getOpNameStr . getOpName . unLoc) op of
1236+ Just "$" -> exprPlacement (unLoc y)
1237+ _ -> Normal
1238+ HsApp NoExtField _ y -> exprPlacement (unLoc y)
1239+ HsProc NoExtField p _ ->
1240+ -- Indentation breaks if pattern is longer than one line and left
1241+ -- hanging. Consequently, only apply hanging when it is safe.
1242+ if isOneLineSpan (getLoc p)
1243+ then Hanging
1244+ else Normal
6681245 _ -> Normal
6691246
670−withGuards :: [LGRHS GhcPs (LHsExpr GhcPs)] -> Bool
1247+withGuards :: [LGRHS GhcPs (Located body)] -> Bool
6711248withGuards = any (checkOne . unLoc)
6721249 where
673− checkOne :: GRHS GhcPs (LHsExpr GhcPs) -> Bool
674− checkOne (GRHS NoExt [] _) = False
1250+ checkOne :: GRHS GhcPs (Located body) -> Bool
1251+ checkOne (GRHS NoExtField [] _) = False
6751252 checkOne _ = True
1253+
1254+exprOpTree :: LHsExpr GhcPs -> OpTree (LHsExpr GhcPs) (LHsExpr GhcPs)
1255+exprOpTree (L _ (OpApp NoExtField x op y)) = OpBranch (exprOpTree x) op (exprOpTree y)
1256+exprOpTree n = OpNode n
1257+
1258+getOpName :: HsExpr GhcPs -> Maybe RdrName
1259+getOpName = \case
1260+ HsVar NoExtField (L _ a) -> Just a
1261+ _ -> Nothing
1262+
1263+getOpNameStr :: RdrName -> String
1264+getOpNameStr = occNameString . rdrNameOcc
1265+
1266+p_exprOpTree ::
1267+ -- | Bracket style to use
1268+ BracketStyle ->
1269+ OpTree (LHsExpr GhcPs) (LHsExpr GhcPs) ->
1270+ R ()
1271+p_exprOpTree s (OpNode x) = located x (p_hsExpr' s)
1272+p_exprOpTree s (OpBranch x op y) = do
1273+ -- If the beginning of the first argument and the second argument are on
1274+ -- the same line, and the second argument has a hanging form, use hanging
1275+ -- placement.
1276+ let placement =
1277+ if isOneLineSpan
1278+ (mkSrcSpan (srcSpanStart (opTreeLoc x)) (srcSpanStart (opTreeLoc y)))
1279+ then case y of
1280+ OpNode (L _ n) -> exprPlacement n
1281+ _ -> Normal
1282+ else Normal
1283+ -- Distinguish holes used in infix notation.
1284+ -- eg. '1 _foo 2' and '1 `_foo` 2'
1285+ opWrapper = case unLoc op of
1286+ HsUnboundVar NoExtField _ -> backticks
1287+ _ -> id
1288+ layout <- getLayout
1289+ let ub = case layout of
1290+ SingleLine -> useBraces
1291+ MultiLine -> case placement of
1292+ Hanging -> useBraces
1293+ Normal -> dontUseBraces
1294+ opNameStr = (fmap getOpNameStr . getOpName . unLoc) op
1295+ gotDollar = opNameStr == Just "$"
1296+ gotColon = opNameStr == Just ":"
1297+ gotRecordDot = isRecordDot (unLoc op) (opTreeLoc y)
1298+ lhs =
1299+ switchLayout [opTreeLoc x] $
1300+ p_exprOpTree s x
1301+ p_op = located op (opWrapper . p_hsExpr)
1302+ p_y = switchLayout [opTreeLoc y] (p_exprOpTree N y)
1303+ isSection = case (opTreeLoc x, getLoc op) of
1304+ (RealSrcSpan treeSpan, RealSrcSpan opSpan) ->
1305+ srcSpanEndCol treeSpan /= srcSpanStartCol opSpan
1306+ _ -> False
1307+ isDoBlock = \case
1308+ OpNode (L _ HsDo {}) -> True
1309+ _ -> False
1310+ useRecordDot' <- useRecordDot
1311+ if
1312+ | gotColon -> do
1313+ lhs
1314+ space
1315+ p_op
1316+ case placement of
1317+ Hanging -> do
1318+ space
1319+ p_y
1320+ Normal -> do
1321+ breakpoint
1322+ inciIf (isDoBlock y) p_y
1323+ | gotDollar
1324+ && isOneLineSpan (opTreeLoc x)
1325+ && placement == Normal -> do
1326+ useBraces lhs
1327+ space
1328+ p_op
1329+ breakpoint
1330+ inci p_y
1331+ | useRecordDot' && gotRecordDot -> do
1332+ lhs
1333+ when isSection space
1334+ p_op
1335+ p_y
1336+ | otherwise -> do
1337+ ub lhs
1338+ placeHanging placement $ do
1339+ p_op
1340+ space
1341+ p_y
1342+
1343+-- | Return 'True' if given expression is a record-dot operator expression.
1344+isRecordDot ::
1345+ -- | Operator expression
1346+ HsExpr GhcPs ->
1347+ -- | Span of the expression on the right-hand side of the operator
1348+ SrcSpan ->
1349+ Bool
1350+isRecordDot op (RealSrcSpan ySpan) = case op of
1351+ HsVar NoExtField (L (RealSrcSpan opSpan) opName) ->
1352+ (getOpNameStr opName == ".") && (srcSpanEndCol opSpan == srcSpanStartCol ySpan)
1353+ _ -> False
1354+isRecordDot _ _ = False
1355+
1356+-- | Get annotations for the enclosing element.
1357+getEnclosingAnns :: R [AnnKeywordId]
1358+getEnclosingAnns = do
1359+ e <- getEnclosingSpan (const True)
1360+ case e of
1361+ Nothing -> return []
1362+ Just e' -> getAnns (RealSrcSpan e')