{-# LANGUAGE CPP #-}
module GHC.SourceGen.Pat.Internal where

import GHC.Hs.Pat (Pat(..))
#if MIN_VERSION_ghc(9,0,0)
import GHC.Hs.Type (HsConDetails(..))
import GHC.Types.SrcLoc (unLoc)
#else
import GHC.Hs.Type (HsConDetails(..))
import SrcLoc (unLoc)
#endif

import GHC.SourceGen.Lit.Internal (litNeedsParen, overLitNeedsParen)
import GHC.SourceGen.Syntax.Internal

-- Note: GHC>=8.6 inserts parentheses automatically when pretty-printing patterns.
-- When we stop supporting lower versions, we may be able to simplify this.
parenthesize :: Pat' -> Pat'
parenthesize :: Pat' -> Pat'
parenthesize Pat'
p
    | Pat' -> Bool
needsPar Pat'
p = Pat' -> Pat'
parPat Pat'
p
    | Bool
otherwise = Pat'
p


needsPar :: Pat' -> Bool
#if MIN_VERSION_ghc(8,6,0)
needsPar :: Pat' -> Bool
needsPar (LitPat XLitPat GhcPs
_ HsLit GhcPs
l) = HsLit GhcPs -> Bool
litNeedsParen HsLit GhcPs
l
needsPar (NPat XNPat GhcPs
_ Located (HsOverLit GhcPs)
l Maybe (SyntaxExpr GhcPs)
_ SyntaxExpr GhcPs
_) = HsOverLit GhcPs -> Bool
overLitNeedsParen (HsOverLit GhcPs -> Bool) -> HsOverLit GhcPs -> Bool
forall a b. (a -> b) -> a -> b
$ Located (HsOverLit GhcPs)
-> SrcSpanLess (Located (HsOverLit GhcPs))
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc Located (HsOverLit GhcPs)
l
#else
needsPar (LitPat l) = litNeedsParen l
needsPar (NPat l _ _ _) = overLitNeedsParen $ unLoc l
#endif
#if MIN_VERSION_ghc(9,2,0)
needsPar (ConPat _ _ (PrefixCon _ xs)) = not $ null xs
#elif MIN_VERSION_ghc(9,0,0)
needsPar (ConPat _ _ (PrefixCon xs)) = not $ null xs
#else
needsPar (ConPatIn Located (IdP GhcPs)
_ (PrefixCon [LPat GhcPs]
xs)) = Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ [Located Pat'] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [LPat GhcPs]
[Located Pat']
xs
#endif
#if MIN_VERSION_ghc(9,0,0)
needsPar (ConPat _ _ (InfixCon _ _)) = True
#else
needsPar (ConPatIn Located (IdP GhcPs)
_ (InfixCon LPat GhcPs
_ LPat GhcPs
_)) = Bool
True
needsPar ConPatOut{} = Bool
True
#endif
#if MIN_VERSION_ghc(8,6,0)
needsPar SigPat{} = Bool
True
#else
needsPar SigPatIn{} = True
needsPar SigPatOut{} = True
#endif
needsPar Pat'
_ = Bool
False

parPat :: Pat' -> Pat'
parPat :: Pat' -> Pat'
parPat = (NoExtField -> Located Pat' -> Pat') -> Located Pat' -> Pat'
forall a. (NoExtField -> a) -> a
withEpAnnNotUsed NoExtField -> Located Pat' -> Pat'
forall p. XParPat p -> LPat p -> Pat p
ParPat (Located Pat' -> Pat') -> (Pat' -> Located Pat') -> Pat' -> Pat'
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Pat' -> LPat GhcPs
Pat' -> Located Pat'
builtPat