Repository navigation
fix: keep the line offsets of inline tokens when rules call getLines again (DEV-3364) - #26
galaxian85 wants to merge 2 commits into
Conversation
…again (DEV-3364) StateBlock#getLines overwrites lineOffsets and linePads for its lines, and inline parsing runs after the whole block parse, so a rule that read the lines of an inline token pushed earlier (e.g. a plugin probing earlier lines) changed how that token's children were mapped to the source. Before a getLines call overwrites lines of an inline token pushed earlier, save that token's values on the block state; the core inline rule writes them back before parsing the token. Rules that only read lines after the tokens pushed so far (all built-in rules) take a fast path, so documents without such probes pay almost nothing and their positions are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Coverage Report for CI Build 44482659639Warning No base build found for commit Coverage: 98.937%Details
Uncovered Changes
Coverage RegressionsRequires a base build to compare against. How to fix this → Coverage Stats💛 - Coveralls |
Yukaii
left a comment
There was a problem hiding this comment.
Review of ecdf3ab (COMMENT only).
Verdict: OK to merge after deciding on the P2 below. Risk: low. No P0/P1 found. Built-in rules never hit the new save path, and token positions and HTML stay the same when no plugin calls getLines again.
What I checked on this head:
npm teston Node 24.21: lint ok, build ok, mocha 1626 passing, 1 pending, specsplit ok (master: 1620 passing). The same run on Node 26 stops inside c8 (require is not definedin c8's yargs), so that failure comes from the environment and not from this PR.- The repro table in the description, with the
look_backrule: on master theb/cchildren sit at 4/7 (>,), 4/7 (list), and 6/9 (nested> >). With this PR they sit at 6/9, 6/9 and 10/17, the same as without the plugin.a\n b *c*is unaffected either way. - No-plugin A/B against master: 4853 documents (each fixture file, each fixture example bare, inside
>and inside-, plusbenchmark/samples), with default options and with html+linkify+typographer. Every token and childposition/size/mapand the rendered HTML are byte-identical. - Performance: a local micro-benchmark (benchmark samples, the CommonMark spec, a 3000-row table; median of 5) shows only noise-level differences from master. The incremental scan plus the
begin >= lineEndearly return keepsgetLinescheap for built-in rules. - Merged with #27 onto master in both orders: the only conflict is the
[14.2.1]section ofCHANGELOG.md;test/annotation.jsmerges cleanly. With the CHANGELOG resolved to two bullets,npm testgives 1630 passing, and the table trap test still passes.
Findings:
- P2
lib/rules_block/state_block.mjs:213: the "still being built" exception only applies when the empty inline token is the last token. If a rule pushesopen/inline/closefirst and then fills the content withgetLines, master gives correct positions and this PR gives wrong ones (repro inline). - nit
test/annotation.js:745,:801: the comments name a downstream project and an issue-tracker ID. This is a public repo, so it is better to describe these generically.
The core-rule window (core rules that run between block and inline see the overwritten values) and the table limitation are both documented in the getLines comment and in the CHANGELOG. That is fine for this PR.
Merge order with #27: either order works. I'd merge #27 first because it is smaller and self-contained. This PR then rebases and keeps both bullets under the single ### Fixed in [14.2.1] - Unreleased.
| if (token.type !== 'inline' || !token.map) continue | ||
| // still being built: its content may come from the call being made | ||
| // (e.g. definition list terms), and the values are its own | ||
| if (token.content === '' && i === tokens.length - 1) break |
There was a problem hiding this comment.
P2: a token whose content is filled after a later token is pushed gets a stale snapshot.
The exception only applies to an empty inline token at tokens.length - 1. Suppose a rule pushes open, inline (empty) and close, and then sets inline.content = state.getLines(...). That call finds the inline token already scanned (it is not last), begin < lineEnd, so saveTokenLines snapshots the values from before this call. The core inline rule then writes those stale values back over the correct ones.
Repro (no probing plugin involved):
const md = markdownit()
md.block.ruler.before('paragraph', 'late', (state, s, e, silent) => {
const pos = state.bMarks[s] + state.tShift[s]
if (!state.src.startsWith('::: ', pos)) return false
if (silent) return true
const o = state.push('box_open', 'div', 1); o.map = [s, s + 3]
const t = state.push('inline', '', 0); t.map = [s + 1, s + 3]; t.children = []
state.push('box_close', 'div', -1)
t.content = state.getLines(s + 1, s + 3, state.blkIndent, false)
t.position = state.bMarks[s + 1] + state.tShift[s + 1]
state.line = s + 3
return true
})
md.parse('> ::: x\n> a\n> b *c*\n\nnext', {})Text children: master a@10 "b "@14 c@17 (correct). This PR: a@10 "b "@12 c@15, which point at > and .
So for this push order, the PR makes correct output wrong. No built-in rule pushes in this order, so this is a plugin-API concern. Options: use a more general way to detect "still being built". A plain "any empty inline" check isn't enough, because an empty heading like # would block the scan forever. Or document in the getLines comment and CHANGELOG that a rule must call getLines for an inline token's content before pushing anything after that token.
| } | ||
|
|
||
| // `lineOffsets` of each inline token, read from the block state during | ||
| // inline parsing (as plugins of hackmd-production do). |
There was a problem hiding this comment.
nit: this is a public repo, so I'd describe it generically (e.g. "as plugins reading state.env.state_block.lineOffsets do") rather than naming a downstream project.
| textMapsToSource(src, probed.parse(src, {})) | ||
| assert.deepStrictEqual(positions(probed.parse(src, {})), positions(plain.parse(src, {})), JSON.stringify(src)) | ||
| }) | ||
| // the first example of DEV-3364 |
There was a problem hiding this comment.
nit: the issue-tracker ID means nothing to readers of the public repo. Something like // a paragraph in a blockquote, probed from a later line would explain the case better.
DEV-3364
摘要
StateBlock#getLines每次呼叫都會覆寫[begin, end)的lineOffsets/linePads。inline 解析在整份文件的 block 解析結束後才跑,所以如果某個 rule 在 inline token 建立之後,又對同樣的行呼叫getLines(例如往回探查),這個 token 的子 token 位置就會錯。這個 PR 在覆寫前把該 token 的值存起來,coreinlinerule 解析它之前再寫回去。這是 14.2.1 批次的一部分,merge 後先不要發版。
輸出的 HTML 不變。沒有這種 plugin 的文件,所有位置都不變。hackmd-production 不用改 code。
問題和重現
一個 block rule 在每一行往回讀前 3 行,然後放棄:
> a\n> b *c*\n\nnextb、c>)、7()- a\n b *c*\n\nnextb、c)、7> > a\n> > b\n> > *c*\n\nnextb、c>)、9沒有容器(例如
a\n b *c*)的段落不受影響,因為那時每行被拿掉的字元數本來就和探查的結果一樣。調查結果:只有自訂 plugin 會踩到
paragraph、lheading、code、fence、html_block都是決定建立 token 之後,才對自己的行呼叫getLines。用 instrumented 的getLines跑過所有 fixture 和 benchmark 樣本(3284 份),沒有任何一次覆寫到已建立的 inline token 的行。extra.js,透過loadFrontendRenderer)和 server 的getParser()解析 55 份樣本:spoiler、extraTag、mention、smartypants、deflist、svg、alert 放在 blockquote/list/巢狀容器/lazy continuation 的多行段落裡。覆寫次數是 0。@hackmd/markdown-it-deflist2.2.2 是先 push 空的 inline token,再對 term 那一行呼叫getLines,讀的是自己的行。svg.ts是決定建立svg_block之後,才對自己的行呼叫。修法
不是在 push inline token 時就存快照,而是等到真的要被覆寫時才存:
getLines開始時,先看自上次呼叫以來新 push 的 token,更新「已 push 的 inline token 最遠到哪一行」(_inlineLineEnd)。begin在這一行之後就直接返回(內建 rule 都是這種情況)。map和[begin, end)重疊的 inline token,把它map範圍內的lineOffsets/linePads存進 block state 上的_inlineSaved(Map,key 是 token)。inlinerule 解析每個 inline token 前,如果它有存值,就寫回 block state 的陣列。和 Linear 建議的做法(push 時存快照)不同,理由:
lheading是 push inline token 之後才呼叫trimmedContentStart重新起算lineOffsets;deflist 也是先 push、再用getLines設 content。push 時存的快照會是錯的。延到下一次getLines開始時,這些都已經完成了。快照放在 block state 的
_inlineScanned/_inlineLineEnd/_inlineSaved上,不在 token 上,也不會被序列化。lineOffsets/linePads的名稱、索引方式(絕對行號),以及「inline 解析時陣列裡是當下 inline token 的偏移」這個語意都沒變,所以直接讀state.env.state_block.lineOffsets的 production plugin(githubAlertsPositionPlugin.js、extraTagPlugin.js)和透過getLineOffset讀的 plugin 都不用改。沒有涵蓋的部分(已寫進註解和 CHANGELOG)
getLines建立 inline token 的 rule(例如表格)會直接讀陣列裡現有的值。如果在那之前有 rule 探查過這些行,位置還是會錯,例如 blockquote 裡的表格配上往前探查的 plugin。這一點加了一個記錄現況的測試。建議探查改用getLine/bMarks/eMarks。inlinerule 裡。 在 block 和 inline 之間執行的 core rule 讀到的還是被覆寫的值。production 的githubAlertsPositionPlugin.js就是在這個時間點讀陣列,但 production 沒有會覆寫的 plugin,所以不受影響。效能
repo 的
benchmark/benchmark.mjs需要先全域安裝舊版 marked/commonmark(benchmark-deps),所以改用同一套 Benchmark.js 和benchmark/samples,只比較 master 和這個 branch(Node 24,html/linkify/typographer開啟),28 個樣本取幾何平均:差異落在雜訊範圍內。第一版每一行都記錄 owner,小文件會慢 4–6%(
block-fences慢 20%),所以改成上面的快速路徑。測試
test/annotation.js新增 6 個測試(Annotation with rules calling getLines again)。修正前,其中 5 個會失敗:begin和indent讀自己行的 rule(包住paragraph)。getLines設 content),配上前後探查。這個測試會抓到「把還在建立的 token 也納入」的錯誤實作(拿掉那個判斷時,這個測試會失敗)。state.env.state_block.lineOffsets和getLineOffset/getLinePad得到的值,要和沒有探查時一樣(production plugin 的讀法)。既有的測試都沒改。
npm test(Node 24):1626 passing、1 pending,lint 通過。和 #25(DEV-3359)一起測:在臨時 worktree 把 #25 merge 進來(只有 CHANGELOG 衝突),
npm test1630 passing。paragraph_close.position是在 push 時就算好的,有探查的 plugin 時結果也一樣(例如> a\n> b是 7)。hackmd-production 驗證
在 #6100 的 branch(
fix/dev-3358-code-source-map-real-line-starts,14.2.0)用 symlink 換成這個 branch build 出來的 fork,用bin/agent/test跑和 markdown 相關的 spec:另外用臨時 spec(沒有 commit)比較 npm 14.2.0 和 fork 的 token:用 frontend renderer 和 server parser 解析 55 份樣本(spoiler、extraTag、mention、smartypants、deflist、svg、alert,放在各種容器裡的多行段落),所有 token 和子 token 的
position/size/map、mention 的data-position,以及輸出的 HTML 完全相同。production 沒有會觸發這個問題的 plugin,所以沒有「原本錯、現在修正」的差異。🤖 Generated with Claude Code