1{-# LANGUAGE OverloadedStrings #-}
2module Elm.Compiler.Type
7import Control.Applicative ((<$>), (<*>))
8import Control.Arrow (second)
9import Data.Aeson ((.:), (.=))
10import qualified Data.Aeson as Json
11import qualified Data.ByteString.Lazy.Char8 as BS
12import qualified Data.Text as Text
13import Text.PrettyPrint as P
15import qualified AST.Helpers as Help
23 | Record [(String, Type)] (Maybe Type)
28data Context = None | ADT | Function
31toString :: Type -> String
33 P.render (toDoc None tipe)
36toDoc :: Context -> Type -> P.Doc
41 map (toDoc Function) (collectLambdas tipe)
44 P.sep [ t, P.sep (map (P.text "->" <+>) ts) ]
54 P.text (if name == "_Tuple0" then "()" else name)
57 | Help.isTuple name ->
59 [ P.cat (zipWith (<+>) (P.lparen : repeat P.comma) (map (toDoc None) args))
64 let adt = P.hang (P.text name) 2 (P.sep $ map (toDoc ADT) args)
66 case (context, args) of
67 (ADT, _ : _) -> P.parens adt
71 case flattenRecord tipe of
77 [ P.cat (zipWith (<+>) (P.lbrace : repeat P.comma) (map prettyField fields))
83 (P.lbrace <+> P.text x <+> P.text "|")
86 [ P.cat (zipWith (<+>) (P.space : repeat P.comma) (map prettyField fields))
90 prettyField (field, tipe) =
91 P.text field <+> P.text ":" <+> toDoc None tipe
94collectLambdas :: Type -> [Type]
97 Lambda arg body -> arg : collectLambdas body
101flattenRecord :: Type -> ( [(String, Type)], Maybe String )
104 Var x -> ([], Just x)
106 Record fields Nothing -> (fields, Nothing)
108 Record fields (Just ext) ->
109 let (fields',ext') = flattenRecord ext
111 (fields' ++ fields, ext')
113 _ -> error "Trying to flatten ill-formed record."
118instance Json.ToJSON Type where
120 Json.object (getFields tipe)
125 [ "tag" .= ("lambda" :: Text.Text)
126 , "in" .= Json.toJSON t1
127 , "out" .= Json.toJSON t2
131 [ "tag" .= ("var" :: Text.Text)
132 , "name" .= Json.toJSON x
136 [ "tag" .= ("type" :: Text.Text)
137 , "name" .= Json.toJSON name
141 [ "tag" .= ("app" :: Text.Text)
142 , "func" .= Json.toJSON t
143 , "args" .= Json.toJSON ts
147 [ "tag" .= ("record" :: Text.Text)
148 , "fields" .= Json.toJSON (map (Json.toJSON . second Json.toJSON) fields)
149 , "extension" .= Json.toJSON ext
153instance Json.FromJSON Type where
154 parseJSON (Json.Object obj) =
155 do tag <- obj .: "tag"
156 case (tag :: String) of
158 Lambda <$> obj .: "in" <*> obj .: "out"
161 Var <$> obj .: "name"
164 Type <$> obj .: "name"
167 App <$> obj .: "func" <*> obj .: "args"
170 Record <$> obj .: "fields" <*> obj .: "extension"
173 fail $ "Error when decoding type with tag: " ++ tag
177 fail $ "Cannot decode Value from: " ++ BS.unpack (Json.encode value)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list