packages feed

pykinos-core-0.1.1.0: src/Pykinos/Text/PieceRope.hs

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DerivingStrategies #-}
-- | Module: Pykinos.Text.PieceRope
-- Description: Persistent 5-metric UTF-8 piece-rope with Sub4KB leaves and O(log N) coordinate indexing
--
-- Stores immutable text in balanced Sub4KB UTF-8 chunks annotated with a 5-coordinate
-- monoidal summary ('TextMetrics'): UTF-8 bytes, UTF-16 code units (for LSP),
-- line breaks, logical grapheme clusters, and terminal display width.
module Pykinos.Text.PieceRope
  ( maxLeafBytes
  , TextMetrics(..)
  , measureText
  , PieceRope
  , emptyRope
  , fromText
  , toText
  , ropeMetrics
  , ropeByteLength
  , ropeHeight
  , appendRope
  , splitAtByte
  , sliceBytes
  , insertAtByte
  , deleteRangeByte
  , byteToLineCol
  , lineColToByte
  , byteToUtf16
  , utf16ToByte
  ) where

import Data.Char (ord)
import Data.Text (Text)
import qualified Data.Text as T

-- | Maximum UTF-8 byte length per rope leaf (strictly Sub4KB nursery-safe).
maxLeafBytes :: Int
maxLeafBytes = 512

-- | 5-coordinate monoidal summary tracked at every 'PieceRope' node.
data TextMetrics = TextMetrics
  { tmUtf8Bytes  :: {-# UNPACK #-} !Int
  , tmUtf16Units :: {-# UNPACK #-} !Int
  , tmLines      :: {-# UNPACK #-} !Int
  , tmGraphemes  :: {-# UNPACK #-} !Int
  , tmDispWidth  :: {-# UNPACK #-} !Int
  } deriving stock (Eq, Ord, Show)

instance Semigroup TextMetrics where
  {-# INLINE (<>) #-}
  TextMetrics b1 u1 l1 g1 w1 <> TextMetrics b2 u2 l2 g2 w2 =
    TextMetrics (b1 + b2) (u1 + u2) (l1 + l2) (g1 + g2) (w1 + w2)

instance Monoid TextMetrics where
  {-# INLINE mempty #-}
  mempty = TextMetrics 0 0 0 0 0

{-# INLINE utf8CharLen #-}
-- | Return UTF-8 byte length of a Unicode code point.
utf8CharLen :: Char -> Int
utf8CharLen c
  | n < 0x80    = 1
  | n < 0x800   = 2
  | n < 0x10000 = 3
  | otherwise   = 4
  where
    !n = ord c

{-# INLINE utf16CharLen #-}
-- | Return UTF-16 code-unit length of a Unicode code point (1 for BMP, 2 for surrogate pair).
utf16CharLen :: Char -> Int
utf16CharLen c = if ord c >= 0x10000 then 2 else 1

{-# INLINE charDispWidth #-}
-- | Return terminal display cell width of a character (0 for control/formatting, 2 for wide/full-width/emoji, 1 for regular).
charDispWidth :: Char -> Int
charDispWidth c
  | n < 0x20 || n == 0x7F = 0
  | (n >= 0x1100 && n <= 0x115F)
    || (n >= 0x2E80 && n <= 0xA4CF)
    || (n >= 0xAC00 && n <= 0xD7A3)
    || (n >= 0xF900 && n <= 0xFAFF)
    || (n >= 0x1F300 && n <= 0x1FAFF) = 2
  | otherwise = 1
  where
    !n = ord c

-- | Computes the 5-coordinate 'TextMetrics' of a 'Text' chunk in one strict pass.
measureText :: Text -> TextMetrics
measureText = T.foldl' step mempty
  where
    step (TextMetrics b u l g w) c =
      let !b' = b + utf8CharLen c
          !u' = u + utf16CharLen c
          !l' = if c == '\n' then l + 1 else l
          !g' = g + 1
          !w' = w + charDispWidth c
      in TextMetrics b' u' l' g' w'

-- | Height-balanced persistent piece-rope with monoidal 'TextMetrics' summaries.
data PieceRope
  = RopeEmpty
  | RopeLeaf !TextMetrics !Text
  | RopeNode {-# UNPACK #-} !Int !TextMetrics !PieceRope !PieceRope
  deriving stock (Show)

instance Eq PieceRope where
  r1 == r2 = toText r1 == toText r2

-- | Empty 'PieceRope'.
emptyRope :: PieceRope
emptyRope = RopeEmpty

{-# INLINE ropeHeight #-}
-- | Height of the rope tree.
ropeHeight :: PieceRope -> Int
ropeHeight RopeEmpty          = 0
ropeHeight (RopeLeaf _ _)     = 1
ropeHeight (RopeNode h _ _ _) = h

-- | Returns the O(1) root 'TextMetrics' summary.
{-# INLINE ropeMetrics #-}
ropeMetrics :: PieceRope -> TextMetrics
ropeMetrics RopeEmpty          = mempty
ropeMetrics (RopeLeaf m _)     = m
ropeMetrics (RopeNode _ m _ _) = m

-- | Returns the O(1) UTF-8 byte length of the rope.
{-# INLINE ropeByteLength #-}
ropeByteLength :: PieceRope -> Int
ropeByteLength = tmUtf8Bytes . ropeMetrics

-- | Construct a leaf from non-empty text, or RopeEmpty if empty.
mkLeaf :: Text -> PieceRope
mkLeaf t
  | T.null t  = RopeEmpty
  | otherwise = RopeLeaf (measureText t) t

-- | Smart constructor for internal node maintaining height and metric summaries.
mkNode :: PieceRope -> PieceRope -> PieceRope
mkNode RopeEmpty r = r
mkNode l RopeEmpty = l
mkNode l r =
  let !h = 1 + max (ropeHeight l) (ropeHeight r)
      !m = ropeMetrics l <> ropeMetrics r
  in RopeNode h m l r

-- | AVL rebalancing operator keeping subtree height delta <= 1.
balance :: PieceRope -> PieceRope -> PieceRope
balance RopeEmpty r = r
balance l RopeEmpty = l
balance l r
  | hl > hr + 1 =
      case l of
        RopeNode _ _ ll lr
          | ropeHeight ll >= ropeHeight lr -> mkNode ll (balance lr r)
          | otherwise ->
              case lr of
                RopeNode _ _ lrl lrr -> mkNode (mkNode ll lrl) (mkNode lrr r)
                _                    -> mkNode l r
        _ -> mkNode l r
  | hr > hl + 1 =
      case r of
        RopeNode _ _ rl rr
          | ropeHeight rr >= ropeHeight rl -> mkNode (balance l rl) rr
          | otherwise ->
              case rl of
                RopeNode _ _ rll rlr -> mkNode (mkNode l rll) (mkNode rlr rr)
                _                    -> mkNode l r
        _ -> mkNode l r
  | otherwise = mkNode l r
  where
    !hl = ropeHeight l
    !hr = ropeHeight r

-- | Splits a 'Text' strictly at or just before @targetByte@ on a valid code-point boundary.
splitTextAtByte :: Int -> Text -> (Text, Text)
splitTextAtByte !targetByte txt
  | targetByte <= 0 = (T.empty, txt)
  | otherwise       = T.splitAt (findCharCount 0 0 txt) txt
  where
    findCharCount !bytes !chars remTxt =
      case T.uncons remTxt of
        Nothing -> chars
        Just (c, rest) ->
          let !b' = bytes + utf8CharLen c
          in if b' > targetByte
               then chars
               else findCharCount b' (chars + 1) rest

-- | Constructs a balanced 'PieceRope' chunked into Sub4KB leaves.
fromText :: Text -> PieceRope
fromText txt
  | T.null txt = RopeEmpty
  | otherwise  = buildChunks (chunkText txt)
  where
    chunkText t
      | T.null t  = []
      | otherwise =
          let (pfx, rest) = splitTextAtByte maxLeafBytes t
          in if T.null pfx
               then [mkLeaf t]
               else mkLeaf pfx : chunkText rest

    buildChunks []  = RopeEmpty
    buildChunks [x] = x
    buildChunks xs  =
      let (a, b) = splitAt (length xs `div` 2) xs
      in balance (buildChunks a) (buildChunks b)

-- | Materializes the entire 'PieceRope' as a contiguous 'Text'.
toText :: PieceRope -> Text
toText = T.concat . go []
  where
    go acc RopeEmpty          = acc
    go acc (RopeLeaf _ t)     = t : acc
    go acc (RopeNode _ _ l r) = go (go acc r) l

-- | Concatenates two ropes in O(log N) while coalescing tiny adjacent leaves.
appendRope :: PieceRope -> PieceRope -> PieceRope
appendRope RopeEmpty r = r
appendRope l RopeEmpty = l
appendRope (RopeLeaf ml tl) (RopeLeaf mr tr)
  | tmUtf8Bytes ml + tmUtf8Bytes mr <= maxLeafBytes =
      RopeLeaf (ml <> mr) (tl <> tr)
appendRope l r = balance l r

-- | Splits a rope at UTF-8 byte offset @off@ in O(log N).
splitAtByte :: Int -> PieceRope -> (PieceRope, PieceRope)
splitAtByte !_ RopeEmpty = (RopeEmpty, RopeEmpty)
splitAtByte !off rope
  | off <= 0                   = (RopeEmpty, rope)
  | off >= ropeByteLength rope = (rope, RopeEmpty)
splitAtByte !off (RopeLeaf _ t) =
  let (l, r) = splitTextAtByte off t
  in (mkLeaf l, mkLeaf r)
splitAtByte !off (RopeNode _ _ l r) =
  let !lb = ropeByteLength l
  in if off < lb
       then let (ll, lr) = splitAtByte off l
            in (ll, appendRope lr r)
       else if off > lb
         then let (rl, rr) = splitAtByte (off - lb) r
              in (appendRope l rl, rr)
         else (l, r)

-- | Extracts the UTF-8 byte range @[start, end)@ as a 'Text'.
sliceBytes :: Int -> Int -> PieceRope -> Text
sliceBytes !start !end rope
  | end <= start = T.empty
  | otherwise =
      let (_, rest) = splitAtByte start rope
          (mid, _)  = splitAtByte (end - start) rest
      in toText mid

-- | Inserts @txt@ at UTF-8 byte offset @off@ in O(log N).
insertAtByte :: Int -> Text -> PieceRope -> PieceRope
insertAtByte !off txt rope
  | T.null txt = rope
  | otherwise =
      let (l, r) = splitAtByte off rope
      in appendRope (appendRope l (fromText txt)) r

-- | Deletes the half-open UTF-8 byte range @[start, end)@ in O(log N).
deleteRangeByte :: Int -> Int -> PieceRope -> PieceRope
deleteRangeByte !start !end rope
  | end <= start = rope
  | otherwise =
      let (l, rest) = splitAtByte start rope
          (_, r)    = splitAtByte (end - start) rest
      in appendRope l r

-- | Converts a UTF-8 byte offset to zero-based @(line, byteColOnLine)@ in O(log N).
byteToLineCol :: PieceRope -> Int -> (Int, Int)
byteToLineCol rope !off =
  let (pfx, _) = splitAtByte off rope
      !lineNo  = tmLines (ropeMetrics pfx)
      !lineStart = lineColToByte rope (lineNo, 0)
  in (lineNo, max 0 (ropeByteLength pfx - lineStart))

-- | Converts zero-based @(line, byteColOnLine)@ to a UTF-8 byte offset in O(log N).
lineColToByte :: PieceRope -> (Int, Int) -> Int
lineColToByte rope (!targetLine, !targetCol)
  | targetLine <= 0 = clampOff targetCol
  | otherwise       = clampOff (goLine 0 targetLine rope + max 0 targetCol)
  where
    !total = ropeByteLength rope
    clampOff !x = max 0 (min total x)

    goLine !accBytes !_ RopeEmpty = accBytes
    goLine !accBytes !remLines (RopeLeaf _ t) =
      accBytes + scanNewlines 0 remLines t
    goLine !accBytes !remLines (RopeNode _ _ l r) =
      let !lm = ropeMetrics l
      in if remLines <= tmLines lm
           then goLine accBytes remLines l
           else goLine (accBytes + tmUtf8Bytes lm) (remLines - tmLines lm) r

    scanNewlines !b !remLinesRemaining t
      | remLinesRemaining <= 0 = b
      | otherwise =
          case T.uncons t of
            Nothing -> b
            Just (c, rest) ->
              let !b' = b + utf8CharLen c
                  !rem' = if c == '\n' then remLinesRemaining - 1 else remLinesRemaining
              in scanNewlines b' rem' rest

-- | Converts a UTF-8 byte offset to a UTF-16 code-unit offset (LSP) in O(log N).
byteToUtf16 :: PieceRope -> Int -> Int
byteToUtf16 rope !off =
  let (pfx, _) = splitAtByte off rope
  in tmUtf16Units (ropeMetrics pfx)

-- | Converts a UTF-16 code-unit offset (LSP) to a UTF-8 byte offset in O(log N).
utf16ToByte :: PieceRope -> Int -> Int
utf16ToByte rope !targetU16
  | targetU16 <= 0 = 0
  | otherwise      = go 0 targetU16 rope
  where
    go !accBytes !_ RopeEmpty = accBytes
    go !accBytes !remU (RopeLeaf _ t) =
      accBytes + scanU16 0 remU t
    go !accBytes !remU (RopeNode _ _ l r) =
      let !lm = ropeMetrics l
      in if remU <= tmUtf16Units lm
           then go accBytes remU l
           else go (accBytes + tmUtf8Bytes lm) (remU - tmUtf16Units lm) r

    scanU16 !b !remUnits t
      | remUnits <= 0 = b
      | otherwise =
          case T.uncons t of
            Nothing -> b
            Just (c, rest) ->
              let !u = utf16CharLen c
              in if u > remUnits
                   then b
                   else scanU16 (b + utf8CharLen c) (remUnits - u) rest