HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Moduleparsers-megaparsec-0.1.0.2Haskell2010

Text.Megaparsec.Parsers

A newtype wrapper for ParsecT that has instances of Parsing, CharParsing, LookAheadParsing, and TokenParsing.

Parsing and LookAheadParsing have instances for any Stream instance.

CharParsing and TokenParsing only have instances for String, strict Text, and lazy Text, because those type classes expect the Token type to be Char

  • 5 types
  • 4 classes
  • 80 values
classclass Alternative m => Parsing (m :: Type -> Type) where
#

Additional functionality needed to describe parsers independent of input type.

Methods

  • try :: m a -> m a

    Take a parser that may consume input, and on failure, go back to where we started and fail as if we didn't consume input.

  • (<?>) :: m a -> String -> m ainfixr 0

    Give a parser a name

  • skipMany :: m a -> m ()

    A version of many that discards its input. Specialized because it can often be implemented more cheaply.

  • skipSome :: m a -> m ()

    skipSome p applies the parser p one or more times, skipping its result. (aka skipMany1 in parsec)

  • unexpected :: String -> m a

    Used to emit an error on an unexpected token

  • eof :: m ()

    This parser only succeeds at the end of the input. This is not a primitive parser but it is defined using notFollowedBy.

     eof  = notFollowedBy anyChar <?> "end of input"
  • notFollowedBy :: Show a => m a -> m ()

    notFollowedBy p only succeeds when parser p fails. This parser does not consume any input. This parser can be used to implement the 'longest match' rule. For example, when recognizing keywords (for example let), we want to make sure that a keyword is not followed by a legal identifier character, in which case the keyword is actually an identifier (for example lets). We can program this behaviour as follows:

     keywordLet  = try $ string "let" <* notFollowedBy alphaNum
Instances16Parsing, …
valueoptional :: Alternative f => f a -> f (Maybe a)
#

One or none.

It is useful for modelling any computation that is allowed to fail.

Examples

Using the Alternative instance of Control.Monad.Except, the following functions:

Example1 expression
import Control.Monad.Except
Example2 expressions
canFail = throwError "it failed" :: Except String Intfinal = return 42                :: Except String Int

Can be combined by allowing the first function to fail:

Example1 expression
runExcept $ canFail *> finalLeft "it failed"
Example1 expression
runExcept $ optional canFail *> finalRight 42
methodmany :: f a -> f [a]
#

Zero or more.

Examples
Example1 expression
many (putStr "la")lalalalalalalalala... * goes on forever *
Example1 expression
many NothingJust []
Example1 expression
take 5 <$> many (Just 1)* hangs forever *

Note that this function can be used with Parsers based on Applicatives. In that case many parser will attempt to parse parser zero or more times until it fails.

methodsome :: f a -> f [a]
#

One or more.

Examples
Example1 expression
some (putStr "la")lalalalalalalalala... * goes on forever *
Example1 expression
some Nothingnothing
Example1 expression
take 5 <$> some (Just 1)* hangs forever *

Note that this function can be used with Parsers based on Applicatives. In that case some parser will attempt to parse parser one or more times until it fails.

valuebetween :: Applicative m => m bra -> m ket -> m a -> m a
#

between open close p parses open, followed by p and close. Returns the value returned by p.

 braces  = between (symbol "{") (symbol "}")
valuechoice :: Alternative m => [m a] -> m a
#

choice ps tries to apply the parsers in the list ps in order, until one of them succeeds. Returns the value of the succeeding parser.

valueoption :: Alternative m => a -> m a -> m a
#

option x p tries to apply parser p. If p fails without consuming input, it returns the value x, otherwise the value returned by p.

 priority = option 0 (digitToInt <$> digit)
valuecount :: Applicative m => Int -> m a -> m [a]
#

count n p parses n occurrences of p. If n is smaller or equal to zero, the parser equals to return []. Returns a list of n values returned by p.

valueendBy :: Alternative m => m a -> m sep -> m [a]
#

endBy p sep parses zero or more occurrences of p, separated and ended by sep. Returns a list of values returned by p.

  cStatements  = cStatement `endBy` semi
valueendBy1 :: Alternative m => m a -> m sep -> m [a]
#

endBy1 p sep parses one or more occurrences of p, separated and ended by sep. Returns a list of values returned by p.

valuemanyTill :: Alternative m => m a -> m end -> m [a]
#

manyTill p end applies parser p zero or more times until parser end succeeds. Returns the list of values returned by p. This parser can be used to scan comments:

 simpleComment   = do{ string "<!--"
                     ; manyTill anyChar (try (string "-->"))
                     }

Note the overlapping parsers anyChar and string "-->", and therefore the use of the try combinator.

valuesepBy :: Alternative m => m a -> m sep -> m [a]
#

sepBy p sep parses zero or more occurrences of p, separated by sep. Returns a list of values returned by p.

 commaSep p  = p `sepBy` (symbol ",")
valuesepBy1 :: Alternative m => m a -> m sep -> m [a]
#

sepBy1 p sep parses one or more occurrences of p, separated by sep. Returns a list of values returned by p.

valuesepEndBy :: Alternative m => m a -> m sep -> m [a]
#

sepEndBy p sep parses zero or more occurrences of p, separated and optionally ended by sep, ie. haskell style statements. Returns a list of values returned by p.

 haskellStatements  = haskellStatement `sepEndBy` semi
valuesepEndBy1 :: Alternative m => m a -> m sep -> m [a]
#

sepEndBy1 p sep parses one or more occurrences of p, separated and optionally ended by sep. Returns a list of values returned by p.

valuechainl :: Alternative m => m a -> m (a -> a -> a) -> a -> m a
#

chainl p op x parses zero or more occurrences of p, separated by op. Returns a value obtained by a left associative application of all functions returned by op to the values returned by p. If there are zero occurrences of p, the value x is returned.

valuechainl1 :: Alternative m => m a -> m (a -> a -> a) -> m a
#

chainl1 p op x parses one or more occurrences of p, separated by op Returns a value obtained by a left associative application of all functions returned by op to the values returned by p. . This parser can for example be used to eliminate left recursion which typically occurs in expression grammars.

 expr   = term   `chainl1` addop
 term   = factor `chainl1` mulop
 factor = parens expr <|> integer

 mulop  = (*) <$ symbol "*"
      <|> div <$ symbol "/"

 addop  = (+) <$ symbol "+"
      <|> (-) <$ symbol "-"
valuechainr :: Alternative m => m a -> m (a -> a -> a) -> a -> m a
#

chainr p op x parses zero or more occurrences of p, separated by op Returns a value obtained by a right associative application of all functions returned by op to the values returned by p. If there are no occurrences of p, the value x is returned.

valuechainr1 :: Alternative m => m a -> m (a -> a -> a) -> m a
#

chainr1 p op x parses one or more occurrences of p, separated by op Returns a value obtained by a right associative application of all functions returned by op to the values returned by p.

valueendByNonEmpty :: Alternative m => m a -> m sep -> m (NonEmpty a)
#

endByNonEmpty p sep parses one or more occurrences of p, separated and ended by sep. Returns a non-empty list of values returned by p.

valuesepByNonEmpty :: Alternative m => m a -> m sep -> m (NonEmpty a)
#

sepByNonEmpty p sep parses one or more occurrences of p, separated by sep. Returns a non-empty list of values returned by p.

valuesepEndByNonEmpty :: Alternative m => m a -> m sep -> m (NonEmpty a)
#

sepEndByNonEmpty p sep parses one or more occurrences of p, separated and optionally ended by sep. Returns a non-empty list of values returned by p.

valueskipOptional :: Alternative m => m a -> m ()
#

skipOptional p tries to apply parser p. It will parse p or nothing. It only fails if p fails after consuming input. It discards the result of p. (Plays the role of parsec's optional, which conflicts with Applicative's optional)

valuesurroundedBy :: Applicative m => m a -> m sur -> m a
#

p `surroundedBy` f is p surrounded by f. Shortcut for between f f p. As in between, returns the value returned by p.

classclass Parsing m => CharParsing (m :: Type -> Type) where
#

Additional functionality needed to parse character streams.

Methods

  • satisfy :: (Char -> Bool) -> m Char

    Parse a single character of the input, with UTF-8 decoding

  • char :: Char -> m Char

    char c parses a single character c. Returns the parsed character (i.e. c).

    e.g.

    semiColon = char ';'
  • notChar :: Char -> m Char

    notChar c parses any single character other than c. Returns the parsed character.

  • anyChar :: m Char

    This parser succeeds for any character. Returns the parsed character.

  • string :: String -> m String

    string s parses a sequence of characters given by s. Returns the parsed string (i.e. s).

     divOrMod    =   string "div"
                 <|> string "mod"
  • text :: Text -> m Text

    text t parses a sequence of characters determined by the text t Returns the parsed text fragment (i.e. t).

    Using OverloadedStrings:

     divOrMod    =   text "div"
                 <|> text "mod"
Instances17CharParsing, …
valuenoneOf :: CharParsing m => [Char] -> m Char
#

As the dual of oneOf, noneOf cs succeeds if the current character is not in the supplied list of characters cs. Returns the parsed character.

 consonant = noneOf "aeiou"
valueoneOf :: CharParsing m => [Char] -> m Char
#

oneOf cs succeeds if the current character is in the supplied list of characters cs. Returns the parsed character. See also satisfy.

  vowel  = oneOf "aeiou"
valuehexDigit :: CharParsing m => m Char
#

Parses a hexadecimal digit (a digit or a letter between 'a' and 'f' or 'A' and 'F'). Returns the parsed character.

valueletter :: CharParsing m => m Char
#

Parses a letter (an upper case or lower case character). Returns the parsed character.

valuenoneOfSet :: CharParsing m => CharSet -> m Char
#

As the dual of oneOf, noneOf cs succeeds if the current character is not in the supplied list of characters cs. Returns the parsed character.

 consonant = noneOf "aeiou"
valueoctDigit :: CharParsing m => m Char
#

Parses an octal digit (a character between '0' and '7'). Returns the parsed character.

valueoneOfSet :: CharParsing m => CharSet -> m Char
#

oneOfSet cs succeeds if the current character is in the supplied set of characters cs. Returns the parsed character. See also satisfy.

  vowel  = oneOf "aeiou"
valuespace :: CharParsing m => m Char
#

Parses a white space character (any character which satisfies isSpace) Returns the parsed character.

valuetab :: CharParsing m => m Char
#

Parses a tab character ('\t'). Returns a tab character.

classclass Parsing m => LookAheadParsing (m :: Type -> Type) where
#

Additional functionality needed to describe parsers independent of input type.

Methods

  • lookAhead :: m a -> m a

    lookAhead p parses p without consuming any input.

Instances13LookAheadParsing, …
valuescientific :: TokenParsing m => m Scientific
#

This token parser parses a floating point value. Returns the value of the number. The number is parsed according to the grammar rules defined in the Haskell report.

classclass CharParsing m => TokenParsing (m :: Type -> Type) where
#

Additional functionality that is needed to tokenize input while ignoring whitespace.

Methods

  • someSpace :: m ()

    Usually, someSpace consists of one or more occurrences of a space. Some parsers may choose to recognize line comments or block (multi line) comments as white space as well.

  • nesting :: m a -> m a

    Called when we enter a nested pair of symbols. Overloadable to enable disabling layout

  • semi :: m Char

    The token parser |semi| parses the character ';' and skips any trailing white space. Returns the character ';'. Overloadable to permit automatic semicolon insertion or Haskell-style layout.

  • highlight :: Highlight -> m a -> m a

    Tag a region of parsed text with a bit of semantic information. Most parsers won't use this, but it is indispensible for highlighters.

  • token :: m a -> m a

    token p first applies parser p and then the whiteSpace parser, returning the value of p. Every lexical token (token) is defined using token, this way every parse starts at a point without white space. Parsers that use token are called token parsers in this document.

    The only point where the whiteSpace parser should be called explicitly is the start of the main parser in order to skip any leading white space.

    Alternatively, one might define token as first parsing whiteSpace and then parser p. By parsing whiteSpace first, the parser is able to return before parsing additional whiteSpace, improving laziness.

    mainParser  = sum <$ whiteSpace <*> many (token digit) <* eof
Instances17TokenParsing, …
newtypenewtype Unhighlighted (m :: Type -> Type) a
#

This is a parser transformer you can use to disable syntax highlighting over a range of text you are parsing.

Instances12MonadTrans, MonadReader, MonadState, MonadWriter, Monad, Functor, …
newtypenewtype Unlined (m :: Type -> Type) a
#

This is a parser transformer you can use to disable the automatic trailing newline (but not whitespace-in-general) consumption of a Token parser.

Constructors

Instances12MonadTrans, MonadReader, MonadState, MonadWriter, Monad, Functor, …
newtypenewtype Unspaced (m :: Type -> Type) a
#

This is a parser transformer you can use to disable the automatic trailing space consumption of a Token parser.

Constructors

Instances12MonadTrans, MonadReader, MonadState, MonadWriter, Monad, Functor, …
valueangles :: TokenParsing m => m a -> m a
#

Token parser angles p parses p enclosed in angle brackets ('<' and '>'), returning the value of p.

valuebraces :: TokenParsing m => m a -> m a
#

Token parser braces p parses p enclosed in braces ('{' and '}'), returning the value of p.

valuebrackets :: TokenParsing m => m a -> m a
#

Token parser brackets p parses p enclosed in brackets ('[' and ']'), returning the value of p.

valuecharLiteral :: TokenParsing m => m Char
#

This token parser parses a single literal character. Returns the literal character value. This parsers deals correctly with escape sequences. The literal character is parsed according to the grammar rules defined in the Haskell report (which matches most programming languages quite closely).

valuecharacterChar :: TokenParsing m => m Char
#

This parser parses a character literal without the surrounding quotation marks.

This parser does NOT swallow trailing whitespace

valuecolon :: TokenParsing m => m Char
#

Token parser colon parses the character ':' and skips any trailing white space. Returns the string ":".

valuecomma :: TokenParsing m => m Char
#

Token parser comma parses the character ',' and skips any trailing white space. Returns the string ",".

valuecommaSep :: TokenParsing m => m a -> m [a]
#

Token parser commaSep p parses zero or more occurrences of p separated by comma. Returns a list of values returned by p.

valuecommaSep1 :: TokenParsing m => m a -> m [a]
#

Token parser commaSep1 p parses one or more occurrences of p separated by comma. Returns a list of values returned by p.

valuedecimal :: TokenParsing m => m Integer
#

Parses a non-negative whole number in the decimal system. Returns the value of the number.

This parser does NOT swallow trailing whitespace

valuedot :: TokenParsing m => m Char
#

Token parser dot parses the character '.' and skips any trailing white space. Returns the string ".".

valuedouble :: TokenParsing m => m Double
#

This token parser parses a floating point value. Returns the value of the number. The number is parsed according to the grammar rules defined in the Haskell report.

valuehexadecimal :: TokenParsing m => m Integer
#

Parses a non-negative whole number in the hexadecimal system. The number should be prefixed with "x" or "X". Returns the value of the number.

This parser does NOT swallow trailing whitespace

valueinteger :: TokenParsing m => m Integer
#

This token parser parses an integer (a whole number). This parser is like natural except that it can be prefixed with sign (i.e. '-' or '+'). Returns the value of the number. The number can be specified in decimal, hexadecimal or octal. The number is parsed according to the grammar rules in the Haskell report.

valueinteger' :: TokenParsing m => m Integer
#

This parser parses an integer (a whole number). This parser is like natural except that it can be prefixed with sign (i.e. '-' or '+'). Returns the value of the number. The number can be specified in decimal, hexadecimal or octal. The number is parsed according to the grammar rules in the Haskell report.

This parser does NOT swallow trailing whitespace.

Also, unlike the integer parser, this parser does not admit spaces between the sign and the number.

valuenatural :: TokenParsing m => m Integer
#

This token parser parses a natural number (a non-negative whole number). Returns the value of the number. The number can be specified in decimal, hexadecimal or octal. The number is parsed according to the grammar rules in the Haskell report.

This token parser parses either natural or a float. Returns the value of the number. This parsers deals with any overlap in the grammar rules for naturals and floats. The number is parsed according to the grammar rules defined in the Haskell report.

valueoctal :: TokenParsing m => m Integer
#

Parses a non-negative whole number in the octal system. The number should be prefixed with "o" or "O". Returns the value of the number.

This parser does NOT swallow trailing whitespace

valueparens :: TokenParsing m => m a -> m a
#

Token parser parens p parses p enclosed in parenthesis, returning the value of p.

valuesemiSep :: TokenParsing m => m a -> m [a]
#

Token parser semiSep p parses zero or more occurrences of p separated by semi. Returns a list of values returned by p.

valuesemiSep1 :: TokenParsing m => m a -> m [a]
#

Token parser semiSep1 p parses one or more occurrences of p separated by semi. Returns a list of values returned by p.

valuestringLiteral :: (TokenParsing m, IsString s) => m s
#

This token parser parses a literal string. Returns the literal string value. This parsers deals correctly with escape sequences and gaps. The literal string is parsed according to the grammar rules defined in the Haskell report (which matches most programming languages quite closely).

valuewhiteSpace :: TokenParsing m => m ()
#

Skip zero or more bytes worth of white space. More complex parsers are free to consider comments as white space.

newtypenewtype ParsecT e s (m :: Type -> Type) a
#

Constructors

Instances23MonadParsec, MonadError, MonadReader, MonadState, MonadTrans, Monad, …