Haskell Parser Combinators in 2026: Megaparsec vs Attoparsec vs Parsec vs Trifecta

Every Haskell project eventually needs a parser, and the choice is usually made by copying whatever the last project used. That is how teams end up parsing a 40 GB log stream with a library built for compiler error messages, or shipping a language server that cannot tell a user where their syntax error is because the parser only returns Nothing.

The five libraries in this comparison are not interchangeable. Megaparsec 9.8.3 (984 stars, pushed 2026-12-05) is a monad transformer with typed errors. Attoparsec 0.14.4 (528 stars) is a ByteString machine built for network protocols and incremental input. Parsec 3.1.18.0 (891 stars, pushed 2026-06-09) is the 2001 original that Megaparsec forked. Trifecta 2.1.4 (304 stars, last push 2025-03-03) adds highlighting and Clang-style diagnostics. Flatparse 0.5.5.0 (183 stars, pushed 2026-09-23) is the performance outlier that its own README claims runs “2-10 times faster than attoparsec or megaparsec” on microbenchmarks.

The 30-Second Verdict

Megaparsec for anything a human reads — config languages, DSLs, source code, query strings. It has the best error messages in the ecosystem and the most ergonomic combinator set. Attoparsec for machine-generated bytes at volume — HTTP headers, binary protocols, log lines, streaming input split across chunk boundaries. Parsec only for legacy code — there is no reason to start a new parser on it in 2026. Trifecta if you are building a pretty error reporter and can accept a library whose last commit was March 2025. Flatparse when the profile says parsing is the bottleneck and you can live with strict ByteString and little-endian hosts.

The one-line rule that covers 90% of projects: if the input is text a person will see in an error message, use Megaparsec; if the input is bytes a machine produced, use Attoparsec.

How the Five Compare

MegaparsecAttoparsecParsecTrifectaFlatparse
Version9.8.30.14.43.1.18.02.1.40.5.5.0
Stars984528891304183
Last push2026-12-052024-12-122026-06-092025-03-032026-09-23
Input typeText / String / ByteStringByteString (strict + lazy)Text / StringTextstrict ByteString only
Error qualityTyped, multi-error, source spansMinimal (offset + message)BasicBest-in-class renderingLow-level, roll your own
Incremental inputNoYes (parseWith)NoNoNo
Monad transformerYes (ParsecT)NoYesYesNo
Backtracking modeltry / try-free MonadParsecAlways backtracks (no consumed-input tracking)Consumed-input trackingConsumed-input trackingFailure vs error distinction
Compile time / binary sizeHeaviestModerateModerateHeavyLightest
LicenceBSD-2BSD-3BSD-2BSD-3MIT

Two rows carry most of the decision. Incremental input is why network code uses Attoparsec: it can be fed 80 KB chunks and resume. Error quality is why language tooling uses Megaparsec: you get a ParseErrorBundle with offsets, not a Maybe.

Decision Matrix: Pick By Use Case

Use caseRecommendedWhy
Programming language / DSL front endMegaparsecSource spans, <?> labels, error recovery with region
HTTP or binary wire protocolAttoparsecparseWith handles chunk boundaries, no Text decoding step
Log line parsing at GB/sAttoparsec or FlatparseByte-oriented, no allocation-heavy token types
JSON/CSV-like bulk dataAttoparsecData.Attoparsec.ByteString + scientific is the fast path
Compiler with gorgeous diagnosticsTrifectaHighlighting, slicing, Clang-style caret output
Hot loop where parsing dominates the profileFlatparseUnboxed tuples and GHC primops, zero-allocation validators
Existing 2015 codebaseParsec (then migrate)Fork-compatible API, but no reason to start here
Parser that must also work in a monad stackMegaparsecMonadParsec instance for StateT, ReaderT, WriterT

Megaparsec — The Default for Human-Readable Input

Megaparsec’s README is unusually candid about what it is: “an industrial-strength monadic parser combinator library” that “strikes a nice balance between speed, flexibility, and the quality of parse errors”, built around the MonadParsec type class so that WriterT, StateT, and ReaderT are also instances — meaning you can wrap ParsecT inside those monads to get backtracking state.

The library’s own documentation is opinionated about the two type synonyms everyone gets wrong:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
-- from Text/Megaparsec.hs module documentation
type Parser = Parsec Void Text
--                   ^    ^
--                   |    |
-- Custom error component    Input stream type

-- and, for the error type:
ParseErrorBundle Text Void
--                ^    ^
--                |    |
-- Input stream type    Custom error component (same as Parser)

Getting these parameters wrong produces the “Type variable e0 is ambiguous” error that sends people to Stack Overflow; the module docs’ advice is blunt — give explicit signatures to all top-level parsers.

Install and declare it the normal Cabal way:

1
2
3
cabal install --lib megaparsec
# or, in your package .cabal:
#   build-depends: base >=4.14 && <5, megaparsec >=9.6, text

A parser for a real config format, using only documented exports (parse, Parsec, Void, some, char, string, <?>, eof):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{-# LANGUAGE OverloadedStrings #-}
import Data.Void (Void)
import Text.Megaparsec
import Text.Megaparsec.Char
import qualified Text.Megaparsec.Char.Lexer as L

type Parser = Parsec Void Text

sc :: Parser ()
sc = L.space space1 empty empty

lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc

key :: Parser Text
key = lexeme (some (alphaNumChar <|> char '_')) <?> "setting name"

value :: Parser Text
value = lexeme (takeWhile1P (Just "value") (/= '\n'))

setting :: Parser (Text, Text)
setting = (,) <$> key <* symbol "=" <*> value

settings :: Parser [(Text, Text)]
settings = sc *> many setting <* eof

main :: IO ()
main = case parse settings "config" "port = 8080\nhost = 0.0.0.0\n" of
  Left bundle  -> putStrLn (errorBundlePretty bundle)
  Right pairs  -> print pairs

errorBundlePretty is the feature people stay for. It prints the file, line, column, and a caret under the offending token, and Megaparsec can report multiple errors at once, plus recover “on the fly” and continue — capabilities the README lists explicitly as differences from Parsec.

Attoparsec — Built for Bytes and Chunk Boundaries

Attoparsec’s README describes it as “a fast Haskell parser combinator library, aimed particularly at dealing efficiently with network protocols and complicated text/binary file formats”. That sentence is the whole product. Its distinguishing API is parseWith, which takes a refill action: when the parser runs out of input mid-token, it asks you for more bytes instead of failing.

Real code from the repo’s examples/Atto_RFC2616.hs, which parses HTTP/1.1 requests off a socket:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import Data.Attoparsec.ByteString
import qualified Data.ByteString.Char8 as B

refill :: Handle -> IO B.ByteString
refill h = B.hGet h (80*1024)

incrementy :: FilePath -> Handle -> IO ()
incrementy file h = go (0::Int) =<< refill h
 where
   go !n is = do
     r <- parseWith (refill h) request is
     case r of
       Fail _ _ msg -> hPutStrLn stderr $ file ++ ": " ++ msg
       Done bs _req
           | B.null bs -> do
              s <- refill h
              if B.null s
                then print (n+1)
                else go (n+1) s
           | otherwise -> go (n+1) bs

Note what is missing: no Text, no String, no monad transformer, no source span. Attoparsec tracks a byte offset and a message. If your parser fails on line 4,000 of a log, you find out by counting bytes.

Install is the usual:

1
cabal install --lib attoparsec

Attoparsec also never tracks whether input was consumed, so every alternative backtracks. That removes the try tax that trips people up in Parsec-family libraries, at the cost of being unable to distinguish “no match here” from “definitely broken here”.

The repository is stable rather than dormant: the last push is 2024-12-12 because the library is finished, not abandoned. Version 0.14.4 has been the workhorse behind aeson’s parsing for years.

Parsec — The Ancestor, Kept Alive for Compatibility

Parsec 3.1.18.0 still gets commits (2026-06-09) and still works. Megaparsec’s README dedicates a section to the differences, and it reads as a list of reasons to migrate: better error messages with typed and custom errors, multiple errors at once, the offending line included in the error, fixes for “some quirks and bugs of Parsec”, better Unicode support in Text.Parsec.Char, more powerful combinators including indentation-sensitive parsing, better documentation, on-the-fly error recovery, and context tags via region.

What Parsec still has: ubiquity. Thousands of packages depend on it, and Text.Parsec is a single straightforward import with no type-level machinery. If you maintain a library whose public API exposes Parsec types, switching to Megaparsec is a breaking change — which is the only honest argument for starting a new parser on Parsec in 2026, and it is a weak one.

Trifecta — Diagnostics as the Product

Trifecta 2.1.4 describes itself with unusual honesty: “Parser combinators with highlighting, slicing, layout, literate comments, Clang-style diagnostics and the kitchen sink”. It is the parser behind several Haskell tooling projects, and its reason to exist is that parse errors should be pretty — with the offending span highlighted, not just pointed at.

The trade-off is maintenance tempo: last push 2025-03-03, 304 stars, and a heavy dependency footprint (it pulls in parsers, lens-adjacent machinery, and ansi-terminal for rendering). Choose it when diagnostic presentation is a first-class requirement, such as a compiler front end whose errors are the user interface. Do not choose it for a config file.

Flatparse — When the Profile Says Parsing Is the Problem

Flatparse’s README is the most technically specific of the five. It claims 2-10x faster than Attoparsec or Megaparsec on microbenchmarks, better compile times and executable sizes, and “pure validators (parsers returning ()) in flatparse are not difficult to implement with zero heap allocation” thanks to unboxed tuples and GHC primops.

It also lists its own non-features without hedging: no incremental parsing, only strict ByteString input, little-endian hosts only, and batteries deliberately not included — error messages, spans, and indentation support exist as low-level interfaces you assemble yourself. Its backtracking model separates parser failure (control flow, backtrackable) from parsing error (fatal), closer to Rust’s nom than to Parsec.

1
2
cabal install --lib flatparse
# advised: build with -fllvm for a further 20-40% on parser-heavy code

If you parse a language and want Flatparse’s speed, budget real time for the error-reporting layer. The README says the primitives are there; it does not pretend the batteries are included.

Benchmarks, Honestly

Cross-library parser benchmarks are the easiest thing in Haskell to fake, because parser performance depends more on your grammar’s shape than on the library. Three claims are defensible:

  1. Flatparse is the fastest of the five on the workloads its author benchmarks — by its own README’s numbers, 2-10x over Attoparsec and Megaparsec.
  2. Attoparsec beats Megaparsec on byte-oriented bulk input, because it never builds Text tokens and can resume across chunks.
  3. Megaparsec is the slowest per byte and the fastest per developer-hour. The monad transformer stack, source-position tracking, and error accumulation all cost cycles — and all save debugging time.

One architectural note worth more than any microbenchmark: avoid String. All five libraries can parse String, and on any real input it is the dominant cost. Convert to Text or ByteString at the boundary and stay there.

Pitfalls That Cost Real Days

  • try on every alternative. In Parsec and Megaparsec, p1 <|> p2 only tries p2 if p1 failed without consuming input. Wrapping everything in try fixes the symptom and destroys error messages, because the parser can no longer say “you got this far and then broke”. Restructure the grammar instead.
  • Attoparsec’s missing error position. Fail gives you a byte offset. Convert it to line/column yourself if humans will read the message, or you will be debugging with offsets.
  • Megaparsec’s error type parameters. Parsec Void Text and ParseErrorBundle Text Void have the parameters in different orders. Mixing them up compiles until it does not; write the type synonyms once and reuse them.
  • Flatparse’s host assumptions. Strict ByteString only, little-endian only. A parser that works on x86-64 CI can silently produce wrong results on a big-endian target.
  • Trifecta’s dependency weight. It brings a rendering stack into your build. On a small CLI that is a multi-second compile-time tax for error messages nobody will see.
  • Incremental input is not retrofittable. If you might ever parse from a socket, start with Attoparsec’s parseWith. Bolting chunking onto a Text-based parser later means rewriting it.

For the rest of the toolchain, our Haskell library comparison covers the argument-parsing layer that usually sits next to your parser, the Haskell serialization guide explains where Attoparsec’s byte-oriented design pays off, and the Haskell testing frameworks comparison shows how to property-test the grammar you just wrote.

FAQ

Which Haskell parser library should I use for a programming language? Megaparsec. You get source positions, labelled expectations with <?>, multiple errors per run, and error recovery — the features a language front end actually needs. Use Flatparse only if profiling proves the parser is the bottleneck.

Is Attoparsec still maintained? Yes. Its last push is 2024-12-12 because version 0.14.4 is feature-complete and stable, not abandoned. It remains the parser inside widely used libraries and is the correct choice for byte-oriented, incremental input.

Can Megaparsec parse input incrementally from a socket? Not in the way Attoparsec can. Attoparsec’s parseWith takes a refill action and resumes mid-token; Megaparsec expects a complete input stream, so the usual pattern is to frame messages yourself and parse each frame.

Why does everyone say to avoid try? Because try resets the consumed-input flag, which is what Parsec-family libraries use to choose between alternatives and to phrase errors. Overusing it makes grammars ambiguous and error messages useless. Restructure the grammar so alternatives are distinguishable by their first token.

Is Flatparse a drop-in replacement for Megaparsec? No. It only accepts strict ByteString, does not support incremental input, assumes a little-endian host, and provides no built-in error rendering — you write the diagnostics layer. It is a performance tool, not a general-purpose front end.

What is the fastest way to stop paying for String? Convert at the boundary. Parse Text for human-readable input and ByteString for machine input, and never let String reach the hot loop of a parser.


💰 想测试你的市场判断力?我用 Polymarket 做预测市场交易——这是全球最大的预测市场平台,从大选结果到技术监管时间线,什么都可以押注。和赌博不同,这是真正的信息市场:你懂的信息越多,胜率越高。我靠预测技术相关事件的走向已经赚了不少。用我的邀请链接注册:Polymarket.com