aboutsummaryrefslogtreecommitdiffstats
path: root/src/Data/JLD/Model/IRI.hs
blob: 7c054eb32f22fe71ec19081379e44efdd2973347 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
module Data.JLD.Model.IRI (
    CompactIRI (..),
    compactIriPrefix,
    compactIriSuffix,
    isBlankIri,
    endsWithGenericDelim,
    parseCompactIri,
    renderCompactIri,
) where

import Data.JLD.Prelude

import Data.Char (isAlphaNum)
import Data.Text qualified as T (drop, findIndex, isPrefixOf, take, uncons, unsnoc)

data CompactIRI = CompactIRI Text Text | BlankIRI Text
    deriving (Show, Eq)

compactIriPrefix :: CompactIRI -> Text
compactIriPrefix (CompactIRI prefix _) = prefix
compactIriPrefix (BlankIRI _) = "_"

compactIriSuffix :: CompactIRI -> Text
compactIriSuffix (CompactIRI _ suffix) = suffix
compactIriSuffix (BlankIRI suffix) = suffix

renderCompactIri :: CompactIRI -> Text
renderCompactIri iri = compactIriPrefix iri <> ":" <> compactIriSuffix iri

parseCompactIri :: Text -> Maybe CompactIRI
parseCompactIri value
    | Just idx <- (+ 1) <$> T.findIndex (== ':') (T.drop 1 value)
    , prefix <- T.take idx value
    , suffix <- T.drop (idx + 1) value
    , not ("/" `T.isPrefixOf` suffix)
    , Just (prefixFirst, _) <- T.uncons prefix
    , prefixFirst == '_' || isAlphaNum prefixFirst =
        Just <| if prefix == "_" then BlankIRI suffix else CompactIRI prefix suffix
    | otherwise = Nothing

isBlankIri :: Text -> Bool
isBlankIri = T.isPrefixOf "_:"

endsWithGenericDelim :: Text -> Bool
endsWithGenericDelim (T.unsnoc -> Just (_, c)) = c `elem` (":/?#[]@" :: String)
endsWithGenericDelim _ = False