summaryrefslogtreecommitdiff
path: root/src/Elm/Expression.hs
blob: ac670baca1f438f8c6f0207de362e5a9e3d888e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
{-# OPTIONS_HADDOCK prune #-}
{-# OPTIONS_GHC -Werror -Wall #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe              #-}

-- | Used to declare expressions
module Elm.Expression
    ( Expr(..)
    ) where

import           Protolude

import           Control.Monad        (mapM, when)
import           Control.Monad.Writer (tell)
import           Data.List            hiding (map)
import           Data.String          (IsString (..), String)
import           Elm.Classes          (Generate (..))
import           Elm.GenError         (GenError (..))
import           Text.PrettyPrint     hiding (Str)

-- | The expression type
data Expr {-
      Constants
    -}
    -- | A boolean literal
    = Bool Bool
    -- | A string literal
    | Str String
    -- | An integer literal
    | Int Int
    -- | A float literal
    | Float Float
    -- | An underscore variable placeholder
    | Under
    {-
      Inline
    -}
    -- | A variable
    | Var String
    -- | Function application, the tail is applied to the head
    | App [Expr]
    -- | A list of expressions
    | List [Expr]
    -- | Apply an inline operator to two expressions
    | Op String
         Expr
         Expr
    -- | A tuple of expressions
    | Tuple [Expr]
    -- | A record, the first paramater is an optional record to update from
    | Record (Maybe Expr)
             [(String, Expr)]
    {-
      Multi Line
    -}
    -- | A let expression
    | Let Expr
          [(Expr, Expr)]
    -- | A case expression
    | Case Expr
           [(Expr, Expr)]
    {-
      Util
    -}
    -- | Wrap an expression in parens, should be mostly automatic
    | Parens Expr

-- | Allows creating variables with overloaded strings
instance IsString Expr where
    fromString = Var

instance Generate Expr where
    generate expr =
        case expr of
            Var str -> do
                when (str == "") $
                    tell $ Error "An empty string is not a valid variable name"
                return $ text str
            App []
            -- I don't think this has a valid meaning
             -> do
                tell $ Error "Invalid syntax, trying to apply nothing"
                return $ text ""
            App [expr'] -> generate expr'
            App exprs
            -- If only I could understand my own code :(
             -> do
                docs <- mapM vop exprs
                return . hsep $ docs
            Tuple [] ->
                return "()"
            Tuple items -> do
                when (length items > 9) $
                    tell $ Error "Length of tuple is too long"
                when (length items > 7) $
                    tell $
                    WarningList
                        [ "Tuples of length longer than seven are not comparable"
                        ]
                docs <- mapM generate items
                return $ lparen <+> (hsep . punctuate "," $ docs) <+> rparen
            Str str -> return . doubleQuotes . text $ str
            Op op expr1 expr2 -> do
                doc1 <- vop expr1
                doc2 <- vop expr2
                return $ doc1 <+> text op <+> doc2
            Case _ [] -> do
                tell $ Error "Unable to create case expression with 0 cases"
                return ""
            Case value options -> do
                docValue <- generate value
                optionsList <- genCaseList options
                return $ "case" <+> docValue <+> "of" $+$ nest 4 optionsList
            List items -> do
                docs <- mapM generate items
                return . brackets . hsep . punctuate "," $ docs
            Let _ [] -> do
                tell $ Error "Unable to create let expression with 0 bindings"
                return ""
            Let value bindings -> do
                bindingsList <- genLetList bindings
                valueDoc <- generate value
                return $
                    "let" $+$ nest 4 bindingsList $+$ "in" $+$ nest 4 valueDoc
            Int val -> do
                when (val > 9007199254740991) $
                -- I would love for someone, somewhere, to get this warning
                    tell $
                    WarningList
                        [ "The number " ++
                          show val ++
                          " is larger than the largest safe number in js"
                        ]
                return . int $ val
            Float val -> do
                when (val > 9007199254740991) $
                    tell $
                    WarningList
                        [ "The number " ++
                          show val ++
                          " is larger that the largest safe number in js"
                        ]
                return . float $ val
            Under -> return . char $ '_'
            Bool bool' ->
                if bool'
                    then return . text $ "True"
                    else return . text $ "False"
            Record Nothing [] -> return "{}"
            Record (Just (Var str)) []
            -- tbh, what would you even be trying to do?
             -> do
                tell $
                    WarningList
                        [ "Trying to update record " ++
                          str ++ " with no changed fields"
                        ]
                return . text $ str
            Record (Just (Var str)) updates -> do
                list' <- genRecordList updates
                return $ lbrace <+> text str <+> "|" <+> list' <+> rbrace
            Record (Just _) _
            -- This seems to be how it is
             -> do
                tell $
                    Error
                        "You are unable to update a record with a non constant"
                return ""
            Record Nothing updates -> do
                list' <- genRecordList updates
                return $ lbrace <+> list' <+> rbrace
            Parens expr' -> do
                doc <- generate expr'
                return . parens $ doc
            -- Generates the list of key value pairs in a record
      where
        genRecordList updates = do
            let (keys, values) = unzip updates
            let docKeys = map text keys
            docValues <- mapM generate values
            return . hsep . punctuate "," . map (\(a, b) -> a <+> "=" <+> b) $
                zip docKeys docValues
            -- Generates the list of declerations in a let expression
        genLetList bindings = do
            let (keys, values) = unzip bindings
            docKeys <- mapM generate keys
            docValues <- mapM generate values
            return . vcat . map (\(a, b) -> a <+> "=" <+> b) $
                zip docKeys docValues
            -- Generates the list of cases in a case statement
        genCaseList options = do
            let (keys, values) = unzip options
            docKeys <- mapM generate keys
            docValues <- sequence . map generate $ values
            return . vcat . punctuate "\n" . map (\(a, b) -> a <+> "->" $+$ nest 4 b) $
                zip docKeys docValues
            -- takes an expression and wraps it in parens
            -- if required for nesting it in another expression
        vop expr' =
            case expr' of
                Var _ -> generate expr'
                Tuple _ -> generate expr'
                List _ -> generate expr'
                Int _ -> generate expr'
                Float _ -> generate expr'
                Under -> generate expr'
                Str _ -> generate expr'
                Record _ _ -> generate expr'
                _ -> do
                    doc <- generate expr'
                    return . parens $ doc