{- |
Module      : LH.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 LH.Control.Superimposition (
    -- * Superimposition
    Superimposable (..), Identifiable (..),
    -- ** Identifiers
    DeclId (..), DirectiveId (..),
    -- ** Flattening lists
    flattenDecls, flattenTokens,
    -- ** Token precedences
    precs, groupPrecs
    ) where

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

import qualified Data.Map as Map

import qualified Happy.Frontend.AbsSyn        as Y
import qualified Happy.Frontend.PrettyGrammar as Y
import qualified Language.Haskell.Parser      as H
import qualified Language.Haskell.Pretty      as H
import qualified Language.Haskell.Syntax      as H

import LH.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
-------------------------------------------------------------------------------

instance Superimposable H.HsQName
instance Superimposable H.HsCName
instance Superimposable H.HsConDecl
instance Superimposable H.HsMatch

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

instance Identifiable H.HsCName where
    type Identifier H.HsCName = H.HsName
    identify :: HsCName -> LHsMakeError (Identifier HsCName)
identify (H.HsVarName HsName
name) = HsName -> Either String HsName
forall a b. b -> Either a b
Right HsName
name
    identify (H.HsConName HsName
name) = HsName -> Either String HsName
forall a b. b -> Either a b
Right HsName
name

instance Identifiable H.HsConDecl where
    type Identifier H.HsConDecl = H.HsName
    identify :: HsConDecl -> LHsMakeError (Identifier HsConDecl)
identify (H.HsConDecl SrcLoc
_ HsName
name [HsBangType]
_) = HsName -> Either String HsName
forall a b. b -> Either a b
Right HsName
name
    identify (H.HsRecDecl SrcLoc
_ HsName
name [([HsName], HsBangType)]
_) = HsName -> Either String HsName
forall a b. b -> Either a b
Right HsName
name

-- | A function is identified by its patterns.
instance Identifiable H.HsMatch where
    type Identifier H.HsMatch = [H.HsPat]
    identify :: HsMatch -> LHsMakeError (Identifier HsMatch)
identify (H.HsMatch SrcLoc
_ HsName
_ [HsPat]
pats HsRhs
_ [HsDecl]
_) = [HsPat] -> Either String [HsPat]
forall a b. b -> Either a b
Right [HsPat]
pats

-- 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@.
flattenDecls :: H.HsDecl -> [H.HsDecl]
flattenDecls :: HsDecl -> [HsDecl]
flattenDecls (H.HsTypeSig SrcLoc
loc [HsName]
names HsQualType
ty)         = [SrcLoc -> [HsName] -> HsQualType -> HsDecl
H.HsTypeSig SrcLoc
loc [HsName
name] HsQualType
ty | HsName
name <- [HsName]
names]
flattenDecls (H.HsInfixDecl SrcLoc
loc HsAssoc
assoc Int
prec [HsOp]
ops) = [SrcLoc -> HsAssoc -> Int -> [HsOp] -> HsDecl
H.HsInfixDecl SrcLoc
loc HsAssoc
assoc Int
prec [HsOp
op] | HsOp
op <- [HsOp]
ops]
flattenDecls (H.HsPatBind SrcLoc
loc (H.HsPVar HsName
name) HsRhs
rhs [HsDecl]
wheres)
    = [[HsMatch] -> HsDecl
H.HsFunBind [SrcLoc -> HsName -> [HsPat] -> HsRhs -> [HsDecl] -> HsMatch
H.HsMatch SrcLoc
loc HsName
name [] HsRhs
rhs [HsDecl]
wheres]]
flattenDecls HsDecl
decl = [HsDecl
decl]

-- | To superimpose two Haskell modules, they must have the same name.
--   Then, their exports and imports are merged.
--   Declarations are flattened before they are merged (see 'flattenDecls'), 
instance Superimposable H.HsModule where
    H.HsModule SrcLoc
loc Module
mod1 Maybe [HsExportSpec]
exps1 [HsImportDecl]
imps1 [HsDecl]
decls1 --> :: HsModule -> HsModule -> LHsMakeError HsModule
--> H.HsModule SrcLoc
_ Module
mod2 Maybe [HsExportSpec]
exps2 [HsImportDecl]
imps2 [HsDecl]
decls2
        | Module
mod1 Module -> Module -> Bool
forall a. Eq a => a -> a -> Bool
== Module
mod2 = do
            Maybe [HsExportSpec]
exps  <- Maybe (Either String [HsExportSpec])
-> Either String (Maybe [HsExportSpec])
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 (([HsExportSpec] -> [HsExportSpec] -> Either String [HsExportSpec])
-> Maybe [HsExportSpec]
-> Maybe [HsExportSpec]
-> Maybe (Either String [HsExportSpec])
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 [HsExportSpec] -> [HsExportSpec] -> Either String [HsExportSpec]
forall a. Superimposable a => a -> a -> LHsMakeError a
(-->) Maybe [HsExportSpec]
exps1 Maybe [HsExportSpec]
exps2)
            [HsImportDecl]
imps  <- [HsImportDecl]
imps1 [HsImportDecl] -> [HsImportDecl] -> LHsMakeError [HsImportDecl]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [HsImportDecl]
imps2
            [HsDecl]
decls <- (HsDecl -> [HsDecl]) -> [HsDecl] -> [HsDecl]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap HsDecl -> [HsDecl]
flattenDecls [HsDecl]
decls1 [HsDecl] -> [HsDecl] -> LHsMakeError [HsDecl]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> (HsDecl -> [HsDecl]) -> [HsDecl] -> [HsDecl]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap HsDecl -> [HsDecl]
flattenDecls [HsDecl]
decls2
            HsModule -> LHsMakeError HsModule
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (SrcLoc
-> Module
-> Maybe [HsExportSpec]
-> [HsImportDecl]
-> [HsDecl]
-> HsModule
H.HsModule SrcLoc
loc Module
mod1 Maybe [HsExportSpec]
exps [HsImportDecl]
imps [HsDecl]
decls)
        | Bool
otherwise = String -> LHsMakeError HsModule
forall a b. a -> Either a b
Left (String
"Cannot merge differing modules: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Module -> String
forall a. Pretty a => a -> String
H.prettyPrint Module
mod1 String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" and " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Module -> String
forall a. Pretty a => a -> String
H.prettyPrint Module
mod2)

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

instance Superimposable H.HsExportSpec where
    x :: HsExportSpec
x@(H.HsEThingAll HsQName
_) --> :: HsExportSpec -> HsExportSpec -> LHsMakeError HsExportSpec
--> HsExportSpec
_                      = HsExportSpec -> LHsMakeError HsExportSpec
forall a b. b -> Either a b
Right HsExportSpec
x
    HsExportSpec
_ --> y :: HsExportSpec
y@(H.HsEThingAll HsQName
_)                      = HsExportSpec -> LHsMakeError HsExportSpec
forall a b. b -> Either a b
Right HsExportSpec
y
    H.HsEThingWith HsQName
name [HsCName]
xs --> H.HsEThingWith HsQName
_ [HsCName]
ys = HsQName -> [HsCName] -> HsExportSpec
H.HsEThingWith HsQName
name ([HsCName] -> HsExportSpec)
-> Either String [HsCName] -> LHsMakeError HsExportSpec
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ([HsCName]
xs [HsCName] -> [HsCName] -> Either String [HsCName]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [HsCName]
ys)
    H.HsEAbs HsQName
_ --> y :: HsExportSpec
y@(H.HsEThingWith HsQName
_ [HsCName]
_)          = HsExportSpec -> LHsMakeError HsExportSpec
forall a b. b -> Either a b
Right HsExportSpec
y
    HsExportSpec
x --> HsExportSpec
_                                        = HsExportSpec -> LHsMakeError HsExportSpec
forall a b. b -> Either a b
Right HsExportSpec
x

instance Identifiable H.HsExportSpec where
    type Identifier H.HsExportSpec = Either H.HsQName H.Module  -- an entity, or a whole module
    identify :: HsExportSpec -> LHsMakeError (Identifier HsExportSpec)
identify (H.HsEVar HsQName
name)            = Either HsQName Module -> Either String (Either HsQName Module)
forall a b. b -> Either a b
Right (HsQName -> Either HsQName Module
forall a b. a -> Either a b
Left  HsQName
name)
    identify (H.HsEAbs HsQName
name)            = Either HsQName Module -> Either String (Either HsQName Module)
forall a b. b -> Either a b
Right (HsQName -> Either HsQName Module
forall a b. a -> Either a b
Left  HsQName
name)
    identify (H.HsEThingAll HsQName
name)       = Either HsQName Module -> Either String (Either HsQName Module)
forall a b. b -> Either a b
Right (HsQName -> Either HsQName Module
forall a b. a -> Either a b
Left  HsQName
name)
    identify (H.HsEThingWith HsQName
name [HsCName]
_)    = Either HsQName Module -> Either String (Either HsQName Module)
forall a b. b -> Either a b
Right (HsQName -> Either HsQName Module
forall a b. a -> Either a b
Left  HsQName
name)
    identify (H.HsEModuleContents Module
modl) = Either HsQName Module -> Either String (Either HsQName Module)
forall a b. b -> Either a b
Right (Module -> Either HsQName Module
forall a b. b -> Either a b
Right Module
modl)

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

instance Superimposable H.HsImportDecl where
    HsImportDecl
x --> :: HsImportDecl -> HsImportDecl -> LHsMakeError HsImportDecl
--> HsImportDecl
y = do
        Maybe (Bool, [HsImportSpec])
specs <- Maybe (Either String (Bool, [HsImportSpec]))
-> Either String (Maybe (Bool, [HsImportSpec]))
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 (((Bool, [HsImportSpec])
 -> (Bool, [HsImportSpec]) -> Either String (Bool, [HsImportSpec]))
-> Maybe (Bool, [HsImportSpec])
-> Maybe (Bool, [HsImportSpec])
-> Maybe (Either String (Bool, [HsImportSpec]))
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 (Bool, [HsImportSpec])
-> (Bool, [HsImportSpec]) -> Either String (Bool, [HsImportSpec])
forall a. Superimposable a => a -> a -> LHsMakeError a
(-->) (HsImportDecl -> Maybe (Bool, [HsImportSpec])
H.importSpecs HsImportDecl
x) (HsImportDecl -> Maybe (Bool, [HsImportSpec])
H.importSpecs HsImportDecl
y))
        HsImportDecl -> LHsMakeError HsImportDecl
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (HsImportDecl
x { H.importSpecs = specs })

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

-- | A list of module imports.
--   @(False, xs)@ imports only @xs@, and @(True, xs)@ imports everything except @xs@.
type ImportList = (Bool, [H.HsImportSpec])

instance Superimposable ImportList where
    (Bool
False, [HsImportSpec]
xs) --> :: (Bool, [HsImportSpec])
-> (Bool, [HsImportSpec]) -> Either String (Bool, [HsImportSpec])
--> (Bool
False, [HsImportSpec]
ys) = ([HsImportSpec] -> (Bool, [HsImportSpec]))
-> Either String [HsImportSpec]
-> Either String (Bool, [HsImportSpec])
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
False) ([HsImportSpec]
xs [HsImportSpec] -> [HsImportSpec] -> Either String [HsImportSpec]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [HsImportSpec]
ys)
    (Bool
True,  [HsImportSpec]
xs) --> (Bool
True,  [HsImportSpec]
ys) = do
        [HsName]
xids <- (HsImportSpec -> Either String HsName)
-> [HsImportSpec] -> Either String [HsName]
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 HsImportSpec -> Either String HsName
HsImportSpec -> LHsMakeError (Identifier HsImportSpec)
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [HsImportSpec]
xs
        [HsName]
yids <- (HsImportSpec -> Either String HsName)
-> [HsImportSpec] -> Either String [HsName]
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 HsImportSpec -> Either String HsName
HsImportSpec -> LHsMakeError (Identifier HsImportSpec)
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [HsImportSpec]
ys
        (Bool, [HsImportSpec]) -> Either String (Bool, [HsImportSpec])
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool
True, [HsImportSpec
x | (HsImportSpec
x, HsName
xid) <- [HsImportSpec] -> [HsName] -> [(HsImportSpec, HsName)]
forall a b. [a] -> [b] -> [(a, b)]
zip [HsImportSpec]
xs [HsName]
xids, HsName
xid HsName -> [HsName] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [HsName]
yids])
    (Bool
False, [HsImportSpec]
xs) --> (Bool
True,  [HsImportSpec]
ys) = do
        [HsName]
xids <- (HsImportSpec -> Either String HsName)
-> [HsImportSpec] -> Either String [HsName]
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 HsImportSpec -> Either String HsName
HsImportSpec -> LHsMakeError (Identifier HsImportSpec)
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [HsImportSpec]
xs
        [HsName]
yids <- (HsImportSpec -> Either String HsName)
-> [HsImportSpec] -> Either String [HsName]
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 HsImportSpec -> Either String HsName
HsImportSpec -> LHsMakeError (Identifier HsImportSpec)
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [HsImportSpec]
ys
        (Bool, [HsImportSpec]) -> Either String (Bool, [HsImportSpec])
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool
True, [HsImportSpec
y | (HsImportSpec
y, HsName
yid) <- [HsImportSpec] -> [HsName] -> [(HsImportSpec, HsName)]
forall a b. [a] -> [b] -> [(a, b)]
zip [HsImportSpec]
ys [HsName]
yids, HsName
yid HsName -> [HsName] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [HsName]
xids])
    (Bool
True,  [HsImportSpec]
xs) --> (Bool
False, [HsImportSpec]
ys) = do
        [HsName]
xids <- (HsImportSpec -> Either String HsName)
-> [HsImportSpec] -> Either String [HsName]
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 HsImportSpec -> Either String HsName
HsImportSpec -> LHsMakeError (Identifier HsImportSpec)
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [HsImportSpec]
xs
        [HsName]
yids <- (HsImportSpec -> Either String HsName)
-> [HsImportSpec] -> Either String [HsName]
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 HsImportSpec -> Either String HsName
HsImportSpec -> LHsMakeError (Identifier HsImportSpec)
forall a. Identifiable a => a -> LHsMakeError (Identifier a)
identify [HsImportSpec]
ys
        (Bool, [HsImportSpec]) -> Either String (Bool, [HsImportSpec])
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool
True, [HsImportSpec
x | (HsImportSpec
x, HsName
xid) <- [HsImportSpec] -> [HsName] -> [(HsImportSpec, HsName)]
forall a b. [a] -> [b] -> [(a, b)]
zip [HsImportSpec]
xs [HsName]
xids, HsName
xid HsName -> [HsName] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [HsName]
yids])

instance Superimposable H.HsImportSpec where
    x :: HsImportSpec
x@(H.HsIThingAll HsName
_) --> :: HsImportSpec -> HsImportSpec -> LHsMakeError HsImportSpec
--> HsImportSpec
_                      = HsImportSpec -> LHsMakeError HsImportSpec
forall a b. b -> Either a b
Right HsImportSpec
x
    HsImportSpec
_ --> y :: HsImportSpec
y@(H.HsIThingAll HsName
_)                      = HsImportSpec -> LHsMakeError HsImportSpec
forall a b. b -> Either a b
Right HsImportSpec
y
    H.HsIThingWith HsName
name [HsCName]
xs --> H.HsIThingWith HsName
_ [HsCName]
ys = ([HsCName] -> HsImportSpec)
-> Either String [HsCName] -> LHsMakeError HsImportSpec
forall a b. (a -> b) -> Either String a -> Either String b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (HsName -> [HsCName] -> HsImportSpec
H.HsIThingWith HsName
name) ([HsCName]
xs [HsCName] -> [HsCName] -> Either String [HsCName]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [HsCName]
ys)
    H.HsIAbs HsName
_ --> y :: HsImportSpec
y@(H.HsIThingWith HsName
_ [HsCName]
_)          = HsImportSpec -> LHsMakeError HsImportSpec
forall a b. b -> Either a b
Right HsImportSpec
y
    HsImportSpec
x --> HsImportSpec
_                                        = HsImportSpec -> LHsMakeError HsImportSpec
forall a b. b -> Either a b
Right HsImportSpec
x

instance Identifiable H.HsImportSpec where
    type Identifier H.HsImportSpec = H.HsName
    identify :: HsImportSpec -> LHsMakeError (Identifier HsImportSpec)
identify (H.HsIVar HsName
name)         = HsName -> Either String HsName
forall a b. b -> Either a b
Right HsName
name
    identify (H.HsIAbs HsName
name)         = HsName -> Either String HsName
forall a b. b -> Either a b
Right HsName
name
    identify (H.HsIThingAll HsName
name)    = HsName -> Either String HsName
forall a b. b -> Either a b
Right HsName
name
    identify (H.HsIThingWith HsName
name [HsCName]
_) = HsName -> Either String HsName
forall a b. b -> Either a b
Right HsName
name

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

-- | Identifiers for Haskell declarations.
--
--   Only these declarations can be merged. Everything else (classes, instances, default
--   declarations, foreign declarations, pattern bindings) is rejected by 'identify'.
data DeclId
    = Value  H.HsName  -- ^ Functions and variables.
    | Sig    H.HsName  -- ^ Type signatures.
    | Type   H.HsName  -- ^ Type synonyms, datatype declarations, and @newtype@s.
    | Fixity H.HsName  -- ^ Fixity 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

-- | 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
--
--   See 'DeclId'.
instance Identifiable H.HsDecl where
    type Identifier H.HsDecl = DeclId
    identify :: HsDecl -> LHsMakeError (Identifier HsDecl)
identify (H.HsTypeDecl SrcLoc
_ HsName
name [HsName]
_ HsType
_)                  = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (HsName -> DeclId
Type HsName
name)
    identify (H.HsDataDecl SrcLoc
_ HsContext
_ HsName
name [HsName]
_ [HsConDecl]
_ [HsQName]
_)              = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (HsName -> DeclId
Type HsName
name)
    identify (H.HsNewTypeDecl SrcLoc
_ HsContext
_ HsName
name [HsName]
_ HsConDecl
_ [HsQName]
_)           = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (HsName -> DeclId
Type HsName
name)
    identify (H.HsFunBind (H.HsMatch SrcLoc
_ HsName
name [HsPat]
_ HsRhs
_ [HsDecl]
_ : [HsMatch]
_)) = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (HsName -> DeclId
Value HsName
name)
    identify (H.HsTypeSig SrcLoc
_ [HsName
name] HsQualType
_)                   = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (HsName -> DeclId
Sig HsName
name)
    identify (H.HsInfixDecl SrcLoc
_ HsAssoc
_ Int
_ [H.HsVarOp HsName
name])     = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (HsName -> DeclId
Fixity HsName
name)
    identify (H.HsInfixDecl SrcLoc
_ HsAssoc
_ Int
_ [H.HsConOp HsName
name])     = DeclId -> Either String DeclId
forall a b. b -> Either a b
Right (HsName -> DeclId
Fixity HsName
name)
    identify HsDecl
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 (HsDecl -> String
forall a. Pretty a => a -> String
H.prettyPrint HsDecl
decl)))

-- | Datatype declarations and functions are merged.
--   Type synonyms, @newtype@s, type signatures, and fixity declarations are overridden from the left.
instance Superimposable H.HsDecl where
    H.HsDataDecl SrcLoc
loc HsContext
ctx HsName
name [HsName]
vars [HsConDecl]
cons1 [HsQName]
derivs1 --> :: HsDecl -> HsDecl -> LHsMakeError HsDecl
--> H.HsDataDecl SrcLoc
_ HsContext
_ HsName
_ [HsName]
_ [HsConDecl]
cons2 [HsQName]
derivs2 = do
        [HsConDecl]
cons   <- [HsConDecl]
cons1 [HsConDecl] -> [HsConDecl] -> LHsMakeError [HsConDecl]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [HsConDecl]
cons2
        [HsQName]
derivs <- [HsQName]
derivs1 [HsQName] -> [HsQName] -> LHsMakeError [HsQName]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [HsQName]
derivs2
        HsDecl -> LHsMakeError HsDecl
forall a. a -> Either String a
forall (m :: * -> *) a. Monad m => a -> m a
return (SrcLoc
-> HsContext
-> HsName
-> [HsName]
-> [HsConDecl]
-> [HsQName]
-> HsDecl
H.HsDataDecl SrcLoc
loc HsContext
ctx HsName
name [HsName]
vars [HsConDecl]
cons [HsQName]
derivs)
    H.HsFunBind [HsMatch]
ms1 --> H.HsFunBind [HsMatch]
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 [[HsPat] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [HsPat]
pats | H.HsMatch SrcLoc
_ HsName
_ [HsPat]
pats HsRhs
_ [HsDecl]
_ <- [HsMatch]
ms1 [HsMatch] -> [HsMatch] -> [HsMatch]
forall a. [a] -> [a] -> [a]
++ [HsMatch]
ms2]) Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
1
        = ([HsMatch] -> HsDecl)
-> Either String [HsMatch] -> LHsMakeError HsDecl
forall a b. (a -> b) -> Either String a -> Either String b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap [HsMatch] -> HsDecl
H.HsFunBind ([HsMatch]
ms1 [HsMatch] -> [HsMatch] -> Either String [HsMatch]
forall a. Superimposable a => a -> a -> LHsMakeError a
--> [HsMatch]
ms2)
    HsDecl
x --> HsDecl
_ = HsDecl -> LHsMakeError HsDecl
forall a b. b -> Either a b
Right HsDecl
x

-------------------------------------------------------------------------------
-- 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
        HsModule
modl1 <- Maybe String -> Maybe String -> LHsMakeError HsModule
parse Maybe String
head1 Maybe String
foot1
        HsModule
modl2 <- Maybe String -> Maybe String -> LHsMakeError HsModule
parse Maybe String
head2 Maybe String
foot2
        H.HsModule SrcLoc
loc Module
name Maybe [HsExportSpec]
exps [HsImportDecl]
imps [HsDecl]
decls <- HsModule
modl1 HsModule -> HsModule -> LHsMakeError HsModule
forall a. Superimposable a => a -> a -> LHsMakeError a
--> HsModule
modl2
        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 Haskell module declaration and imports.
                            (String -> Maybe String
forall a. a -> Maybe a
Just (HsModule -> String
forall a. Pretty a => a -> String
H.prettyPrint (SrcLoc
-> Module
-> Maybe [HsExportSpec]
-> [HsImportDecl]
-> [HsDecl]
-> HsModule
H.HsModule SrcLoc
loc Module
name Maybe [HsExportSpec]
exps [HsImportDecl]
imps [])))
                            AbsSyn String
syn
                            -- The footer contains Haskell declarations.
                            (String -> Maybe String
forall a. a -> Maybe a
Just ([String] -> String
unlines ((HsDecl -> String) -> [HsDecl] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map HsDecl -> String
forall a. Pretty a => a -> String
H.prettyPrint [HsDecl]
decls))))
        where
            parse :: Maybe String -> Maybe String -> LHsMakeError HsModule
parse Maybe String
header Maybe String
footer = case String -> ParseResult HsModule
H.parseModule ([String] -> String
unlines ([Maybe String] -> [String]
forall a. [Maybe a] -> [a]
catMaybes [Maybe String
header, Maybe String
footer])) of
                H.ParseOk HsModule
modl      -> HsModule -> LHsMakeError HsModule
forall a b. b -> Either a b
Right HsModule
modl
                H.ParseFailed SrcLoc
_ String
msg -> String -> LHsMakeError HsModule
forall a b. a -> Either a b
Left (String
"Invalid Happy header or footer: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
msg)