module Swish.RDF.Formatter.N3
( NodeGenLookupMap
, formatGraphAsText
, formatGraphAsLazyText
, formatGraphAsBuilder
, formatGraphIndent
, formatGraphDiag
)
where
import Swish.RDF.Formatter.Internal (NodeGenLookupMap, SubjTree, PredTree
, LabelContext(..)
, NodeGenState(..), emptyNgs
, findMaxBnode
, getCollection
, processArcs
, findPrefix)
import Swish.Namespace (ScopedName, getScopeLocal, getScopeURI)
import Swish.QName (getLName)
import Swish.RDF.Graph (
RDFGraph, RDFLabel(..),
NamespaceMap,
emptyNamespaceMap,
FormulaMap, emptyFormulaMap,
setNamespaces, getNamespaces,
getFormulae,
emptyRDFGraph
, quote
, quoteT
, resRdfFirst, resRdfRest
)
import Swish.RDF.Vocabulary (
fromLangTag,
rdfType,
rdfNil,
owlSameAs, logImplies
, xsdBoolean, xsdDecimal, xsdInteger, xsdDouble
)
import Control.Monad (liftM, when, void)
import Control.Monad.State (State, modify, get, put, runState)
import Data.Char (isDigit)
import Data.List (partition, intersperse)
import Data.Monoid (Monoid(..))
import Data.Word (Word32)
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.Text.Lazy as L
import qualified Data.Text.Lazy.Builder as B
quoteB :: Bool -> String -> B.Builder
quoteB f v = B.fromString $ quote f v
data N3FormatterState = N3FS
{ indent :: B.Builder
, lineBreak :: Bool
, graph :: RDFGraph
, subjs :: SubjTree RDFLabel
, props :: PredTree RDFLabel
, objs :: [RDFLabel]
, formAvail :: FormulaMap RDFLabel
, formQueue :: [(RDFLabel,RDFGraph)]
, nodeGenSt :: NodeGenState
, bNodesCheck :: [RDFLabel]
, traceBuf :: [String]
}
type Formatter a = State N3FormatterState a
emptyN3FS :: NodeGenState -> N3FormatterState
emptyN3FS ngs = N3FS
{ indent = "\n"
, lineBreak = False
, graph = emptyRDFGraph
, subjs = []
, props = []
, objs = []
, formAvail = emptyFormulaMap
, formQueue = []
, nodeGenSt = ngs
, bNodesCheck = []
, traceBuf = []
}
getIndent :: Formatter B.Builder
getIndent = indent `liftM` get
setIndent :: B.Builder -> Formatter ()
setIndent ind = modify $ \st -> st { indent = ind }
getLineBreak :: Formatter Bool
getLineBreak = lineBreak `liftM` get
setLineBreak :: Bool -> Formatter ()
setLineBreak brk = modify $ \st -> st { lineBreak = brk }
getNgs :: Formatter NodeGenState
getNgs = nodeGenSt `liftM` get
setNgs :: NodeGenState -> Formatter ()
setNgs ngs = modify $ \st -> st { nodeGenSt = ngs }
getPrefixes :: Formatter NamespaceMap
getPrefixes = prefixes `liftM` getNgs
getSubjs :: Formatter (SubjTree RDFLabel)
getSubjs = subjs `liftM` get
setSubjs :: SubjTree RDFLabel -> Formatter ()
setSubjs sl = modify $ \st -> st { subjs = sl }
getProps :: Formatter (PredTree RDFLabel)
getProps = props `liftM` get
setProps :: PredTree RDFLabel -> Formatter ()
setProps ps = modify $ \st -> st { props = ps }
getBnodesCheck :: Formatter [RDFLabel]
getBnodesCheck = bNodesCheck `liftM` get
queueFormula :: RDFLabel -> Formatter ()
queueFormula fn = do
st <- get
let fa = formAvail st
_newState fv = st {
formAvail = M.delete fn fa,
formQueue = (fn,fv) : formQueue st
}
case M.lookup fn fa of
Nothing -> return ()
Just v -> void $ put $ _newState v
extractFormula :: RDFLabel -> Formatter (Maybe RDFGraph)
extractFormula fn = do
st <- get
let (rval, nform) = M.updateLookupWithKey (\_ _ -> Nothing) fn $ formAvail st
put $ st { formAvail = nform }
return rval
extractList :: LabelContext -> RDFLabel -> Formatter (Maybe [RDFLabel])
extractList lctxt ln = do
osubjs <- getSubjs
oprops <- getProps
let mlst = getCollection osubjs' ln
fprops = filter ((`elem` [resRdfFirst, resRdfRest]) . fst) oprops
osubjs' =
case lctxt of
SubjContext -> (ln, fprops) : osubjs
_ -> osubjs
case mlst of
Just (sl,ls,_) -> do
setSubjs sl
when (lctxt == SubjContext) $ setProps $ filter ((`notElem` [resRdfFirst, resRdfRest]) . fst) oprops
return (Just ls)
Nothing -> return Nothing
formatGraphAsText :: RDFGraph -> T.Text
formatGraphAsText = L.toStrict . formatGraphAsLazyText
formatGraphAsLazyText :: RDFGraph -> L.Text
formatGraphAsLazyText = B.toLazyText . formatGraphAsBuilder
formatGraphAsBuilder :: RDFGraph -> B.Builder
formatGraphAsBuilder = formatGraphIndent "\n" True
formatGraphIndent ::
B.Builder
-> Bool
-> RDFGraph
-> B.Builder
formatGraphIndent indnt flag gr =
let (res, _, _, _) = formatGraphDiag indnt flag gr
in res
formatGraphDiag ::
B.Builder
-> Bool
-> RDFGraph
-> (B.Builder, NodeGenLookupMap, Word32, [String])
formatGraphDiag indnt flag gr =
let fg = formatGraph indnt " .\n" False flag gr
ngs = emptyNgs {
prefixes = M.empty,
nodeGen = findMaxBnode gr
}
(out, fgs) = runState fg (emptyN3FS ngs)
ogs = nodeGenSt fgs
in (out, nodeMap ogs, nodeGen ogs, traceBuf fgs)
formatGraph ::
B.Builder
-> B.Builder
-> Bool
-> Bool
-> RDFGraph
-> Formatter B.Builder
formatGraph ind end dobreak dopref gr = do
setIndent ind
setLineBreak dobreak
setGraph gr
fp <- if dopref
then formatPrefixes (getNamespaces gr)
else return mempty
more <- moreSubjects
if more
then do
fr <- formatSubjects
return $ mconcat [fp, fr, end]
else return fp
formatPrefixes :: NamespaceMap -> Formatter B.Builder
formatPrefixes pmap = do
let mls = map pref $ M.assocs pmap
ls <- sequence mls
return $ mconcat ls
where
pref (Just p,u) = nextLine $ mconcat ["@prefix ", B.fromText p, ": <", quoteB True (show u), "> ."]
pref (_,u) = nextLine $ mconcat ["@prefix : <", quoteB True (show u), "> ."]
formatSubjects :: Formatter B.Builder
formatSubjects = do
sb <- nextSubject
sbstr <- formatLabel SubjContext sb
flagP <- moreProperties
if flagP
then do
prstr <- formatProperties sb sbstr
flagS <- moreSubjects
if flagS
then do
fr <- formatSubjects
return $ mconcat [prstr, " .", fr]
else return prstr
else do
txt <- nextLine sbstr
flagS <- moreSubjects
if flagS
then do
fr <- formatSubjects
return $ mconcat [txt, " .", fr]
else return txt
hackIndent :: B.Builder
hackIndent = " "
formatProperties :: RDFLabel -> B.Builder -> Formatter B.Builder
formatProperties sb sbstr = do
pr <- nextProperty sb
prstr <- formatLabel PredContext pr
obstr <- formatObjects sb pr $ mconcat [sbstr, " ", prstr]
more <- moreProperties
let sbindent = hackIndent
if more
then do
fr <- formatProperties sb sbindent
nl <- nextLine $ obstr `mappend` " ;"
return $ nl `mappend` fr
else nextLine obstr
formatObjects :: RDFLabel -> RDFLabel -> B.Builder -> Formatter B.Builder
formatObjects sb pr prstr = do
ob <- nextObject sb pr
obstr <- formatLabel ObjContext ob
more <- moreObjects
if more
then do
let prindent = hackIndent
fr <- formatObjects sb pr prindent
nl <- nextLine $ mconcat [prstr, " ", obstr, ","]
return $ nl `mappend` fr
else return $ mconcat [prstr, " ", obstr]
insertFormula :: RDFGraph -> Formatter B.Builder
insertFormula gr = do
ngs0 <- getNgs
ind <- getIndent
let grm = formatGraph (ind `mappend` " ") "" True False
(setNamespaces emptyNamespaceMap gr)
(f3str, fgs') = runState grm (emptyN3FS ngs0)
setNgs (nodeGenSt fgs')
f4str <- nextLine " } "
return $ mconcat [" { ",f3str, f4str]
insertList :: [RDFLabel] -> Formatter B.Builder
insertList [] = return "()"
insertList xs = do
ls <- mapM (formatLabel ObjContext) xs
return $ mconcat ("( " : intersperse " " ls) `mappend` " )"
insertBnode :: LabelContext -> RDFLabel -> Formatter B.Builder
insertBnode SubjContext lbl = do
flag <- moreProperties
txt <- if flag
then (`mappend` "\n") `liftM` formatProperties lbl ""
else return ""
return $ mconcat ["[", txt, "]"]
insertBnode _ lbl = do
ost <- get
let osubjs = subjs ost
oprops = props ost
oobjs = objs ost
(bsubj, rsubjs) = partition ((== lbl) . fst) osubjs
rprops = case bsubj of
[(_,rs)] -> rs
_ -> []
nst = ost { subjs = rsubjs,
props = rprops,
objs = []
}
put nst
flag <- moreProperties
txt <- if flag
then (`mappend` "\n") `liftM` formatProperties lbl ""
else return ""
nst' <- get
let slist = map fst $ subjs nst'
nsubjs = filter (\(l,_) -> l `elem` slist) osubjs
put $ nst' { subjs = nsubjs,
props = oprops,
objs = oobjs
}
return $ mconcat ["[", txt, "]"]
newState :: RDFGraph -> N3FormatterState -> N3FormatterState
newState gr st =
let ngs0 = nodeGenSt st
pre' = prefixes ngs0 `M.union` getNamespaces gr
ngs' = ngs0 { prefixes = pre' }
(arcSubjs, bNodes) = processArcs gr
in st { graph = gr
, subjs = arcSubjs
, props = []
, objs = []
, formAvail = getFormulae gr
, nodeGenSt = ngs'
, bNodesCheck = bNodes
}
setGraph :: RDFGraph -> Formatter ()
setGraph = modify . newState
hasMore :: (N3FormatterState -> [b]) -> Formatter Bool
hasMore lens = (not . null . lens) `liftM` get
moreSubjects :: Formatter Bool
moreSubjects = hasMore subjs
moreProperties :: Formatter Bool
moreProperties = hasMore props
moreObjects :: Formatter Bool
moreObjects = hasMore objs
nextSubject :: Formatter RDFLabel
nextSubject = do
st <- get
let sb:sbs = subjs st
nst = st { subjs = sbs
, props = snd sb
, objs = []
}
put nst
return $ fst sb
nextProperty :: RDFLabel -> Formatter RDFLabel
nextProperty _ = do
st <- get
let pr:prs = props st
nst = st { props = prs
, objs = snd pr
}
put nst
return $ fst pr
nextObject :: RDFLabel -> RDFLabel -> Formatter RDFLabel
nextObject _ _ = do
st <- get
let ob:obs = objs st
nst = st { objs = obs }
put nst
return ob
nextLine :: B.Builder -> Formatter B.Builder
nextLine str = do
ind <- getIndent
brk <- getLineBreak
if brk
then return $ ind `mappend` str
else do
setLineBreak True
return str
specialTable :: [(ScopedName, String)]
specialTable =
[ (rdfType, "a")
, (owlSameAs, "=")
, (logImplies, "=>")
, (rdfNil, "()")
]
formatLabel :: LabelContext -> RDFLabel -> Formatter B.Builder
formatLabel lctxt lab@(Blank (_:_)) = do
mlst <- extractList lctxt lab
case mlst of
Just lst -> insertList lst
Nothing -> do
mfml <- extractFormula lab
case mfml of
Just fml -> insertFormula fml
Nothing -> do
nb1 <- getBnodesCheck
if lctxt /= PredContext && lab `notElem` nb1
then insertBnode lctxt lab
else formatNodeId lab
formatLabel _ lab@(Res sn) =
case lookup sn specialTable of
Just txt -> return $ quoteB True txt
Nothing -> do
pr <- getPrefixes
let nsuri = getScopeURI sn
local = getLName $ getScopeLocal sn
prefix = findPrefix nsuri pr
name = case prefix of
Just (Just p) -> B.fromText $ quoteT True $ mconcat [p, ":", local]
_ -> mconcat ["<", quoteB True (show nsuri ++ T.unpack local), ">"]
queueFormula lab
return name
formatLabel _ (TypedLit lit dtype)
| dtype == xsdDouble = return $ B.fromText $ T.toLower lit
| dtype `elem` [xsdBoolean, xsdDecimal, xsdInteger] = return $ B.fromText lit
| otherwise = return $ quoteText lit `mappend` "^^" `mappend` showScopedName dtype
formatLabel _ (LangLit lit lcode) =
return $ quoteText lit `mappend` "@" `mappend` B.fromText (fromLangTag lcode)
formatLabel _ (Lit lit) = return $ quoteText lit
formatLabel _ lab = return $ B.fromString $ show lab
quoteText :: T.Text -> B.Builder
quoteText txt =
let st = T.unpack txt
qst = quoteB (n==1) st
n = if '\n' `elem` st || '"' `elem` st then 3 else 1
qch = B.fromString (replicate n '"')
in mconcat [qch, qst, qch]
formatNodeId :: RDFLabel -> Formatter B.Builder
formatNodeId lab@(Blank (lnc:_)) =
if isDigit lnc then mapBlankNode lab else return $ B.fromString $ show lab
formatNodeId other = error $ "formatNodeId not expecting a " ++ show other
mapBlankNode :: RDFLabel -> Formatter B.Builder
mapBlankNode lab = do
ngs <- getNgs
let cmap = nodeMap ngs
cval = nodeGen ngs
nv <- case M.findWithDefault 0 lab cmap of
0 -> do
let nval = succ cval
nmap = M.insert lab nval cmap
setNgs $ ngs { nodeGen = nval, nodeMap = nmap }
return nval
n -> return n
return $ "_:swish" `mappend` B.fromString (show nv)
showScopedName :: ScopedName -> B.Builder
showScopedName = quoteB True . show