attoparsec-0.10.4.0: Fast combinator parsing for bytestrings and text

Portability | unknown
Stability | experimental
Maintainer | bos@serpentine.com
Safe Haskell | None

Data.Attoparsec.Text

Contents

- Differences from Parsec
- Incremental input
- Performance considerations
- Parser types
- Running parsers
  - Result conversion
- Combinators
- Parsing individual characters
  - Special character parsers
  - Character classes
- Efficient string handling
  - String combinators
  - Consume all remaining input
- Text parsing
- Numeric parsers
- State observation and manipulation functions

Description

Simple, efficient combinator parsing for `Text` strings, loosely based on the Parsec library.

Synopsis

- type Parser = Parser Text
- type Result = IResult Text
- data IResult t r
  - = Fail t [String] String
  - | Partial (t -> IResult t r)
  - | Done t r
- compareResults :: (Eq t, Eq r) => IResult t r -> IResult t r -> Maybe Bool
- parse :: Parser a -> Text -> Result a
- feed :: Result r -> Text -> Result r
- parseOnly :: Parser a -> Text -> Either String a
- parseWith :: Monad m => m Text -> Parser a -> Text -> m (Result a)
- parseTest :: Show a => Parser a -> Text -> IO ()
- maybeResult :: Result r -> Maybe r
- eitherResult :: Result r -> Either String r
- (<?>) :: Parser a -> String -> Parser a
- try :: Parser a -> Parser a
- module Data.Attoparsec.Combinator
- char :: Char -> Parser Char
- anyChar :: Parser Char
- notChar :: Char -> Parser Char
- satisfy :: (Char -> Bool) -> Parser Char
- satisfyWith :: (Char -> a) -> (a -> Bool) -> Parser a
- skip :: (Char -> Bool) -> Parser ()
- peekChar :: Parser (Maybe Char)
- digit :: Parser Char
- letter :: Parser Char
- space :: Parser Char
- inClass :: String -> Char -> Bool
- notInClass :: String -> Char -> Bool
- string :: Text -> Parser Text
- stringCI :: Text -> Parser Text
- asciiCI :: Text -> Parser Text
- skipSpace :: Parser ()
- skipWhile :: (Char -> Bool) -> Parser ()
- scan :: s -> (s -> Char -> Maybe s) -> Parser Text
- take :: Int -> Parser Text
- takeWhile :: (Char -> Bool) -> Parser Text
- takeWhile1 :: (Char -> Bool) -> Parser Text
- takeTill :: (Char -> Bool) -> Parser Text
- (.*>) :: Text -> Parser a -> Parser a
- (<*.) :: Parser a -> Text -> Parser a
- takeText :: Parser Text
- takeLazyText :: Parser Text
- endOfLine :: Parser ()
- isEndOfLine :: Char -> Bool
- isHorizontalSpace :: Char -> Bool
- decimal :: Integral a => Parser a
- hexadecimal :: (Integral a, Bits a) => Parser a
- signed :: Num a => Parser a -> Parser a
- double :: Parser Double
- data Number
  - = I !Integer
  - | D !Double
- number :: Parser Number
- rational :: Fractional a => Parser a
- endOfInput :: Parser ()
- atEnd :: Parser Bool

# Differences from Parsec

Compared to Parsec 3, Attoparsec makes several tradeoffs. It is not intended for, or ideal for, all possible uses.

- While Attoparsec can consume input incrementally, Parsec cannot. Incremental input is a huge deal for efficient and secure network and system programming, since it gives much more control to users of the library over matters such as resource usage and the I/O model to use.
- Much of the performance advantage of Attoparsec is gained via high-performance parsers such as `takeWhile` and `string`. If you use complicated combinators that return lists of characters, there is less performance difference between the two libraries.
- Unlike Parsec 3, Attoparsec does not support being used as a monad transformer.
- Attoparsec is specialised to deal only with strict `Text` input. Efficiency concerns rule out both lists and lazy text. The usual use for lazy text would be to allow consumption of very large input without a large footprint. For this need, Attoparsec's incremental input provides an excellent substitute, with much more control over when input takes place. If you must use lazy text, see the `Lazy` module, which feeds lazy chunks to a regular parser.
- Parsec parsers can produce more helpful error messages than Attoparsec parsers. This is a matter of focus: Attoparsec avoids the extra book-keeping in favour of higher performance.

# Incremental input

Attoparsec supports incremental input, meaning that you can feed it a `Text` that represents only part of the expected total amount of data to parse. If your parser reaches the end of a fragment of input and could consume more input, it will suspend parsing and return a `Partial` continuation.

Supplying the `Partial` continuation with another string will resume parsing at the point where it was suspended. You must be prepared for the result of the resumed parse to be another `Partial` continuation.

To indicate that you have no more input, supply the `Partial` continuation with an `empty` `Text`.

Remember that some parsing combinators will not return a result until they reach the end of input. They may thus cause `Partial` results to be returned.

If you do not need support for incremental input, consider using the `parseOnly` function to run your parser. It will never prompt for more input.

# Performance considerations

If you write an Attoparsec-based parser carefully, it can be realistic to expect it to perform within a factor of 2 of a hand-rolled C parser (measuring megabytes parsed per second).

To actually achieve high performance, there are a few guidelines that it is useful to follow.

Use the `Text`-oriented parsers whenever possible, e.g. `takeWhile1` instead of `many1` `anyChar`. There is about a factor of 100 difference in performance between the two kinds of parser.

For very simple character-testing predicates, write them by hand instead of using `inClass` or `notInClass`. For instance, both of these predicates test for an end-of-line character, but the first is much faster than the second:

    endOfLine_fast c = c == '\r' || c == '\n'
    endOfLine_slow   = inClass "\r\n"

Make active use of benchmarking and profiling tools to measure, find the problems with, and improve the performance of your parser.

# Parser types

type Parser = Parser Text Source

type Result = IResult Text Source

data IResult t r Source

The result of a parse. This is parameterised over the type `t` of string that was processed.

This type is an instance of `Functor`, where `fmap` transforms the value in a `Done` result.

Constructors

Fail t [String] String | The parse failed. The `t` parameter is the input that had not yet been consumed when the failure occurred. The `[``String``]` is a list of contexts in which the error occurred. The `String` is the message describing the error, if any.
Partial (t -> IResult t r) | Supply this continuation with more input so that the parser can resume. To indicate that no more input is available, use an empty string.
Done t r | The parse succeeded. The `t` parameter is the input that had not yet been consumed (if any) when the parse succeeded.

Instances

Functor (IResult t) |
(Show t, Show r) => Show (IResult t r) |
(NFData t, NFData r) => NFData (IResult t r) |

compareResults :: (Eq t, Eq r) => IResult t r -> IResult t r -> Maybe Bool Source

Compare two `IResult` values for equality.

If both `IResult`s are `Partial`, the result will be `Nothing`, as they are incomplete and hence their equality cannot be known. (This is why there is no `Eq` instance for `IResult`.)

# Running parsers

parse :: Parser a -> Text -> Result aSource

Run a parser.

feed :: Result r -> Text -> Result rSource

If a parser has returned a `Partial` result, supply it with more input.

parseOnly :: Parser a -> Text -> Either String aSource

Run a parser that cannot be resupplied via a `Partial` result.

parseWith Source

Arguments

:: Monad m |
=> m Text | An action that will be executed to provide the parser with more input, if necessary. The action must return an `empty` string when there is no more input available.
-> Parser a |
-> Text | Initial input for the parser.
-> m (Result a) |

Run a parser with an initial input string, and a monadic action that can supply more input if needed.

parseTest :: Show a => Parser a -> Text -> IO ()Source

Run a parser and print its result to standard output.

## Result conversion

maybeResult :: Result r -> Maybe rSource

Convert a `Result` value to a `Maybe` value. A `Partial` result is treated as failure.

eitherResult :: Result r -> Either String rSource

Convert a `Result` value to an `Either` value. A `Partial` result is treated as failure.

# Combinators

(<?>)Source

Arguments

:: Parser a |
-> String | the name to use if parsing fails
-> Parser a |

Name the parser, in case failure occurs.

try :: Parser a -> Parser aSource

Attempt a parse, and if it fails, rewind the input so that no input appears to have been consumed.

This combinator is provided for compatibility with Parsec. Attoparsec parsers always backtrack on failure.

module Data.Attoparsec.Combinator

# Parsing individual characters

char :: Char -> Parser Char Source

Match a specific character.

anyChar :: Parser Char Source

Match any character.

notChar :: Char -> Parser Char Source

Match any character except the given one.

satisfy :: (Char -> Bool) -> Parser Char Source

The parser `satisfy p` succeeds for any character for which the predicate `p` returns `True`. Returns the character that is actually parsed.

    digit = satisfy isDigit
        where isDigit c = c >= '0' && c <= '9'

satisfyWith :: (Char -> a) -> (a -> Bool) -> Parser aSource

The parser `satisfyWith f p` transforms a character, and succeeds if the predicate `p` returns `True` on the transformed value. The parser returns the transformed character that was parsed.

skip :: (Char -> Bool) -> Parser ()Source

The parser `skip p` succeeds for any character for which the predicate `p` returns `True`.

    skipDigit = skip isDigit
        where isDigit c = c >= '0' && c <= '9'

peekChar :: Parser (Maybe Char)Source

Match any character. Returns `Nothing` if end of input has been reached. Does not consume any input.

Note: Because this parser does not fail, do not use it with combinators such as `many`, because such parsers loop until a failure occurs. Careless use will thus result in an infinite loop.

## Special character parsers

digit :: Parser Char Source

Parse a single digit, as recognised by `isDigit`.

letter :: Parser Char Source

Parse a letter, as recognised by `isAlpha`.

space :: Parser Char Source

Parse a space character, as recognised by `isSpace`.

## Character classes

inClass :: String -> Char -> Bool Source

Match any character in a set.

    vowel = inClass "aeiou"

Range notation is supported.

    halfAlphabet = inClass "a-nA-N"

To add a literal `'-'` to a set, place it at the beginning or end of the string.

notInClass :: String -> Char -> Bool Source

Match any character not in a set.

# Efficient string handling

string :: Text -> Parser Text Source

`string s` parses a sequence of characters that identically match `s`. Returns the parsed string (i.e. `s`). This parser consumes no input if it fails (even if a partial match).

Note: The behaviour of this parser is different to that of the similarly-named parser in Parsec, as this one is all-or-nothing. To illustrate the difference, the following parser will fail under Parsec given an input of `"for"`:

    string "foo" <|> string "for"

The reason for its failure is that the first branch is a partial match, and will consume the letters `'f'` and `'o'` before failing. In Attoparsec, the above parser will succeed on that input, because the failed first branch will consume nothing.

stringCI :: Text -> Parser Text Source

Deprecated: this is very inefficient, use asciiCI instead

Satisfy a literal string, ignoring case.

Note: this function is currently quite inefficient. Unicode case folding can change the length of a string ("ß" becomes ss), which makes a simple, efficient implementation tricky. We have (for now) chosen simplicity over efficiency.

asciiCI :: Text -> Parser Text Source

Satisfy a literal string, ignoring case for characters in the ASCII range.

skipSpace :: Parser ()Source

Skip over white space.

skipWhile :: (Char -> Bool) -> Parser ()Source

Skip past input for as long as the predicate returns `True`.

scan :: s -> (s -> Char -> Maybe s) -> Parser Text Source

A stateful scanner. The predicate consumes and transforms a state argument, and each transformed state is passed to successive invocations of the predicate on each character of the input until one returns `Nothing` or the input ends.

This parser does not fail. It will return an empty string if the predicate returns `Nothing` on the first character of input.

Note: Because this parser does not fail, do not use it with combinators such as `many`, because such parsers loop until a failure occurs. Careless use will thus result in an infinite loop.

take :: Int -> Parser Text Source

Consume exactly `n` characters of input.

takeWhile :: (Char -> Bool) -> Parser Text Source

Consume input as long as the predicate returns `True`, and return the consumed input.

This parser does not fail. It will return an empty string if the predicate returns `False` on the first character of input.

Note: Because this parser does not fail, do not use it with combinators such as `many`, because such parsers loop until a failure occurs. Careless use will thus result in an infinite loop.

takeWhile1 :: (Char -> Bool) -> Parser Text Source

Consume input as long as the predicate returns `True`, and return the consumed input.

This parser requires the predicate to succeed on at least one character of input: it will fail if the predicate never returns `True` or if there is no input left.

takeTill :: (Char -> Bool) -> Parser Text Source

Consume input as long as the predicate returns `False` (i.e. until it returns `True`), and return the consumed input.

This parser does not fail. It will return an empty string if the predicate returns `True` on the first character of input.

Note: Because this parser does not fail, do not use it with combinators such as `many`, because such parsers loop until a failure occurs. Careless use will thus result in an infinite loop.

## String combinators

The `.*>` and `<*.` combinators are intended for use with the `OverloadedStrings` language extension. They simplify the common task of matching a statically known string, then immediately parsing something else.

An example makes this easier to understand:

    {-# LANGUAGE OverloadedStrings #-}

    shoeSize = "Shoe size: " .*> decimal

If we were to try to use `*>` above instead, the type checker would not be able to tell which `IsString` instance to use for the text in quotes. We would have to be explicit, using either a type signature or the `string` parser.

(.*>) :: Text -> Parser a -> Parser aSource

Type-specialized version of `*>` for `Text`.

(<*.) :: Parser a -> Text -> Parser aSource

Type-specialized version of `<*` for `Text`.

## Consume all remaining input

takeText :: Parser Text Source

Consume all remaining input and return it as a single string.

takeLazyText :: Parser Text Source

Consume all remaining input and return it as a single string.

# Text parsing

endOfLine :: Parser ()Source

Match either a single newline character `'\n'`, or a carriage return followed by a newline character `"\r\n"`.

isEndOfLine :: Char -> Bool Source

A predicate that matches either a carriage return `'\r'` or newline `'\n'` character.

isHorizontalSpace :: Char -> Bool Source

A predicate that matches either a space `' '` or horizontal tab `'\t'` character.

# Numeric parsers

decimal :: Integral a => Parser aSource

Parse and decode an unsigned decimal number.

hexadecimal :: (Integral a, Bits a) => Parser aSource

Parse and decode an unsigned hexadecimal number. The hex digits `'a'` through `'f'` may be upper or lower case.

This parser does not accept a leading `"0x"` string.

signed :: Num a => Parser a -> Parser aSource

Parse a number with an optional leading `'+'` or `'-'` sign character.

double :: Parser Double Source

Parse a rational number.

The syntax accepted by this parser is the same as for `rational`.

Note: This function is almost ten times faster than `rational`, but is slightly less accurate.

The `Double` type supports about 16 decimal places of accuracy. For 94.2% of numbers, this function and `rational` give identical results, but for the remaining 5.8%, this function loses precision around the 15th decimal place. For 0.001% of numbers, this function will lose precision at the 13th or 14th decimal place.

This function does not accept string representations of "NaN" or "Infinity".

data Number Source

A numeric type that can represent integers accurately, and floating point numbers to the precision of a `Double`.

Constructors

I !Integer |
D !Double |

Instances

Eq Number |
Fractional Number |
Data Number |
Num Number |
Ord Number |
Real Number |
RealFrac Number |
Show Number |
Typeable Number |
NFData Number |

number :: Parser Number Source

Parse a number, attempting to preserve both speed and precision.

The syntax accepted by this parser is the same as for `rational`.

Note: This function is almost ten times faster than `rational`. On integral inputs, it gives perfectly accurate answers, and on floating point inputs, it is slightly less accurate than `rational`.

This function does not accept string representations of "NaN" or "Infinity".

rational :: Fractional a => Parser aSource

Parse a rational number.

This parser accepts an optional leading sign character, followed by at least one decimal digit. The syntax similar to that accepted by the `read` function, with the exception that a trailing `'.'` or `'e'` not followed by a number is not consumed.

Examples with behaviour identical to `read`, if you feed an empty continuation to the first result:

    rational "3"     == Done 3.0 ""
    rational "3.1"   == Done 3.1 ""
    rational "3e4"   == Done 30000.0 ""
    rational "3.1e4" == Done 31000.0, ""

Examples with behaviour identical to `read`:

    rational ".3"    == Fail "input does not start with a digit"
    rational "e3"    == Fail "input does not start with a digit"

Examples of differences from `read`:

    rational "3.foo" == Done 3.0 ".foo"
    rational "3e"    == Done 3.0 "e"

This function does not accept string representations of "NaN" or "Infinity".

# State observation and manipulation functions

endOfInput :: Parser ()Source

Match only if all input has been consumed.

atEnd :: Parser Bool Source

Return an indication of whether the end of input has been reached.