summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorPéter Diviánszky <divipp@gmail.com>2016-01-23 09:34:16 +0100
committerPéter Diviánszky <divipp@gmail.com>2016-01-23 09:34:16 +0100
commit940ebb71ef18c8e85cc0bb482189eb1c114d1084 (patch)
treeb0bd58fec48ffe4f73504d5984ed6c677dd84823 /src
parent803972fcc4ecc6b3c65c64ed09831e17cd4e81d2 (diff)
major refactoring
Diffstat (limited to 'src')
-rw-r--r--src/LambdaCube/Compiler/CoreToIR.hs2
-rw-r--r--src/LambdaCube/Compiler/Infer.hs872
2 files changed, 419 insertions, 455 deletions
diff --git a/src/LambdaCube/Compiler/CoreToIR.hs b/src/LambdaCube/Compiler/CoreToIR.hs
index 05ed480d..15046beb 100644
--- a/src/LambdaCube/Compiler/CoreToIR.hs
+++ b/src/LambdaCube/Compiler/CoreToIR.hs
@@ -516,7 +516,7 @@ genStreamInput backend i = fmap concat $ mapM input $ case i of
516 PTuple l -> l 516 PTuple l -> l
517 x -> [x] 517 x -> [x]
518 where 518 where
519 input (PVar t n) = tell [unwords [inputDef,toGLSLType (n ++ "\n") t,n,";"]] >> return [n] 519 input (PVar t n) = tell [unwords [inputDef,toGLSLType (n ++ " " ++ "\n") t,n,";"]] >> return [n]
520 input a = error $ "genStreamInput " ++ ppShow a 520 input a = error $ "genStreamInput " ++ ppShow a
521 inputDef = case backend of 521 inputDef = case backend of
522 OpenGL33 -> "in" 522 OpenGL33 -> "in"
diff --git a/src/LambdaCube/Compiler/Infer.hs b/src/LambdaCube/Compiler/Infer.hs
index 38fd456e..fe89d392 100644
--- a/src/LambdaCube/Compiler/Infer.hs
+++ b/src/LambdaCube/Compiler/Infer.hs
@@ -44,7 +44,8 @@ import Control.Applicative
44import Control.Exception hiding (try) 44import Control.Exception hiding (try)
45import Control.DeepSeq 45import Control.DeepSeq
46 46
47import Text.Parsec hiding (label, Empty, State, (<|>), many) 47import Text.Parsec hiding (label, Empty, State, (<|>), many, try)
48import qualified Text.Parsec as Pa
48import qualified Text.Parsec.Token as Pa 49import qualified Text.Parsec.Token as Pa
49import qualified Text.ParserCombinators.Parsec.Language as Pa 50import qualified Text.ParserCombinators.Parsec.Language as Pa
50import Text.Parsec.Pos 51import Text.Parsec.Pos
@@ -72,7 +73,7 @@ data Stmt
72 = Let SIName MFixity (Maybe SExp) [Visibility]{-source arity-} SExp 73 = Let SIName MFixity (Maybe SExp) [Visibility]{-source arity-} SExp
73 | Data SIName [(Visibility, SExp)]{-parameters-} SExp{-type-} Bool{-True:add foralls-} [(SIName, SExp)]{-constructor names and types-} 74 | Data SIName [(Visibility, SExp)]{-parameters-} SExp{-type-} Bool{-True:add foralls-} [(SIName, SExp)]{-constructor names and types-}
74 | PrecDef SIName Fixity 75 | PrecDef SIName Fixity
75 | ValueDef ([SIName], Pat) SExp 76 | ValueDef Pat SExp
76 | TypeFamily SIName [(Visibility, SExp)]{-parameters-} SExp{-type-} 77 | TypeFamily SIName [(Visibility, SExp)]{-parameters-} SExp{-type-}
77 78
78 -- eliminated during parsing 79 -- eliminated during parsing
@@ -143,7 +144,7 @@ data SExp
143 = SGlobal SIName 144 = SGlobal SIName
144 | SBind SI Binder SIName{-parameter's name-} SExp SExp 145 | SBind SI Binder SIName{-parameter's name-} SExp SExp
145 | SApp SI Visibility SExp SExp 146 | SApp SI Visibility SExp SExp
146 | SLet SExp SExp -- let x = e in f --> SLet e f{-x is Var 0-} 147 | SLet LI SExp SExp -- let x = e in f --> SLet e f{-x is Var 0-}
147 | SVar_ (SData SIName) !Int 148 | SVar_ (SData SIName) !Int
148 | STyped SI ExpType 149 | STyped SI ExpType
149 deriving (Eq, Show) 150 deriving (Eq, Show)
@@ -184,10 +185,10 @@ pattern SAnn a t <- STyped _ (Lam Visible TType (Lam Visible (Var 0) (Var
184pattern TyType a <- STyped _ (Lam Visible TType (Var 0), TType :~> TType) `SAppV` a 185pattern TyType a <- STyped _ (Lam Visible TType (Var 0), TType :~> TType) `SAppV` a
185 where TyType a = STyped noSI (Lam Visible TType (Var 0), TType :~> TType) `SAppV` a 186 where TyType a = STyped noSI (Lam Visible TType (Var 0), TType :~> TType) `SAppV` a
186 -- same as (a :: TType) -- a :: TType ~~> (\(x :: TType) -> x) a 187 -- same as (a :: TType) -- a :: TType ~~> (\(x :: TType) -> x) a
187pattern SCstr a b = SBuiltin "'EqCT" `SAppV` SType `SAppV` a `SAppV` b -- a ~ b 188pattern SCstr a b = SBuiltin "'EqCT" `SAppV` SType `SAppV` a `SAppV` b -- a ~ b
188pattern SParEval a b = SBuiltin "parEval" `SAppV` Wildcard SType `SAppV` a `SAppV` b 189pattern SParEval a b = SBuiltin "parEval" `SAppV` Wildcard SType `SAppV` a `SAppV` b
189pattern SLabelEnd a = SBuiltin "labelend" `SAppV` a 190pattern SLabelEnd a = SBuiltin "labelend" `SAppV` a
190pattern ST2 a b = SBuiltin "'T2" `SAppV` a `SAppV` b 191pattern ST2 a b = SBuiltin "'T2" `SAppV` a `SAppV` b
191 192
192pattern SBuiltin s <- SGlobal (_, s) where SBuiltin s = SGlobal (debugSI $ "builtin " ++ s, s) 193pattern SBuiltin s <- SGlobal (_, s) where SBuiltin s = SGlobal (debugSI $ "builtin " ++ s, s)
193 194
@@ -202,8 +203,8 @@ infixl 2 `SAppV`, `SAppH`, `App`, `app_`
202-------------------------------------------------------------------------------- destination data 203-------------------------------------------------------------------------------- destination data
203 204
204data Exp 205data Exp
205 = Pi_ MaxDB Visibility Exp Exp -- TODO: prohibit meta binder here; BLam is not allowed 206 = Pi_ MaxDB Visibility Exp Exp
206 | Meta Exp Exp -- TODO: prohibit meta binder here; BLam is not allowed 207 | Meta Exp Exp
207 | Lam_ MaxDB Visibility Exp Exp 208 | Lam_ MaxDB Visibility Exp Exp
208 | Con_ MaxDB ConName [Exp] 209 | Con_ MaxDB ConName [Exp]
209 | TyCon_ MaxDB TyConName [Exp] 210 | TyCon_ MaxDB TyConName [Exp]
@@ -410,8 +411,8 @@ data Env
410 | EBind2_ SI Binder Exp Env -- zoom into second parameter of SBind 411 | EBind2_ SI Binder Exp Env -- zoom into second parameter of SBind
411 | EApp1 SI Visibility Env SExp 412 | EApp1 SI Visibility Env SExp
412 | EApp2 SI Visibility Exp Env 413 | EApp2 SI Visibility Exp Env
413 | ELet1 Env SExp 414 | ELet1 LI Env SExp
414 | ELet2 ExpType Env 415 | ELet2 LI ExpType Env
415 | EGlobal String{-full source of current module-} GlobalEnv [Stmt] 416 | EGlobal String{-full source of current module-} GlobalEnv [Stmt]
416 | ELabelEnd Env 417 | ELabelEnd Env
417 418
@@ -436,8 +437,8 @@ parent = \case
436 EBind1 _ _ x _ -> Right x 437 EBind1 _ _ x _ -> Right x
437 EApp1 _ _ x _ -> Right x 438 EApp1 _ _ x _ -> Right x
438 EApp2 _ _ _ x -> Right x 439 EApp2 _ _ _ x -> Right x
439 ELet1 x _ -> Right x 440 ELet1 _ x _ -> Right x
440 ELet2 _ x -> Right x 441 ELet2 _ _ x -> Right x
441 CheckType _ x -> Right x 442 CheckType _ x -> Right x
442 CheckIType _ x -> Right x 443 CheckIType _ x -> Right x
443 CheckSame _ x -> Right x 444 CheckSame _ x -> Right x
@@ -452,7 +453,7 @@ initEnv = Map.fromList
452 ] 453 ]
453 454
454-- monad used during elaborating statments -- TODO: use zippers instead 455-- monad used during elaborating statments -- TODO: use zippers instead
455type ElabStmtM m = ReaderT String{-full source-} (StateT GlobalEnv (ExceptT String (WriterT Infos m))) 456type ElabStmtM m = ReaderT (Extensions, String{-full source-}) (StateT GlobalEnv (ExceptT String (WriterT Infos m)))
456 457
457newtype Infos = Infos (Map.Map (SourcePos, SourcePos) (Set.Set String)) 458newtype Infos = Infos (Map.Map (SourcePos, SourcePos) (Set.Set String))
458 deriving (NFData) 459 deriving (NFData)
@@ -560,7 +561,7 @@ handleLet i j f
560 561
561foldS g f i = \case 562foldS g f i = \case
562 SApp _ _ a b -> foldS g f i a <> foldS g f i b 563 SApp _ _ a b -> foldS g f i a <> foldS g f i b
563 SLet a b -> foldS g f i a <> foldS g f (i+1) b 564 SLet _ a b -> foldS g f i a <> foldS g f (i+1) b
564 SBind _ _ _ a b -> foldS g f i a <> foldS g f (i+1) b 565 SBind _ _ _ a b -> foldS g f i a <> foldS g f (i+1) b
565 STyped si (e, t) -> f si i e <> f si i t 566 STyped si (e, t) -> f si i e <> f si i t
566 SVar (si, _) j -> f si i (Var j) 567 SVar (si, _) j -> f si i (Var j)
@@ -601,7 +602,7 @@ mapS_ gg ff = mapS__ gg ff $ \sn i j -> case ff i $ Var j of
601mapS__ gg f1 f2 h e = g e where 602mapS__ gg f1 f2 h e = g e where
602 g i = \case 603 g i = \case
603 SApp si v a b -> SApp si v (g i a) (g i b) 604 SApp si v a b -> SApp si v (g i a) (g i b)
604 SLet a b -> SLet (g i a) (g (h i) b) 605 SLet x a b -> SLet x (g i a) (g (h i) b)
605 SBind si k si' a b -> SBind si k si' (g i a) (g (h i) b) 606 SBind si k si' a b -> SBind si k si' (g i a) (g (h i) b)
606 STyped si (x, t) -> STyped si (f1 i x, f1 i t) 607 STyped si (x, t) -> STyped si (f1 i x, f1 i t)
607 SVar sn j -> f2 sn i j 608 SVar sn j -> f2 sn i j
@@ -644,6 +645,12 @@ substSG :: SName -> (SI -> SExp) -> SExp -> SExp
644substSG j x = mapS_ (\si x i -> if i == j then x si else SGlobal (si, i)) (const id) (fmap upS) x 645substSG j x = mapS_ (\si x i -> if i == j then x si else SGlobal (si, i)) (const id) (fmap upS) x
645substSG0 n e = substSG n (\si -> (SVar (si, n) 0)) $ upS e 646substSG0 n e = substSG n (\si -> (SVar (si, n) 0)) $ upS e
646 647
648dbf' = dbf_ 0
649dbf_ j xs e = foldl (\e (i, (si, n)) -> substSG n (\si -> SVar (si, n) i) e) e $ zip [j..] xs
650
651dbff :: DBNames -> SExp -> SExp
652dbff ns e = foldr substSG0 e $ map snd ns
653
647substE err = substE_ (error $ "substE: todo: environment required in " ++ err) -- todo: remove 654substE err = substE_ (error $ "substE: todo: environment required in " ++ err) -- todo: remove
648 655
649substE_ :: Env -> Int -> Exp -> Exp -> Exp 656substE_ :: Env -> Int -> Exp -> Exp -> Exp
@@ -688,7 +695,7 @@ varType :: String -> Int -> Env -> (Binder, Exp)
688varType err n_ env = f n_ env where 695varType err n_ env = f n_ env where
689 f n (EAssign i x es) = id *** substE "varType" i x $ f (if n < i then n else n+1) es 696 f n (EAssign i x es) = id *** substE "varType" i x $ f (if n < i then n else n+1) es
690 f n (EBind2 b t es) = if n == 0 then (b, up1E 0 t) else id *** up1E 0 $ f (n-1) es 697 f n (EBind2 b t es) = if n == 0 then (b, up1E 0 t) else id *** up1E 0 $ f (n-1) es
691 f n (ELet2 (x, t) es) = if n == 0 then (BLam Visible{-??-}, up1E 0 t) else id *** up1E 0 $ f (n-1) es 698 f n (ELet2 _ (x, t) es) = if n == 0 then (BLam Visible{-??-}, up1E 0 t) else id *** up1E 0 $ f (n-1) es
692 f n e = either (error $ "varType: " ++ err ++ "\n" ++ show n_ ++ "\n" ++ showEnv env) (f n) $ parent e 699 f n e = either (error $ "varType: " ++ err ++ "\n" ++ show n_ ++ "\n" ++ showEnv env) (f n) $ parent e
693 700
694-------------------------------------------------------------------------------- reduction 701-------------------------------------------------------------------------------- reduction
@@ -985,7 +992,7 @@ inferN tracelevel = infer where
985 STyped si et -> focus_' te exp et 992 STyped si et -> focus_' te exp et
986 SGlobal (si, s) -> focus_' te exp =<< getDef te si s 993 SGlobal (si, s) -> focus_' te exp =<< getDef te si s
987 SApp si h a b -> infer (EApp1 (si `validate` [sourceInfo a, sourceInfo b]) h te b) a 994 SApp si h a b -> infer (EApp1 (si `validate` [sourceInfo a, sourceInfo b]) h te b) a
988 SLet a b -> infer (ELet1 te b{-in-}) a{-let-} -- infer te SLamV b `SAppV` a) 995 SLet le a b -> infer (ELet1 le te b{-in-}) a{-let-} -- infer te SLamV b `SAppV` a)
989 SBind si h _ a b -> infer ((if h /= BMeta then CheckType_ (sourceInfo exp) TType else id) $ EBind1 si h te $ (if isPi h then TyType else id) b) a 996 SBind si h _ a b -> infer ((if h /= BMeta then CheckType_ (sourceInfo exp) TType else id) $ EBind1 si h te $ (if isPi h then TyType else id) b) a
990 997
991 checkN :: Env -> SExp -> Exp -> TCM m ExpType 998 checkN :: Env -> SExp -> Exp -> TCM m ExpType
@@ -1059,8 +1066,8 @@ inferN tracelevel = infer where
1059 | otherwise -> infer (CheckType_ (sourceInfo b) (Var 2) $ cstr' h (upE 0 2 et) (Pi Visible (Var 1) (Var 1)) (upE 0 2 e) $ EBind2_ (sourceInfo b) BMeta TType $ EBind2_ (sourceInfo b) BMeta TType te) (upS__ 0 3 b) 1066 | otherwise -> infer (CheckType_ (sourceInfo b) (Var 2) $ cstr' h (upE 0 2 et) (Pi Visible (Var 1) (Var 1)) (upE 0 2 e) $ EBind2_ (sourceInfo b) BMeta TType $ EBind2_ (sourceInfo b) BMeta TType te) (upS__ 0 3 b)
1060 where 1067 where
1061 cstr' h x y e = EApp2 noSI h (eval (error "cstr'") $ Coe (up1E 0 x) (up1E 0 y) (Var 0) (up1E 0 e)) . EBind2_ (sourceInfo b) BMeta (cstr x y) 1068 cstr' h x y e = EApp2 noSI h (eval (error "cstr'") $ Coe (up1E 0 x) (up1E 0 y) (Var 0) (up1E 0 e)) . EBind2_ (sourceInfo b) BMeta (cstr x y)
1062 ELet1 te b{-in-} -> replaceMetas "let" Lam e >>= \e' -> infer (ELet2 (addType_ te e'{-let-}) te) b{-in-} 1069 ELet1 le te b{-in-} -> replaceMetas "let" Lam e >>= \e' -> infer (ELet2 le (addType_ te e'{-let-}) te) b{-in-}
1063 ELet2 (x{-let-}, xt) te -> focus_ te (substE "app2" 0 (x{-let-}) ( e{-in-}), et) 1070 ELet2 le (x{-let-}, xt) te -> focus_ te (substE "app2" 0 (mkELet le x xt){-let-} e{-in-}, et)
1064 CheckIType x te -> checkN te x e 1071 CheckIType x te -> checkN te x e
1065 CheckType_ si t te 1072 CheckType_ si t te
1066 | hArgs et > hArgs t 1073 | hArgs et > hArgs t
@@ -1083,11 +1090,11 @@ inferN tracelevel = infer where
1083 -> refocus te $ both (substE "inferN3" 1 (Var 0)) (e, et) 1090 -> refocus te $ both (substE "inferN3" 1 (Var 0)) (e, et)
1084 | EBind2 h x te' <- te, h /= BMeta, Just b' <- downE 0 tt 1091 | EBind2 h x te' <- te, h /= BMeta, Just b' <- downE 0 tt
1085 -> refocus (EBind2_ si h (up1E 0 x) $ EBind2_ si BMeta b' te') $ both (substE "inferN3" 2 (Var 0) . up1E 0) (e, et) 1092 -> refocus (EBind2_ si h (up1E 0 x) $ EBind2_ si BMeta b' te') $ both (substE "inferN3" 2 (Var 0) . up1E 0) (e, et)
1086 | ELet2 (x, xt) te' <- te, Just b' <- downE 0 tt 1093 | ELet2 le (x, xt) te' <- te, Just b' <- downE 0 tt
1087 -> refocus (ELet2 (up1E 0 x, up1E 0 xt) $ EBind2_ si BMeta b' te') $ both (substE "inferN32" 2 (Var 0) . up1E 0) (e, et) 1094 -> refocus (ELet2 le (up1E 0 x, up1E 0 xt) $ EBind2_ si BMeta b' te') $ both (substE "inferN32" 2 (Var 0) . up1E 0) (e, et)
1088 | EBind1 si h te' x <- te -> refocus (EBind1 si h (EBind2_ si BMeta tt te') $ upS__ 1 1 x) (e, et) 1095 | EBind1 si h te' x <- te -> refocus (EBind1 si h (EBind2_ si BMeta tt te') $ upS__ 1 1 x) (e, et)
1089 | ELet1 te' x <- te, {-usedE 0 e, -} floatLetMeta $ expType_ "3" env $ replaceMetas' Lam $ Meta tt e --not (tt == TType) {-todo: tweak?-} 1096 | ELet1 le te' x <- te, {-usedE 0 e, -} floatLetMeta $ expType_ "3" env $ replaceMetas' Lam $ Meta tt e --not (tt == TType) {-todo: tweak?-}
1090 -> refocus (ELet1 (EBind2_ si BMeta tt te') $ upS__ 1 1 x) (e, et) 1097 -> refocus (ELet1 le (EBind2_ si BMeta tt te') $ upS__ 1 1 x) (e, et)
1091 | CheckAppType si h t te' x <- te -> refocus (CheckAppType si h (up1E 0 t) (EBind2_ si BMeta tt te') $ upS x) (e, et) 1098 | CheckAppType si h t te' x <- te -> refocus (CheckAppType si h (up1E 0 t) (EBind2_ si BMeta tt te') $ upS x) (e, et)
1092 | EApp1 si h te' x <- te -> refocus (EApp1 si h (EBind2_ si BMeta tt te') $ upS x) (e, et) 1099 | EApp1 si h te' x <- te -> refocus (EApp1 si h (EBind2_ si BMeta tt te') $ upS x) (e, et)
1093 | EApp2 si h x te' <- te -> refocus (EApp2 si h (up1E 0 x) $ EBind2_ si BMeta tt te') (e, et) 1100 | EApp2 si h x te' <- te -> refocus (EApp2 si h (up1E 0 x) $ EBind2_ si BMeta tt te') (e, et)
@@ -1106,9 +1113,9 @@ inferN tracelevel = infer where
1106 EAssign i b te -> case te of 1113 EAssign i b te -> case te of
1107 EBind2_ si h x te' | i > 0, Just b' <- downE 0 b 1114 EBind2_ si h x te' | i > 0, Just b' <- downE 0 b
1108 -> refocus' (EBind2_ si h (substE "inferN5" (i-1) b' x) (EAssign (i-1) b' te')) (e, et) 1115 -> refocus' (EBind2_ si h (substE "inferN5" (i-1) b' x) (EAssign (i-1) b' te')) (e, et)
1109 ELet2 (x, xt) te' | i > 0, Just b' <- downE 0 b 1116 ELet2 le (x, xt) te' | i > 0, Just b' <- downE 0 b
1110 -> refocus' (ELet2 (substE "inferN51" (i-1) b' x, substE "inferN52" (i-1) b' xt) (EAssign (i-1) b' te')) (e, et) 1117 -> refocus' (ELet2 le (substE "inferN51" (i-1) b' x, substE "inferN52" (i-1) b' xt) (EAssign (i-1) b' te')) (e, et)
1111 ELet1 te' x -> refocus' (ELet1 (EAssign i b te') $ substS (i+1) (up1E 0 b) x) (e, et) 1118 ELet1 le te' x -> refocus' (ELet1 le (EAssign i b te') $ substS (i+1) (up1E 0 b) x) (e, et)
1112 EBind1 si h te' x -> refocus' (EBind1 si h (EAssign i b te') $ substS (i+1) (up1E 0 b) x) (e, et) 1119 EBind1 si h te' x -> refocus' (EBind1 si h (EAssign i b te') $ substS (i+1) (up1E 0 b) x) (e, et)
1113 CheckAppType si h t te' x -> refocus' (CheckAppType si h (substE "inferN6" i b t) (EAssign i b te') $ substS i b x) (e, et) 1120 CheckAppType si h t te' x -> refocus' (CheckAppType si h (substE "inferN6" i b t) (EAssign i b te') $ substS i b x) (e, et)
1114 EApp1 si h te' x -> refocus' (EApp1 si h (EAssign i b te') $ substS i b x) (e, et) 1121 EApp1 si h te' x -> refocus' (EApp1 si h (EAssign i b te') $ substS i b x) (e, et)
@@ -1163,8 +1170,8 @@ recheck' msg' e x = e'
1163 e@EGlobal{} -> e 1170 e@EGlobal{} -> e
1164 EBind1 si h e b -> EBind1 si h (checkEnv e) b 1171 EBind1 si h e b -> EBind1 si h (checkEnv e) b
1165 EBind2_ si h t e -> EBind2_ si h (recheckEnv e t) $ checkEnv e -- E [\(x :: t) -> e] -> check E [t] 1172 EBind2_ si h t e -> EBind2_ si h (recheckEnv e t) $ checkEnv e -- E [\(x :: t) -> e] -> check E [t]
1166 ELet1 e b -> ELet1 (checkEnv e) b 1173 ELet1 le e b -> ELet1 le (checkEnv e) b
1167 ELet2 (x, t) e -> ELet2 (recheckEnv e x, recheckEnv e t{-?-}) $ checkEnv e 1174 ELet2 le (x, t) e -> ELet2 le (recheckEnv e x, recheckEnv e t{-?-}) $ checkEnv e
1168 EApp1 si h e b -> EApp1 si h (checkEnv e) b 1175 EApp1 si h e b -> EApp1 si h (checkEnv e) b
1169 EApp2 si h a e -> EApp2 si h (recheckEnv {-(EApp1 h e _)-}e a) $ checkEnv e -- E [a x] -> check 1176 EApp2 si h a e -> EApp2 si h (recheckEnv {-(EApp1 h e _)-}e a) $ checkEnv e -- E [a x] -> check
1170 EAssign i x e -> EAssign i (recheckEnv e $ up1E i x) $ checkEnv e -- __ <i := x> 1177 EAssign i x e -> EAssign i (recheckEnv e $ up1E i x) $ checkEnv e -- __ <i := x>
@@ -1279,12 +1286,12 @@ checkMetas err = \case
1279 where 1286 where
1280 f = checkMetas err 1287 f = checkMetas err
1281 1288
1282getGEnv exs f = do 1289getGEnv f = do
1283 src <- ask 1290 (exs, src) <- ask
1284 gets (\ge -> EGlobal src ge mempty) >>= f 1291 gets (\ge -> EGlobal src ge mempty) >>= f
1285inferTerm exs msg tr f t = getGEnv exs $ \env -> let env' = f env in smartTrace exs $ \tr -> 1292inferTerm msg tr f t = asks fst >>= \exs -> getGEnv $ \env -> let env' = f env in smartTrace exs $ \tr ->
1286 fmap (addType . recheck msg env') $ replaceMetas "lam" Lam . fst =<< lift (lift $ inferN (if tr then trace_level exs else 0) env' t) 1293 fmap (addType . recheck msg env') $ replaceMetas "lam" Lam . fst =<< lift (lift $ inferN (if tr then trace_level exs else 0) env' t)
1287inferType exs tr t = getGEnv exs $ \env -> fmap (recheck "inferType" env) $ replaceMetas "pi" Pi . fst =<< lift (lift $ inferN (if tr then trace_level exs else 0) (CheckType_ (debugSI "inferType CheckType_") TType env) t) 1294inferType tr t = asks fst >>= \exs -> getGEnv $ \env -> fmap (recheck "inferType" env) $ replaceMetas "pi" Pi . fst =<< lift (lift $ inferN (if tr then trace_level exs else 0) (CheckType_ (debugSI "inferType CheckType_") TType env) t)
1288 1295
1289smartTrace :: MonadError String m => Extensions -> (Bool -> m a) -> m a 1296smartTrace :: MonadError String m => Extensions -> (Bool -> m a) -> m a
1290smartTrace exs f | trace_level exs >= 2 = f True 1297smartTrace exs f | trace_level exs >= 2 = f True
@@ -1297,14 +1304,15 @@ smartTrace exs f = catchError (f False) $ \err ->
1297 , "---------------------------------" 1304 , "---------------------------------"
1298 ]) $ f True 1305 ]) $ f True
1299 1306
1300addToEnv :: Monad m => Extensions -> SIName -> (Exp, Exp) -> ElabStmtM m () 1307addToEnv :: Monad m => SIName -> (Exp, Exp) -> ElabStmtM m ()
1301addToEnv exs (si, s) (x, t) = do 1308addToEnv (si, s) (x, t) = do
1302-- maybe (pure ()) throwError_ $ ambiguityCheck s t 1309-- maybe (pure ()) throwError_ $ ambiguityCheck s t
1310 exs <- asks fst
1303 when (tr_light exs) $ mtrace (s ++ " :: " ++ showExp t) 1311 when (tr_light exs) $ mtrace (s ++ " :: " ++ showExp t)
1304 v <- gets $ Map.lookup s 1312 v <- gets $ Map.lookup s
1305 case v of 1313 case v of
1306 Nothing -> modify $ Map.insert s (closedExp x, closedExp t, si) 1314 Nothing -> modify $ Map.insert s (closedExp x, closedExp t, si)
1307 Just (_, _, si') -> getGEnv exs $ \ge -> throwError $ "already defined " ++ s ++ " at " ++ showSI ge si ++ "\n and at " ++ showSI ge si' 1315 Just (_, _, si') -> getGEnv $ \ge -> throwError $ "already defined " ++ s ++ " at " ++ showSI ge si ++ "\n and at " ++ showSI ge si'
1308 1316
1309-- Ambiguous: (Int ~ F a) => Int 1317-- Ambiguous: (Int ~ F a) => Int
1310-- Not ambiguous: (Show a, a ~ F b) => b 1318-- Not ambiguous: (Show a, a ~ F b) => b
@@ -1363,42 +1371,59 @@ downToS n m = map (SVar (debugSI "20", ".ds")) [n+m-1, n+m-2..n]
1363 1371
1364defined' = Map.keys 1372defined' = Map.keys
1365 1373
1366addF exs = gets $ addForalls exs . defined' 1374addF = asks fst >>= \exs -> gets $ addForalls exs . defined'
1367 1375
1368tellType te si t = tell $ mkInfoItem (sourceInfo si) $ removeEscs $ showExp {-te TODO-} t 1376tellType te si t = tell $ mkInfoItem (sourceInfo si) $ removeEscs $ showExp {-te TODO-} t
1369tellStmtType exs si t = getGEnv exs $ \te -> tellType te si t 1377tellStmtType si t = getGEnv $ \te -> tellType te si t
1370 1378
1371handleStmt :: MonadFix m => Extensions -> Stmt -> ElabStmtM m () 1379xSLabelEnd = id --SLabelEnd
1372handleStmt exs = \case 1380
1373 PrecDef{} -> return () 1381type LI = (Bool, SIName, SData (Maybe Fixity), [Visibility])
1382
1383mkELet (False, n, mf, ar) x xt = x
1384mkELet (True, n, SData mf, ar) x t{-type of x-} = term
1385 where
1386 term = label LabelPM (addLams' ar t 0) $ par ar t x 0
1387
1388 addLams' [] _ i = Fun (FunName (snd n) mf t) $ downTo 0 i
1389 addLams' (h: ar) (Pi h' d t) i | h == h' = Lam h d $ addLams' ar t (i+1)
1390 addLams' ar@(Visible: _) (Pi h@Hidden d t) i = Lam h d $ addLams' ar t (i+1)
1391
1392 par ar tt (FunN "primFix" [_, f]) i = f `app_` label LabelFix (addLams' ar tt i) (foldl app_ term $ downTo 0 i)
1393 par ar (Pi Hidden _ tt) (Lam Hidden k z) i = Lam Hidden k $ par (dropHidden ar) tt z (i+1)
1394 where
1395 dropHidden (Hidden: ar) = ar
1396 dropHidden ar = ar
1397 par ar t x _ = x
1398
1399mkLets :: Bool -> GlobalEnv' -> [Stmt]{-where block-} -> SExp{-main expression-} -> SExp{-big let with lambdas; replaces global names with de bruijn indices-}
1400mkLets _ _ [] e = e
1401mkLets False ge (Let n _ mt ar (downS 0 -> Just x): ds) e
1402 = SLet (False, n, (SData Nothing), ar) (maybe id (flip SAnn . addForalls {-todo-}[] []) mt x) (substSG0 (snd n) $ mkLets False ge ds e)
1403mkLets True ge (Let n _ mt ar (downS 0 -> Just x): ds) e
1404 = SLet (False, n, (SData Nothing), ar) (maybe id (flip SAnn . addForalls {-todo-}[] []) mt x) (substSG0 (snd n) $ mkLets True ge ds e)
1405mkLets le ge (ValueDef p x: ds) e = patLam id ge p (dbff (getPVars p) $ mkLets le ge ds e) `SAppV` x -- (p = e; f) --> (\p -> f) e
1406mkLets _ _ (x: ds) e = error $ "mkLets: " ++ show x
1407
1408handleStmt :: MonadFix m => [Stmt] -> Stmt -> ElabStmtM m ()
1409handleStmt defs = \case
1374 Primitive n mf t_ -> do 1410 Primitive n mf t_ -> do
1375 t <- inferType exs tr =<< ($ t_) <$> addF exs 1411 t <- inferType tr =<< ($ t_) <$> addF
1376 tellStmtType exs (fst n) t 1412 tellStmtType (fst n) t
1377 addToEnv exs n $ flip (,) t $ lamify t $ Fun (FunName (snd n) mf t) 1413 addToEnv n $ flip (,) t $ lamify t $ Fun (FunName (snd n) mf t)
1378 Let n mf mt ar t_ -> do 1414 Let n mf mt ar t_ -> do
1379 af <- addF exs 1415 af <- addF
1380 let t__ = maybe id (flip SAnn . af) mt t_ 1416 let t__ = maybe id (flip SAnn . af) mt t_
1381 (x, t) <- inferTerm exs (snd n) tr id $ fromMaybe (SBuiltin "primFix" `SAppV` SLamV t__) $ downS 0 t__ 1417 (x, t) <- inferTerm (snd n) tr id $ fromMaybe (SBuiltin "primFix" `SAppV` SLamV t__) $ downS 0 t__
1382 let 1418 tellStmtType (fst n) t
1383 term = label LabelPM (addLams' ar t 0) $ par ar t x 0 1419 addToEnv n (mkELet (True, n, SData mf, ar) x t, t)
1384 1420 PrecDef{} -> return ()
1385 addLams' [] _ i = Fun (FunName (snd n) mf t) $ downTo 0 i 1421 TypeFamily s ps t -> handleStmt defs $ Primitive s Nothing $ addParamsS ps t
1386 addLams' (h: ar) (Pi h' d t) i | h == h' = Lam h d $ addLams' ar t (i+1)
1387 addLams' ar@(Visible: _) (Pi h@Hidden d t) i = Lam h d $ addLams' ar t (i+1)
1388
1389 par ar tt (FunN "primFix" [_, f]) i = f `app_` label LabelFix (addLams' ar tt i) (foldl app_ term $ downTo 0 i)
1390 par ar (Pi Hidden _ tt) (Lam Hidden k z) i = Lam Hidden k $ par (dropHidden ar) tt z (i+1)
1391 where
1392 dropHidden (Hidden: ar) = ar
1393 dropHidden ar = ar
1394 par ar t x _ = x
1395 tellStmtType exs (fst n) t
1396 addToEnv exs n (term, t)
1397 TypeFamily s ps t -> handleStmt exs $ Primitive s Nothing $ addParamsS ps t
1398 Data s ps t_ addfa cs -> do 1422 Data s ps t_ addfa cs -> do
1423 exs <- asks fst
1399 af <- if addfa then gets $ addForalls exs . (snd s:) . defined' else return id 1424 af <- if addfa then gets $ addForalls exs . (snd s:) . defined' else return id
1400 vty <- inferType exs tr $ addParamsS ps t_ 1425 vty <- inferType tr $ addParamsS ps t_
1401 tellStmtType exs (fst s) vty 1426 tellStmtType (fst s) vty
1402 let 1427 let
1403 pnum' = length $ filter ((== Visible) . fst) ps 1428 pnum' = length $ filter ((== Visible) . fst) ps
1404 inum = arity vty - length ps 1429 inum = arity vty - length ps
@@ -1406,13 +1431,13 @@ handleStmt exs = \case
1406 mkConstr j (cn, af -> ct) 1431 mkConstr j (cn, af -> ct)
1407 | c == SGlobal s && take pnum' xs == downToS (length . fst . getParamsS $ ct) pnum' 1432 | c == SGlobal s && take pnum' xs == downToS (length . fst . getParamsS $ ct) pnum'
1408 = do 1433 = do
1409 cty <- removeHiddenUnit <$> inferType exs tr (addParamsS [(Hidden, x) | (Visible, x) <- ps] ct) 1434 cty <- removeHiddenUnit <$> inferType tr (addParamsS [(Hidden, x) | (Visible, x) <- ps] ct)
1410 tellStmtType exs (fst cn) cty 1435 tellStmtType (fst cn) cty
1411 let pars = zipWith (\x -> id *** (STyped (debugSI "mkConstr1")) . flip (,) TType . upE x (1+j)) [0..] $ drop (length ps) $ fst $ getParams cty 1436 let pars = zipWith (\x -> id *** (STyped (debugSI "mkConstr1")) . flip (,) TType . upE x (1+j)) [0..] $ drop (length ps) $ fst $ getParams cty
1412 act = length . fst . getParams $ cty 1437 act = length . fst . getParams $ cty
1413 acts = map fst . fst . getParams $ cty 1438 acts = map fst . fst . getParams $ cty
1414 conn = ConName (snd cn) Nothing j cty 1439 conn = ConName (snd cn) (listToMaybe [f | PrecDef n f <- defs, n == cn]) j cty
1415 addToEnv exs cn (Con conn [], cty) 1440 addToEnv cn (Con conn [], cty)
1416 return ( conn 1441 return ( conn
1417 , addParamsS pars 1442 , addParamsS pars
1418 $ foldl SAppV (SVar (debugSI "22", ".cs") $ j + length pars) $ drop pnum' xs ++ [apps' (SGlobal cn) (zip acts $ downToS (j+1+length pars) (length ps) ++ downToS 0 (act- length ps))] 1443 $ foldl SAppV (SVar (debugSI "22", ".cs") $ j + length pars) $ drop pnum' xs ++ [apps' (SGlobal cn) (zip acts $ downToS (j+1+length pars) (length ps) ++ downToS 0 (act- length ps))]
@@ -1426,9 +1451,9 @@ handleStmt exs = \case
1426 1451
1427 mdo 1452 mdo
1428 let tcn = TyConName (snd s) Nothing inum vty (map fst cons) ct 1453 let tcn = TyConName (snd s) Nothing inum vty (map fst cons) ct
1429 addToEnv exs s (TyCon tcn [], vty) 1454 addToEnv s (TyCon tcn [], vty)
1430 cons <- zipWithM mkConstr [0..] cs 1455 cons <- zipWithM mkConstr [0..] cs
1431 ct <- inferType exs tr 1456 ct <- inferType tr
1432 ( (\x -> traceD ("type of case-elim before elaboration: " ++ showSExp x) x) $ addParamsS 1457 ( (\x -> traceD ("type of case-elim before elaboration: " ++ showSExp x) x) $ addParamsS
1433 ( [(Hidden, x) | (_, x) <- ps] 1458 ( [(Hidden, x) | (_, x) <- ps]
1434 ++ (Visible, motive) 1459 ++ (Visible, motive)
@@ -1438,14 +1463,14 @@ handleStmt exs = \case
1438 ) 1463 )
1439 $ foldl SAppV (SVar (debugSI "23", ".ct") $ length cs + inum + 1) $ downToS 1 inum ++ [SVar (debugSI "24", ".24") 0] 1464 $ foldl SAppV (SVar (debugSI "23", ".ct") $ length cs + inum + 1) $ downToS 1 inum ++ [SVar (debugSI "24", ".24") 0]
1440 ) 1465 )
1441 addToEnv exs (fst s, caseName (snd s)) (lamify ct $ CaseFun (CaseFunName (snd s) ct $ length ps), ct) 1466 addToEnv (fst s, caseName (snd s)) (lamify ct $ CaseFun (CaseFunName (snd s) ct $ length ps), ct)
1442 let ps' = fst $ getParams vty 1467 let ps' = fst $ getParams vty
1443 t = (TType :~> TType) 1468 t = (TType :~> TType)
1444 :~> addParams ps' (Var (length ps') `app_` TyCon tcn (downTo 0 $ length ps')) 1469 :~> addParams ps' (Var (length ps') `app_` TyCon tcn (downTo 0 $ length ps'))
1445 :~> TType 1470 :~> TType
1446 :~> Var 2 `app_` Var 0 1471 :~> Var 2 `app_` Var 0
1447 :~> Var 3 `app_` Var 1 1472 :~> Var 3 `app_` Var 1
1448 addToEnv exs (fst s, matchName (snd s)) (lamify t $ TyCaseFun (TyCaseFunName (snd s) t), t) 1473 addToEnv (fst s, matchName (snd s)) (lamify t $ TyCaseFun (TyCaseFunName (snd s) t), t)
1449 1474
1450 stmt -> error $ "handleStmt: " ++ show stmt 1475 stmt -> error $ "handleStmt: " ++ show stmt
1451 1476
@@ -1457,18 +1482,19 @@ removeHiddenUnit t = t
1457-------------------------------------- parser ----------------------------------------- 1482-------------------------------------- parser -----------------------------------------
1458 1483
1459-- see http://blog.ezyang.com/2014/05/parsec-try-a-or-b-considered-harmful/comment-page-1/#comment-6602 1484-- see http://blog.ezyang.com/2014/05/parsec-try-a-or-b-considered-harmful/comment-page-1/#comment-6602
1460try' s m = try m <?> s 1485try s m = Pa.try m <?> s
1461 1486
1462check msg p m = try' msg $ mfilter p m 1487check msg p m = try msg $ mfilter p m
1463 1488
1464-------------------------------------------------------------------------------- parser type 1489-------------------------------------------------------------------------------- parser type
1465 1490
1466type P = ParsecT (IndentStream (CharIndentStream String)) SourcePos (Reader GlobalEnv') 1491type P = ParsecT (IndentStream (CharIndentStream String)) SourcePos InnerP
1492type InnerP = StateT [DBNames] (Reader (GlobalEnv', Namespace))
1467 1493
1468 1494
1469-------------------------------------------------------------------------------- lexing 1495-------------------------------------------------------------------------------- lexing
1470 1496
1471lexer :: Pa.GenTokenParser (IndentStream (CharIndentStream String)) SourcePos (Reader GlobalEnv') 1497lexer :: Pa.GenTokenParser (IndentStream (CharIndentStream String)) SourcePos InnerP
1472lexer = makeTokenParser lexeme $ makeIndentLanguageDef style 1498lexer = makeTokenParser lexeme $ makeIndentLanguageDef style
1473 where 1499 where
1474 style = Pa.LanguageDef 1500 style = Pa.LanguageDef
@@ -1523,30 +1549,20 @@ data Level
1523 | ExpLevel 1549 | ExpLevel
1524 deriving (Eq, Show) 1550 deriving (Eq, Show)
1525 1551
1526levelElim typeLevel expLevel = \case 1552data Namespace = Namespace (Maybe Level) Bool{-True means case sensitive first letter parsing-}
1527 TypeLevel -> typeLevel
1528 ExpLevel -> expLevel
1529
1530data Namespace
1531 = Namespace Level Bool{-True means case sensitive first letter parsing-}
1532 | NonTypeNamespace
1533 deriving (Show) 1553 deriving (Show)
1534 1554
1535caseSensitiveNS :: Namespace -> Bool 1555caseSensitiveNS :: Namespace -> Bool
1536caseSensitiveNS NonTypeNamespace = True
1537caseSensitiveNS (Namespace _ sensitive) = sensitive 1556caseSensitiveNS (Namespace _ sensitive) = sensitive
1538 1557
1539namespaceLevel (Namespace l _) = Just l 1558namespaceLevel (Namespace l _) = l
1540namespaceLevel _ = Nothing
1541
1542typeNS (Namespace _ p) = Namespace TypeLevel p
1543typeNS n = n
1544 1559
1545expNS (Namespace _ p) = Namespace ExpLevel p 1560mapLevel f (Namespace l p) = Namespace (f l) p
1546expNS n = n
1547 1561
1548switchNS (Namespace l p) = Namespace (case l of ExpLevel -> TypeLevel; TypeLevel -> ExpLevel) p 1562typeNS, expNS, switchNS :: P a -> P a
1549switchNS n = n 1563typeNS = local $ id *** mapLevel (const TypeLevel <$>)
1564expNS = local $ id *** mapLevel (const ExpLevel <$>)
1565switchNS = local $ id *** mapLevel ((\l -> case l of ExpLevel -> TypeLevel; TypeLevel -> ExpLevel) <$>)
1550 1566
1551tick TypeLevel ('\'':n) = n 1567tick TypeLevel ('\'':n) = n
1552tick TypeLevel n = '\'': n 1568tick TypeLevel n = '\'': n
@@ -1554,31 +1570,32 @@ tick _ n = n
1554 1570
1555tick' = tick . fromMaybe ExpLevel . namespaceLevel 1571tick' = tick . fromMaybe ExpLevel . namespaceLevel
1556 1572
1557tickIdent ns = tick' ns <$> identifier 1573getNS :: (Namespace -> P a) -> P a
1574getNS f = asks snd >>= f
1575
1576getNS' :: (Namespace -> a) -> P a
1577getNS' f = getNS $ return . f
1558 1578
1559-------------------------------------------------------------------------------- identifiers 1579-------------------------------------------------------------------------------- identifiers
1560 1580
1561--upperCase, lowerCase, symbols, colonSymbols :: P String 1581upperCase, lowerCase, symbols, colonSymbols :: P SName
1562upperCase NonTypeNamespace = mzero -- todo 1582--upperCase NonTypeNamespace = mzero -- todo
1563upperCase ns = (if caseSensitiveNS ns then check "uppercase ident" (isUpper . head') else id) $ tickIdent ns 1583upperCase = getNS $ \ns -> (if caseSensitiveNS ns then check "uppercase ident" (isUpper . head') else id) $ tick' ns <$> (identifier <|> try "tick ident" (('\'':) <$ char '\'' <*> identifier))
1564lowerCase ns = (if caseSensitiveNS ns then check "lowercase ident" (isLower . head') else id) identifier <|> try (('_':) <$ char '_' <*> identifier) 1584lowerCase = getNS $ \ns -> (if caseSensitiveNS ns then check "lowercase ident" (isLower . head') else id) identifier
1585 <|> try "underscore ident" (('_':) <$ char '_' <*> identifier)
1565symbols = check "symbols" ((/=':') . head) operator 1586symbols = check "symbols" ((/=':') . head) operator
1566colonSymbols = "Cons" <$ reservedOp ":" <|> check "symbols" ((==':') . head) operator 1587colonSymbols = "Cons" <$ reservedOp ":" <|> check "symbols" ((==':') . head) operator
1567 1588
1568var ns = lowerCase ns 1589moduleName = {-qualified_ todo-} expNS upperCase
1569patVar ns = lowerCase ns <|> "" <$ reserved "_" 1590patVar = lowerCase <|> "" <$ reserved "_"
1570qIdent ns = {-qualified_ todo-} (var ns <|> upperCase ns) 1591--qIdent = {-qualified_ todo-} (lowerCase <|> upperCase)
1571conOperator = colonSymbols 1592backquotedIdent = try "backquoted ident" $ lexeme $ char '`' *> ((:) <$> satisfy isAlpha <*> many (satisfy isAlphaNum)) <* char '`'
1572varId ns = var ns <|> parens operatorT 1593operatorT = symbols <|> colonSymbols <|> backquotedIdent
1573backquotedIdent = try' "backquoted" $ lexeme $ char '`' *> ((:) <$> satisfy isAlpha <*> many (satisfy isAlphaNum)) <* char '`' 1594varId = lowerCase <|> parens operatorT
1574operatorT = symbols
1575 <|> conOperator
1576 <|> backquotedIdent
1577moduleName = {-qualified_ todo-} upperCase (Namespace ExpLevel True)
1578 1595
1579{- 1596{-
1580qualified_ id = do 1597qualified_ id = do
1581 q <- try' "qualification" $ upperCase' <* dot 1598 q <- try "qualification" $ upperCase' <* dot
1582 (N t qs n i) <- qualified_ id 1599 (N t qs n i) <- qualified_ id
1583 return $ N t (q:qs) n i 1600 return $ N t (q:qs) n i
1584 <|> 1601 <|>
@@ -1609,7 +1626,7 @@ data Export = ExportModule SName | ExportId SName
1609parseExport :: Namespace -> P Export 1626parseExport :: Namespace -> P Export
1610parseExport ns = 1627parseExport ns =
1611 ExportModule <$ reserved "module" <*> moduleName 1628 ExportModule <$ reserved "module" <*> moduleName
1612 <|> ExportId <$> varId ns 1629 <|> ExportId <$> varId
1613 1630
1614-------------------------------------------------------------------------------- import 1631-------------------------------------------------------------------------------- import
1615 1632
@@ -1617,7 +1634,7 @@ data ImportItems
1617 = ImportAllBut [SName] 1634 = ImportAllBut [SName]
1618 | ImportJust [SName] 1635 | ImportJust [SName]
1619 1636
1620importlist ns = parens (commaSep (varId ns <|> upperCase ns)) 1637importlist = parens $ commaSep $ varId <|> upperCase
1621 1638
1622-------------------------------------------------------------------------------- extensions 1639-------------------------------------------------------------------------------- extensions
1623 1640
@@ -1632,7 +1649,7 @@ data Extension
1632 1649
1633parseExtensions :: P [Extension] 1650parseExtensions :: P [Extension]
1634parseExtensions 1651parseExtensions
1635 = try (string "{-#") *> simpleSpace *> string "LANGUAGE" *> simpleSpace *> commaSep ext <* simpleSpace <* string "#-}" <* simpleSpace 1652 = try "language pragma" (string "{-#") *> simpleSpace *> string "LANGUAGE" *> simpleSpace *> commaSep ext <* simpleSpace <* string "#-}" <* simpleSpace
1636 where 1653 where
1637 extensions = [toEnum 0 .. ] 1654 extensions = [toEnum 0 .. ]
1638 extensionMap = Map.fromList $ map (show &&& return) extensions 1655 extensionMap = Map.fromList $ map (show &&& return) extensions
@@ -1651,170 +1668,150 @@ data ModuleR
1651 { extensions :: Extensions 1668 { extensions :: Extensions
1652 , moduleImports :: [(SName, ImportItems)] 1669 , moduleImports :: [(SName, ImportItems)]
1653 , moduleExports :: Maybe [Export] 1670 , moduleExports :: Maybe [Export]
1654 , definitions :: GlobalEnv' -> Either String [Stmt] 1671 , definitions :: GlobalEnv' -> (Either String [Stmt], [DBNames])
1655 , sourceCode :: String 1672 , sourceCode :: String
1656 } 1673 }
1657 1674
1658parseLC :: MonadError ErrorMsg m => FilePath -> String -> m ModuleR 1675parseLC :: MonadError ErrorMsg m => FilePath -> String -> m ModuleR
1659parseLC f str = either (throwError . ErrorMsg . show) return . flip runReader (error "globalenv used") . runParserT p (newPos "" 0 0) f . mkIndentStream 0 infIndentation True Ge . mkCharIndentStream $ str 1676parseLC f str
1660 where 1677 = either (throwError . ErrorMsg . show) return
1661 p = do 1678 . flip runReader (error "globalenv used", Namespace (Just ExpLevel) True)
1662 getPosition >>= setState 1679 . flip evalStateT []
1663 setPosition =<< flip setSourceName f <$> getPosition 1680 . runParserT (parseModule f str) (initialPos f) f
1664 exts <- concat <$> many parseExtensions 1681 . mkIndentStream 0 infIndentation True Ge . mkCharIndentStream
1665 let ns = if NoTypeNamespace `elem` exts 1682 $ str
1666 then NonTypeNamespace 1683
1667 else Namespace ExpLevel (not $ NoConstructorNamespace `elem` exts) 1684parseModule f str = do
1668 whiteSpace 1685 exts <- concat <$> many parseExtensions
1669 header <- optionMaybe $ do 1686 let ns = Namespace (if NoTypeNamespace `elem` exts then Nothing else Just ExpLevel) (not $ NoConstructorNamespace `elem` exts)
1670 modn <- reserved "module" *> moduleName 1687 whiteSpace
1671 exps <- optionMaybe (parens $ commaSep $ parseExport ns) 1688 header <- optionMaybe $ do
1672 reserved "where" 1689 modn <- reserved "module" *> moduleName
1673 return (modn, exps) 1690 exps <- optionMaybe (parens $ commaSep $ parseExport ns)
1674 let mkIDef _ n i h _ = (n, f i h) 1691 reserved "where"
1675 where 1692 return (modn, exps)
1676 f Nothing Nothing = ImportAllBut [] 1693 let mkIDef _ n i h _ = (n, f i h)
1677 f (Just h) Nothing = ImportAllBut h 1694 where
1678 f Nothing (Just i) = ImportJust i 1695 f Nothing Nothing = ImportAllBut []
1679 idefs <- many $ 1696 f (Just h) Nothing = ImportAllBut h
1680 mkIDef <$> (reserved "import" *> (optionMaybe $ try $ reserved "qualified")) 1697 f Nothing (Just i) = ImportJust i
1681 <*> moduleName 1698 idefs <- many $
1682 <*> (optionMaybe $ try $ reserved "hiding" *> importlist ns) 1699 mkIDef <$> (reserved "import" *> (optionMaybe $ reserved "qualified"))
1683 <*> (optionMaybe $ try $ importlist ns) 1700 <*> moduleName
1684 <*> (optionMaybe $ try $ reserved "as" *> moduleName) 1701 <*> (optionMaybe $ reserved "hiding" *> importlist)
1685 st <- getParserState 1702 <*> (optionMaybe $ importlist)
1686 1703 <*> (optionMaybe $ reserved "as" *> moduleName)
1687 let defs ge = (show +++ id) . flip runReader ge . runParserT p (newPos "" 0 0) f . mkIndentStream 0 infIndentation True Ge . mkCharIndentStream $ "" 1704 st <- getParserState
1688 where 1705 return $ Module
1689 p = do 1706 { extensions = exts
1690 setParserState st 1707 , moduleImports = [("Prelude", ImportAllBut []) | NoImplicitPrelude `notElem` exts] ++ idefs
1691 parseDefs SLabelEnd ns <* eof 1708 , moduleExports = join $ snd <$> header
1692 return $ Module 1709 , definitions = \ge -> (show +++ id) *** id $ flip runReader (ge, ns) . flip runStateT [] $ runPT' (parseDefs SLabelEnd <* eof) st
1693 { extensions = exts 1710 , sourceCode = str
1694 , moduleImports = if NoImplicitPrelude `elem` exts 1711 }
1695 then idefs 1712
1696 else ("Prelude", ImportAllBut []): idefs 1713runPT' p st --u name s
1697 , moduleExports = join $ snd <$> header 1714 = do res <- runParsecT p st -- (Pa.State s (initialPos name) u)
1698 , definitions = defs 1715 r <- parserReply res
1699 , sourceCode = str 1716 case r of
1700 } 1717 Ok x _ _ -> return (Right x)
1701 1718 Error err -> return (Left err)
1719 where
1720 parserReply res
1721 = case res of
1722 Consumed r -> r
1723 Pa.Empty r -> r
1702-------------------------------------------------------------------------------- 1724--------------------------------------------------------------------------------
1703 1725
1704parseType ns mb = maybe id option mb (reservedOp "::" *> parseTTerm ns PrecLam) 1726parseType mb = maybe id option mb (reservedOp "::" *> parseTTerm PrecLam)
1705typedIds ns mb = (,) <$> commaSep1 (withSI (varId ns <|> patVar ns <|> upperCase ns)) 1727typedIds mb = (,) <$> commaSep1 (withSI (varId <|> patVar <|> upperCase)) <*> localIndentation Gt {-TODO-} (parseType mb)
1706 <*> localIndentation Gt {-TODO-} (parseType ns mb)
1707 1728
1708telescope ns mb = (DBNamesC *** id) <$> telescopeSI ns mb 1729hiddenTerm p q = (,) Hidden <$ reservedOp "@" <*> p <|> (,) Visible <$> q
1709 1730
1710telescopeSI :: Namespace -> Maybe SExp -> P ([SIName], [(Visibility, SExp)]) -- todo: refactor to [(SIName, (Visibility, SExp))] 1731telescopeSI :: Maybe SExp -> P (Visibility, (SIName, SExp))
1711telescopeSI ns mb = first reverse <$> go [] 1732telescopeSI mb
1733 = hiddenTerm (typedId <|> maybe empty (tvar . pure) mb)
1734 $ try "::" typedId <|> maybe ((,) <$> withSI (pure "") <*> parseTTerm PrecAtom) (tvar . pure) mb
1712 where 1735 where
1713 go vs = option ([], []) $ do 1736 tvar x = (,) <$> withSI patVar <*> x
1714 (x, vt) <- 1737 typedId = parens $ tvar $ localIndentation Gt {-TODO-} (parseType mb)
1715 ( reservedOp "@" *> (maybe empty (\x -> flip (,) (Hidden, x) <$> withSI (patVar ns)) mb <|> parens (typedId Hidden))
1716 <|> try (parens $ typedId Visible)
1717 <|> maybe ((,) (debugSI "s13", "") . (,) Visible . dbf' (DBNamesC vs) <$> parseTerm ns PrecAtom)
1718 (\x -> flip (,) (Visible, x) <$> withSI (patVar ns))
1719 mb
1720 )
1721 ((x:) *** (vt:)) <$> go (x: vs)
1722 where
1723 typedId v = (\f s -> (f,(v,s)))
1724 <$> withSI (patVar ns)
1725 <*> localIndentation Gt {-TODO-} (dbf' (DBNamesC vs) <$> parseType ns mb)
1726 1738
1727telescopeDataFields :: Namespace -> P ([SIName], [(Visibility, SExp)]) 1739telescope mb = dbfi <$> many (telescopeSI mb)
1728telescopeDataFields ns = {-telescopeSI ns Nothing-} first reverse <$> go [] 1740
1741telescopeDataFields :: P ([SIName], [(Visibility, SExp)])
1742telescopeDataFields = dbfi <$> commaSep ((,) Visible <$> ((,) <$> withSI lowerCase <*> parseType Nothing))
1743
1744dbfi = first reverse . unzip . go []
1729 where 1745 where
1730 go vs = option ([], []) $ do 1746 go _ [] = []
1731 (x, vt) <- do name <- withSI $ var (expNS ns) 1747 go vs ((v, (n, e)): ts) = (n, (v, dbf' vs e)): go (n: vs) ts
1732 term <- parseType ns Nothing 1748
1733 return (name, (Visible, dbf' (DBNamesC vs) term)) 1749parsePat = \case
1734 ((x:) *** (vt:)) <$> (comma *> go (x: vs) <|> pure ([], [])) 1750 PrecAnn ->
1735 1751 patType <$> parsePat PrecOp <*> parseType (Just $ Wildcard SType)
1736patternAtom ns = patternAtom' ns <&> \p -> (getPVars p, p) 1752 PrecOp ->
1737patternAtom' ns = 1753 asks (calculatePatPrecs . fst) <*> p_
1738-- <|> sLit . LInt . fromIntegral <$ char '#' <*> natural 1754 where
1739 flip ViewPat eqPP . SAppV (SBuiltin "primCompareFloat") <$> (sLit . LFloat <$> try float) 1755 p_ = (,) <$> parsePat PrecApp <*> option [] (withSI colonSymbols >>= p)
1740 <|> flip ViewPat eqPP . SAppV (SBuiltin "primCompareString") <$> (sLit . LString <$> stringLiteral) 1756 p op = do (exp, op') <- try "pattern" ((,) <$> parsePat PrecApp <*> withSI colonSymbols)
1741 <|> flip ViewPat eqPP . SAppV (SBuiltin "primCompareChar") <$> (sLit . LChar <$> try charLiteral) 1757 ((op, exp):) <$> p op'
1742 <|> mkNatPat ns <$> (withSI natural) 1758 <|> pure . (,) op <$> parsePat PrecAnn
1743 <|> flip PCon [] <$> (withSI $ upperCase ns) 1759 PrecApp ->
1744 <|> char '\'' *> patternAtom' (switchNS ns) 1760 PCon <$> withSI upperCase <*> many (ParPat . pure <$> parsePat PrecAtom)
1745 <|> PVar <$> withSI (patVar ns) 1761 <|> parsePat PrecAtom
1746 <|> pConSI . mkListPat ns <$> brackets (patlist ns <|> pure []) 1762 PrecAtom ->
1747 <|> pConSI . mkTupPat ns <$> parens (patlist ns) 1763 litP "primCompareFloat" . LFloat <$> try "float literal" float
1764 <|> litP "primCompareString" . LString <$> stringLiteral
1765 <|> litP "primCompareChar" . LChar <$> try "char literal" charLiteral
1766 <|> getNS' mkNatPat <*> withSI natural
1767 <|> flip PCon [] <$> withSI upperCase
1768 <|> char '\'' *> switchNS (parsePat PrecAtom)
1769 <|> PVar <$> withSI patVar
1770 <|> getNS' (\ns -> pConSI . mkListPat ns) <*> brackets patlist
1771 <|> getNS' (\ns -> pConSI . mkTupPat ns) <*> parens patlist
1748 where 1772 where
1749 mkNatPat (Namespace ExpLevel _) (si, n) = flip ViewPat eqPP . SAppV (SBuiltin "primCompareInt") . sLit . LInt $ fromIntegral n 1773 litP s = flip ViewPat eqPP . SAppV (SBuiltin s) . sLit
1750 mkNatPat _ (si, n) = toNatP si n 1774 mkNatPat (Namespace (Just ExpLevel) _) (si, n) = litP "primCompareInt" . LInt $ fromIntegral n
1751 pConSI (PCon (_, n) ps) = PCon (sourceInfo ps, n) ps 1775 mkNatPat _ (si, n) = toNatP si n
1752 pConSI p = p 1776 pConSI (PCon (_, n) ps) = PCon (sourceInfo ps, n) ps
1777 pConSI p = p
1778
1779 patlist = commaSep $ parsePat PrecAnn
1780
1781longPattern = parsePat PrecAnn <&> (getPVars &&& id)
1782patternAtom = parsePat PrecAtom <&> (getPVars &&& id)
1783
1784telescopePat = fmap (getPPVars . ParPat . map snd &&& id) $ many $ uncurry f <$> hiddenTerm (parsePat PrecAtom) (parsePat PrecAtom)
1785 where
1786 f h (PatType (ParPat [p]) t) = ((h, t), p)
1787 f h p = ((h, Wildcard SType), p)
1753 1788
1754eqPP = ParPat [PCon (debugSI "eqPP", "EQ") []] 1789eqPP = ParPat [PCon (debugSI "eqPP", "EQ") []]
1755truePP = ParPat [PCon (debugSI "truePP", "True") []] 1790truePP = ParPat [PCon (debugSI "truePP", "True") []]
1756 1791
1757patlist ns = fmap snd $ commaSepUnfold (\vs -> (\(vs, p) t -> (vs, patType (dbPat vs p) t)) <$> pattern' ns <*> (dbf' vs <$> parseType ns (Just $ Wildcard SType))) mempty
1758
1759mkListPat ns [p] | namespaceLevel ns == Just TypeLevel = PCon (debugSI "mkListPat4", "'List") [ParPat [p]] 1792mkListPat ns [p] | namespaceLevel ns == Just TypeLevel = PCon (debugSI "mkListPat4", "'List") [ParPat [p]]
1760mkListPat ns (p: ps) = PCon (debugSI "mkListPat2", "Cons") $ map (ParPat . (:[])) [p, mkListPat ns ps] 1793mkListPat ns (p: ps) = PCon (debugSI "mkListPat2", "Cons") $ map (ParPat . (:[])) [p, mkListPat ns ps]
1761mkListPat _ [] = PCon (debugSI "mkListPat3", "Nil") [] 1794mkListPat _ [] = PCon (debugSI "mkListPat3", "Nil") []
1762 1795
1763mkTupPat :: Namespace -> [Pat] -> Pat 1796--mkTupPat :: [Pat] -> Pat
1764mkTupPat _ [x] = x 1797mkTupPat ns [x] = x
1765mkTupPat ns ps = PCon (debugSI "", tick' ns $ "Tuple" ++ show (length ps)) (ParPat . (:[]) <$> ps) 1798mkTupPat ns ps = PCon (debugSI "", tick' ns $ "Tuple" ++ show (length ps)) (ParPat . (:[]) <$> ps)
1766 1799
1767pattern' ns = pattern'_ ns <&> \p -> (getPVars p, p)
1768pattern'_ ns =
1769 PCon <$> (withSI $ upperCase ns) <*> patterns' ns
1770 <|> PCon <$> try (withSI (char '\'' *> upperCase (switchNS ns))) <*> patterns' ns
1771 <|> (patternAtom ns >>= \(vs, p) -> option p ((\op p' -> PCon (debugSI "pattern'","Cons") (ParPat . (:[]) <$> [p, p'])) <$> withSI conOperator <*> (dbPat vs <$> pattern'_ ns)))
1772
1773{-
1774 PrecOp -> asks calculatePrecs <*> p' where
1775 p' = ((\si (t, xs) -> (mkNat ns 0, (SBuiltin "-", t): xs)) `withRange` (reservedOp "-" *> p_))
1776 <|> p_
1777 p_ = (,) <$> parseTerm ns PrecApp <*> (option [] $ sVar operatorT >>= p)
1778 p op = do (exp, op') <- try ((,) <$> parseTerm ns PrecApp <*> sVar operatorT)
1779 ((op, exp):) <$> p op'
1780 <|> pure . (,) op <$> parseTerm ns PrecLam
1781-}
1782
1783dbPat v = mapP (dbf' v) 1800dbPat v = mapP (dbf' v)
1784 1801
1785pCon i (vs, x) = (vs, PCon i x) 1802pCon i (vs, x) = (vs, PCon i x)
1786 1803
1787patterns ns = patterns' ns <&> \p -> (foldMap getPPVars p, p)
1788patterns' ns = fmap snd $
1789 do patternAtom ns >>= \(vs, p) -> patterns ns >>= \(vs', ps) -> pure (vs' <> vs, ParPat [p]: map (mapPP $ dbf' vs) ps)
1790 <|> pure (mempty, [])
1791
1792patType p (Wildcard SType) = p 1804patType p (Wildcard SType) = p
1793patType p t = PatType (ParPat [p]) t 1805patType p t = PatType (ParPat [p]) t
1794 1806
1795checkPattern :: DBNames -> P () 1807checkPattern :: DBNames -> P ()
1796checkPattern (DBNamesC ns) = case filter (not . null . tail) . group . sort . filter ((`notElem` ["", "_"]) . snd) $ ns of 1808checkPattern ns = modify (ns:)
1797 [] -> return ()
1798 xs -> fail $ "multiple pattern vars:\n" ++ unlines [n ++ " is defined at " ++ showSIRange si | ns <- xs, (si, n) <- ns]
1799 1809
1800-- todo: eliminate 1810checkDBNames nss = case [ns' | ns <- nss
1801commaSepUnfold :: (t -> P (t, a)) -> t -> P (t, [a]) 1811 , ns' <- group . sort . filter ((`notElem` ["", "_"]) . snd) $ ns
1802commaSepUnfold p vs = commaSepUnfold1 p vs <|> pure (vs, []) 1812 , not . null . tail $ ns'] of
1803 where 1813 [] -> return ()
1804 commaSepUnfold1 :: (t -> P (t, a)) -> t -> P (t, [a]) 1814 xs -> throwErrorTCM $ text $ "multiple pattern vars:\n" ++ unlines [n ++ " is defined at " ++ showSIRange si | ns <- xs, (si, n) <- ns]
1805 commaSepUnfold1 p vs0 = do
1806 (vs1, x) <- p vs0
1807 (second (x:) <$ comma <*> commaSepUnfold1 p vs1) <|> pure (vs1, [x])
1808
1809telescopePat ns = go mempty where
1810 go vs = option (vs, []) $ do
1811 (vs', vt) <-
1812 reservedOp "@" *> (second (f Hidden . mapP (dbf' vs)) <$> patternAtom ns)
1813 <|> second (f Visible . mapP (dbf' vs)) <$> patternAtom ns
1814 (id *** (vt:)) <$> go (vs' <> vs)
1815 where
1816 f h (PatType (ParPat [p]) t) = ((h, t), p)
1817 f h p = ((h, Wildcard SType), p)
1818 1815
1819compileFunAlts' lend ge ds = fmap concat . sequence $ map (compileFunAlts False lend lend ge ds) $ groupBy h ds where 1816compileFunAlts' lend ge ds = fmap concat . sequence $ map (compileFunAlts False lend lend ge ds) $ groupBy h ds where
1820 h (FunAlt n _ _) (FunAlt m _ _) = m == n 1817 h (FunAlt n _ _) (FunAlt m _ _) = m == n
@@ -1865,107 +1862,105 @@ compileFunAlts par ulend lend ge ds = \case
1865compileGuardTrees False ulend lend ge alts = compileGuardTree ulend lend ge $ Alts alts 1862compileGuardTrees False ulend lend ge alts = compileGuardTree ulend lend ge $ Alts alts
1866compileGuardTrees True ulend lend ge alts = foldr1 SParEval $ compileGuardTree ulend lend ge <$> alts 1863compileGuardTrees True ulend lend ge alts = foldr1 SParEval $ compileGuardTree ulend lend ge <$> alts
1867 1864
1868parseDefs lend ns = join $ (asks $ \ge -> compileFunAlts' lend ge . concat) <*> many (parseDef ns) 1865parseDefs lend = join $ (asks $ \ge -> compileFunAlts' lend (fst ge) . concat) <*> many (parseDef)
1869 1866
1870parseDef :: Namespace -> P [Stmt] 1867parseDef :: P [Stmt]
1871parseDef ns = 1868parseDef =
1872 do reserved "data" 1869 do reserved "data"
1873 localIndentation Gt $ do 1870 localIndentation Gt $ do
1874 x <- withSI $ upperCase (typeNS ns) 1871 x <- withSI $ typeNS upperCase
1875 (npsd, ts) <- telescope (typeNS ns) (Just SType) 1872 (npsd, ts) <- telescope (Just SType)
1876 t <- dbf' npsd <$> parseType (typeNS ns) (Just SType) 1873 t <- dbf' npsd <$> parseType (Just SType)
1877 let mkConTy mk (nps', ts') = 1874 let mkConTy mk (nps', ts') =
1878 ( if mk then Just nps' else Nothing 1875 ( if mk then Just nps' else Nothing
1879 , foldr (uncurry SPi) (foldl SAppV (SGlobal x) $ downToS (length ts') $ length ts) ts') 1876 , foldr (uncurry SPi) (foldl SAppV (SGlobal x) $ downToS (length ts') $ length ts) ts')
1880 (af, cs) <- 1877 (af, cs) <- option (True, []) $
1881 do (,) True <$ reserved "where" <*> localIndentation Ge (localAbsoluteIndentation $ many $ 1878 do (,) True <$ reserved "where" <*> localIndentation Ge (localAbsoluteIndentation $ many $
1882 (id *** (,) Nothing . dbf' npsd) <$> typedIds ns Nothing) 1879 (id *** (,) Nothing . dbf' npsd) <$> typedIds Nothing)
1883 <|> do (,) False <$ reservedOp "=" <*> 1880 <|> do (,) False <$ reservedOp "=" <*>
1884 sepBy1 ((,) <$> (pure <$> withSI (upperCase ns)) 1881 sepBy1 ((,) <$> (pure <$> withSI upperCase)
1885 <*> ( braces (mkConTy True . (\(x, y) -> (x, zipWith (\i (v, e) -> (v, dbf_ i npsd e)) [0..] y)) <$> telescopeDataFields (typeNS ns)) 1882 <*> ( braces (mkConTy True . (id *** zipWith (\i (v, e) -> (v, dbf_ i npsd e)) [0..])
1886 <|> (mkConTy False . (\(x, y) -> (x, zipWith (\i (v, e) -> (v, dbf_ i npsd e)) [0..] y)) <$> telescopeSI (typeNS ns) Nothing)) ) 1883 <$> telescopeDataFields)
1887 (reservedOp "|") 1884 <|> (mkConTy False . (id *** zipWith (\i (v, e) -> (v, dbf_ i npsd e)) [0..]) . dbfi
1888 <|> pure (True, []) 1885 <$> many (telescopeSI Nothing))) )
1889 ge <- ask 1886 (reservedOp "|")
1887 ge <- asks fst
1890 return $ mkData ge x ts t af $ concatMap (\(vs, t) -> (,) <$> vs <*> pure t) $ cs 1888 return $ mkData ge x ts t af $ concatMap (\(vs, t) -> (,) <$> vs <*> pure t) $ cs
1891 <|> do reserved "class" 1889 <|> do reserved "class"
1892 localIndentation Gt $ do 1890 localIndentation Gt $ do
1893 x <- withSI $ upperCase (typeNS ns) 1891 x <- withSI $ typeNS upperCase
1894 (nps, ts) <- telescope (typeNS ns) (Just SType) 1892 (nps, ts) <- telescope (Just SType)
1895 cs <- 1893 cs <- option [] $ reserved "where" *> localIndentation Ge (localAbsoluteIndentation $ many $ typedIds Nothing)
1896 do reserved "where" *> localIndentation Ge (localAbsoluteIndentation $ many $ typedIds ns Nothing)
1897 <|> pure []
1898 return $ pure $ Class x (map snd ts) (concatMap (\(vs, t) -> (,) <$> vs <*> pure (dbf' nps t)) cs) 1894 return $ pure $ Class x (map snd ts) (concatMap (\(vs, t) -> (,) <$> vs <*> pure (dbf' nps t)) cs)
1899 <|> do reserved "instance" 1895 <|> do reserved "instance"
1900 let ns' = typeNS ns 1896 localIndentation Gt $ typeNS $ do
1901 localIndentation Gt $ do 1897 constraints <- option [] $ try "constraint" $ getTTuple' <$> parseTerm PrecEq <* reservedOp "=>"
1902 constraints <- option [] $ try $ getTTuple' <$> parseTerm ns' PrecEq <* reservedOp "=>" 1898 x <- withSI upperCase
1903 x <- withSI $ upperCase ns' 1899 (nps, args) <- telescopePat
1904 (nps, args) <- telescopePat ns'
1905 checkPattern nps 1900 checkPattern nps
1906 cs <- option [] $ reserved "where" *> localIndentation Ge (localAbsoluteIndentation $ some $ 1901 cs <- expNS $ option [] $ reserved "where" *> localIndentation Ge (localAbsoluteIndentation $ some $
1907 dbFunAlt nps <$> funAltDef (varId ns) ns) 1902 dbFunAlt nps <$> funAltDef varId)
1908 <|> pure [] 1903 ge <- asks fst
1909 ge <- ask 1904 pure . Instance x ({-todo-}map snd args) (dbff (nps <> [x]) <$> constraints) <$> compileFunAlts' id{-TODO-} ge cs
1910 pure . Instance x ({-todo-}map snd args) (dbff (diffDBNames nps ++ [snd x]) <$> constraints) <$> compileFunAlts' id{-TODO-} ge cs 1905 <|> do try "type family" (reserved "type" >> reserved "family")
1911 <|> do try (reserved "type" >> reserved "family") 1906 localIndentation Gt $ typeNS $ do
1912 let ns' = typeNS ns 1907 x <- withSI upperCase
1913 localIndentation Gt $ do 1908 (nps, ts) <- telescope (Just SType)
1914 x <- withSI $ upperCase ns' 1909 t <- dbf' nps <$> parseType (Just SType)
1915 (nps, ts) <- telescope ns' (Just SType)
1916 t <- dbf' nps <$> parseType ns' (Just SType)
1917 option {-open type family-}[TypeFamily x ts t] $ do 1910 option {-open type family-}[TypeFamily x ts t] $ do
1918 cs <- reserved "where" *> localIndentation Ge (localAbsoluteIndentation $ many $ 1911 cs <- reserved "where" *> localIndentation Ge (localAbsoluteIndentation $ many $
1919 funAltDef (upperCase ns' >>= \x' -> guard (snd x == x') >> return x') ns') 1912 funAltDef (upperCase >>= \x' -> guard (snd x == x') >> return x'))
1920 ge <- ask 1913 ge <- asks fst
1921 -- closed type family desugared here 1914 -- closed type family desugared here
1922 compileFunAlts False id SLabelEnd ge [TypeAnn x $ addParamsS ts t] cs 1915 compileFunAlts False id SLabelEnd ge [TypeAnn x $ addParamsS ts t] cs
1923 <|> do reserved "type" 1916 <|> do reserved "type"
1924 let ns' = typeNS ns 1917 localIndentation Gt $ typeNS $ do
1925 localIndentation Gt $ do 1918 x <- withSI upperCase
1926 x <- withSI $ upperCase ns' 1919 (nps, ts) <- dbfi <$> many (telescopeSI $ Just (Wildcard SType))
1927 (nps, ts) <- telescopeSI ns' (Just (Wildcard SType))
1928 reservedOp "=" 1920 reservedOp "="
1929 rhs <- dbf' (DBNamesC nps) <$> parseTerm ns' PrecLam 1921 rhs <- dbf' nps <$> parseTerm PrecLam
1930 ge <- ask 1922 ge <- asks fst
1931 compileFunAlts False id SLabelEnd ge 1923 compileFunAlts False id SLabelEnd ge
1932 [{-TypeAnn x $ addParamsS ts $ SType-}{-todo-}] 1924 [{-TypeAnn x $ addParamsS ts $ SType-}{-todo-}]
1933 [FunAlt x (reverse $ zip (reverse ts) $ map PVar nps) $ Right rhs] 1925 [FunAlt x (reverse $ zip (reverse ts) $ map PVar nps) $ Right rhs]
1934 <|> do try (reserved "type" >> reserved "instance") 1926 <|> do try "type instance" (reserved "type" >> reserved "instance")
1935 let ns' = typeNS ns 1927 typeNS $ pure <$> localIndentation Gt (funAltDef upperCase)
1936 pure <$> localIndentation Gt (funAltDef (upperCase ns') ns') 1928 <|> do (vs, t) <- try "typed ident" $ typedIds Nothing
1937 <|> do (vs, t) <- try $ typedIds ns Nothing
1938 return $ TypeAnn <$> vs <*> pure t 1929 return $ TypeAnn <$> vs <*> pure t
1939 <|> fixityDef 1930 <|> fixityDef
1940 <|> pure <$> funAltDef (varId ns) ns 1931 <|> pure <$> funAltDef varId
1941 <|> pure . uncurry ValueDef <$> valueDef ns 1932 <|> pure <$> valueDef
1942 1933
1943funAltDef parseName ns = do -- todo: use ns to determine parseName 1934funAltDef parseName = do -- todo: use ns to determine parseName
1944 (n, (fee, tss)) <- 1935 (n, (fee, tss)) <-
1945 do try' "operator definition" $ do 1936 do try "operator definition" $ do
1946 (e', a1) <- patternAtom ns 1937 (e', a1) <- patternAtom
1947 localIndentation Gt $ do 1938 localIndentation Gt $ do
1948 n <- withSI operatorT 1939 n <- withSI (symbols <|> backquotedIdent)
1949 (e'', a2) <- patternAtom ns 1940 (e'', a2) <- patternAtom
1950 lookAhead $ reservedOp "=" <|> reservedOp "|" 1941 lookAhead $ reservedOp "=" <|> reservedOp "|"
1951 let ps = e'' <> e' 1942 let ps = e'' <> e'
1952 checkPattern ps 1943 checkPattern ps
1953 return (n, (ps, (,) (Visible, Wildcard SType) <$> [a1, mapP (dbf' e') a2])) 1944 return (n, (ps, (,) (Visible, Wildcard SType) <$> [a1, mapP (dbf' e') a2]))
1954 <|> do try $ do 1945 <|> do try "lhs" $ do
1955 n <- withSI parseName 1946 n <- withSI parseName
1956 localIndentation Gt $ (,) n <$> (telescopePat ns >>= \ps -> checkPattern (fst ps) >> return ps) <* (lookAhead $ reservedOp "=" <|> reservedOp "|") 1947 localIndentation Gt $ (,) n <$> (telescopePat >>= \ps -> checkPattern (fst ps) >> return ps) <* (lookAhead $ reservedOp "=" <|> reservedOp "|")
1957 let fe = dbf' $ fee <> addDBName n 1948 let fe = dbf' $ fee <> addDBName n
1958 ts = map (id *** upP 0 1{-todo: replace n with Var 0-}) tss 1949 ts = map (id *** upP 0 1{-todo: replace n with Var 0-}) tss
1959 FunAlt n ts <$> parseRHS ns fe "=" 1950 FunAlt n ts <$> parseRHS fe "="
1960 1951
1961parseRHS ns fe tok = localIndentation Gt $ do 1952parseRHS fe tok = localIndentation Gt $ do
1962 gs <- some $ (,) <$ reservedOp "|" <*> parseTerm ns PrecOp <* reservedOp tok <*> parseTerm ns PrecLam 1953 gs <- some $ (,) <$ reservedOp "|" <*> parseTerm PrecOp <* reservedOp tok <*> parseTerm PrecLam
1963-- f <- parseWhereBlock ns -- todo: where + guards 1954-- f <- parseWhereBlock -- todo: where + guards
1964 return $ Left $ fmap (fe *** fe) gs 1955 return $ Left $ fmap (fe *** fe) gs
1965 <|> do 1956 <|> do
1966 reservedOp tok 1957 reservedOp tok
1967 rhs <- parseTerm ns PrecLam 1958 rhs <- parseTerm PrecLam
1968 f <- parseWhereBlock ns 1959 f <- option id $ do
1960 reserved "where"
1961 dcls <- localIndentation Ge (localAbsoluteIndentation $ parseDefs xSLabelEnd)
1962 ge <- asks fst
1963 return $ mkLets True ge dcls
1969 return $ Right $ (fe . f) rhs 1964 return $ Right $ (fe . f) rhs
1970 1965
1971dbFunAlt v (FunAlt n ts gue) = FunAlt n (map (id *** mapP (dbf' v)) ts) $ fmap (dbf' v *** dbf' v) +++ dbf' v $ gue 1966dbFunAlt v (FunAlt n ts gue) = FunAlt n (map (id *** mapP (dbf' v)) ts) $ fmap (dbf' v *** dbf' v) +++ dbf' v $ gue
@@ -1978,113 +1973,98 @@ mkData ge x ts t af cs = [Data x ts t af $ (id *** snd) <$> cs] ++ concatMap mkP
1978 | (i, fn) <- zip [0..] fs] 1973 | (i, fn) <- zip [0..] fs]
1979 mkProj _ = [] 1974 mkProj _ = []
1980 1975
1981parseWhereBlock ns = option id $ do 1976type DBNames = [SIName] -- De Bruijn variable names
1982 reserved "where"
1983 dcls <- localIndentation Ge (localAbsoluteIndentation $ parseDefs id ns)
1984 ge <- ask
1985 return $ mkLets ge dcls
1986
1987newtype DBNames = DBNamesC [SIName] -- De Bruijn variable names
1988instance Show DBNames where show (DBNamesC x) = show $ map snd x
1989instance Monoid DBNames where mempty = DBNamesC []
1990 mappend (DBNamesC a) (DBNamesC b) = DBNamesC (a ++ b)
1991 1977
1992addDBName n = DBNamesC [n] 1978addDBName n = [n]
1993diffDBNames (DBNamesC xs) = map snd xs
1994 1979
1995sVar = withRange $ curry SGlobal 1980sVar = withRange $ curry SGlobal
1996 1981
1997valueDef :: Namespace -> P (([SIName], Pat), SExp) 1982valueDef :: P Stmt
1998valueDef ns = do 1983valueDef = do
1999 (dns@(DBNamesC e'), p) <- try $ pattern' ns <* reservedOp "=" 1984 (dns, p) <- try "pattern" $ longPattern <* reservedOp "="
2000 checkPattern dns 1985 checkPattern dns
2001 localIndentation Gt $ do 1986 localIndentation Gt $ ValueDef p <$> parseETerm PrecLam
2002 ex <- parseETerm ns PrecLam
2003 return ((e', p), ex)
2004 1987
2005parseTTerm ns = parseTerm $ typeNS ns 1988parseTTerm = typeNS . parseTerm
2006parseETerm ns = parseTerm $ expNS ns 1989parseETerm = expNS . parseTerm
2007 1990
2008parseTerm :: Namespace -> Prec -> P SExp 1991parseTerm :: Prec -> P SExp
2009parseTerm ns prec = withRange setSI $ case prec of 1992parseTerm prec = withRange setSI $ case prec of
2010 PrecLam -> 1993 PrecLam ->
2011 mkIf <$ reserved "if" <*> parseTerm ns PrecLam <* reserved "then" <*> parseTerm ns PrecLam <* reserved "else" <*> parseTerm ns PrecLam 1994 mkIf <$ reserved "if" <*> parseTerm PrecLam <* reserved "then" <*> parseTerm PrecLam <* reserved "else" <*> parseTerm PrecLam
2012 <|> do (tok, ns) <- (SPi . const Hidden <$ reservedOp "." <|> SPi . const Visible <$ reservedOp "->", typeNS ns) <$ reserved "forall" 1995 <|> do reserved "forall"
2013 (fe, ts) <- telescope ns (Just $ Wildcard SType) 1996 (fe, ts) <- telescope (Just $ Wildcard SType)
2014 f <- tok 1997 f <- SPi . const Hidden <$ reservedOp "." <|> SPi . const Visible <$ reservedOp "->"
2015 t' <- dbf' fe <$> parseTerm ns PrecLam 1998 t' <- dbf' fe <$> parseTTerm PrecLam
2016 return $ foldr (uncurry f) t' ts 1999 return $ foldr (uncurry f) t' ts
2017 <|> do 2000 <|> do expNS $ do
2018 reservedOp "\\" 2001 reservedOp "\\"
2019 let ns' = expNS ns 2002 (fe, ts) <- telescopePat
2020 (fe, ts) <- telescopePat ns' 2003 checkPattern fe
2021 checkPattern fe 2004 reservedOp "->"
2022 reservedOp "->" 2005 t' <- dbf' fe <$> parseTerm PrecLam
2023 t' <- dbf' fe <$> parseTerm ns' PrecLam 2006 ge <- asks fst
2024 ge <- ask 2007 return $ foldr (uncurry (patLam_ id ge)) t' ts
2025 return $ foldr (uncurry (patLam_ id ge)) t' ts 2008 <|> do asks (compileCase . fst) <* reserved "case" <*> parseETerm PrecLam
2026 <|> do asks compileCase <* reserved "case" <*> parseETerm ns PrecLam
2027 <* reserved "of" <*> localIndentation Ge (localAbsoluteIndentation $ some $ do 2009 <* reserved "of" <*> localIndentation Ge (localAbsoluteIndentation $ some $ do
2028 (fe, p) <- pattern' ns 2010 (fe, p) <- longPattern
2029 (,) p <$> parseRHS ns (dbf' fe) "->" 2011 (,) p <$> parseRHS (dbf' fe) "->"
2030 ) 2012 )
2031 <|> do (asks $ \ge -> compileGuardTree id id ge . Alts) <*> parseSomeGuards ns (const True) 2013 <|> do (asks $ \ge -> compileGuardTree id id (fst ge) . Alts) <*> parseSomeGuards (const True)
2032 <|> do t <- parseTerm ns PrecEq 2014 <|> do t <- parseTerm PrecEq
2033 option t $ mkPi <$> (Visible <$ reservedOp "->" <|> Hidden <$ reservedOp "=>") <*> pure t <*> parseTTerm ns PrecLam 2015 option t $ mkPi <$> (Visible <$ reservedOp "->" <|> Hidden <$ reservedOp "=>") <*> pure t <*> parseTTerm PrecLam
2034 PrecEq -> parseTerm ns PrecAnn >>= \t -> option t $ SCstr t <$ reservedOp "~" <*> parseTTerm ns PrecAnn 2016 PrecEq -> parseTerm PrecAnn >>= \t -> option t $ SCstr t <$ reservedOp "~" <*> parseTTerm PrecAnn
2035 PrecAnn -> parseTerm ns PrecOp >>= \t -> option t $ SAnn t <$> parseType ns Nothing 2017 PrecAnn -> parseTerm PrecOp >>= \t -> option t $ SAnn t <$> parseType Nothing
2036 PrecOp -> asks calculatePrecs <*> p' where 2018 PrecOp -> asks (calculatePrecs . fst) <*> p' where
2037 p' = ((\si (t, xs) -> (mkNat ns 0, (SBuiltin "-", t): xs)) `withRange` (reservedOp "-" *> p_)) 2019 p' = (getNS $ \ns -> (\si (t, xs) -> (mkNat ns 0, (SBuiltin "-", t): xs)) `withRange` (reservedOp "-" *> p_))
2038 <|> p_ 2020 <|> p_
2039 p_ = (,) <$> parseTerm ns PrecApp <*> (option [] $ sVar operatorT >>= p) 2021 p_ = (,) <$> parseTerm PrecApp <*> (option [] $ sVar operatorT >>= p)
2040 p op = do (exp, op') <- try ((,) <$> parseTerm ns PrecApp <*> sVar operatorT) 2022 p op = do (exp, op') <- try "expression" ((,) <$> parseTerm PrecApp <*> sVar operatorT)
2041 ((op, exp):) <$> p op' 2023 ((op, exp):) <$> p op'
2042 <|> pure . (,) op <$> parseTerm ns PrecLam 2024 <|> pure . (,) op <$> parseTerm PrecLam
2043 PrecApp -> 2025 PrecApp ->
2044 try {- TODO: adjust try for better error messages e.g. don't use braces -} 2026 try "" {- TODO: adjust try for better error messages e.g. don't use braces -}
2045 (apps' <$> sVar (upperCase ns) <*> braces (commaSep $ lowerCase ns *> reservedOp "=" *> ((,) Visible <$> parseTerm ns PrecLam))) <|> 2027 (apps' <$> sVar upperCase <*> braces (commaSep $ lowerCase *> reservedOp "=" *> ((,) Visible <$> parseTerm PrecLam)))
2046 (apps' <$> parseTerm ns PrecSwiz <*> many 2028 <|> apps' <$> parseTerm PrecSwiz <*> many (hiddenTerm (parseTTerm PrecSwiz) $ parseTerm PrecSwiz)
2047 ( (,) Visible <$> parseTerm ns PrecSwiz
2048 <|> (,) Hidden <$ reservedOp "@" <*> parseTTerm ns PrecSwiz))
2049 PrecSwiz -> do 2029 PrecSwiz -> do
2050 t <- parseTerm ns PrecProj 2030 t <- parseTerm PrecProj
2051 try (mkSwizzling t `withRange` (lexeme $ char '%' *> manyNM 1 4 (satisfy (`elem` ("xyzwrgba" :: [Char]))))) <|> pure t 2031 option t $ mkSwizzling t <$> try "swizzling" (lexeme $ char '%' *> manyNM 1 4 (satisfy (`elem` ("xyzwrgba" :: [Char]))))
2052 PrecProj -> do 2032 PrecProj -> do
2053 t <- parseTerm ns PrecAtom 2033 t <- parseTerm PrecAtom
2054 try (mkProjection t <$ char '.' <*> (sepBy1 (sLit . LString <$> lowerCase ns) (char '.'))) <|> pure t 2034 option t $ try "projection" $ mkProjection t <$ char '.' <*> (sepBy1 (sLit . LString <$> lowerCase) (char '.'))
2055 PrecAtom -> 2035 PrecAtom ->
2056 sLit . LChar <$> try charLiteral 2036 sLit . LChar <$> try "char literal" charLiteral
2057 <|> sLit . LString <$> stringLiteral 2037 <|> sLit . LString <$> stringLiteral
2058 <|> sLit . LFloat <$> try float 2038 <|> sLit . LFloat <$> try "float literal" float
2059 <|> sLit . LInt . fromIntegral <$ char '#' <*> natural 2039 <|> sLit . LInt . fromIntegral <$ char '#' <*> natural
2060 <|> mkNat ns <$> natural 2040 <|> getNS' mkNat <*> natural
2061 <|> Wildcard (Wildcard SType) <$ reserved "_" 2041 <|> Wildcard (Wildcard SType) <$ reserved "_"
2062 <|> char '\'' *> parseTerm (switchNS ns) PrecAtom 2042 <|> char '\'' *> switchNS (parseTerm PrecAtom)
2063 <|> sVar (try (varId ns) <|> upperCase ns) 2043 <|> sVar (try "identifier" varId <|> upperCase)
2064 <|> mkDotDot <$> try (reservedOp "[" *> parseTerm ns PrecLam <* reservedOp ".." ) <*> parseTerm ns PrecLam <* reservedOp "]" 2044 <|> mkDotDot <$> try "dotdot expression" (reservedOp "[" *> parseTerm PrecLam <* reservedOp ".." ) <*> parseTerm PrecLam <* reservedOp "]"
2065 <|> listCompr ns 2045 <|> listCompr
2066 <|> mkList ns <$> brackets (commaSep $ parseTerm ns PrecLam) 2046 <|> getNS' mkList <*> brackets (commaSep $ parseTerm PrecLam)
2067 <|> mkLeftSection <$> try{-todo: better try-} (parens $ (,) <$> withSI (guardM (/= "-") operatorT) <*> parseTerm ns PrecLam) 2047 <|> mkLeftSection <$> try "left section"{-todo: better try-} (parens $ (,) <$> withSI (guardM (/= "-") operatorT) <*> parseTerm PrecLam)
2068 <|> mkRightSection <$> try{-todo: better try!-} (parens $ (,) <$> parseTerm ns PrecApp <*> withSI operatorT) 2048 <|> mkRightSection <$> try "right section"{-todo: better try!-} (parens $ (,) <$> parseTerm PrecApp <*> withSI operatorT)
2069 <|> mkTuple ns <$> parens (commaSep $ parseTerm ns PrecLam) 2049 <|> getNS' mkTuple <*> parens (commaSep $ parseTerm PrecLam)
2070 <|> mkRecord <$> braces (commaSep $ ((,) <$> lowerCase ns <* colon <*> parseTerm ns PrecLam)) 2050 <|> mkRecord <$> braces (commaSep $ ((,) <$> lowerCase <* colon <*> parseTerm PrecLam))
2071 <|> do reserved "let" 2051 <|> do reserved "let"
2072 dcls <- localIndentation Ge (localAbsoluteIndentation $ parseDefs id ns) 2052 dcls <- localIndentation Ge (localAbsoluteIndentation $ parseDefs xSLabelEnd)
2073 ge <- ask 2053 ge <- asks fst
2074 mkLets ge dcls <$ reserved "in" <*> parseTerm ns PrecLam 2054 mkLets True ge dcls <$ reserved "in" <*> parseTerm PrecLam
2075 2055
2076guardM p m = m >>= \x -> if p x then return x else fail "guardM" 2056guardM p m = m >>= \x -> if p x then return x else fail "guardM"
2077 2057
2078mkLeftSection (op, e) = SLam Visible (Wildcard SType) $ SGlobal op `SAppV` SVar (noSI, ".ls") 0 `SAppV` upS e 2058mkLeftSection (op, e) = SLam Visible (Wildcard SType) $ SGlobal op `SAppV` SVar (noSI, ".ls") 0 `SAppV` upS e
2079mkRightSection (e, op) = SLam Visible (Wildcard SType) $ SGlobal op `SAppV` upS e `SAppV` SVar (noSI, ".rs") 0 2059mkRightSection (e, op) = SLam Visible (Wildcard SType) $ SGlobal op `SAppV` upS e `SAppV` SVar (noSI, ".rs") 0
2080 2060
2081mkSwizzling term si = swizzcall 2061mkSwizzling term = swizzcall
2082 where 2062 where
2083 sc c = SGlobal (si,'S':c:[]) 2063 sc c = SBuiltin $ 'S':c:[]
2084 swizzcall [x] = SBuiltin "swizzscalar" `SAppV` term `SAppV` (sc . synonym) x 2064 swizzcall [x] = SBuiltin "swizzscalar" `SAppV` term `SAppV` (sc . synonym) x
2085 swizzcall xs = SBuiltin "swizzvector" `SAppV` term `SAppV` swizzparam xs 2065 swizzcall xs = SBuiltin "swizzvector" `SAppV` term `SAppV` swizzparam xs
2086 swizzparam xs = foldl (\exp s -> exp `SAppV` s) (vec xs) $ map (sc . synonym) xs 2066 swizzparam xs = foldl (\exp s -> exp `SAppV` s) (vec xs) $ map (sc . synonym) xs
2087 vec xs = SGlobal $ (,) si $ case length xs of 2067 vec xs = SBuiltin $ case length xs of
2088 0 -> error "impossible: swizzling parsing returned empty pattern" 2068 0 -> error "impossible: swizzling parsing returned empty pattern"
2089 1 -> error "impossible: swizzling went to vector for one scalar" 2069 1 -> error "impossible: swizzling went to vector for one scalar"
2090 n -> "V" ++ show n 2070 n -> "V" ++ show n
@@ -2110,14 +2090,16 @@ mkRecord xs = SBuiltin "RecordCons" `SAppH` names `SAppV` values
2110 2090
2111mkTuple _ [x] = x 2091mkTuple _ [x] = x
2112mkTuple (Namespace level _) xs = foldl SAppV (SBuiltin (tuple ++ show (length xs))) xs 2092mkTuple (Namespace level _) xs = foldl SAppV (SBuiltin (tuple ++ show (length xs))) xs
2113 where tuple = levelElim "'Tuple" "Tuple" level 2093 where tuple = case level of
2114mkTuple _ xs = error "mkTuple" 2094 Just TypeLevel -> "'Tuple"
2095 Just ExpLevel -> "Tuple"
2096 _ -> error "mkTuple"
2115 2097
2116mkList (Namespace TypeLevel _) [x] = SBuiltin "'List" `SAppV` x 2098mkList (Namespace (Just TypeLevel) _) [x] = SBuiltin "'List" `SAppV` x
2117mkList (Namespace ExpLevel _) xs = foldr (\x l -> SBuiltin "Cons" `SAppV` x `SAppV` l) (SBuiltin "Nil") xs 2099mkList (Namespace (Just ExpLevel) _) xs = foldr (\x l -> SBuiltin "Cons" `SAppV` x `SAppV` l) (SBuiltin "Nil") xs
2118mkList _ xs = error "mkList" 2100mkList _ xs = error "mkList"
2119 2101
2120mkNat (Namespace ExpLevel _) n = SBuiltin "fromInt" `SAppV` sLit (LInt $ fromIntegral n) 2102mkNat (Namespace (Just ExpLevel) _) n = SBuiltin "fromInt" `SAppV` sLit (LInt $ fromIntegral n)
2121mkNat _ n = toNat n 2103mkNat _ n = toNat n
2122 2104
2123mkIf b t f = SBuiltin "primIfThenElse" `SAppV` b `SAppV` t `SAppV` f 2105mkIf b t f = SBuiltin "primIfThenElse" `SAppV` b `SAppV` t `SAppV` f
@@ -2133,43 +2115,28 @@ manyNM n m p = do
2133 2115
2134-------------------------------------------------------------------------------- list comprehensions 2116-------------------------------------------------------------------------------- list comprehensions
2135 2117
2136generator, letdecl, boolExpression :: Namespace -> DBNames -> P (DBNames, SExp -> SExp) 2118listCompr :: P SExp
2137generator ns dbs = do 2119listCompr = foldr ($)
2138 (dbs', pat) <- try $ pattern' ns <* reservedOp "<-" 2120 <$> try "List comprehension" ((SBuiltin "singleton" `SAppV`) <$ reservedOp "[" <*> parseTerm PrecLam <* reservedOp "|")
2139 checkPattern dbs' 2121 <*> commaSep (generator <|> letdecl <|> boolExpression) <* reservedOp "]"
2140 exp <- dbf' dbs <$> parseTerm ns PrecLam 2122 where
2141 ge <- ask 2123 generator, letdecl, boolExpression :: P (SExp -> SExp)
2142 return $ (,) (dbs' <> dbs) $ \e -> application 2124 generator = do
2143 [ SBuiltin "concatMap" 2125 (dbs, pat) <- try "generator" $ longPattern <* reservedOp "<-"
2144 , SLamV $ compileGuardTree id id ge $ Alts 2126 checkPattern dbs
2145 [ compilePatts [(mapP (dbf' dbs) pat, 0)] $ Right e 2127 exp <- parseTerm PrecLam
2146 , GuardLeaf $ SBuiltin "Nil" 2128 ge <- asks fst
2147 ] 2129 return $ \e ->
2148 , exp 2130 SBuiltin "concatMap"
2149 ] 2131 `SAppV` SLamV (compileGuardTree id id ge $ Alts
2150 2132 [ compilePatts [(pat, 0)] $ Right $ dbff dbs e
2151letdecl ns dbs = ask >>= \ge -> reserved "let" *> ((\((dbs', p), e) -> (dbs, \exp -> mkLets ge [ValueDef (dbs', mapP (dbf' dbs) p) $ dbf' dbs e] exp)) <$> valueDef ns) 2133 , GuardLeaf $ SBuiltin "Nil"
2152 2134 ])
2153boolExpression ns dbs = do 2135 `SAppV` exp
2154 pred <- dbf' dbs <$> parseTerm ns PrecLam 2136
2155 return (dbs, \e -> application [SBuiltin "primIfThenElse", pred, e, SBuiltin "Nil"]) 2137 letdecl = asks (\(ge, _) x -> mkLets False ge [x]) <* reserved "let" <*> valueDef
2156 2138
2157application = foldl1 SAppV 2139 boolExpression = (\pred e -> SBuiltin "primIfThenElse" `SAppV` pred `SAppV` e `SAppV` SBuiltin "Nil") <$> parseTerm PrecLam
2158
2159listCompr :: Namespace -> P SExp
2160listCompr ns = (\e (dbs', fs) -> foldr ($) (dbff (diffDBNames dbs') e) fs)
2161 <$> try' "List comprehension" ((SBuiltin "singleton" `SAppV`) <$ reservedOp "[" <*> parseTerm ns PrecLam <* reservedOp "|")
2162 <*> commaSepUnfold (liftA2 (<|>) (generator ns) $ liftA2 (<|>) (letdecl ns) (boolExpression ns)) mempty <* reservedOp "]"
2163
2164-- todo: make it more efficient
2165diffDBNames' xs ys = take (length xs - length ys) xs
2166
2167dbf' = dbf_ 0
2168dbf_ j (DBNamesC xs) e = foldl (\e (i, (si, n)) -> substSG n (\si -> SVar (si, n) i) e) e $ zip [j..] xs
2169
2170dbff :: [String] -> SExp -> SExp
2171dbff [] e = e
2172dbff (n: ns) e = substSG0 n $ dbff ns e
2173 2140
2174-------------------------------------------------------------------------------- 2141--------------------------------------------------------------------------------
2175 2142
@@ -2180,11 +2147,11 @@ calculatePrecs dcls (e, xs) = calcPrec (\op x y -> op `SAppV` x `SAppV` y) (getF
2180 gf (SGlobal (si, n)) = n 2147 gf (SGlobal (si, n)) = n
2181 gf (SVar (_, n) i) = n 2148 gf (SVar (_, n) i) = n
2182 2149
2150calculatePatPrecs :: GlobalEnv' -> (Pat, [(SIName, Pat)]) -> Pat
2183calculatePatPrecs _ (e, []) = e 2151calculatePatPrecs _ (e, []) = e
2184calculatePatPrecs dcls (e, xs) = calcPrec (\op x y -> op `SAppV` x `SAppV` y) (getFixity dcls . gf) e xs 2152calculatePatPrecs dcls (e, xs) = calcPrec (\op x y -> PCon op $ ParPat . (:[]) <$> [x, y]) gf e xs
2185 where 2153 where
2186 gf (SGlobal (si, n)) = n 2154 gf (si, n) = getFixity dcls n
2187 gf (SVar (_, n) i) = n
2188 2155
2189getFixity :: GlobalEnv' -> SName -> Fixity 2156getFixity :: GlobalEnv' -> SName -> Fixity
2190getFixity (fm, _) n = fromMaybe (InfixL, 9) $ Map.lookup n fm 2157getFixity (fm, _) n = fromMaybe (InfixL, 9) $ Map.lookup n fm
@@ -2224,11 +2191,11 @@ extractGlobalEnv' ge =
2224joinGlobalEnv' (fm, cm) (fm', cm') = (Map.union fm fm', Map.union cm cm') 2191joinGlobalEnv' (fm, cm) (fm', cm') = (Map.union fm fm', Map.union cm cm')
2225 2192
2226calcPrec 2193calcPrec
2227 :: (Show e) 2194 :: (Show e, Show f)
2228 => (e -> e -> e -> e) 2195 => (f -> e -> e -> e)
2229 -> (e -> Fixity) 2196 -> (f -> Fixity)
2230 -> e 2197 -> e
2231 -> [(e, e)] 2198 -> [(f, e)]
2232 -> e 2199 -> e
2233calcPrec app getFixity e es = compileOps [((Infix, -1), undefined, e)] es 2200calcPrec app getFixity e es = compileOps [((Infix, -1), undefined, e)] es
2234 where 2201 where
@@ -2251,6 +2218,8 @@ calcPrec app getFixity e es = compileOps [((Infix, -1), undefined, e)] es
2251 (InfixR, InfixR) -> Right GT 2218 (InfixR, InfixR) -> Right GT
2252 _ -> Left $ "fixity error:" ++ show (op, op') 2219 _ -> Left $ "fixity error:" ++ show (op, op')
2253 2220
2221---------------------------------------------------------------------
2222
2254mkPi Hidden (getTTuple' -> xs) b = foldr (sNonDepPi Hidden) b xs 2223mkPi Hidden (getTTuple' -> xs) b = foldr (sNonDepPi Hidden) b xs
2255mkPi h a b = sNonDepPi h a b 2224mkPi h a b = sNonDepPi h a b
2256 2225
@@ -2263,30 +2232,23 @@ getTTuple (SAppV (getTTuple -> Just (n, xs)) z) = Just (n, xs ++ [z]{-todo: eff-
2263getTTuple (SGlobal (si, s@(splitAt 6 -> ("'Tuple", reads -> [(n, "")])))) = Just (n :: Int, []) 2232getTTuple (SGlobal (si, s@(splitAt 6 -> ("'Tuple", reads -> [(n, "")])))) = Just (n :: Int, [])
2264getTTuple _ = Nothing 2233getTTuple _ = Nothing
2265 2234
2266mkLets :: GlobalEnv' -> [Stmt]{-where block-} -> SExp{-main expression-} -> SExp{-big let with lambdas; replaces global names with de bruijn indices-}
2267mkLets _ [] e = e
2268mkLets ge (Let n _ mt _ (downS 0 -> Just x): ds) e
2269 = SLet (maybe id (flip SAnn . addForalls {-todo-}[] []) mt x) (substSG0 (snd n) $ mkLets ge ds e)
2270mkLets ge (ValueDef (ns, p) x: ds) e = patLam id ge p (dbff (map snd ns) $ mkLets ge ds e) `SAppV` x -- (p = e; f) --> (\p -> f) e
2271mkLets _ (x: ds) e = error $ "mkLets: " ++ show x
2272
2273patLam f ge = patLam_ f ge (Visible, Wildcard SType) 2235patLam f ge = patLam_ f ge (Visible, Wildcard SType)
2274 2236
2275patLam_ :: (SExp -> SExp) -> GlobalEnv' -> (Visibility, SExp) -> Pat -> SExp -> SExp 2237patLam_ :: (SExp -> SExp) -> GlobalEnv' -> (Visibility, SExp) -> Pat -> SExp -> SExp
2276patLam_ f ge (v, t) p e = SLam v t $ compileGuardTree f f ge $ compilePatts [(p, 0)] $ Right e 2238patLam_ f ge (v, t) p e = SLam v t $ compileGuardTree f f ge $ compilePatts [(p, 0)] $ Right e
2277 2239
2278parseSomeGuards ns f = do 2240parseSomeGuards f = do
2279 pos <- sourceColumn <$> getPosition <* reservedOp "|" 2241 pos <- sourceColumn <$> getPosition <* reservedOp "|"
2280 guard $ f pos 2242 guard $ f pos
2281 (e', f) <- 2243 (e', f) <-
2282 do (e', PCon (_, p) vs) <- try $ pattern' ns <* reservedOp "<-" 2244 do (e', PCon (_, p) vs) <- try "pattern" $ longPattern <* reservedOp "<-"
2283 checkPattern e' 2245 checkPattern e'
2284 x <- parseETerm ns PrecEq 2246 x <- parseETerm PrecEq
2285 return (e', \gs' gs -> GuardNode x p vs (Alts gs'): gs) 2247 return (e', \gs' gs -> GuardNode x p vs (Alts gs'): gs)
2286 <|> do x <- parseETerm ns PrecEq 2248 <|> do x <- parseETerm PrecEq
2287 return (mempty, \gs' gs -> [GuardNode x "True" [] $ Alts gs', GuardNode x "False" [] $ Alts gs]) 2249 return (mempty, \gs' gs -> [GuardNode x "True" [] $ Alts gs', GuardNode x "False" [] $ Alts gs])
2288 f <$> ((map (dbfGT e') <$> parseSomeGuards ns (> pos)) <|> (:[]) . GuardLeaf <$ reservedOp "->" <*> (dbf' e' <$> parseETerm ns PrecLam)) 2250 f <$> ((map (dbfGT e') <$> parseSomeGuards (> pos)) <|> (:[]) . GuardLeaf <$ reservedOp "->" <*> (dbf' e' <$> parseETerm PrecLam))
2289 <*> (parseSomeGuards ns (== pos) <|> pure []) 2251 <*> option [] (parseSomeGuards (== pos))
2290 2252
2291toNat 0 = SBuiltin "Zero" 2253toNat 0 = SBuiltin "Zero"
2292toNat n | n > 0 = SAppV (SBuiltin "Succ") $ toNat (n-1) 2254toNat n | n > 0 = SAppV (SBuiltin "Succ") $ toNat (n-1)
@@ -2334,7 +2296,7 @@ instance SourceInfo SExp where
2334 SGlobal (si, _) -> si 2296 SGlobal (si, _) -> si
2335 SBind si _ (si', _) e1 e2 -> si 2297 SBind si _ (si', _) e1 e2 -> si
2336 SApp si _ e1 e2 -> si 2298 SApp si _ e1 e2 -> si
2337 SLet e1 e2 -> sourceInfo e1 <> sourceInfo e2 2299 SLet _ e1 e2 -> sourceInfo e1 <> sourceInfo e2
2338 SVar (si, _) _ -> si 2300 SVar (si, _) _ -> si
2339 STyped si _ -> si 2301 STyped si _ -> si
2340 2302
@@ -2345,7 +2307,7 @@ instance SetSourceInfo SExp where
2345 setSI si = \case 2307 setSI si = \case
2346 SBind _ a b c d -> SBind si a b c d 2308 SBind _ a b c d -> SBind si a b c d
2347 SApp _ a b c -> SApp si a b c 2309 SApp _ a b c -> SApp si a b c
2348 SLet a b -> SLet a b 2310 SLet le a b -> SLet le a b
2349 SVar (_, n) i -> SVar (si, n) i 2311 SVar (_, n) i -> SVar (si, n) i
2350 STyped _ t -> STyped si t 2312 STyped _ t -> STyped si t
2351 SGlobal (_, n) -> SGlobal (si, n) 2313 SGlobal (_, n) -> SGlobal (si, n)
@@ -2403,9 +2365,9 @@ varP = \case
2403 PatType pp e -> varPP pp 2365 PatType pp e -> varPP pp
2404 2366
2405getPVars :: Pat -> DBNames 2367getPVars :: Pat -> DBNames
2406getPVars = DBNamesC . reverse . getPVars_ 2368getPVars = reverse . getPVars_
2407 2369
2408getPPVars = DBNamesC . reverse . getPPVars_ 2370getPPVars = reverse . getPPVars_
2409 2371
2410getPVars_ = \case 2372getPVars_ = \case
2411 PVar n -> [n] 2373 PVar n -> [n]
@@ -2585,8 +2547,8 @@ envDoc x m = case x of
2585 EApp1 _ h ts b -> envDoc ts $ shApp h <$> m <*> sExpDoc b 2547 EApp1 _ h ts b -> envDoc ts $ shApp h <$> m <*> sExpDoc b
2586 EApp2 _ h (Lam Visible TType (Var 0)) ts -> envDoc ts $ shApp h (shAtom "tyType") <$> m 2548 EApp2 _ h (Lam Visible TType (Var 0)) ts -> envDoc ts $ shApp h (shAtom "tyType") <$> m
2587 EApp2 _ h a ts -> envDoc ts $ shApp h <$> expDoc a <*> m 2549 EApp2 _ h a ts -> envDoc ts $ shApp h <$> expDoc a <*> m
2588 ELet1 ts b -> envDoc ts $ shLet_ m (sExpDoc b) 2550 ELet1 _ ts b -> envDoc ts $ shLet_ m (sExpDoc b)
2589 ELet2 (x, _) ts -> envDoc ts $ shLet_ (expDoc x) m 2551 ELet2 _ (x, _) ts -> envDoc ts $ shLet_ (expDoc x) m
2590 EAssign i x ts -> envDoc ts $ shLet i (expDoc x) m 2552 EAssign i x ts -> envDoc ts $ shLet i (expDoc x) m
2591 CheckType t ts -> envDoc ts $ shAnn ":" False <$> m <*> expDoc t 2553 CheckType t ts -> envDoc ts $ shAnn ":" False <$> m <*> expDoc t
2592 CheckSame t ts -> envDoc ts $ shCstr <$> m <*> expDoc t 2554 CheckSame t ts -> envDoc ts $ shCstr <$> m <*> expDoc t
@@ -2624,7 +2586,7 @@ sExpDoc = \case
2624 SApp _ h a b -> shApp h <$> sExpDoc a <*> sExpDoc b 2586 SApp _ h a b -> shApp h <$> sExpDoc a <*> sExpDoc b
2625 Wildcard t -> shAnn ":" True (shAtom "_") <$> sExpDoc t 2587 Wildcard t -> shAnn ":" True (shAtom "_") <$> sExpDoc t
2626 SBind _ h _ a b -> join $ shLam (usedS 0 b) h <$> sExpDoc a <*> pure (sExpDoc b) 2588 SBind _ h _ a b -> join $ shLam (usedS 0 b) h <$> sExpDoc a <*> pure (sExpDoc b)
2627 SLet a b -> shLet_ (sExpDoc a) (sExpDoc b) 2589 SLet _ a b -> shLet_ (sExpDoc a) (sExpDoc b)
2628 STyped _ (e,t) -> expDoc e 2590 STyped _ (e,t) -> expDoc e
2629 SVar _ i -> expDoc (Var i) 2591 SVar _ i -> expDoc (Var i)
2630 2592
@@ -2785,8 +2747,10 @@ throwErrorTCM d = throwError $ ErrorMsg $ show d
2785 2747
2786inference_ :: PolyEnv -> ModuleR -> ErrorT (WriterT Infos Identity) PolyEnv 2748inference_ :: PolyEnv -> ModuleR -> ErrorT (WriterT Infos Identity) PolyEnv
2787inference_ (PolyEnv pe is) m = ff $ runWriter $ runExceptT $ mdo 2749inference_ (PolyEnv pe is) m = ff $ runWriter $ runExceptT $ mdo
2788 defs <- either (throwError . ErrorMsg) return $ definitions m $ mkGlobalEnv' defs `joinGlobalEnv'` extractGlobalEnv' pe 2750 let (x, dns) = definitions m $ mkGlobalEnv' defs `joinGlobalEnv'` extractGlobalEnv' pe
2789 mapExceptT (fmap $ ErrorMsg +++ snd) . flip runStateT (initEnv <> pe) . flip runReaderT (sourceCode m) . mapM_ (handleStmt $ extensions m) $ defs 2751 defs <- either (throwError . ErrorMsg) return x
2752 checkDBNames dns
2753 mapExceptT (fmap $ ErrorMsg +++ snd) . flip runStateT (initEnv <> pe) . flip runReaderT (extensions m, sourceCode m) . mapM_ (handleStmt defs) $ defs
2790 where 2754 where
2791 ff (Left e, is) = throwError e 2755 ff (Left e, is) = throwError e
2792 ff (Right ge, is) = do 2756 ff (Right ge, is) = do