on master help sign in
Add support for exponent notation for floating point numbers
05c8e0eEvan Czaplicki
compiler/Parse/Literal.hs+30−12
@@ -1,4 +1,4 @@
1−{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind #-}
1+{-# OPTIONS_GHC -W #-}
2module Parse.Literal (literal) where
2module Parse.Literal (literal) where
3
3
4import Control.Applicative ((<$>))
4import Control.Applicative ((<$>))
@@ -7,16 +7,34 @@ import Parse.Helpers
7import SourceSyntax.Literal
7import SourceSyntax.Literal
8
8
9literal :: IParser Literal
9literal :: IParser Literal
10−literal = num <|> (Str <$> str) <|> (Chr <$> chr)
10+literal = num <|> (Str <$> str) <|> (Chr <$> chr) <?> "literal"
11
11
12num :: IParser Literal
12num :: IParser Literal
13−num = fmap toLit (preNum <?> "number")
13+num = toLit <$> (number <?> "number")
14+ where
15+ toLit n
14− where toLit n | '.' `elem` n = FloatNum (read n)
16+ | any (`elem` ".eE") n = FloatNum (read n)
15− | otherwise = IntNum (read n)
17+ | otherwise = IntNum (read n)
16− preNum = concat <$> sequence [ option "" minus, many1 digit, option "" postNum ]
18+
19+ number = concat <$> sequence
20+ [ option "" minus
21+ , many1 digit
22+ , option "" decimals
23+ , option "" exponent ]
24+
25+ minus = try $ do
26+ string "-"
27+ lookAhead digit
28+ return "-"
29+
30+ decimals = do
17− postNum = do try $ lookAhead (string "." >> digit)
31+ try $ lookAhead (string "." >> digit)
18− string "."
32+ string "."
19− ('.':) <$> many1 digit
33+ n <- many1 digit
20− minus = try $ do string "-"
34+ return ('.' : n)
35+
36+ exponent = do
37+ string "e" <|> string "E"
38+ op <- option "" (string "+" <|> string "-")
21− lookAhead digit
39+ n <- many1 digit
22− return "-"
40+ return ('e' : op ++ n)