For seven days we moved to Rust the things a visitor doesn't see: routes, sessions, the queue, migrations. Day eight is the first step toward what they do see. Every DevSense article is Markdown that PHP turns into HTML. If Rust is ever going to serve articles, it has to do it the same way. Not similar. The same.
In short
- Task: move
MarkdownContentService::convert()from league/commonmark to comrak without changing a single byte. - How we check: PHP renders all 613 article files on the site (8 languages) and saves the Markdown and HTML to JSON. Rust renders the same Markdown and compares.
- First run: 605 of 613. Eight articles differed in the same small detail: spaces in blank code lines inside lists.
- Result: 613 of 613. The new crate
rust/crates/mdis already in production, but no page uses it yet. It's groundwork.
What PHP does
Rendering an article in DevSense is more than CommonMark. Here is what actually happens in MarkdownContentService:
$environment = new Environment([
'html_input' => 'allow', // our own guides: raw HTML allowed
]);
$environment->addExtension(new CommonMarkCoreExtension);
$environment->addExtension(new TableExtension);
$environment->addExtension(new FrontMatterExtension);
$environment->addRenderer(FencedCode::class, new CustomCodeBlockRenderer($locale), 100);
$result = (new MarkdownConverter($environment))->convert($markdown);
$html = $this->convertAlerts($result->getContent(), $locale); // > [!NOTE] → a coloured box
$html = $this->wrapTables($html, $locale); // wide tables scroll
$html = $this->markManualToc($html); // the hand-written contents list
Plus localizeLinks(): the link /en/php/8.4 in a Russian article becomes /ru/php/8.4.
The most visible part is CustomCodeBlockRenderer. A code block on the site is not a bare <pre>: it has a "Code: rust" label, a "Copy" button and, if the first line is a comment with a path, a header with the file name. All of it in 8 languages.
Why comrak
We went through the options in the article "Blade and Markdown in Rust". In short: pulldown-cmark is faster, but it emits a stream of events, and we need to replace one node type entirely. comrak builds a tree, like league/commonmark, and supports the same extensions: GFM tables, front matter, raw HTML. So the logic can be ported almost one to one.
The options are the same as in PHP:
let mut options = Options::default();
options.extension.table = true;
options.extension.front_matter_delimiter = Some("---".to_owned());
// 'html_input' => 'allow': the guides are ours, not visitors'.
options.render.r#unsafe = true;
Our own code block renderer, via the tree
In league/commonmark, a custom renderer is registered for a node class. In comrak there is nothing to register, but you can change the tree before rendering. We walk the nodes and replace each fenced code block with ready HTML:
for node in root.descendants() {
if let NodeValue::CodeBlock(block) = &node.data().value {
if block.fenced {
let html = code_block(&block.info, &block.literal, labels);
node.data_mut().value = NodeValue::HtmlBlock(NodeHtmlBlock::new(html));
}
}
}
let mut html = String::new();
format_html(root, &options, &mut html)?;
code_block is CustomCodeBlockRenderer::render() rewritten line by line: the same language parsing (preg_split('/\s+/', $info)[0] and the language- prefix), the same path detection in the first line, the same escaping as htmlspecialchars.
The texts (labels, "Copy", "Copied", callout titles) live in lang/*/ui.php. Laravel Rust has no translations yet (they're the next day), so the crate gets them from outside, as one struct:
pub struct Labels {
pub code_label: String, // ui.code.label ("Code: :lang")
pub code_label_plain: String, // ui.code.label_plain
pub copy: String, // ui.code.copy
pub copied: String, // ui.code.copied
pub table: String, // ui.markdown.table
pub alerts: [String; 5], // ui.md_alert.{note,tip,important,warning,caution}
pub icons_url: String, // BrandAsset::url('brand/icons.svg')
}
Three HTML passes, the same regexes
After rendering, PHP edits the HTML three times with regular expressions. We ported them as is, quirks included: > [!WARNING] callouts, table wrapping, marking the contents list. Here are the callouts as an example:
return preg_replace_callback(
'/<blockquote>\s*<p>\s*\[!(NOTE|WARNING|IMPORTANT|TIP|CAUTION)\]([\s\S]*?)<\/blockquote>/i',
static function (array $matches) use ($locale): string { /* <div class="markdown-alert …"> */ },
$html
);
static ALERT: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?i)<blockquote>[\t\n\x0B\x0C\r ]*<p>[\t\n\x0B\x0C\r ]*\[!(NOTE|WARNING|IMPORTANT|TIP|CAUTION)\]((?s:.)*?)</blockquote>")
.expect("a valid regex")
});
Two things that are easy to get wrong:
\sis not the same. In PCRE without theuflag it's six ASCII characters. In Rust,\sknows Unicode and will eat a non-breaking space. So instead of\swe use an explicit class[\t\n\x0B\x0C\r ].- Lookahead. The contents list is found with an expression that has
(?!</h2>), and theregexcrate can't do that: it guarantees linear time. For this one regex we tookfancy-regex.
How to compare: a corpus of real articles
Comparing "on a couple of examples" is pointless: bugs live in rare combinations that show up in one article out of a hundred. So the reference is PHP itself. The script tests/fixtures/dump.php boots Laravel, takes every article's Markdown file in every language and calls the very same convert() of the production service, through reflection, because the method is protected. The JSON gets the Markdown, the HTML, the HTML after localizeLinks() and the labels in all languages. The script writes nothing to the database or the cache.
$service = $app->make(MarkdownContentService::class);
$convert = new ReflectionMethod($service, 'convert');
$localize = new ReflectionMethod($service, 'localizeLinks');
foreach ($files as $file) {
$html = $convert->invoke($service, $markdown, $locale)['html'];
$documents[] = [
'path' => $relative,
'locale' => $locale,
'markdown' => $markdown,
'html' => $html,
'localized' => $localize->invoke($service, $html, $locale),
];
}
The Rust test reads this file, renders each Markdown and compares the bytes. On a mismatch it prints the first difference with 80 characters of context on both sides. That's enough to see the cause right away.
We don't put the full corpus in the repository: it's about 40 MB, and it changes with every article. Git holds a sample of five articles (sample.json), which CI runs. The full run is enabled by the MD_PARITY environment variable with a path to a fresh dump.
605 of 613
The first full run: 605 articles matched, 8 didn't. All eight differed in the same way. Schematically, it looked like this:
php: <code class="language-bash">docker compose up -d\n\nsail artisan migrate
rust: <code class="language-bash">docker compose up -d\n \nsail artisan migrate
A code block inside a list item, and in it a blank line where the author left three spaces. PHP produced an empty line, Rust produced three spaces.
Who is right? The reference cmark, like comrak, keeps the spaces beyond the item's indent. The difference is in league/commonmark: for a blank line, its ListItemParser jumps to the first non-space character, and the spaces are lost. Outside lists, both parsers behave the same.
We copied this quirk, but only where it exists:
let in_list_item = node
.ancestors()
.skip(1)
.any(|a| matches!(a.data().value, NodeValue::Item(_)));
let literal = if in_list_item {
blank_lines_emptied(&block.literal) // whitespace-only lines → empty
} else {
block.literal.clone()
};
Second run: 613 of 613, byte for byte, in all eight languages.
We could have gone the other way: declare comrak's behaviour correct and live with the difference. But "correct per the spec" is not the point here. The goal is that visitors don't notice the move, and search engines don't see changed pages.
What we ended up with
rust/crates/md/
├── src/lib.rs convert(), code_block(), convert_alerts(), wrap_tables(),
│ mark_manual_toc(), localize_links()
└── tests/
├── parity.rs 613/613 against the HTML PHP renders
└── fixtures/
├── dump.php the corpus, dumped by the PHP app itself
└── sample.json a sample for CI
The crate is already in production, but no page uses it yet. That's on purpose: first prove that Rust renders the same, then let it serve visitors.
And a new rule in the README: change the PHP renderer, change crates/md. The test won't let you forget: CI runs the sample, and the full corpus runs before every article migration.
What we took away from day eight
- The reference is the working system, not the spec. We checked against what PHP actually outputs and found a parser difference the docs don't mention.
- A corpus beats examples. 605 of 613 is 99%, but the remaining percent lives in real articles, not in made-up tests.
- Regexes don't port word for word.
\sand lookahead are different things in PCRE and in Rust.
What's next
Code block labels still come from outside, because Laravel Rust has no translations. Day nine is about them: how to move lang/*.php to Rust without parsing JSON at runtime, which data structures are faster, and what bug in PHP we found along the way.
Links
- comrak: CommonMark and GFM in Rust
- league/commonmark: the parser the PHP version of DevSense uses
- CommonMark spec: lists and code blocks
- fancy-regex: regular expressions with lookahead
- Blade and Markdown in Rust: why comrak and MiniJinja
- From Laravel to Laravel Rust. Day 7: the beta update and the mystery of the empty log