meon
Declarative flat parsing engine for text formats: describe a grammar once,
get a parser whose output is one flat span vector per element kind.
This documentation describes the current checkout. Unreleased DSL changes are
listed in CHANGELOG.md; build the workspace crates to use them.
What is meon
Most text parsers build a tree. meon(wiki) builds a table.
You describe a grammar once with define_parser! and get back a content struct
where every element kind lives in its own flat Vec. Headings in one vec,
bold spans in another, links in a third. No tree traversal, no allocator
pressure from node objects, no virtual dispatch. Just contiguous arrays of
byte-offset pairs (the offset type defaults to u32) that you iterate at
native speed.
Key properties
| Property |
What it means |
| O(1) access by element kind |
Every element kind is its own Vec of spans. “All links” or “all headings” is a field, not a tree walk with node matching. |
| Standalone parsing of a single kind |
Supported rules generate find_*: it scans the source for that one kind only and skips everything else. Need only the headings — parse only the headings. |
| One declaration, whole parser |
define_parser! is a code generator: from one grammar you get the content struct, parse, every find_* / find_context_* iterator and every accessor. No runtime grammar interpreter, no dispatch. |
| Throughput that holds as input grows |
The output is a flat table of 8-byte spans, so the working set stays small. On an input 100x larger than cache meon-md keeps its throughput within ~4% (nightly within ~6%) and meon-json loses at most ~30%, while the tree, event and tape parsers it is compared with lose a third to two thirds of theirs. |
meon-md full parse vs CommonMark parsers, small (fits in cache) -> big
(100x larger, exceeds L3), stable build, median throughput:
| Corpus |
meon-md |
pulldown-cmark |
comrak |
plain |
3.07 -> 2.96 GiB/s (-4%) |
880 -> 536 MiB/s (-39%) |
260 -> 119 MiB/s (-54%) |
hot |
981 -> 976 MiB/s (-1%) |
159 -> 86 MiB/s (-46%) |
43 -> 23 MiB/s (-47%) |
heavy |
806 -> 808 MiB/s (0%) |
115 -> 70 MiB/s (-39%) |
32 -> 19 MiB/s (-41%) |
Single-kind extraction on the same big corpora runs at memchr speed over
that kind’s markers: find_headings at 7-17 GiB/s on hot / heavy,
find_bolds at 3.3-4.9 GiB/s. Neither CommonMark parser has an equivalent —
pulling one kind out of them means a full parse.
meon-md is a Markdown subset and does not aim at CommonMark compliance, so
these numbers compare different jobs; see
MD_COMPARE.md
and
JSON_COMPARE.md
for full tables, the JSON scaling story and the fairness frame.
Flat output — hardware-friendly by design
A typical parser hands you a heterogeneous AST. To find all bold spans you
walk the tree, match node types, and collect what you need. Cache misses
accumulate as you jump between pointer-linked nodes of varying sizes.
meon inverts this. The output is a struct-of-arrays:
MarkdownContent {
source: &[u8] ← original bytes, borrowed
texts: Vec<Span> ← all plain text runs
bolds: Vec<Span> ← all bold spans
italics: Vec<Span> ← all italic spans
codes: Vec<Span> ← all inline code spans
links: Vec<Link> ← all links and images
headings: Vec<(Heading, Span)>
fenced_codes: Vec<Span>
bullet_items: Vec<(BulletItem, Span)>
...
}
All spans are byte offsets. The type defaults to u32 (8 bytes per span) and is selected by limits { offset = ...; }. Access to any element
kind is O(1). Iterating all bold spans is a single forward scan over a
contiguous array. The CPU prefetcher is happy.
Spans — zero-copy access into the source
Every element is represented as a Span { start: u32, end: u32 } by default — a
half-open byte range [start, end) into the original source slice. Nothing
is copied. Nothing is decoded unless you ask for it.
let src = b"**bold** and *italic*\n";
let c = MarkdownParser::parse(src).unwrap();
// Resolve a span to a string slice — zero copy, borrow from source.
// Returns `None` on invalid UTF-8 instead of panicking.
let text: &str = c.str(c.bolds[0]).unwrap();
assert_eq!(text, "bold");
// Or work with raw bytes, no UTF-8 check
let bytes: &[u8] = c.bytes(c.italics[0]);
// Fields backed by a standalone rule also get a generated `_clean`
// (delimiters stripped) and `_raw` (delimiters included) accessor —
// zero-copy byte-slice iterators. Fallback fields get `_clean` only.
let raw: &[u8] = c.bolds_raw().next().unwrap();
assert_eq!(raw, b"**bold**");
The content struct borrows the source for its entire lifetime. When the struct
is dropped the source is released. No intermediate representations persist.
Every standalone-capable rule generates a find_* iterator. It scans the raw
source for one element kind only, with no knowledge of surrounding elements,
active blocks, or other rules’ line classification. The rule’s own
escapes, balancing, nesting and blank-line limits still apply.
// Full parse — all element kinds in one pass
let content = MarkdownParser::parse(src).unwrap();
// Standalone — only bold spans, nothing else computed
for span in MarkdownParser::find_bolds(src).unwrap() {
println!("{}", std::str::from_utf8(&src[span.start as usize..span.end as usize]).unwrap());
}
// Headings with metadata — level and content span
for (heading, span) in MarkdownParser::find_headings(src).unwrap() {
println!("h{}: {}", heading.level, std::str::from_utf8(&src[span.start as usize..span.end as usize]).unwrap());
}
// Links and images — structured type, two spans inside
for link in MarkdownParser::find_links(src).unwrap() {
let text = std::str::from_utf8(&src[link.text.start as usize..link.text.end as usize]).unwrap();
let url = std::str::from_utf8(&src[link.url.start as usize..link.url.end as usize]).unwrap();
println!("[{}]({}) image={}", text, url, link.is_image);
}
Standalone iterators are faster than a full parse when only one element kind
is needed — they skip all cross-element bookkeeping. Same-type block nesting
(> > opening two blockquote frames) matches the full parse, capped by the
grammar’s max_nest. The remaining trade-off is opacity: a bold marker
inside a fenced code block will be matched by find_bolds but suppressed by
the full parser. This divergence is by design and documented — and closable:
// Build the opaque-region map once (fenced blocks, code spans, autolinks,
// links), then run any number of context-aware finders over it.
let ctx = MarkdownParser::context(src).unwrap();
for span in MarkdownParser::find_context_bolds(src, &ctx).unwrap() {
// bold markers inside code spans and fenced blocks are skipped,
// matching the full parse
}
Transparent symmetric/asymmetric and non-fence line/block rules get
a find_context_* variant. The map is built once and shared across them.
Declarative grammar — one invocation, full parser
The engine has no built-in knowledge of any text format. You describe your
format as a grammar and the engine compiles it into a parser at build time:
use meon::define_parser;
use std::num::NonZeroU8;
#[derive(Debug, Clone, Copy)]
pub struct Heading { pub level: NonZeroU8 }
define_parser!(MyFormat {
sep = b' ', eol = b'\n', tab = b'\t', escape = b'\\';
limits {
offset = u32;
max_nest = 4;
max_inline_span = 0;
max_line_span = 0;
max_block_span = 0;
max_input_bytes = 0;
}
inline {
on_trigger(b'*') {
symmetric b'*' {
parse_inside = true;
1 => italics [40],
2 => bolds [40],
}
}
fallback => texts [10];
}
lines {
line(b'#', max = 6) |n|:
Heading { level: NonZeroU8::new(n).unwrap_or(NonZeroU8::MIN) }
=> headings [200];
}
blocks {
block_simple {
fence(b'`', min = 3) => fenced_codes [400];
}
fallback => paragraphs [80];
}
});
// Generated:
// MyFormatParser::parse(src) -> Result<MyFormatContent<'_>, InputBytesTooLarge>
// MyFormatParser::parse_unchecked(src) -> MyFormatContent<'_>
// MyFormatParser::find_bolds(src) -> Result<impl Iterator<Item = Span>, InputBytesTooLarge>
// MyFormatParser::find_bolds_unchecked(src) -> impl Iterator<Item = Span>
// MyFormatParser::find_headings(src) -> Result<impl Iterator<Item = (Heading, Span)>, InputBytesTooLarge>
// MyFormatParser::context(src) -> Result<ParseContext, InputBytesTooLarge>
// MyFormatParser::context_unchecked(src) -> ParseContext
// MyFormatParser::find_context_bolds(src, &ctx) -> Result<impl Iterator<Item = Span>, InputBytesTooLarge>
// MyFormatParser::find_context_bolds_unchecked(src, &ctx) -> impl Iterator<Item = Span>
// MyFormatContent::bolds_clean() -> impl Iterator<Item = &[u8]>
// MyFormatContent::bolds_raw() -> impl Iterator<Item = &[u8]>
// ... and more
Everything — the content struct, the parse method, all find_* iterators, all
accessors — is generated at compile time. There is no runtime dispatch, no
vtable, no grammar interpreter.
Limits
limits { ... } is optional. offset selects the span offset type (u8, u16, u32, u64, default u32). max_nest sets the shared nesting cap;
max_inline_span, max_line_span and max_block_span cap the length of an
emitted span in bytes, measured on the clean span without delimiters. 0 and
the offset type’s maximum mean absent: no check and no fallback code is
generated for that cap. A value above the offset maximum is a compile error.
When a span exceeds its cap it is not emitted: transparent inline elements
keep their inner spans and text, opaque inline elements are reparsed inside,
line and block items go to blocks { fallback => ... }, and an over-long
fence is reparsed as paragraph runs.
max_input_bytes caps the source length. 0 and the offset type’s maximum
mean that maximum; the checked methods reject input over it. _ or an absent
key means no check, and the parser reads only the prefix that fits. The check runs before any parser state is
allocated. The checked methods return Result<_, InputBytesTooLarge>; the
_unchecked variants skip the check and keep the old behaviour.
Repository structure
meon/ ← workspace root (this file)
├── meon/ ← parsing engine + runtime macros
├── meon-macros/ ← define_parser! proc-macro
├── meon-md/ ← Markdown grammar built on meon
├── meon-json/ ← JSON reader grammar built on meon
├── benches/ ← criterion benchmarks
└── fuzz/ ← cargo-fuzz harness
meon-md is a concrete grammar that parses a useful subset of Markdown. It
demonstrates that the engine covers real-world complexity, and serves as
the benchmark and fuzz target for the project.
meon-json is a second reference grammar — a flat, span-based JSON reader. It
shows the engine is not Markdown-specific: a structurally opposite format —
deep nesting, containers, key: value pairs, line breaks as ordinary content
— falls out of the same define_parser! primitives, emitting one flat Vec
per element kind (objects, arrays, strings, members) instead of a tree.
Feature flags
| Feature |
Effect |
avx2 |
32-byte SIMD search (requires nightly + AVX2 CPU) |
avx512 |
64-byte SIMD search (implies avx2) |
Without either flag the crate compiles on stable Rust.
License
meon is available under the
MIT OR APACHE-2.0 license.
评论