{- This module was generated from data in the Kate syntax highlighting file prolog.xml, version 1.04,
   by   -}

module Text.Highlighting.Kate.Syntax.Prolog ( 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 = "Prolog"

-- | Filename extensions for this language.
syntaxExtensions :: String
syntaxExtensions = "*.prolog"

-- | 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 = "Prolog" }
  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 [("Prolog",["normal"])], synStLanguage = "Prolog", synStCurrentLine = "", synStCharsParsedInLine = 0, synStPrevChar = '\n', synStCaseSensitive = True, synStKeywordCaseSensitive = True, synStCaptures = []}

parseSourceLine = manyTill parseExpressionInternal pEndLine

pEndLine = do
  newline <|> (eof >> return '\n')
  context <- currentContext
  case context of
    "normal" -> return ()
    "comment" -> (popContext >> return ())
    "string" -> return ()
    "string2" -> return ()
    "comment region" -> return ()
    _ -> return ()
  lineContents <- lookAhead wholeLine
  updateState $ \st -> st { synStCurrentLine = lineContents, synStCharsParsedInLine = 0, synStPrevChar = '\n' }

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"),("Data Type","dt"),("Comment","co"),("Integer","dv"),("String","st"),("Variable","ot"),("Arithmetic","kw")]

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

list_keywordl = Set.fromList $ words $ "abstract align as and class clauses constants database determ domains elsedef endclass enddef erroneous facts failure global goal if ifdef ifndef implement include language multi nocopy nondeterm object or procedure protected predicates reference single static struct this"
list_keywordu = Set.fromList $ words $ "ABSTRACT ALIGN AS AND CLASS CLAUSES CONSTANTS DATABASE DETERM DOMAINS ELSEDEF ENDCLASS ENDDEF ERRONEOUS FACTS FAILURE GLOBAL GOAL IF IFDEF IFNDEF IMPLEMENT INCLUDE LANGUAGE MULTI NOCOPY NONDETERM OBJECT OR PROCEDURE PROTECTED PREDICATES REFERENCE SINGLE STATIC STRUCT THIS"
list_special = Set.fromList $ words $ "assert asserta assertz bound chain_inserta chain_insertafter chain_insertz chain_terms consult db_btrees db_chains fail findall format free msgrecv msgsend nl not readterm ref_term retract retractall save term_bin term_replace term_str trap write writef"
list_compiler = Set.fromList $ words $ "bgidriver bgifont check_determ code config diagnostics error errorlevel heap gstacksize nobreak nowarnings printermenu project"
list_arith = Set.fromList $ words $ "mod div abs exp ln log sqrt round trunc val cos sin tan arctan random randominit"
list_basetype = Set.fromList $ words $ "char real string symbol byte sbyte short ushort word integer unsigned dword long ulong binary ref"
list_keywords = Set.fromList $ words $ "true false"

regex_'5bA'2dZ'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a = compileRegex "[A-Z_][A-Za-z0-9_]*"
regex_'5ba'2dz'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a = compileRegex "[a-z][A-Za-z0-9_]*"

defaultAttributes = [("normal","Symbol"),("comment","Comment"),("string","String"),("string2","String"),("comment region","Comment")]

parseRules "normal" = 
  do (attr, result) <- (((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_keywordl >>= withAttribute "Keyword"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_keywordu >>= withAttribute "Keyword"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_arith >>= withAttribute "Arithmetic"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_compiler >>= withAttribute "Keyword"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_special >>= withAttribute "Keyword"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_basetype >>= withAttribute "Data Type"))
                        <|>
                        ((pRegExpr regex_'5bA'2dZ'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a >>= withAttribute "Variable"))
                        <|>
                        ((pRegExpr regex_'5ba'2dz'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a >>= withAttribute "Identifier"))
                        <|>
                        ((pDetectChar False '%' >>= withAttribute "Comment") >>~ pushContext "comment")
                        <|>
                        ((pDetect2Chars False '/' '*' >>= withAttribute "Comment") >>~ pushContext "comment region")
                        <|>
                        ((pInt >>= withAttribute "Integer"))
                        <|>
                        ((pDetectChar False '"' >>= withAttribute "String") >>~ pushContext "string")
                        <|>
                        ((pDetectChar False '\'' >>= withAttribute "String") >>~ pushContext "string2")
                        <|>
                        ((pAnyChar "~!^*()-+=[]|\\:;,./?&<>" >>= withAttribute "Symbol")))
     return (attr, result)

parseRules "comment" = 
  pzero

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

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

parseRules "comment region" = 
  do (attr, result) <- ((pDetect2Chars False '*' '/' >>= withAttribute "Comment") >>~ (popContext >> return ()))
     return (attr, result)

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