@@ -1,452 +1,450 @@
1−{-# LANGUAGE FlexibleInstances #-}
2−{-# LANGUAGE LambdaCase #-}
3{-# LANGUAGE OverloadedStrings #-}
1{-# LANGUAGE OverloadedStrings #-}
4−{-# LANGUAGE TupleSections #-}
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
17−import Data.Foldable as F
19−import Data.Map.Strict as M
22−import Data.Text.IO as T
23−import Data.Traversable
31−makeNamePrefix :: Text -> Text
32−makeNamePrefix = T.map C.toLower . T.filter (\c -> C.isUpper c || C.isDigit c)
34−type GenMonad = ReaderT DatatypeMap (Writer Text)
36−class Fields a where
6+where
37− fields :: a -> [Text]
39−instance Fields Datatype where
40− fields (TypeComplex ty) = fields ty
41− fields (TypeSimple ty) = fields ty
43−instance Fields SimpleType where
44− fields ty@(STAtomic tyName _ _ restrictions) = if shouldBeNewtype ty
45− then [getNewtypeUnconsName tyName]
46− else getEnumeratedCode restrictions
48−instance Fields ComplexType where
49− fields (ComplexType _ _ _ (Just g)) = fields g
50− fields (ComplexType _ _ _ Nothing) = []
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
57−class References a where
58− references :: a -> [Text]
60−instance References Datatype where
8+import Data.Text (Text)
61− references (TypeComplex (ComplexType _ _ _ mmgs)) =
9+import qualified Data.Text as Text
62− case mmgs of
10+import qualified Data.Text.IO as Text
63− Just mgs -> case mgs of
11+import Data.Maybe
64− CTSequence els -> F.concatMap references els
12+import qualified Data.List as List
65− CTChoice els -> F.concatMap references els
13+import qualified Data.Set as Set
66− CTAll els -> F.concatMap references els
14+import Data.Map (Map)
67− Nothing -> []
15+import qualified Data.Map as Map
68− references (TypeSimple _) = []
16+import Control.Monad
69−
17+import qualified System.IO as IO
70−instance References Element where
18+import qualified Xsd
71− references (Element _ t _ _ _) = references t
73−instance References DatatypeRef where
74− references (DatatypeRef ty) = [ty]
75− references (InlineComplex dt) = references dt
77−instance References a => References [a] where
78− references = F.concatMap references
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)])
84−type PreElemMonad = RWS DatatypeMap [Element] [Element]
86−-- | Marks the given type as processed.
87−proceed :: Text -> Datatype -> PreMonad ()
90− modify $ \(f,s) -> (M.delete t f, S.insert t s)
92−-- | Marks element as processed.
93−proceed' :: Element -> PreElemMonad ()
98−untwistDeps :: [Element] -> DatatypeMap -> ([(Text, Datatype)], [Element])
99−untwistDeps e dm = (dList, e')
101− dList = disambiguateNames . nub . execWriter $ do
102− (a, _) <- runStateT sortDatatypesByDeps (dm, S.empty)
104− (_, e') = execRWS sortElemsByDeps (M.fromList dList) e
106−type Abbreviation = Text
107−type Subelement = Text
108−type DisambiguaterMonad = State (M.Map Abbreviation (S.Set Subelement))
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
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
124− attempt :: Abbreviation -> S.Set Subelement -> Int -> DisambiguaterMonad Text
125− attempt tyName fieldNames n = do
126− processedTypes <- get
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
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'
141−sortElemsByDeps :: PreElemMonad ()
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
150− results <- traverse memberDatatype xs
152− then proceed' first >> sortElemsByDeps
154− let failed = fmap snd $ L.filter (not . fst) $ L.zip results xs
155− error $ "impossible to lookup types: " <> show failed
157−memberDatatype :: Text -> PreElemMonad Bool
158−memberDatatype ty = do
159− -- traceM $ "memberDatatype: " <> show ty
161− case M.lookup ty dm of
162− Just _ -> return True
163− Nothing -> return False
165−sortDatatypesByDeps :: PreMonad ()
166−sortDatatypesByDeps = do
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
174− traverse_ lookupDatatype xs
175− uncurry proceed first
178−lookupDatatype :: Text -> PreMonad ()
179−lookupDatatype ty = do
180− traceM $ "lookupDatatype: " <> show ty
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
189−class Capitalizable t where
190− capitalize :: t -> t
192−instance Capitalizable String where
194− capitalize (a:as) = C.toUpper a : as
196−instance Capitalizable Text where
199− | otherwise = T.singleton (C.toUpper (T.head t)) <> T.tail t
201−data DataFlavour = QQ | Plain
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"
228− wrap QQ t = "[t|" <> t <> "|]"
232− :: [Text] -- generated code
235−tellGen code comment =
236− tell $ "\n" <> comment <> T.unlines code
238−runGen :: DatatypeMap -> GenMonad a -> Text
20+import Options
239−runGen dm act = execWriter $ runReaderT act dm
21+import Gen
241−generateIsoXml :: Maybe Header -> ModuleName -> GenType -> XSD -> Text
25+main :: IO ()
242−generateIsoXml mHeader name genType (XSD (e,dm)) =
26+main = do
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)
36+ , resultWarnings :: [Text]
39+generate :: Options -> Xsd.Schema -> Either String Result
40+generate opts schema = do
244− (dList, el) = untwistDeps e dm
42+ types = Map.union (Xsd.schemaTypes schema)
245− in (header mHeader name genType <>) . runGen dm $ do
43+ (elementsToTypes (Xsd.schemaElements schema))
246− for_ dList $ \(t,dt) ->
44+ s <- runGen (initialGenState opts types) $ do
247− generateIsoDatatype genType t dt []
45+ genHeader opts
248− for_ el (generateIsoRecord genType)
46+ genTypes types
250−toQualifier :: Int -> Int -> Text
48+ { resultCode = Text.unlines (reverse (gsCode s))
251−toQualifier minOc maxOc
49+ , resultWarnings = reverse (gsWarnings s)
252− | minOc == 1 && maxOc == 1 = "!"
50+ }
253− | minOc == 0 && maxOc == 1 = "?"
51+
254− | minOc == 1 && maxOc > minOc = "+"
52+elementsToTypes :: Map Xsd.QName Xsd.Element -> Map Xsd.QName Xsd.Type
255− | minOc == 1 && maxOc < minOc = error "maxOccurs < minOccurs"
53+elementsToTypes = List.foldl' step Map.empty . Map.toList
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"
263− , "import Control.DeepSeq"
264− , "import Data.THGen.XML"
266− [ "import Prelude hiding ((*), (+))"
269− specImports = case genType of
55+ step types (_, e) = case Xsd.elementType e of
270− Generator -> [ xmlWriter ]
56+ Xsd.Ref _ -> types
271− Parser -> [ domParser ]
57+ Xsd.Inline t -> Map.insert (Xsd.elementName e) t types
272− Both -> [ domParser, xmlWriter ]
58+
273− xmlWriter, domParser :: Text
59+genTypes :: Map Xsd.QName Xsd.Type -> Gen ()
274− xmlWriter = "import Text.XML.Writer"
60+genTypes types = mapM_ (uncurry genTopType) . Map.toList $ types
275− domParser = "import Text.XML.DOM.Parser.FromDom"
61+
276−
62+genTopType :: Xsd.QName -> Xsd.Type -> Gen ()
277−quote :: Text -> Text
63+genTopType = genType []
278−quote t = "\"" <> t <> "\""
64+
279−
65+genType :: [Xsd.Annotation] -> Xsd.QName -> Xsd.Type -> Gen ()
280−generateIsoRecord :: GenType -> Element -> GenMonad ()
282− genType
66+genType annotations name tp = do
283− (Element (_, laxName) elXtype _ _ elAnnotations) = do
67+ known <- knownTypeName name
285− case elXtype of
68+ case known of
286− InlineComplex dt ->
69+ Just _ -> return () -- already generated
287− generateIsoDatatype genType laxName dt elAnnotations
70+ Nothing -> do
288− DatatypeRef nam -> if M.member nam written
71+ -- we should generate dependencies before the type itself to make
289− then pure ()
72+ -- sure they are in scope when xml-isogen quotes them
290− else error $ "Implementation failure: "
73+ -- (stage restriction in TH)
291− <> show nam <> " type never encountered before"
74+ genDependencies tp
292−
75+ typeName <- makeTypeName name tp
293−data CommentType = Haddock | Regular
76+ case tp of
294−
77+ Xsd.TypeSimple t -> genSimpleType typeName t annotations
295−toComment :: CommentType -> [Annotation] -> Text
78+ Xsd.TypeComplex t -> genComplexType typeName t annotations
296−toComment ct ann = case texts of
79+ genExtension name
298− (h:tl) -> T.unlines ((prefix <> h) : fmap ("-- "<>) tl)
81+genExtension :: Xsd.QName -> Gen ()
299− where
82+genExtension base = do
300− texts = stripTexts $ F.concatMap (wrap80 . fromDocumentation) ann
83+ exts <- extensions base
301− stripTexts = \case
84+ case exts of
302− [] -> []
85+ [] -> return ()
303− l@(h:tl) -> if T.all (\x -> x == ' ' || x == '\n') h then stripTexts tl else l
86+ types -> do
304− prefix = case ct of
87+ mapM_ (uncurry genTopType) types
305− Haddock -> "-- | "
88+ baseTypeName <- tnPrefixed <$> resolveTypeName base
306− Regular -> "-- "
89+ writeCode
307−
90+ [ "data Any" <> baseTypeName
308−fromDocumentation :: Annotation -> Text
91+ , " = The" <> baseTypeName <> " !" <> baseTypeName
309−fromDocumentation (Documentation t) = t
92+ ]
311−wrap80 :: Text -> [Text]
94+ mkConstructor (n, _) = do
312−wrap80 = L.foldl' go [] . T.split (==' ')
95+ tn <- tnPrefixed <$> resolveTypeName n
313− where
96+ exts' <- extensions n
316− let last' = L.last l
317− in if T.length last' + T.length e >= 73 -- 80 minus "-- | " and ' '
319− else L.init l <> [L.last l <> " " <> e]
327− -- ^ (type name for lookups, generated code)
331− (TypeComplex (ComplexType _ _ tyAnnotations mGroupSchema))
333− case mGroupSchema of
334− Just groupSchema -> case groupSchema of
335− CTSequence elements -> do
336− tyFields <- for elements (generateIsoField genType)
338− comment = toComment Haddock $ annotationsRec
98+ n' = case exts' of
339− <> [Documentation ""]
99+ [] -> tn
340− <> tyAnnotations
100+ _ -> "Any" <> tn
341− tyHeader =
101+ return (" | The" <> n' <> " !" <> n')
342− quote (capitalize eName)
102+ constructors <- mapM mkConstructor types
343− <> " =:= record "
103+ writeCode constructors
105+ [ " deriving (Eq, Show)"
109+ [ "instance NFData Any" <> baseTypeName <> " where"
114+ unless (mode == Generator) $ do
116+ [ "instance FromDom Any" <> baseTypeName <> " where"
118+ , " tp <- parseAttribute"
120+ "\"{http://www.w3.org/2001/XMLSchema-instance}type\")"
126+ tn <- resolveTypeName n
127+ exts' <- extensions n
129+ [] -> return (tnPrefixed tn)
130+ _ | n == base -> return (tnPrefixed tn)
131+ _ -> return ("Any" <> tnPrefixed tn)
139+ clauses <- mapM mkClause (base : map fst types)
142+ [ " _ -> throwParserError (PEOther \"Unexpected type\")"
145+ unless (mode == Parser) $ do
147+ [ "instance ToXML Any" <> baseTypeName <> " where"
148+ , " toXML (The" <> baseTypeName <> " a) = toXML a"
151+ mkClause (n, _) = do
152+ tn <- tnPrefixed <$> resolveTypeName n
153+ exts' <- extensions n
158+ return (" toXML (The" <> n' <> " a) = toXML a")
159+ clauses <- mapM mkClause types
163+ [ "instance ToXmlParentAttributes Any" <> baseTypeName <> " where"
167+ tn <- resolveTypeName n
168+ exts' <- extensions n
170+ [] -> return (tnPrefixed tn)
171+ _ | n == base -> return (tnPrefixed tn)
172+ _ -> return ("Any" <> tnPrefixed tn)
174+ [ " toXmlParentAttributes (The" <> n' <> " a) ="
175+ , " (\"{http://www.w3.org/2001/XMLSchema-instance}type\", \""
176+ <> tnName tn <> "\")"
177+ , " : toXmlParentAttributes a"
179+ attrLines <- mapM toAttrLine (base : map fst types)
180+ writeCode (concat attrLines)
182+genDependencies :: References a => a -> Gen ()
183+genDependencies a = forM_ (references a) $ \name -> do
184+ known <- knownTypeName name
186+ Just _ -> return () -- already generated
188+ tp <- resolveType name
191+genSimpleType :: TypeName -> Xsd.SimpleType -> [Xsd.Annotation]-> Gen ()
192+genSimpleType tn (Xsd.AtomicType restriction ann) parentAnn = do
194+ baseName r = case Xsd.simpleRestrictionBase r of
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
201+ | isEnum restriction
203+ (Xsd.simpleRestrictionConstraints restriction)
206+ genNewtype tn base (parentAnn <> ann)
207+ _ -> genUnsupported tn
208+genSimpleType typeName (Xsd.ListType _ _) _ = genUnsupported typeName
209+genSimpleType typeName (Xsd.UnionType _ _) _ = genUnsupported typeName
211+genNewtype :: TypeName -> Xsd.QName -> [Xsd.Annotation] -> Gen ()
212+genNewtype tn base annots = do
213+ fieldTypeName <- tnPrefixed <$> resolveTypeName base
216+ typeName = tnPrefixed tn
217+ fieldName = "un" <> typeName
218+ toxml = case mode of
221+ writeCode $ makeComments tn annots
223+ [ "newtype " <> typeName
225+ , " { " <> fieldName <> " :: " <> fieldTypeName
226+ , " } deriving (Show, Eq, NFData" <> toxml <> ")"
229+ unless (mode == Generator) $ writeCode
230+ [ "instance FromDom " <> typeName <> " where"
231+ , " fromDom = " <> typeName <> " <$> fromDom"
235+genEnum :: TypeName -> [Xsd.Constraint] -> [Xsd.Annotation] -> Gen ()
236+genEnum tn constraints annots = do
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 "
344− <> genTypeToText genType
246+ <> genTypeToText mode : enumLines
345− tellGen (tyHeader : tyFields) comment
247+ writeCode [""]
346− CTChoice _ -> error "'Choice' group not supported yet"
248+
347− CTAll _ -> error "'All' group not supported yet"
249+isEnum :: Xsd.SimpleRestriction -> Bool
348− Nothing -> error $ "No group schema provided for type: " <> T.unpack eName
250+isEnum = any isEnumConstraint . Xsd.simpleRestrictionConstraints
352− (TypeSimple ty@(STAtomic iName sat tyAnnotations restrictions))
356− toComment Haddock $ annotationsRec
357− <> [Documentation ""]
359− if not (shouldBeNewtype ty)
362− (quote $ capitalize eName)
363− (getEnumeratedCode restrictions))
366− tellGen (generateNewtype genType iName sat) comment
368−getEnumeratedCode :: [Restriction] -> [Text]
369−getEnumeratedCode = F.concatMap fromEnumeration . Prelude.filter isEnumeration
371− fromEnumeration (Enumeration x) = x
252+ isEnumConstraint (Xsd.Enumeration _) = True
373−isEnumeration :: Restriction -> Bool
254+genComplexType :: TypeName -> Xsd.ComplexType -> [Xsd.Annotation] -> Gen ()
374−isEnumeration (Enumeration _) = True
255+genComplexType typeName t parentAnn = do
376−shouldBeNewtype :: SimpleType -> Bool
377−shouldBeNewtype (STAtomic _ _ _ restrictions) =
378− not . Prelude.any isEnumeration $ restrictions
380−getNewtypeConsName :: Text -> Text
381−getNewtypeConsName = ("Xml" <>) . capitalize
383−getNewtypeUnconsName :: Text -> Text
384−getNewtypeUnconsName = ("un" <>) . getNewtypeConsName
386−generateNewtype :: GenType -> Text -> SimpleAtomicType -> [Text]
387−generateNewtype genType n sat =
389− constructor = getNewtypeConsName n
390− decons = getNewtypeUnconsName n
393− , "instance FromDom " <> constructor <> " where"
394− , " fromDom = " <> constructor <> " <$> fromDom"
397− [ "newtype " <> constructor
398− , " = " <> constructor
399− , " { " <> decons <> " :: " <> simpleTypeToIsoType Plain sat
400− , " } deriving (Show, Eq, NFData" <> case genType of
403− ] <> case genType of
408− :: Text -- type name
410− -> [Text] -- generated code
411−generateEnum enumName enums =
413− enumHeader = enumName <> " Exhaustive =:= enum Both"
258+ header = "\"" <> tnName typeName <> "\" =:= record "
414− eFields = ("& "<>) <$> enums
259+ <> genTypeToText mode
415− in pure enumHeader <> eFields
260+ fields <- genFields typeName (Xsd.complexContent t)
416−
261+ writeCode $ makeComments typeName
417−lookupSimpleType
262+ (parentAnn <> Xsd.complexAnnotations t)
418− :: DatatypeRef
263+ writeCode [header]
419− -> GenMonad (Maybe Text)
264+ writeCode fields
420−lookupSimpleType (InlineComplex _) = pure Nothing
265+ writeCode [""]
421−lookupSimpleType (DatatypeRef tyName) =
266+
422− asks (M.lookup tyName) >>= \case
267+makeComments :: TypeName -> [Xsd.Annotation] -> [Text]
423− Just (TypeComplex _) -> pure Nothing
268+makeComments typeName annotations = if null annotations
424− Just (TypeSimple (STAtomic nam _ _ _)) -> pure $ Just nam
269+ then
425− Nothing -> error $ "can't look up type: " <> show tyName
270+ [ "{-|"
427−generateIsoField :: GenType -> Element -> GenMonad Text
272+ , "-}"
428−generateIsoField
273+ ]
430− (Element (_, fieldName) fieldXtype minOc maxOc fieldAnnotations) = do
275+ [ "{-|"
432− qualifier = toQualifier minOc maxOc
277+ , ""
433− line <- lookupSimpleType fieldXtype >>= \case
278+ ] <> map makeDoc annotations <>
434− Just tyName ->
279+ [ "-}"
435− pure $ quote fieldName <> " [t|Xml" <> tyName <> "|]"
280+ ]
436− Nothing -> case fieldXtype of
281+ where
437− InlineComplex dt -> do
282+ generated = "Generated from: " <> prefix <> name
438− generateIsoDatatype genType (capitalize fieldName) dt fieldAnnotations
283+ qname = tnQName typeName
439− pure $ quote fieldName
284+ name = Xsd.qnName qname
440− DatatypeRef ref ->
285+ prefix = maybe "" ((<> ":") . Xsd.fromNamespace) (Xsd.qnNamespace qname)
441− pure $ quote fieldName <> " [t|Xml" <> capitalize ref <> "|]"
286+ makeDoc (Xsd.Documentation docs) = docs
442− pure $ " " <> qualifier <> " " <> line
287+
288+-- | Generate code for record fields
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)
301+ fields <- maybe (return []) (genFieldsForModel typeName)
302+ (Xsd.complexExtensionModel e)
303+ return (baseFields ++ fields)
304+genFields _ (Xsd.ContentComplex (Xsd.ComplexContentRestriction _)) =
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"
313+genFieldsForModel _ (Xsd.All _) = do
314+ warn "all: not implemented"
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)
322+ fieldTypeName <- case Xsd.elementType e of
324+ tn <- tnPrefixed <$> resolveTypeName name
325+ exts <- extensions name
328+ _ -> return ("Any" <> tn)
330+ genType (Xsd.elementAnnotations e) (Xsd.elementName e) t
331+ tnPrefixed <$> resolveTypeName (Xsd.elementName e)
333+ qualifier <- makeQualifier (Xsd.elementOccurs e)
446− Options{..} <- getOptions
447− xml <- BL.readFile oInput
449− xsd = case parseXSD def xml of
336+ fieldType = if Xsd.elementNillable e
450− Right xsd' -> xsd'
337+ then "Nillable " <> fieldTypeName
451− Left e -> error $ show e
338+ else fieldTypeName
452− T.hPutStrLn stdout $ generateIsoXml oHeader oModule oMode xsd
339+
340+ return $ Just $ mconcat
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
355+toQualifier :: Int -> Int -> Gen Text
356+toQualifier 1 1 = return "!"
357+toQualifier 0 1 = return "?"
360+ = genError "maxOccurs < minOccurs"
364+toQualifier _ _ = return "*"
366+genUnsupported :: TypeName -> Gen ()
367+genUnsupported tn = do
368+ let typeName = tnPrefixed tn
369+ warn $ "generating stub for unsupported construct in " <> typeName
371+ writeCode (makeComments tn [])
373+ [ "data " <> typeName <> " = " <> typeName
374+ , " deriving (Eq, Show)"
376+ , "instance NFData " <> typeName <> " where"
381+ unless (mode == Parser) $ writeCode
382+ [ "instance ToXML " <> typeName <> " where"
383+ , " toXML _ = comment \"" <> typeName <> "\""
387+ unless (mode == Generator) $ writeCode
388+ [ "instance FromDom " <> typeName <> " where"
389+ , " fromDom = undefined"
393+genHeader :: Options -> Gen ()
395+ case oHeader opts of
396+ Nothing -> return ()
398+ writeCode . fmap ("-- " <>) . Text.lines $ h
402+ [ "{-# OPTIONS_GHC -Wno-unused-imports #-}"
403+ , "module " <> oModule opts <> " where"
405+ , "import Control.DeepSeq"
406+ , "import Data.Scientific"
407+ , "import Data.THGen.XML"
411+ [ "import Prelude hiding ((*), (+))"
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"
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
429+ , gsExtensions = collectExtensions types
430+ , gsKnownTypes = builtInTypes
431+ , gsBoundTypeName = Set.empty
432+ , gsBoundFields = Set.empty
433+ , gsMode = oMode opts
439+ :: Map Xsd.QName Xsd.Type
440+ -> Map Xsd.QName [(Xsd.QName, Xsd.Type)]
441+collectExtensions = List.foldl' step Map.empty . Map.toList
443+ step exts (n, t) = case baseOf t of
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)