{-# LANGUAGE OverloadedStrings #-}

module BNFC.Backend.Common.Makefile where

import Prelude hiding ((<>))

import BNFC.Options (SharedOptions(..))
import BNFC.Backend.Base (mkfile, Backend)
import BNFC.PrettyPrint

-- | Creates a Makefile rule.
--
-- >>> mkRule "main" ["file1","file2"] ["do something"]
-- main : file1 file2
-- 	do something
-- <BLANKLINE>
--
-- >>> mkRule "main" ["program.exe"] []
-- main : program.exe
-- <BLANKLINE>
--
mkRule :: String   -- ^ The target name.
       -> [String] -- ^ Dependencies.
       -> [String] -- ^ Recipe.
       -> Doc
mkRule :: FilePath -> [FilePath] -> [FilePath] -> Doc
mkRule FilePath
target [FilePath]
deps [FilePath]
recipe = [Doc] -> Doc
vcat ([Doc] -> Doc) -> ([[Doc]] -> [Doc]) -> [[Doc]] -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [[Doc]] -> [Doc]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([[Doc]] -> Doc) -> [[Doc]] -> Doc
forall a b. (a -> b) -> a -> b
$
    [ [ FilePath -> Doc
text FilePath
target Doc -> Doc -> Doc
<+> Doc
":" Doc -> Doc -> Doc
<+> [Doc] -> Doc
hsep ((FilePath -> Doc) -> [FilePath] -> [Doc]
forall a b. (a -> b) -> [a] -> [b]
map FilePath -> Doc
text [FilePath]
deps) ]
    , (FilePath -> Doc) -> [FilePath] -> [Doc]
forall a b. (a -> b) -> [a] -> [b]
map ((Doc
"\t" Doc -> Doc -> Doc
<>) (Doc -> Doc) -> (FilePath -> Doc) -> FilePath -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. FilePath -> Doc
text) [FilePath]
recipe
    , [ Doc
"" ]
    ]

-- | Variable assignment.
--
-- >>> mkVar "FOO" "bar"
-- FOO=bar
--
mkVar :: String -> String -> Doc
mkVar :: FilePath -> FilePath -> Doc
mkVar FilePath
n FilePath
v = FilePath -> Doc
text FilePath
n Doc -> Doc -> Doc
<> Doc
"=" Doc -> Doc -> Doc
<> FilePath -> Doc
text FilePath
v

-- UNUSED:
-- -- | Variable referencing.
-- --
-- -- >>> mkRefVar "FOO"
-- -- ${FOO}
-- --
-- mkRefVar :: String -> Doc
-- mkRefVar m  = case m of
--     "" -> empty
--     _ -> text $ refVar m


-- | Variable referencing.
--
-- >>> refVar "FOO"
-- "${FOO}"
--
refVar :: String -> String
refVar :: FilePath -> FilePath
refVar FilePath
m = FilePath
"${" FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
m FilePath -> FilePath -> FilePath
forall a. [a] -> [a] -> [a]
++ FilePath
"}"

-- | Create the Makefile file using the name specified in the option record.
--
mkMakefile :: SharedOptions -> (String -> Doc) -> Backend
mkMakefile :: SharedOptions -> (FilePath -> Doc) -> Backend
mkMakefile Options{make :: SharedOptions -> Maybe FilePath
make = Just FilePath
m } FilePath -> Doc
mkContent = FilePath -> Doc -> Backend
forall c. FileContent c => FilePath -> c -> Backend
mkfile FilePath
m (FilePath -> Doc
mkContent FilePath
m)
mkMakefile Options{make :: SharedOptions -> Maybe FilePath
make = Maybe FilePath
Nothing} FilePath -> Doc
_         = () -> Backend
forall (m :: * -> *) a. Monad m => a -> m a
return ()