{- This module was generated from data in the Kate syntax highlighting file coffeescript.xml, version 1.1,
   by  Max Shawabkeh (max99x@gmail.com) -}

module Text.Highlighting.Kate.Syntax.Coffeescript ( highlight, parseExpression, syntaxName, syntaxExtensions ) where
import Text.Highlighting.Kate.Definitions
import Text.Highlighting.Kate.Common
import qualified Text.Highlighting.Kate.Syntax.Alert_indent
import qualified Text.Highlighting.Kate.Syntax.Javascript
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 = "CofeeScript"

-- | Filename extensions for this language.
syntaxExtensions :: String
syntaxExtensions = "Cakefile;*.coffee;*.coco"

-- | 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 = "CofeeScript" }
  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 [("CofeeScript",["Normal"])], synStLanguage = "CofeeScript", 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
    "Multiline Regex" -> return () >> pHandleEndLine
    "Class" -> return () >> pHandleEndLine
    "Comment" -> (popContext) >> pEndLine
    "Multiline Comment" -> return () >> pHandleEndLine
    "String" -> return () >> pHandleEndLine
    "Rich String" -> return () >> pHandleEndLine
    "Heredoc" -> return () >> pHandleEndLine
    "Rich Heredoc" -> return () >> pHandleEndLine
    "Embedding" -> return () >> pHandleEndLine
    "Javascript" -> return () >> pHandleEndLine
    _ -> 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"),("Function","fu"),("Decimal","dv"),("Float","fl"),("Oct","bn"),("Hex","bn"),("String","st"),("Comment","co"),("Symbol","kw"),("Embedding","ch"),("Accessor","dt"),("Class","dt"),("Javascript","al"),("Regex","st"),("Reserved","al"),("Value Keywords","ot"),("Globals","ot")]

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

list_value'5fkeywords = Set.fromList $ words $ "false true yes no on off undefined null NaN Infinity"
list_keywords = Set.fromList $ words $ "return break continue throw for while until loop if else unless switch when then and or in of by is isnt not typeof delete where super try catch finally try catch finally constructor"
list_class'5fkeywords = Set.fromList $ words $ "class extends new instanceof"
list_reserved = Set.fromList $ words $ "case default function var void with const let enum export import native __hasProp __extends __slice __bind __indexOf"
list_globals = Set.fromList $ words $ "Object Number Boolean Array String RegExp Function Date Math eval setInterval clearInterval setTimeout clearTimeout isFinite isNaN parseFloat parseInt escape unescape console encodeURI encodeURIComponent decodeURI decodeURIComponent"
list_browser'5fglobals = Set.fromList $ words $ "window document navigator location history screen alert prompt"
list_nodejs'5fglobals = Set.fromList $ words $ "process GLOBAL require exports"

regex_'28'40'5b'5f'24a'2dzA'2dZ'5d'5b'24'5cw'5d'2b'7c'5cbthis'29'5cb = compileRegex "(@[_$a-zA-Z][$\\w]+|\\bthis)\\b"
regex_'28'5c'28'28'5c'27'5b'5e'27'5d'2a'27'7c'22'5b'5e'22'5d'2a'22'7c'5b'5e'28'29'5d'29'2a'5c'29'29'3f'5cs'2a'28'2d'7c'3d'29'3e = compileRegex "(\\((\\'[^']*'|\"[^\"]*\"|[^()])*\\))?\\s*(-|=)>"
regex_'5b'5f'24a'2dz'5d'5b'24'5cw'5d'2b'5cb = compileRegex "[_$a-z][$\\w]+\\b"
regex_'2f'2f'2f = compileRegex "///"
regex_'2f'28'5b'5e'2f'5c'5c'5cr'5cn'5d'7c'5c'5c'2e'29'2a'2f'5bmig'5d'7b0'2c3'7d = compileRegex "/([^/\\\\\\r\\n]|\\\\.)*/[mig]{0,3}"
regex_'2f'2f'2f'5bmig'5d'7b0'2c3'7d = compileRegex "///[mig]{0,3}"
regex_'5b'40'24'3a'2e'5cw'5c'5b'5c'5d'5d'2b = compileRegex "[@$:.\\w\\[\\]]+"

defaultAttributes = [("Normal","Normal"),("Multiline Regex","Regex"),("Class","Normal"),("Comment","Comment"),("Multiline Comment","Comment"),("String","String"),("Rich String","String"),("Heredoc","String"),("Rich Heredoc","String"),("Embedding","Normal"),("Javascript","Javascript")]

parseRules "Normal" = 
  do (attr, result) <- (((pDetectSpaces >>= withAttribute "Normal"))
                        <|>
                        ((pFloat >>= withAttribute "Float"))
                        <|>
                        ((pInt >>= withAttribute "Decimal"))
                        <|>
                        ((pHlCOct >>= withAttribute "Oct"))
                        <|>
                        ((pHlCHex >>= withAttribute "Hex"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\#'" list_keywords >>= withAttribute "Keyword"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\#'" list_class'5fkeywords >>= withAttribute "Keyword") >>~ pushContext "Class")
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\#'" list_value'5fkeywords >>= withAttribute "Value Keywords"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\#'" list_reserved >>= withAttribute "Reserved"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\#'" list_globals >>= withAttribute "Globals"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\#'" list_browser'5fglobals >>= withAttribute "Browser Globals"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\#'" list_nodejs'5fglobals >>= withAttribute "Node.js Globals"))
                        <|>
                        ((pRegExpr regex_'28'40'5b'5f'24a'2dzA'2dZ'5d'5b'24'5cw'5d'2b'7c'5cbthis'29'5cb >>= withAttribute "Accessor"))
                        <|>
                        ((pRegExpr regex_'28'5c'28'28'5c'27'5b'5e'27'5d'2a'27'7c'22'5b'5e'22'5d'2a'22'7c'5b'5e'28'29'5d'29'2a'5c'29'29'3f'5cs'2a'28'2d'7c'3d'29'3e >>= withAttribute "Function"))
                        <|>
                        ((pRegExpr regex_'5b'5f'24a'2dz'5d'5b'24'5cw'5d'2b'5cb >>= withAttribute "Identifier"))
                        <|>
                        ((pString False "'''" >>= withAttribute "String") >>~ pushContext "Heredoc")
                        <|>
                        ((pString False "\"\"\"" >>= withAttribute "String") >>~ pushContext "Rich Heredoc")
                        <|>
                        ((pDetectChar False '\'' >>= withAttribute "String") >>~ pushContext "String")
                        <|>
                        ((pDetectChar False '"' >>= withAttribute "String") >>~ pushContext "Rich String")
                        <|>
                        ((pDetectChar False '`' >>= withAttribute "Javascript") >>~ pushContext "Javascript")
                        <|>
                        ((pString False "###" >>= withAttribute "Comment") >>~ pushContext "Multiline Comment")
                        <|>
                        ((pDetectChar False '#' >>= withAttribute "Comment") >>~ pushContext "Comment")
                        <|>
                        ((pRegExpr regex_'2f'2f'2f >>= withAttribute "Regex") >>~ pushContext "Multiline Regex")
                        <|>
                        ((pRegExpr regex_'2f'28'5b'5e'2f'5c'5c'5cr'5cn'5d'7c'5c'5c'2e'29'2a'2f'5bmig'5d'7b0'2c3'7d >>= withAttribute "Regex"))
                        <|>
                        ((pAnyChar "():!%&+,-/.*<=>?[]|~^;{}" >>= withAttribute "Symbol")))
     return (attr, result)

parseRules "Multiline Regex" = 
  do (attr, result) <- (((pHlCStringChar >>= withAttribute "Regex"))
                        <|>
                        ((pDetectChar False '#' >>= withAttribute "Comment") >>~ pushContext "Comment")
                        <|>
                        ((pRegExpr regex_'2f'2f'2f'5bmig'5d'7b0'2c3'7d >>= withAttribute "Regex") >>~ (popContext)))
     return (attr, result)

parseRules "Class" = 
  do (attr, result) <- (((pDetectSpaces >>= withAttribute "Normal"))
                        <|>
                        ((pRegExpr regex_'5b'40'24'3a'2e'5cw'5c'5b'5c'5d'5d'2b >>= withAttribute "Class") >>~ (popContext)))
     return (attr, result)

parseRules "Comment" = 
  do (attr, result) <- ((Text.Highlighting.Kate.Syntax.Alert_indent.parseExpression))
     return (attr, result)

parseRules "Multiline Comment" = 
  do (attr, result) <- (((pString False "###" >>= withAttribute "Comment") >>~ (popContext))
                        <|>
                        ((Text.Highlighting.Kate.Syntax.Alert_indent.parseExpression)))
     return (attr, result)

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

parseRules "Rich String" = 
  do (attr, result) <- (((pHlCStringChar >>= withAttribute "String"))
                        <|>
                        ((pDetect2Chars False '#' '{' >>= withAttribute "Embedding") >>~ pushContext "Embedding")
                        <|>
                        ((pDetectChar False '"' >>= withAttribute "String") >>~ (popContext)))
     return (attr, result)

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

parseRules "Rich Heredoc" = 
  do (attr, result) <- (((pHlCStringChar >>= withAttribute "String"))
                        <|>
                        ((pDetect2Chars False '#' '{' >>= withAttribute "Embedding") >>~ pushContext "Embedding")
                        <|>
                        ((pString False "\"\"\"" >>= withAttribute "String") >>~ (popContext)))
     return (attr, result)

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

parseRules "Javascript" = 
  do (attr, result) <- (((pDetectChar False '`' >>= withAttribute "Javascript") >>~ (popContext))
                        <|>
                        ((Text.Highlighting.Kate.Syntax.Javascript.parseExpression)))
     return (attr, result)

parseRules "" = parseRules "Normal"

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