@@ -1,452 +1,450 @@
1−{-# LANGUAGE FlexibleInstances #-}
2−{-# LANGUAGE LambdaCase #-}
31{-# LANGUAGE OverloadedStrings #-}
4−{-# LANGUAGE TupleSections #-}
52
63module Main
7− ( main
8− ) where
9−
10−import Control.Monad.RWS.CPS (RWS, execRWS)
11−import Control.Monad.Reader
12−import Control.Monad.State.Strict
13−import Control.Monad.Writer.CPS (Writer, tell, execWriter)
14−import Data.ByteString.Lazy as BL
15−import Data.Char as C
16−import Data.Default
17−import Data.Foldable as F
18−import Data.List as L
19−import Data.Map.Strict as M
20−import Data.Set as S
21−import Data.Text as T
22−import Data.Text.IO as T
23−import Data.Traversable
24−import Debug.Trace
25−import System.IO
26−import Text.XSD
27−import Options
28−import Data.Maybe
29−
30−
31−makeNamePrefix :: Text -> Text
32−makeNamePrefix = T.map C.toLower . T.filter (\c -> C.isUpper c || C.isDigit c)
33−
34−type GenMonad = ReaderT DatatypeMap (Writer Text)
35−
36−class Fields a where
37− fields :: a -> [Text]
38−
39−instance Fields Datatype where
40− fields (TypeComplex ty) = fields ty
41− fields (TypeSimple ty) = fields ty
42−
43−instance Fields SimpleType where
44− fields ty@(STAtomic tyName _ _ restrictions) = if shouldBeNewtype ty
45− then [getNewtypeUnconsName tyName]
46− else getEnumeratedCode restrictions
47−
48−instance Fields ComplexType where
49− fields (ComplexType _ _ _ (Just g)) = fields g
50− fields (ComplexType _ _ _ Nothing) = []
51−
52−instance Fields ModelGroupSchema where
53− fields (CTSequence els) = snd . name <$> els
54− fields (CTChoice els) = snd . name <$> els
55− fields (CTAll els) = snd . name <$> els
56−
57−class References a where
58− references :: a -> [Text]
4+( main
5+)
6+where
597
60−instance References Datatype where
61− references (TypeComplex (ComplexType _ _ _ mmgs)) =
62− case mmgs of
63− Just mgs -> case mgs of
64− CTSequence els -> F.concatMap references els
65− CTChoice els -> F.concatMap references els
66− CTAll els -> F.concatMap references els
67− Nothing -> []
68− references (TypeSimple _) = []
69−
70−instance References Element where
71− references (Element _ t _ _ _) = references t
72−
73−instance References DatatypeRef where
74− references (DatatypeRef ty) = [ty]
75− references (InlineComplex dt) = references dt
76−
77−instance References a => References [a] where
78− references = F.concatMap references
79−
80−-- | 'DatatypeMap' are the types left to process
81−-- 'S.Set Text' are the types already processed.
82−type PreMonad = StateT (DatatypeMap, S.Set Text) (Writer [(Text, Datatype)])
83−
84−type PreElemMonad = RWS DatatypeMap [Element] [Element]
85−
86−-- | Marks the given type as processed.
87−proceed :: Text -> Datatype -> PreMonad ()
88−proceed t dt = do
89− tell [(t, dt)]
90− modify $ \(f,s) -> (M.delete t f, S.insert t s)
91−
92−-- | Marks element as processed.
93−proceed' :: Element -> PreElemMonad ()
94−proceed' el = do
95− tell [el]
96− modify $ L.delete el
97−
98−untwistDeps :: [Element] -> DatatypeMap -> ([(Text, Datatype)], [Element])
99−untwistDeps e dm = (dList, e')
100− where
101− dList = disambiguateNames . nub . execWriter $ do
102− (a, _) <- runStateT sortDatatypesByDeps (dm, S.empty)
103− return a
104− (_, e') = execRWS sortElemsByDeps (M.fromList dList) e
105−
106−type Abbreviation = Text
107−type Subelement = Text
108−type DisambiguaterMonad = State (M.Map Abbreviation (S.Set Subelement))
109−
110−-- | If any two datatypes with the same name abbreviation ('makeNamePrefix')
111−-- have any fields in common, then one of them gets a \"2\" appended to it
112−-- (\"_2\" if the last character of the name was a digit).
113−-- Repeat the same process until there are no conflicts.
114−-- If we have already appended a \"2\" to a datatype and it still has conflicts,
115−-- we change the 2 to a 3, a 3 to a 4 and so on.
116−disambiguateNames :: [(Text, Datatype)] -> [(Text, Datatype)]
117−disambiguateNames = flip evalState mempty . mapM disambiguateName
118− where
119− disambiguateName :: (Text, Datatype) -> DisambiguaterMonad (Text, Datatype)
120− disambiguateName (tyName', dt) = do
121− let rNames = S.fromList $ fields dt
122− (, dt) <$> attempt tyName' rNames 1
123− where
124− attempt :: Abbreviation -> S.Set Subelement -> Int -> DisambiguaterMonad Text
125− attempt tyName fieldNames n = do
126− processedTypes <- get
127− let
128− newTyName
129− | n == 1 = tyName
130− | shouldSeparateNumber = tyName <> "_" <> T.pack (show n)
131− | otherwise = tyName <> T.pack (show n)
132− abr = makeNamePrefix newTyName
133− case M.lookup abr processedTypes of
134− Just usedNames ->
135− if S.null $ S.intersection fieldNames usedNames
136− then modify (M.adjust (S.union fieldNames) abr) >> return newTyName
137− else attempt tyName fieldNames (n + 1)
138− Nothing -> modify (M.insert abr fieldNames) >> return newTyName
139− shouldSeparateNumber = isDigit $ T.last tyName'
140−
141−sortElemsByDeps :: PreElemMonad ()
142−sortElemsByDeps = do
143− els <- get
144− if Prelude.null els then pure () else do
145− let first = Prelude.head els
146− -- traceM $ "sortElemsByDeps: " <> show first
147− case references first of
148− [] -> proceed' first >> sortElemsByDeps
149− xs -> do
150− results <- traverse memberDatatype xs
151− if L.and results
152− then proceed' first >> sortElemsByDeps
153− else do
154− let failed = fmap snd $ L.filter (not . fst) $ L.zip results xs
155− error $ "impossible to lookup types: " <> show failed
156−
157−memberDatatype :: Text -> PreElemMonad Bool
158−memberDatatype ty = do
159− -- traceM $ "memberDatatype: " <> show ty
160− dm <- ask
161− case M.lookup ty dm of
162− Just _ -> return True
163− Nothing -> return False
164−
165−sortDatatypesByDeps :: PreMonad ()
166−sortDatatypesByDeps = do
167− (dm, _) <- get
168− if M.null dm then pure () else do
169− let first = Prelude.head (M.toList dm)
170− traceM $ "sortDatatypesByDeps: " <> show first
171− case references $ snd first of
172− [] -> uncurry proceed first >> sortDatatypesByDeps
173− xs -> do
174− traverse_ lookupDatatype xs
175− uncurry proceed first
176− sortDatatypesByDeps
177−
178−lookupDatatype :: Text -> PreMonad ()
179−lookupDatatype ty = do
180− traceM $ "lookupDatatype: " <> show ty
181− (dm, s) <- get
182− case M.lookup ty dm of
183− Nothing -> if S.member ty s then pure () else
184− error $ "can't look up datatype: " <> show ty
185− Just typ -> case references typ of
186− [] -> proceed ty typ
187− xs -> traverse_ lookupDatatype xs >> proceed ty typ
188−
189−class Capitalizable t where
190− capitalize :: t -> t
191−
192−instance Capitalizable String where
193− capitalize [] = []
194− capitalize (a:as) = C.toUpper a : as
195−
196−instance Capitalizable Text where
197− capitalize t
198− | T.null t = t
199− | otherwise = T.singleton (C.toUpper (T.head t)) <> T.tail t
200−
201−data DataFlavour = QQ | Plain
202−
203−-- TODO: improve after moving some XML types to xml-isogen
204−simpleTypeToIsoType :: DataFlavour -> SimpleAtomicType -> Text
205−simpleTypeToIsoType fl = \case
206− STAnyURI -> wrap fl "Text"
207− STBase64Binary -> wrap fl "ByteString"
208− STBoolean -> wrap fl "Bool"
209− STDate -> wrap fl "Date \"%YYYYj\""
210− STDateTime -> wrap fl "Text"
211− STDateTimeStamp -> wrap fl "Text"
212− STDecimal DTDecimal -> wrap fl "Double"
213− (STDecimal _) -> wrap fl "Integer"
214− STDouble -> wrap fl "Double"
215− (STDuration _) -> wrap fl "Integer"
216− STFloat -> wrap fl "Float"
217− STGDay -> wrap fl "Day"
218− STGMonth -> wrap fl "Text"
219− STGMonthDay -> wrap fl "Text"
220− STGYear -> wrap fl "Text"
221− STGYearMonth -> wrap fl "Text"
222− STHexBinary -> wrap fl "Text"
223− STNOTATION -> wrap fl "Text"
224− STQName -> wrap fl "Text"
225− (STString _) -> wrap fl "Text"
226− STTime -> wrap fl "Text"
227− where
228− wrap QQ t = "[t|" <> t <> "|]"
229− wrap Plain t = t
230−
231−tellGen
232− :: [Text] -- generated code
233− -> Text -- comment
234− -> GenMonad ()
235−tellGen code comment =
236− tell $ "\n" <> comment <> T.unlines code
8+import Data.Text (Text)
9+import qualified Data.Text as Text
10+import qualified Data.Text.IO as Text
11+import Data.Maybe
12+import qualified Data.List as List
13+import qualified Data.Set as Set
14+import Data.Map (Map)
15+import qualified Data.Map as Map
16+import Control.Monad
17+import qualified System.IO as IO
18+import qualified Xsd
23719
238−runGen :: DatatypeMap -> GenMonad a -> Text
239−runGen dm act = execWriter $ runReaderT act dm
20+import Options
21+import Gen
22+import References
23+import BuiltInTypes
24024
241−generateIsoXml :: Maybe Header -> ModuleName -> GenType -> XSD -> Text
242−generateIsoXml mHeader name genType (XSD (e,dm)) =
25+main :: IO ()
26+main = do
27+ opts <- getOptions
28+ schema <- Xsd.getSchema (oInput opts)
29+ res <- either fail return
30+ (generate opts schema)
31+ mapM_ (Text.hPutStrLn IO.stderr) (resultWarnings res)
32+ Text.putStrLn (resultCode res)
33+
34+data Result = Result
35+ { resultCode :: Text
36+ , resultWarnings :: [Text]
37+ }
38+
39+generate :: Options -> Xsd.Schema -> Either String Result
40+generate opts schema = do
24341 let
244− (dList, el) = untwistDeps e dm
245− in (header mHeader name genType <>) . runGen dm $ do
246− for_ dList $ \(t,dt) ->
247− generateIsoDatatype genType t dt []
248− for_ el (generateIsoRecord genType)
249−
250−toQualifier :: Int -> Int -> Text
251−toQualifier minOc maxOc
252− | minOc == 1 && maxOc == 1 = "!"
253− | minOc == 0 && maxOc == 1 = "?"
254− | minOc == 1 && maxOc > minOc = "+"
255− | minOc == 1 && maxOc < minOc = error "maxOccurs < minOccurs"
256− | otherwise = "*"
257−
258−header :: Maybe Header -> ModuleName -> GenType -> Text
259−header mHeader name genType = T.unlines $
260− maybeToList (T.unlines . fmap ("-- " <>) . T.lines <$> mHeader) <>
261− [ "module " <> name <> " where"
262− , ""
263− , "import Control.DeepSeq"
264− , "import Data.THGen.XML"
265− ] <> specImports <>
266− [ "import Prelude hiding ((*), (+))"
267− , "" ]
42+ types = Map.union (Xsd.schemaTypes schema)
43+ (elementsToTypes (Xsd.schemaElements schema))
44+ s <- runGen (initialGenState opts types) $ do
45+ genHeader opts
46+ genTypes types
47+ Right Result
48+ { resultCode = Text.unlines (reverse (gsCode s))
49+ , resultWarnings = reverse (gsWarnings s)
50+ }
51+
52+elementsToTypes :: Map Xsd.QName Xsd.Element -> Map Xsd.QName Xsd.Type
53+elementsToTypes = List.foldl' step Map.empty . Map.toList
26854 where
269− specImports = case genType of
270− Generator -> [ xmlWriter ]
271− Parser -> [ domParser ]
272− Both -> [ domParser, xmlWriter ]
273− xmlWriter, domParser :: Text
274− xmlWriter = "import Text.XML.Writer"
275− domParser = "import Text.XML.DOM.Parser.FromDom"
276−
277−quote :: Text -> Text
278−quote t = "\"" <> t <> "\""
279−
280−generateIsoRecord :: GenType -> Element -> GenMonad ()
281−generateIsoRecord
282− genType
283− (Element (_, laxName) elXtype _ _ elAnnotations) = do
284− written <- ask
285− case elXtype of
286− InlineComplex dt ->
287− generateIsoDatatype genType laxName dt elAnnotations
288− DatatypeRef nam -> if M.member nam written
289− then pure ()
290− else error $ "Implementation failure: "
291− <> show nam <> " type never encountered before"
292−
293−data CommentType = Haddock | Regular
294−
295−toComment :: CommentType -> [Annotation] -> Text
296−toComment ct ann = case texts of
297− [] -> ""
298− (h:tl) -> T.unlines ((prefix <> h) : fmap ("-- "<>) tl)
299− where
300− texts = stripTexts $ F.concatMap (wrap80 . fromDocumentation) ann
301− stripTexts = \case
302− [] -> []
303− l@(h:tl) -> if T.all (\x -> x == ' ' || x == '\n') h then stripTexts tl else l
304− prefix = case ct of
305− Haddock -> "-- | "
306− Regular -> "-- "
307−
308−fromDocumentation :: Annotation -> Text
309−fromDocumentation (Documentation t) = t
310−
311−wrap80 :: Text -> [Text]
312−wrap80 = L.foldl' go [] . T.split (==' ')
313− where
314− go [] e = [e]
315− go l e =
316− let last' = L.last l
317− in if T.length last' + T.length e >= 73 -- 80 minus "-- | " and ' '
318− then l <> pure e
319− else L.init l <> [L.last l <> " " <> e]
320−
321−generateIsoDatatype
322− :: GenType
323− -> Text
324− -> Datatype
325− -> [Annotation]
326− -> GenMonad ()
327− -- ^ (type name for lookups, generated code)
328−generateIsoDatatype
329− genType
330− eName
331− (TypeComplex (ComplexType _ _ tyAnnotations mGroupSchema))
332− annotationsRec =
333− case mGroupSchema of
334− Just groupSchema -> case groupSchema of
335− CTSequence elements -> do
336− tyFields <- for elements (generateIsoField genType)
55+ step types (_, e) = case Xsd.elementType e of
56+ Xsd.Ref _ -> types
57+ Xsd.Inline t -> Map.insert (Xsd.elementName e) t types
58+
59+genTypes :: Map Xsd.QName Xsd.Type -> Gen ()
60+genTypes types = mapM_ (uncurry genTopType) . Map.toList $ types
61+
62+genTopType :: Xsd.QName -> Xsd.Type -> Gen ()
63+genTopType = genType []
64+
65+genType :: [Xsd.Annotation] -> Xsd.QName -> Xsd.Type -> Gen ()
66+genType annotations name tp = do
67+ known <- knownTypeName name
68+ case known of
69+ Just _ -> return () -- already generated
70+ Nothing -> do
71+ -- we should generate dependencies before the type itself to make
72+ -- sure they are in scope when xml-isogen quotes them
73+ -- (stage restriction in TH)
74+ genDependencies tp
75+ typeName <- makeTypeName name tp
76+ case tp of
77+ Xsd.TypeSimple t -> genSimpleType typeName t annotations
78+ Xsd.TypeComplex t -> genComplexType typeName t annotations
79+ genExtension name
80+
81+genExtension :: Xsd.QName -> Gen ()
82+genExtension base = do
83+ exts <- extensions base
84+ case exts of
85+ [] -> return ()
86+ types -> do
87+ mapM_ (uncurry genTopType) types
88+ baseTypeName <- tnPrefixed <$> resolveTypeName base
89+ writeCode
90+ [ "data Any" <> baseTypeName
91+ , " = The" <> baseTypeName <> " !" <> baseTypeName
92+ ]
93+ let
94+ mkConstructor (n, _) = do
95+ tn <- tnPrefixed <$> resolveTypeName n
96+ exts' <- extensions n
33797 let
338− comment = toComment Haddock $ annotationsRec
339− <> [Documentation ""]
340− <> tyAnnotations
341− tyHeader =
342− quote (capitalize eName)
343− <> " =:= record "
344− <> genTypeToText genType
345− tellGen (tyHeader : tyFields) comment
346− CTChoice _ -> error "'Choice' group not supported yet"
347− CTAll _ -> error "'All' group not supported yet"
348− Nothing -> error $ "No group schema provided for type: " <> T.unpack eName
349−generateIsoDatatype
350− genType
351− eName
352− (TypeSimple ty@(STAtomic iName sat tyAnnotations restrictions))
353− annotationsRec = do
354− let
355− comment =
356− toComment Haddock $ annotationsRec
357− <> [Documentation ""]
358− <> tyAnnotations
359− if not (shouldBeNewtype ty)
360− then tellGen
361− (generateEnum
362− (quote $ capitalize eName)
363− (getEnumeratedCode restrictions))
364− comment
365− else
366− tellGen (generateNewtype genType iName sat) comment
367−
368−getEnumeratedCode :: [Restriction] -> [Text]
369−getEnumeratedCode = F.concatMap fromEnumeration . Prelude.filter isEnumeration
98+ n' = case exts' of
99+ [] -> tn
100+ _ -> "Any" <> tn
101+ return (" | The" <> n' <> " !" <> n')
102+ constructors <- mapM mkConstructor types
103+ writeCode constructors
104+ writeCode
105+ [ " deriving (Eq, Show)"
106+ , ""
107+ ]
108+ writeCode
109+ [ "instance NFData Any" <> baseTypeName <> " where"
110+ , " rnf = rwhnf"
111+ , " "
112+ ]
113+ mode <- getMode
114+ unless (mode == Generator) $ do
115+ writeCode
116+ [ "instance FromDom Any" <> baseTypeName <> " where"
117+ , " fromDom = do"
118+ , " tp <- parseAttribute"
119+ , " (matchName " <>
120+ "\"{http://www.w3.org/2001/XMLSchema-instance}type\")"
121+ , " Right"
122+ , " case tp of"
123+ ]
124+ let
125+ mkClause n = do
126+ tn <- resolveTypeName n
127+ exts' <- extensions n
128+ n' <- case exts' of
129+ [] -> return (tnPrefixed tn)
130+ _ | n == base -> return (tnPrefixed tn)
131+ _ -> return ("Any" <> tnPrefixed tn)
132+ return $ mconcat
133+ [ " \""
134+ , tnName tn
135+ , "\" -> The"
136+ , n'
137+ , " <$> fromDom"
138+ ]
139+ clauses <- mapM mkClause (base : map fst types)
140+ writeCode clauses
141+ writeCode
142+ [ " _ -> throwParserError (PEOther \"Unexpected type\")"
143+ , ""
144+ ]
145+ unless (mode == Parser) $ do
146+ writeCode
147+ [ "instance ToXML Any" <> baseTypeName <> " where"
148+ , " toXML (The" <> baseTypeName <> " a) = toXML a"
149+ ]
150+ let
151+ mkClause (n, _) = do
152+ tn <- tnPrefixed <$> resolveTypeName n
153+ exts' <- extensions n
154+ let
155+ n' = case exts' of
156+ [] -> tn
157+ _ -> "Any" <> tn
158+ return (" toXML (The" <> n' <> " a) = toXML a")
159+ clauses <- mapM mkClause types
160+ writeCode clauses
161+ writeCode [""]
162+ writeCode
163+ [ "instance ToXmlParentAttributes Any" <> baseTypeName <> " where"
164+ ]
165+ let
166+ toAttrLine n = do
167+ tn <- resolveTypeName n
168+ exts' <- extensions n
169+ n' <- case exts' of
170+ [] -> return (tnPrefixed tn)
171+ _ | n == base -> return (tnPrefixed tn)
172+ _ -> return ("Any" <> tnPrefixed tn)
173+ return
174+ [ " toXmlParentAttributes (The" <> n' <> " a) ="
175+ , " (\"{http://www.w3.org/2001/XMLSchema-instance}type\", \""
176+ <> tnName tn <> "\")"
177+ , " : toXmlParentAttributes a"
178+ ]
179+ attrLines <- mapM toAttrLine (base : map fst types)
180+ writeCode (concat attrLines)
181+
182+genDependencies :: References a => a -> Gen ()
183+genDependencies a = forM_ (references a) $ \name -> do
184+ known <- knownTypeName name
185+ case known of
186+ Just _ -> return () -- already generated
187+ Nothing -> do
188+ tp <- resolveType name
189+ genTopType name tp
190+
191+genSimpleType :: TypeName -> Xsd.SimpleType -> [Xsd.Annotation]-> Gen ()
192+genSimpleType tn (Xsd.AtomicType restriction ann) parentAnn = do
193+ let
194+ baseName r = case Xsd.simpleRestrictionBase r of
195+ Xsd.Ref n -> Just n
196+ Xsd.Inline (Xsd.AtomicType r' _) -> baseName r'
197+ Xsd.Inline (Xsd.ListType _ _) -> Nothing
198+ Xsd.Inline (Xsd.UnionType _ _) -> Nothing
199+ case baseName restriction of
200+ Just _
201+ | isEnum restriction
202+ -> genEnum tn
203+ (Xsd.simpleRestrictionConstraints restriction)
204+ (parentAnn <> ann)
205+ Just base ->
206+ genNewtype tn base (parentAnn <> ann)
207+ _ -> genUnsupported tn
208+genSimpleType typeName (Xsd.ListType _ _) _ = genUnsupported typeName
209+genSimpleType typeName (Xsd.UnionType _ _) _ = genUnsupported typeName
210+
211+genNewtype :: TypeName -> Xsd.QName -> [Xsd.Annotation] -> Gen ()
212+genNewtype tn base annots = do
213+ fieldTypeName <- tnPrefixed <$> resolveTypeName base
214+ mode <- getMode
215+ let
216+ typeName = tnPrefixed tn
217+ fieldName = "un" <> typeName
218+ toxml = case mode of
219+ Parser -> ""
220+ _ -> ", ToXML"
221+ writeCode $ makeComments tn annots
222+ writeCode
223+ [ "newtype " <> typeName
224+ , " = " <> typeName
225+ , " { " <> fieldName <> " :: " <> fieldTypeName
226+ , " } deriving (Show, Eq, NFData" <> toxml <> ")"
227+ , ""
228+ ]
229+ unless (mode == Generator) $ writeCode
230+ [ "instance FromDom " <> typeName <> " where"
231+ , " fromDom = " <> typeName <> " <$> fromDom"
232+ , ""
233+ ]
234+
235+genEnum :: TypeName -> [Xsd.Constraint] -> [Xsd.Annotation] -> Gen ()
236+genEnum tn constraints annots = do
237+ mode <- getMode
238+ let
239+ values = map toValue constraints
240+ toValue (Xsd.Enumeration v) = v
241+ enumLines <- forM values $ \v -> do
242+ enumName <- makeEnumName v
243+ return (" & \"" <> enumName <> "\"")
244+ writeCode $ makeComments tn annots
245+ writeCode $ "\"" <> tnName tn <> "\" Exhaustive =:= enum "
246+ <> genTypeToText mode : enumLines
247+ writeCode [""]
248+
249+isEnum :: Xsd.SimpleRestriction -> Bool
250+isEnum = any isEnumConstraint . Xsd.simpleRestrictionConstraints
370251 where
371− fromEnumeration (Enumeration x) = x
252+ isEnumConstraint (Xsd.Enumeration _) = True
372253
373−isEnumeration :: Restriction -> Bool
374−isEnumeration (Enumeration _) = True
375−
376−shouldBeNewtype :: SimpleType -> Bool
377−shouldBeNewtype (STAtomic _ _ _ restrictions) =
378− not . Prelude.any isEnumeration $ restrictions
379−
380−getNewtypeConsName :: Text -> Text
381−getNewtypeConsName = ("Xml" <>) . capitalize
382−
383−getNewtypeUnconsName :: Text -> Text
384−getNewtypeUnconsName = ("un" <>) . getNewtypeConsName
385−
386−generateNewtype :: GenType -> Text -> SimpleAtomicType -> [Text]
387−generateNewtype genType n sat =
388− let
389− constructor = getNewtypeConsName n
390− decons = getNewtypeUnconsName n
391− parser =
392− [ ""
393− , "instance FromDom " <> constructor <> " where"
394− , " fromDom = " <> constructor <> " <$> fromDom"
395− ]
396− in
397− [ "newtype " <> constructor
398− , " = " <> constructor
399− , " { " <> decons <> " :: " <> simpleTypeToIsoType Plain sat
400− , " } deriving (Show, Eq, NFData" <> case genType of
401− Parser -> ")"
402− _ -> ", ToXML)"
403− ] <> case genType of
404− Generator -> []
405− _ -> parser
406−
407−generateEnum
408− :: Text -- type name
409− -> [Text] -- enums
410− -> [Text] -- generated code
411−generateEnum enumName enums =
254+genComplexType :: TypeName -> Xsd.ComplexType -> [Xsd.Annotation] -> Gen ()
255+genComplexType typeName t parentAnn = do
256+ mode <- getMode
412257 let
413− enumHeader = enumName <> " Exhaustive =:= enum Both"
414− eFields = ("& "<>) <$> enums
415− in pure enumHeader <> eFields
416−
417−lookupSimpleType
418− :: DatatypeRef
419− -> GenMonad (Maybe Text)
420−lookupSimpleType (InlineComplex _) = pure Nothing
421−lookupSimpleType (DatatypeRef tyName) =
422− asks (M.lookup tyName) >>= \case
423− Just (TypeComplex _) -> pure Nothing
424− Just (TypeSimple (STAtomic nam _ _ _)) -> pure $ Just nam
425− Nothing -> error $ "can't look up type: " <> show tyName
426−
427−generateIsoField :: GenType -> Element -> GenMonad Text
428−generateIsoField
429− genType
430− (Element (_, fieldName) fieldXtype minOc maxOc fieldAnnotations) = do
431− let
432− qualifier = toQualifier minOc maxOc
433− line <- lookupSimpleType fieldXtype >>= \case
434− Just tyName ->
435− pure $ quote fieldName <> " [t|Xml" <> tyName <> "|]"
436− Nothing -> case fieldXtype of
437− InlineComplex dt -> do
438− generateIsoDatatype genType (capitalize fieldName) dt fieldAnnotations
439− pure $ quote fieldName
440− DatatypeRef ref ->
441− pure $ quote fieldName <> " [t|Xml" <> capitalize ref <> "|]"
442− pure $ " " <> qualifier <> " " <> line
258+ header = "\"" <> tnName typeName <> "\" =:= record "
259+ <> genTypeToText mode
260+ fields <- genFields typeName (Xsd.complexContent t)
261+ writeCode $ makeComments typeName
262+ (parentAnn <> Xsd.complexAnnotations t)
263+ writeCode [header]
264+ writeCode fields
265+ writeCode [""]
266+
267+makeComments :: TypeName -> [Xsd.Annotation] -> [Text]
268+makeComments typeName annotations = if null annotations
269+ then
270+ [ "{-|"
271+ , generated
272+ , "-}"
273+ ]
274+ else
275+ [ "{-|"
276+ , generated
277+ , ""
278+ ] <> map makeDoc annotations <>
279+ [ "-}"
280+ ]
281+ where
282+ generated = "Generated from: " <> prefix <> name
283+ qname = tnQName typeName
284+ name = Xsd.qnName qname
285+ prefix = maybe "" ((<> ":") . Xsd.fromNamespace) (Xsd.qnNamespace qname)
286+ makeDoc (Xsd.Documentation docs) = docs
287+
288+-- | Generate code for record fields
289+--
290+-- The first argument - record name
291+genFields :: TypeName -> Xsd.Content -> Gen [Text]
292+genFields typeName (Xsd.ContentPlain c) =
293+ maybe (return []) (genFieldsForModel typeName) (Xsd.plainContentModel c)
294+genFields _ (Xsd.ContentSimple _) = return []
295+genFields typeName (Xsd.ContentComplex (Xsd.ComplexContentExtension e)) = do
296+ base <- resolveType (Xsd.complexExtensionBase e)
297+ genDependencies base
298+ baseFields <- case base of
299+ Xsd.TypeComplex t -> genFields typeName (Xsd.complexContent t)
300+ _ -> return []
301+ fields <- maybe (return []) (genFieldsForModel typeName)
302+ (Xsd.complexExtensionModel e)
303+ return (baseFields ++ fields)
304+genFields _ (Xsd.ContentComplex (Xsd.ComplexContentRestriction _)) =
305+ return []
306+
307+genFieldsForModel :: TypeName -> Xsd.ModelGroup -> Gen [Text]
308+genFieldsForModel typeName (Xsd.Sequence elements) =
309+ catMaybes <$> mapM (genField typeName) elements
310+genFieldsForModel _ (Xsd.Choice _) = do
311+ warn "choice: not implemented"
312+ return []
313+genFieldsForModel _ (Xsd.All _) = do
314+ warn "all: not implemented"
315+ return []
316+
317+genField :: TypeName -> Xsd.RefOr Xsd.Element -> Gen (Maybe Text)
318+genField _ (Xsd.Ref _) = return Nothing
319+genField typeName (Xsd.Inline e) = do
320+ fieldName <- makeFieldName typeName (Xsd.elementName e)
321+
322+ fieldTypeName <- case Xsd.elementType e of
323+ Xsd.Ref name -> do
324+ tn <- tnPrefixed <$> resolveTypeName name
325+ exts <- extensions name
326+ case exts of
327+ [] -> return tn
328+ _ -> return ("Any" <> tn)
329+ Xsd.Inline t -> do
330+ genType (Xsd.elementAnnotations e) (Xsd.elementName e) t
331+ tnPrefixed <$> resolveTypeName (Xsd.elementName e)
332+
333+ qualifier <- makeQualifier (Xsd.elementOccurs e)
443334
444−main :: IO ()
445−main = do
446− Options{..} <- getOptions
447− xml <- BL.readFile oInput
448335 let
449− xsd = case parseXSD def xml of
450− Right xsd' -> xsd'
451− Left e -> error $ show e
452− T.hPutStrLn stdout $ generateIsoXml oHeader oModule oMode xsd
336+ fieldType = if Xsd.elementNillable e
337+ then "Nillable " <> fieldTypeName
338+ else fieldTypeName
339+
340+ return $ Just $ mconcat
341+ [ " "
342+ , qualifier
343+ , " \""
344+ , fieldName
345+ , "\" [t|"
346+ , fieldType
347+ , "|]"
348+ ]
349+
350+makeQualifier :: (Int, Xsd.MaxOccurs) -> Gen Text
351+makeQualifier (minOcc, maxOcc) = case maxOcc of
352+ Xsd.MaxOccursUnbound -> toQualifier minOcc maxBound
353+ Xsd.MaxOccurs v -> toQualifier minOcc v
354+
355+toQualifier :: Int -> Int -> Gen Text
356+toQualifier 1 1 = return "!"
357+toQualifier 0 1 = return "?"
358+toQualifier 1 maxOcc
359+ | maxOcc < 1
360+ = genError "maxOccurs < minOccurs"
361+toQualifier 1 maxOcc
362+ | maxOcc > 1
363+ = return "+"
364+toQualifier _ _ = return "*"
365+
366+genUnsupported :: TypeName -> Gen ()
367+genUnsupported tn = do
368+ let typeName = tnPrefixed tn
369+ warn $ "generating stub for unsupported construct in " <> typeName
370+ mode <- getMode
371+ writeCode (makeComments tn [])
372+ writeCode
373+ [ "data " <> typeName <> " = " <> typeName
374+ , " deriving (Eq, Show)"
375+ , ""
376+ , "instance NFData " <> typeName <> " where"
377+ , " rnf _ = ()"
378+ , ""
379+ ]
380+
381+ unless (mode == Parser) $ writeCode
382+ [ "instance ToXML " <> typeName <> " where"
383+ , " toXML _ = comment \"" <> typeName <> "\""
384+ , ""
385+ ]
386+
387+ unless (mode == Generator) $ writeCode
388+ [ "instance FromDom " <> typeName <> " where"
389+ , " fromDom = undefined"
390+ , ""
391+ ]
392+
393+genHeader :: Options -> Gen ()
394+genHeader opts = do
395+ case oHeader opts of
396+ Nothing -> return ()
397+ Just h -> do
398+ writeCode . fmap ("-- " <>) . Text.lines $ h
399+ writeCode [""]
400+
401+ writeCode
402+ [ "{-# OPTIONS_GHC -Wno-unused-imports #-}"
403+ , "module " <> oModule opts <> " where"
404+ , ""
405+ , "import Control.DeepSeq"
406+ , "import Data.Scientific"
407+ , "import Data.THGen.XML"
408+ ]
409+ writeCode imports
410+ writeCode
411+ [ "import Prelude hiding ((*), (+))"
412+ , ""
413+ , ""
414+ ]
415+ where
416+ imports = case oMode opts of
417+ Generator -> [ xmlWriter, parentAttr ]
418+ Parser -> [ domParser ]
419+ ParserAndGenerator -> [ domParser, xmlWriter, parentAttr ]
420+ xmlWriter = "import Text.XML.Writer"
421+ parentAttr = "import Text.XML.ParentAttributes"
422+ domParser = "import Text.XML.DOM.Parser"
423+
424+-- | We populate the initial state with all built-in types to make sure
425+-- they will be correctly resolved
426+initialGenState :: Options -> Map Xsd.QName Xsd.Type -> GenState
427+initialGenState opts types = GenState
428+ { gsTypes = types
429+ , gsExtensions = collectExtensions types
430+ , gsKnownTypes = builtInTypes
431+ , gsBoundTypeName = Set.empty
432+ , gsBoundFields = Set.empty
433+ , gsMode = oMode opts
434+ , gsCode = []
435+ , gsWarnings = []
436+ }
437+
438+collectExtensions
439+ :: Map Xsd.QName Xsd.Type
440+ -> Map Xsd.QName [(Xsd.QName, Xsd.Type)]
441+collectExtensions = List.foldl' step Map.empty . Map.toList
442+ where
443+ step exts (n, t) = case baseOf t of
444+ Nothing -> exts
445+ Just base -> Map.insertWith (++) base [(n, t)] exts
446+ baseOf (Xsd.TypeSimple _) = Nothing
447+ baseOf (Xsd.TypeComplex t) = case Xsd.complexContent t of
448+ Xsd.ContentComplex (Xsd.ComplexContentExtension e) ->
449+ Just (Xsd.complexExtensionBase e)
450+ _ -> Nothing