forked from carp-lang/Carp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Obj.hs
1181 lines (1014 loc) · 41.7 KB
/
Obj.hs
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 DeriveGeneric #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RecordWildCards #-}
module Obj where
import Control.Applicative
import Control.Monad.State
import Data.Char
import Data.Hashable
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
import GHC.Generics (Generic)
import Info
import qualified Map
import Project
import qualified Set
import SymPath
import Types
import TypesToC
import Util
-- | Will the lookup look at other Carp code or at C code. This matters when calling functions, should they assume it's a lambda or a normal C function?
data GlobalMode
= CarpLand
| ExternalCode
deriving (Eq, Show, Ord, Generic)
instance Hashable GlobalMode
-- | Will the lookup look at a global variable
data DefinitionMode
= AVariable
| AFunction
deriving (Eq, Show, Ord, Generic)
instance Hashable DefinitionMode
-- | For local lookups, does the variable live in the current function or is it captured from outside it's body?
data CaptureMode
= NoCapture
| Capture Int
deriving (Eq, Show, Ord, Generic)
instance Hashable CaptureMode
-- | A symbol knows a bit about what it refers to - is it a local scope or a global one? (the latter include modules).
-- | A symbol that is not used for looking up things will use the 'Symbol' case.
data SymbolMode
= Symbol
| LookupLocal CaptureMode
| LookupRecursive
| LookupGlobal GlobalMode DefinitionMode
| LookupGlobalOverride String -- Used to emit another name than the one used in the Carp program.
deriving (Eq, Show, Ord, Generic)
instance Hashable SymbolMode
isLookupGlobal :: SymbolMode -> Bool
isLookupGlobal (LookupGlobal _ _) = True
isLookupGlobal _ = False
isLookupLocal :: SymbolMode -> Bool
isLookupLocal (LookupLocal _) = True
isLookupLocal _ = False
data MatchMode = MatchValue | MatchRef deriving (Eq, Show, Generic)
instance Hashable MatchMode
data Number = Floating Double | Integral Int deriving (Generic)
instance Hashable Number
instance Eq Number where
(Floating a) == (Floating b) = a == b
(Integral a) == (Integral b) = a == b
(Floating a) == (Integral b) = a == fromIntegral b
(Integral a) == (Floating b) = fromIntegral a == b
instance Ord Number where
(Floating a) <= (Floating b) = a <= b
(Integral a) <= (Integral b) = a <= b
(Floating a) <= (Integral b) = a <= fromIntegral b
(Integral a) <= (Floating b) = fromIntegral a <= b
instance Num Number where
(Floating a) + (Floating b) = Floating (a + b)
(Integral a) + (Integral b) = Integral (a + b)
(Floating a) + (Integral b) = Floating (a + fromIntegral b)
(Integral a) + (Floating b) = Floating (fromIntegral a + b)
(Integral a) * (Integral b) = Integral (a * b)
(Floating a) * (Floating b) = Floating (a * b)
(Integral a) * (Floating b) = Floating (fromIntegral a * b)
(Floating a) * (Integral b) = Floating (a * fromIntegral b)
negate (Floating a) = Floating (negate a)
negate (Integral a) = Integral (negate a)
abs (Floating a) = Floating (abs a)
abs (Integral a) = Integral (abs a)
signum (Floating a) = Floating (signum a)
signum (Integral a) = Integral (signum a)
fromInteger a = Integral (fromInteger a)
instance Real Number where
toRational (Integral a) = toRational a
toRational (Floating a) = toRational a
instance Enum Number where
toEnum a = Integral (toEnum a)
fromEnum (Integral a) = fromEnum a
fromEnum (Floating _) = error "floating fromenum"
instance Fractional Number where
fromRational a = Floating (fromRational a)
recip (Floating a) = Floating (recip a)
recip (Integral _) = error "integral recip"
instance Integral Number where
quotRem (Integral a) (Integral b) = let (q, r) = quotRem a b in (Integral q, Integral r)
quotRem _ _ = error "quotRem"
toInteger (Integral a) = toInteger a
toInteger _ = error "toInteger"
instance Show Number where
show (Floating a) = show a
show (Integral a) = show a
-- | The canonical Lisp object.
data Obj
= Sym SymPath SymbolMode
| MultiSym String [SymPath] -- refering to multiple functions with the same name
| InterfaceSym String -- refering to an interface. TODO: rename to InterfaceLookupSym?
| Num Ty Number
| Str String
| Pattern String
| Chr Char
| Bol Bool
| Lst [XObj]
| Arr [XObj]
| StaticArr [XObj]
| Dict (Map.Map XObj XObj)
| Closure XObj ClosureContext
| Defn (Maybe (Set.Set XObj)) -- if this is a lifted lambda it needs the set of captured variables
| Def
| Fn (Maybe SymPath) (Set.Set XObj) -- the name of the lifted function, the set of variables this lambda captures, and a dynamic environment
| Do
| Let
| LocalDef
| While
| Break
| If
| Match MatchMode
| Mod Env TypeEnv
| Deftype Ty
| DefSumtype Ty
| With
| External (Maybe String)
| ExternalType (Maybe String)
| MetaStub
| Deftemplate TemplateCreator
| Instantiate Template
| Defalias Ty
| SetBang
| Macro
| Dynamic -- DefnDynamic
| DefDynamic
| Command CommandFunctionType
| Primitive PrimitiveFunctionType
| The
| Ref
| Deref
| Interface Ty [SymPath]
| C String -- C literal
deriving (Show, Eq, Generic)
instance Hashable Obj
isGlobalFunc :: XObj -> Bool
isGlobalFunc xobj =
case xobj of
XObj (InterfaceSym _) _ (Just FuncTy {}) -> True
XObj (MultiSym _ _) _ (Just FuncTy {}) -> True
XObj (Sym _ (LookupGlobal _ _)) _ (Just FuncTy {}) -> True
XObj (Sym _ (LookupGlobalOverride _)) _ (Just FuncTy {}) -> True
_ -> False
isNumericLiteral :: XObj -> Bool
isNumericLiteral (XObj (Num _ _) _ _) = True
isNumericLiteral (XObj (Bol _) _ _) = True
isNumericLiteral (XObj (Chr _) _ _) = True
isNumericLiteral _ = False
-- | Is the given XObj an unqualified symbol.
isUnqualifiedSym :: XObj -> Bool
isUnqualifiedSym (XObj (Sym (SymPath [] _) _) _ _) = True
isUnqualifiedSym _ = False
isSym :: XObj -> Bool
isSym (XObj (Sym (SymPath _ _) _) _ _) = True
isSym _ = False
isSpecialSym :: XObj -> Bool
isSpecialSym (XObj (Sym (SymPath [] s) _) _ _) =
elem s ["defn", "def", "do", "while", "fn", "let", "break", "if", "match", "match-ref", "set!", "the", "ref", "deref", "with"]
isSpecialSym _ = False
isArray :: XObj -> Bool
isArray (XObj (Arr _) _ _) = True
isArray _ = False
isLiteral :: XObj -> Bool
isLiteral (XObj (Num _ _) _ _) = True
isLiteral (XObj (Chr _) _ _) = True
isLiteral (XObj (Bol _) _ _) = True
isLiteral _ = False
isBool :: XObj -> Bool
isBool (XObj (Bol _) _ _) = True
isBool _ = False
isExternalFunction :: XObj -> Bool
isExternalFunction (XObj (Lst (XObj (External _) _ _ : _)) _ _) = True
isExternalFunction _ = False
isTypeDef :: XObj -> Bool
isTypeDef (XObj (Lst (XObj (Defalias _) _ _ : _)) _ _) = True
isTypeDef (XObj (Lst (XObj (Deftype _) _ _ : _)) _ _) = True
isTypeDef (XObj (Lst (XObj (DefSumtype _) _ _ : _)) _ _) = True
isTypeDef _ = False
isType :: XObj -> Bool
isType (XObj (Lst (XObj (ExternalType _) _ _ : _)) _ _) = True
isType x = isTypeDef x
isMod :: XObj -> Bool
isMod (XObj (Mod _ _) _ _) = True
isMod _ = False
isFn :: XObj -> Bool
isFn (XObj (Lst (XObj (Fn _ _) _ _ : _)) _ _) = True
isFn (XObj (Lst (XObj (Sym (SymPath [] "fn") _) _ _ : _)) _ _) = True
isFn _ = False
-- | This instance is needed for the dynamic Dictionary
instance Ord Obj where
compare (Str a) (Str b) = compare a b
compare (Num _ a) (Num _ b) = compare a b
compare a b = compare (show a) (show b)
-- TODO: handle comparison of lists, arrays and dictionaries
type NullaryPrimitiveCallback = XObj -> Context -> IO (Context, Either EvalError XObj)
type UnaryPrimitiveCallback = XObj -> Context -> XObj -> IO (Context, Either EvalError XObj)
type BinaryPrimitiveCallback = XObj -> Context -> XObj -> XObj -> IO (Context, Either EvalError XObj)
type TernaryPrimitiveCallback = XObj -> Context -> XObj -> XObj -> XObj -> IO (Context, Either EvalError XObj)
type QuaternaryPrimitiveCallback = XObj -> Context -> XObj -> XObj -> XObj -> XObj -> IO (Context, Either EvalError XObj)
type VariadicPrimitiveCallback = XObj -> Context -> [XObj] -> IO (Context, Either EvalError XObj)
-- | The type of primitive functions. See Primitives.hs
data PrimitiveFunctionType
= NullaryPrimitive NullaryPrimitiveCallback
| UnaryPrimitive UnaryPrimitiveCallback
| BinaryPrimitive BinaryPrimitiveCallback
| TernaryPrimitive TernaryPrimitiveCallback
| QuaternaryPrimitive QuaternaryPrimitiveCallback
| VariadicPrimitive VariadicPrimitiveCallback
instance Hashable PrimitiveFunctionType where
hashWithSalt s = const s
instance Eq PrimitiveFunctionType where
_ == _ = True
instance Show PrimitiveFunctionType where
show _ = "Primitive { ... }"
type NullaryCommandCallback = Context -> IO (Context, Either EvalError XObj)
type UnaryCommandCallback = Context -> XObj -> IO (Context, Either EvalError XObj)
type BinaryCommandCallback = Context -> XObj -> XObj -> IO (Context, Either EvalError XObj)
type TernaryCommandCallback = Context -> XObj -> XObj -> XObj -> IO (Context, Either EvalError XObj)
type VariadicCommandCallback = Context -> [XObj] -> IO (Context, Either EvalError XObj)
data CommandFunctionType
= NullaryCommandFunction NullaryCommandCallback
| UnaryCommandFunction UnaryCommandCallback
| BinaryCommandFunction BinaryCommandCallback
| TernaryCommandFunction TernaryCommandCallback
| VariadicCommandFunction VariadicCommandCallback
instance Hashable CommandFunctionType where
hashWithSalt s = const s
instance Eq CommandFunctionType where
_ == _ = True
instance Show CommandFunctionType where
show (NullaryCommandFunction _) = "NullaryCommandFunction { ... }"
show (UnaryCommandFunction _) = "UnaryCommandFunction { ... }"
show (BinaryCommandFunction _) = "BinaryCommandFunction { ... }"
show (TernaryCommandFunction _) = "TernaryCommandFunction { ... }"
show (VariadicCommandFunction _) = "VariadicCommandFunction { ... }"
newtype TemplateCreator = TemplateCreator {getTemplateCreator :: TypeEnv -> Env -> Template}
instance Hashable TemplateCreator where
hashWithSalt s = const s
instance Show TemplateCreator where
show _ = "TemplateCreator"
-- | Note: This is to make comparisons of Environments possible, otherwise
-- | they are always different when they contain TemplateCreators.
instance Eq TemplateCreator where
_ == _ = True
prettyInfoFromXObj :: XObj -> String
prettyInfoFromXObj xobj = maybe "no info" prettyInfo (xobjInfo xobj)
machineReadableInfoFromXObj :: FilePathPrintLength -> XObj -> String
machineReadableInfoFromXObj fppl xobj =
case xobjInfo xobj of
Just i -> machineReadableInfo fppl i
Nothing -> ""
-- | Obj with eXtra information.
data XObj = XObj
{ xobjObj :: Obj,
xobjInfo :: Maybe Info,
xobjTy :: Maybe Ty
}
deriving (Show, Eq, Ord)
setObj :: XObj -> Obj -> XObj
setObj x o = x {xobjObj = o}
instance Hashable XObj where
hashWithSalt s XObj {..} = s `hashWithSalt` xobjObj
getBinderDescription :: XObj -> String
getBinderDescription (XObj (Lst (XObj (Defn _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "defn"
getBinderDescription (XObj (Lst (XObj Def _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "def"
getBinderDescription (XObj (Lst (XObj Macro _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "macro"
getBinderDescription (XObj (Lst (XObj DefDynamic _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "defdynamic"
getBinderDescription (XObj (Lst (XObj Dynamic _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "dynamic"
getBinderDescription (XObj (Lst (XObj (Command _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "command"
getBinderDescription (XObj (Lst (XObj (Primitive _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "primitive"
getBinderDescription (XObj (Lst (XObj (Deftemplate _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "template"
getBinderDescription (XObj (Lst (XObj (Instantiate _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "instantiate"
getBinderDescription (XObj (Lst (XObj (Defalias _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "alias"
getBinderDescription (XObj (Lst (XObj (External _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "external"
getBinderDescription (XObj (Lst (XObj (ExternalType _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "external-type"
getBinderDescription (XObj (Lst (XObj MetaStub _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "meta-stub"
getBinderDescription (XObj (Lst (XObj (Deftype _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "deftype"
getBinderDescription (XObj (Lst (XObj (DefSumtype _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "deftype"
getBinderDescription (XObj (Lst (XObj (Interface _ _) _ _ : XObj (Sym _ _) _ _ : _)) _ _) = "interface"
getBinderDescription (XObj (Mod _ _) _ _) = "module"
getBinderDescription b = error ("Unhandled binder: " ++ show b)
getName :: XObj -> String
getName xobj = show (getPath xobj)
getSimpleName :: XObj -> String
getSimpleName xobj = let SymPath _ name = getPath xobj in name
getSimpleNameWithArgs :: XObj -> Maybe String
getSimpleNameWithArgs xobj@(XObj (Lst (XObj (Defn _) _ _ : _ : XObj (Arr args) _ _ : _)) _ _) =
Just $
"(" ++ getSimpleName xobj ++ (if not (null args) then " " else "")
++ unwords (map getSimpleName args)
++ ")"
getSimpleNameWithArgs xobj@(XObj (Lst (XObj Macro _ _ : _ : XObj (Arr args) _ _ : _)) _ _) =
Just $
"(" ++ getSimpleName xobj ++ (if not (null args) then " " else "")
++ unwords (map getSimpleName args)
++ ")"
getSimpleNameWithArgs xobj@(XObj (Lst (XObj Dynamic _ _ : _ : XObj (Arr args) _ _ : _)) _ _) =
Just $
"(" ++ getSimpleName xobj ++ (if not (null args) then " " else "")
++ unwords (map getSimpleName args)
++ ")"
getSimpleNameWithArgs _ = Nothing
-- | Extracts the second form (where the name of definitions are stored) from a list of XObj:s.
getPath :: XObj -> SymPath
getPath (XObj (Lst (XObj (Defn _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj Def _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj LocalDef _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj Macro _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj Dynamic _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj DefDynamic _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Deftemplate _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Instantiate _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Defalias _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (External _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (ExternalType _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj MetaStub _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Deftype _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Mod _ _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Interface _ _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Command _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Lst (XObj (Primitive _) _ _ : XObj (Sym path _) _ _ : _)) _ _) = path
getPath (XObj (Sym path _) _ _) = path
getPath x = SymPath [] (pretty x)
getBinderPath :: Binder -> SymPath
getBinderPath = getPath . binderXObj
-- | Changes the second form (where the name of definitions are stored) in a list of XObj:s.
setPath :: XObj -> SymPath -> XObj
setPath (XObj (Lst (defn@(XObj (Defn _) _ _) : XObj (Sym _ _) si st : rest)) i t) newPath =
XObj (Lst (defn : XObj (Sym newPath Symbol) si st : rest)) i t
setPath (XObj (Lst [extr@(XObj (External _) _ _), XObj (Sym _ _) si st, ty]) i t) newPath =
XObj (Lst [extr, XObj (Sym newPath Symbol) si st, ty]) i t
setPath (XObj (Lst (def@(XObj Def _ _) : XObj (Sym _ _) si st : rest)) i t) newPath =
XObj (Lst (def : XObj (Sym newPath Symbol) si st : rest)) i t
setPath x _ =
error ("Can't set path on " ++ show x)
-- | Convert an Obj to a pretty string representation.
-- | Reuses `pretty`.
prettyObj :: Obj -> String
prettyObj = pretty . buildXObj
where
buildXObj o = XObj o Nothing Nothing
-- | Convert an XObj to a pretty string representation.
pretty :: XObj -> String
pretty = visit 0
where
visit :: Int -> XObj -> String
visit indent xobj =
case xobjObj xobj of
C c -> show c
Lst lst -> "(" ++ joinWithSpace (map (visit indent) lst) ++ ")"
Arr arr -> "[" ++ joinWithSpace (map (visit indent) arr) ++ "]"
StaticArr arr -> "$[" ++ joinWithSpace (map (visit indent) arr) ++ "]"
Dict dict -> "{" ++ joinWithSpace (map (visit indent) (concatMap (\(a, b) -> [a, b]) (Map.toList dict))) ++ "}"
Num IntTy num -> show num
Num LongTy num -> show num ++ "l"
Num ByteTy num -> show num ++ "b"
Num FloatTy num -> show num ++ "f"
Num DoubleTy num -> show num
Num _ _ -> error "Invalid number type."
Str str -> show str
Pattern str -> '#' : show str
Chr c -> '\\' : c : ""
Sym path _ -> show path -- ++ " <" ++ show mode ++ ">"
MultiSym originalName paths -> originalName ++ "{" ++ joinWithComma (map show paths) ++ "}"
InterfaceSym name -> name -- ++ "§"
Bol b -> if b then "true" else "false"
Defn maybeCaptures ->
"defn" ++ case maybeCaptures of
Just captures -> " <" ++ prettyCaptures captures ++ ">"
Nothing -> ""
Def -> "def"
Fn _ captures -> "fn" ++ " <" ++ prettyCaptures captures ++ ">"
Closure elt _ -> "closure<" ++ pretty elt ++ ">"
If -> "if"
Match MatchValue -> "match"
Match MatchRef -> "match-ref"
While -> "while"
Do -> "do"
Let -> "let"
LocalDef -> "local-binding"
Mod env _ -> fromMaybe "module" (envModuleName env)
Deftype _ -> "deftype"
DefSumtype _ -> "deftype"
Deftemplate _ -> "deftemplate"
Instantiate _ -> "instantiate"
External Nothing -> "external"
External (Just override) -> "external (override: " ++ show override ++ ")"
ExternalType Nothing -> "external-type"
ExternalType (Just override) -> "external-type (override: " ++ show override ++ ")"
MetaStub -> "meta-stub"
Defalias _ -> "defalias"
SetBang -> "set!"
Macro -> "macro"
Dynamic -> "dynamic"
DefDynamic -> "defdynamic"
Command _ -> "command"
Primitive _ -> "primitive"
The -> "the"
Ref -> "ref"
Deref -> "deref"
Break -> "break"
Interface _ _ -> "interface"
With -> "with"
prettyUpTo :: Int -> XObj -> String
prettyUpTo lim xobj =
let prettied = pretty xobj
in if length prettied > lim
then take lim prettied ++ "..." ++ end
else prettied
where
end =
-- we match all of them explicitly to get errors if we forget one
case xobjObj xobj of
Lst _ -> ")"
Arr _ -> "]"
StaticArr _ -> "]"
Dict _ -> "}"
Num LongTy _ -> "l"
Num IntTy _ -> ""
Num ByteTy _ -> "b"
Num FloatTy _ -> "f"
Num DoubleTy _ -> ""
Num _ _ -> error "Invalid number type."
Str _ -> ""
C _ -> ""
Pattern _ -> ""
Chr _ -> ""
Sym _ _ -> ""
MultiSym _ _ -> "}"
InterfaceSym _ -> ""
Bol _ -> ""
Defn maybeCaptures ->
case maybeCaptures of
Just _ -> ">"
Nothing -> ""
Def -> ""
Fn _ _ -> ">"
Closure _ _ -> ">"
If -> ""
Match _ -> ""
While -> ""
Do -> ""
Let -> ""
LocalDef -> ""
Mod _ _ -> ""
Deftype _ -> ""
DefSumtype _ -> ""
Deftemplate _ -> ""
Instantiate _ -> ""
External Nothing -> ""
External (Just _) -> ")"
ExternalType Nothing -> ""
ExternalType (Just _) -> ")"
MetaStub -> ""
Defalias _ -> ""
SetBang -> ""
Macro -> ""
Dynamic -> ""
DefDynamic -> ""
Command _ -> ""
Primitive _ -> ""
The -> ""
Ref -> ""
Deref -> ""
Break -> ""
Interface _ _ -> ""
With -> ""
prettyCaptures :: Set.Set XObj -> String
prettyCaptures captures =
joinWithComma (map (\x -> getName x ++ " : " ++ maybe "" show (xobjTy x)) (Set.toList captures))
data EvalError
= EvalError String [XObj] FilePathPrintLength (Maybe Info)
| HasStaticCall XObj (Maybe Info)
deriving (Eq)
instance Show EvalError where
show (HasStaticCall xobj info) = "Expression " ++ pretty xobj ++ " has unexpected static call" ++ showInfo info
where
showInfo (Just i) = " at " ++ prettyInfo i ++ "."
showInfo Nothing = ""
show (EvalError msg t fppl info) = msg ++ showInfo info ++ getTrace
where
showInfo (Just i) = " at " ++ machineReadableInfo fppl i ++ "."
showInfo Nothing = ""
getTrace =
if null t
then ""
else
"\n\nTraceback:\n "
++ unlines (map (\x -> prettyUpTo 60 x ++ showInfo (xobjInfo x)) t)
-- | Get the type of an XObj as a string.
typeStr :: XObj -> String
typeStr xobj = case xobjTy xobj of
Nothing -> "" --" : _"
Just t -> " : " ++ show t
-- | Get the identifier of an XObj as a string.
identifierStr :: XObj -> String
identifierStr xobj = case xobjInfo xobj of
Just i -> "#" ++ show (infoIdentifier i)
Nothing -> "#?"
-- | Get the deleters of an XObj as a string.
deletersStr :: XObj -> String
deletersStr xobj = case xobjInfo xobj of
Just i -> joinWithComma (map show (Set.toList (infoDelete i)))
Nothing -> ""
-- | Convert XObj to pretty string representation with type annotations.
prettyTyped :: XObj -> String
prettyTyped = visit 0
where
visit :: Int -> XObj -> String
visit indent xobj =
let suffix =
typeStr xobj ++ " "
++ identifierStr xobj
++ " "
++ deletersStr xobj
++ " "
++ "\n"
in case xobjObj xobj of
Lst lst ->
listPrinter "(" ")" lst suffix indent
Arr arr ->
listPrinter "[" "]" arr suffix indent
StaticArr arr ->
listPrinter "$[" "]" arr suffix indent
_ ->
pretty xobj ++ suffix
listPrinter :: String -> String -> [XObj] -> String -> Int -> String
listPrinter opening closing xobjs suffix indent =
opening ++ " "
++ joinWith (spaces (indent + 4)) (map (visit (indent + 4)) xobjs)
++ spaces indent
++ closing
++ suffix
spaces :: Int -> String
spaces n = replicate n ' '
-- | Datatype for holding meta data about a binder, like type annotation or docstring.
newtype MetaData = MetaData {getMeta :: Map.Map String XObj} deriving (Eq, Show, Generic)
instance Hashable MetaData
emptyMeta :: MetaData
emptyMeta = MetaData Map.empty
metaIsTrue :: MetaData -> String -> Bool
metaIsTrue metaData key =
case Map.lookup key (getMeta metaData) of
Just (XObj (Bol True) _ _) -> True
_ -> False
-- | Wraps and holds an XObj in an environment.
data Binder = Binder {binderMeta :: MetaData, binderXObj :: XObj} deriving (Eq, Generic)
instance Hashable Binder
instance Show Binder where
show binder = showBinderIndented 0 False (getName (binderXObj binder), binder)
-- | Show a binder even if its hidden.
forceShowBinder :: Binder -> String
forceShowBinder binder = showBinderIndented 0 True (getName (binderXObj binder), binder)
showBinderIndented :: Int -> Bool -> (String, Binder) -> String
showBinderIndented indent _ (name, Binder _ (XObj (Mod env tenv) _ _)) =
replicate indent ' ' ++ name ++ " : Module = {\n"
++ prettyEnvironmentIndented (indent + 4) env
++ "\n"
++ prettyEnvironmentIndented (indent + 4) (getTypeEnv tenv)
++ "\n"
++ replicate indent ' '
++ "}"
showBinderIndented indent _ (name, Binder _ (XObj (Lst [XObj (Interface t paths) _ _, _]) _ _)) =
replicate indent ' ' ++ name ++ " : " ++ show t ++ " = {\n "
++ joinWith "\n " (map show paths)
++ "\n"
++ replicate indent ' '
++ "}"
showBinderIndented indent showHidden (name, Binder meta xobj) =
if not showHidden && metaIsTrue meta "hidden"
then ""
else
replicate indent ' ' ++ name
++
-- " (" ++ show (getPath xobj) ++ ")" ++
" : "
++ showMaybeTy (xobjTy xobj)
-- ++ " <" ++ getBinderDescription xobj ++ ">"
-- | Get a list of pairs from a deftype declaration.
memberXObjsToPairs :: [XObj] -> [(String, Ty)]
memberXObjsToPairs xobjs = map (\(n, t) -> (mangle (getName n), fromJustWithErrorMessage (xobjToTy t) ("Failed to convert " ++ show t ++ "\nPRETTY: " ++ pretty t ++ " from xobj to type."))) (pairwise xobjs)
fromJustWithErrorMessage :: Maybe Ty -> String -> Ty
fromJustWithErrorMessage (Just x) _ = x
fromJustWithErrorMessage Nothing msg = error msg
-- | Helper function to create binding pairs for registering external functions.
register :: String -> Ty -> (String, Binder)
register name t =
( name,
Binder
emptyMeta
( XObj
( Lst
[ XObj (External Nothing) Nothing Nothing,
XObj (Sym (SymPath [] name) Symbol) Nothing Nothing
]
)
(Just dummyInfo)
(Just t)
)
)
data EnvMode = ExternalEnv | InternalEnv | RecursionEnv deriving (Show, Eq, Generic)
instance Hashable EnvMode
-- | Environment
data Env = Env
{ envBindings :: Map.Map String Binder,
envParent :: Maybe Env,
envModuleName :: Maybe String,
envUseModules :: Set.Set SymPath,
envMode :: EnvMode,
envFunctionNestingLevel :: Int -- Normal defn:s have 0, lambdas get +1 for each level of nesting
}
deriving (Show, Eq, Generic)
instance Hashable Env
newtype ClosureContext = CCtx Context
deriving (Show, Generic)
instance Hashable ClosureContext
instance Eq ClosureContext where
_ == _ = True
newtype TypeEnv = TypeEnv {getTypeEnv :: Env} deriving (Generic, Eq)
instance Hashable TypeEnv
instance Show TypeEnv where
show (TypeEnv env) = "(TypeEnv " ++ show env ++ ")"
safeEnvModuleName :: Env -> String
safeEnvModuleName env =
case envModuleName env of
Just name -> name ++ ", with parent " ++ parent
Nothing -> "???, with parent " ++ parent
where
parent = maybe "Global" safeEnvModuleName (envParent env)
-- | Used by the compiler command "(env)"
prettyEnvironment :: Env -> String
prettyEnvironment = prettyEnvironmentIndented 0
prettyEnvironmentIndented :: Int -> Env -> String
prettyEnvironmentIndented indent env =
joinLines $
filter (/= "") (map (showBinderIndented indent False) (Map.toList (envBindings env)))
++ let modules = envUseModules env
in if null modules
then []
else ("\n" ++ replicate indent ' ' ++ "Used modules:") : Set.toList (Set.map (showImportIndented indent) modules)
-- | For debugging nested environments
prettyEnvironmentChain :: Env -> String
prettyEnvironmentChain env =
let bs = envBindings env
name = fromMaybe "<env has no name>" (envModuleName env)
otherInfo = "(" ++ show (envMode env) ++ ", lvl " ++ show (envFunctionNestingLevel env) ++ ")"
in ( if length bs < 20
then
"'" ++ name ++ "' " ++ otherInfo ++ ":\n"
++ joinLines
( filter
(/= "")
(map (showBinderIndented 4 False) (Map.toList (envBindings env)))
)
else "'" ++ name ++ "' " ++ otherInfo ++ ":\n Too big to show bindings."
)
++ ( case envParent env of
Just parent -> "\nWITH PARENT ENV " ++ prettyEnvironmentChain parent
Nothing -> ""
)
pathToEnv :: Env -> [String]
pathToEnv rootEnv = reverse (visit rootEnv)
where
visit env =
case envModuleName env of
Just name -> name : parent
Nothing -> parent
where
parent = maybe [] visit (envParent env)
showImportIndented :: Int -> SymPath -> String
showImportIndented indent path = replicate indent ' ' ++ " * " ++ show path
incrementEnvNestLevel :: Env -> Env
incrementEnvNestLevel env =
let current = envFunctionNestingLevel env
in env {envFunctionNestingLevel = current + 1}
-- | Converts an S-expression to one of the Carp types.
xobjToTy :: XObj -> Maybe Ty
xobjToTy (XObj (Sym (SymPath _ "C") _) _ _) = Just CTy
xobjToTy (XObj (Sym (SymPath _ "Unit") _) _ _) = Just UnitTy
xobjToTy (XObj (Sym (SymPath _ "Int") _) _ _) = Just IntTy
xobjToTy (XObj (Sym (SymPath _ "Float") _) _ _) = Just FloatTy
xobjToTy (XObj (Sym (SymPath _ "Double") _) _ _) = Just DoubleTy
xobjToTy (XObj (Sym (SymPath _ "Long") _) _ _) = Just LongTy
xobjToTy (XObj (Sym (SymPath _ "Byte") _) _ _) = Just ByteTy
xobjToTy (XObj (Sym (SymPath _ "String") _) _ _) = Just StringTy
xobjToTy (XObj (Sym (SymPath _ "Pattern") _) _ _) = Just PatternTy
xobjToTy (XObj (Sym (SymPath _ "Char") _) _ _) = Just CharTy
xobjToTy (XObj (Sym (SymPath _ "Bool") _) _ _) = Just BoolTy
xobjToTy (XObj (Sym (SymPath _ "Static") _) _ _) = Just StaticLifetimeTy
xobjToTy (XObj (Sym spath@(SymPath _ s@(firstLetter : _)) _) _ _)
| isLower firstLetter = Just (VarTy s)
| otherwise = Just (StructTy (ConcreteNameTy spath) [])
xobjToTy (XObj (Lst [XObj (Sym (SymPath _ "Ptr") _) _ _, innerTy]) _ _) =
do
okInnerTy <- xobjToTy innerTy
pure (PointerTy okInnerTy)
xobjToTy (XObj (Lst (XObj (Sym (SymPath _ "Ptr") _) _ _ : _)) _ _) =
Nothing
xobjToTy (XObj (Lst [XObj (Sym (SymPath _ "Ref") _) _ _, innerTy]) i _) =
do
okInnerTy <- xobjToTy innerTy
pure (RefTy okInnerTy (VarTy (makeTypeVariableNameFromInfo i)))
xobjToTy (XObj (Lst [XObj (Sym (SymPath _ "Ref") _) _ _, innerTy, lifetimeTy]) _ _) =
do
okInnerTy <- xobjToTy innerTy
okLifetimeTy <- xobjToTy lifetimeTy
pure (RefTy okInnerTy okLifetimeTy)
xobjToTy (XObj (Lst [XObj Ref _ _, innerTy]) i _) =
-- This enables parsing of '&'
do
okInnerTy <- xobjToTy innerTy
pure (RefTy okInnerTy (VarTy (makeTypeVariableNameFromInfo i)))
xobjToTy (XObj (Lst (XObj (Sym (SymPath _ "Ref") _) _ _ : _)) _ _) =
Nothing
xobjToTy (XObj (Lst [XObj (Sym (SymPath path "╬╗") _) fi ft, XObj (Arr argTys) ai at, retTy]) i t) =
xobjToTy (XObj (Lst [XObj (Sym (SymPath path "Fn") Symbol) fi ft, XObj (Arr argTys) ai at, retTy]) i t)
xobjToTy (XObj (Lst [XObj (Sym (SymPath path "λ") _) fi ft, XObj (Arr argTys) ai at, retTy]) i t) =
xobjToTy (XObj (Lst [XObj (Sym (SymPath path "Fn") Symbol) fi ft, XObj (Arr argTys) ai at, retTy]) i t)
xobjToTy (XObj (Lst [XObj (Sym (SymPath _ "Fn") _) _ _, XObj (Arr argTys) _ _, retTy]) _ _) =
do
okArgTys <- mapM xobjToTy argTys
okRetTy <- xobjToTy retTy
pure (FuncTy okArgTys okRetTy StaticLifetimeTy)
xobjToTy (XObj (Lst [XObj (Sym (SymPath _ "Fn") _) _ _, XObj (Arr argTys) _ _, retTy, lifetime]) _ _) =
do
okArgTys <- mapM xobjToTy argTys
okRetTy <- xobjToTy retTy
_ <- xobjToTy lifetime
pure (FuncTy okArgTys okRetTy StaticLifetimeTy)
xobjToTy (XObj (Lst []) _ _) = Just UnitTy
xobjToTy (XObj (Lst (x : xs)) _ _) =
do
okX <- xobjToTy x
okXS <- mapM xobjToTy xs
case okX of
(StructTy n []) -> pure (StructTy n okXS)
v@(VarTy _) -> pure (StructTy v okXS) -- Struct type with type variable as a name, i.e. "(a b)"
_ -> Nothing
xobjToTy _ = Nothing
-- | Generates the suffix added to polymorphic functions when they are instantiated.
-- For example (defn id [x] x) : t -> t
-- might be invoked like this (id 5)
-- which will generate int id__Int(int x) { return x; }
-- The "__Int" is the suffix!
polymorphicSuffix :: Ty -> Ty -> String
polymorphicSuffix signature actualType =
case evalState (visit signature actualType) [] of
[] -> ""
parts -> "__" ++ intercalate "_" parts
where
visit :: Ty -> Ty -> State VisitedTypes [String]
visit sig actual =
case (sig, actual) of
(VarTy _, VarTy _) ->
-- error $ "Unsolved variable in actual type: " ++ show sig ++ " => " ++ show actual ++
-- " when calculating polymorphic suffix for " ++
-- show signature ++ " => " ++ show actualType
pure ["?"]
(a@(VarTy _), b) -> do
visitedTypeVariables <- get
if a `elem` visitedTypeVariables
then pure []
else do
put (a : visitedTypeVariables) -- now it's visited
pure [tyToC b]
(FuncTy argTysA retTyA _, FuncTy argTysB retTyB _) -> do
visitedArgs <- fmap concat (zipWithM visit argTysA argTysB)
visitedRets <- visit retTyA retTyB
pure (visitedArgs ++ visitedRets)
(StructTy _ a, StructTy _ b) -> fmap concat (zipWithM visit a b)
(PointerTy a, PointerTy b) -> visit a b
(RefTy a _, RefTy b _) -> visit a b
(_, _) -> pure []
type VisitedTypes = [Ty]
-- | Templates are like macros, but defined inside the compiler and with access to the types they are instantiated with
data Template = Template
{ templateSignature :: Ty,
templateDeclaration :: Ty -> [Token], -- Will this parameterization ever be useful?
templateDefinition :: Ty -> [Token],
templateDependencies :: Ty -> [XObj]
}
instance Hashable Template where
hashWithSalt s Template {..} = s `hashWithSalt` templateSignature
instance Show Template where
show _ = "Template"
-- | Note: This is to make comparisons of Environments possible, otherwise
-- | they are always different when they contain Templates.
instance Eq Template where
a == b = templateSignature a == templateSignature b
data TokTyMode = Normal | Raw deriving (Eq, Ord)
-- | Tokens are used for emitting C code from templates.
data Token
= TokTy Ty TokTyMode -- Some kind of type, will be looked up if it's a type variable.
| TokC String -- Plain C code.
| TokDecl -- Will emit the declaration (i.e. "foo(int x)"), this is useful
-- for avoiding repetition in the definition part of the template.
| TokName -- Will emit the name of the instantiated function/variable.
deriving (Eq, Ord)
instance Show Token where
show (TokC s) = s
show (TokTy t Normal) = tyToCLambdaFix t -- Any function type will be emitted as 'Lambda'
show (TokTy t Raw) = tyToC t -- Function types will be emitted in typedef:able form
show TokName = "<name>"
show TokDecl = "<declaration>"
instantiateTemplate :: SymPath -> Ty -> Template -> (XObj, [XObj])
instantiateTemplate path actualType template =
let defLst = [XObj (Instantiate template) Nothing Nothing, XObj (Sym path Symbol) Nothing Nothing]
deps = templateDependencies template actualType
in (XObj (Lst defLst) (Just (Info (-1) (-1) (show path ++ " template") Set.empty (-1))) (Just actualType), deps)
-- | Type aliases are used to create C-typedefs when those are needed.
defineTypeAlias :: String -> Ty -> XObj
defineTypeAlias name t =
XObj
( Lst
[ XObj (Defalias t) Nothing Nothing,
XObj (Sym (SymPath [] name) Symbol) Nothing Nothing
]
)
(Just dummyInfo)
(Just TypeTy)
defineFunctionTypeAlias :: Ty -> XObj
defineFunctionTypeAlias aliasTy = defineTypeAlias (tyToC aliasTy) aliasTy
defineArrayTypeAlias :: Ty -> XObj
defineArrayTypeAlias t = defineTypeAlias (tyToC t) (StructTy (ConcreteNameTy (SymPath [] "Array")) [])
defineStaticArrayTypeAlias :: Ty -> XObj
defineStaticArrayTypeAlias t = defineTypeAlias (tyToC t) (StructTy (ConcreteNameTy (SymPath [] "Array")) [])
-- |
defineInterface :: String -> Ty -> [SymPath] -> Maybe Info -> XObj
defineInterface name t paths info =
XObj
( Lst
[ XObj (Interface t paths) Nothing Nothing,
XObj (Sym (SymPath [] name) Symbol) Nothing Nothing
]
)
info
(Just InterfaceTy)
-- | Unsafe way of getting the type from an XObj
forceTy :: XObj -> Ty
forceTy xobj = fromMaybe (error ("No type in " ++ show xobj)) (xobjTy xobj)
-- | How should the compiler be run? Interactively or just build / build & run and then quit?
data ExecutionMode = Repl | Build | BuildAndRun | Install String | Check deriving (Show, Eq)
-- | Information needed by the REPL
data Context = Context
{ contextGlobalEnv :: Env,
contextInternalEnv :: Maybe Env,
contextTypeEnv :: TypeEnv,
contextPath :: [String],
contextProj :: Project,