elm / parser

A parsing library, focused on simplicity and great error messages
https://package.elm-lang.org/packages/elm/parser/latest
BSD 3-Clause "New" or "Revised" License
230 stars 46 forks source link

Float parser comitting to leading 'e' #44

Open j-maas opened 4 years ago

j-maas commented 4 years ago

Similar to #28, the float parser comitts when it encounters an 'e', making it impossible to have a parser that reads either a float or some text:

floatOrText =
    oneOf
        [ float |> map (\n -> "Number: " ++ String.fromFloat n)
        , chompUntilEndOr "\n" |> getChompedString
    ]

run floatOrText "not starting with e" --> Ok "not starting with e"
run floatOrText "1e10" --> Ok "Number: 10000000000"
run floatOrText "e should be text" --> Err: ExpectingFloat

(Try it on Ellie: https://ellie-app.com/8yp6MxtzSsna1)

j-maas commented 4 years ago

As a workaround, one can define their own float parser:

{-| The built-in float parser has a bug with leading 'e'.
See <https://github.com/elm/parser/issues/44>
-}
parseFloat : Parser Float
parseFloat =
    {- By making it backtrackable, even if the input start with an 'e',
       we will be able to try out other alternatives instead of getting
       stuck on it as an invalid number.
    -}
    Parser.backtrackable <| Parser.float ExpectingFloat InvalidNumber
AlienKevin commented 4 years ago

int parser has the same problem of committing the leading 'e'

dwayne commented 2 years ago

I ran in to this same problem:

term : Parser Expr
term =
  P.oneOf
    [ P.succeed Number
        |= number
    , P.succeed EParam
        |= param
    ]

Given,

Parser.run term "E"

it returns

Err [{ col = 2, problem = ExpectingInt, row = 1 }]

instead of

Ok (EParam "E")