An associative binary operation
Modulemegaparsec-9.7.0Haskell2010
Text.Megaparsec
This module includes everything you need to get started writing a parser. If you are new to Megaparsec and don't know where to begin, take a look at the tutorial https://markkarpov.com/tutorial/megaparsec.html.
In addition to the Text.Megaparsec module, which exports and re-exports almost everything that you may need, we advise to import Text.Megaparsec.Char if you plan to work with a stream of Char tokens or Text.Megaparsec.Byte if you intend to parse binary data.
It is common to start working with the library by defining a type synonym like this:
type Parser = Parsec Void Text
^ ^
| |
Custom error component Input stream typeThen you can write type signatures like Parser Int—for a parser that
returns an Int for example.
Similarly (since it's known to cause confusion), you should use ParseErrorBundle type parametrized like this:
ParseErrorBundle Text Void
^ ^
| |
Input stream type Custom error component (the same you used in Parser)Megaparsec uses some type-level machinery to provide flexibility without
compromising on type safety. Thus type signatures are sometimes necessary
to avoid ambiguous types. If you're seeing an error message that reads
like “Type variable e0 is ambiguous …”, you need to give an explicit
signature to your parser to resolve the ambiguity. It's a good idea to
provide type signatures for all top-level definitions.
- 4 types
- 1 class
- 56 values
- Packagemegaparsec-9.7.0
- Exports63
- LanguageHaskell2010
- LicenceBSD-2-Clause
- SourceMegaparsec.hs
Re-exports
26 declarationsNote that we re-export monadic combinators from Control.Monad.Combinators because these are more efficient than Applicative-based ones (†). Thus many and some may clash with the functions from Control.Applicative. You need to hide the functions like this:
import Control.Applicative hiding (many, some)† As of Megaparsec 9.7.0 many and some are as efficient as their monadic counterparts.
Also note that you can import Control.Monad.Combinators.NonEmpty if you
wish that combinators like some return NonEmpty lists. The module
lives in the parser-combinators package (you need at least version
0.4.0).
This module is intended to be imported qualified:
import qualified Control.Monad.Combinators.NonEmpty as NEOther modules of interest are:
Control.Monad.Combinators.Expr for parsing of expressions.
Control.Applicative.Permutations for parsing of permutations phrases.
module Text.Megaparsec.Pos
module Text.Megaparsec.Error
module Text.Megaparsec.Stream
The identity of <|>
empty <|> a == a
a <|> empty == amany p applies the parser p zero or more times and returns a
list of the values returned by p.
identifier = (:) <$> letter <*> many (alphaNumChar <|> char '_')some p applies the parser p one or more times and returns a
list of the values returned by p.
word = some letterOne 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:
import Control.Monad.ExceptcanFail = throwError "it failed" :: Except String Intfinal = return 42 :: Except String Int
Can be combined by allowing the first function to fail:
runExcept $ canFail *> finalLeft "it failed"
runExcept $ optional canFail *> finalRight 42
between open close p parses open, followed by p and close.
Returns the value returned by p.
braces = between (symbol "{") (symbol "}")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.
choice = asumendBy 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` semicolonendBy1 p sep parses one or more occurrences of p, separated and
ended by sep. Returns a list of values returned by p.
manyTill p end applies parser p zero or more times until parser
end succeeds. Returns the list of values returned by p. Note that
end result is consumed and lost. Use manyTill_ if you wish to keep
it.
See also: skipMany, skipManyTill.
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` commasepBy1 p sep parses one or more occurrences of p, separated by
sep. Returns a list of values returned by p.
skipMany p applies the parser p zero or more times, skipping
its result.
See also: manyTill, skipManyTill.
Combine two alternatives.
eitherP a b = (Left <$> a) <|> (Right <$> b)manyTill_ p end applies parser p zero or more times until
parser end succeeds. Returns the list of values returned by p and the
end result. Use manyTill if you have no need in the result of the
end.
See also: skipMany, skipManyTill.
sepEndBy p sep parses zero or more occurrences of p, separated
and optionally ended by sep. Returns a list of values returned by p.
sepEndBy1 p sep parses one or more occurrences of p, separated
and optionally ended by sep. Returns a list of values returned by p.
skipManyTill p end applies the parser p zero or more times
skipping results until parser end succeeds. Result parsed by end is
then returned.
skipSome p applies the parser p one or more times, skipping its
result.
See also: someTill, skipSomeTill.
skipSomeTill p end applies the parser p one or more times
skipping results until parser end succeeds. Result parsed by end is
then returned.
someTill p end works similarly to manyTill p end, but p
should succeed at least once. Note that end result is consumed and
lost. Use someTill_ if you wish to keep it.
someTill p end = liftM2 (:) p (manyTill p end)See also: skipSome, skipSomeTill.
someTill_ p end works similarly to manyTill_ p end, but p
should succeed at least once. Use someTill if you have no need in the
result of the end.
See also: skipSome, skipSomeTill.
Data types
4 declarationsThis is the Megaparsec's state parametrized over stream type s and
custom error component type e.
Constructors
StatestateInput :: sThe rest of input to process
stateOffset :: !IntNumber of processed tokens so far
statePosState :: PosState sState that is used for line/column calculation
stateParseErrors :: [ParseError s e]Collection of “delayed” ParseErrors in reverse order. This means that the last registered error is the first element of the list.
Instances6Eq, Data, Show, Generic, NFData, Rep
(Eq (ParseError s e), Eq s) => Eq (State s e)Defined in megaparsec-9.7.0 · Text.Megaparsec.State(Data e, Data (ParseError s e), Data s) => Data (State s e)Defined in megaparsec-9.7.0 · Text.Megaparsec.State(Show (ParseError s e), Show s) => Show (State s e)Defined in megaparsec-9.7.0 · Text.Megaparsec.StateGeneric (State s e)Defined in megaparsec-9.7.0 · Text.Megaparsec.State(NFData s, NFData (ParseError s e)) => NFData (State s e)Defined in megaparsec-9.7.0 · Text.Megaparsec.Statetype Rep (State s e) = D1 ('MetaDataDefined in megaparsec-9.7.0 · Text.Megaparsec.State"State"
"Text.Megaparsec.State"
"megaparsec-9.7.0-Jiz5oe6zAALBOFyVFbTGRU"
'False) (C1 ('MetaCons"State"
'PrefixI 'True) ((S1 ('MetaSel ('Just"stateInput"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 s) :*: S1 ('MetaSel ('Just"stateOffset"
) 'SourceUnpack 'SourceStrict 'DecidedUnpack) (Rec0 Int)) :*: (S1 ('MetaSel ('Just"statePosState"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (PosState s)) :*: S1 ('MetaSel ('Just"stateParseErrors"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 [ParseError s e]))))
A special kind of state that is used to calculate line/column positions on demand.
Constructors
PosStatepstateInput :: sThe rest of input to process
pstateOffset :: !IntOffset corresponding to beginning of pstateInput
pstateSourcePos :: !SourcePosSource position corresponding to beginning of pstateInput
pstateTabWidth :: PosTab width to use for column calculation
pstateLinePrefix :: StringPrefix to prepend to offending line
Instances6Eq, Data, Show, Generic, NFData, Rep
Eq s => Eq (PosState s)Defined in megaparsec-9.7.0 · Text.Megaparsec.StateData s => Data (PosState s)Defined in megaparsec-9.7.0 · Text.Megaparsec.StateShow s => Show (PosState s)Defined in megaparsec-9.7.0 · Text.Megaparsec.StateGeneric (PosState s)Defined in megaparsec-9.7.0 · Text.Megaparsec.StateNFData s => NFData (PosState s)Defined in megaparsec-9.7.0 · Text.Megaparsec.Statetype Rep (PosState s) = D1 ('MetaDataDefined in megaparsec-9.7.0 · Text.Megaparsec.State"PosState"
"Text.Megaparsec.State"
"megaparsec-9.7.0-Jiz5oe6zAALBOFyVFbTGRU"
'False) (C1 ('MetaCons"PosState"
'PrefixI 'True) ((S1 ('MetaSel ('Just"pstateInput"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 s) :*: S1 ('MetaSel ('Just"pstateOffset"
) 'NoSourceUnpackedness 'SourceStrict 'DecidedUnpack) (Rec0 Int)) :*: (S1 ('MetaSel ('Just"pstateSourcePos"
) 'NoSourceUnpackedness 'SourceStrict 'DecidedStrict) (Rec0 SourcePos) :*: (S1 ('MetaSel ('Just"pstateTabWidth"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Pos) :*: S1 ('MetaSel ('Just"pstateLinePrefix"
) 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 String)))))
ParsecT e s m a is a parser with custom data component of error
e, stream type s, underlying monad m and return type a.
Instances19MonadParsec, MonadParsecDbg, MonadError, MonadReader, MonadState, MonadWriter, …
(Ord e, Stream s) => MonadParsec e s (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internal(VisualStream s, ShowErrorComponent e) => MonadParsecDbg e s (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Debug(Stream s, MonadError e' m) => MonadError e' (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internal(Stream s, MonadReader r m) => MonadReader r (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internal(Stream s, MonadState st m) => MonadState st (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internal(Stream s, MonadWriter w m) => MonadWriter w (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.InternalStream s => MonadTrans (ParsecT e s)Defined in megaparsec-9.7.0 · Text.Megaparsec.InternalStream s => Monad (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internalreturn returns a parser that succeeds without consuming input.
Functor (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internal(Stream s, MonadFix m) => MonadFix (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.InternalStream s => MonadFail (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.InternalStream s => Applicative (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internalpure returns a parser that succeeds without consuming input.
(Ord e, Stream s) => Alternative (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internalempty is a parser that fails without consuming input.
(Ord e, Stream s) => MonadPlus (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internalmzero is a parser that fails without consuming input.
Note: strictly speaking, this instance is unlawful. The right identity law does not hold, e.g. in general this is not true:
v >> mzero = mzeroHowever the following holds:
try v >> mzero = mzero(Stream s, MonadIO m) => MonadIO (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internal(Stream s, MonadCont m) => MonadCont (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internal(a ~ Tokens s, IsString a, Eq a, Stream s, Ord e) => IsString (ParsecT e s m a)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internal(Stream s, Semigroup a) => Semigroup (ParsecT e s m a)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internal(Stream s, Monoid a) => Monoid (ParsecT e s m a)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internal
Running parser
7 declarationsparse :: Parsec e s aParser to run
-> StringName of source file
-> sInput for parser
-> Either (ParseErrorBundle s e) a
parse p file input runs parser p over Identity (see
runParserT if you're using the ParsecT monad transformer; parse
itself is just a synonym for runParser). It returns either a
ParseErrorBundle (Left) or a value of type a (Right).
errorBundlePretty can be used to turn ParseErrorBundle into the
string representation of the error message. See Text.Megaparsec.Error
if you need to do more advanced error analysis.
main = case parse numbers "" "11,2,43" of
Left bundle -> putStr (errorBundlePretty bundle)
Right xs -> print (sum xs)
numbers = decimal `sepBy` char ','parseMaybe p input runs the parser p on input and returns the
result inside Just on success and Nothing on failure. This function
also parses eof, so if the parser doesn't consume all of its input, it
will fail.
The function is supposed to be useful for lightweight parsing, where error messages (and thus file names) are not important and entire input should be consumed. For example, it can be used for parsing of a single number according to a specification of its format.
parseTest :: (ShowErrorComponent e, Show a, VisualStream s, TraversableStream s)=> Parsec e s aParser to run
-> sInput for parser
-> IO ()
The expression parseTest p input applies the parser p on the
input input and prints the result to stdout. Useful for testing.
runParser :: Parsec e s aParser to run
-> StringName of source file
-> sInput for parser
-> Either (ParseErrorBundle s e) a
runParser p file input runs parser p on the input stream of
tokens input, obtained from source file. The file is only used in
error messages and may be the empty string. Returns either a
ParseErrorBundle (Left) or a value of type a (Right).
parseFromFile p file = runParser p file <$> readFile filerunParser' :: Parsec e s aParser to run
-> State s eInitial state
-> (State s e, Either (ParseErrorBundle s e) a)
runParserT :: Monad m=> ParsecT e s m aParser to run
-> StringName of source file
-> sInput for parser
-> m (Either (ParseErrorBundle s e) a)
runParserT p file input runs parser p on the input list of tokens
input, obtained from source file. The file is only used in error
messages and may be the empty string. Returns a computation in the
underlying monad m that returns either a ParseErrorBundle (Left) or
a value of type a (Right).
runParserT' This function is similar to runParserT, but like runParser' it accepts and returns parser state. This is thus the most general way to run a parser.
Primitive combinators
1 declarationType class describing monads that implement the full set of primitive parsers.
Note that the following primitives are “fast” and should be taken advantage of as much as possible if your aim is a fast parser: tokens, takeWhileP, takeWhile1P, and takeP.
Methods
parseError :: ParseError s e -> m aStop parsing and report the ParseError. This is the only way to control position of the error without manipulating the parser state manually.
label :: String -> m a -> m aThe parser
label name pbehaves as parserp, but whenever the parserpfails without consuming any input, it replaces names of “expected” tokens with the namename.try :: m a -> m aThe parser
try pbehaves like the parserp, except that it backtracks the parser state whenpfails (either consuming input or not).This combinator is used whenever arbitrary look ahead is needed. Since it pretends that it hasn't consumed any input when
pfails, the (A.<|>) combinator will try its second alternative even if the first parser failed while consuming input.For example, here is a parser that is supposed to parse the word “let” or the word “lexical”:
Example1 expression parseTest (string "let" <|> string "lexical") "lexical"1:1:unexpected "lex"expecting "let"
What happens here? The first parser consumes “le” and fails (because it doesn't see a “t”). The second parser, however, isn't tried, since the first parser has already consumed some input! try fixes this behavior and allows backtracking to work:
Example1 expression parseTest (try (string "let") <|> string "lexical") "lexical""lexical"
try also improves error messages in case of overlapping alternatives, because Megaparsec's hint system can be used:
Example1 expression parseTest (try (string "let") <|> string "lexical") "le"1:1:unexpected "le"expecting "let" or "lexical"
Note that as of Megaparsec 4.4.0, string backtracks automatically (see tokens), so it does not need try. However, the examples above demonstrate the idea behind try so well that it was decided to keep them. You still need to use try when your alternatives are complex, composite parsers.
lookAhead :: m a -> m aIf
pinlookAhead psucceeds (either consuming input or not) the whole parser behaves likepsucceeded without consuming anything (parser state is not updated as well). Ifpfails, lookAhead has no effect, i.e. it will fail consuming input ifpfails consuming input. Combine with try if this is undesirable.notFollowedBy :: m a -> m ()notFollowedBy ponly succeeds when the parserpfails. This parser never consumes any input and never modifies parser state. It can be used to implement the “longest match” rule.withRecovery :: (ParseError s e -> m a) -> m a -> m awithRecovery r pallows us to continue parsing even if the parserpfails. In this caseris called with the actual ParseError as its argument. Typical usage is to return a value signifying failure to parse this particular object and to consume some part of the input up to the point where the next object starts.Note that if
rfails, the original error message is reported as if without withRecovery. In no way recovering parserrcan influence error messages.observing :: m a -> m (Either (ParseError s e) a)observing pallows us to “observe” failure of thepparser, should it happen, without actually ending parsing but instead getting the ParseError in Left. On success parsed value is returned in Right as usual. Note that this primitive just allows you to observe parse errors as they happen, it does not backtrack or change how thepparser works in any way.eof :: m ()This parser only succeeds at the end of input.
token :: (Token s -> Maybe a) -> Set (ErrorItem (Token s)) -> m aThe parser
token test expectedaccepts tokens for which the matching functiontestreturns Just results. If Nothing is returned theexpectedset is used to report the items that were expected.For example, the satisfy parser is implemented as:
satisfy f = token testToken Set.empty where testToken x = if f x then Just x else NothingNote: type signature of this primitive was changed in the version 7.0.0.
tokens :: (Tokens s -> Tokens s -> Bool) -> Tokens s -> m (Tokens s)The parser
tokens test chkparses a chunk of inputchkand returns it. The supplied predicatetestis used to check equality of given and parsed chunks after a candidate chunk of correct length is fetched from the stream.This can be used for example to write chunk:
chunk = tokens (==)Note that beginning from Megaparsec 4.4.0, this is an auto-backtracking primitive, which means that if it fails, it never consumes any input. This is done to make its consumption model match how error messages for this primitive are reported (which becomes an important thing as user gets more control with primitives like withRecovery):
Example1 expression parseTest (string "abc") "abd"1:1:unexpected "abd"expecting "abc"
This means, in particular, that it's no longer necessary to use try with tokens-based parsers, such as string and string'. This feature does not affect performance in any way.
takeWhileP :: Maybe String -> (Token s -> Bool) -> m (Tokens s)Parse zero or more tokens for which the supplied predicate holds. Try to use this as much as possible because for many streams this combinator is much faster than parsers built with many and satisfy.
takeWhileP (Just "foo") f = many (satisfy f <?> "foo") takeWhileP Nothing f = many (satisfy f)The combinator never fails, although it may parse the empty chunk.
takeWhile1P :: Maybe String -> (Token s -> Bool) -> m (Tokens s)Similar to takeWhileP, but fails if it can't parse at least one token. Try to use this as much as possible because for many streams this combinator is much faster than parsers built with some and satisfy.
takeWhile1P (Just "foo") f = some (satisfy f <?> "foo") takeWhile1P Nothing f = some (satisfy f)Note that the combinator either succeeds or fails without consuming any input, so try is not necessary with it.
takeP :: Maybe String -> Int -> m (Tokens s)Extract the specified number of tokens from the input stream and return them packed as a chunk of stream. If there is not enough tokens in the stream, a parse error will be signaled. It's guaranteed that if the parser succeeds, the requested number of tokens will be returned.
The parser is roughly equivalent to:
takeP (Just "foo") n = count n (anySingle <?> "foo") takeP Nothing n = count n anySingleNote that if the combinator fails due to insufficient number of tokens in the input stream, it backtracks automatically. No try is necessary with takeP.
getParserState :: m (State s e)Return the full parser state as a State record.
updateParserState :: (State s e -> State s e) -> m ()updateParserState fapplies the functionfto the parser state.mkParsec :: (State s e -> Reply e s a) -> m aAn escape hatch for defining custom MonadParsec primitives. You will need to import Text.Megaparsec.Internal in order to construct Reply.
Instances9MonadParsec, …
MonadParsec e s m => MonadParsec e s (IdentityT m)Defined in megaparsec-9.7.0 · Text.Megaparsec.ClassMonadParsec e s m => MonadParsec e s (ReaderT r m)Defined in megaparsec-9.7.0 · Text.Megaparsec.ClassMonadParsec e s m => MonadParsec e s (StateT st m)Defined in megaparsec-9.7.0 · Text.Megaparsec.ClassMonadParsec e s m => MonadParsec e s (StateT st m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Class(Monoid w, MonadParsec e s m) => MonadParsec e s (WriterT w m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Class(Monoid w, MonadParsec e s m) => MonadParsec e s (WriterT w m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Class(Ord e, Stream s) => MonadParsec e s (ParsecT e s m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Internal(Monoid w, MonadParsec e s m) => MonadParsec e s (RWST r w st m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Class(Monoid w, MonadParsec e s m) => MonadParsec e s (RWST r w st m)Defined in megaparsec-9.7.0 · Text.Megaparsec.Class
Signaling parse errors
8 declarationsThe most general function to fail and end parsing is parseError. These
are built on top of it. The section also includes functions starting with
the register prefix which allow users to register “delayed”
ParseErrors.
failure Stop parsing and report a trivial ParseError.
Stop parsing and report a fancy ParseError. To report a single custom parse error, see customFailure.
The parser unexpected item fails with an error message telling
about unexpected item item without consuming any input.
unexpected item = failure (Just item) Set.emptyReport a custom parse error. For a more general version, see fancyFailure.
customFailure = fancyFailure . Set.singleton . ErrorCustomregion :: MonadParsec e s m=> (ParseError s e -> ParseError s e)How to process ParseErrors
-> m aThe “region” that the processing applies to
-> m a
Specify how to process ParseErrors that happen inside of this wrapper. This applies to both normal and delayed ParseErrors.
As a side-effect of the implementation the inner computation will start with an empty collection of delayed errors and they will be updated and “restored” on the way out of region.
Register a ParseError for later reporting. This action does not end parsing and has no effect except for adding the given ParseError to the collection of “delayed” ParseErrors which will be taken into consideration at the end of parsing. Only if this collection is empty the parser will succeed. This is the main way to report several parse errors at once.
registerFailure Like failure, but for delayed ParseErrors.
Like fancyFailure, but for delayed ParseErrors.
Derivatives of primitive combinators
11 declarationsThe parser satisfy f succeeds for any token for which the supplied
function f returns True.
digitChar = satisfy isDigit <?> "digit"
oneOf cs = satisfy (`elem` cs)Performance note: when you need to parse a single token, it is often a good idea to use satisfy with the right predicate function instead of creating a complex parser using the combinators.
See also: anySingle, anySingleBut, oneOf, noneOf.
Parse and return a single token. It's a good idea to attach a label to this parser.
anySingle = satisfy (const True)See also: satisfy, anySingleBut.
oneOf :: (Foldable f, MonadParsec e s m)=> f (Token s)Collection of matching tokens
-> m (Token s)
oneOf ts succeeds if the current token is in the supplied
collection of tokens ts. Returns the parsed token. Note that this
parser cannot automatically generate the “expected” component of error
message, so usually you should label it manually with label or (<?>).
oneOf cs = satisfy (`elem` cs)See also: satisfy.
digit = oneOf ['0'..'9'] <?> "digit"Performance note: prefer satisfy when you can because it's faster when you have only a couple of tokens to compare to:
quoteFast = satisfy (\x -> x == '\'' || x == '\"')
quoteSlow = oneOf "'\""noneOf :: (Foldable f, MonadParsec e s m)=> f (Token s)Collection of taken we should not match
-> m (Token s)
As the dual of oneOf, noneOf ts succeeds if the current token
not in the supplied list of tokens ts. Returns the parsed character.
Note that this parser cannot automatically generate the “expected”
component of error message, so usually you should label it manually with
label or (<?>).
noneOf cs = satisfy (`notElem` cs)See also: satisfy.
Performance note: prefer satisfy and anySingleBut when you can because it's faster.
A synonym for label in the form of an operator.
Return both the result of a parse and a chunk of input that was consumed during parsing. This relies on the change of the stateOffset value to evaluate how many tokens were consumed. If you mess with it manually in the argument parser, prepare for troubles.
Consume the rest of the input and return it as a chunk. This parser never fails, but may return the empty chunk.
takeRest = takeWhileP Nothing (const True)Return True when end of input has been reached.
atEnd = option False (True <$ hidden eof)Parser state combinators
6 declarationsReturn the current input.
setInput input continues parsing with input.
Return the current source position. This function is not cheap, do not call it e.g. on matching of every token, that's a bad idea. Still you can use it to get SourcePos to attach to things that you parse.
The function works under the assumption that we move in the input stream only forwards and never backwards, which is always true unless the user abuses the library.
Get the number of tokens processed so far.
See also: setOffset.
Set the number of tokens processed so far.
See also: getOffset.
setParserState st sets the parser state to st.
See also: getParserState, updateParserState.