{- This module was generated from data in the Kate syntax highlighting file makefile.xml, version 1.12,
   by  Per Wigren (wigren@home.se) -}

module Text.Highlighting.Kate.Syntax.Makefile ( highlight, parseExpression, syntaxName, syntaxExtensions ) where
import Text.Highlighting.Kate.Definitions
import Text.Highlighting.Kate.Common
import Text.ParserCombinators.Parsec
import Control.Monad (when)
import Data.Map (fromList)
import Data.Maybe (fromMaybe, maybeToList)

import qualified Data.Set as Set
-- | Full name of language.
syntaxName :: String
syntaxName = "Makefile"

-- | Filename extensions for this language.
syntaxExtensions :: String
syntaxExtensions = "GNUmakefile;Makefile;makefile;GNUmakefile.*;Makefile.*;makefile.*"

-- | Highlight source code using this syntax definition.
highlight :: String -> Either String [SourceLine]
highlight input =
  case runParser parseSource startingState "source" input of
    Left err     -> Left $ show err
    Right result -> Right result

-- | Parse an expression using appropriate local context.
parseExpression :: GenParser Char SyntaxState LabeledSource
parseExpression = do
  st <- getState
  let oldLang = synStLanguage st
  setState $ st { synStLanguage = "Makefile" }
  context <- currentContext <|> (pushContext "Normal" >> currentContext)
  result <- parseRules context
  updateState $ \st -> st { synStLanguage = oldLang }
  return result

parseSource = do 
  lineContents <- lookAhead wholeLine
  updateState $ \st -> st { synStCurrentLine = lineContents }
  result <- manyTill parseSourceLine eof
  return $ map normalizeHighlighting result

startingState = SyntaxState {synStContexts = fromList [("Makefile",["Normal"])], synStLanguage = "Makefile", synStCurrentLine = "", synStCharsParsedInLine = 0, synStPrevChar = '\n', synStCaseSensitive = True, synStKeywordCaseSensitive = True, synStCaptures = []}

parseSourceLine = manyTill parseExpressionInternal pEndLine

pEndLine = do
  lookAhead $ newline <|> (eof >> return '\n')
  context <- currentContext
  case context of
    "Normal" -> return () >> pHandleEndLine
    "String" -> (popContext) >> pEndLine
    "Value" -> (popContext) >> pEndLine
    "VarFromValue(" -> return () >> pHandleEndLine
    "VarFromValue{" -> return () >> pHandleEndLine
    "VarFromNormal(" -> return () >> pHandleEndLine
    "VarFromNormal{" -> return () >> pHandleEndLine
    "FunctionCall(" -> return () >> pHandleEndLine
    "FunctionCall{" -> return () >> pHandleEndLine
    "Commands" -> (popContext) >> pEndLine
    _ -> pHandleEndLine

withAttribute attr txt = do
  when (null txt) $ fail "Parser matched no text"
  let labs = attr : maybeToList (lookup attr styles)
  st <- getState
  let oldCharsParsed = synStCharsParsedInLine st
  let prevchar = if null txt then '\n' else last txt
  updateState $ \st -> st { synStCharsParsedInLine = oldCharsParsed + length txt, synStPrevChar = prevchar } 
  return (labs, txt)

styles = [("Keyword","kw"),("Comment","co"),("String","st"),("Variable","dt"),("Target","dv"),("Section","ot"),("Operator","ch"),("Commands","bn"),("Special","fl")]

parseExpressionInternal = do
  context <- currentContext
  parseRules context <|> (pDefault >>= withAttribute (fromMaybe "" $ lookup context defaultAttributes))

list_keywords = Set.fromList $ words $ "include define else endef endif ifdef ifeq ifndef ifneq"
list_functions = Set.fromList $ words $ "call subst patsubst strip findstring filter filter-out sort word wordlist words firstword lastword dir notdir suffix basename addsuffix addprefix join wildcard realpath abspath if or and foreach value eval origin flavor shell error warning info"

regex_'5b'5f'5cw'5cd'5d'2a'5cs'2a'28'3f'3d'3a'3d'7c'3d'7c'5c'2b'3d'7c'5c'3f'3d'29 = compileRegex "[_\\w\\d]*\\s*(?=:=|=|\\+=|\\?=)"
regex_'5b'5f'5cw'5cd'2d'5d'2a'5cs'2a'3a = compileRegex "[_\\w\\d-]*\\s*:"
regex_'5b'2e'5d'2e'2a'3a = compileRegex "[.].*:"
regex_'23'2e'2a'24 = compileRegex "#.*$"
regex_'40'5b'2d'5f'5cd'5cw'5d'2a'40 = compileRegex "@[-_\\d\\w]*@"
regex_'5b'5f'5cw'2d'5d'2a'5cb = compileRegex "[_\\w-]*\\b"

defaultAttributes = [("Normal","Normal Text"),("String","String"),("Value","String"),("VarFromValue(","Variable"),("VarFromValue{","Variable"),("VarFromNormal(","Variable"),("VarFromNormal{","Variable"),("FunctionCall(","String"),("FunctionCall{","String"),("Commands","Normal Text")]

parseRules "Normal" = 
  do (attr, result) <- (((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_keywords >>= withAttribute "Keyword"))
                        <|>
                        ((pRegExpr regex_'5b'5f'5cw'5cd'5d'2a'5cs'2a'28'3f'3d'3a'3d'7c'3d'7c'5c'2b'3d'7c'5c'3f'3d'29 >>= withAttribute "Variable") >>~ pushContext "Value")
                        <|>
                        ((pFirstNonSpace >> pRegExpr regex_'5b'5f'5cw'5cd'2d'5d'2a'5cs'2a'3a >>= withAttribute "Target"))
                        <|>
                        ((pColumn 0 >> pRegExpr regex_'5b'2e'5d'2e'2a'3a >>= withAttribute "Section"))
                        <|>
                        ((pDetectChar False '"' >>= withAttribute "String") >>~ pushContext "String")
                        <|>
                        ((pDetect2Chars False '$' '{' >>= withAttribute "Operator") >>~ pushContext "VarFromNormal{")
                        <|>
                        ((pDetect2Chars False '$' '(' >>= withAttribute "Operator") >>~ pushContext "VarFromNormal(")
                        <|>
                        ((pDetect2Chars False '\\' '#' >>= withAttribute "Special"))
                        <|>
                        ((pDetect2Chars False '\\' '\\' >>= withAttribute "Special"))
                        <|>
                        ((pAnyChar "+*=%$():\\;" >>= withAttribute "Operator"))
                        <|>
                        ((pFirstNonSpace >> pAnyChar "@-" >>= withAttribute "Operator") >>~ pushContext "Commands")
                        <|>
                        ((pRegExpr regex_'23'2e'2a'24 >>= withAttribute "Comment")))
     return (attr, result)

parseRules "String" = 
  do (attr, result) <- (((pLineContinue >>= withAttribute "String"))
                        <|>
                        ((pDetectChar False '"' >>= withAttribute "String") >>~ (popContext)))
     return (attr, result)

parseRules "Value" = 
  do (attr, result) <- (((pLineContinue >>= withAttribute "Operator"))
                        <|>
                        ((pDetect2Chars False '$' '{' >>= withAttribute "Operator") >>~ pushContext "VarFromValue{")
                        <|>
                        ((pDetect2Chars False '$' '(' >>= withAttribute "Operator") >>~ pushContext "VarFromValue(")
                        <|>
                        ((pRegExpr regex_'40'5b'2d'5f'5cd'5cw'5d'2a'40 >>= withAttribute "Special") >>~ (popContext))
                        <|>
                        ((pDetectChar False ';' >>= withAttribute "Operator") >>~ (popContext)))
     return (attr, result)

parseRules "VarFromValue(" = 
  do (attr, result) <- ((pDetectChar False ')' >>= withAttribute "Operator") >>~ (popContext))
     return (attr, result)

parseRules "VarFromValue{" = 
  do (attr, result) <- ((pDetectChar False '}' >>= withAttribute "Operator") >>~ (popContext))
     return (attr, result)

parseRules "VarFromNormal(" = 
  do (attr, result) <- (((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_functions >>= withAttribute "Keyword") >>~ pushContext "FunctionCall(")
                        <|>
                        ((pDetectChar False ')' >>= withAttribute "Operator") >>~ (popContext)))
     return (attr, result)

parseRules "VarFromNormal{" = 
  do (attr, result) <- (((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_functions >>= withAttribute "Keyword") >>~ pushContext "FunctionCall{")
                        <|>
                        ((pDetectChar False '}' >>= withAttribute "Comment") >>~ (popContext)))
     return (attr, result)

parseRules "FunctionCall(" = 
  do (attr, result) <- (((pDetect2Chars False '$' '{' >>= withAttribute "Operator") >>~ pushContext "VarFromNormal{")
                        <|>
                        ((pDetect2Chars False '$' '(' >>= withAttribute "Operator") >>~ pushContext "VarFromNormal(")
                        <|>
                        ((pDetectChar False ')' >>= withAttribute "Operator") >>~ (popContext >> popContext)))
     return (attr, result)

parseRules "FunctionCall{" = 
  do (attr, result) <- (((pDetect2Chars False '$' '{' >>= withAttribute "Operator") >>~ pushContext "VarFromNormal{")
                        <|>
                        ((pDetect2Chars False '$' '(' >>= withAttribute "Operator") >>~ pushContext "VarFromNormal(")
                        <|>
                        ((pDetectChar False '}' >>= withAttribute "Operator") >>~ (popContext >> popContext)))
     return (attr, result)

parseRules "Commands" = 
  do (attr, result) <- (((pDetect2Chars False '$' '{' >>= withAttribute "Operator") >>~ pushContext "VarFromNormal{")
                        <|>
                        ((pDetect2Chars False '$' '(' >>= withAttribute "Operator") >>~ pushContext "VarFromNormal(")
                        <|>
                        ((pRegExpr regex_'5b'5f'5cw'2d'5d'2a'5cb >>= withAttribute "Commands") >>~ (popContext)))
     return (attr, result)

parseRules "" = parseRules "Normal"

parseRules x = fail $ "Unknown context" ++ x