{- This module was generated from data in the Kate syntax highlighting file actionscript.xml, version 1.0,
   by  Aaron Miller (armantic101@gmail.com) -}

module Text.Highlighting.Kate.Syntax.Actionscript ( highlight, parseExpression, syntaxName, syntaxExtensions ) where
import Text.Highlighting.Kate.Definitions
import Text.Highlighting.Kate.Common
import qualified Text.Highlighting.Kate.Syntax.Javadoc
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 = "ActionScript 2.0"

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

-- | 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 = "ActionScript 2.0" }
  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 [("ActionScript 2.0",["Normal"])], synStLanguage = "ActionScript 2.0", 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
    "Member" -> (popContext) >> pEndLine
    "StaticImports" -> (popContext) >> pEndLine
    "Imports" -> (popContext) >> pEndLine
    "Commentar 1" -> (popContext) >> pEndLine
    "Commentar 2" -> 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"),("StaticImports","kw"),("Imports","kw"),("Data Type","dt"),("Decimal","dv"),("Octal","bn"),("Hex","bn"),("Float","fl"),("Char","ch"),("String","st"),("String Char","ch"),("Comment","co")]

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

list_properties = Set.fromList $ words $ "_accProps _focusrect _global _highquality _level _parent _quality _root _soundbuftime maxscroll scroll this"
list_global'5ffunctions = Set.fromList $ words $ "asfunction call chr clearInterval duplicateMovieClip escape eval fscommand getProperty getTimer getURL getVersion gotoAndPlay gotoAndStop ifFrameLoaded int isFinite isNaN length loadMovie loadMovieNum loadVariables loadVariablesNum mbchr mblength mbord mbsubstring nextFrame nextScene on onClipEvent ord parseFloat parseInt play prevFrame prevScene print printAsBitmap printAsBitmapNum printNum random removeMovieClip setInterval setProperty showRedrawRegions startDrag stop stopAllSounds stopDrag substring targetPath tellTarget toggleHighQuality trace typeof unescape unloadMovie unloadMovieNum updateAfterEvent"
list_classes = Set.fromList $ words $ "Accessibility Accordion Alert Binding Button Camera CellRenderer CheckBox Collection Color ComboBox ComponentMixins ContextMenu ContextMenuItem CustomActions CustomFormatter CustomValidator DataGrid DataHolder DataProvider DataSet DataType Date DateChooser DateField Delta DeltaItem DeltaPacket DepthManager EndPoint Error FaultEvent FocusManager Form Function Iterator Key Label List LoadVars Loader LocalConnection Log Math Media Menu MenuBar Microphone Mouse MovieClip MovieClipLoader NetConnection NetStream Number NumericStepper PendingCall PopUpManager PrintJob ProgressBar RDBMSResolver RadioButton RelayResponder SOAPCall Screen ScrollPane Selection SharedObject Slide Sound Stage StyleManager System TextArea TextField TextFormat TextInput TextSnapshot TransferObject Tree TreeDataProvider TypedValue UIComponent UIEventDispatcher UIObject Video WebService WebServiceConnector Window XML XMLConnector XUpdateResolver"
list_keywords = Set.fromList $ words $ "add and break case catch class continue default delete do dynamic else eq extends finally for function ge get gt if implements import in instanceof interface intrinsic le lt ne new not or private public return set static switch throw try var void while with"
list_const = Set.fromList $ words $ "false Infinity -Infinity NaN newline null true undefined"
list_types = Set.fromList $ words $ "Array Boolean Number Object String Void"

regex_'2f'2f'5cs'2aBEGIN'2e'2a'24 = compileRegex "//\\s*BEGIN.*$"
regex_'2f'2f'5cs'2aEND'2e'2a'24 = compileRegex "//\\s*END.*$"
regex_'5c'2e'7b3'2c3'7d'5cs'2b = compileRegex "\\.{3,3}\\s+"
regex_'5cb'28import'5cs'2bstatic'29'5cb = compileRegex "\\b(import\\s+static)\\b"
regex_'5cb'28package'7cimport'29'5cb = compileRegex "\\b(package|import)\\b"
regex_'5cb'5b'5f'5cw'5d'5b'5f'5cw'5cd'5d'2a'28'3f'3d'5b'5cs'5d'2a'28'2f'5c'2a'5cs'2a'5cd'2b'5cs'2a'5c'2a'2f'5cs'2a'29'3f'5b'28'5d'29 = compileRegex "\\b[_\\w][_\\w\\d]*(?=[\\s]*(/\\*\\s*\\d+\\s*\\*/\\s*)?[(])"
regex_'5b'2e'5d'7b1'2c1'7d = compileRegex "[.]{1,1}"
regex_'5cb'5b'5fa'2dzA'2dZ'5d'5cw'2a'28'3f'3d'5b'5cs'5d'2a'29 = compileRegex "\\b[_a-zA-Z]\\w*(?=[\\s]*)"
regex_'5cs'2a'2e'2a'24 = compileRegex "\\s*.*$"

defaultAttributes = [("Normal","Normal Text"),("String","String"),("Member","Normal Text"),("StaticImports","Normal Text"),("Imports","Normal Text"),("Commentar 1","Comment"),("Commentar 2","Comment")]

parseRules "Normal" = 
  do (attr, result) <- (((Text.Highlighting.Kate.Syntax.Javadoc.parseExpression))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_properties >>= withAttribute "Properties"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_global'5ffunctions >>= withAttribute "Global Functions"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_classes >>= withAttribute "Classes"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_keywords >>= withAttribute "Keyword"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_const >>= withAttribute "Constants"))
                        <|>
                        ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_types >>= withAttribute "Data Type"))
                        <|>
                        (withChildren (pFloat >>= withAttribute "Float") ((pAnyChar "fF" >>= withAttribute "Float")))
                        <|>
                        ((pHlCOct >>= withAttribute "Octal"))
                        <|>
                        ((pHlCHex >>= withAttribute "Hex"))
                        <|>
                        (withChildren (pInt >>= withAttribute "Decimal") (((pString False "ULL" >>= withAttribute "Decimal"))
                                                                          <|>
                                                                          ((pString False "LUL" >>= withAttribute "Decimal"))
                                                                          <|>
                                                                          ((pString False "LLU" >>= withAttribute "Decimal"))
                                                                          <|>
                                                                          ((pString False "UL" >>= withAttribute "Decimal"))
                                                                          <|>
                                                                          ((pString False "LU" >>= withAttribute "Decimal"))
                                                                          <|>
                                                                          ((pString False "LL" >>= withAttribute "Decimal"))
                                                                          <|>
                                                                          ((pString False "U" >>= withAttribute "Decimal"))
                                                                          <|>
                                                                          ((pString False "L" >>= withAttribute "Decimal"))))
                        <|>
                        ((pHlCChar >>= withAttribute "Char"))
                        <|>
                        ((pRegExpr regex_'2f'2f'5cs'2aBEGIN'2e'2a'24 >>= withAttribute "Decimal"))
                        <|>
                        ((pRegExpr regex_'2f'2f'5cs'2aEND'2e'2a'24 >>= withAttribute "Decimal"))
                        <|>
                        ((pDetectChar False '"' >>= withAttribute "String") >>~ pushContext "String")
                        <|>
                        ((pDetect2Chars False '/' '/' >>= withAttribute "Comment") >>~ pushContext "Commentar 1")
                        <|>
                        ((pDetect2Chars False '/' '*' >>= withAttribute "Comment") >>~ pushContext "Commentar 2")
                        <|>
                        ((pDetectChar False '{' >>= withAttribute "Symbol"))
                        <|>
                        ((pDetectChar False '}' >>= withAttribute "Symbol"))
                        <|>
                        ((pRegExpr regex_'5c'2e'7b3'2c3'7d'5cs'2b >>= withAttribute "Keyword"))
                        <|>
                        ((pRegExpr regex_'5cb'28import'5cs'2bstatic'29'5cb >>= withAttribute "Keyword") >>~ pushContext "StaticImports")
                        <|>
                        ((pRegExpr regex_'5cb'28package'7cimport'29'5cb >>= withAttribute "Keyword") >>~ pushContext "Imports")
                        <|>
                        ((pRegExpr regex_'5cb'5b'5f'5cw'5d'5b'5f'5cw'5cd'5d'2a'28'3f'3d'5b'5cs'5d'2a'28'2f'5c'2a'5cs'2a'5cd'2b'5cs'2a'5c'2a'2f'5cs'2a'29'3f'5b'28'5d'29 >>= withAttribute "Function"))
                        <|>
                        ((pRegExpr regex_'5b'2e'5d'7b1'2c1'7d >>= withAttribute "Symbol") >>~ pushContext "Member")
                        <|>
                        ((pAnyChar ":!%&()+,-/.*<=>?[]|~^;" >>= withAttribute "Symbol")))
     return (attr, result)

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

parseRules "Member" = 
  do (attr, result) <- (((pRegExpr regex_'5cb'5b'5fa'2dzA'2dZ'5d'5cw'2a'28'3f'3d'5b'5cs'5d'2a'29 >>= withAttribute "Function") >>~ (popContext))
                        <|>
                        ((popContext) >> return ([], "")))
     return (attr, result)

parseRules "StaticImports" = 
  do (attr, result) <- ((pRegExpr regex_'5cs'2a'2e'2a'24 >>= withAttribute "StaticImports") >>~ (popContext))
     return (attr, result)

parseRules "Imports" = 
  do (attr, result) <- ((pRegExpr regex_'5cs'2a'2e'2a'24 >>= withAttribute "Imports") >>~ (popContext))
     return (attr, result)

parseRules "Commentar 1" = 
  pzero

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

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