{-# LANGUAGE CPP #-}{-# LANGUAGE OverloadedStrings #-}{-# LANGUAGE FlexibleContexts #-}{-# LANGUAGE TupleSections #-}module Skylighting.Parser ( parseSyntaxDefinition , parseSyntaxDefinitionFromText , addSyntaxDefinition , resolveKeywords , missingIncludes ) whereimport qualified Data.String as Stringimport qualified Data.ByteString.Lazy.Char8 as BLimport Data.Char (isAlphaNum, toUpper)import qualified Data.Map as Mimport Data.Maybe (fromMaybe)import qualified Data.Set as Setimport Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Lazy as TLimport qualified Data.Text.Lazy.Encoding as TLEimport qualified Data.Text.Read as TRimport qualified Data.Text.Encoding as TEimport Safeimport Skylighting.Regeximport Skylighting.Typesimport System.FilePathimport Text.XMLimport qualified Control.Exception as Eimport Control.Monad.Trans.Exceptimport Control.Monad.Error.Classimport Control.Monad.Identity#if MIN_VERSION_mtl(2,3,0)import Control.Monad#endif-- | Adds a syntax definition to a syntax map,-- replacing any existing definition with the same name.addSyntaxDefinition :: Syntax -> SyntaxMap -> SyntaxMapaddSyntaxDefinition s = M.insert (sName s) s-- | Scan a list of 'Syntax's and make sure that-- `IncludeRules` never asks for a syntax not in this-- list. Produces a list of pairs where the first-- element is the including syntax name and the second-- element is the (missing) included syntax name.-- This is intended for sanity checks to avoid run-time-- errors.missingIncludes :: [Syntax] -> [(Text, Text)]missingIncludes syns = ordNub [(sName s, lang) | s <- syns , c <- M.elems (sContexts s) , IncludeRules (lang, _) <- map rMatcher (cRules c) , not (lang `Set.member` syntaxNames)] where syntaxNames = Set.fromList $ map sName synsordNub :: (Ord a) => [a] -> [a]ordNub l = go Set.empty l where go _ [] = [] go s (x:xs) = if x `Set.member` s then go s xs else x : go (Set.insert x s) xsstandardDelims :: Set.Set CharstandardDelims = Set.fromList " \n\t.():!+,-<=>%&*/;?[]^{|}~\\"defaultKeywordAttr :: KeywordAttrdefaultKeywordAttr = KeywordAttr { keywordCaseSensitive = True , keywordDelims = standardDelims }vBool :: Bool -> Text -> BoolvBool defaultVal value = case value of "true" -> True "yes" -> True "1" -> True "false" -> False "no" -> False "0" -> False _ -> defaultVal-- | Parses a file containing a Kate XML syntax definition-- into a 'Syntax' description. Note that the resulting 'Syntax'-- must be processed with 'resolveKeywords' (once the full syntax-- map is assembled) before it can be used for tokenizing; the-- functions in Skylighting.Loader do this automatically.parseSyntaxDefinition :: FilePath -> IO (Either String Syntax)parseSyntaxDefinition fp = do bs <- BL.readFile fp case parseText def (toTextLazy bs) of Left e -> return $ Left $ E.displayException e Right doc -> runExceptT (documentToSyntax fp doc) where toTextLazy = TLE.decodeUtf8 . filterCRs . dropBOM dropBOM bs = if "\xEF\xBB\xBF" `BL.isPrefixOf` bs then BL.drop 3 bs else bs filterCRs = BL.filter (/='\r')parseSyntaxDefinitionFromText :: FilePath -> TL.Text -> Either String SyntaxparseSyntaxDefinitionFromText fp xml = case parseText def xml of Left e -> Left $ E.displayException e Right doc -> runIdentity $ runExceptT $ documentToSyntax fp doc-- | Resolve Keyword matchers that refer to lists; following up-- include directives in the syntax map and producing WordSets.resolveKeywords :: SyntaxMap -> Syntax -> SyntaxresolveKeywords sm = goSyntax where goSyntax syntax = syntax{ sContexts = M.map (goContext (sLists syntax)) (sContexts syntax) } goContext lists context = context{ cRules = map (goRule lists) (cRules context) } goRule lists rule = case rMatcher rule of Keyword kwattr (Left listname) -> case M.lookup listname lists of Nothing -> rule Just lst -> rule{ rMatcher = Keyword kwattr (Right (makeWordSet (keywordCaseSensitive kwattr) (foldr goItem [] lst))) } _ -> rule goItem (Item t) ts = t:ts goItem (IncludeList (syntaxname,listname)) ts = case M.lookup syntaxname sm >>= M.lookup listname . sLists of Nothing -> ts Just lst -> foldr goItem ts lst-- | Parses an XML 'Document' as a 'Syntax' description.documentToSyntax :: Monad m => FilePath -- ^ used for short name -> Document -> ExceptT String m SyntaxdocumentToSyntax fp Document{ documentRoot = rootEl } = do unless (elementName rootEl == "language") $ throwError "Root element is not language" let filename = takeFileName fp let casesensitive = vBool True $ getAttrValue "casesensitive" rootEl hlEl <- case getElementsNamed "highlighting" rootEl of [] -> throwError "No highlighting element" (hl:_) -> return hl lists <- M.fromList <$> mapM getList (getElementsNamed "list" hlEl) let itemDatas = getItemData hlEl let defKeywordAttr = getKeywordAttrs casesensitive rootEl let contextEls = getElementsNamed "contexts" hlEl >>= getElementsNamed "context" let syntaxname = getAttrValue "name" rootEl contexts <- mapM (getContext syntaxname itemDatas lists defKeywordAttr) contextEls startingContext <- case contexts of (c:_) -> return $ cName c [] -> throwError "No contexts" return Syntax{ sName = getAttrValue "name" rootEl , sFilename = filename , sShortname = T.pack $ pathToLangName filename , sAuthor = getAttrValue "author" rootEl , sVersion = getAttrValue "version" rootEl , sLicense = getAttrValue "license" rootEl , sExtensions = words $ map (\c -> if c == ';' then ' ' else c) $ T.unpack $ getAttrValue "extensions" rootEl , sLists = lists , sContexts = M.fromList [(cName c, c) | c <- contexts] , sStartingContext = startingContext }elementNamed :: String -> Node -> BoolelementNamed name (NodeElement el) = elementName el == String.fromString nameelementNamed _ _ = FalsegetElementsNamed :: String -> Element -> [Element]getElementsNamed name node = [el | NodeElement el <- filter (elementNamed name) (elementNodes node)]getAttrValue :: String -> Element -> TextgetAttrValue key el = fromMaybe mempty $ M.lookup (String.fromString key) $ elementAttributes elgetTextContent :: Element -> TextgetTextContent el = mconcat [t | NodeContent t <- elementNodes el]getList :: Monad m => Element -> ExceptT String m (Text, [ListItem])getList el = do case M.lookup "name" (elementAttributes el) of Nothing -> throwError "No name attribute on list" Just name -> (name,) <$> mapM toListItem [el' | NodeElement el' <- elementNodes el] where toListItem el' = case elementName el' of "item" -> return $ Item $ T.strip $ getTextContent el' "include" -> do let (syntaxname, listname) = splitContext (getTextContent el') return $ IncludeList (syntaxname, listname) x -> throwError $ "Unknown element " ++ show x ++ " in list"splitContext :: Text -> (Text, Text)splitContext t = case T.breakOn "##" (T.strip t) of (x, y) | T.null y -> ("", x) | otherwise -> (T.drop 2 y, x)getParser :: Monad m => Text -> ItemData -> M.Map Text [ListItem] -> KeywordAttr -> Text -> Element -> ExceptT String m RulegetParser syntaxname itemdatas lists kwattr cattr el = do let name = nameLocalName . elementName $ el let attribute = getAttrValue "attribute" el let context = getAttrValue "context" el let char0 = readChar $ getAttrValue "char" el let char1 = readChar $ getAttrValue "char1" el let str' = getAttrValue "String" el -- rules default to case-sensitive matching; the language's -- casesensitive attribute applies only to keyword lists (as in KDE): let insensitive = vBool False $ getAttrValue "insensitive" el let includeAttrib = vBool False $ getAttrValue "includeAttrib" el let weakDelim = Set.fromList $ T.unpack $ getAttrValue "weakDeliminator" el let additionalDelim = Set.fromList $ T.unpack $ getAttrValue "additionalDeliminator" el -- In KDE the word delimiters of a rule are the language's word -- delimiters (standard delimiters as modified by additionalDeliminator -- and weakDeliminator on general > keywords, which we get from -- kwattr), further modified by the additionalDeliminator and -- weakDeliminator attributes on the rule itself: let ruleDelims = Set.union (keywordDelims kwattr) additionalDelim Set.\\ weakDelim let lookahead = vBool False $ getAttrValue "lookAhead" el let firstNonSpace = vBool False $ getAttrValue "firstNonSpace" el let column' = getAttrValue "column" el let dynamic = vBool False $ getAttrValue "dynamic" el let minimal = vBool False $ getAttrValue "minimal" el children <- mapM (getParser syntaxname itemdatas lists kwattr attribute) [e | NodeElement e <- elementNodes el ] let tildeRegex = name == "RegExpr" && T.take 1 str' == "^" let str = if tildeRegex then T.drop 1 str' else str' let column = if tildeRegex then Just (0 :: Int) else either (\_ -> Nothing) (Just . fst) $ TR.decimal column' let re = RegExpr RE{ reString = TE.encodeUtf8 str , reCaseSensitive = not insensitive , reMinimal = minimal } let contextSwitches = parseContextSwitches syntaxname context let (incsyntax, inccontext) = case contextSwitches of (Push (s,c) : _) -> (s,c) _ -> error "IncludeRules doesn't specify a syntax and context" matcher <- case name of "DetectChar" -> return $ DetectChar char0 "Detect2Chars" -> return $ Detect2Chars char0 char1 "AnyChar" -> return $ AnyChar $ Set.fromList $ T.unpack str "RangeDetect" -> return $ RangeDetect char0 char1 "StringDetect" -> return $ StringDetect str "WordDetect" -> return $ WordDetect str "RegExpr" -> return $ re -- an insensitive attribute on the keyword rule itself -- (if present) overrides the case sensitivity of the -- keyword list, and additionalDeliminator and -- weakDeliminator attributes adjust its delimiters -- (as in KDE): "keyword" -> return $ let kwattr' = if M.member (String.fromString "insensitive") (elementAttributes el) then kwattr{ keywordCaseSensitive = not insensitive } else kwattr in Keyword kwattr'{ keywordDelims = ruleDelims } (Left str) "Int" -> return $ Int "Float" -> return $ Float "HlCOct" -> return $ HlCOct "HlCHex" -> return $ HlCHex "HlCStringChar" -> return $ HlCStringChar "HlCChar" -> return $ HlCChar -- KDE uses the first character of the char attribute, -- or backslash if it is absent or empty: "LineContinue" -> return $ LineContinue $ case T.uncons (getAttrValue "char" el) of Just (c, _) -> c Nothing -> '\\' "IncludeRules" -> return $ IncludeRules (incsyntax, inccontext) "DetectSpaces" -> return $ DetectSpaces "DetectIdentifier" -> return $ DetectIdentifier _ -> throwError $ "Unknown element " ++ T.unpack name return $ Rule{ rMatcher = matcher , rAttribute = fromMaybe NormalTok $ if T.null attribute then M.lookup cattr itemdatas else M.lookup attribute itemdatas , rIncludeAttribute = includeAttrib , rWordDelimiters = ruleDelims , rDynamic = dynamic , rCaseSensitive = not insensitive , rChildren = children , rContextSwitch = if name == "IncludeRules" then [] else contextSwitches , rLookahead = lookahead , rFirstNonspace = firstNonSpace , rColumn = column }getContext :: Monad m => Text -> ItemData -> M.Map Text [ListItem] -> KeywordAttr -> Element -> ExceptT String m ContextgetContext syntaxname itemDatas lists kwattr el = do let name = getAttrValue "name" el let attribute = getAttrValue "attribute" el let lineEmptyContext = getAttrValue "lineEmptyContext" el let lineEndContext = getAttrValue "lineEndContext" el let fallthrough = vBool False $ getAttrValue "fallthrough" el let fallthroughContext = getAttrValue "fallthroughContext" el let dynamic = vBool False $ getAttrValue "dynamic" el parsers <- mapM (getParser syntaxname itemDatas lists kwattr attribute) [e | NodeElement e <- elementNodes el ] return $ Context { cName = name , cSyntax = syntaxname , cRules = parsers , cAttribute = fromMaybe NormalTok $ M.lookup attribute itemDatas -- lineEmptyContext defaults to lineEndContext when it is -- unspecified or #stay; this avoids skipping empty lines -- after a line continuation character (KDE context.cpp, -- Context::resolveContexts, see kde bug 405903): , cLineEmptyContext = case parseContextSwitches syntaxname lineEmptyContext of [] -> parseContextSwitches syntaxname lineEndContext cs -> cs , cLineEndContext = parseContextSwitches syntaxname lineEndContext , cFallthrough = fallthrough , cFallthroughContext = parseContextSwitches syntaxname fallthroughContext , cDynamic = dynamic }getItemData :: Element -> ItemDatagetItemData el = toItemDataTable $ [(getAttrValue "name" e, getAttrValue "defStyleNum" e) | e <- (getElementsNamed "itemDatas" el >>= getElementsNamed "itemData") ]-- The default case sensitivity of keyword lists is given by the-- casesensitive attribute on the language element, and may be-- overridden by the casesensitive attribute on general > keywords:getKeywordAttrs :: Bool -> Element -> KeywordAttrgetKeywordAttrs casesensitive el = case (getElementsNamed "general" el >>= getElementsNamed "keywords") of [] -> defaultKeywordAttr{ keywordCaseSensitive = casesensitive } (x:_) -> let weakDelim = T.unpack $ getAttrValue "weakDeliminator" x additionalDelim = T.unpack $ getAttrValue "additionalDeliminator" x in KeywordAttr { keywordCaseSensitive = vBool casesensitive $ getAttrValue "casesensitive" x , keywordDelims = Set.union standardDelims (Set.fromList additionalDelim) Set.\\ Set.fromList weakDelim }parseContextSwitches :: Text -> Text -> [ContextSwitch]parseContextSwitches syntaxname t = if T.null t || t == "#stay" then [] else case T.stripPrefix "#pop" t of Just rest -> Pop : parseContextSwitches syntaxname rest Nothing -> -- a sequence of contexts separated by !; in -- A!B!C, C is the top of the stack. let cs = filter (not . T.null) $ T.split (== '!') t toContext x = let (othersyntax, contextname) = splitContext x syntaxname' = if T.null othersyntax then syntaxname else othersyntax in (syntaxname', contextname) in map (Push . toContext) cstype ItemData = M.Map Text TokenTypetoItemDataTable :: [(Text, Text)] -> ItemDatatoItemDataTable = M.fromList . map (\(s,t) -> (s, toTokenType t))toTokenType :: Text -> TokenTypetoTokenType t = case t of "dsNormal" -> NormalTok "dsKeyword" -> KeywordTok "dsDataType" -> DataTypeTok "dsDecVal" -> DecValTok "dsBaseN" -> BaseNTok "dsFloat" -> FloatTok "dsConstant" -> ConstantTok "dsChar" -> CharTok "dsSpecialChar" -> SpecialCharTok "dsString" -> StringTok "dsVerbatimString" -> VerbatimStringTok "dsSpecialString" -> SpecialStringTok "dsImport" -> ImportTok "dsComment" -> CommentTok "dsDocumentation" -> DocumentationTok "dsAnnotation" -> AnnotationTok "dsCommentVar" -> CommentVarTok "dsOthers" -> OtherTok "dsFunction" -> FunctionTok "dsVariable" -> VariableTok "dsControlFlow" -> ControlFlowTok "dsOperator" -> OperatorTok "dsBuiltIn" -> BuiltInTok "dsExtension" -> ExtensionTok "dsPreprocessor" -> PreprocessorTok "dsAttribute" -> AttributeTok "dsRegionMarker" -> RegionMarkerTok "dsInformation" -> InformationTok "dsWarning" -> WarningTok "dsAlert" -> AlertTok "dsError" -> ErrorTok _ -> NormalTok-- Note, some xml files have "\\" for a backslash,-- others have "\". Not sure what the rules are, but-- this covers both bases:readChar :: Text -> CharreadChar t = case T.unpack t of [c] -> c s -> readDef '\xffff' $ "'" ++ s ++ "'"pathToLangName :: String -> StringpathToLangName s = capitalize (camelize (takeBaseName s))camelize :: String -> Stringcamelize (d:c:cs) | not (isAlphaNum d) = toUpper c : camelize cscamelize (c:cs) = c : camelize cscamelize [] = []capitalize :: String -> Stringcapitalize (c:cs) = toUpper c : cscapitalize [] = []