74 lines
1.7 KiB
Haskell
Raw Normal View History

2020-06-04 17:40:38 +04:00
{- | Continious location inside the source and utilities.
-}
2020-06-01 22:02:16 +04:00
module Range
( Range(..)
, HasRange(..)
, diffRange
2020-06-04 13:48:04 +04:00
, cutOut
2020-07-08 18:55:11 +04:00
, point
2020-06-01 22:02:16 +04:00
)
where
2020-06-04 13:48:04 +04:00
import qualified Data.ByteString as BS
import Data.ByteString (ByteString)
import Data.Text (Text)
import Data.Text.Encoding
import Pretty
2020-06-09 15:56:11 +04:00
import Lattice
import Product
2020-04-30 21:06:01 +04:00
2020-07-08 18:55:11 +04:00
point :: Int -> Int -> Range
point l c = Range (l, c, 0) (l, c, 0) ""
2020-06-01 22:02:16 +04:00
-- | A continious location in text.
data Range = Range
2020-05-08 01:18:26 +04:00
{ rStart :: (Int, Int, Int) -- ^ [Start: line, col, byte-offset...
, rFinish :: (Int, Int, Int) -- ^ ... End: line, col, byte-offset).
, rFile :: FilePath
}
deriving (Show) via PP Range
2020-06-17 22:05:44 +04:00
deriving stock (Ord)
2020-05-08 01:18:26 +04:00
-- | TODO: Ugh. Purge it.
diffRange :: Range -> Range -> Range
diffRange (Range ws wf f) (Range ps _ _) = Range (max ws ps) wf f
2020-04-30 21:06:01 +04:00
instance Pretty Range where
pp (Range (ll, lc, _) (rl, rc, _) f) =
2020-06-17 22:05:44 +04:00
color 2 do
brackets do
text f <> ":"
<> int ll <> ":"
<> int lc <> "-"
<> int rl <> ":"
<> int rc
2020-06-01 22:02:16 +04:00
-- | Ability to get range out of something.
class HasRange a where
2020-06-04 13:48:04 +04:00
getRange :: a -> Range
instance HasRange Range where
getRange = id
2020-06-09 15:56:11 +04:00
instance Contains Range xs => HasRange (Product xs) where
getRange = getElem
2020-06-04 13:48:04 +04:00
-- | Extract textual representation of given range.
cutOut :: Range -> ByteString -> Text
cutOut (Range (_, _, s) (_, _, f) _) bs =
2020-06-04 13:48:04 +04:00
decodeUtf8
$ BS.take (f - s)
$ BS.drop s
bs
2020-06-09 15:56:11 +04:00
instance Lattice Range where
Range (ll1, lc1, _) (ll2, lc2, _) _ <? Range (rl1, rc1, _) (rl2, rc2, _) _ =
2020-06-09 15:56:11 +04:00
(rl1 < ll1 || rl1 == ll1 && rc1 <= lc1) &&
(rl2 > ll2 || rl2 == ll2 && rc2 >= lc2)
instance Eq Range where
Range (l, c, _) (r, d, _) f == Range (l1, c1, _) (r1, d1, _) f1 =
(l, c, r, d, f) == (l1, c1, r1, d1, f1)