| 1 |
{-# LANGUAGE ScopedTypeVariables, ExistentialQuantification, MultiParamTypeClasses #-} |
| 2 |
{-# OPTIONS_GHC -fno-warn-name-shadowing #-} |
| 3 |
|
| 4 |
-- | This module defines implementations of syntax-awareness drivers. |
| 5 |
|
| 6 |
module Yi.Syntax.Driver where |
| 7 |
|
| 8 |
import Data.Map (Map) |
| 9 |
import qualified Data.Map as M (Map, assocs, empty, findWithDefault, fromList) |
| 10 |
import Yi.Buffer.Basic (WindowRef) |
| 11 |
import Yi.Lexer.Alex (Tok) |
| 12 |
import Yi.Syntax hiding (Cache) |
| 13 |
import Yi.Syntax.Tree (IsTree, fromNodeToFinal) |
| 14 |
|
| 15 |
type Path = [Int] |
| 16 |
|
| 17 |
data Cache state tree tt = Cache { |
| 18 |
path :: M.Map WindowRef Path, |
| 19 |
cachedStates :: [state], |
| 20 |
root :: tree (Tok tt), |
| 21 |
focused :: !(M.Map WindowRef (tree (Tok tt))) |
| 22 |
} |
| 23 |
|
| 24 |
mkHighlighter :: forall state tree tt. (IsTree tree, Show state) => |
| 25 |
(Scanner Point Char -> Scanner state (tree (Tok tt))) -> |
| 26 |
Highlighter (Cache state tree tt) (tree (Tok tt)) |
| 27 |
mkHighlighter scanner = |
| 28 |
Yi.Syntax.SynHL |
| 29 |
{ hlStartState = Cache M.empty [] emptyResult M.empty |
| 30 |
, hlRun = updateCache |
| 31 |
, hlGetTree = \(Cache _ _ _ focused) w -> M.findWithDefault emptyResult w focused |
| 32 |
, hlFocus = focus |
| 33 |
} |
| 34 |
where startState :: state |
| 35 |
startState = scanInit (scanner emptyFileScan) |
| 36 |
emptyResult = scanEmpty (scanner emptyFileScan) |
| 37 |
updateCache :: Scanner Point Char -> Point -> Cache state tree tt -> Cache state tree tt |
| 38 |
updateCache newFileScan dirtyOffset (Cache path cachedStates oldResult _) = Cache path newCachedStates newResult M.empty |
| 39 |
where newScan = scanner newFileScan |
| 40 |
reused :: [state] |
| 41 |
reused = takeWhile ((< dirtyOffset) . scanLooked (scanner newFileScan)) cachedStates |
| 42 |
resumeState :: state |
| 43 |
resumeState = if null reused then startState else last reused |
| 44 |
|
| 45 |
newCachedStates = reused ++ fmap fst recomputed |
| 46 |
recomputed = scanRun newScan resumeState |
| 47 |
newResult :: tree (Tok tt) |
| 48 |
newResult = if null recomputed then oldResult else snd $ head recomputed |
| 49 |
focus r (Cache path states root _focused) = |
| 50 |
Cache path' states root focused |
| 51 |
where (path', focused) = unzipFM $ zipWithFM (\newpath oldpath -> fromNodeToFinal newpath (oldpath,root)) [] r path |
| 52 |
|
| 53 |
unzipFM :: Ord k => [(k,(u,v))] -> (Map k u, Map k v) |
| 54 |
unzipFM l = (M.fromList mu, M.fromList mv) |
| 55 |
where (mu, mv) = unzip [((k,u),(k,v)) | (k,(u,v)) <- l] |
| 56 |
|
| 57 |
zipWithFM :: Ord k => (u -> v -> w) -> v -> Map k u -> Map k v -> [(k,w)] |
| 58 |
zipWithFM f v0 mu mv = [ (k,f u (M.findWithDefault v0 k mv) ) | (k,u) <- M.assocs mu] |