-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathHell.hs
More file actions
3379 lines (3078 loc) · 131 KB
/
Copy pathHell.hs
File metadata and controls
3379 lines (3078 loc) · 131 KB
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE ExistentialQuantification, DuplicateRecordFields, NoFieldSelectors #-}
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE QuantifiedConstraints #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
--
-- Welcome to Hell
--
-- Haskell as a scripting language!
--
-- Special thanks to Stephanie Weirich, whose type-safe typechecker
-- this is built upon, and for the Type.Reflection module, which has
-- made some of this more ergonomic.
{-# OPTIONS_GHC -Wno-unused-foralls #-}
module Main (main, specMain) where
#if __GLASGOW_HASKELL__ >= 906
import Control.Monad
#endif
-- All modules tend to be imported qualified by their last component,
-- e.g. 'Data.Graph' becomes 'Graph', and are then exposed to the Hell
-- guest language as such.
import qualified Data.CaseInsensitive as CI
import Data.CaseInsensitive (CI, FoldCase)
import qualified Network.HTTP.Types as Http
import qualified Network.Wai as Wai
import qualified Network.Wai.Handler.Warp as Warp
import Data.ByteString.Builder (Builder)
import qualified Data.ByteString.Builder as Builder
import Control.Applicative (Alternative (..), optional)
import qualified Control.Concurrent as Concurrent
import Control.Exception (evaluate)
import Control.Monad.Reader
import Control.Monad.State.Strict
import Criterion.Measurement
import Data.Aeson (Value)
import qualified Data.Aeson as Json
import qualified Data.Aeson.KeyMap as KeyMap
import Data.Bifunctor
import qualified Data.Bool as Bool
import Data.ByteString (ByteString)
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Builder as ByteString hiding (writeFile)
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy as L
import Data.Constraint
import Data.Containers.ListUtils
import Data.Dynamic
import qualified Data.Either as Either
import qualified Data.Eq as Eq
import Data.Foldable
import qualified Data.Function as Function
import qualified Data.Generics as SYB
import qualified Data.Graph as Graph
import qualified Data.List as List
import qualified Data.Map as Map
import Data.Map.Strict (Map)
import qualified Data.Maybe as Maybe
import qualified Data.Ord as Ord
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import qualified Data.Text.IO as Text
import Data.These (These)
import qualified Data.These as These
import Data.Time (Day, TimeOfDay, UTCTime, DayOfWeek)
import qualified Data.Time as Time
import qualified Data.Time.Format.ISO8601 as Time
import Data.Traversable
import Data.Tree (Tree)
import qualified Data.Tree as Tree
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Data.Void
import GHC.TypeLits
import GHC.Types (Type)
import qualified Language.Haskell.Exts as HSE
import Language.Haskell.TH (Q)
import qualified Language.Haskell.TH as TH
import Language.Haskell.TH.Instances ()
import qualified Language.Haskell.TH.Syntax as TH
import Lucid hiding (Term, for_, term)
import Numeric
import Options.Applicative (Parser)
import qualified Options.Applicative as Options
import qualified System.Directory as Dir
import System.Environment
import qualified System.Exit as Exit
import qualified System.IO as IO
import qualified System.IO.Temp as Temp
import System.Process.Typed as Process
import qualified System.Timeout as Timeout
import Test.Hspec
import qualified Text.Read as Read
import qualified Text.Show as Show
import Type.Reflection (SomeTypeRep (..), TypeRep, typeRep, typeRepKind, pattern TypeRep)
import qualified Type.Reflection as Type
import qualified UnliftIO.Async as Async
------------------------------------------------------------------------------
-- Main entry point
-- | Commands available.
data Command
= Run FilePath
| Check FilePath StatsEnabled
| Version
data StatsEnabled = NoStats | PrintStats Int
-- | Main entry point.
main :: IO ()
main = do
initializeTime
args <- getArgs
case args of
(x : ys)
| not (List.isPrefixOf "-" x) -> withArgs ys $ dispatch (Run x)
_ -> dispatch =<< Options.execParser opts
where
opts =
Options.info
(commandParser Options.<**> Options.helper)
( Options.fullDesc
<> Options.progDesc "Runs and typechecks Hell scripts"
<> Options.header "hell - A Haskell-driven scripting language"
)
-- | Command options.
commandParser :: Options.Parser Command
commandParser =
Options.asum
[ Run <$> Options.strArgument (Options.metavar "FILE" <> Options.help "Run the given .hell file"),
Check
<$> Options.strOption (Options.long "check" <> Options.metavar "FILE" <> Options.help "Typecheck the given .hell file")
<*> Options.flag NoStats (PrintStats 0) (Options.long "compiler-stats" <> Options.internal),
Version <$ Options.flag () () (Options.long "version" <> Options.help "Print the version")
]
-- | Version of Hell.
hellVersion :: Text
hellVersion = "2026-05-29"
-- | Dispatch on the command.
dispatch :: Command -> IO ()
dispatch Version = Text.putStrLn hellVersion
dispatch (Run filePath) = do
action <- compileFile NoStats filePath
eval () action
dispatch (Check filePath stats) = do
compileFile stats filePath >>= void . evaluate
--------------------------------------------------------------------------------
-- Compiler
-- | Parses the file with HSE, desugars it, infers it, checks it,
-- returns it. Or throws an error.
compileFile :: StatsEnabled -> FilePath -> IO (Term () (IO ()))
compileFile stats filePath = do
t0 <- getTime
!result <- parseFile (nestStat stats) filePath
t1 <- getTime
emitStat stats "parse" (t1 - t0)
case result of
Left e -> error $ e
Right File {terms, types}
| anyCycles terms -> error "Cyclic bindings are not supported!"
| anyCycles types -> error "Cyclic types are not supported!"
| otherwise -> do
t2 <- getTime
emitStat stats "cycle_detect" (t2 - t1)
case desugarAll types terms of
Left err -> error $ prettyString err
Right !dterms -> do
t3 <- getTime
emitStat stats "desugar" (t3 - t2)
case lookup "main" dterms of
Nothing -> error "No main declaration!"
Just main' -> do
inferred <- inferExp (nestStat stats) main'
case inferred of
Left err -> error $ prettyString err
Right uterm -> do
t4 <- getTime
emitStat stats "infer" (t4 - t3)
case check uterm Nil of
Left err -> error $ prettyString err
Right (Typed t ex) -> do
t5 <- getTime
emitStat stats "check" (t5 - t4)
case Type.eqTypeRep (typeRepKind t) (typeRep @Type) of
Nothing -> error $ "Kind error, that's nowhere near an IO ()!"
Just Type.HRefl ->
case Type.eqTypeRep t (typeRep @(IO ())) of
Just Type.HRefl ->
pure ex
Nothing -> error $ "Type isn't IO (), but: " ++ show t
emitStat :: StatsEnabled -> Text -> Double -> IO ()
emitStat NoStats _ _ = pure ()
emitStat (PrintStats n0) label s =
t_putStrLn $ Text.replicate (n0 * 2) " " <> "stat: " <> label <> " = " <> Text.pack (secs s)
nestStat :: StatsEnabled -> StatsEnabled
nestStat NoStats = NoStats
nestStat (PrintStats n) = PrintStats (n + 1)
--------------------------------------------------------------------------------
-- Get declarations from the module
parseModule :: HSE.Module HSE.SrcSpanInfo -> HSE.ParseResult File
parseModule (HSE.Module _ Nothing [] [] decls) = do
termsAndTypes <- traverse parseDecl decls
let terms = concatMap fst termsAndTypes
types = concatMap snd termsAndTypes
let names = map fst terms
tyNames = map fst types
if Set.size (Set.fromList names) == length names
&& Set.size (Set.fromList tyNames) == length tyNames
then pure File {terms, types}
else fail "Duplicate names!"
where
parseDecl (HSE.PatBind _ (HSE.PVar _ (HSE.Ident _ string)) (HSE.UnGuardedRhs _ exp') Nothing) =
pure ([(string, exp')], types)
where
types = []
parseDecl
( HSE.PatBind
_
( HSE.PatTypeSig
l
(HSE.PVar _ (HSE.Ident _ string))
typ
)
(HSE.UnGuardedRhs _ exp')
Nothing
) =
pure ([(string, HSE.ExpTypeSig l exp' typ)], types)
where
types = []
parseDecl (HSE.DataDecl _ HSE.DataType {} Nothing (HSE.DHead _ name) [qualConDecl] []) =
do
(termName, termExpr, typeName, typ) <- parseDataDecl name qualConDecl
pure ([(termName, termExpr)], [(typeName, typ)])
parseDecl (HSE.DataDecl _ HSE.DataType {} Nothing (HSE.DHead _ name) qualConDecls []) =
do
(terms, tyname, typ) <- parseSumDecl name qualConDecls
pure (terms, [(tyname, typ)])
parseDecl d = fail $ "Can't parse that! " ++ show d
parseModule _ = fail "Module headers aren't supported."
-- data Value = Text Text | Number Int
-- \ x ->
-- hell:Hell.Tagged @"Main.Value"
-- @(Variant (ConsL "Number" Int (ConsL "Text" Text NilL)))
-- (Variant.left @"Number" x)
-- \ x ->
-- hell:Hell.Tagged @"Main.Value"
-- @(Variant (ConsL "Number" Int (ConsL "Text" Text NilL)))
-- (Variant.right (Variant.left @"Text" x))
parseSumDecl ::
(l ~ HSE.SrcSpanInfo) =>
HSE.Name l ->
[HSE.QualConDecl l] ->
-- | ^^^^ type name and type
HSE.ParseResult
( [(String, HSE.Exp HSE.SrcSpanInfo)],
-- \^^^^^ constructor and term
String,
HSE.Type HSE.SrcSpanInfo
)
parseSumDecl (HSE.Ident _ tyname) conDecls0 = do
conDecls <- fmap Map.fromList $ traverse parseConDecl conDecls0
let variantType = desugarVariantType $ Map.toList conDecls
let taggedVariantType =
-- Example: Tagged "Main.Person" (Variant ..)
-- vvvvvv vvvvvvvv vvvvvvvvvvv
HSE.TyApp l (HSE.TyApp l (hellTaggedTyCon l) (tySym qualifiedName)) variantType
-- Note: the constructors are sorted by name, to provide a canonical ordering.
let terms = map (makeCons conDecls variantType) $ Map.toList conDecls
pure (terms, tyname, taggedVariantType)
where
l = HSE.noSrcSpan
makeCons conDecls variantType (conName, typ)
| HSE.TyCon _ (HSE.Qual _ (HSE.ModuleName _ "hell:Hell") (HSE.Ident _ "Nullary")) <- typ =
( conName,
appTagged variantType $
desugarVariantCon True (Map.keys conDecls) conName
)
| otherwise = (conName, expr)
where
expr =
HSE.Lambda l [HSE.PVar l (HSE.Ident l "x")] $
appTagged variantType $
desugarVariantCon False (Map.keys conDecls) conName
qualifiedName = "Main." ++ tyname
appTagged ty =
HSE.App l $
HSE.App
l
( HSE.App
l
( HSE.App
l
(hellTaggedCon l)
(HSE.TypeApp l (tySym qualifiedName))
)
(HSE.TypeApp l ty)
)
( HSE.App
l
(hellSSymbolCon l)
(HSE.TypeApp l (tySym qualifiedName))
)
tySym s = HSE.TyPromoted l (HSE.PromotedString l s s)
parseSumDecl _ _ =
fail "Sum type declaration not in supported format."
desugarVariantCon :: Bool -> [String] -> String -> HSE.Exp HSE.SrcSpanInfo
desugarVariantCon nullary cons thisCon = rights $ left
where
right _ = HSE.Var l (hellQName l "RightV")
rights e = foldr (HSE.App l) e $ map right $ takeWhile (/= thisCon) cons
left =
if nullary
then
HSE.App
l
left0
(HSE.Con l (hellQName l "Nullary"))
else
HSE.App
l
left0
(HSE.Var l (HSE.UnQual l (HSE.Ident l "x")))
where
left0 =
HSE.App
l
( HSE.App
l
(HSE.Var l (hellQName l "LeftV"))
(HSE.TypeApp l (tySym thisCon))
)
( HSE.App
l
(hellSSymbolCon l)
(HSE.TypeApp l (tySym thisCon))
)
tySym s = HSE.TyPromoted l (HSE.PromotedString l s s)
l = HSE.noSrcSpan
desugarVariantType :: [(String, HSE.Type HSE.SrcSpanInfo)] -> HSE.Type HSE.SrcSpanInfo
desugarVariantType = appRecord . foldr appCons nilL
where
appCons (name, typ) rest =
HSE.TyApp l (HSE.TyApp l (HSE.TyApp l consL (tySym name)) typ) rest
appRecord x =
HSE.TyParen l (HSE.TyApp l (hellVariantTyCon l) x)
tySym s = HSE.TyPromoted l (HSE.PromotedString l s s)
nilL = hellNilTyCon l
consL = hellConsTyCon l
l = HSE.noSrcSpan
parseConDecl :: (MonadFail f) => HSE.QualConDecl l -> f (String, HSE.Type l)
parseConDecl (HSE.QualConDecl _ Nothing Nothing (HSE.ConDecl _ (HSE.Ident _ consName) [slot])) =
pure (consName, slot)
parseConDecl (HSE.QualConDecl l Nothing Nothing (HSE.ConDecl _ (HSE.Ident _ consName) [])) =
pure (consName, hellTyCon l "Nullary")
parseConDecl _ = fail "Unsupported constructor declaration format."
parseDataDecl ::
(l ~ HSE.SrcSpanInfo) =>
HSE.Name l ->
HSE.QualConDecl l ->
HSE.ParseResult
( String,
HSE.Exp HSE.SrcSpanInfo,
-- ^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
-- Term constructor name... and its expr.
String,
HSE.Type HSE.SrcSpanInfo
)
-- ^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^
-- Type name... type content.
parseDataDecl (HSE.Ident _ tyname) (HSE.QualConDecl _ Nothing Nothing (HSE.RecDecl _ (HSE.Ident _ consName) fields)) = do
-- Note: the fields are sorted by name.
fields' <- fmap (List.sortBy (Ord.comparing fst) . concat) $ traverse getField fields
let names = map fst fields'
-- Technically the type checker is quite capable of handling this in
-- a sound manner, but it's weird and Haskell disallows it, so we
-- turn it off.
when (List.nub names /= names) $
fail "Field names cannot be repeated."
let (consExpr, typ) = makeConstructor tyname fields'
pure (consName, consExpr, tyname, typ)
where
getField (HSE.FieldDecl _ names typ) = do
names' <- for names \case
(HSE.Ident _ n) -> pure n
_ -> fail "Invalid field name."
pure $ map (,typ) names'
parseDataDecl _ _ =
fail "Record declaration not in supported format."
makeConstructor ::
String ->
[(String, HSE.Type HSE.SrcSpanInfo)] ->
(HSE.Exp HSE.SrcSpanInfo, HSE.Type HSE.SrcSpanInfo)
makeConstructor name fields = (appTagged recordType, taggedRecordType)
where
recordType = desugarRecordType fields
taggedRecordType =
-- Example: Tagged "Main.Person" (Record ..)
-- vvvvvv vvvvvvvv vvvvvvvvvvv
HSE.TyApp l (HSE.TyApp l (hellTaggedTyCon l) (tySym qualifiedName)) recordType
qualifiedName = "Main." ++ name
appTagged ty =
HSE.App
l
( HSE.App
l
( HSE.App
l
(hellTaggedCon l)
(HSE.TypeApp l (tySym qualifiedName))
)
(HSE.TypeApp l ty)
)
( HSE.App
l
(hellSSymbolCon l)
(HSE.TypeApp l (tySym qualifiedName))
)
tySym s = HSE.TyPromoted l (HSE.PromotedString l s s)
l = HSE.noSrcSpan
makeConstructRecord :: HSE.QName HSE.SrcSpanInfo -> [HSE.FieldUpdate HSE.SrcSpanInfo] -> HSE.Exp HSE.SrcSpanInfo
makeConstructRecord qname fields =
HSE.App l (HSE.Con l qname)
$ foldr
( \(name, expr) rest ->
let tySym s = HSE.TyPromoted l (HSE.PromotedString l s s)
in HSE.App
l
( HSE.App
l
( HSE.App
l
(HSE.Var l (hellQName l "ConsR"))
( HSE.App
l
(hellSSymbolCon l)
(HSE.TypeApp l (tySym name))
)
)
expr
)
rest
)
(HSE.Var l (hellQName l "NilR"))
$ List.sortBy (Ord.comparing fst)
$ map
( \case
HSE.FieldUpdate _ (HSE.UnQual _ (HSE.Ident _ i)) expr -> (i, expr)
HSE.FieldPun _ v@(HSE.UnQual _ (HSE.Ident l' i)) -> (i, HSE.Var l' v)
f -> error $ "Invalid field: " ++ show f
)
fields
where
l = HSE.noSrcSpan
desugarRecordType :: [(String, HSE.Type HSE.SrcSpanInfo)] -> HSE.Type HSE.SrcSpanInfo
desugarRecordType = appRecord . foldr appCons nilL
where
appCons (name, typ) rest =
HSE.TyApp l (HSE.TyApp l (HSE.TyApp l consL (tySym name)) typ) rest
appRecord x =
HSE.TyApp l (hellRecordTyCon l) x
tySym s = HSE.TyPromoted l (HSE.PromotedString l s s)
nilL = hellNilTyCon l
consL = hellConsTyCon l
l = HSE.noSrcSpan
--------------------------------------------------------------------------------
-- Typed AST support
--
-- We define a well-typed, well-indexed GADT AST which can be evaluated directly.
data Term g t where
Var :: Var g t -> Term g t
Lam :: Term (g, a) b -> Term g (a -> b)
App :: Term g (s -> t) -> Term g s -> Term g t
Lit :: a -> Term g a
data Var g t where
ZVar :: (t -> a) -> Var (h, t) a
SVar :: Var h t -> Var (h, s) t
--------------------------------------------------------------------------------
-- Evaluator
--
-- This is the entire evaluator. Type-safe and total.
eval :: env -> Term env t -> t
eval env (Var v) = lookp v env
eval env (Lam e) = \x -> eval (env, x) e
eval env (App e1 e2) = (eval env e1) (eval env e2)
eval _env (Lit a) = a
-- Type-safe, total lookup. The final @slot@ determines which slot of
-- a given tuple to pick out.
lookp :: Var env t -> env -> t
lookp (ZVar slot) (_, x) = slot x
lookp (SVar v) (env, _) = lookp v env
--------------------------------------------------------------------------------
-- The "untyped" AST
--
-- This is the AST that is not interpreted, and is just
-- type-checked. The HSE AST is desugared into this one.
data UTerm t
= UVar HSE.SrcSpanInfo t String
| ULam HSE.SrcSpanInfo t Binding (Maybe SomeStarType) (UTerm t)
| UApp HSE.SrcSpanInfo t (UTerm t) (UTerm t)
| USig HSE.SrcSpanInfo t (UTerm t) SomeStarType
| -- IRep below: The variables are poly types, they aren't metavars,
-- and need to be instantiated.
UForall Prim HSE.SrcSpanInfo t [SomeTypeRep] Forall [TH.Uniq] (IRep TH.Uniq) [t]
deriving (Traversable, Functor, Foldable)
typeOf :: UTerm t -> t
typeOf = \case
UVar _ t _ -> t
ULam _ t _ _ _ -> t
UApp _ t _ _ -> t
USig _ t _ _ -> t
UForall _ _ t _ _ _ _ _ -> t
data Binding = Singleton String | Tuple [String]
data Forall where
-- The final term, not polymorphic anymore.
Term :: (forall g. Typed (Term g)) -> Forall
-- forall a. ...
Forall :: TypeRep (s :: Type) -> (forall (a :: s). TypeRep a -> Forall) -> Forall
-- Cls a => ...
ClassConstraint ::
forall k (c :: k -> Constraint) (a :: k).
TypeRep a ->
TypeRep c ->
((c a) => Forall) ->
Forall
-- Special operators with magic type-system rules:
GetOf ::
TypeRep (k :: Symbol) ->
TypeRep (a :: Type) ->
TypeRep (t :: Symbol) ->
TypeRep (r :: List) ->
((Tagged t (Record r) -> a) -> Forall) ->
Forall
SetOf ::
TypeRep (k :: Symbol) ->
TypeRep (a :: Type) ->
TypeRep (t :: Symbol) ->
TypeRep (r :: List) ->
((a -> Tagged t (Record r) -> Tagged t (Record r)) -> Forall) ->
Forall
ModifyOf ::
TypeRep (k :: Symbol) ->
TypeRep (a :: Type) ->
TypeRep (t :: Symbol) ->
TypeRep (r :: List) ->
(((a -> a) -> Tagged t (Record r) -> Tagged t (Record r)) -> Forall) ->
Forall
lit :: (Type.Typeable a) => Prim -> a -> UTerm ()
lit name = litWithSpan name HSE.noSrcSpan
litWithSpan :: (Type.Typeable a) => Prim -> HSE.SrcSpanInfo -> a -> UTerm ()
litWithSpan name srcSpanInfo l =
litWithSpanBare name srcSpanInfo (Type.typeOf l) l
litWithSpanBare :: Prim -> HSE.SrcSpanInfo -> TypeRep a -> a -> UTerm ()
litWithSpanBare name srcSpanInfo typeRep' l =
UForall
name
srcSpanInfo
()
[]
(Term (Typed typeRep' (Lit l)))
[]
(fromSomeType (SomeTypeRep typeRep'))
[]
data Prim
= LitP (HSE.Literal HSE.SrcSpanInfo)
| NameP String
| UnitP
| SSymbolP String
data SomeStarType = forall (a :: Type). SomeStarType (TypeRep a)
instance Pretty SomeStarType where
pretty (SomeStarType a) = pretty a
deriving instance Show SomeStarType
instance Eq SomeStarType where
SomeStarType x == SomeStarType y = Type.SomeTypeRep x == Type.SomeTypeRep y
pattern StarTypeRep t <- (toStarType -> Just (SomeStarType t))
where
StarTypeRep t = SomeTypeRep t
toStarType :: SomeTypeRep -> Maybe SomeStarType
toStarType (SomeTypeRep t) = do
Type.HRefl <- Type.eqTypeRep (typeRepKind t) (typeRep @Type)
pure $ SomeStarType t
--------------------------------------------------------------------------------
-- The type checker
data Typed (thing :: Type -> Type) = forall ty. Typed (TypeRep (ty :: Type)) (thing ty)
data TypeCheckError
= NotInScope String
| TupleTypeMismatch
| TypeCheckMismatch
| TupleTypeTooBig
| TypeOfApplicandIsNotFunction
| LambdaIsNotAFunBug
| InferredCheckedDisagreeBug
| LambdaMustBeStarBug
| ConstraintResolutionProblem HSE.SrcSpanInfo Forall String
deriving (Show)
instance Show Forall where show = showR
typed :: (Type.Typeable a) => a -> Typed (Term g)
typed l = Typed (Type.typeOf l) (Lit l)
-- The type environment and lookup
data TyEnv g where
Nil :: TyEnv g
Cons :: Binding -> TypeRep (t :: Type) -> TyEnv h -> TyEnv (h, t)
-- The top-level checker used by the main function.
check :: (UTerm SomeTypeRep) -> TyEnv () -> Either TypeCheckError (Typed (Term ()))
check = tc
-- Type check a term given an environment of names.
tc :: (UTerm SomeTypeRep) -> TyEnv g -> Either TypeCheckError (Typed (Term g))
tc (USig _l _ e (SomeStarType someStarType)) env = do
case tc e env of
Left err -> Left err
Right typed'@(Typed ty _)
| Just {} <- Type.eqTypeRep ty someStarType ->
pure typed'
| otherwise ->
Left TypeCheckMismatch
tc (UVar _ _ v) env = do
Typed ty v' <- lookupVar v env
pure $ Typed ty (Var v')
tc (ULam _ (StarTypeRep lam_ty) s _ body) env =
case lam_ty of
Type.Fun bndr_ty' _
| Just Type.HRefl <- Type.eqTypeRep (typeRepKind bndr_ty') (typeRep @Type) ->
case tc body (Cons s bndr_ty' env) of
Left e -> Left e
Right (Typed body_ty' body') ->
let checked_ty = Type.Fun bndr_ty' body_ty'
in case Type.eqTypeRep checked_ty lam_ty of
Just Type.HRefl -> Right $ Typed lam_ty (Lam body')
Nothing -> Left InferredCheckedDisagreeBug
_ -> Left LambdaIsNotAFunBug
tc (ULam _ (SomeTypeRep {}) _ _ _) _ =
Left LambdaMustBeStarBug
tc (UApp _ _ e1 e2) env =
case tc e1 env of
Left e -> Left e
Right (Typed (Type.Fun bndr_ty body_ty) e1') ->
case tc e2 env of
Left e -> Left e
Right (Typed arg_ty e2') ->
case Type.eqTypeRep arg_ty bndr_ty of
Nothing ->
Left TypeCheckMismatch
Just (Type.HRefl) ->
let kind = typeRepKind body_ty
in case Type.eqTypeRep kind (typeRep @Type) of
Just Type.HRefl -> Right $ Typed body_ty (App e1' e2')
_ -> Left TypeCheckMismatch
Right {} -> Left TypeOfApplicandIsNotFunction
-- Polytyped terms, must be, syntactically, fully-saturated
tc (UForall _ forallLoc _ _ fall _ _ reps0) _env = go reps0 fall
where
go :: [SomeTypeRep] -> Forall -> Either TypeCheckError (Typed (Term g))
go [] (Term typed') = pure typed'
go (SomeTypeRep rep : reps) (Forall sym f)
| Just Type.HRefl <- Type.eqTypeRep (typeRepKind rep) sym = go reps (f rep)
go reps (ClassConstraint rep crep f) =
withClassConstraint forallLoc reps rep crep f go
go reps fa@(GetOf k0 a0 t0 r0 f) =
case makeAccessor k0 r0 a0 t0 of
Just accessor -> go reps (f accessor)
Nothing -> problem fa $ "missing field for field access"
go reps fa@(SetOf k0 a0 t0 r0 f) =
case makeSetter k0 r0 a0 t0 of
Just accessor -> go reps (f accessor)
Nothing -> problem fa $ "missing field for field set"
go reps fa@(ModifyOf k0 a0 t0 r0 f) =
case makeModify k0 r0 a0 t0 of
Just accessor -> go reps (f accessor)
Nothing -> problem fa $ "missing field for field modify"
go tys r = problem r $ "forall type arguments mismatch: " ++ show tys ++ " for " ++ showR r
problem :: Forall -> String -> Either TypeCheckError a
problem fa = Left . ConstraintResolutionProblem forallLoc fa
--------------------------------------------------------------------------------
-- Type class resolution at the call site
-- Declaration of instances (instance0, instance1, etc.) is kind-polymorphic,
-- and resolve, resolve1, etc. are kind-polymorphic. But this function IS NOT.
-- At some point you have to decide on the kinds of things. This
-- function handles a few common cases for instance head types:
--
-- Int :: Type (common case)
-- [] :: Type -> Type (less common case)
-- Either :: Type -> Type -> Type (rare case)
-- Mod :: (Type -> Type) -> Type -> Type (only one example as of writing this comment)
withClassConstraint ::
forall g k (c :: k -> Constraint) (a :: k).
HSE.SrcSpanInfo ->
[SomeTypeRep] ->
TypeRep a ->
TypeRep c ->
((c a) => Forall) ->
([SomeTypeRep] -> Forall -> Either TypeCheckError (Typed (Term g))) ->
Either TypeCheckError (Typed (Term g))
withClassConstraint forallLoc reps rep crep f go =
case lookupDict rep crep of
Just dict -> go reps (withDict dict f)
Nothing -> problem $
"type "
++ show rep
++ " doesn't appear to be an instance of "
++ show crep
where
problem :: forall x. String -> Either TypeCheckError x
problem = Left . ConstraintResolutionProblem forallLoc (ClassConstraint rep crep f)
-- The workhorse behind withClassConstraint. See documentation there.
lookupDict ::
forall g k (c :: k -> Constraint) (a :: k).
TypeRep a ->
TypeRep c ->
Maybe (Dict (c a))
lookupDict rep crep =
if
-- Cases that look like: Semigroup (Vector (e :: *))
-- Note: the kinds are limited to this exact specification in the signature above.
| Type.App t _ <- rep,
Just Type.HRefl <- Type.eqTypeRep (typeRepKind t) (TypeRep @(Type -> Type)),
Just dict <- resolve1 (Type.App crep rep) crep t instances ->
pure dict
-- Cases that look like: Eq (Either (e :: *) (a :: *))
-- Note: the kinds are limited to this exact specification in the signature above.
| Type.App (Type.App t _) _ <- rep,
Just Type.HRefl <- Type.eqTypeRep (typeRepKind t) (TypeRep @(Type -> Type -> Type)),
Just dict <- resolve2 (Type.App crep rep) crep t instances ->
pure dict
-- Cases that look like: Monad (Either (e :: *))
-- Note: the kinds are limited to this exact specification in the signature above.
| Type.App t _ <- rep,
Just Type.HRefl <- Type.eqTypeRep (typeRepKind t) (TypeRep @(Type -> Type -> Type)),
Just dict <- resolve1 (Type.App crep rep) crep t instances ->
pure dict
-- Cases that look like: Semigroup (Mod (f :: * -> *) (a :: *))
-- Note: the kinds are limited to this exact specification in the signature above.
| Type.App (Type.App t _a) _b <- rep,
Just Type.HRefl <- Type.eqTypeRep (typeRepKind t) (TypeRep @((Type -> Type) -> Type -> Type)),
Just dict <- resolve2 (Type.App crep rep) crep t instances ->
pure dict
-- Simple cases: Eq (a :: k)
| otherwise ->
resolve crep rep instances
--------------------------------------------------------------------------------
-- Instances
-- Dict but for (t :: * -> *), like Monad []
newtype D1 c t = D1 (forall e. Dict (c (t e)))
-- Dict but for (t :: * -> * -> *), like Monad (Either e)
newtype D2 c t = D2 (forall f a. Dict (c (t f a)))
-- Entailment, c a => c (t a), E.g. Eq a :- Eq [a]
newtype ED1 c t = ED1 (forall e. c e :- c (t e))
-- Entailment, (c a, c b) => c (t a b), E.g. (Eq a, Eq b) :- Eq (Either a b)
newtype ED2 c t = ED2 (forall e f. (c e, c f) :- c (t e f))
newtype Instances = Instances {getInstances ::Map (SomeTypeRep, SomeTypeRep) Dynamic}
instances :: Instances
instances =
Instances $
Map.fromList
[ entail1 @Show @[],
entail1 @Show @Set,
entail1 @Show @CI,
entail1 @Show @Tree,
entail1 @Show @Maybe,
entail1 @Show @Vector,
entail2 @Show @Either,
entail2 @Show @(,),
instance0 @Show @Int,
instance0 @Show @Integer,
instance0 @Show @Day,
instance0 @Show @DayOfWeek,
instance0 @Show @UTCTime,
instance0 @Show @TimeOfDay,
instance0 @Show @Double,
instance0 @Show @Bool,
instance0 @Show @Char,
instance0 @Show @Text,
instance0 @Show @ByteString,
instance0 @Show @Builder,
instance0 @Show @ExitCode,
instance0 @Show @Value,
entail1 @Eq @CI,
entail1 @Eq @[],
entail1 @Eq @Set,
entail1 @Eq @Maybe,
entail2 @Eq @Either,
entail2 @Eq @(,),
entail1 @Eq @Tree,
entail1 @Eq @Vector,
instance0 @Eq @Int,
instance0 @Eq @Integer,
instance0 @Eq @Day,
instance0 @Eq @DayOfWeek,
instance0 @Eq @UTCTime,
instance0 @Eq @TimeOfDay,
instance0 @Eq @Double,
instance0 @Eq @Bool,
instance0 @Eq @Char,
instance0 @Eq @Text,
instance0 @Eq @ByteString,
instance0 @Eq @ExitCode,
entail1 @Ord @[],
entail1 @Ord @Set,
entail1 @Ord @CI,
entail1 @Ord @Maybe,
entail2 @Ord @Either,
entail2 @Ord @(,),
entail1 @Ord @Tree,
entail1 @Ord @Vector,
instance0 @Ord @Int,
instance0 @Ord @Integer,
instance0 @Ord @Day,
instance0 @Ord @DayOfWeek,
instance0 @Ord @UTCTime,
instance0 @Ord @TimeOfDay,
instance0 @Ord @Double,
instance0 @Ord @Bool,
instance0 @Ord @Char,
instance0 @Ord @Text,
instance0 @Ord @ByteString,
instance0 @Ord @ExitCode,
instance0 @Enum @Int,
instance0 @Enum @Integer,
instance0 @Enum @Day,
instance0 @Enum @DayOfWeek,
instance0 @Enum @Bool,
instance0 @Enum @Char,
instance0 @Monad @IO,
instance0 @Monad @Maybe,
instance0 @Monad @[],
instance0 @Monad @Tree,
instance1 @Monad @Either,
instance0 @Functor @IO,
instance0 @Functor @Maybe,
instance0 @Functor @[],
instance0 @Functor @Tree,
instance0 @Functor @Options.Parser,
instance1 @Functor @Either,
instance1 @Functor @(,), -- Functor (a,)
instance0 @Applicative @IO,
instance0 @Applicative @Maybe,
instance0 @Applicative @[],
instance0 @Applicative @Tree,
instance0 @Applicative @Options.Parser,
instance1 @Applicative @Either,
instance0 @Alternative @Options.Parser,
instance0 @Alternative @Maybe,
entail1 @Monoid @Maybe,
instance0 @Monoid @Text,
instance0 @Monoid @Builder,
instance1 @Monoid @Vector,
instance2 @Monoid @Options.Mod,
instance1 @Monoid @[],
entail1 @Semigroup @Maybe,
instance2 @Semigroup @Either,
instance2 @Semigroup @Options.Mod,
instance1 @Semigroup @Options.InfoMod,
instance0 @Semigroup @Text,
instance0 @Semigroup @Builder,
instance1 @Semigroup @Vector,
instance1 @Semigroup @[],
instance0 @FoldCase @Text,
instance0 @FoldCase @ByteString
]
--------------------------------------------------------------------------------
-- Instance declarations
instance0 ::
forall cls a.
(cls a, Typeable cls, Typeable a) =>
((SomeTypeRep, SomeTypeRep), Dynamic)
instance0 =
( (SomeTypeRep $ typeRep @cls, SomeTypeRep $ typeRep @a),
toDyn $ Dict @(cls a)
)
instance1 ::
forall {k0} {k1} (c :: k1 -> Constraint) (t :: k0 -> k1).
((forall a. c (t a)), Typeable c, Typeable t, Typeable k0, Typeable k1) =>
((SomeTypeRep, SomeTypeRep), Dynamic)
instance1 =
( (SomeTypeRep $ typeRep @c, SomeTypeRep $ typeRep @t),
toDyn $ D1 @c @t Dict
)
-- A very restricted kind of entailment: C a => C (t a)
-- This serves:
-- Eq a => Eq [a], Ord a => Ord (Maybe [a]), etc.
--
-- Lookup process:
-- class = Ord
-- type = Maybe [Int]
-- find (Ord,Maybe)
-- recurse
-- find (Ord,[])
-- recurse
-- find (Ord,Int)
-- ==> Ord Int
-- ==> Ord [Int]
-- ==> Ord (Maybe [Int])
entail1 ::
forall {k1} (c :: k1 -> Constraint) (t :: k1 -> k1).
((forall a. c a => c (t a)), Typeable c, Typeable t, Typeable k1) =>
((SomeTypeRep, SomeTypeRep), Dynamic)
entail1 =
( (SomeTypeRep $ typeRep @c, SomeTypeRep $ typeRep @t),
toDyn $ ED1 @c @t (Sub Dict)
)
instance2 ::
forall {k0} {k1} {k2} (c :: k2 -> Constraint) (t :: k0 -> k1 -> k2).
((forall a b. c (t a b)), Typeable c, Typeable t, Typeable k0, Typeable k1, Typeable k2) =>
((SomeTypeRep, SomeTypeRep), Dynamic)
instance2 =