{- |
Module      : LHMake.Control.Superimposition
Description : Superimposition of Haskell and Happy ASTs.
Copyright   : (c) Hangil Kim, 2026
                  Kairon Johnson, 2026
                  Leonidas Sallos, 2026
                  Oscar Abelanet, 2026
License     : MIT
Maintainer  : kimhang@oregonstate.edu
Stability   : experimental

This module provides a superimposition operator @'(-->)'@ on Haskell and Happy abstract syntax trees.
The following example illustrates its use on two Haskell files.

> -- A.hs
> module LH.Feature.A.Basic where
>
> data Expr = Lit Int
> 
> eval :: Expr -> Int
> eval (Lit n) = n
> 
> -- B.hs
> module LH.Feature.B.Basic where
>
> data Expr = Add Expr Expr
> 
> eval :: Expr -> Int
> eval (Add e1 e2) = eval e1 + eval e2
> 
> -- B.hs --> A.hs
> module LH.Feature.BA.Basic where
>
> data Expr = Lit Int | Add Expr Expr
> 
> eval :: Expr -> Int
> eval (Lit n) = n
> eval (Add e1 e2) = eval e1 + eval e2
-}
{-# LANGUAGE FlexibleContexts, FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module LHMake.Control.Superimposition (
    -- * Superimposition
    Superimposable (..), Identifiable (..),
    -- ** Parsing
    parseMode,
    -- ** Identifiers
    PragmaId (..), DeclId (..), DirectiveId (..),
    -- ** Flattening lists
    flattenPragmas, flattenDecls, flattenTokens,
    -- ** Token precedences
    precs, groupPrecs
    ) where

import Control.Applicative ((<|>))
import Data.Char           (isSpace)
import Data.Functor        (void)
import Data.List           (nub, partition)
import Data.Map            (Map)
import Data.Maybe          (catMaybes, fromMaybe)

import qualified Data.Map as Map

import qualified Happy.Frontend.AbsSyn        as Y
import qualified Happy.Frontend.PrettyGrammar as Y
import qualified Language.Haskell.Exts        as H

import LHMake.Data.Error (LHsMakeError)

infixl 6 -->

-- | A 'Superimposable' type allows merging of two values \(L\) and \(R\),
--   which range over anything from Haskell modules to Happy productions.
--   \(L\) and \(R\) are assumed to have the same 'Identifier', as defined by the 'Identifiable' typeclass.
--
--   By default, \(L\) overrides the contents of \(R\).
--   Specific instances replace this behavior with a merging semantics.
class Superimposable a where
    -- | Superimposes two values.
    --   
    --   Note that superimposition can fail for various reasons, such as when differing module names are encountered.
    (-->) :: a -> a -> LHsMakeError a
    a
x --> a
_ = a -> LHsMakeError a
forall a b. b -> Either a b
Right a
x

-- | An 'Identifiable' type @a@ has an 'Identifier', which is a value of some type identifying a value of type @a@.
--   'Identifier' is defined on a case-by-case basis, since a type @a@ might need a different identification mechanism than another type @b@.
--   The 'identify' function then takes a value and produces its 'Identifier'.
--   This allows us to decide whether two values can be merged in a general way.
class Identifiable a where
    type Identifier a
    -- | Identifies a value.
    --   
    --   Note that identification can fail for various reasons, 
    --   most notably when superimposition has not been defined for a 
    --   given language construct out of a lack of necessity.
    identify :: a -> LHsMakeError (Identifier a)

-- | Lists are superimposed element by element. 
--   Elements with the same identifier are superimposed, 
--   and elements that only the right list has are added at the end.
instance (Identifiable a, Eq (Identifier a), Superimposable a) => Superimposable [a] where
    [a]
xs --> :: [a] -> [a] -> LHsMakeError [a]
--> [a]
ys = do
        [Identifier a]
xids   <- (a -> Either String (Identifier a))
-> [a] -> Either String [Identifier a]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse a -> Either String (Identifier a)
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [a]
xs
        [Identifier a]
yids   <- (a -> Either String (Identifier a))
-> [a] -> Either String [Identifier a]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse a -> Either String (Identifier a)
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [a]
ys
        [a]
merged <- [Either String a] -> LHsMakeError [a]
forall (t :: * -> *) (m :: * -> *) a.
(Traversable t, Monad m) =>
t (m a) -> m (t a)
forall (m :: * -> *) a. Monad m => [m a] -> m [a]
sequence [Either String a
-> (a -> Either String a) -> Maybe a -> Either String a
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (a -> Either String a
forall a b. b -> Either a b
Right a
x) (a
x a -> a -> Either String a
forall a. Superimposable a => a -> a -> LHsMakeError a
-->) (Identifier a -> [(Identifier a, a)] -> Maybe a
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Identifier a
xid ([Identifier a] -> [a] -> [(Identifier a, a)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Identifier a]
yids [a]
ys)) | (a
x, Identifier a
xid) <- [a] -> [Identifier a] -> [(a, Identifier a)]
forall a b. [a] -> [b] -> [(a, b)]
zip [a]
xs [Identifier a]
xids]
        let added :: [a]
added = [a
y | (a
y, Identifier a
yid) <- [a] -> [Identifier a] -> [(a, Identifier a)]
forall a b. [a] -> [b] -> [(a, b)]
zip [a]
ys [Identifier a]
yids, Identifier a
yid Identifier a -> [Identifier a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Identifier a]
xids]
        [a] -> LHsMakeError [a]
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return ([a]
merged [a] -> [a] -> [a]
forall a. [a] -> [a] -> [a]
++ [a]
added)

-------------------------------------------------------------------------------
-- Haskell
-------------------------------------------------------------------------------

-- | 'H.defaultParseMode' but with 'H.fixities' set to 'Nothing'.
--
--   Operator precedence resolution is disabled since superimposition does 
--   not merge expressions (e.g., RHSs of function clauses).
parseMode :: H.ParseMode
parseMode :: ParseMode
parseMode = ParseMode
H.defaultParseMode { H.fixities = Nothing }

-- All Haskell syntax trees here carry the annotation (), since the source
-- positions the parser records would otherwise make equal values compare as different.

instance Superimposable (H.CName ())
instance Superimposable (H.QualConDecl ())
instance Superimposable (H.InstRule ())
instance Superimposable (H.Match ())

instance Identifiable (H.CName ()) where
    type Identifier (H.CName ()) = H.Name ()
    identify :: CName () -> LHsMakeError (Identifier (CName ()))
identify (H.VarName ()
_ Name ()
name) = Name () -> Either String (Name ())
forall a b. b -> Either a b
Right Name ()
name
    identify (H.ConName ()
_ Name ()
name) = Name () -> Either String (Name ())
forall a b. b -> Either a b
Right Name ()
name

-- | A constructor is identified by its name.
instance Identifiable (H.QualConDecl ()) where
    type Identifier (H.QualConDecl ()) = H.Name ()
    identify :: QualConDecl () -> LHsMakeError (Identifier (QualConDecl ()))
identify (H.QualConDecl ()
_ Maybe [TyVarBind ()]
_ Maybe (Context ())
_ ConDecl ()
con) = case ConDecl ()
con of
        H.ConDecl ()
_ Name ()
name [Type ()]
_        -> Name () -> Either String (Name ())
forall a b. b -> Either a b
Right Name ()
name
        H.InfixConDecl ()
_ Type ()
_ Name ()
name Type ()
_ -> Name () -> Either String (Name ())
forall a b. b -> Either a b
Right Name ()
name
        H.RecDecl ()
_ Name ()
name [FieldDecl ()]
_        -> Name () -> Either String (Name ())
forall a b. b -> Either a b
Right Name ()
name

instance Identifiable (H.InstRule ()) where
    type Identifier (H.InstRule ()) = H.InstRule ()
    identify :: InstRule () -> LHsMakeError (Identifier (InstRule ()))
identify = InstRule () -> LHsMakeError (InstRule ())
InstRule () -> LHsMakeError (Identifier (InstRule ()))
forall a b. b -> Either a b
Right

-- | Splits a function clause into its name and patterns.
--   An infix definition such as @x ++ y = e@ is treated like @(++) x y = e@.
clause :: H.Match l -> (H.Name l, [H.Pat l])
clause :: forall l. Match l -> (Name l, [Pat l])
clause (H.Match l
_ Name l
name [Pat l]
pats Rhs l
_ Maybe (Binds l)
_)          = (Name l
name, [Pat l]
pats)
clause (H.InfixMatch l
_ Pat l
pat Name l
name [Pat l]
pats Rhs l
_ Maybe (Binds l)
_) = (Name l
name, Pat l
pat Pat l -> [Pat l] -> [Pat l]
forall a. a -> [a] -> [a]
: [Pat l]
pats)

-- | A function is identified by its patterns.
instance Identifiable (H.Match ()) where
    type Identifier (H.Match ()) = [H.Pat ()]
    identify :: Match () -> LHsMakeError (Identifier (Match ()))
identify = [Pat ()] -> Either String [Pat ()]
forall a b. b -> Either a b
Right ([Pat ()] -> Either String [Pat ()])
-> (Match () -> [Pat ()]) -> Match () -> Either String [Pat ()]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Name (), [Pat ()]) -> [Pat ()]
forall a b. (a, b) -> b
snd ((Name (), [Pat ()]) -> [Pat ()])
-> (Match () -> (Name (), [Pat ()])) -> Match () -> [Pat ()]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Match () -> (Name (), [Pat ()])
forall l. Match l -> (Name l, [Pat l])
clause

-- Pragmas --------------------------------------------------------------------

-- | Identifiers for module pragmas.
data PragmaId
    = Extension (H.Name ())             -- ^ A @LANGUAGE@ pragma.
    | Options   (Maybe H.Tool) [String] -- ^ An @OPTIONS@ pragma, such as @OPTIONS_GHC@.
    | Annotated (H.ModulePragma ())     -- ^ An @ANN@ pragma, identified by its contents.
    deriving PragmaId -> PragmaId -> Bool
(PragmaId -> PragmaId -> Bool)
-> (PragmaId -> PragmaId -> Bool) -> Eq PragmaId
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PragmaId -> PragmaId -> Bool
== :: PragmaId -> PragmaId -> Bool
$c/= :: PragmaId -> PragmaId -> Bool
/= :: PragmaId -> PragmaId -> Bool
Eq

-- | Splits a @LANGUAGE@ pragma holding several extensions into one pragma per extension.
--
--   For instance, @{-# LANGUAGE A, B #-}@ is flattened into @{-# LANGUAGE A #-}@ and @{-# LANGUAGE B #-}@.
--   All other pragmas are left as is.
flattenPragmas :: H.ModulePragma () -> [H.ModulePragma ()]
flattenPragmas :: ModulePragma () -> [ModulePragma ()]
flattenPragmas (H.LanguagePragma ()
_ [Name ()]
names) = [() -> [Name ()] -> ModulePragma ()
forall l. l -> [Name l] -> ModulePragma l
H.LanguagePragma () [Name ()
name] | Name ()
name <- [Name ()]
names]
flattenPragmas ModulePragma ()
pragma                     = [ModulePragma ()
pragma]

instance Superimposable (H.ModulePragma ())

instance Identifiable (H.ModulePragma ()) where
    type Identifier (H.ModulePragma ()) = PragmaId
    identify :: ModulePragma () -> LHsMakeError (Identifier (ModulePragma ()))
identify (H.LanguagePragma ()
_ [Name ()
name])  = PragmaId -> Either String PragmaId
forall a b. b -> Either a b
Right (Name () -> PragmaId
Extension Name ()
name)
    identify (H.LanguagePragma ()
_ [Name ()]
_)       = String -> Either String PragmaId
forall a b. a -> Either a b
Left String
"Cannot merge a LANGUAGE pragma that holds several extensions"
    identify (H.OptionsPragma ()
_ Maybe Tool
tool String
opt) = PragmaId -> Either String PragmaId
forall a b. b -> Either a b
Right (Maybe Tool -> [String] -> PragmaId
Options Maybe Tool
tool (String -> [String]
words String
opt))
    identify pragma :: ModulePragma ()
pragma@(H.AnnModulePragma ()
_ Annotation ()
_) = PragmaId -> Either String PragmaId
forall a b. b -> Either a b
Right (ModulePragma () -> PragmaId
Annotated ModulePragma ()
pragma)

-- Modules --------------------------------------------------------------------

-- | Splits a declaration holding several names into one declaration per name.
--   Variable bindings (such as @x = e@) are also rewritten as function bindings, since they get parsed as a pattern binding.
--
--   For instance, the Haskell type signature @f g :: A@ is flattened into @f :: A@ and @g :: A@.
--
--   Note that pragmas attached to declarations (such as @WARNING@) are dropped by 'flattenDecls'.
flattenDecls :: H.Decl () -> [H.Decl ()]
flattenDecls :: Decl () -> [Decl ()]
flattenDecls (H.TypeSig ()
_ [Name ()]
names Type ()
ty)         = [() -> [Name ()] -> Type () -> Decl ()
forall l. l -> [Name l] -> Type l -> Decl l
H.TypeSig () [Name ()
name] Type ()
ty | Name ()
name <- [Name ()]
names]
flattenDecls (H.InfixDecl ()
_ Assoc ()
assoc Maybe Int
prec [Op ()]
ops) = [() -> Assoc () -> Maybe Int -> [Op ()] -> Decl ()
forall l. l -> Assoc l -> Maybe Int -> [Op l] -> Decl l
H.InfixDecl () Assoc ()
assoc Maybe Int
prec [Op ()
op] | Op ()
op <- [Op ()]
ops]
flattenDecls (H.PatBind ()
_ (H.PVar ()
_ Name ()
name) Rhs ()
rhs Maybe (Binds ())
wheres)
    = [() -> [Match ()] -> Decl ()
forall l. l -> [Match l] -> Decl l
H.FunBind () [() -> Name () -> [Pat ()] -> Rhs () -> Maybe (Binds ()) -> Match ()
forall l.
l -> Name l -> [Pat l] -> Rhs l -> Maybe (Binds l) -> Match l
H.Match () Name ()
name [] Rhs ()
rhs Maybe (Binds ())
wheres]]
flattenDecls (H.InstDecl ()
_ Maybe (Overlap ())
overlap InstRule ()
rule Maybe [InstDecl ()]
decls)
    = [()
-> Maybe (Overlap ())
-> InstRule ()
-> Maybe [InstDecl ()]
-> Decl ()
forall l.
l
-> Maybe (Overlap l) -> InstRule l -> Maybe [InstDecl l] -> Decl l
H.InstDecl () Maybe (Overlap ())
overlap InstRule ()
rule (([InstDecl ()] -> [InstDecl ()])
-> Maybe [InstDecl ()] -> Maybe [InstDecl ()]
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((InstDecl () -> [InstDecl ()]) -> [InstDecl ()] -> [InstDecl ()]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap InstDecl () -> [InstDecl ()]
flattenInstDecl) Maybe [InstDecl ()]
decls)]
flattenDecls H.InlineSig {}        = []
flattenDecls H.InlineConlikeSig {} = []
flattenDecls H.SpecSig {}          = []
flattenDecls H.SpecInlineSig {}    = []
flattenDecls H.InstSig {}          = []
flattenDecls H.RulePragmaDecl {}   = []
flattenDecls H.DeprPragmaDecl {}   = []
flattenDecls H.WarnPragmaDecl {}   = []
flattenDecls H.AnnPragma {}        = []
flattenDecls H.MinimalPragma {}    = []
flattenDecls Decl ()
decl = [Decl ()
decl]

-- | Flattens the declarations inside of an instance declaration.
flattenInstDecl :: H.InstDecl () -> [H.InstDecl ()]
flattenInstDecl :: InstDecl () -> [InstDecl ()]
flattenInstDecl (H.InsDecl ()
_ Decl ()
decl) = (Decl () -> InstDecl ()) -> [Decl ()] -> [InstDecl ()]
forall a b. (a -> b) -> [a] -> [b]
map (() -> Decl () -> InstDecl ()
forall l. l -> Decl l -> InstDecl l
H.InsDecl ()) (Decl () -> [Decl ()]
flattenDecls Decl ()
decl)
flattenInstDecl InstDecl ()
decl               = [InstDecl ()
decl]

-- | To superimpose two Haskell modules, they must have the same name.
--   Then, their pragmas, exports, and imports are merged.
--   Pragmas and declarations are flattened before they are merged. See 'flattenPragmas' and 'flattenDecls'. 
instance Superimposable (H.Module ()) where
    H.Module ()
_ Maybe (ModuleHead ())
head1 [ModulePragma ()]
pragmas1 [ImportDecl ()]
imps1 [Decl ()]
decls1 --> :: Module () -> Module () -> LHsMakeError (Module ())
--> H.Module ()
_ Maybe (ModuleHead ())
head2 [ModulePragma ()]
pragmas2 [ImportDecl ()]
imps2 [Decl ()]
decls2 = do
        Maybe (ModuleHead ())
hd      <- case (Maybe (ModuleHead ())
head1, Maybe (ModuleHead ())
head2) of
            (Just ModuleHead ()
h1, Just ModuleHead ()
h2) -> (ModuleHead () -> Maybe (ModuleHead ()))
-> Either String (ModuleHead ())
-> Either String (Maybe (ModuleHead ()))
forall a b. (a -> b) -> Either String a -> Either String b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ModuleHead () -> Maybe (ModuleHead ())
forall a. a -> Maybe a
Just (ModuleHead ()
h1 ModuleHead () -> ModuleHead () -> Either String (ModuleHead ())
forall a. Superimposable a => a -> a -> LHsMakeError a
--> ModuleHead ()
h2)
            (Maybe (ModuleHead ())
Nothing, Maybe (ModuleHead ())
Nothing) -> Maybe (ModuleHead ()) -> Either String (Maybe (ModuleHead ()))
forall a b. b -> Either a b
Right Maybe (ModuleHead ())
forall a. Maybe a
Nothing
            (Maybe (ModuleHead ()), Maybe (ModuleHead ()))
_                  -> String -> Either String (Maybe (ModuleHead ()))
forall a b. a -> Either a b
Left String
"Cannot merge a module that has a header with one that does not"
        [ModulePragma ()]
pragmas <- (ModulePragma () -> [ModulePragma ()])
-> [ModulePragma ()] -> [ModulePragma ()]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ModulePragma () -> [ModulePragma ()]
flattenPragmas [ModulePragma ()]
pragmas1 [ModulePragma ()]
-> [ModulePragma ()] -> LHsMakeError [ModulePragma ()]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> (ModulePragma () -> [ModulePragma ()])
-> [ModulePragma ()] -> [ModulePragma ()]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ModulePragma () -> [ModulePragma ()]
flattenPragmas [ModulePragma ()]
pragmas2
        [ImportDecl ()]
imps    <- [ImportDecl ()]
imps1 [ImportDecl ()] -> [ImportDecl ()] -> LHsMakeError [ImportDecl ()]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [ImportDecl ()]
imps2
        [Decl ()]
decls   <- (Decl () -> [Decl ()]) -> [Decl ()] -> [Decl ()]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Decl () -> [Decl ()]
flattenDecls [Decl ()]
decls1 [Decl ()] -> [Decl ()] -> LHsMakeError [Decl ()]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> (Decl () -> [Decl ()]) -> [Decl ()] -> [Decl ()]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Decl () -> [Decl ()]
flattenDecls [Decl ()]
decls2
        Module () -> LHsMakeError (Module ())
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (()
-> Maybe (ModuleHead ())
-> [ModulePragma ()]
-> [ImportDecl ()]
-> [Decl ()]
-> Module ()
forall l.
l
-> Maybe (ModuleHead l)
-> [ModulePragma l]
-> [ImportDecl l]
-> [Decl l]
-> Module l
H.Module () Maybe (ModuleHead ())
hd [ModulePragma ()]
pragmas [ImportDecl ()]
imps [Decl ()]
decls)
    Module ()
_ --> Module ()
_ = String -> LHsMakeError (Module ())
forall a b. a -> Either a b
Left String
"Cannot merge modules that are not plain Haskell modules"

-- | A module header holds the module name and its exports.
--   The names must be the same, and then the exports are merged.
instance Superimposable (H.ModuleHead ()) where
    H.ModuleHead ()
_ ModuleName ()
mod1 Maybe (WarningText ())
warn1 Maybe (ExportSpecList ())
exps1 --> :: ModuleHead () -> ModuleHead () -> Either String (ModuleHead ())
--> H.ModuleHead ()
_ ModuleName ()
mod2 Maybe (WarningText ())
_ Maybe (ExportSpecList ())
exps2
        | ModuleName ()
mod1 ModuleName () -> ModuleName () -> Bool
forall a. Eq a => a -> a -> Bool
== ModuleName ()
mod2 = do
            Maybe (ExportSpecList ())
exps <- Maybe (Either String (ExportSpecList ()))
-> Either String (Maybe (ExportSpecList ()))
forall (t :: * -> *) (f :: * -> *) a.
(Traversable t, Applicative f) =>
t (f a) -> f (t a)
forall (f :: * -> *) a. Applicative f => Maybe (f a) -> f (Maybe a)
sequenceA ((ExportSpecList ()
 -> ExportSpecList () -> Either String (ExportSpecList ()))
-> Maybe (ExportSpecList ())
-> Maybe (ExportSpecList ())
-> Maybe (Either String (ExportSpecList ()))
forall a b c. (a -> b -> c) -> Maybe a -> Maybe b -> Maybe c
forall (f :: * -> *) a b c.
Applicative f =>
(a -> b -> c) -> f a -> f b -> f c
liftA2 ExportSpecList ()
-> ExportSpecList () -> Either String (ExportSpecList ())
forall a. Superimposable a => a -> a -> LHsMakeError a
(-->) Maybe (ExportSpecList ())
exps1 Maybe (ExportSpecList ())
exps2)
            ModuleHead () -> Either String (ModuleHead ())
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (()
-> ModuleName ()
-> Maybe (WarningText ())
-> Maybe (ExportSpecList ())
-> ModuleHead ()
forall l.
l
-> ModuleName l
-> Maybe (WarningText l)
-> Maybe (ExportSpecList l)
-> ModuleHead l
H.ModuleHead () ModuleName ()
mod1 Maybe (WarningText ())
warn1 Maybe (ExportSpecList ())
exps)
        | Bool
otherwise = String -> Either String (ModuleHead ())
forall a b. a -> Either a b
Left (String
"Cannot merge differing modules: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ ModuleName () -> String
forall a. Pretty a => a -> String
H.prettyPrint ModuleName ()
mod1 String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" and " String -> String -> String
forall a. [a] -> [a] -> [a]
++ ModuleName () -> String
forall a. Pretty a => a -> String
H.prettyPrint ModuleName ()
mod2)

-- Exports --------------------------------------------------------------------

instance Superimposable (H.ExportSpecList ()) where
    H.ExportSpecList ()
_ [ExportSpec ()]
xs --> :: ExportSpecList ()
-> ExportSpecList () -> Either String (ExportSpecList ())
--> H.ExportSpecList ()
_ [ExportSpec ()]
ys = ([ExportSpec ()] -> ExportSpecList ())
-> Either String [ExportSpec ()]
-> Either String (ExportSpecList ())
forall a b. (a -> b) -> Either String a -> Either String b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (() -> [ExportSpec ()] -> ExportSpecList ()
forall l. l -> [ExportSpec l] -> ExportSpecList l
H.ExportSpecList ()) ([ExportSpec ()]
xs [ExportSpec ()] -> [ExportSpec ()] -> Either String [ExportSpec ()]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [ExportSpec ()]
ys)

instance Superimposable (H.ExportSpec ()) where
    x :: ExportSpec ()
x@(H.EThingWith ()
_ (H.EWildcard {}) QName ()
_ [CName ()]
_) --> :: ExportSpec () -> ExportSpec () -> LHsMakeError (ExportSpec ())
--> ExportSpec ()
_ 
        = ExportSpec () -> LHsMakeError (ExportSpec ())
forall a b. b -> Either a b
Right ExportSpec ()
x
    ExportSpec ()
_ --> y :: ExportSpec ()
y@(H.EThingWith ()
_ (H.EWildcard {}) QName ()
_ [CName ()]
_) 
        = ExportSpec () -> LHsMakeError (ExportSpec ())
forall a b. b -> Either a b
Right ExportSpec ()
y
    H.EThingWith ()
_ EWildcard ()
wild QName ()
name [CName ()]
xs --> H.EThingWith ()
_ EWildcard ()
_ QName ()
_ [CName ()]
ys 
        = ([CName ()] -> ExportSpec ())
-> Either String [CName ()] -> LHsMakeError (ExportSpec ())
forall a b. (a -> b) -> Either String a -> Either String b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (() -> EWildcard () -> QName () -> [CName ()] -> ExportSpec ()
forall l. l -> EWildcard l -> QName l -> [CName l] -> ExportSpec l
H.EThingWith () EWildcard ()
wild QName ()
name) ([CName ()]
xs [CName ()] -> [CName ()] -> Either String [CName ()]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [CName ()]
ys)
    H.EAbs ()
_ Namespace ()
_ QName ()
_ --> y :: ExportSpec ()
y@(H.EThingWith ()
_ EWildcard ()
_ QName ()
_ [CName ()]
_)     
        = ExportSpec () -> LHsMakeError (ExportSpec ())
forall a b. b -> Either a b
Right ExportSpec ()
y
    ExportSpec ()
x --> ExportSpec ()
_                                       
        = ExportSpec () -> LHsMakeError (ExportSpec ())
forall a b. b -> Either a b
Right ExportSpec ()
x

instance Identifiable (H.ExportSpec ()) where
    -- An export spec is identified by an entity or a whole module.
    type Identifier (H.ExportSpec ()) = Either (H.QName ()) (H.ModuleName ())
    identify :: ExportSpec () -> LHsMakeError (Identifier (ExportSpec ()))
identify (H.EVar ()
_ QName ()
name)            = Either (QName ()) (ModuleName ())
-> Either String (Either (QName ()) (ModuleName ()))
forall a b. b -> Either a b
Right (QName () -> Either (QName ()) (ModuleName ())
forall a b. a -> Either a b
Left  QName ()
name)
    identify (H.EAbs ()
_ Namespace ()
_ QName ()
name)          = Either (QName ()) (ModuleName ())
-> Either String (Either (QName ()) (ModuleName ()))
forall a b. b -> Either a b
Right (QName () -> Either (QName ()) (ModuleName ())
forall a b. a -> Either a b
Left  QName ()
name)
    identify (H.EThingWith ()
_ EWildcard ()
_ QName ()
name [CName ()]
_)  = Either (QName ()) (ModuleName ())
-> Either String (Either (QName ()) (ModuleName ()))
forall a b. b -> Either a b
Right (QName () -> Either (QName ()) (ModuleName ())
forall a b. a -> Either a b
Left  QName ()
name)
    identify (H.EModuleContents ()
_ ModuleName ()
modl) = Either (QName ()) (ModuleName ())
-> Either String (Either (QName ()) (ModuleName ()))
forall a b. b -> Either a b
Right (ModuleName () -> Either (QName ()) (ModuleName ())
forall a b. b -> Either a b
Right ModuleName ()
modl)

-- Imports --------------------------------------------------------------------

instance Superimposable (H.ImportDecl ()) where
    ImportDecl ()
x --> :: ImportDecl () -> ImportDecl () -> LHsMakeError (ImportDecl ())
--> ImportDecl ()
y = do
        Maybe (ImportSpecList ())
specs <- Maybe (Either String (ImportSpecList ()))
-> Either String (Maybe (ImportSpecList ()))
forall (t :: * -> *) (f :: * -> *) a.
(Traversable t, Applicative f) =>
t (f a) -> f (t a)
forall (f :: * -> *) a. Applicative f => Maybe (f a) -> f (Maybe a)
sequenceA ((ImportSpecList ()
 -> ImportSpecList () -> Either String (ImportSpecList ()))
-> Maybe (ImportSpecList ())
-> Maybe (ImportSpecList ())
-> Maybe (Either String (ImportSpecList ()))
forall a b c. (a -> b -> c) -> Maybe a -> Maybe b -> Maybe c
forall (f :: * -> *) a b c.
Applicative f =>
(a -> b -> c) -> f a -> f b -> f c
liftA2 ImportSpecList ()
-> ImportSpecList () -> Either String (ImportSpecList ())
forall a. Superimposable a => a -> a -> LHsMakeError a
(-->) (ImportDecl () -> Maybe (ImportSpecList ())
forall l. ImportDecl l -> Maybe (ImportSpecList l)
H.importSpecs ImportDecl ()
x) (ImportDecl () -> Maybe (ImportSpecList ())
forall l. ImportDecl l -> Maybe (ImportSpecList l)
H.importSpecs ImportDecl ()
y))
        ImportDecl () -> LHsMakeError (ImportDecl ())
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (ImportDecl ()
x { H.importSpecs = specs })

instance Identifiable (H.ImportDecl ()) where
    type Identifier (H.ImportDecl ()) = (H.ModuleName (), Bool, Maybe (H.ModuleName ()))
    identify :: ImportDecl () -> LHsMakeError (Identifier (ImportDecl ()))
identify ImportDecl ()
imp = (ModuleName (), Bool, Maybe (ModuleName ()))
-> Either String (ModuleName (), Bool, Maybe (ModuleName ()))
forall a b. b -> Either a b
Right (ImportDecl () -> ModuleName ()
forall l. ImportDecl l -> ModuleName l
H.importModule ImportDecl ()
imp, ImportDecl () -> Bool
forall l. ImportDecl l -> Bool
H.importQualified ImportDecl ()
imp, ImportDecl () -> Maybe (ModuleName ())
forall l. ImportDecl l -> Maybe (ModuleName l)
H.importAs ImportDecl ()
imp)

-- Note that @ImportSpecList _ False xs@ imports only @xs@, 
-- and @ImportSpecList _ True xs@ imports everything except @xs@.
instance Superimposable (H.ImportSpecList ()) where
    H.ImportSpecList ()
_ Bool
False [ImportSpec ()]
xs --> :: ImportSpecList ()
-> ImportSpecList () -> Either String (ImportSpecList ())
--> H.ImportSpecList ()
_ Bool
False [ImportSpec ()]
ys = ([ImportSpec ()] -> ImportSpecList ())
-> Either String [ImportSpec ()]
-> Either String (ImportSpecList ())
forall a b. (a -> b) -> Either String a -> Either String b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (() -> Bool -> [ImportSpec ()] -> ImportSpecList ()
forall l. l -> Bool -> [ImportSpec l] -> ImportSpecList l
H.ImportSpecList () Bool
False) ([ImportSpec ()]
xs [ImportSpec ()] -> [ImportSpec ()] -> Either String [ImportSpec ()]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [ImportSpec ()]
ys)
    H.ImportSpecList ()
_ Bool
True  [ImportSpec ()]
xs --> H.ImportSpecList ()
_ Bool
True  [ImportSpec ()]
ys = do
        [Name ()]
xids <- (ImportSpec () -> Either String (Name ()))
-> [ImportSpec ()] -> Either String [Name ()]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse ImportSpec () -> Either String (Name ())
ImportSpec () -> LHsMakeError (Identifier (ImportSpec ()))
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [ImportSpec ()]
xs
        [Name ()]
yids <- (ImportSpec () -> Either String (Name ()))
-> [ImportSpec ()] -> Either String [Name ()]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse ImportSpec () -> Either String (Name ())
ImportSpec () -> LHsMakeError (Identifier (ImportSpec ()))
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [ImportSpec ()]
ys
        ImportSpecList () -> Either String (ImportSpecList ())
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (() -> Bool -> [ImportSpec ()] -> ImportSpecList ()
forall l. l -> Bool -> [ImportSpec l] -> ImportSpecList l
H.ImportSpecList () Bool
True [ImportSpec ()
x | (ImportSpec ()
x, Name ()
xid) <- [ImportSpec ()] -> [Name ()] -> [(ImportSpec (), Name ())]
forall a b. [a] -> [b] -> [(a, b)]
zip [ImportSpec ()]
xs [Name ()]
xids, Name ()
xid Name () -> [Name ()] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Name ()]
yids])
    H.ImportSpecList ()
_ Bool
False [ImportSpec ()]
xs --> H.ImportSpecList ()
_ Bool
True  [ImportSpec ()]
ys = do
        [Name ()]
xids <- (ImportSpec () -> Either String (Name ()))
-> [ImportSpec ()] -> Either String [Name ()]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse ImportSpec () -> Either String (Name ())
ImportSpec () -> LHsMakeError (Identifier (ImportSpec ()))
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [ImportSpec ()]
xs
        [Name ()]
yids <- (ImportSpec () -> Either String (Name ()))
-> [ImportSpec ()] -> Either String [Name ()]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse ImportSpec () -> Either String (Name ())
ImportSpec () -> LHsMakeError (Identifier (ImportSpec ()))
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [ImportSpec ()]
ys
        ImportSpecList () -> Either String (ImportSpecList ())
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (() -> Bool -> [ImportSpec ()] -> ImportSpecList ()
forall l. l -> Bool -> [ImportSpec l] -> ImportSpecList l
H.ImportSpecList () Bool
True [ImportSpec ()
y | (ImportSpec ()
y, Name ()
yid) <- [ImportSpec ()] -> [Name ()] -> [(ImportSpec (), Name ())]
forall a b. [a] -> [b] -> [(a, b)]
zip [ImportSpec ()]
ys [Name ()]
yids, Name ()
yid Name () -> [Name ()] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Name ()]
xids])
    H.ImportSpecList ()
_ Bool
True  [ImportSpec ()]
xs --> H.ImportSpecList ()
_ Bool
False [ImportSpec ()]
ys = do
        [Name ()]
xids <- (ImportSpec () -> Either String (Name ()))
-> [ImportSpec ()] -> Either String [Name ()]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse ImportSpec () -> Either String (Name ())
ImportSpec () -> LHsMakeError (Identifier (ImportSpec ()))
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [ImportSpec ()]
xs
        [Name ()]
yids <- (ImportSpec () -> Either String (Name ()))
-> [ImportSpec ()] -> Either String [Name ()]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse ImportSpec () -> Either String (Name ())
ImportSpec () -> LHsMakeError (Identifier (ImportSpec ()))
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [ImportSpec ()]
ys
        ImportSpecList () -> Either String (ImportSpecList ())
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (() -> Bool -> [ImportSpec ()] -> ImportSpecList ()
forall l. l -> Bool -> [ImportSpec l] -> ImportSpecList l
H.ImportSpecList () Bool
True [ImportSpec ()
x | (ImportSpec ()
x, Name ()
xid) <- [ImportSpec ()] -> [Name ()] -> [(ImportSpec (), Name ())]
forall a b. [a] -> [b] -> [(a, b)]
zip [ImportSpec ()]
xs [Name ()]
xids, Name ()
xid Name () -> [Name ()] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Name ()]
yids])

instance Superimposable (H.ImportSpec ()) where
    x :: ImportSpec ()
x@(H.IThingAll ()
_ Name ()
_) --> :: ImportSpec () -> ImportSpec () -> LHsMakeError (ImportSpec ())
--> ImportSpec ()
_                      
        = ImportSpec () -> LHsMakeError (ImportSpec ())
forall a b. b -> Either a b
Right ImportSpec ()
x
    ImportSpec ()
_ --> y :: ImportSpec ()
y@(H.IThingAll ()
_ Name ()
_)                      
        = ImportSpec () -> LHsMakeError (ImportSpec ())
forall a b. b -> Either a b
Right ImportSpec ()
y
    H.IThingWith ()
_ Name ()
name [CName ()]
xs --> H.IThingWith ()
_ Name ()
_ [CName ()]
ys 
        = ([CName ()] -> ImportSpec ())
-> Either String [CName ()] -> LHsMakeError (ImportSpec ())
forall a b. (a -> b) -> Either String a -> Either String b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (() -> Name () -> [CName ()] -> ImportSpec ()
forall l. l -> Name l -> [CName l] -> ImportSpec l
H.IThingWith () Name ()
name) ([CName ()]
xs [CName ()] -> [CName ()] -> Either String [CName ()]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [CName ()]
ys)
    H.IAbs ()
_ Namespace ()
_ Name ()
_ --> y :: ImportSpec ()
y@(H.IThingWith ()
_ Name ()
_ [CName ()]
_)        
        = ImportSpec () -> LHsMakeError (ImportSpec ())
forall a b. b -> Either a b
Right ImportSpec ()
y
    ImportSpec ()
x --> ImportSpec ()
_                                       
        = ImportSpec () -> LHsMakeError (ImportSpec ())
forall a b. b -> Either a b
Right ImportSpec ()
x

instance Identifiable (H.ImportSpec ()) where
    type Identifier (H.ImportSpec ()) = H.Name ()
    identify :: ImportSpec () -> LHsMakeError (Identifier (ImportSpec ()))
identify (H.IVar ()
_ Name ()
name)         = Name () -> Either String (Name ())
forall a b. b -> Either a b
Right Name ()
name
    identify (H.IAbs ()
_ Namespace ()
_ Name ()
name)       = Name () -> Either String (Name ())
forall a b. b -> Either a b
Right Name ()
name
    identify (H.IThingAll ()
_ Name ()
name)    = Name () -> Either String (Name ())
forall a b. b -> Either a b
Right Name ()
name
    identify (H.IThingWith ()
_ Name ()
name [CName ()]
_) = Name () -> Either String (Name ())
forall a b. b -> Either a b
Right Name ()
name

-- Declarations ---------------------------------------------------------------

-- | Identifiers for Haskell declarations.
--
--   Only these declarations can be merged. Everything else (classes, default
--   declarations, foreign declarations, pattern bindings) is rejected by 'identify'.
data DeclId
    = Value    (H.Name ())  -- ^ Functions and variables.
    | Sig      (H.Name ())  -- ^ Type signatures.
    | Type     (H.Name ())  -- ^ Type synonyms, datatype declarations, and @newtype@s.
    | Fixity   (H.Name ())  -- ^ Fixity declarations.
    | Instance (H.InstHead ())
                            -- ^ Typeclass instance declarations.
    deriving DeclId -> DeclId -> Bool
(DeclId -> DeclId -> Bool)
-> (DeclId -> DeclId -> Bool) -> Eq DeclId
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DeclId -> DeclId -> Bool
== :: DeclId -> DeclId -> Bool
$c/= :: DeclId -> DeclId -> Bool
/= :: DeclId -> DeclId -> Bool
Eq

-- | Finds the name that a declaration head (such as @T a b@) declares.
headName :: H.DeclHead l -> H.Name l
headName :: forall l. DeclHead l -> Name l
headName (H.DHead l
_ Name l
name)     = Name l
name
headName (H.DHInfix l
_ TyVarBind l
_ Name l
name) = Name l
name
headName (H.DHParen l
_ DeclHead l
hd)     = DeclHead l -> Name l
forall l. DeclHead l -> Name l
headName DeclHead l
hd
headName (H.DHApp l
_ DeclHead l
hd TyVarBind l
_)     = DeclHead l -> Name l
forall l. DeclHead l -> Name l
headName DeclHead l
hd

-- | Finds the instance head (the class and its types) of an instance rule.
instHead :: H.InstRule l -> H.InstHead l
instHead :: forall l. InstRule l -> InstHead l
instHead (H.IRule l
_ Maybe [TyVarBind l]
_ Maybe (Context l)
_ InstHead l
hd) = InstHead l
hd
instHead (H.IParen l
_ InstRule l
rule)  = InstRule l -> InstHead l
forall l. InstRule l -> InstHead l
instHead InstRule l
rule

-- | Only a subset of Haskell declarations have been given superimposition definitions.
--   These are as follows.
--
--       * Type synonyms
--       * Datatype declarations
--       * Newtype declarations
--       * Function bindings
--       * Type signatures
--       * Fixity declarations
--       * Typeclass instance declarations.
--
--   See 'DeclId'.
instance Identifiable (H.Decl ()) where
    type Identifier (H.Decl ()) = DeclId
    identify :: Decl () -> LHsMakeError (Identifier (Decl ()))
identify (H.TypeDecl ()
_ DeclHead ()
hd Type ()
_)                  = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (Name () -> DeclId
Type (DeclHead () -> Name ()
forall l. DeclHead l -> Name l
headName DeclHead ()
hd))
    identify (H.DataDecl ()
_ DataOrNew ()
_ Maybe (Context ())
_ DeclHead ()
hd [QualConDecl ()]
_ [Deriving ()]
_)            = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (Name () -> DeclId
Type (DeclHead () -> Name ()
forall l. DeclHead l -> Name l
headName DeclHead ()
hd))
    identify (H.FunBind ()
_ (Match ()
m : [Match ()]
_))                = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (Name () -> DeclId
Value ((Name (), [Pat ()]) -> Name ()
forall a b. (a, b) -> a
fst (Match () -> (Name (), [Pat ()])
forall l. Match l -> (Name l, [Pat l])
clause Match ()
m)))
    identify (H.TypeSig ()
_ [Name ()
name] Type ()
_)               = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (Name () -> DeclId
Sig Name ()
name)
    identify (H.InfixDecl ()
_ Assoc ()
_ Maybe Int
_ [H.VarOp ()
_ Name ()
name]) = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (Name () -> DeclId
Fixity Name ()
name)
    identify (H.InfixDecl ()
_ Assoc ()
_ Maybe Int
_ [H.ConOp ()
_ Name ()
name]) = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (Name () -> DeclId
Fixity Name ()
name)
    identify (H.InstDecl ()
_ Maybe (Overlap ())
_ InstRule ()
rule Maybe [InstDecl ()]
_)              = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (InstHead () -> DeclId
Instance (InstRule () -> InstHead ()
forall l. InstRule l -> InstHead l
instHead InstRule ()
rule))
    identify Decl ()
decl = String -> Either String DeclId
forall a b. a -> Either a b
Left (String
"Cannot merge this declaration: "
                          String -> String -> String
forall a. [a] -> [a] -> [a]
++ (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n') ((Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace (Decl () -> String
forall a. Pretty a => a -> String
H.prettyPrint Decl ()
decl)))

-- | Datatype declarations, functions, and typeclass instance declarations are merged.
--   Type synonyms, @newtype@s, type signatures, and fixity declarations are overridden from the left.
instance Superimposable (H.Decl ()) where
    H.DataDecl ()
_ dn :: DataOrNew ()
dn@(H.DataType ()
_) Maybe (Context ())
ctx DeclHead ()
hd [QualConDecl ()]
cons1 [Deriving ()]
derivs1 --> :: Decl () -> Decl () -> LHsMakeError (Decl ())
--> H.DataDecl ()
_ (H.DataType ()
_) Maybe (Context ())
_ DeclHead ()
_ [QualConDecl ()]
cons2 [Deriving ()]
derivs2 = do
        [QualConDecl ()]
cons   <- [QualConDecl ()]
cons1 [QualConDecl ()]
-> [QualConDecl ()] -> LHsMakeError [QualConDecl ()]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [QualConDecl ()]
cons2
        [Deriving ()]
derivs <- [Deriving ()]
derivs1 [Deriving ()] -> [Deriving ()] -> LHsMakeError [Deriving ()]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [Deriving ()]
derivs2
        Decl () -> LHsMakeError (Decl ())
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (()
-> DataOrNew ()
-> Maybe (Context ())
-> DeclHead ()
-> [QualConDecl ()]
-> [Deriving ()]
-> Decl ()
forall l.
l
-> DataOrNew l
-> Maybe (Context l)
-> DeclHead l
-> [QualConDecl l]
-> [Deriving l]
-> Decl l
H.DataDecl () DataOrNew ()
dn Maybe (Context ())
ctx DeclHead ()
hd [QualConDecl ()]
cons [Deriving ()]
derivs)
    H.FunBind ()
_ [Match ()]
ms1 --> H.FunBind ()
_ [Match ()]
ms2
        | [Int] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([Int] -> [Int]
forall a. Eq a => [a] -> [a]
nub [[Pat ()] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ((Name (), [Pat ()]) -> [Pat ()]
forall a b. (a, b) -> b
snd (Match () -> (Name (), [Pat ()])
forall l. Match l -> (Name l, [Pat l])
clause Match ()
m)) | Match ()
m <- [Match ()]
ms1 [Match ()] -> [Match ()] -> [Match ()]
forall a. [a] -> [a] -> [a]
++ [Match ()]
ms2]) Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1
        = ([Match ()] -> Decl ())
-> Either String [Match ()] -> LHsMakeError (Decl ())
forall a b. (a -> b) -> Either String a -> Either String b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (() -> [Match ()] -> Decl ()
forall l. l -> [Match l] -> Decl l
H.FunBind ()) ([Match ()]
ms1 [Match ()] -> [Match ()] -> Either String [Match ()]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [Match ()]
ms2)
    H.InstDecl ()
_ Maybe (Overlap ())
overlap InstRule ()
rule Maybe [InstDecl ()]
decls1 --> H.InstDecl ()
_ Maybe (Overlap ())
_ InstRule ()
_ Maybe [InstDecl ()]
decls2 = do
        [InstDecl ()]
decls <- [InstDecl ()] -> Maybe [InstDecl ()] -> [InstDecl ()]
forall a. a -> Maybe a -> a
fromMaybe [] Maybe [InstDecl ()]
decls1 [InstDecl ()] -> [InstDecl ()] -> LHsMakeError [InstDecl ()]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [InstDecl ()] -> Maybe [InstDecl ()] -> [InstDecl ()]
forall a. a -> Maybe a -> a
fromMaybe [] Maybe [InstDecl ()]
decls2
        Decl () -> LHsMakeError (Decl ())
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (()
-> Maybe (Overlap ())
-> InstRule ()
-> Maybe [InstDecl ()]
-> Decl ()
forall l.
l
-> Maybe (Overlap l) -> InstRule l -> Maybe [InstDecl l] -> Decl l
H.InstDecl () Maybe (Overlap ())
overlap InstRule ()
rule (if [InstDecl ()] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [InstDecl ()]
decls then Maybe [InstDecl ()]
forall a. Maybe a
Nothing else [InstDecl ()] -> Maybe [InstDecl ()]
forall a. a -> Maybe a
Just [InstDecl ()]
decls))
    Decl ()
x --> Decl ()
_ = Decl () -> LHsMakeError (Decl ())
forall a b. b -> Either a b
Right Decl ()
x

instance Superimposable (H.InstDecl ()) where
    H.InsDecl ()
_ Decl ()
x --> :: InstDecl () -> InstDecl () -> LHsMakeError (InstDecl ())
--> H.InsDecl ()
_ Decl ()
y = (Decl () -> InstDecl ())
-> LHsMakeError (Decl ()) -> LHsMakeError (InstDecl ())
forall a b. (a -> b) -> Either String a -> Either String b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (() -> Decl () -> InstDecl ()
forall l. l -> Decl l -> InstDecl l
H.InsDecl ()) (Decl ()
x Decl () -> Decl () -> LHsMakeError (Decl ())
forall a. Superimposable a => a -> a -> LHsMakeError a
--> Decl ()
y)
    InstDecl ()
x --> InstDecl ()
_ = InstDecl () -> LHsMakeError (InstDecl ())
forall a b. b -> Either a b
Right InstDecl ()
x

instance Identifiable (H.InstDecl ()) where
    type Identifier (H.InstDecl ()) = DeclId
    identify :: InstDecl () -> LHsMakeError (Identifier (InstDecl ()))
identify (H.InsDecl ()
_ Decl ()
decl) = Decl () -> LHsMakeError (Identifier (Decl ()))
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify Decl ()
decl
    identify InstDecl ()
decl = 
        String -> Either String DeclId
forall a b. a -> Either a b
Left (String
"Cannot merge this instance declaration: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ 
              (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n') ((Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace (InstDecl () -> String
forall a. Pretty a => a -> String
H.prettyPrint InstDecl ()
decl)))

-- | A @deriving@ clause is identified by its strategy (e.g., 'H.DerivStock').
--   Clauses with the same strategy are merged, and the classes they derive are merged by their names.
instance Superimposable (H.Deriving ()) where
    H.Deriving ()
_ Maybe (DerivStrategy ())
strat [InstRule ()]
rules1 --> :: Deriving () -> Deriving () -> LHsMakeError (Deriving ())
--> H.Deriving ()
_ Maybe (DerivStrategy ())
_ [InstRule ()]
rules2 
        = ([InstRule ()] -> Deriving ())
-> Either String [InstRule ()] -> LHsMakeError (Deriving ())
forall a b. (a -> b) -> Either String a -> Either String b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (() -> Maybe (DerivStrategy ()) -> [InstRule ()] -> Deriving ()
forall l.
l -> Maybe (DerivStrategy l) -> [InstRule l] -> Deriving l
H.Deriving () Maybe (DerivStrategy ())
strat) ([InstRule ()]
rules1 [InstRule ()] -> [InstRule ()] -> Either String [InstRule ()]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [InstRule ()]
rules2)

instance Identifiable (H.Deriving ()) where
    type Identifier (H.Deriving ()) = Maybe (H.DerivStrategy ())
    identify :: Deriving () -> LHsMakeError (Identifier (Deriving ()))
identify (H.Deriving ()
_ Maybe (DerivStrategy ())
strat [InstRule ()]
_) = Maybe (DerivStrategy ())
-> Either String (Maybe (DerivStrategy ()))
forall a b. b -> Either a b
Right Maybe (DerivStrategy ())
strat

-------------------------------------------------------------------------------
-- Happy
-------------------------------------------------------------------------------

instance Superimposable (Y.Prod String)

-- | A production is identified by its RHS.
instance Identifiable (Y.Prod String) where
    type Identifier (Y.Prod String) = [String]
    identify :: Prod String -> LHsMakeError (Identifier (Prod String))
identify (Y.Prod [Term]
terms String
_ Int
_ Prec
_) = [String] -> Either String [String]
forall a b. b -> Either a b
Right ((Term -> String) -> [Term] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (Doc -> String
Y.render (Doc -> String) -> (Term -> Doc) -> Term -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Term -> Doc
Y.ppTerm) [Term]
terms)

instance Superimposable (Y.Rule String) where
    Y.Rule String
name [String]
params1 [Prod String]
prods1 Maybe String
ty1 --> :: Rule String -> Rule String -> LHsMakeError (Rule String)
--> Y.Rule String
_ [String]
params2 [Prod String]
prods2 Maybe String
ty2
        | [String]
params1 [String] -> [String] -> Bool
forall a. Eq a => a -> a -> Bool
== [String]
params2 = do
            [Prod String]
prods <- [Prod String]
prods1 [Prod String] -> [Prod String] -> LHsMakeError [Prod String]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [Prod String]
prods2
            Rule String -> LHsMakeError (Rule String)
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> [String] -> [Prod String] -> Maybe String -> Rule String
forall e. String -> [String] -> [Prod e] -> Maybe String -> Rule e
Y.Rule String
name [String]
params1 [Prod String]
prods (Maybe String
ty1 Maybe String -> Maybe String -> Maybe String
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe String
ty2))
    Rule String
rule --> Rule String
_ = Rule String -> LHsMakeError (Rule String)
forall a b. b -> Either a b
Right Rule String
rule

instance Identifiable (Y.Rule String) where
    type Identifier (Y.Rule String) = String
    identify :: Rule String -> LHsMakeError (Identifier (Rule String))
identify (Y.Rule String
name [String]
_ [Prod String]
_ Maybe String
_) = String -> Either String String
forall a b. b -> Either a b
Right String
name

-- | @%token@ directives are merged and @%name@ directives are overridden from the left.
--   Other differing directives are simply rejected.
instance Superimposable (Y.Directive String) where
    x :: Directive String
x@(Y.TokenSpec [(String, TokenSpec)]
_)  --> :: Directive String
-> Directive String -> LHsMakeError (Directive String)
--> Directive String
_ = Directive String -> LHsMakeError (Directive String)
forall a b. b -> Either a b
Right Directive String
x
    x :: Directive String
x@(Y.TokenName {}) --> Directive String
_ = Directive String -> LHsMakeError (Directive String)
forall a b. b -> Either a b
Right Directive String
x
    Directive String
x --> Directive String
y
        | Directive String
x Directive String -> Directive String -> Bool
forall a. Eq a => a -> a -> Bool
== Directive String
y    = Directive String -> LHsMakeError (Directive String)
forall a b. b -> Either a b
Right Directive String
x
        | Bool
otherwise = String -> LHsMakeError (Directive String)
forall a b. a -> Either a b
Left (String
"Cannot merge differing directives: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Directive String -> String
forall a. Show a => a -> String
show Directive String
x String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" and " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Directive String -> String
forall a. Show a => a -> String
show Directive String
y)

-- | Identifiers for Happy directives.
data DirectiveId
    = Token     String  -- ^ A @%token@ directive, one per token.
    | Name      String  -- ^ The @%name@ directive.
    | Attribute String  -- ^ The @%attribute@ directive.
    | Prec      String  -- ^ A @%left@, @%right@, or @%nonassoc@ directive, one per token.
    | Other     String  -- ^ Any other directive.
    deriving DirectiveId -> DirectiveId -> Bool
(DirectiveId -> DirectiveId -> Bool)
-> (DirectiveId -> DirectiveId -> Bool) -> Eq DirectiveId
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DirectiveId -> DirectiveId -> Bool
== :: DirectiveId -> DirectiveId -> Bool
$c/= :: DirectiveId -> DirectiveId -> Bool
/= :: DirectiveId -> DirectiveId -> Bool
Eq

instance Identifiable (Y.Directive String) where
    type Identifier (Y.Directive String) = DirectiveId
    identify :: Directive String -> LHsMakeError (Identifier (Directive String))
identify (Y.TokenSpec [(String
name, TokenSpec
_)]) = DirectiveId -> Either String DirectiveId
forall a b. b -> Either a b
Right (String -> DirectiveId
Token String
name)
    identify (Y.TokenName String
_ Maybe String
_ Bool
True)    = String -> Either String DirectiveId
forall a b. a -> Either a b
Left String
"Cannot merge %partial directives"
    identify (Y.TokenName String
name Maybe String
_ Bool
_)    = DirectiveId -> Either String DirectiveId
forall a b. b -> Either a b
Right (String -> DirectiveId
Name String
name)
    identify (Y.TokenAttribute String
name String
_) = DirectiveId -> Either String DirectiveId
forall a b. b -> Either a b
Right (String -> DirectiveId
Attribute String
name)
    identify (Y.TokenLeft [String
name])      = DirectiveId -> Either String DirectiveId
forall a b. b -> Either a b
Right (String -> DirectiveId
Prec String
name)
    identify (Y.TokenRight [String
name])     = DirectiveId -> Either String DirectiveId
forall a b. b -> Either a b
Right (String -> DirectiveId
Prec String
name)
    identify (Y.TokenNonassoc [String
name])  = DirectiveId -> Either String DirectiveId
forall a b. b -> Either a b
Right (String -> DirectiveId
Prec String
name)
    identify Directive String
dir                       = DirectiveId -> Either String DirectiveId
forall a b. b -> Either a b
Right (String -> DirectiveId
Other ((Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
' ') (Directive String -> String
forall a. Show a => a -> String
show Directive String
dir)))

-- | Splits @x a b@ into @x a@ and @x b@, where @x@ ranges over the @%token@, @%left@, @%right@, and @%nonassoc@ directives.
--   All other directives are left as is.
flattenTokens :: [Y.Directive String] -> [Y.Directive String]
flattenTokens :: [Directive String] -> [Directive String]
flattenTokens = (Directive String -> [Directive String])
-> [Directive String] -> [Directive String]
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
(=<<) Directive String -> [Directive String]
forall {a}. Directive a -> [Directive a]
flattenToken
    where
        flattenToken :: Directive a -> [Directive a]
flattenToken (Y.TokenSpec [(a, TokenSpec)]
specs)    = ((a, TokenSpec) -> Directive a)
-> [(a, TokenSpec)] -> [Directive a]
forall a b. (a -> b) -> [a] -> [b]
map ([(a, TokenSpec)] -> Directive a
forall a. [(a, TokenSpec)] -> Directive a
Y.TokenSpec ([(a, TokenSpec)] -> Directive a)
-> ((a, TokenSpec) -> [(a, TokenSpec)])
-> (a, TokenSpec)
-> Directive a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (a, TokenSpec) -> [(a, TokenSpec)]
forall a. a -> [a]
forall (m :: * -> *) a. Monad m => a -> m a
return) [(a, TokenSpec)]
specs
        flattenToken (Y.TokenLeft [String]
toks)     = (String -> Directive a) -> [String] -> [Directive a]
forall a b. (a -> b) -> [a] -> [b]
map ([String] -> Directive a
forall a. [String] -> Directive a
Y.TokenLeft ([String] -> Directive a)
-> (String -> [String]) -> String -> Directive a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> [String]
forall a. a -> [a]
forall (m :: * -> *) a. Monad m => a -> m a
return) [String]
toks
        flattenToken (Y.TokenRight [String]
toks)    = (String -> Directive a) -> [String] -> [Directive a]
forall a b. (a -> b) -> [a] -> [b]
map ([String] -> Directive a
forall a. [String] -> Directive a
Y.TokenRight ([String] -> Directive a)
-> (String -> [String]) -> String -> Directive a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> [String]
forall a. a -> [a]
forall (m :: * -> *) a. Monad m => a -> m a
return) [String]
toks
        flattenToken (Y.TokenNonassoc [String]
toks) = (String -> Directive a) -> [String] -> [Directive a]
forall a b. (a -> b) -> [a] -> [b]
map ([String] -> Directive a
forall a. [String] -> Directive a
Y.TokenNonassoc ([String] -> Directive a)
-> (String -> [String]) -> String -> Directive a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> [String]
forall a. a -> [a]
forall (m :: * -> *) a. Monad m => a -> m a
return) [String]
toks
        flattenToken Directive a
dir = Directive a -> [Directive a]
forall a. a -> [a]
forall (m :: * -> *) a. Monad m => a -> m a
return Directive a
dir

-- | Precedences of tokens, where a higher number binds tighter than a lower one.
--   The (relative) precedences of tokens corresponding to operators borrow directly from Haskell.
--   Operator associativity is defined within the parser files themselves.
--
--   Note that the precedence resolution mechanism here is slightly weaker than precedence climbing. 
--   In Happy files, tokens with the same precedence but different associativity cannot 
--   share a precedence level. Consequently, superimposition must order such tokens 
--   sequentially in precedence lists. As a result, Layered Haskell accepts expressions that 
--   GHC would normally reject, like @x . y !! z@.
-- 
--   ==== __Precedences__
--
--   Tokens where superimposition diverges from GHC are marked with a @!@.
--   There is currently only one such precedence level.
--
--   > LAM                0
--   > 'in'               1
--   > 'else'             2
--   > '$'                3
--   > '||'               4
--   > '&&'               5
--   > '==' '/='          6
--   > '<' '>' '<=' '>='  7
--   > ':' '++'           8
--   > '+' '-'            9
--   > '*'               10
--   > NEG               11
--   > '.' '!!'          12 !
precs :: Map String Int
precs :: Map String Int
precs = [(String, Int)] -> Map String Int
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList
    [ (String
"LAM",    Int
0)
    , (String
"'in'",   Int
1)
    , (String
"'else'", Int
2)
    , (String
"'$'",    Int
3)
    , (String
"'||'",   Int
4)
    , (String
"'&&'",   Int
5)
    , (String
"'=='",   Int
6), (String
"'/='",  Int
6)
    , (String
"'<'",    Int
7), (String
"'>'",   Int
7), (String
"'<='",  Int
7), (String
"'>='", Int
7)
    , (String
"':'",    Int
8), (String
"'++'",  Int
8)
    , (String
"'+'",    Int
9), (String
"'-'",   Int
9)
    , (String
"'*'",   Int
10)
    , (String
"NEG",   Int
11)
    , (String
"'.'",   Int
12), (String
"'!!'", Int
12)
    ]

-- | Groups precedence directives by the (numeric) precedence and associativity of the 
--   involved tokens. If a token with an unknown precedence is encountered, an error is emitted.
--   
--   Note that the numeric precedences come from 'precs', while the associativities come from the parser files themselves.
--   Consequently, the order in which token precedence is specified within the parser files is ignored,
--   since 'groupPrecs' sorts tokens into the expected order anyway.
groupPrecs :: [Y.Directive String] -> LHsMakeError [Y.Directive String]
groupPrecs :: [Directive String] -> LHsMakeError [Directive String]
groupPrecs [Directive String]
prios = do
    [(String, Int)]
tokPrecs <- (String -> Either String (String, Int))
-> [String] -> Either String [(String, Int)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM String -> Either String (String, Int)
precOf [String]
toks
    [Directive String] -> LHsMakeError [Directive String]
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return
        [ [String] -> Directive String
dir [String]
toksAtPrec
        | Int
prec <- [Int
0 .. Map String Int -> Int
forall a. Ord a => Map String a -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
maximum Map String Int
precs]
        , [String] -> Directive String
dir  <- [[String] -> Directive String
forall a. [String] -> Directive a
Y.TokenLeft, [String] -> Directive String
forall a. [String] -> Directive a
Y.TokenRight, [String] -> Directive String
forall a. [String] -> Directive a
Y.TokenNonassoc]
        , let toksAtPrec :: [String]
toksAtPrec = [String
tok | (String
tok, Int
p) <- [(String, Int)]
tokPrecs, Int
p Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
prec, [String] -> Directive String
dir [String
tok] Directive String -> [Directive String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Directive String]
prios]
        , Bool -> Bool
not ([String] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
toksAtPrec) ]
    where
        toks :: [String]
toks       = (Directive String -> [String]) -> [Directive String] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Directive String -> [String]
forall t. Directive t -> [String]
Y.getPrioNames [Directive String]
prios
        precOf :: String -> Either String (String, Int)
precOf String
tok = Either String (String, Int)
-> (Int -> Either String (String, Int))
-> Maybe Int
-> Either String (String, Int)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (String -> Either String (String, Int)
forall a b. a -> Either a b
Left (String
"Unknown precedence for: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
tok)) (\Int
p -> (String, Int) -> Either String (String, Int)
forall a b. b -> Either a b
Right (String
tok, Int
p)) (String -> Map String Int -> Maybe Int
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup String
tok Map String Int
precs)

-- | Directives are first flattened (see 'flattenTokens'), then merged as much as possible.
--   Precedence directives are merged with respect to numeric precedences (see 'precs').
instance Superimposable (Y.AbsSyn String) where
    Y.AbsSyn [Directive String]
dirs1 [Rule String]
rules1 --> :: AbsSyn String -> AbsSyn String -> LHsMakeError (AbsSyn String)
--> Y.AbsSyn [Directive String]
dirs2 [Rule String]
rules2 = do
        [Directive String]
merged  <- [Directive String] -> [Directive String]
flattenTokens [Directive String]
dirs1 [Directive String]
-> [Directive String] -> LHsMakeError [Directive String]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [Directive String] -> [Directive String]
flattenTokens [Directive String]
dirs2
        [Rule String]
rules   <- [Rule String]
rules1 [Rule String] -> [Rule String] -> LHsMakeError [Rule String]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [Rule String]
rules2
        let ([Directive String]
prios, [Directive String]
others) = (Directive String -> Bool)
-> [Directive String] -> ([Directive String], [Directive String])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition (Directive String -> [Directive String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Directive String] -> [Directive String]
forall t. [Directive t] -> [Directive t]
Y.getPrios [Directive String]
merged) [Directive String]
merged
        [Directive String]
grouped <- [Directive String] -> LHsMakeError [Directive String]
groupPrecs [Directive String]
prios
        AbsSyn String -> LHsMakeError (AbsSyn String)
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return ([Directive String] -> [Rule String] -> AbsSyn String
forall e. [Directive String] -> [Rule e] -> AbsSyn e
Y.AbsSyn ([Directive String]
others [Directive String] -> [Directive String] -> [Directive String]
forall a. [a] -> [a] -> [a]
++ [Directive String]
grouped) [Rule String]
rules)

-- | Happy grammars are superimposed by first superimposing the header and footer as a Haskell module.
--   Then, each rule is superimposed.
instance Superimposable Y.BookendedAbsSyn where
    Y.BookendedAbsSyn Maybe String
opts1 Maybe String
head1 AbsSyn String
syn1 Maybe String
foot1 --> :: BookendedAbsSyn -> BookendedAbsSyn -> LHsMakeError BookendedAbsSyn
--> Y.BookendedAbsSyn Maybe String
opts2 Maybe String
head2 AbsSyn String
syn2 Maybe String
foot2 = do
        Module ()
modl1  <- Maybe String -> Maybe String -> LHsMakeError (Module ())
parse Maybe String
head1 Maybe String
foot1
        Module ()
modl2  <- Maybe String -> Maybe String -> LHsMakeError (Module ())
parse Maybe String
head2 Maybe String
foot2
        Module ()
merged <- Module ()
modl1 Module () -> Module () -> LHsMakeError (Module ())
forall a. Superimposable a => a -> a -> LHsMakeError a
--> Module ()
modl2
        (Module ()
shell, [Decl ()]
decls) <- case Module ()
merged of
            H.Module ()
_ Maybe (ModuleHead ())
hd [ModulePragma ()]
pragmas [ImportDecl ()]
imps [Decl ()]
ds -> (Module (), [Decl ()]) -> Either String (Module (), [Decl ()])
forall a b. b -> Either a b
Right (()
-> Maybe (ModuleHead ())
-> [ModulePragma ()]
-> [ImportDecl ()]
-> [Decl ()]
-> Module ()
forall l.
l
-> Maybe (ModuleHead l)
-> [ModulePragma l]
-> [ImportDecl l]
-> [Decl l]
-> Module l
H.Module () Maybe (ModuleHead ())
hd [ModulePragma ()]
pragmas [ImportDecl ()]
imps [], [Decl ()]
ds)
            Module ()
_                             -> String -> Either String (Module (), [Decl ()])
forall a b. a -> Either a b
Left String
"Invalid Happy header or footer: not a plain Haskell module"
        AbsSyn String
syn <- AbsSyn String
syn1 AbsSyn String -> AbsSyn String -> LHsMakeError (AbsSyn String)
forall a. Superimposable a => a -> a -> LHsMakeError a
--> AbsSyn String
syn2
        BookendedAbsSyn -> LHsMakeError BookendedAbsSyn
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe String
-> Maybe String -> AbsSyn String -> Maybe String -> BookendedAbsSyn
Y.BookendedAbsSyn (Maybe String
opts1 Maybe String -> Maybe String -> Maybe String
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe String
opts2)
                            -- The header contains the pragmas, the Haskell module declaration and imports.
                            (String -> Maybe String
forall a. a -> Maybe a
Just (Module () -> String
forall a. Pretty a => a -> String
H.prettyPrint Module ()
shell))
                            AbsSyn String
syn
                            -- The footer contains Haskell declarations.
                            (String -> Maybe String
forall a. a -> Maybe a
Just ([String] -> String
unlines ((Decl () -> String) -> [Decl ()] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Decl () -> String
forall a. Pretty a => a -> String
H.prettyPrint [Decl ()]
decls))))
        where
            parse :: Maybe String -> Maybe String -> LHsMakeError (Module ())
parse Maybe String
header Maybe String
footer = case ParseMode -> String -> ParseResult (Module SrcSpanInfo)
H.parseModuleWithMode ParseMode
parseMode ([String] -> String
unlines ([Maybe String] -> [String]
forall a. [Maybe a] -> [a]
catMaybes [Maybe String
header, Maybe String
footer])) of
                H.ParseOk Module SrcSpanInfo
modl      -> Module () -> LHsMakeError (Module ())
forall a b. b -> Either a b
Right (Module SrcSpanInfo -> Module ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void Module SrcSpanInfo
modl)
                H.ParseFailed SrcLoc
_ String
msg -> String -> LHsMakeError (Module ())
forall a b. a -> Either a b
Left (String
"Invalid Happy header or footer: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
msg)