summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorPéter Diviánszky <divipp@gmail.com>2016-04-16 17:57:13 +0200
committerPéter Diviánszky <divipp@gmail.com>2016-04-16 17:57:13 +0200
commit8aba7053836ba79b3fda3ca87d02b601c0cf2cb4 (patch)
treec0d0e36948b2e964fd8bca1d40744b12cb8f8edc /src
parent5d476c29e708a760521f9e7e52781ead35ad8f6e (diff)
refactoring
Diffstat (limited to 'src')
-rw-r--r--src/LambdaCube/Compiler/Infer.hs14
-rw-r--r--src/LambdaCube/Compiler/Lexer.hs90
-rw-r--r--src/LambdaCube/Compiler/Parser.hs20
3 files changed, 68 insertions, 56 deletions
diff --git a/src/LambdaCube/Compiler/Infer.hs b/src/LambdaCube/Compiler/Infer.hs
index 4a04564c..f68be803 100644
--- a/src/LambdaCube/Compiler/Infer.hs
+++ b/src/LambdaCube/Compiler/Infer.hs
@@ -137,9 +137,7 @@ data FName
137 | FSplit 137 | FSplit
138 deriving (Eq, Ord) 138 deriving (Eq, Ord)
139 139
140cFName mod i (RangeSI (Range fn (r, c) _), s) = fromMaybe (CFName n $ SData s) $ lookup s fntable 140cFName (RangeSI (Range fn p _), s) = fromMaybe (CFName (hashPos fn p) $ SData s) $ lookup s fntable
141 where
142 n = fileId fn * 2^32 + r * 2^16 + c * 2^3 -- + i
143 141
144fntable = 142fntable =
145 [ (,) "'VecScalar" FVecScalar 143 [ (,) "'VecScalar" FVecScalar
@@ -1221,14 +1219,12 @@ inference (x:xs) = do
1221 y <- handleStmt x 1219 y <- handleStmt x
1222 (y:) <$> withEnv y (inference xs) 1220 (y:) <$> withEnv y (inference xs)
1223 1221
1224modn = 0
1225
1226handleStmt :: MonadFix m => Stmt -> IM m GlobalEnv 1222handleStmt :: MonadFix m => Stmt -> IM m GlobalEnv
1227handleStmt = \case 1223handleStmt = \case
1228 Primitive n (trSExp' -> t_) -> do 1224 Primitive n (trSExp' -> t_) -> do
1229 t <- inferType =<< ($ t_) <$> addF 1225 t <- inferType =<< ($ t_) <$> addF
1230 tellType (fst n) t 1226 tellType (fst n) t
1231 addToEnv n $ flip (,) t $ lamify t $ Neut . DFun_ (FunName (cFName modn 0 n) Nothing t) 1227 addToEnv n $ flip (,) t $ lamify t $ Neut . DFun_ (FunName (cFName n) Nothing t)
1232 Let n mt t_ -> do 1228 Let n mt t_ -> do
1233 af <- addF 1229 af <- addF
1234 let t__ = maybe id (flip SAnn . af) mt t_ 1230 let t__ = maybe id (flip SAnn . af) mt t_
@@ -1251,7 +1247,7 @@ handleStmt = \case
1251 vty <- inferType $ addParamsS ps t_ 1247 vty <- inferType $ addParamsS ps t_
1252 tellType (fst s) vty 1248 tellType (fst s) vty
1253 let 1249 let
1254 sint = cFName modn 2 s 1250 sint = cFName s
1255 pnum' = length $ filter ((== Visible) . fst) ps 1251 pnum' = length $ filter ((== Visible) . fst) ps
1256 inum = arity vty - length ps 1252 inum = arity vty - length ps
1257 1253
@@ -1263,7 +1259,7 @@ handleStmt = \case
1263 let pars = zipWith (\x -> second $ STyped (debugSI "mkConstr1") . flip (,) TType . up_ (1+j) x) [0..] $ drop (length ps) $ fst $ getParams cty 1259 let pars = zipWith (\x -> second $ STyped (debugSI "mkConstr1") . flip (,) TType . up_ (1+j) x) [0..] $ drop (length ps) $ fst $ getParams cty
1264 act = length . fst . getParams $ cty 1260 act = length . fst . getParams $ cty
1265 acts = map fst . fst . getParams $ cty 1261 acts = map fst . fst . getParams $ cty
1266 conn = ConName (cFName modn 1 cn) j cty 1262 conn = ConName (cFName cn) j cty
1267 e <- addToEnv cn (Con conn 0 [], cty) 1263 e <- addToEnv cn (Con conn 0 [], cty)
1268 return (e, ((conn, cty) 1264 return (e, ((conn, cty)
1269 , addParamsS pars 1265 , addParamsS pars
@@ -1310,7 +1306,7 @@ withEnv e = local $ second (<> e)
1310mkELet n x xt = {-(if null vs then id else trace_ $ "mkELet " ++ show (length vs) ++ " " ++ show n)-} term 1306mkELet n x xt = {-(if null vs then id else trace_ $ "mkELet " ++ show (length vs) ++ " " ++ show n)-} term
1311 where 1307 where
1312 vs = [Var i | i <- Set.toList $ free x <> free xt] 1308 vs = [Var i | i <- Set.toList $ free x <> free xt]
1313 fn = FunName (cFName modn 5 n) (Just x) xt 1309 fn = FunName (cFName n) (Just x) xt
1314 1310
1315 term = pmLabel fn vs 0 [] $ getFix x 0 1311 term = pmLabel fn vs 0 [] $ getFix x 0
1316 1312
diff --git a/src/LambdaCube/Compiler/Lexer.hs b/src/LambdaCube/Compiler/Lexer.hs
index 6817f9ed..9a1ac44c 100644
--- a/src/LambdaCube/Compiler/Lexer.hs
+++ b/src/LambdaCube/Compiler/Lexer.hs
@@ -13,9 +13,11 @@ import Data.Monoid
13import Data.List 13import Data.List
14import Data.Char 14import Data.Char
15import Data.Function 15import Data.Function
16import Data.Bits
16import qualified Data.Set as Set 17import qualified Data.Set as Set
17import qualified Data.Map as Map 18import qualified Data.Map as Map
18import Control.Monad.RWS 19import Control.Monad.RWS
20import Control.Monad.Except
19import Control.Arrow hiding ((<+>)) 21import Control.Arrow hiding ((<+>))
20import Control.Applicative 22import Control.Applicative
21import Control.DeepSeq 23import Control.DeepSeq
@@ -25,7 +27,7 @@ import Text.Megaparsec
25import Text.Megaparsec as ParseUtils hiding (try, Message) 27import Text.Megaparsec as ParseUtils hiding (try, Message)
26import Text.Megaparsec.Lexer hiding (lexeme, symbol, negate) 28import Text.Megaparsec.Lexer hiding (lexeme, symbol, negate)
27 29
28import LambdaCube.Compiler.Pretty hiding (Doc, braces, parens) 30import LambdaCube.Compiler.Pretty hiding (braces, parens)
29 31
30-------------------------------------------------------------------------------- utils 32-------------------------------------------------------------------------------- utils
31 33
@@ -112,24 +114,39 @@ parseLit = lexeme (LChar <$> charLiteral <|> LString <$> stringLiteral <|> natFl
112-------------------------------------------------------------------------------- source infos 114-------------------------------------------------------------------------------- source infos
113 115
114-- source position without file name 116-- source position without file name
115type SourcePos' = (Int, Int) -- row, column; starts with (1, 1) 117data SPos = SPos
118 { row :: !Int -- 1, 2, 3, ...
119 , column :: !Int -- 1, 2, 3, ...
120 }
121 deriving (Eq, Ord)
122
123instance PShow SPos where
124 pShowPrec _ (SPos r c) = pShow r <> ":" <> pShow c
125
126toSPos :: SourcePos -> SPos
127toSPos p = SPos (sourceLine p) (sourceColumn p)
116 128
117toSourcePos' :: SourcePos -> SourcePos' 129getSPos = toSPos <$> getPosition
118toSourcePos' p = (sourceLine p, sourceColumn p)
119 130
120getPosition' = toSourcePos' <$> getPosition 131-------------
121 132
122data FileInfo = FileInfo 133data FileInfo = FileInfo
123 { fileId :: Int 134 { fileId :: !Int
124 , filePath :: FilePath 135 , filePath :: FilePath
125 , fileContent :: String 136 , fileContent :: String
126 } 137 }
127 138
128instance Eq FileInfo where (==) = (==) `on` fileId 139instance Eq FileInfo where (==) = (==) `on` fileId
129instance Ord FileInfo where compare = compare `on` fileId 140instance Ord FileInfo where compare = compare `on` fileId
130instance Show FileInfo where show = show . filePath
131 141
132data Range = Range !FileInfo !SourcePos' !SourcePos' 142instance PShow FileInfo where pShowPrec _ = text . filePath
143
144showPos :: FileInfo -> SPos -> Doc
145showPos n p = pShow n <> ":" <> pShow p
146
147-------------
148
149data Range = Range !FileInfo !SPos !SPos
133 deriving (Eq, Ord) 150 deriving (Eq, Ord)
134 151
135instance NFData Range where 152instance NFData Range where
@@ -137,15 +154,13 @@ instance NFData Range where
137 154
138-- short version 155-- short version
139instance PShow Range where 156instance PShow Range where
140 pShowPrec _ (Range n b e) = text (filePath n) <+> f b <> "-" <> f e 157 pShowPrec _ (Range n b e) = pShow n <+> pShow b <> "-" <> pShow e
141 where
142 f (r, c) = pShow r <> ":" <> pShow c
143 158
144-- long version 159-- long version
145showRange (Range n (r, c) (r', c')) = intercalate "\n" 160showRange (Range n p@(SPos r c) (SPos r' c')) = vcat
146 $ (showPos n (r, c) ++ ":") 161 $ (showPos n p <> ":")
147 : (drop (r - 1) $ take r' $ lines $ fileContent n) 162 : map text (drop (r - 1) $ take r' $ lines $ fileContent n)
148 ++ [replicate (c - 1) ' ' ++ replicate (c' - c) '^' | r' == r] 163 ++ [text $ replicate (c - 1) ' ' ++ replicate (c' - c) '^' | r' == r]
149 164
150joinRange :: Range -> Range -> Range 165joinRange :: Range -> Range -> Range
151joinRange (Range n b e) (Range n' b' e') {- | n == n' -} = Range n (min b b') (max e e') 166joinRange (Range n b e) (Range n' b' e') {- | n == n' -} = Range n (min b b') (max e e')
@@ -176,20 +191,17 @@ instance PShow SI where
176 191
177-- long version 192-- long version
178showSI (NoSI ds) = unwords $ Set.toList ds 193showSI (NoSI ds) = unwords $ Set.toList ds
179showSI (RangeSI r) = showRange r 194showSI (RangeSI r) = show $ showRange r
180
181showSourcePosSI (NoSI ds) = unwords $ Set.toList ds
182showSourcePosSI (RangeSI (Range n p _)) = showPos n p
183
184showPos n (r, c) = filePath n ++ ":" ++ show r ++ ":" ++ show c
185 195
186-- TODO: remove 196hashPos :: FileInfo -> SPos -> Int
187validSI RangeSI{} = True 197hashPos fn (SPos r c) = fileId fn `shiftL` 32 .|. r `shiftL` 16 .|. c
188validSI _ = False
189 198
190debugSI a = NoSI (Set.singleton a) 199debugSI a = NoSI (Set.singleton a)
191 200
192si@(RangeSI r) `validate` xs | all validSI xs && r `notElem` [r | RangeSI r <- xs] = si 201si@(RangeSI r) `validate` xs | all validSI xs && r `notElem` [r | RangeSI r <- xs] = si
202 where
203 validSI RangeSI{} = True
204 validSI _ = False
193_ `validate` _ = mempty 205_ `validate` _ = mempty
194 206
195sourceNameSI (RangeSI (Range n _ _)) = n 207sourceNameSI (RangeSI (Range n _ _)) = n
@@ -210,7 +222,7 @@ class SetSourceInfo a where
210 setSI :: SI -> a -> a 222 setSI :: SI -> a -> a
211 223
212appRange :: Parse r w (SI -> a) -> Parse r w a 224appRange :: Parse r w (SI -> a) -> Parse r w a
213appRange p = (\fi p1 a p2 -> a $ RangeSI $ Range fi p1 p2) <$> asks fileInfo <*> getPosition' <*> p <*> get 225appRange p = (\fi p1 a p2 -> a $ RangeSI $ Range fi p1 p2) <$> asks fileInfo <*> getSPos <*> p <*> get
214 226
215type SIName = (SI, SName) 227type SIName = (SI, SName)
216 228
@@ -220,14 +232,14 @@ data ParseEnv x = ParseEnv
220 { fileInfo :: FileInfo 232 { fileInfo :: FileInfo
221 , desugarInfo :: x 233 , desugarInfo :: x
222 , namespace :: Namespace 234 , namespace :: Namespace
223 , indentationLevel :: SourcePos' 235 , indentationLevel :: SPos
224 } 236 }
225 237
226type Parse r w = ParsecT String (RWS (ParseEnv r) [w] SourcePos') 238type Parse r w = ParsecT String (RWS (ParseEnv r) [w] SPos)
227 239
228runParse env p = (\(a, s, w) -> (a, w)) $ runRWS p env (1, 1) 240runParse env p = (\(a, s, w) -> (a, w)) $ runRWS p env (SPos 1 1)
229 241
230parseString fi di p s = runParse (ParseEnv fi di ExpNS (0, 0)) $ runParserT p (filePath fi) s 242parseString fi di p s = runParse (ParseEnv fi di ExpNS (SPos 0 0)) $ runParserT p (filePath fi) s
231 243
232getParseState = (,) <$> asks desugarInfo <*> ((,,,) <$> asks fileInfo <*> asks namespace <*> asks indentationLevel <*> getParserState) 244getParseState = (,) <$> asks desugarInfo <*> ((,,,) <$> asks fileInfo <*> asks namespace <*> asks indentationLevel <*> getParserState)
233 245
@@ -236,21 +248,21 @@ parseWithState p (di, (fi, ns, l, st)) = runParse (ParseEnv fi di ns l) $ runPar
236----------------------------------------------------------- indentation, white space, symbols 248----------------------------------------------------------- indentation, white space, symbols
237 249
238checkIndent = do 250checkIndent = do
239 (r, c) <- asks indentationLevel 251 (SPos r c) <- asks indentationLevel
240 p@(r', c') <- getPosition' 252 p@(SPos r' c') <- getSPos
241 if (c' <= c && r' > r) then fail "wrong indentation" else return p 253 if (c' <= c && r' > r) then fail "wrong indentation" else return p
242 254
243identation allowempty p = (if allowempty then option [] else id) $ do 255identation allowempty p = (if allowempty then option [] else id) $ do
244 (_, c) <- checkIndent 256 (SPos _ c) <- checkIndent
245 (if allowempty then many else some) $ do 257 (if allowempty then many else some) $ do
246 pos@(_, c') <- getPosition' 258 pos@(SPos _ c') <- getSPos
247 guard (c' == c) 259 guard (c' == c)
248 local (\e -> e {indentationLevel = pos}) p 260 local (\e -> e {indentationLevel = pos}) p
249 261
250lexemeWithoutSpace p = do 262lexemeWithoutSpace p = do
251 p1 <- checkIndent 263 p1 <- checkIndent
252 x <- p 264 x <- p
253 p2 <- getPosition' 265 p2 <- getSPos
254 put p2 266 put p2
255 fi <- asks fileInfo 267 fi <- asks fileInfo
256 return (RangeSI $ Range fi p1 p2, x) 268 return (RangeSI $ Range fi p1 p2, x)
@@ -393,20 +405,20 @@ type Fixity = (FixityDef, Int)
393type FixityMap = Map.Map SName Fixity 405type FixityMap = Map.Map SName Fixity
394 406
395calcPrec 407calcPrec
396 :: (Show e, Show f) 408 :: (Show e, Show f, MonadError String m)
397 => (f -> e -> e -> e) 409 => (f -> e -> e -> e)
398 -> (f -> Fixity) 410 -> (f -> Fixity)
399 -> e 411 -> e
400 -> [(f, e)] 412 -> [(f, e)]
401 -> e 413 -> m e
402calcPrec app getFixity e = compileOps [((Infix, -1000), error "calcPrec", e)] 414calcPrec app getFixity e = compileOps [((Infix, -1000), error "calcPrec", e)]
403 where 415 where
404 compileOps [(_, _, e)] [] = e 416 compileOps [(_, _, e)] [] = return e
405 compileOps acc [] = compileOps (shrink acc) [] 417 compileOps acc [] = compileOps (shrink acc) []
406 compileOps acc@((p, g, e1): ee) es_@((op, e'): es) = case compareFixity (pr, op) (p, g) of 418 compileOps acc@((p, g, e1): ee) es_@((op, e'): es) = case compareFixity (pr, op) (p, g) of
407 Right GT -> compileOps ((pr, op, e'): acc) es 419 Right GT -> compileOps ((pr, op, e'): acc) es
408 Right LT -> compileOps (shrink acc) es_ 420 Right LT -> compileOps (shrink acc) es_
409 Left err -> error err 421 Left err -> throwError err
410 where 422 where
411 pr = getFixity op 423 pr = getFixity op
412 424
diff --git a/src/LambdaCube/Compiler/Parser.hs b/src/LambdaCube/Compiler/Parser.hs
index e8f59fad..ca9570b4 100644
--- a/src/LambdaCube/Compiler/Parser.hs
+++ b/src/LambdaCube/Compiler/Parser.hs
@@ -487,20 +487,21 @@ parseTerm_ prec = case prec of
487 mkDotDot e f = SBuiltin "fromTo" `SAppV` e `SAppV` f 487 mkDotDot e f = SBuiltin "fromTo" `SAppV` e `SAppV` f
488 488
489 calculatePrecs :: DesugarInfo -> [Either SIName SExp] -> P SExp 489 calculatePrecs :: DesugarInfo -> [Either SIName SExp] -> P SExp
490 calculatePrecs dcls = either fail return . f where 490 calculatePrecs dcls = f where
491 f [] = error "impossible" 491 f [] = error "impossible"
492 f (Right t: xs) = either (\(op, xs) -> Section $ SLamV $ SGlobal op `SAppV` up1 (calcPrec' t xs) `SAppV` SVar (mempty, ".rs") 0) (calcPrec' t) <$> cont xs 492 f (Right t: xs) = join $ either (\(op, xs) -> calcPrec' t xs <&> \z -> Section $ SLamV $ SGlobal op `SAppV` up1 z `SAppV` SVar (mempty, ".rs") 0) (calcPrec' t) <$> cont xs
493 f xs@(Left op@(_, "-"): _) = f $ Right (mkLit $ LInt 0): xs 493 f xs@(Left op@(_, "-"): _) = f $ Right (mkLit $ LInt 0): xs
494 f (Left op: xs) = g op xs >>= either (const $ Left "TODO: better error message @476") 494 f (Left op: xs) = g op xs >>= either (const $ fail "TODO: better error message @476")
495 (\((op, e): oe) -> return $ Section $ SLamV $ SGlobal op `SAppV` SVar (mempty, ".ls") 0 `SAppV` up1 (calcPrec' e oe)) 495 (\((op, e): oe) -> calcPrec' e oe <&> \z -> Section $ SLamV $ SGlobal op `SAppV` SVar (mempty, ".ls") 0 `SAppV` up1 z)
496
496 g op (Right t: xs) = (second ((op, t):) +++ ((op, t):)) <$> cont xs 497 g op (Right t: xs) = (second ((op, t):) +++ ((op, t):)) <$> cont xs
497 g op [] = return $ Left (op, []) 498 g op [] = return $ Left (op, [])
498 g op _ = Left "two operator is not allowed next to each-other" 499 g op _ = fail "two operator is not allowed next to each-other"
499 cont (Left op: xs) = g op xs 500 cont (Left op: xs) = g op xs
500 cont [] = return $ Right [] 501 cont [] = return $ Right []
501 cont _ = error "impossible" 502 cont _ = error "impossible"
502 503
503 calcPrec' = calcPrec (\op x y -> SGlobal op `SAppV` x `SAppV` y) (getFixity dcls . snd) 504 calcPrec' = (postponedCheck .) . calcPrec (\op x y -> SGlobal op `SAppV` x `SAppV` y) (getFixity dcls . snd)
504 505
505 generator, letdecl, boolExpression :: P (SExp -> SExp) 506 generator, letdecl, boolExpression :: P (SExp -> SExp)
506 generator = do 507 generator = do
@@ -601,7 +602,7 @@ parsePat = \case
601 PrecAnn -> 602 PrecAnn ->
602 patType <$> parsePat PrecOp <*> parseType (Just $ Wildcard SType) 603 patType <$> parsePat PrecOp <*> parseType (Just $ Wildcard SType)
603 PrecOp -> 604 PrecOp ->
604 calculatePatPrecs <$> dsInfo <*> p_ 605 join $ calculatePatPrecs <$> dsInfo <*> p_
605 where 606 where
606 p_ = (,) <$> parsePat PrecApp <*> option [] (colonSymbols >>= p) 607 p_ = (,) <$> parsePat PrecApp <*> option [] (colonSymbols >>= p)
607 p op = do (exp, op') <- try "pattern" ((,) <$> parsePat PrecApp <*> colonSymbols) 608 p op = do (exp, op') <- try "pattern" ((,) <$> parsePat PrecApp <*> colonSymbols)
@@ -647,7 +648,7 @@ parsePat = \case
647 patType p (Wildcard SType) = p 648 patType p (Wildcard SType) = p
648 patType p t = PatType (ParPat [p]) t 649 patType p t = PatType (ParPat [p]) t
649 650
650 calculatePatPrecs dcls (e, xs) = calcPrec (\op x y -> PCon op $ ParPat . (:[]) <$> [x, y]) (getFixity dcls . snd) e xs 651 calculatePatPrecs dcls (e, xs) = postponedCheck $ calcPrec (\op x y -> PCon op $ ParPat . (:[]) <$> [x, y]) (getFixity dcls . snd) e xs
651 652
652longPattern = parsePat PrecAnn <&> (getPVars &&& id) 653longPattern = parsePat PrecAnn <&> (getPVars &&& id)
653--patternAtom = parsePat PrecAtom <&> (getPVars &&& id) 654--patternAtom = parsePat PrecAtom <&> (getPVars &&& id)
@@ -665,6 +666,9 @@ checkPattern ns = lift $ tell $ pure $
665 [] -> Nothing 666 [] -> Nothing
666 xs -> Just $ "multiple pattern vars:\n" ++ unlines [n ++ " is defined at " ++ ppShow si | ns <- xs, (si, n) <- ns] 667 xs -> Just $ "multiple pattern vars:\n" ++ unlines [n ++ " is defined at " ++ ppShow si | ns <- xs, (si, n) <- ns]
667 668
669postponedCheck x = do
670 lift $ tell [either Just (const Nothing) x]
671 return $ either (const $ error "impossible") id x
668 672
669-------------------------------------------------------------------------------- pattern match compilation 673-------------------------------------------------------------------------------- pattern match compilation
670 674