From 48e1a558476d919a1b8c78e3e0b8430645d1d16b Mon Sep 17 00:00:00 2001 From: Adam Sapek Date: Wed, 25 Mar 2015 23:46:33 -0700 Subject: [PATCH] Simplify the JSON representation of AST --- compiler/Bond/Schema/JSON.hs | 45 ++++++++++++++++++++++++++++++------ compiler/Bond/Schema/Util.hs | 3 +-- 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/compiler/Bond/Schema/JSON.hs b/compiler/Bond/Schema/JSON.hs index 94e4d0e0..0a38dcdd 100644 --- a/compiler/Bond/Schema/JSON.hs +++ b/compiler/Bond/Schema/JSON.hs @@ -59,7 +59,7 @@ instance FromJSON Type where o .: "value" String "user" -> BT_UserDefined <$> o .: "declaration" <*> - o .: "arguments" + o .:? "arguments" .!= [] _ -> modifyFailure (const $ "Invalid value `" ++ show type_ ++ "` for the `type` key.") empty @@ -121,6 +121,10 @@ instance ToJSON Type where [ "type" .= String "parameter" , "value" .= p ] + toJSON (BT_UserDefined decl []) = object + [ "type" .= String "user" + , "declaration" .= decl + ] toJSON (BT_UserDefined decl args) = object [ "type" .= String "user" , "declaration" .= decl @@ -206,11 +210,38 @@ deriving instance Generic Language instance FromJSON Language instance ToJSON Language -deriving instance Generic Namespace -instance FromJSON Namespace -instance ToJSON Namespace +instance FromJSON Namespace where + parseJSON (Object v) = + Namespace <$> + v .:? "language" <*> + v .: "name" + parseJSON x = modifyFailure + (const $ "Expected an object but found: " ++ show x) + empty -deriving instance Generic Bond -instance FromJSON Bond -instance ToJSON Bond +instance ToJSON Namespace where + toJSON (Namespace Nothing name) = object + [ "name" .= name + ] + toJSON Namespace {..} = object + [ "language" .= nsLanguage + , "name" .= nsName + ] + +instance FromJSON Bond where + parseJSON (Object v) = + Bond <$> + v .: "imports" <*> + v .: "namespaces" <*> + v .: "declarations" + parseJSON x = modifyFailure + (const $ "Expected an object but found: " ++ show x) + empty + +instance ToJSON Bond where + toJSON Bond {..} = object + [ "imports" .= bondImports + , "namespaces" .= bondNamespaces + , "declarations" .= bondDeclarations + ] diff --git a/compiler/Bond/Schema/Util.hs b/compiler/Bond/Schema/Util.hs index 48f08215..9581c38e 100644 --- a/compiler/Bond/Schema/Util.hs +++ b/compiler/Bond/Schema/Util.hs @@ -138,8 +138,7 @@ foldMapFields f t = case t of (BT_UserDefined a@Alias {..} args) -> foldMapFields f $ resolveAlias a args _ -> mempty -foldMapStructFields :: Monoid m - => (Field -> m) -> Declaration -> m +foldMapStructFields :: Monoid m => (Field -> m) -> Declaration -> m foldMapStructFields f s = foldMapFields f $ BT_UserDefined s [] foldMapType :: (Monoid m) => (Type -> m) -> Type -> m