summaryrefslogtreecommitdiff
path: root/src/LambdaCube
diff options
context:
space:
mode:
authorPéter Diviánszky <divipp@gmail.com>2016-02-18 18:34:47 +0100
committerPéter Diviánszky <divipp@gmail.com>2016-02-19 02:50:09 +0100
commit998ae8f884f4b1d4e092ebdf3a441b97b2cf05b7 (patch)
tree6ced17ee38fa78de69b05c8765288ecabe52fb6e /src/LambdaCube
parent27c8f3aeb2d13da0bec522ee8a8a98f534fa39e8 (diff)
tuples are heterogeneous lists
Diffstat (limited to 'src/LambdaCube')
-rw-r--r--src/LambdaCube/Compiler.hs12
-rw-r--r--src/LambdaCube/Compiler/CoreToIR.hs127
-rw-r--r--src/LambdaCube/Compiler/Infer.hs179
-rw-r--r--src/LambdaCube/Compiler/Lexer.hs3
-rw-r--r--src/LambdaCube/Compiler/Parser.hs75
5 files changed, 188 insertions, 208 deletions
diff --git a/src/LambdaCube/Compiler.hs b/src/LambdaCube/Compiler.hs
index fc9068cc..54013b74 100644
--- a/src/LambdaCube/Compiler.hs
+++ b/src/LambdaCube/Compiler.hs
@@ -28,7 +28,7 @@ import Data.List
28import Data.Function 28import Data.Function
29import Data.Map.Strict (Map) 29import Data.Map.Strict (Map)
30import qualified Data.Map.Strict as Map 30import qualified Data.Map.Strict as Map
31import Control.Monad.State 31import Control.Monad.State.Strict
32import Control.Monad.Reader 32import Control.Monad.Reader
33import Control.Monad.Writer 33import Control.Monad.Writer
34import Control.Monad.Except 34import Control.Monad.Except
@@ -47,7 +47,7 @@ import LambdaCube.IR as IR
47import LambdaCube.Compiler.Pretty hiding ((</>)) 47import LambdaCube.Compiler.Pretty hiding ((</>))
48import LambdaCube.Compiler.Parser (Module(..), Export(..), ImportItems (..), runDefParser, parseLC) 48import LambdaCube.Compiler.Parser (Module(..), Export(..), ImportItems (..), runDefParser, parseLC)
49import LambdaCube.Compiler.Lexer as Exported (Range(..)) 49import LambdaCube.Compiler.Lexer as Exported (Range(..))
50import LambdaCube.Compiler.Infer (PolyEnv(..), showError, joinPolyEnvs, filterPolyEnv, inference_, extractDesugarInfo) 50import LambdaCube.Compiler.Infer (PolyEnv(..), showError, joinPolyEnvs, filterPolyEnv, inference_)
51import LambdaCube.Compiler.Infer as Exported (Infos, listAllInfos, listTypeInfos, listTraceInfos, Exp, outputType, boolType, trueExp, unfixlabel) 51import LambdaCube.Compiler.Infer as Exported (Infos, listAllInfos, listTypeInfos, listTraceInfos, Exp, outputType, boolType, trueExp, unfixlabel)
52import LambdaCube.Compiler.CoreToIR 52import LambdaCube.Compiler.CoreToIR
53 53
@@ -148,20 +148,20 @@ loadModule imp mname_ = do
148 do 148 do
149 ms <- mapM loadModuleImports $ moduleImports e 149 ms <- mapM loadModuleImports $ moduleImports e
150 x' <- {-trace ("loading " ++ fname) $-} do 150 x' <- {-trace ("loading " ++ fname) $-} do
151 env@(PolyEnv ge _) <- joinPolyEnvs False ms 151 env@(PolyEnv ge _ ds) <- joinPolyEnvs False ms
152 defs <- MMT $ mapExceptT (return . runIdentity) $ runDefParser (extractDesugarInfo ge) $ definitions e 152 defs <- MMT $ mapExceptT (return . runIdentity) $ runDefParser ds $ definitions e
153 srcs <- gets $ Map.mapMaybe (either (const Nothing) (Just . snd)) 153 srcs <- gets $ Map.mapMaybe (either (const Nothing) (Just . snd))
154 x <- MMT $ mapExceptT (lift . lift . mapWriterT (return . first (left $ showError (Map.insert fname src srcs)) . runIdentity)) $ inference_ env (extensions e) defs 154 x <- MMT $ mapExceptT (lift . lift . mapWriterT (return . first (left $ showError (Map.insert fname src srcs)) . runIdentity)) $ inference_ env (extensions e) defs
155 case moduleExports e of 155 case moduleExports e of
156 Nothing -> return x 156 Nothing -> return x
157 Just es -> joinPolyEnvs False $ flip map es $ \exp -> case exp of 157 Just es -> joinPolyEnvs False $ flip map es $ \exp -> case exp of
158 ExportId (snd -> d) -> case Map.lookup d $ getPolyEnv x of 158 ExportId (snd -> d) -> case Map.lookup d $ getPolyEnv x of
159 Just def -> PolyEnv (Map.singleton d def) mempty 159 Just def -> PolyEnv (Map.singleton d def) mempty mempty{-TODO-}
160 Nothing -> error $ d ++ " is not defined" 160 Nothing -> error $ d ++ " is not defined"
161 ExportModule (snd -> m) | m == mname -> x 161 ExportModule (snd -> m) | m == mname -> x
162 ExportModule m -> case [ ms 162 ExportModule m -> case [ ms
163 | ((m', is), ms) <- zip (moduleImports e) ms, m' == m] of 163 | ((m', is), ms) <- zip (moduleImports e) ms, m' == m] of
164 [PolyEnv x infos] -> PolyEnv x mempty -- TODO 164 [PolyEnv x infos ds] -> PolyEnv x mempty{-TODO-} ds
165 [] -> error $ "empty export list: " ++ show (fname, m, map fst $ moduleImports e, mname) 165 [] -> error $ "empty export list: " ++ show (fname, m, map fst $ moduleImports e, mname)
166 _ -> error "export list: internal error" 166 _ -> error "export list: internal error"
167 modify $ Map.insert fname $ Right (x', src) 167 modify $ Map.insert fname $ Right (x', src)
diff --git a/src/LambdaCube/Compiler/CoreToIR.hs b/src/LambdaCube/Compiler/CoreToIR.hs
index de7a7720..8c759ea4 100644
--- a/src/LambdaCube/Compiler/CoreToIR.hs
+++ b/src/LambdaCube/Compiler/CoreToIR.hs
@@ -131,7 +131,7 @@ getCommands backend e = case e of
131 } 131 }
132 return (i, input) 132 return (i, input)
133 where 133 where
134 input = compAttribute attrs 134 input = compInputType'' attrs
135 mergeSlot a b = a 135 mergeSlot a b = a
136 { IR.slotUniforms = IR.slotUniforms a <> IR.slotUniforms b 136 { IR.slotUniforms = IR.slotUniforms a <> IR.slotUniforms b
137 , IR.slotStreams = IR.slotStreams a <> IR.slotStreams b 137 , IR.slotStreams = IR.slotStreams a <> IR.slotStreams b
@@ -202,12 +202,12 @@ getSemantics = compSemantics . frameBufferType . tyOf
202getFragFilter (A2 "map" (EtaPrim2 "filterFragment" p) x) = (Just p, x) 202getFragFilter (A2 "map" (EtaPrim2 "filterFragment" p) x) = (Just p, x)
203getFragFilter x = (Nothing, x) 203getFragFilter x = (Nothing, x)
204 204
205getVertexShader (A2 "map" (EtaPrim2 "mapPrimitive" f@(etaRed -> Just (_, o))) x) = ((Just f, tyOf o), x) 205getVertexShader (A2 "map" (EtaPrim2 "mapPrimitive" f@(etaReds -> Just (_, o))) x) = ((Just f, tyOf o), x)
206--getVertexShader (A2 "map" (EtaPrim2 "mapPrimitive" f) x) = error $ "gff: " ++ show (case f of ExpTV x _ _ -> x) --ppShow (mapVal unFunc' f) 206--getVertexShader (A2 "map" (EtaPrim2 "mapPrimitive" f) x) = error $ "gff: " ++ show (case f of ExpTV x _ _ -> x) --ppShow (mapVal unFunc' f)
207--getVertexShader x = error $ "gf: " ++ ppShow x 207--getVertexShader x = error $ "gf: " ++ ppShow x
208getVertexShader x = ((Nothing, getPrim' $ tyOf x), x) 208getVertexShader x = ((Nothing, getPrim' $ tyOf x), x)
209 209
210getFragmentShader (A2 "map" (EtaPrim2 "mapFragment" f@(etaRed -> Just (_, o))) x) = ((Just f, tyOf o), x) 210getFragmentShader (A2 "map" (EtaPrim2 "mapFragment" f@(etaReds -> Just (_, o))) x) = ((Just f, tyOf o), x)
211--getFragmentShader (A2 "map" (EtaPrim2 "mapFragment" f) x) = error $ "gff: " ++ ppShow f 211--getFragmentShader (A2 "map" (EtaPrim2 "mapFragment" f) x) = error $ "gff: " ++ ppShow f
212--getFragmentShader x = error $ "gf: " ++ ppShow x 212--getFragmentShader x = error $ "gf: " ++ ppShow x
213getFragmentShader x = ((Nothing, getPrim'' $ tyOf x), x) 213getFragmentShader x = ((Nothing, getPrim'' $ tyOf x), x)
@@ -222,10 +222,11 @@ compFrameBuffer = \case
222 A1 "ColorImage" a -> IR.ClearImage IR.Color $ compValue a 222 A1 "ColorImage" a -> IR.ClearImage IR.Color $ compValue a
223 x -> error $ "compFrameBuffer " ++ ppShow x 223 x -> error $ "compFrameBuffer " ++ ppShow x
224 224
225compSemantics = \case 225compSemantics = map compSemantic . compList
226 A2 "Cons" a b -> compSemantic a: compSemantics b 226
227 A0 "Nil" -> [] 227compList (A2 "Cons" a x) = a : compList x
228 x -> error $ "compSemantics: " ++ ppShow x 228compList (A0 "Nil") = []
229compList x = error $ "compList: " ++ ppShow x
229 230
230compSemantic = \case 231compSemantic = \case
231 A1 "Depth" _ -> IR.Depth 232 A1 "Depth" _ -> IR.Depth
@@ -371,24 +372,23 @@ compInputType_ x = case x of
371 TMat 4 2 TFloat -> Just IR.M42F 372 TMat 4 2 TFloat -> Just IR.M42F
372 TMat 4 3 TFloat -> Just IR.M43F 373 TMat 4 3 TFloat -> Just IR.M43F
373 TMat 4 4 TFloat -> Just IR.M44F 374 TMat 4 4 TFloat -> Just IR.M44F
375 -- hack
376 A1 "HList" (compList -> [x]) -> compInputType_ x
374 _ -> Nothing 377 _ -> Nothing
375 378
376compInputType msg x = fromMaybe (error $ "compInputType " ++ msg ++ " " ++ ppShow x) $ compInputType_ x 379compInputType msg x = fromMaybe (error $ "compInputType " ++ msg ++ " " ++ ppShow x) $ compInputType_ x
377 380
378is234 = (`elem` [2,3,4]) 381is234 = (`elem` [2,3,4])
379 382
383compInputType'' attrs@(A1 "Attribute" (EString s)) | A1 "HList" (compList -> [ty]) <- tyOf attrs = [(s, compInputType "cit" ty)]
384compInputType'' attrs = map compAttribute $ eTuple attrs
380 385
381compAttribute x = case x of 386compAttribute = \case
382 ETuple a -> concatMap compAttribute a 387 x@(A1 "Attribute" (EString s)) -> (s, compInputType "compAttr" $ tyOf x)
383 A1 "Attribute" (EString s) -> [(s, compInputType "compAttr" $ tyOf x)]
384 x -> error $ "compAttribute " ++ ppShow x 388 x -> error $ "compAttribute " ++ ppShow x
385 389
386compList (A2 "Cons" a x) = compValue a : compList x
387compList (A0 "Nil") = []
388compList x = error $ "compList: " ++ ppShow x
389
390compAttributeValue :: ExpTV -> [(IR.InputType,IR.ArrayValue)] 390compAttributeValue :: ExpTV -> [(IR.InputType,IR.ArrayValue)]
391compAttributeValue x = checkLength $ go x 391compAttributeValue x = checkLength $ map go $ eTuple x
392 where 392 where
393 emptyArray t | t `elem` [IR.Float,IR.V2F,IR.V3F,IR.V4F,IR.M22F,IR.M23F,IR.M24F,IR.M32F,IR.M33F,IR.M34F,IR.M42F,IR.M43F,IR.M44F] = IR.VFloatArray mempty 393 emptyArray t | t `elem` [IR.Float,IR.V2F,IR.V3F,IR.V4F,IR.M22F,IR.M23F,IR.M24F,IR.M32F,IR.M33F,IR.M34F,IR.M42F,IR.M43F,IR.M44F] = IR.VFloatArray mempty
394 emptyArray t | t `elem` [IR.Int,IR.V2I,IR.V3I,IR.V4I] = IR.VIntArray mempty 394 emptyArray t | t `elem` [IR.Int,IR.V2I,IR.V3I,IR.V4I] = IR.VIntArray mempty
@@ -406,12 +406,9 @@ compAttributeValue x = checkLength $ go x
406 True -> snd $ unzip l 406 True -> snd $ unzip l
407 False -> error "FetchArrays array length mismatch!" 407 False -> error "FetchArrays array length mismatch!"
408 408
409 go = \case 409 go a = (length values,(t,foldr (flatten t) (emptyArray t) values))
410 ETuple a -> concatMap go a 410 where (A1 "List" (compInputType "compAV" -> t)) = tyOf a
411 a -> let A1 "List" (compInputType "compAV" -> t) = tyOf a 411 values = map compValue $ compList a
412 values = compList a
413 in
414 [(length values,(t,foldr (flatten t) (emptyArray t) values))]
415 412
416compFetchPrimitive x = case x of 413compFetchPrimitive x = case x of
417 A0 "Point" -> IR.Points 414 A0 "Point" -> IR.Points
@@ -512,29 +509,38 @@ genGLSLs backend
512 shader $ 509 shader $
513 uniformDecls fragUniforms 510 uniformDecls fragUniforms
514 <> vertOutDecls "in" 511 <> vertOutDecls "in"
515 <> [shaderDecl "out" (toGLSLType "4" tfrag) fragColorName | noUnit tfrag, backend == OpenGL33] 512-- <> [shaderDecl "out" (toGLSLType "4" tfrag) fragColorName | Just{} <- [fragGLSL], backend == OpenGL33]
513 <> [shaderDecl "out" (text t) (text n) | (n, t) <- zip fragOutNames fragOuts, backend == OpenGL33]
516 <> fragFuncs 514 <> fragFuncs
517 <> [mainFunc $ 515 <> [mainFunc $
518 [shaderStmt $ "if" <+> parens ("!" <> parens filt) <+> "discard" | Just filt <- [filtGLSL]] 516 [shaderStmt $ "if" <+> parens ("!" <> parens filt) <+> "discard" | Just filt <- [filtGLSL]]
519 <> [shaderLet fragColorName $ fromMaybe (text $ head vertOutNames) fragGLSL | noUnit tfrag] 517 <> [shaderLet (text n) x | (n, x) <- zip fragOutNames fragGLSL ]
520 ] 518 ]
521 ) 519 )
522 where 520 where
523 uniformDecls us = [shaderDecl "uniform" (text $ showGLSLType "2" t) (text n) | (n, (_, t)) <- Map.toList us] 521 uniformDecls us = [shaderDecl "uniform" (text $ showGLSLType "2" t) (text n) | (n, (_, t)) <- Map.toList us]
524 vertOutDecls io = [shaderDecl (caseWO "varying" $ text i <+> io) (text t) (text n) | (n, (i, t)) <- zip vertOutNames vertOuts] 522 vertOutDecls io = [shaderDecl (caseWO "varying" $ text i <+> io) (text t) (text n) | (n, (i, t)) <- zip vertOutNames vertOuts]
525 523
524 fragOutNames = case length frags of
525 0 -> []
526 1 -> [caseWO (head vertOutNames) fragColorName]
527
526 (vertIns, verts) = case vert of 528 (vertIns, verts) = case vert of
527 Just (etaRed -> Just (vertIns, verts)) -> (toGLSLType "3" <$> vertIns, eTuple verts) 529 Just (etaReds -> Just (xs, ys)) -> (toGLSLType "3" <$> xs, eTuple ys)
528 Nothing -> ([], [mkTVar 0 tvert]) 530 Nothing -> ([toGLSLType "4" tvert], [mkTVar 0 tvert])
531
532 (fragOuts, frags) = case frag of
533 Just (etaReds -> Just (xs, eTuple -> ys)) -> (toGLSLType "3" . tyOf <$> ys, ys)
534 Nothing -> ([toGLSLType "4" tfrag], [mkTVar 0 tfrag])
529 535
530 (((vertGLSL, ptGLSL), (vertUniforms, vertFuncs)), ((filtGLSL, fragGLSL), (fragUniforms, fragFuncs))) = flip evalState shaderNames $ do 536 (((vertGLSL, ptGLSL), (vertUniforms, vertFuncs)), ((filtGLSL, fragGLSL), (fragUniforms, fragFuncs))) = flip evalState shaderNames $ do
531 ((g1, (us1, verts)), (g2, (us2, frags))) <- (,) 537 ((g1, (us1, verts)), (g2, (us2, frags))) <- (,)
532 <$> runWriterT ((,) 538 <$> runWriterT ((,)
533 <$> traverse (genGLSL' vertInNames . (,) vertIns) verts 539 <$> traverse (genGLSL' "1" vertInNames . (,) vertIns) verts
534 <*> traverse (genGLSL' vertOutNamesWithPosition . red) rp) 540 <*> traverse (genGLSL' "2" vertOutNamesWithPosition . reds) rp)
535 <*> runWriterT ((,) 541 <*> runWriterT ((,)
536 <$> traverse (genGLSL' vertOutNames . red) ffilter 542 <$> traverse (genGLSL' "3" vertOutNames . red) ffilter
537 <*> traverse (genGLSL' vertOutNames . red) frag) 543 <*> traverse (genGLSL' "4" vertOutNames . (,) (snd <$> vertOuts)) frags)
538 (,) <$> ((,) g1 <$> fixFuncs us1 mempty [] verts) <*> ((,) g2 <$> fixFuncs us2 mempty [] frags) 544 (,) <$> ((,) g1 <$> fixFuncs us1 mempty [] verts) <*> ((,) g2 <$> fixFuncs us2 mempty [] frags)
539 545
540 fixFuncs :: Uniforms -> Set.Set SName -> [Doc] -> Map.Map SName (ExpTV, ExpTV, [ExpTV]) -> State [SName] (Uniforms, [Doc]) 546 fixFuncs :: Uniforms -> Set.Set SName -> [Doc] -> Map.Map SName (ExpTV, ExpTV, [ExpTV]) -> State [SName] (Uniforms, [Doc])
@@ -558,11 +564,13 @@ genGLSLs backend
558 vertOutNames = map (("vo" ++) . show) [1..length vertOuts] 564 vertOutNames = map (("vo" ++) . show) [1..length vertOuts]
559 vertOutNamesWithPosition = "gl_Position": vertOutNames 565 vertOutNamesWithPosition = "gl_Position": vertOutNames
560 566
561 red (etaRed -> Just (ps, o)) = (ps, o) 567 red (etaReds -> Just (ps, o)) = (ps, o)
562 red x = error $ "red: " ++ ppShow x 568 red x = error $ "red: " ++ ppShow x
563 genGLSL' vertOuts (ps, o) 569 reds (etaReds -> Just (ps, o)) = (ps, o)
570 reds x = error $ "red: " ++ ppShow x
571 genGLSL' err vertOuts (ps, o)
564 | length ps == length vertOuts = genGLSL (reverse vertOuts) o 572 | length ps == length vertOuts = genGLSL (reverse vertOuts) o
565 | otherwise = error $ "makeSubst illegal input " ++ show ps ++ "\n" ++ show vertOuts 573 | otherwise = error $ "makeSubst illegal input " ++ err ++ " " ++ show ps ++ "\n" ++ show vertOuts
566 574
567 noUnit TTuple0 = False 575 noUnit TTuple0 = False
568 noUnit _ = True 576 noUnit _ = True
@@ -596,10 +604,6 @@ genGLSLs backend
596 604
597 caseWO w o = case backend of WebGL1 -> w; OpenGL33 -> o 605 caseWO w o = case backend of WebGL1 -> w; OpenGL33 -> o
598 606
599
600eTuple (ETuple l) = l
601eTuple x = [x]
602
603data Uniform 607data Uniform
604 = UUniform 608 = UUniform
605 | UTexture2DSlot 609 | UTexture2DSlot
@@ -753,7 +757,6 @@ genGLSL dns e = case e of
753 -- not supported 757 -- not supported
754 n | n `elem` ["primIntToWord", "primIntToFloat", "primCompareInt", "primCompareWord", "primCompareFloat"] -> error $ "WebGL 1 does not support: " ++ ppShow e 758 n | n `elem` ["primIntToWord", "primIntToFloat", "primCompareInt", "primCompareWord", "primCompareFloat"] -> error $ "WebGL 1 does not support: " ++ ppShow e
755 n | n `elem` ["M23F", "M24F", "M32F", "M34F", "M42F", "M43F"] -> error "WebGL 1 does not support matrices with this dimension" 759 n | n `elem` ["M23F", "M24F", "M32F", "M34F", "M42F", "M43F"] -> error "WebGL 1 does not support matrices with this dimension"
756 (tupName -> Just n) -> pure $ error "GLSL codegen for tuple is not supported yet"
757 x -> error $ "GLSL codegen - unsupported function: " ++ ppShow x 760 x -> error $ "GLSL codegen - unsupported function: " ++ ppShow x
758 761
759 x -> error $ "GLSL codegen - unsupported expression: " ++ ppShow x 762 x -> error $ "GLSL codegen - unsupported expression: " ++ ppShow x
@@ -907,18 +910,20 @@ removeLams 0 x = x
907removeLams i (ELam _ x) = removeLams (i-1) x 910removeLams i (ELam _ x) = removeLams (i-1) x
908removeLams i (Lam Hidden _ x) = removeLams i x 911removeLams i (Lam Hidden _ x) = removeLams i x
909 912
910etaRed (ELam _ (App (down 0 -> Just f) (EVar 0))) = etaRed f 913etaReds (ELam _ (App (down 0 -> Just f) (EVar 0))) = etaReds f
911etaRed (ELam _ (A3 (tupCaseName -> Just k) _ (down 0 -> Just x) (EVar 0))) = Just $ getPats k x 914etaReds (ELam _ (hlistLam -> x@Just{})) = x
912etaRed (ELam p i) = Just (getPVars p, i) 915etaReds (ELam p i) = Just ([p], i)
913--etaRed x | Pi Visible a b <- tyOf x = Just ([mkTVar 0 a], App x $ mkTVar 0 a) 916etaReds x = Nothing
914etaRed x = Nothing
915 917
916getPVars = \case 918hlistLam :: ExpTV -> Maybe ([ExpTV], ExpTV)
917 TTuple0 -> [] 919hlistLam (A3 "hlistNilCase" _ (down 0 -> Just x) (EVar 0)) = Just ([], x)
918 t -> [t] 920hlistLam (A3 "hlistConsCase" _ (down 0 -> Just (getPats 2 -> Just ([p, px], x))) (EVar 0)) = first (p:) <$> hlistLam x
921hlistLam _ = Nothing
919 922
920getPats 0 e = ([], e) 923getPats 0 e = Just ([], e)
921getPats i (ELam p e) = first (p:) $ getPats (i-1) e 924getPats i (ELam p e) = first (p:) <$> getPats (i-1) e
925getPats i (Lam Hidden p (down 0 -> Just e)) = getPats i e
926getPats i x = error $ "getPats: " ++ show i ++ " " ++ ppShow x
922 927
923pattern EtaPrim1 s <- (getEtaPrim -> Just (s, [])) 928pattern EtaPrim1 s <- (getEtaPrim -> Just (s, []))
924pattern EtaPrim2 s x <- (getEtaPrim -> Just (s, [x])) 929pattern EtaPrim2 s x <- (getEtaPrim -> Just (s, [x]))
@@ -936,14 +941,6 @@ getEtaPrim2 _ = Nothing
936initLast [] = Nothing 941initLast [] = Nothing
937initLast xs = Just (init xs, last xs) 942initLast xs = Just (init xs, last xs)
938 943
939tupCaseName "Tuple2Case" = Just 2
940tupCaseName "Tuple3Case" = Just 3
941tupCaseName "Tuple4Case" = Just 4
942tupCaseName "Tuple5Case" = Just 5
943tupCaseName "Tuple6Case" = Just 6
944tupCaseName "Tuple7Case" = Just 7
945tupCaseName _ = Nothing
946
947------------- 944-------------
948 945
949pattern EVar n <- Var n _ 946pattern EVar n <- Var n _
@@ -956,7 +953,7 @@ pattern A3 n a b c <- Con n [a, b, c]
956pattern A4 n a b c d <- Con n [a, b, c, d] 953pattern A4 n a b c d <- Con n [a, b, c, d]
957pattern A5 n a b c d e <- Con n [a, b, c, d, e] 954pattern A5 n a b c d e <- Con n [a, b, c, d, e]
958 955
959pattern TTuple0 <- A0 "Tuple0" 956pattern TTuple0 <- A1 "HList" (A0 "Nil")
960pattern TBool <- A0 "Bool" 957pattern TBool <- A0 "Bool"
961pattern TWord <- A0 "Word" 958pattern TWord <- A0 "Word"
962pattern TInt <- A0 "Int" 959pattern TInt <- A0 "Int"
@@ -976,16 +973,12 @@ fromNat _ = Nothing
976pattern TTuple xs <- ETuple xs 973pattern TTuple xs <- ETuple xs
977pattern ETuple xs <- (getTuple -> Just xs) 974pattern ETuple xs <- (getTuple -> Just xs)
978 975
979getTuple (Con (tupName -> Just n) xs) | length xs == n = Just xs 976eTuple (ETuple l) = l
980getTuple _ = Nothing 977eTuple x | A1 "HList" _ <- tyOf x = error $ "eTuple: " ++ ppShow x --[x]
978eTuple x = [x]
981 979
982tupName = \case 980getTuple (A1 "HList" l) = Just $ compList l
983 "Tuple0" -> Just 0 981getTuple (A0 "HNil") = Just []
984 "Tuple2" -> Just 2 982getTuple (A2 "HCons" x (getTuple -> Just xs)) = Just (x: xs)
985 "Tuple3" -> Just 3 983getTuple _ = Nothing
986 "Tuple4" -> Just 4
987 "Tuple5" -> Just 5
988 "Tuple6" -> Just 6
989 "Tuple7" -> Just 7
990 _ -> Nothing
991 984
diff --git a/src/LambdaCube/Compiler/Infer.hs b/src/LambdaCube/Compiler/Infer.hs
index 79a97a09..9afa8a36 100644
--- a/src/LambdaCube/Compiler/Infer.hs
+++ b/src/LambdaCube/Compiler/Infer.hs
@@ -28,7 +28,6 @@ module LambdaCube.Compiler.Infer
28 , nType, conType, neutType, neutType', appTy, mkConPars, makeCaseFunPars, makeCaseFunPars' 28 , nType, conType, neutType, neutType', appTy, mkConPars, makeCaseFunPars, makeCaseFunPars'
29 , MaxDB(..), unfixlabel 29 , MaxDB(..), unfixlabel
30 , ErrorMsg, showError 30 , ErrorMsg, showError
31 , extractDesugarInfo
32 ) where 31 ) where
33 32
34import Data.Monoid 33import Data.Monoid
@@ -165,20 +164,12 @@ pattern TFloat <- TTyCon0 "'Float" where TFloat = tTyCon0 "'Float" $ er
165pattern TString <- TTyCon0 "'String" where TString = tTyCon0 "'String" $ error "cs 6" 164pattern TString <- TTyCon0 "'String" where TString = tTyCon0 "'String" $ error "cs 6"
166pattern TChar <- TTyCon0 "'Char" where TChar = tTyCon0 "'Char" $ error "cs 7" 165pattern TChar <- TTyCon0 "'Char" where TChar = tTyCon0 "'Char" $ error "cs 7"
167pattern TOrdering <- TTyCon0 "'Ordering" where TOrdering = tTyCon0 "'Ordering" $ error "cs 8" 166pattern TOrdering <- TTyCon0 "'Ordering" where TOrdering = tTyCon0 "'Ordering" $ error "cs 8"
168pattern TOutput <- TTyCon0 "'Output" where TOutput = tTyCon0 "'Output" $ error "cs 9"
169pattern TTuple0 <- TTyCon0 "'Tuple0" where TTuple0 = tTyCon0 "'Tuple0" $ error "cs 10"
170pattern TVec a b <- TyConN "'VecS" {-(TType :~> TNat :~> TType)-} [b, a] 167pattern TVec a b <- TyConN "'VecS" {-(TType :~> TNat :~> TType)-} [b, a]
171--pattern TTuple2 a b = TTyCon "'Tuple2" (TType :~> TType :~> TType) [a, b] 168
172pattern TInterpolated a <- TyConN "'Interpolated" [a]
173tFloating t = error "tFloating" --TFun "'Floating" (TType :~> TType) [t]
174tInterpolated x = tTyCon "'Interpolated" (TType :~> TType) [x] [Pi Hidden TType $ Pi Hidden (tFloating $ Var 0) $ tInterpolated $ Var 1, error "cs 12'", error "cs 12''"]
175pattern TList a <- TyConN "'List" [a] where TList a = tTyCon "'List" (TType :~> TType) [a] $ error "cs 11"
176pattern Empty s <- TyCon (TyConName "'Empty" _ _ _ _) [EString s] where 169pattern Empty s <- TyCon (TyConName "'Empty" _ _ _ _) [EString s] where
177 Empty s = TyCon (TyConName "'Empty" (error "todo: inum2_") (TString :~> TType) (error "todo: tcn cons 3_") $ error "Empty") [EString s] 170 Empty s = TyCon (TyConName "'Empty" (error "todo: inum2_") (TString :~> TType) (error "todo: tcn cons 3_") $ error "Empty") [EString s]
178 171
179pattern TT <- ConN' _ _ where TT = Closed (tCon "TT" 0 Unit []) 172pattern TT <- ConN' _ _ where TT = Closed (tCon "TT" 0 Unit [])
180nil = (tCon_ 1 "Nil" 0 (Pi Hidden TType $ TList (Var 0)) [])
181cons a b = (tCon_ 1 "Cons" 1 (Pi Hidden TType $ Var 0 :~> TList (Var 1) :~> TList (Var 2)) [a, b])
182pattern Zero <- ConN "Zero" _ where Zero = Closed (tCon "Zero" 0 TNat []) 173pattern Zero <- ConN "Zero" _ where Zero = Closed (tCon "Zero" 0 TNat [])
183pattern Succ n <- ConN "Succ" (n:_) where Succ n = tCon "Succ" 1 (TNat :~> TNat) [n] 174pattern Succ n <- ConN "Succ" (n:_) where Succ n = tCon "Succ" 1 (TNat :~> TNat) [n]
184 175
@@ -197,8 +188,6 @@ pattern EBool a <- (getEBool -> Just a) where EBool = mkBool
197pattern ENat n <- (fromNatE -> Just n) where ENat = toNatE 188pattern ENat n <- (fromNatE -> Just n) where ENat = toNatE
198pattern ENat' n <- (fromNatE' -> Just n) 189pattern ENat' n <- (fromNatE' -> Just n)
199 190
200pattern NoTup <- (noTup -> True)
201
202toNatE :: Int -> Exp 191toNatE :: Int -> Exp
203toNatE 0 = Zero 192toNatE 0 = Zero
204toNatE n | n > 0 = Closed (Succ (toNatE (n - 1))) 193toNatE n | n > 0 = Closed (Succ (toNatE (n - 1)))
@@ -225,13 +214,10 @@ mkOrdering x = Closed $ case x of
225 EQ -> tCon "EQ" 1 TOrdering [] 214 EQ -> tCon "EQ" 1 TOrdering []
226 GT -> tCon "GT" 2 TOrdering [] 215 GT -> tCon "GT" 2 TOrdering []
227 216
228noTup (TyConN s _) = take 6 s /= "'Tuple" -- todo
229noTup _ = False
230
231conTypeName :: ConName -> TyConName 217conTypeName :: ConName -> TyConName
232conTypeName (ConName _ _ t) = case snd $ getParams t of TyCon n _ -> n 218conTypeName (ConName _ _ t) = case snd $ getParams t of TyCon n _ -> n
233 219
234outputType = TOutput 220outputType = tTyCon0 "'Output" $ error "cs 9"
235boolType = TBool 221boolType = TBool
236trueExp = EBool True 222trueExp = EBool True
237 223
@@ -478,6 +464,9 @@ getFunDef s f = case s of
478 parEval _ _ (LabelEnd x) = LabelEnd x 464 parEval _ _ (LabelEnd x) = LabelEnd x
479 parEval t a b = ParEval t a b 465 parEval t a b = ParEval t a b
480 466
467 "hlistNilCase" -> \case [_, x, unfixlabel -> Con n@(ConName _ 0 _) _ []] -> x; xs -> f xs
468 "hlistConsCase" -> \case [_, _, _, x, unfixlabel -> Con n@(ConName _ 1 _) _ [_, _, a, b]] -> x `app_` a `app_` b; xs -> f xs
469
481 -- general compiler primitives 470 -- general compiler primitives
482 "primAddInt" -> \case [EInt i, EInt j] -> EInt (i + j); xs -> f xs 471 "primAddInt" -> \case [EInt i, EInt j] -> EInt (i + j); xs -> f xs
483 "primSubInt" -> \case [EInt i, EInt j] -> EInt (i - j); xs -> f xs 472 "primSubInt" -> \case [EInt i, EInt j] -> EInt (i - j); xs -> f xs
@@ -520,40 +509,27 @@ getFunDef s f = case s of
520 509
521cstr = f [] 510cstr = f []
522 where 511 where
523 f _ _ a a' | unfixlabel a == unfixlabel a' = Unit 512 f z ty a a' = f_ z (unfixlabel ty) (unfixlabel a) (unfixlabel a')
524 f ns typ (LabelEnd a) (LabelEnd a') = f ns typ a a'
525 f ns typ (FL a) a' = f ns typ a a'
526 f ns typ a (FL a') = f ns typ a a'
527 f ns typ (Con a n xs) (Con a' n' xs') | a == a' && n == n' && length xs == length xs' =
528 if null xs then Unit else ff ns (foldl appTy (conType typ a) $ mkConPars n typ) $ zip xs xs'
529 f ns typ (TyCon a xs) (TyCon a' xs') | a == a' && length xs == length xs' =
530 ff ns (nType a) $ zip xs xs'
531 f (_: ns) typ{-down?-} (down 0 -> Just a) (down 0 -> Just a') = f ns typ a a'
532 f ns TType (Pi h a b) (Pi h' a' b') | h == h' = t2 (f ns TType a a') (f ((a, a'): ns) TType b b')
533
534 f [] TType (UFunN "'VecScalar" [a, b]) (TVec a' b') = t2 (f [] TNat a a') (f [] TType b b')
535 f [] TType (UFunN "'VecScalar" [a, b]) (UFunN "'VecScalar" [a', b']) = t2 (f [] TNat a a') (f [] TType b b')
536 f [] TType (UFunN "'VecScalar" [a, b]) t@(TTyCon0 n) | isElemTy n = t2 (f [] TNat a (ENat 1)) (f [] TType b t)
537 f [] TType t@(TTyCon0 n) (UFunN "'VecScalar" [a, b]) | isElemTy n = t2 (f [] TNat a (ENat 1)) (f [] TType b t)
538
539-- f [] TType (UTFun "map" (Pi _ t _) [a, b]) (TyConN ":" [x, xs]) = f [] t a (cons x nil)
540 513
541 f [] TType (UTFun "'FragOps" (Pi _ t _) [a]) (TyConN "'FragmentOperation" [x]) = f [] t a (cons x nil) 514 f_ _ _ a a' | a == a' = Unit
542 f [] TType (UTFun "'FragOps" (Pi _ t _) [a]) (TyConN "'Tuple2" [TyConN "'FragmentOperation" [x], TyConN "'FragmentOperation" [y]]) = f [] t a $ cons x $ cons y nil 515 f_ ns typ (LabelEnd a) (LabelEnd a') = f ns typ a a'
543 516 f_ ns typ (Con a n xs) (Con a' n' xs') | a == a' && n == n' && length xs == length xs' =
544 f ns@[] TType (TyConN "'Tuple2" [x, y]) (UFunN "'JoinTupleType" [x', y']) = t2 (f ns TType x x') (f ns TType y y') 517 ff ns (foldl appTy (conType typ a) $ mkConPars n typ) $ zip xs xs'
545 f ns@[] TType (UFunN "'JoinTupleType" [x', y']) (TyConN "'Tuple2" [x, y]) = t2 (f ns TType x' x) (f ns TType y' y) 518 f_ ns typ (TyCon a xs) (TyCon a' xs') | a == a' && length xs == length xs' =
546 f ns@[] TType (UFunN "'JoinTupleType" [x', y']) x@NoTup = t2 (f ns TType x' x) (f ns TType y' TTuple0) 519 ff ns (nType a) $ zip xs xs'
520 f_ (_: ns) typ{-down?-} (down 0 -> Just a) (down 0 -> Just a') = f ns typ a a'
521 f_ ns TType (Pi h a b) (Pi h' a' b') | h == h' = t2 (f ns TType a a') (f ((a, a'): ns) TType b b')
547 522
548-- f ns@[] TType (UFunN "'InterpolatedType" [x'@Neut{}]) TTuple0 = f ns TType x' TTuple0 523 f_ [] TType (UFunN "'VecScalar" [a, b]) (UFunN "'VecScalar" [a', b']) = t2 (f [] TNat a a') (f [] TType b b')
549-- f ns@[] TType (UFunN "'InterpolatedType" [x'@Neut{}]) x@NoTup = f ns TType (tInterpolated x') x 524 f_ [] TType (UFunN "'VecScalar" [a, b]) (TVec a' b') = t2 (f [] TNat a a') (f [] TType b b')
550-- f ns@[] TType (UFunN "'InterpolatedType" [x'@Neut{}]) (TInterpolated x) = f ns TType x' x 525 f_ [] TType (UFunN "'VecScalar" [a, b]) t@(TTyCon0 n) | isElemTy n = t2 (f [] TNat a (ENat 1)) (f [] TType b t)
551 f ns@[] TType x@NoTup (UFunN "'InterpolatedType" [x'@Neut{}]) = f ns TType (tInterpolated x) x' 526 f_ [] TType (TVec a' b') (UFunN "'VecScalar" [a, b]) = t2 (f [] TNat a' a) (f [] TType b' b)
527 f_ [] TType t@(TTyCon0 n) (UFunN "'VecScalar" [a, b]) | isElemTy n = t2 (f [] TNat a (ENat 1)) (f [] TType b t)
552 528
553 f [] typ a@Neut{} a' = CstrT typ a a' 529 f_ [] typ a@Neut{} a' = CstrT typ a a'
554 f [] typ a a'@Neut{} = CstrT typ a a' 530 f_ [] typ a a'@Neut{} = CstrT typ a a'
555 531
556 f ns typ a a' = Empty $ unlines [ "can not unify" 532 f_ ns typ a a' = Empty $ unlines [ "can not unify"
557 , ppShow a 533 , ppShow a
558 , "with" 534 , "with"
559 , ppShow a' 535 , ppShow a'
@@ -688,15 +664,7 @@ parent = \case
688 CheckAppType _ _ _ x _ -> Right x 664 CheckAppType _ _ _ x _ -> Right x
689 ELabelEnd x -> Right x 665 ELabelEnd x -> Right x
690 EGlobal -> Left () 666 EGlobal -> Left ()
691{- 667
692freeVars = \case
693 EGlobal -> []
694 EAssign i _ x -> [Var $ if j > i then j-1 else j | Var j <- freeVars x, j /= i]
695 EBind2 _ _ x -> Var 0: (up 1 <$> freeVars x)
696 ELet2 _ _ x -> Var 0: (up 1 <$> freeVars x)
697 x | Right y <- parent x -> freeVars y
698 x -> error $ "freeVars: " ++ show x
699-}
700-------------------------------------------------------------------------------- simple typing 668-------------------------------------------------------------------------------- simple typing
701 669
702litType = \case 670litType = \case
@@ -769,17 +737,10 @@ expAndType s (e, t, si) = (e, t)
769-- todo: do only if NoTypeNamespace extension is not on 737-- todo: do only if NoTypeNamespace extension is not on
770lookupName s@('\'':s') m = expAndType s <$> (Map.lookup s m `mplus` Map.lookup s' m) 738lookupName s@('\'':s') m = expAndType s <$> (Map.lookup s m `mplus` Map.lookup s' m)
771lookupName s m = expAndType s <$> Map.lookup s m 739lookupName s m = expAndType s <$> Map.lookup s m
772--elemIndex' s@('\'':s') m = elemIndex s m `mplus` elemIndex s' m
773--elemIndex' s m = elemIndex s m
774 740
775getDef te si s = do 741getDef te si s = do
776 nv <- asks snd 742 nv <- asks snd
777 maybe (throwError' $ ECantFind s si) return (lookupName s nv) 743 maybe (throwError' $ ECantFind s si) return (lookupName s nv)
778{-
779take' e n xs = case splitAt n xs of
780 (as, []) -> as
781 (as, _) -> as ++ [e]
782-}
783 744
784type ExpType' = CEnv ExpType 745type ExpType' = CEnv ExpType
785 746
@@ -799,6 +760,7 @@ inferN_ tellTrace = infer where
799 760
800 infer :: Env -> SExp2 -> IM m ExpType' 761 infer :: Env -> SExp2 -> IM m ExpType'
801 infer te exp = tellTrace "infer" (showEnvSExp te exp) $ (if debug then fmap (fmap{-todo-} $ recheck' "infer" te) else id) $ case exp of 762 infer te exp = tellTrace "infer" (showEnvSExp te exp) $ (if debug then fmap (fmap{-todo-} $ recheck' "infer" te) else id) $ case exp of
763 Parens x -> infer te x
802 SAnn x t -> checkN (CheckIType x te) t TType 764 SAnn x t -> checkN (CheckIType x te) t TType
803 SLabelEnd x -> infer (ELabelEnd te) x 765 SLabelEnd x -> infer (ELabelEnd te) x
804 SVar (si, _) i -> focus_' te exp (Var i, snd $ varType "C2" i te) 766 SVar (si, _) i -> focus_' te exp (Var i, snd $ varType "C2" i te)
@@ -812,6 +774,7 @@ inferN_ tellTrace = infer where
812 checkN :: Env -> SExp2 -> Type -> IM m ExpType' 774 checkN :: Env -> SExp2 -> Type -> IM m ExpType'
813 checkN te x t = tellTrace "check" (showEnvSExpType te x t) $ checkN_ te x t 775 checkN te x t = tellTrace "check" (showEnvSExpType te x t) $ checkN_ te x t
814 776
777 checkN_ te (Parens e) t = checkN_ te e t
815 checkN_ te e t 778 checkN_ te e t
816 | x@(SGlobal (si, MatchName n)) `SAppV` SLamV (Wildcard _) `SAppV` a `SAppV` SVar siv v `SAppV` b <- e 779 | x@(SGlobal (si, MatchName n)) `SAppV` SLamV (Wildcard _) `SAppV` a `SAppV` SVar siv v `SAppV` b <- e
817 = infer te $ x `SAppV` SLam Visible SType (STyped mempty (subst (v+1) (Var 0) $ up 1 t, TType)) `SAppV` a `SAppV` SVar siv v `SAppV` b 780 = infer te $ x `SAppV` SLam Visible SType (STyped mempty (subst (v+1) (Var 0) $ up 1 t, TType)) `SAppV` a `SAppV` SVar siv v `SAppV` b
@@ -901,8 +864,10 @@ inferN_ tellTrace = infer where
901 864
902 focus2 :: Env -> CEnv ExpType -> IM m ExpType' 865 focus2 :: Env -> CEnv ExpType -> IM m ExpType'
903 focus2 env eet = case env of 866 focus2 env eet = case env of
867-- ELabelEnd te ->
904 ELet1 le te b{-in-} -> infer (ELet2 le (replaceMetas' eet{-let-}) te) b{-in-} 868 ELet1 le te b{-in-} -> infer (ELet2 le (replaceMetas' eet{-let-}) te) b{-in-}
905 EBind2_ si BMeta tt_ te 869 EBind2_ si BMeta tt_ te
870 | ELabelEnd te' <- te -> refocus (ELabelEnd $ EBind2_ si BMeta tt_ te') eet
906 | Unit <- tt -> refocus te $ subst 0 TT eet 871 | Unit <- tt -> refocus te $ subst 0 TT eet
907 | Empty msg <- tt -> throwError' $ ETypeError msg si 872 | Empty msg <- tt -> throwError' $ ETypeError msg si
908 | T2 x y <- tt, let te' = EBind2_ si BMeta (up 1 y) $ EBind2_ si BMeta x te 873 | T2 x y <- tt, let te' = EBind2_ si BMeta (up 1 y) $ EBind2_ si BMeta x te
@@ -923,7 +888,6 @@ inferN_ tellTrace = infer where
923 | EApp2 si h x te' <- te -> refocus (EApp2 si h (up 1 x) $ EBind2_ si BMeta tt_ te') eet 888 | EApp2 si h x te' <- te -> refocus (EApp2 si h (up 1 x) $ EBind2_ si BMeta tt_ te') eet
924 | CheckType_ si t te' <- te -> refocus (CheckType_ si (up 1 t) $ EBind2_ si BMeta tt_ te') eet 889 | CheckType_ si t te' <- te -> refocus (CheckType_ si (up 1 t) $ EBind2_ si BMeta tt_ te') eet
925-- | CheckIType x te' <- te -> refocus (CheckType_ si (up 1 t) $ EBind2_ si BMeta tt te') eet 890-- | CheckIType x te' <- te -> refocus (CheckType_ si (up 1 t) $ EBind2_ si BMeta tt te') eet
926 | ELabelEnd te' <- te -> refocus (ELabelEnd $ EBind2_ si BMeta tt_ te') eet
927 | otherwise -> focus2 te $ Meta tt_ eet 891 | otherwise -> focus2 te $ Meta tt_ eet
928 where 892 where
929 tt = unfixlabel tt_ 893 tt = unfixlabel tt_
@@ -936,6 +900,7 @@ inferN_ tellTrace = infer where
936 _ -> Nothing 900 _ -> Nothing
937 901
938 EAssign i b te -> case te of 902 EAssign i b te -> case te of
903 ELabelEnd te' -> refocus' (ELabelEnd $ EAssign i b te') eet
939 EBind2_ si h x te' | i > 0, Just b' <- down 0 b 904 EBind2_ si h x te' | i > 0, Just b' <- down 0 b
940 -> refocus' (EBind2_ si h (subst (i-1) (fst b') x) (EAssign (i-1) b' te')) eet 905 -> refocus' (EBind2_ si h (subst (i-1) (fst b') x) (EAssign (i-1) b' te')) eet
941 ELet2 le (x, xt) te' | i > 0, Just b' <- down 0 b 906 ELet2 le (x, xt) te' | i > 0, Just b' <- down 0 b
@@ -946,18 +911,26 @@ inferN_ tellTrace = infer where
946 EApp1 si h te' x -> refocus' (EApp1 si h (EAssign i b te') $ substS i b x) eet 911 EApp1 si h te' x -> refocus' (EApp1 si h (EAssign i b te') $ substS i b x) eet
947 EApp2 si h x te' -> refocus' (EApp2 si h (subst i (fst b) x) $ EAssign i b te') eet 912 EApp2 si h x te' -> refocus' (EApp2 si h (subst i (fst b) x) $ EAssign i b te') eet
948 CheckType_ si t te' -> refocus' (CheckType_ si (subst i (fst b) t) $ EAssign i b te') eet 913 CheckType_ si t te' -> refocus' (CheckType_ si (subst i (fst b) t) $ EAssign i b te') eet
949 ELabelEnd te' -> refocus' (ELabelEnd $ EAssign i b te') eet
950 EAssign j a te' | i < j 914 EAssign j a te' | i < j
951 -> refocus' (EAssign (j-1) (subst i (fst b) a) $ EAssign i (up1_ (j-1) b) te') eet 915 -> refocus' (EAssign (j-1) (subst i (fst b) a) $ EAssign i (up1_ (j-1) b) te') eet
952 t | Just te' <- pull i te -> refocus' te' eet 916 t | Just te' <- pull1 i b te -> refocus' te' eet
953 | otherwise -> swapAssign (\i x -> focus2 te . Assign i x) (\i x -> refocus' $ EAssign i x te) i b eet 917 | otherwise -> swapAssign (\i x -> focus2 te . Assign i x) (\i x -> refocus' $ EAssign i x te) i b eet
954 -- todo: CheckSame Exp Env 918 -- todo: CheckSame Exp Env
955 where 919 where
956 refocus' = fix refocus_ 920 refocus' = fix refocus_
921
922 pull1 i b = \case
923 EBind2_ si h x te | i > 0, Just b' <- down 0 b
924 -> EBind2_ si h (subst (i-1) (fst b') x) <$> pull1 (i-1) b' te
925 EAssign j a te
926 | i < j -> EAssign (j-1) (subst i (fst b) a) <$> pull1 i (up1_ (j-1) b) te
927 | j <= i -> EAssign j (subst i (fst b) a) <$> pull1 (i+1) (up1_ j b) te
928 te -> pull i te
929
957 pull i = \case 930 pull i = \case
958 EBind2 BMeta _ te | i == 0 -> Just te 931 EBind2 BMeta _ te | i == 0 -> Just te
959 EBind2_ si h x te -> EBind2_ si h <$> down (i-1) x <*> pull (i-1) te 932 EBind2_ si h x te | i > 0 -> EBind2_ si h <$> down (i-1) x <*> pull (i-1) te
960 EAssign j b te -> EAssign (if j <= i then j else j-1) <$> down i b <*> pull (if j <= i then i+1 else i) te 933 EAssign j a te -> EAssign (if j <= i then j else j-1) <$> down i a <*> pull (if j <= i then i+1 else i) te
961 _ -> Nothing 934 _ -> Nothing
962 935
963 EGlobal{} -> return eet 936 EGlobal{} -> return eet
@@ -1089,30 +1062,13 @@ dependentVars ie = cycle mempty
1089 1062
1090-------------------------------------------------------------------------------- global env 1063-------------------------------------------------------------------------------- global env
1091 1064
1092type GlobalEnv = Map.Map SName (Exp, Type, (SI, MFixity)) 1065type GlobalEnv = Map.Map SName (Exp, Type, SI)
1093 1066
1094initEnv :: GlobalEnv 1067initEnv :: GlobalEnv
1095initEnv = Map.fromList 1068initEnv = Map.fromList
1096 [ (,) "'Type" (TType, TType, (debugSI "source-of-Type", Nothing)) 1069 [ (,) "'Type" (TType, TType, debugSI "source-of-Type")
1097 ] 1070 ]
1098 1071
1099-- todo: eliminate
1100extractDesugarInfo :: GlobalEnv -> DesugarInfo
1101extractDesugarInfo ge =
1102 ( Map.fromList
1103 [ (n, f) | (n, (d, _, (si, Just f))) <- Map.toList ge ]
1104 , Map.fromList $
1105 [ (n, Left ((t, inum), map f cons))
1106 | (n, ( (Con cn 0 []), _, si)) <- Map.toList ge, let TyConName t inum _ cons _ = conTypeName cn
1107 ] ++
1108 [ (n, Right $ pars t)
1109 | (n, ( (TyCon (TyConName _ _ t _ _) []), _, _)) <- Map.toList ge
1110 ]
1111 )
1112 where
1113 f (ConName n _ _, ct) = (n, pars ct)
1114 pars = length . filter ((==Visible) . fst) . fst . getParams
1115
1116-------------------------------------------------------------------------------- infos 1072-------------------------------------------------------------------------------- infos
1117 1073
1118data Info 1074data Info
@@ -1156,16 +1112,16 @@ listTypeInfos m = map (second Set.toList) $ Map.toList $ Map.unionsWith (<>) [Ma
1156 1112
1157handleStmt :: MonadFix m => [Stmt] -> Stmt -> IM m GlobalEnv 1113handleStmt :: MonadFix m => [Stmt] -> Stmt -> IM m GlobalEnv
1158handleStmt defs = \case 1114handleStmt defs = \case
1159 Primitive n mf (trSExp' -> t_) -> do 1115 Primitive n (trSExp' -> t_) -> do
1160 t <- inferType =<< ($ t_) <$> addF 1116 t <- inferType =<< ($ t_) <$> addF
1161 tellType (fst n) t 1117 tellType (fst n) t
1162 addToEnv n mf $ flip (,) t $ lamify t $ Neut . DFun_ (FunName (snd n) Nothing t) 1118 addToEnv n $ flip (,) t $ lamify t $ Neut . DFun_ (FunName (snd n) Nothing t)
1163 Let n mf mt t_ -> do 1119 Let n mt t_ -> do
1164 af <- addF 1120 af <- addF
1165 let t__ = maybe id (flip SAnn . af) mt t_ 1121 let t__ = maybe id (flip SAnn . af) mt t_
1166 (x, t) <- inferTerm (snd n) $ trSExp' $ if usedS n t__ then SBuiltin "primFix" `SAppV` SLamV (substSG0 n t__) else t__ 1122 (x, t) <- inferTerm (snd n) $ trSExp' $ if usedS n t__ then SBuiltin "primFix" `SAppV` SLamV (substSG0 n t__) else t__
1167 tellType (fst n) t 1123 tellType (fst n) t
1168 addToEnv n mf (mkELet n x t, t) 1124 addToEnv n (mkELet n x t, t)
1169{- -- hack 1125{- -- hack
1170 when (snd (getParams t) == TType) $ do 1126 when (snd (getParams t) == TType) $ do
1171 let ps' = fst $ getParams t 1127 let ps' = fst $ getParams t
@@ -1194,7 +1150,7 @@ handleStmt defs = \case
1194 act = length . fst . getParams $ cty 1150 act = length . fst . getParams $ cty
1195 acts = map fst . fst . getParams $ cty 1151 acts = map fst . fst . getParams $ cty
1196 conn = ConName (snd cn) j cty 1152 conn = ConName (snd cn) j cty
1197 e <- addToEnv cn (listToMaybe [f | PrecDef n f <- defs, n == cn]) (Con conn 0 [], cty) 1153 e <- addToEnv cn (Con conn 0 [], cty)
1198 return (e, ((conn, cty) 1154 return (e, ((conn, cty)
1199 , addParamsS pars 1155 , addParamsS pars
1200 $ foldl SAppV (SVar (debugSI "22", ".cs") $ j + length pars) $ drop pnum' xs ++ [apps' (SGlobal cn) (zip acts $ downToS ("a4 " ++ snd cn ++ " " ++ show (length ps)) (j+1+length pars) (length ps) ++ downToS "a5" 0 (act- length ps))] 1156 $ foldl SAppV (SVar (debugSI "22", ".cs") $ j + length pars) $ drop pnum' xs ++ [apps' (SGlobal cn) (zip acts $ downToS ("a4 " ++ snd cn ++ " " ++ show (length ps)) (j+1+length pars) (length ps) ++ downToS "a5" 0 (act- length ps))]
@@ -1209,7 +1165,7 @@ handleStmt defs = \case
1209 (e1, es, tcn, cfn@(CaseFunName _ ct _), _, _) <- mfix $ \ ~(_, _, _, _, ct', cons') -> do 1165 (e1, es, tcn, cfn@(CaseFunName _ ct _), _, _) <- mfix $ \ ~(_, _, _, _, ct', cons') -> do
1210 let cfn = CaseFunName (snd s) ct' $ length ps 1166 let cfn = CaseFunName (snd s) ct' $ length ps
1211 let tcn = TyConName (snd s) inum vty (map fst cons') cfn 1167 let tcn = TyConName (snd s) inum vty (map fst cons') cfn
1212 e1 <- addToEnv s (listToMaybe [f | PrecDef n f <- defs, n == s]) (TyCon tcn [], vty) 1168 e1 <- addToEnv s (TyCon tcn [], vty)
1213 (unzip -> (mconcat -> es, cons)) <- withEnv e1 $ zipWithM mkConstr [0..] cs 1169 (unzip -> (mconcat -> es, cons)) <- withEnv e1 $ zipWithM mkConstr [0..] cs
1214 ct <- withEnv (e1 <> es) $ inferType 1170 ct <- withEnv (e1 <> es) $ inferType
1215 ( (\x -> traceD ("type of case-elim before elaboration: " ++ ppShow x) x) $ addParamsS 1171 ( (\x -> traceD ("type of case-elim before elaboration: " ++ ppShow x) x) $ addParamsS
@@ -1223,14 +1179,14 @@ handleStmt defs = \case
1223 ) 1179 )
1224 return (e1, es, tcn, cfn, ct, cons) 1180 return (e1, es, tcn, cfn, ct, cons)
1225 1181
1226 e2 <- addToEnv (fst s, caseName (snd s)) Nothing (lamify ct $ \xs -> evalCaseFun cfn (init $ drop (length ps) xs) (last xs), ct) 1182 e2 <- addToEnv (fst s, caseName (snd s)) (lamify ct $ \xs -> evalCaseFun cfn (init $ drop (length ps) xs) (last xs), ct)
1227 let ps' = fst $ getParams vty 1183 let ps' = fst $ getParams vty
1228 t = (TType :~> TType) 1184 t = (TType :~> TType)
1229 :~> addParams ps' (Var (length ps') `app_` TyCon tcn (downTo 0 $ length ps')) 1185 :~> addParams ps' (Var (length ps') `app_` TyCon tcn (downTo 0 $ length ps'))
1230 :~> TType 1186 :~> TType
1231 :~> Var 2 `app_` Var 0 1187 :~> Var 2 `app_` Var 0
1232 :~> Var 3 `app_` Var 1 1188 :~> Var 3 `app_` Var 1
1233 e3 <- addToEnv (fst s, MatchName (snd s)) Nothing (lamify t $ \[m, tr, n, f] -> evalTyCaseFun (TyCaseFunName (snd s) t) [m, tr, f] n, t) 1189 e3 <- addToEnv (fst s, MatchName (snd s)) (lamify t $ \[m, tr, n, f] -> evalTyCaseFun (TyCaseFunName (snd s) t) [m, tr, f] n, t)
1234 return (e1 <> e2 <> e3 <> es) 1190 return (e1 <> e2 <> e3 <> es)
1235 1191
1236 stmt -> error $ "handleStmt: " ++ show stmt 1192 stmt -> error $ "handleStmt: " ++ show stmt
@@ -1280,15 +1236,15 @@ inferTerm msg t =
1280inferType :: Monad m => SExp2 -> IM m Type 1236inferType :: Monad m => SExp2 -> IM m Type
1281inferType t = fmap (closedExp . fst . recheck "inferType" EGlobal . flip (,) TType . replaceMetas (Pi Hidden) . fmap fst) $ inferN (CheckType_ (debugSI "inferType CheckType_") TType EGlobal) t 1237inferType t = fmap (closedExp . fst . recheck "inferType" EGlobal . flip (,) TType . replaceMetas (Pi Hidden) . fmap fst) $ inferN (CheckType_ (debugSI "inferType CheckType_") TType EGlobal) t
1282 1238
1283addToEnv :: Monad m => SIName -> MFixity -> ExpType -> IM m GlobalEnv 1239addToEnv :: Monad m => SIName -> ExpType -> IM m GlobalEnv
1284addToEnv (si, s) mf (x, t) = do 1240addToEnv (si, s) (x, t) = do
1285-- maybe (pure ()) throwError_ $ ambiguityCheck s t -- TODO 1241-- maybe (pure ()) throwError_ $ ambiguityCheck s t -- TODO
1286-- b <- asks $ (TraceTypeCheck `elem`) . fst 1242-- b <- asks $ (TraceTypeCheck `elem`) . fst
1287 tell [IType s $ ppShow t] 1243 tell [IType s $ ppShow t]
1288 v <- asks $ Map.lookup s . snd 1244 v <- asks $ Map.lookup s . snd
1289 case v of 1245 case v of
1290 Nothing -> return $ Map.singleton s (closedExp x, closedExp t, (si, mf)) 1246 Nothing -> return $ Map.singleton s (closedExp x, closedExp t, si)
1291 Just (_, _, (si', _)) -> throwError' $ ERedefined s si si' 1247 Just (_, _, si') -> throwError' $ ERedefined s si si'
1292{- 1248{-
1293joinEnv :: Monad m => GlobalEnv -> GlobalEnv -> IM m GlobalEnv 1249joinEnv :: Monad m => GlobalEnv -> GlobalEnv -> IM m GlobalEnv
1294joinEnv e1 e2 = do 1250joinEnv e1 e2 = do
@@ -1308,6 +1264,7 @@ tellType si t = tell $ mkInfoItem (sourceInfo si) $ removeEscs $ showDoc $ mkDoc
1308data PolyEnv = PolyEnv 1264data PolyEnv = PolyEnv
1309 { getPolyEnv :: GlobalEnv 1265 { getPolyEnv :: GlobalEnv
1310 , infos :: Infos 1266 , infos :: Infos
1267 , dsInfo :: DesugarInfo
1311 } 1268 }
1312 1269
1313filterPolyEnv p pe = pe { getPolyEnv = Map.filterWithKey (\k _ -> p k) $ getPolyEnv pe } 1270filterPolyEnv p pe = pe { getPolyEnv = Map.filterWithKey (\k _ -> p k) $ getPolyEnv pe }
@@ -1315,8 +1272,8 @@ filterPolyEnv p pe = pe { getPolyEnv = Map.filterWithKey (\k _ -> p k) $ getPoly
1315joinPolyEnvs :: MonadError String m => Bool -> [PolyEnv] -> m PolyEnv 1272joinPolyEnvs :: MonadError String m => Bool -> [PolyEnv] -> m PolyEnv
1316joinPolyEnvs _ = return . foldr mappend' mempty' -- todo 1273joinPolyEnvs _ = return . foldr mappend' mempty' -- todo
1317 where 1274 where
1318 mempty' = PolyEnv mempty mempty 1275 mempty' = PolyEnv mempty mempty mempty
1319 PolyEnv a b `mappend'` PolyEnv a' b' = PolyEnv (a `mappend` a') (b `mappend` b') 1276 PolyEnv a b c `mappend'` PolyEnv a' b' c' = PolyEnv (a `mappend` a') (b `mappend` b') (c `joinDesugarInfo` c')
1320 1277
1321-------------------------------------------------------------------------------- pretty print 1278-------------------------------------------------------------------------------- pretty print
1322-- todo: do this via conversion to SExp 1279-- todo: do this via conversion to SExp
@@ -1403,9 +1360,11 @@ instance MkDoc Exp where
1403 where 1360 where
1404 f = \case 1361 f = \case
1405-- Lam h a b -> join $ shLam (used 0 b) (BLam h) <$> f a <*> pure (f b) 1362-- Lam h a b -> join $ shLam (used 0 b) (BLam h) <$> f a <*> pure (f b)
1406 Lam b -> join $ shLam True (BLam Visible) <$> f TType{-todo!-} <*> pure (f b) 1363 Lam b -> join $ shLam True (BLam Visible) <$> f TType{-todo!-} <*> pure (f b)
1407 Pi h a b -> join $ shLam (used 0 b) (BPi h) <$> f a <*> pure (f b) 1364 Pi h a b -> join $ shLam (used 0 b) (BPi h) <$> f a <*> pure (f b)
1408 ENat' n -> pure $ shAtom $ show n 1365 ENat' n -> pure $ shAtom $ show n
1366 (getTTup -> Just xs) -> shTuple <$> mapM f xs
1367 (getTup -> Just xs) -> shTuple <$> mapM f xs
1409 Con s _ xs -> foldl (shApp Visible) (shAtom_ $ show s) <$> mapM f xs 1368 Con s _ xs -> foldl (shApp Visible) (shAtom_ $ show s) <$> mapM f xs
1410 TyConN s xs -> foldl (shApp Visible) (shAtom_ s) <$> mapM f xs 1369 TyConN s xs -> foldl (shApp Visible) (shAtom_ s) <$> mapM f xs
1411 TType -> pure $ shAtom "Type" 1370 TType -> pure $ shAtom "Type"
@@ -1440,19 +1399,31 @@ instance MkDoc (CEnv Exp) where
1440 Meta a b -> join $ shLam True BMeta <$> mkDoc ts a <*> pure (f b) 1399 Meta a b -> join $ shLam True BMeta <$> mkDoc ts a <*> pure (f b)
1441 Assign i (x, _) e -> shLet i (mkDoc ts x) (f e) 1400 Assign i (x, _) e -> shLet i (mkDoc ts x) (f e)
1442 1401
1402getTup (unfixlabel -> ConN "HCons" [_, _, x, xs]) = (x:) <$> getTup xs
1403getTup (unfixlabel -> ConN "HNil" []) = Just []
1404getTup _ = Nothing
1405
1406getTTup (unfixlabel -> TyConN "'HList" [xs]) = getList xs
1407getTTup _ = Nothing
1408
1409getList (unfixlabel -> ConN "Cons" [x, xs]) = (x:) <$> getList xs
1410getList (unfixlabel -> ConN "Nil" []) = Just []
1411getList _ = Nothing
1412
1413
1443-------------------------------------------------------------------------------- main 1414-------------------------------------------------------------------------------- main
1444 1415
1445mfix' f = ExceptT (mfix (runExceptT . f . either bomb id)) 1416mfix' f = ExceptT (mfix (runExceptT . f . either bomb id))
1446 where bomb e = error $ "mfix (ExceptT): inner computation returned Left value:\n" ++ show e 1417 where bomb e = error $ "mfix (ExceptT): inner computation returned Left value:\n" ++ show e
1447 1418
1448inference_ :: PolyEnv -> Extensions -> [Stmt] -> ExceptT ErrorMsg (WriterT Infos Identity) PolyEnv 1419inference_ :: PolyEnv -> Extensions -> [Stmt] -> ExceptT ErrorMsg (WriterT Infos Identity) PolyEnv
1449inference_ (PolyEnv pe is) exts defs = mapExceptT (ff . runWriter . flip runReaderT (exts, mempty)) $ gg (handleStmt defs) (initEnv <> pe) defs 1420inference_ (PolyEnv pe is _) exts defs = mapExceptT (ff . runWriter . flip runReaderT (exts, mempty)) $ gg (handleStmt defs) (initEnv <> pe) defs
1450 where 1421 where
1451 ff (Left e, is) = do 1422 ff (Left e, is) = do
1452 tell is 1423 tell is
1453 return $ Left e 1424 return $ Left e
1454 ff (Right ge, is) = do 1425 ff (Right ge, is) = do
1455 return $ Right $ PolyEnv ge is 1426 return $ Right $ PolyEnv ge is $ mkDesugarInfo defs
1456 1427
1457 gg _ acc [] = return acc 1428 gg _ acc [] = return acc
1458 gg m acc (x:xs) = do 1429 gg m acc (x:xs) = do
diff --git a/src/LambdaCube/Compiler/Lexer.hs b/src/LambdaCube/Compiler/Lexer.hs
index 1389ebf2..631bbef9 100644
--- a/src/LambdaCube/Compiler/Lexer.hs
+++ b/src/LambdaCube/Compiler/Lexer.hs
@@ -52,7 +52,7 @@ type PostponedCheck = Maybe String
52type DesugarInfo = (FixityMap, ConsMap) 52type DesugarInfo = (FixityMap, ConsMap)
53 53
54type ConsMap = Map.Map SName{-constructor name-} 54type ConsMap = Map.Map SName{-constructor name-}
55 (Either ((SName{-type name-}, Int{-num of indices-}), [(SName, Int)]{-constructors with arities-}) 55 (Either ((SName{-case eliminator name-}, Int{-num of indices-}), [(SName, Int)]{-constructors with arities-})
56 Int{-arity-}) 56 Int{-arity-})
57 57
58dsInfo :: P DesugarInfo 58dsInfo :: P DesugarInfo
@@ -253,7 +253,6 @@ upperLower = lowerCase <|> upperCase_ <|> parens (symbols <|> backquotedIde
253 253
254data FixityDef = Infix | InfixL | InfixR deriving (Show) 254data FixityDef = Infix | InfixL | InfixR deriving (Show)
255type Fixity = (FixityDef, Int) 255type Fixity = (FixityDef, Int)
256type MFixity = Maybe Fixity
257type FixityMap = Map.Map SName Fixity 256type FixityMap = Map.Map SName Fixity
258 257
259calcPrec 258calcPrec
diff --git a/src/LambdaCube/Compiler/Parser.hs b/src/LambdaCube/Compiler/Parser.hs
index 6a27fb56..e4d482a8 100644
--- a/src/LambdaCube/Compiler/Parser.hs
+++ b/src/LambdaCube/Compiler/Parser.hs
@@ -13,14 +13,14 @@ module LambdaCube.Compiler.Parser
13 , sourceInfo, SI(..), debugSI 13 , sourceInfo, SI(..), debugSI
14 , Module(..), Visibility(..), Binder(..), SExp'(..), Extension(..), Extensions 14 , Module(..), Visibility(..), Binder(..), SExp'(..), Extension(..), Extensions
15 , pattern SVar, pattern SType, pattern Wildcard, pattern SAppV, pattern SLamV, pattern SAnn 15 , pattern SVar, pattern SType, pattern Wildcard, pattern SAppV, pattern SLamV, pattern SAnn
16 , pattern SBuiltin, pattern SPi, pattern Primitive, pattern SLabelEnd, pattern SLam 16 , pattern SBuiltin, pattern SPi, pattern Primitive, pattern SLabelEnd, pattern SLam, pattern Parens
17 , pattern TyType, pattern Wildcard_ 17 , pattern TyType, pattern Wildcard_
18 , debug, isPi, varDB, lowerDB, justDB, upDB, cmpDB, MaxDB (..), iterateN, traceD 18 , debug, isPi, varDB, lowerDB, justDB, upDB, cmpDB, MaxDB (..), iterateN, traceD
19 , parseLC, runDefParser 19 , parseLC, runDefParser
20 , getParamsS, addParamsS, getApps, apps', downToS, addForalls 20 , getParamsS, addParamsS, getApps, apps', downToS, addForalls
21 , mkDesugarInfo, joinDesugarInfo 21 , mkDesugarInfo, joinDesugarInfo
22 , Up (..), up1, up 22 , Up (..), up1, up
23 , Doc, shLam, shApp, shLet, shLet_, shAtom, shAnn, shVar, epar, showDoc, showDoc_, sExpDoc, shCstr 23 , Doc, shLam, shApp, shLet, shLet_, shAtom, shAnn, shVar, epar, showDoc, showDoc_, sExpDoc, shCstr, shTuple
24 , mtrace, sortDefs 24 , mtrace, sortDefs
25 , trSExp', usedS, substSG0, substS 25 , trSExp', usedS, substSG0, substS
26 , Stmt (..), Export (..), ImportItems (..) 26 , Stmt (..), Export (..), ImportItems (..)
@@ -131,6 +131,7 @@ pattern SLabelEnd a = SBuiltin "labelend" `SAppV` a
131pattern SBuiltin s <- SGlobal (_, s) where SBuiltin s = SGlobal (debugSI $ "builtin " ++ s, s) 131pattern SBuiltin s <- SGlobal (_, s) where SBuiltin s = SGlobal (debugSI $ "builtin " ++ s, s)
132 132
133pattern Section e = SBuiltin "^section" `SAppV` e 133pattern Section e = SBuiltin "^section" `SAppV` e
134pattern Parens e = SBuiltin "parens" `SAppV` e
134 135
135sApp v a b = SApp (sourceInfo a <> sourceInfo b) v a b 136sApp v a b = SApp (sourceInfo a <> sourceInfo b) v a b
136sBind v x a b = SBind (sourceInfo a <> sourceInfo b) v x a b 137sBind v x a b = SBind (sourceInfo a <> sourceInfo b) v x a b
@@ -398,25 +399,24 @@ parseTerm prec = setSI' {-TODO: remove, slow-} $ case prec of
398 399
399 mkProjection = foldl $ \exp field -> SBuiltin "project" `SAppV` field `SAppV` exp 400 mkProjection = foldl $ \exp field -> SBuiltin "project" `SAppV` field `SAppV` exp
400 401
401 -- Creates: RecordCons @[("x", _), ("y", _), ("z", _)] (1.0, (2.0, (3.0, ()))) 402 -- Creates: RecordCons @[("x", _), ("y", _), ("z", _)] (1.0, 2.0, 3.0)))
402 mkRecord xs = SBuiltin "RecordCons" `SAppH` names `SAppV` values 403 mkRecord xs = SBuiltin "RecordCons" `SAppH` names `SAppV` values
403 where 404 where
404 (names, values) = mkNames *** mkValues $ unzip xs 405 (names, values) = mkNames *** mkValues $ unzip xs
405 406
406 mkNameTuple (si, v) = SBuiltin "Tuple2" `SAppV` SLit si (LString v) `SAppV` Wildcard SType 407 mkNameTuple (si, v) = SBuiltin "RecItem" `SAppV` SLit si (LString v) `SAppV` Wildcard SType
407 mkNames = foldr (\n ns -> SBuiltin "Cons" `SAppV` mkNameTuple n `SAppV` ns) 408 mkNames = foldr (\n ns -> SBuiltin "Cons" `SAppV` mkNameTuple n `SAppV` ns)
408 (SBuiltin "Nil") 409 (SBuiltin "Nil")
409 410
410 mkValues = foldr (\x xs -> SBuiltin "Tuple2" `SAppV` x `SAppV` xs) 411 mkValues = foldr (\x xs -> SBuiltin "HCons" `SAppV` x `SAppV` xs)
411 (SBuiltin "Tuple0") 412 (SBuiltin "HNil")
412 413
413 mkTuple _ [Section e] = e 414 mkTuple _ [Section e] = e
414 mkTuple _ [x] = x 415 mkTuple (Namespace (Just TypeLevel) _) [Parens e] = SBuiltin "'HList" `SAppV` (SBuiltin "Cons" `SAppV` e `SAppV` SBuiltin "Nil")
415 mkTuple (Namespace level _) xs = foldl SAppV (SBuiltin (tuple ++ show (length xs))) xs 416 mkTuple _ [Parens e] = SBuiltin "HCons" `SAppV` e `SAppV` SBuiltin "HNil"
416 where tuple = case level of 417 mkTuple _ [x] = Parens x
417 Just TypeLevel -> "'Tuple" 418 mkTuple (Namespace (Just TypeLevel) _) xs = SBuiltin "'HList" `SAppV` foldr (\x y -> SBuiltin "Cons" `SAppV` x `SAppV` y) (SBuiltin "Nil") xs
418 Just ExpLevel -> "Tuple" 419 mkTuple _ xs = foldr (\x y -> SBuiltin "HCons" `SAppV` x `SAppV` y) (SBuiltin "HNil") xs
419 _ -> error "mkTuple"
420 420
421 mkList (Namespace (Just TypeLevel) _) [x] = SBuiltin "'List" `SAppV` x 421 mkList (Namespace (Just TypeLevel) _) [x] = SBuiltin "'List" `SAppV` x
422 mkList (Namespace (Just ExpLevel) _) xs = foldr (\x l -> SBuiltin "Cons" `SAppV` x `SAppV` l) (SBuiltin "Nil") xs 422 mkList (Namespace (Just ExpLevel) _) xs = foldr (\x l -> SBuiltin "Cons" `SAppV` x `SAppV` l) (SBuiltin "Nil") xs
@@ -469,11 +469,11 @@ parseTerm prec = setSI' {-TODO: remove, slow-} $ case prec of
469 469
470 sNonDepPi h a b = SPi h a $ up1 b 470 sNonDepPi h a b = SPi h a $ up1 b
471 471
472getTTuple' (getTTuple -> Just (n, xs)) | n == length xs = xs 472getTTuple' (SBuiltin "'HList" `SAppV` (getTTuple -> Just (n, xs))) | n == length xs = xs
473getTTuple' x = [x] 473getTTuple' x = [x]
474 474
475getTTuple (SAppV (getTTuple -> Just (n, xs)) z) = Just (n, xs ++ [z]{-todo: eff-}) 475getTTuple (SBuiltin "Nil") = Just (0, [])
476getTTuple (SGlobal (si, s@(splitAt 6 -> ("'Tuple", reads -> [(n, "")])))) = Just (n :: Int, []) 476getTTuple (SBuiltin "Cons" `SAppV` x `SAppV` (getTTuple -> Just (n, y))) = Just (n+1, x:y)
477getTTuple _ = Nothing 477getTTuple _ = Nothing
478 478
479patLam :: (SExp -> SExp) -> DesugarInfo -> (Visibility, SExp) -> Pat -> SExp -> SExp 479patLam :: (SExp -> SExp) -> DesugarInfo -> (Visibility, SExp) -> Pat -> SExp -> SExp
@@ -488,6 +488,8 @@ data Pat
488 | PatType ParPat SExp 488 | PatType ParPat SExp
489 deriving Show 489 deriving Show
490 490
491pattern PParens p = ViewPat (SBuiltin "parens") (ParPat [p])
492
491-- parallel patterns like v@(f -> [])@(Just x) 493-- parallel patterns like v@(f -> [])@(Just x)
492newtype ParPat = ParPat [Pat] 494newtype ParPat = ParPat [Pat]
493 deriving Show 495 deriving Show
@@ -499,6 +501,7 @@ mapP :: (SExp -> SExp) -> Pat -> Pat
499mapP f = \case 501mapP f = \case
500 PVar n -> PVar n 502 PVar n -> PVar n
501 PCon n pp -> PCon n (mapPP f <$> pp) 503 PCon n pp -> PCon n (mapPP f <$> pp)
504 PParens p -> PParens (mapP f p)
502 ViewPat e pp -> ViewPat (f e) (mapPP f pp) 505 ViewPat e pp -> ViewPat (f e) (mapPP f pp)
503 PatType pp e -> PatType (mapPP f pp) (f e) 506 PatType pp e -> PatType (mapPP f pp) (f e)
504 507
@@ -517,6 +520,7 @@ getPPVars = reverse . getPPVars_
517getPVars_ = \case 520getPVars_ = \case
518 PVar n -> [n] 521 PVar n -> [n]
519 PCon _ pp -> foldMap getPPVars_ pp 522 PCon _ pp -> foldMap getPPVars_ pp
523 PParens p -> getPVars_ p
520 ViewPat e pp -> getPPVars_ pp 524 ViewPat e pp -> getPPVars_ pp
521 PatType pp e -> getPPVars_ pp 525 PatType pp e -> getPPVars_ pp
522 526
@@ -577,8 +581,11 @@ parsePat = \case
577 mkListPat _ [] = PCon (debugSI "mkListPat3", "Nil") [] 581 mkListPat _ [] = PCon (debugSI "mkListPat3", "Nil") []
578 582
579 --mkTupPat :: [Pat] -> Pat 583 --mkTupPat :: [Pat] -> Pat
580 mkTupPat ns [x] = x 584 mkTupPat ns [PParens x] = ff [x]
581 mkTupPat ns ps = PCon (debugSI "", tick ns $ "Tuple" ++ show (length ps)) (ParPat . (:[]) <$> ps) 585 mkTupPat ns [x] = PParens x
586 mkTupPat ns ps = ff ps
587
588 ff ps = foldr (\a b -> PCon (mempty, "HCons") (ParPat . (:[]) <$> [a, b])) (PCon (mempty, "HNil") []) ps
582 589
583 patType p (Wildcard SType) = p 590 patType p (Wildcard SType) = p
584 patType p t = PatType (ParPat [p]) t 591 patType p t = PatType (ParPat [p]) t
@@ -590,6 +597,7 @@ longPattern = parsePat PrecAnn <&> (getPVars &&& id)
590 597
591telescopePat = fmap (getPPVars . ParPat . map snd &&& id) $ many $ uncurry f <$> hiddenTerm (parsePat PrecAtom) (parsePat PrecAtom) 598telescopePat = fmap (getPPVars . ParPat . map snd &&& id) $ many $ uncurry f <$> hiddenTerm (parsePat PrecAtom) (parsePat PrecAtom)
592 where 599 where
600 f h (PParens p) = second PParens $ f h p
593 f h (PatType (ParPat [p]) t) = ((h, t), p) 601 f h (PatType (ParPat [p]) t) = ((h, t), p)
594 f h p = ((h, Wildcard SType), p) 602 f h p = ((h, Wildcard SType), p)
595 603
@@ -636,8 +644,10 @@ compilePatts ps gu = cp [] ps
636 ] 644 ]
637 cp ps' ((p@PVar{}, i): xs) = cp (p: ps') xs 645 cp ps' ((p@PVar{}, i): xs) = cp (p: ps') xs
638 cp ps' ((p@(PCon (si, n) ps), i): xs) = GuardNode (SVar (si, n) $ i + sum (map (fromMaybe 0 . ff) ps')) n ps $ cp (p: ps') xs 646 cp ps' ((p@(PCon (si, n) ps), i): xs) = GuardNode (SVar (si, n) $ i + sum (map (fromMaybe 0 . ff) ps')) n ps $ cp (p: ps') xs
647 cp ps' ((PParens p, i): xs) = cp ps' ((p, i): xs)
639 cp ps' ((p@(ViewPat f (ParPat [PCon (si, n) ps])), i): xs) 648 cp ps' ((p@(ViewPat f (ParPat [PCon (si, n) ps])), i): xs)
640 = GuardNode (SAppV f $ SVar (si, n) $ i + sum (map (fromMaybe 0 . ff) ps')) n ps $ cp (p: ps') xs 649 = GuardNode (SAppV f $ SVar (si, n) $ i + sum (map (fromMaybe 0 . ff) ps')) n ps $ cp (p: ps') xs
650 cp _ p = error $ "cp: " ++ show p
641 651
642 m = length ps 652 m = length ps
643 653
@@ -670,8 +680,8 @@ compileGuardTree ulend lend adts t = (\x -> traceD (" ! :" ++ ppShow x) x) $ g
670 GuardLeaf e: _ -> lend e 680 GuardLeaf e: _ -> lend e
671 ts@(GuardNode f s _ _: _) -> case Map.lookup s (snd adts) of 681 ts@(GuardNode f s _ _: _) -> case Map.lookup s (snd adts) of
672 Nothing -> error $ "Constructor is not defined: " ++ s 682 Nothing -> error $ "Constructor is not defined: " ++ s
673 Just (Left ((t, inum), cns)) -> 683 Just (Left ((casename, inum), cns)) ->
674 foldl SAppV (SGlobal (debugSI "compileGuardTree2", caseName t) `SAppV` iterateN (1 + inum) SLamV (Wildcard SType)) 684 foldl SAppV (SGlobal (debugSI "compileGuardTree2", casename) `SAppV` iterateN (1 + inum) SLamV (Wildcard SType))
675 [ iterateN n SLamV $ guardTreeToCases $ Alts $ map (filterGuardTree (up n f) cn 0 n . upGT 0 n) ts 685 [ iterateN n SLamV $ guardTreeToCases $ Alts $ map (filterGuardTree (up n f) cn 0 n . upGT 0 n) ts
676 | (cn, n) <- cns 686 | (cn, n) <- cns
677 ] 687 ]
@@ -713,6 +723,7 @@ compileGuardTree ulend lend adts t = (\x -> traceD (" ! :" ++ ppShow x) x) $ g
713 guardNode v [] e = e 723 guardNode v [] e = e
714 guardNode v [w] e = case w of 724 guardNode v [w] e = case w of
715 PVar _ -> {-todo guardNode v (subst x v ws) $ -} varGuardNode 0 v e 725 PVar _ -> {-todo guardNode v (subst x v ws) $ -} varGuardNode 0 v e
726 PParens p -> guardNode v [p] e
716 ViewPat f (ParPat p) -> guardNode (f `SAppV` v) p {- $ guardNode v ws -} e 727 ViewPat f (ParPat p) -> guardNode (f `SAppV` v) p {- $ guardNode v ws -} e
717 PCon (_, s) ps' -> GuardNode v s ps' {- $ guardNode v ws -} e 728 PCon (_, s) ps' -> GuardNode v s ps' {- $ guardNode v ws -} e
718 729
@@ -725,7 +736,7 @@ compileCase ge x cs
725-------------------------------------------------------------------------------- declaration representation 736-------------------------------------------------------------------------------- declaration representation
726 737
727data Stmt 738data Stmt
728 = Let SIName MFixity (Maybe SExp) SExp 739 = Let SIName (Maybe SExp) SExp
729 | Data SIName [(Visibility, SExp)]{-parameters-} SExp{-type-} Bool{-True:add foralls-} [(SIName, SExp)]{-constructor names and types-} 740 | Data SIName [(Visibility, SExp)]{-parameters-} SExp{-type-} Bool{-True:add foralls-} [(SIName, SExp)]{-constructor names and types-}
730 | PrecDef SIName Fixity 741 | PrecDef SIName Fixity
731 742
@@ -737,7 +748,7 @@ data Stmt
737 | FunAlt SIName [((Visibility, SExp), Pat)] (Either [(SExp, SExp)]{-guards-} SExp{-no guards-}) 748 | FunAlt SIName [((Visibility, SExp), Pat)] (Either [(SExp, SExp)]{-guards-} SExp{-no guards-})
738 deriving (Show) 749 deriving (Show)
739 750
740pattern Primitive n mf t <- Let n mf (Just t) (SBuiltin "undefined") where Primitive n mf t = Let n mf (Just t) $ SBuiltin "undefined" 751pattern Primitive n t <- Let n (Just t) (SBuiltin "undefined") where Primitive n t = Let n (Just t) $ SBuiltin "undefined"
741 752
742-------------------------------------------------------------------------------- declaration parsing 753-------------------------------------------------------------------------------- declaration parsing
743 754
@@ -864,7 +875,7 @@ parseSomeGuards f = do
864mkLets :: DesugarInfo -> [Stmt]{-where block-} -> SExp{-main expression-} -> SExp{-big let with lambdas; replaces global names with de bruijn indices-} 875mkLets :: DesugarInfo -> [Stmt]{-where block-} -> SExp{-main expression-} -> SExp{-big let with lambdas; replaces global names with de bruijn indices-}
865mkLets ds = mkLets' . sortDefs ds where 876mkLets ds = mkLets' . sortDefs ds where
866 mkLets' [] e = e 877 mkLets' [] e = e
867 mkLets' (Let n _ mt x: ds) e 878 mkLets' (Let n mt x: ds) e
868 = SLet n (maybe id (flip SAnn . addForalls {-todo-}[] []) mt x') (substSG0 n $ mkLets' ds e) 879 = SLet n (maybe id (flip SAnn . addForalls {-todo-}[] []) mt x') (substSG0 n $ mkLets' ds e)
869 where 880 where
870 x' = if usedS n x then SBuiltin "primFix" `SAppV` SLamV (substSG0 n x) else x 881 x' = if usedS n x then SBuiltin "primFix" `SAppV` SLamV (substSG0 n x) else x
@@ -894,11 +905,11 @@ sortDefs ds xs = concatMap (desugarMutual ds) $ topSort mempty mempty mempty nod
894 nodes = zip (zip [0..] xs) $ map (def &&& need) xs 905 nodes = zip (zip [0..] xs) $ map (def &&& need) xs
895 need = \case 906 need = \case
896 PrecDef{} -> mempty 907 PrecDef{} -> mempty
897 Let _ _ mt e -> foldMap freeS' mt <> freeS' e 908 Let _ mt e -> foldMap freeS' mt <> freeS' e
898 Data _ ps t _ cs -> foldMap (freeS' . snd) ps <> freeS' t <> foldMap (freeS' . snd) cs 909 Data _ ps t _ cs -> foldMap (freeS' . snd) ps <> freeS' t <> foldMap (freeS' . snd) cs
899 def = \case 910 def = \case
900 PrecDef{} -> mempty 911 PrecDef{} -> mempty
901 Let n _ _ _ -> Set.singleton n 912 Let n _ _ -> Set.singleton n
902 Data n _ _ _ cs -> Set.singleton n <> Set.fromList (map fst cs) 913 Data n _ _ _ cs -> Set.singleton n <> Set.fromList (map fst cs)
903 freeS' = Set.fromList . freeS 914 freeS' = Set.fromList . freeS
904 topSort acc@(_:_) defs vs xs | Set.null vs = reverse acc: topSort mempty defs vs xs 915 topSort acc@(_:_) defs vs xs | Set.null vs = reverse acc: topSort mempty defs vs xs
@@ -946,15 +957,15 @@ compileFunAlts compilegt ds xs = dsInfo >>= \ge -> case xs of
946-- , let ts = fst $ getParamsS $ up1 t 957-- , let ts = fst $ getParamsS $ up1 t
947 , let as = [ FunAlt m p $ Right {- $ SLam Hidden (Wildcard SType) $ up1 -} $ SLet m' e $ SVar mempty 0 958 , let as = [ FunAlt m p $ Right {- $ SLam Hidden (Wildcard SType) $ up1 -} $ SLet m' e $ SVar mempty 0
948 | Instance n' i cstrs alts <- ds, n' == n 959 | Instance n' i cstrs alts <- ds, n' == n
949 , Let m' ~Nothing ~Nothing e <- alts, m' == m 960 , Let m' ~Nothing e <- alts, m' == m
950 , let p = zip ((,) Hidden <$> ps) i ++ [((Hidden, Wildcard SType), PVar (mempty, ""))] 961 , let p = zip ((,) Hidden <$> ps) i ++ [((Hidden, Wildcard SType), PVar (mempty, ""))]
951 -- , let ic = sum $ map varP i 962 -- , let ic = sum $ map varP i
952 ] 963 ]
953 ] 964 ]
954 return $ cd ++ concat cds 965 return $ cd ++ concat cds
955 [TypeAnn n t] -> return [Primitive n Nothing t | snd n `notElem` [n' | FunAlt (_, n') _ _ <- ds]] 966 [TypeAnn n t] -> return [Primitive n t | snd n `notElem` [n' | FunAlt (_, n') _ _ <- ds]]
956 tf@[TypeFamily n ps t] -> case [d | d@(FunAlt n' _ _) <- ds, n' == n] of 967 tf@[TypeFamily n ps t] -> case [d | d@(FunAlt n' _ _) <- ds, n' == n] of
957 [] -> return [Primitive n Nothing $ addParamsS ps t] 968 [] -> return [Primitive n $ addParamsS ps t]
958 alts -> compileFunAlts compileGuardTrees' [TypeAnn n $ addParamsS ps t] alts 969 alts -> compileFunAlts compileGuardTrees' [TypeAnn n $ addParamsS ps t] alts
959 [p@PrecDef{}] -> return [p] 970 [p@PrecDef{}] -> return [p]
960 fs@(FunAlt n vs _: _) -> case map head $ group [length vs | FunAlt _ vs _ <- fs] of 971 fs@(FunAlt n vs _: _) -> case map head $ group [length vs | FunAlt _ vs _ <- fs] of
@@ -963,7 +974,6 @@ compileFunAlts compilegt ds xs = dsInfo >>= \ge -> case xs of
963 | n `elem` [n' | TypeFamily n' _ _ <- ds] -> return [] 974 | n `elem` [n' | TypeFamily n' _ _ <- ds] -> return []
964 | otherwise -> return 975 | otherwise -> return
965 [ Let n 976 [ Let n
966 (listToMaybe [t | PrecDef n' t <- ds, n' == n])
967 (listToMaybe [t | TypeAnn n' t <- ds, n' == n]) 977 (listToMaybe [t | TypeAnn n' t <- ds, n' == n])
968 $ foldr (uncurry SLam . fst) (compilegt ge 978 $ foldr (uncurry SLam . fst) (compilegt ge
969 [ compilePatts (zip (map snd vs) $ reverse [0.. num - 1]) gsx 979 [ compilePatts (zip (map snd vs) $ reverse [0.. num - 1]) gsx
@@ -984,7 +994,7 @@ mkDesugarInfo :: [Stmt] -> DesugarInfo
984mkDesugarInfo ss = 994mkDesugarInfo ss =
985 ( Map.fromList $ ("'EqCTt", (Infix, -1)): [(s, f) | PrecDef (_, s) f <- ss] 995 ( Map.fromList $ ("'EqCTt", (Infix, -1)): [(s, f) | PrecDef (_, s) f <- ss]
986 , Map.fromList $ 996 , Map.fromList $
987 [(cn, Left ((t, pars ty), (snd *** pars) <$> cs)) | Data (_, t) ps ty _ cs <- ss, ((_, cn), ct) <- cs] 997 [hackHList (cn, Left ((caseName t, pars ty), (snd *** pars) <$> cs)) | Data (_, t) ps ty _ cs <- ss, ((_, cn), ct) <- cs]
988 ++ [(t, Right $ pars $ addParamsS ps ty) | Data (_, t) ps ty _ _ <- ss] 998 ++ [(t, Right $ pars $ addParamsS ps ty) | Data (_, t) ps ty _ _ <- ss]
989-- ++ [(t, Right $ length xs) | Let (_, t) _ (Just ty) xs _ <- ss] 999-- ++ [(t, Right $ length xs) | Let (_, t) _ (Just ty) xs _ <- ss]
990 ++ [("'Type", Right 0)] 1000 ++ [("'Type", Right 0)]
@@ -992,6 +1002,10 @@ mkDesugarInfo ss =
992 where 1002 where
993 pars ty = length $ filter ((== Visible) . fst) $ fst $ getParamsS ty -- todo 1003 pars ty = length $ filter ((== Visible) . fst) $ fst $ getParamsS ty -- todo
994 1004
1005 hackHList ("HCons", _) = ("HCons", Left (("hlistConsCase", 0), [("HCons", 2)]))
1006 hackHList ("HNil", _) = ("HNil", Left (("hlistNilCase", 0), [("HNil", 0)]))
1007 hackHList x = x
1008
995joinDesugarInfo (fm, cm) (fm', cm') = (Map.union fm fm', Map.union cm cm') 1009joinDesugarInfo (fm, cm) (fm', cm') = (Map.union fm fm', Map.union cm cm')
996 1010
997 1011
@@ -1181,6 +1195,9 @@ isAtom' = (<=PrecAtom') . getPrec
1181 1195
1182shAtom = PS PrecAtom 1196shAtom = PS PrecAtom
1183shAtom' = PS PrecAtom' 1197shAtom' = PS PrecAtom'
1198shTuple xs = prec PrecAtom $ \_ -> case xs of
1199 [x] -> "((" ++ str x ++ "))"
1200 xs -> "(" ++ intercalate ", " (map str xs) ++ ")"
1184shAnn _ True x y | str y `elem` ["Type", inGreen "Type"] = x 1201shAnn _ True x y | str y `elem` ["Type", inGreen "Type"] = x
1185shAnn s simp x y | isAtom x && isAtom y = shAtom' $ str x <> s <> str y 1202shAnn s simp x y | isAtom x && isAtom y = shAtom' $ str x <> s <> str y
1186shAnn s simp x y = prec PrecAnn $ lpar x <> " " <> const s <> " " <> rpar y 1203shAnn s simp x y = prec PrecAnn $ lpar x <> " " <> const s <> " " <> rpar y