@@ -0,0 +1,307 @@
1+--------------------------------------------------------------------
3+-- Module : Text.XML.Light.Input
4+-- Copyright : (c) Galois, Inc. 2007
7+-- Maintainer: Iavor S. Diatchki <diatchki@galois.com>
8+-- Stability : provisional
9+-- Portability: portable
11+-- Lightweight XML parsing
14+module Text.XML.Light.Input (parseXML,parseXMLDoc) where
16+import Text.XML.Light.Types
17+import Text.XML.Light.Proc
18+import Text.XML.Light.Output(tagEnd)
20+import Data.Char(isSpace)
21+import Data.List(isPrefixOf)
22+import Numeric(readHex)
24+-- | parseXMLDoc, parse a XMLl document to maybe an element
25+parseXMLDoc :: String -> Maybe Element
26+parseXMLDoc xs = strip (parseXML xs)
27+ where strip cs = case onlyElems cs of
29+ | "?xml" `isPrefixOf` qName (elName e)
30+ -> strip (map Elem es)
31+ | otherwise -> Just e
34+-- | parseXML to a list of content chunks
35+parseXML :: String -> [Content]
36+parseXML xs = parse $ tokens $ preprocess xs
38+------------------------------------------------------------------------
40+parse :: [Token] -> [Content]
42+parse ts = let (es,_,ts1) = nodes ([],Nothing) [] ts
45+-- Information about namespaces.
46+-- The first component is a map that associates prefixes to URIs,
47+-- the second is the URI for the default namespace, if one was provided.
48+type NSInfo = ([(String,String)],Maybe String)
50+nodes :: NSInfo -> [QName] -> [Token] -> ([Content], [QName], [Token])
52+nodes ns ps (TokCRef ref : ts) =
53+ let (es,qs,ts1) = nodes ns ps ts
54+ in (CRef ref : es, qs, ts1)
56+nodes ns ps (TokText txt : ts) =
57+ let (es,qs,ts1) = nodes ns ps ts
58+ (more,es1) = case es of
60+ | cdVerbatim cd == cdVerbatim txt -> (cdData cd,es1')
63+ in (Text txt { cdData = cdData txt ++ more } : es1, qs, ts1)
65+nodes cur_info ps (TokStart p t as empty : ts) = (node : siblings, open, toks)
67+ new_name = annotName new_info t
68+ new_info = foldr addNS cur_info as
69+ node = Elem Element { elLine = Just p
71+ , elAttribs = map (annotAttr new_info) as
72+ , elContent = children
75+ (children,(siblings,open,toks))
76+ | empty = ([], nodes cur_info ps ts)
77+ | otherwise = let (es1,qs1,ts1) = nodes new_info (new_name:ps) ts
80+ [] -> nodes cur_info ps ts1
81+ _ : qs3 -> ([],qs3,ts1))
83+nodes ns ps (TokEnd p t : ts) = let t1 = annotName ns t
84+ in case break (t1 ==) ps of
85+ (as,_:_) -> ([],as,ts)
86+ -- Unknown closing tag. Insert as text.
88+ let (es,qs,ts1) = nodes ns ps ts
91+ cdVerbatim = CDataText,
95+nodes _ ps [] = ([],ps,[])
98+annotName :: NSInfo -> QName -> QName
99+annotName (namespaces,def_ns) n =
100+ n { qURI = maybe def_ns (`lookup` namespaces) (qPrefix n) }
102+annotAttr :: NSInfo -> Attr -> Attr
103+annotAttr ns a@(Attr { attrKey = k}) =
104+ case (qPrefix k, qName k) of
105+ (Nothing,"xmlns") -> a
106+ _ -> a { attrKey = annotName ns k }
108+addNS :: Attr -> NSInfo -> NSInfo
109+addNS (Attr { attrKey = key, attrVal = val }) (ns,def) =
110+ case (qPrefix key, qName key) of
111+ (Nothing,"xmlns") -> (ns, if null val then Nothing else Just val)
112+ (Just "xmlns", k) -> ((k, val) : ns, def)
116+-- Lexer -----------------------------------------------------------------------
118+type LChar = (Line,Char)
119+type LString = [LChar]
120+data Token = TokStart Line QName [Attr] Bool -- is empty?
126+tokens :: String -> [Token]
127+tokens = tokens' . linenumber 1
129+tokens' :: LString -> [Token]
130+tokens' ((_,'<') : c@(_,'!') : cs) = special c cs
132+tokens' ((_,'<') : cs) = tag (dropSpace cs) -- we are being nice here
134+tokens' cs@((l,_):_) = let (as,bs) = breakn ('<' ==) cs
135+ in map cvt (decode_text as) ++ tokens' bs
137+ -- XXX: Note, some of the lines might be a bit inacuarate
138+ where cvt (TxtBit x) = TokText CData { cdLine = Just l
139+ , cdVerbatim = CDataText
142+ cvt (CRefBit x) = case cref_to_char x of
143+ Just c -> TokText CData { cdLine = Just l
144+ , cdVerbatim = CDataText
147+ Nothing -> TokCRef x
150+special :: LChar -> LString -> [Token]
151+special _ ((_,'-') : (_,'-') : cs) = skip cs
152+ where skip ((_,'-') : (_,'-') : (_,'>') : ds) = tokens' ds
153+ skip (_ : ds) = skip ds
154+ skip [] = [] -- unterminated comment
156+special c ((_,'[') : (_,'C') : (_,'D') : (_,'A') : (_,'T') : (_,'A') : (_,'[')
158+ let (xs,ts) = cdata cs
159+ in TokText CData { cdLine = Just (fst c), cdVerbatim = CDataVerbatim, cdData = xs }
161+ where cdata ((_,']') : (_,']') : (_,'>') : ds) = ([],ds)
162+ cdata ((_,d) : ds) = let (xs,ys) = cdata ds in (d:xs,ys)
166+ let (xs,ts) = munch "" 0 cs
167+ in TokText CData { cdLine = Just (fst c), cdVerbatim = CDataRaw, cdData = '<':'!':(reverse xs) } : tokens' ts
168+ where munch acc nesting ((_,'>') : ds)
169+ | nesting == (0::Int) = ('>':acc,ds)
170+ | otherwise = munch ('>':acc) (nesting-1) ds
171+ munch acc nesting ((_,'<') : ds)
172+ = munch ('<':acc) (nesting+1) ds
173+ munch acc n ((_,x) : ds) = munch (x:acc) n ds
174+ munch acc _ [] = (acc,[]) -- unterminated DTD markup
176+--special c cs = tag (c : cs) -- invalid specials are processed as tags
179+qualName :: LString -> (QName,LString)
180+qualName xs = let (as,bs) = breakn endName xs
181+ (q,n) = case break (':'==) as of
182+ (q1,_:n1) -> (Just q1, n1)
184+ in (QName { qURI = Nothing, qPrefix = q, qName = n }, bs)
185+ where endName x = isSpace x || x == '=' || x == '>' || x == '/'
191+tag :: LString -> [Token]
192+tag ((p,'/') : cs) = let (n,ds) = qualName (dropSpace cs)
193+ in TokEnd p n : case ds of
194+ (_,'>') : es -> tokens' es
195+ -- tag was not properly closed...
198+tag cs = let (n,ds) = qualName cs
199+ (as,b,ts) = attribs (dropSpace ds)
200+ in TokStart (fst (head cs)) n as b : ts
202+attribs :: LString -> ([Attr], Bool, [Token])
203+attribs cs = case cs of
204+ (_,'>') : ds -> ([], False, tokens' ds)
206+ (_,'/') : ds -> ([], True, case ds of
207+ (_,'>') : es -> tokens' es
208+ -- insert missing > ...
211+ (_,'?') : (_,'>') : ds -> ([], True, tokens' ds)
213+ -- doc ended within a tag..
216+ _ -> let (a,cs1) = attrib cs
217+ (as,b,ts) = attribs cs1
220+attrib :: LString -> (Attr,LString)
221+attrib cs = let (ks,cs1) = qualName cs
222+ (vs,cs2) = attr_val (dropSpace cs1)
223+ in ((Attr ks (decode_attr vs)),dropSpace cs2)
225+attr_val :: LString -> (String,LString)
226+attr_val ((_,'=') : cs) = string (dropSpace cs)
227+attr_val cs = ("",cs)
230+dropSpace :: LString -> LString
231+dropSpace = dropWhile (isSpace . snd)
233+-- | Match the value for an attribute. For malformed XML we do
234+-- our best to guess the programmer's intention.
235+string :: LString -> (String,LString)
236+string ((_,'"') : cs) = break' ('"' ==) cs
238+-- Allow attributes to be enclosed between ' '.
239+string ((_,'\'') : cs) = break' ('\'' ==) cs
241+-- Allow attributes that are not enclosed by anything.
242+string cs = breakn eos cs
243+ where eos x = isSpace x || x == '>' || x == '/'
246+break' :: (a -> Bool) -> [(b,a)] -> ([a],[(b,a)])
247+break' p xs = let (as,bs) = breakn p xs
252+breakn :: (a -> Bool) -> [(b,a)] -> ([a],[(b,a)])
253+breakn p l = (map snd as,bs) where (as,bs) = break (p . snd) l
257+decode_attr :: String -> String
258+decode_attr cs = concatMap cvt (decode_text cs)
259+ where cvt (TxtBit x) = x
260+ cvt (CRefBit x) = case cref_to_char x of
262+ Nothing -> '&' : x ++ ";"
264+data Txt = TxtBit String | CRefBit String deriving Show
266+decode_text :: [Char] -> [Txt]
267+decode_text xs@('&' : cs) = case break (';' ==) cs of
268+ (as,_:bs) -> CRefBit as : decode_text bs
271+decode_text cs = let (as,bs) = break ('&' ==) cs
272+ in TxtBit as : decode_text bs
274+cref_to_char :: [Char] -> Maybe Char
275+cref_to_char cs = case cs of
276+ '#' : ds -> num_esc ds
284+num_esc :: String -> Maybe Char
285+num_esc cs = case cs of
286+ 'x' : ds -> check (readHex ds)
287+ _ -> check (reads cs)
289+ where check [(n,"")] = cvt_char n
292+cvt_char :: Int -> Maybe Char
294+ | fromEnum (minBound :: Char) <= x && x <= fromEnum (maxBound::Char)
296+ | otherwise = Nothing
298+preprocess :: String -> String
299+preprocess ('\r' : '\n' : cs) = '\n' : preprocess cs
300+preprocess ('\r' : cs) = '\n' : preprocess cs
301+preprocess (c : cs) = c : preprocess cs
304+linenumber :: Line -> String -> LString
306+linenumber n ('\n':s) = n' `seq` ((n,'\n'):linenumber n' s) where n' = n + 1
307+linenumber n (c:s) = (n,c) : linenumber n s