{-# 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 :: String -> [String] -> [String] -> Doc
mkRule String
target [String]
deps [String]
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
$
    [ [ String -> Doc
text String
target Doc -> Doc -> Doc
<+> Doc
":" Doc -> Doc -> Doc
<+> [Doc] -> Doc
hsep ((String -> Doc) -> [String] -> [Doc]
forall a b. (a -> b) -> [a] -> [b]
map String -> Doc
text [String]
deps) ]
    , (String -> Doc) -> [String] -> [Doc]
forall a b. (a -> b) -> [a] -> [b]
map ((Doc
"\t" Doc -> Doc -> Doc
<>) (Doc -> Doc) -> (String -> Doc) -> String -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Doc
text) [String]
recipe
    , [ Doc
"" ]
    ]

-- | Variable assignment.
--
-- >>> mkVar "FOO" "bar"
-- FOO=bar
--
mkVar :: String -> String -> Doc
mkVar :: String -> String -> Doc
mkVar String
n String
v = String -> Doc
text String
n Doc -> Doc -> Doc
<> Doc
"=" Doc -> Doc -> Doc
<> String -> Doc
text String
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 :: String -> String
refVar String
m = String
"${" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
m String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"}"

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