~jojo/Carth

ref: 3438b5bedc247fdc2a2ab5b4edc896251a1267df Carth/src/Ast.hs -rw-r--r-- 9.1 KiB
3438b5beJoJo Change spec of what to do when "closing" a todo 2 years ago
                                                                                
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
{-# LANGUAGE LambdaCase, TypeSynonymInstances, FlexibleInstances
           , MultiParamTypeClasses #-}

module Ast
    ( TVar(..)
    , TConst(..)
    , Type(..)
    , Id(..)
    , Const(..)
    , Pat(..)
    , Expr(..)
    , Def
    , Program(..)
    , reserveds
    , FreeVars(..)
    , mainType
    )
where

import Control.Monad
import Data.String
import Test.QuickCheck.Arbitrary
import Test.QuickCheck.Gen
import Test.QuickCheck.Modifiers
import qualified Data.Set as Set
import Data.Set (Set)
import Data.List

import Misc
import NonEmpty

data TVar
    = TVExplicit String
    | TVImplicit Int
    deriving (Show, Eq, Ord)

data TConst
    = TUnit
    | TInt
    | TDouble
    | TChar
    | TStr
    | TBool
    deriving (Show, Eq, Ord)

data Type
    = TVar TVar
    | TConst TConst
    | TFun Type
           Type
    deriving (Show, Eq)

mainType :: Type
mainType = TFun (TConst TUnit) (TConst TUnit)

newtype Id =
    Id String
    deriving (Eq, Ord)

instance Show Id where
    show (Id x) = x

data Pat
    = PConstructor String
    | PConstruction String
                    (NonEmpty Pat)
    | PVar Id
    deriving (Show, Eq)

data Const
    = Unit
    | Int Int
    | Double Double
    | Char Char
    | Str String
    | Bool Bool
    deriving (Show, Eq)

data Expr
    = Lit Const
    | Var Id
    | App Expr
          Expr
    | If Expr
         Expr
         Expr
    | Fun Id
          Expr
    | Let (NonEmpty Def)
          Expr
    | TypeAscr Expr Type
    | Match Expr
            (NonEmpty (Pat, Expr))
    | FunMatch (NonEmpty (Pat, Expr))
    | Constructor String
    deriving (Show, Eq)

type Def = (Id, Expr)

data Program =
    Program Expr
            [Def]
    deriving (Show, Eq)

instance IsString Id where
    fromString = Id

instance Arbitrary Program where
    arbitrary = do
        main <- arbitrary
        defs <- choose (0, 4) >>= flip vectorOf arbitrary
        pure (Program main defs)
    shrink (Program main defs) =
        [Program main' defs' | (main', defs') <- shrink (main, defs)]

instance Arbitrary Expr where
    arbitrary =
        frequency
            [ (5, pure (Lit Unit))
            , (15, fmap (Lit . Int) arbitrary)
            , (15, fmap (Lit . Double) arbitrary)
            , (8, fmap (Lit . Str . getPrintableString) arbitrary)
            , (5, fmap (Lit . Bool) arbitrary)
            , (5, fmap (Lit . Char) arbitraryChar)
            , (30, fmap Var arbitrary)
            , (8, applyArbitrary2 App)
            , (5, applyArbitrary3 If)
            , (5, applyArbitrary2 Fun)
            , (5, applyArbitrary2 Let)
            , (4, applyArbitrary2 Match)
            , (4, fmap FunMatch arbitrary)
            , (15, fmap Constructor arbitraryConstructor)
            ]
      where
        arbitraryChar =
            oneof
                [ choose ('a', 'z')
                , choose ('A', 'Z')
                , choose ('0', '9')
                , elements ['+', '-', '?', '(', ']', '#']
                , elements ['\n', '\t', '\0', '\a']
                ]
    shrink =
        \case
            App f x ->
                [Lit Unit, f, x] ++ [App f' x' | (f', x') <- shrink (f, x)]
            If p c a ->
                [Lit Unit, p, c, a] ++
                [If p' c' a' | (p', c', a') <- shrink (p, c, a)]
            Fun p b -> [Lit Unit, b] ++ [Fun p' b' | (p', b') <- shrink (p, b)]
            Let bs x ->
                [Lit Unit, x] ++ [Let bs' x' | (bs', x') <- shrink (bs, x)]
            Match e cs ->
                [Lit Unit, e] ++ [Match e' cs' | (e', cs') <- shrink (e, cs)]
            FunMatch cs -> Lit Unit : map FunMatch (shrink cs)
            _ -> []

instance Arbitrary Pat where
    arbitrary =
        frequency
            [ (3, fmap PConstructor arbitraryConstructor)
            , (1, liftM2 PConstruction arbitraryConstructor arbitrary)
            , (3, fmap PVar arbitrary)
            ]
    shrink =
        \case
            PConstruction c ps ->
                PConstructor c : map (PConstruction c) (shrink ps)
            _ -> []

instance Arbitrary Id where
    arbitrary = do
        let first =
                frequency [(26, choose ('a', 'z')), (4, elements ['_', '?'])]
        firsts <-
            frequency
                [ (10, fmap pure first)
                , ( 1
                  , liftM2
                        (\a b -> a : [b])
                        (elements ['-', '+'])
                        (choose ('a', 'z')))
                ]
        rest <- arbitraryRestIdent
        let id = firsts ++ rest
        if elem id reserveds
            then arbitrary
            else pure (Id id)

arbitraryConstructor :: Gen String
arbitraryConstructor = liftM2 (:) (choose ('A', 'Z')) arbitraryRestIdent

arbitraryRestIdent :: Gen String
arbitraryRestIdent = choose (0, 8) >>= flip vectorOf c
  where
    c = frequency
        [ (26, choose ('a', 'z'))
        , (26, choose ('A', 'Z'))
        , (4, elements ['_', '-', '+', '?'])
        ]

reserveds :: [String]
reserveds =
    [ ":"
    , "Fun"
    , "define"
    , "unit"
    , "true"
    , "false"
    , "fun-match"
    , "match"
    , "if"
    , "fun"
    , "let"
    ]

instance FreeVars Def Id where
    freeVars (name, body) = Set.delete name (freeVars body)
    boundVars (name, _) = Set.singleton name

instance FreeVars Expr Id where
    freeVars = fvExpr

instance FreeVars Pat Id where
    freeVars = const Set.empty
    boundVars = bvPat

fvExpr :: Expr -> Set Id
fvExpr = \case
    Lit _ -> Set.empty
    Var x -> Set.singleton x
    App f a -> Set.unions (map freeVars [f, a])
    If p c a -> Set.unions (map freeVars [p, c, a])
    Fun p b -> Set.delete p (freeVars b)
    Let bs e ->
        Set.difference (Set.union (freeVars e) (freeVars bs)) (boundVars bs)
    TypeAscr e _ -> freeVars e
    Match _ _ -> undefined
    FunMatch _ -> undefined
    Constructor _ -> undefined

bvPat :: Pat -> Set Id
bvPat = \case
    PConstructor _ -> Set.empty
    PConstruction _ ps -> Set.unions (map freeVars (nonEmptyToList ps))
    PVar var -> Set.singleton var

instance Pretty Program where
    pretty' = prettyProg

instance Pretty Expr where
    pretty' = prettyExpr

instance Pretty Id where
    pretty' _ (Id s) = s

instance Pretty Pat where
    pretty' _ = prettyPat

instance Pretty Const where
    pretty' _ = prettyConst

instance Pretty Type where
    pretty' _ = prettyType

instance Pretty TConst where
    pretty' _ = prettyTConst

instance Pretty TVar where
    pretty' _ = prettyTVar

prettyProg :: Int -> Program -> String
prettyProg d (Program main defs) =
    let
        allDefs = (Id "main", main) : defs
        prettyDef (Id name, val) = concat
            [ replicate d ' '
            , "(define "
            , name
            , "\n"
            , replicate (d + 2) ' '
            , pretty' (d + 2) val
            , ")"
            ]
    in unlines (map prettyDef allDefs)

prettyExpr :: Int -> Expr -> String
prettyExpr d = \case
    Lit l -> pretty l
    Var (Id v) -> v
    App f x -> concat
        [ "("
        , pretty' (d + 1) f
        , "\n"
        , replicate (d + 1) ' '
        , pretty' (d + 1) x
        , ")"
        ]
    If pred cons alt -> concat
        [ "(if "
        , pretty' (d + 4) pred
        , "\n"
        , replicate (d + 4) ' '
        , pretty' (d + 4) cons
        , "\n"
        , replicate (d + 2) ' '
        , pretty' (d + 2) alt
        , ")"
        ]
    Fun (Id param) body -> concat
        [ "(fun ["
        , param
        , "]\n"
        , replicate (d + 2) ' '
        , pretty' (d + 2) body
        , ")"
        ]
    Let binds body -> concat
        [ "(let ["
        , intercalate1
            ("\n" ++ replicate (d + 6) ' ')
            (map1 (prettyBracketPair (d + 6)) binds)
        , "]\n"
        , replicate (d + 2) ' ' ++ pretty' (d + 2) body
        , ")"
        ]
    TypeAscr e t ->
        concat ["(: ", pretty' (d + 3) e, "\n", pretty' (d + 3) t, ")"]
    Match e cs -> concat
        [ "(match "
        , pretty' (d + 7) e
        , "\n"
        , replicate (d + 2) ' '
        , intercalate1
            ("\n" ++ replicate (d + 2) ' ')
            (map1 (prettyBracketPair (d + 2)) cs)
        , ")"
        ]
    FunMatch cs -> concat
        [ "(fun-match\n"
        , replicate (d + 2) ' '
        , intercalate1
            ("\n" ++ replicate (d + 2) ' ')
            (map1 (prettyBracketPair (d + 2)) cs)
        , ")"
        ]
    Constructor c -> c

prettyPat :: Pat -> String
prettyPat = \case
    PConstructor c -> c
    PConstruction c ps -> concat
        ["(", c, " ", intercalate " " (nonEmptyToList (map1 pretty ps)), ")"]
    PVar (Id v) -> v

prettyConst :: Const -> String
prettyConst = \case
    Unit -> "unit"
    Int n -> show n
    Double x -> show x
    Char c -> showChar' c
    Str s -> '"' : (s >>= showChar'') ++ "\""
    Bool b -> if b then "true" else "false"

prettyType :: Type -> String
prettyType = \case
    Ast.TVar tv -> pretty tv
    Ast.TConst c -> pretty c
    Ast.TFun a b -> concat ["(-> ", pretty a, " ", pretty b, ")"]

prettyTConst :: TConst -> String
prettyTConst = \case
    TUnit -> "Unit"
    TInt -> "Int"
    TDouble -> "Double"
    TChar -> "Char"
    TStr -> "Str"
    TBool -> "Bool"

prettyTVar :: TVar -> String
prettyTVar = \case
    TVExplicit v -> v
    TVImplicit n -> "#" ++ show n