« Back to Search  |  Reader Mode  |  Switch to Full Retro Site View Links: Stay in Reader  |  Retro Mode: ON  |  Original »
GitHub · Extracted in 1685 ms

🐛 Raise instead of hanging when a parser rule does not advance (#444) · executablebooks/markdown-it-py@759f39e

Source: https://github.com/executablebooks/markdown-it-py/commit/759f39e95af31a8d69b2e77485ec27dc804fd143

Repository navigation

Commit 759f39e


Browse files
rupayon123 and hukkin authored 🐛 Raise instead of hanging when a parser rule does not advance (#444 ) A block or inline rule that reports a match without advancing `state.line` / `state.pos` (or moving it backwards) now raises `RuntimeError`, as markdown-it does, instead of looping forever. This covers block tokenize, inline tokenize and inline validation (`skipToken`). Also ported from markdown-it 14.1.0: - raise `none of the block rules matched` when no block rule accepts a line (only possible with `paragraph` disabled); - reset `ok` on every inline tokenize iteration, so a match from the previous iteration no longer causes an infinite loop once nesting reaches `maxNesting`. Closes #441 . Co-authored-by: Taneli Hukkinen <3275109+hukkin@users.noreply.github.com>
1 parent d774374 commit 759f39e

3 files changed

Lines changed: 142 additions & 2 deletions

File tree

‎markdown_it/parser_block.py‎

Lines changed: 9 additions & 1 deletion
Original file line number Diff line number Diff line change
@@ -83,10 +83,18 @@ def tokenize(self, state: StateBlock, startLine: int, endLine: int) -> None:
83 83 # - update `state.line`
84 84 # - update `state.tokens`
85 85 # - return True
86 + ok = False
86 87 for rule in rules:
87 - if rule(state, line, endLine, False):
88 + ok = rule(state, line, endLine, False)
89 + if ok:
90 + if state.line <= line:
91 + raise RuntimeError("block rule didn't increment state.line")
88 92 break
89 93
94 + # this can only happen if user disables paragraph rule
95 + if not ok:
96 + raise RuntimeError("none of the block rules matched")
97 +
90 98 # set state.tight if we had an empty line before current tag
91 99 # i.e. latest empty line should not count
92 100 state.tight = not hasEmptyLines

‎markdown_it/parser_inline.py‎

Lines changed: 6 additions & 1 deletion
Original file line number Diff line number Diff line change
@@ -152,6 +152,8 @@ def skipToken(self, state: StateInline) -> None:
152 152 ok = rule(state, True)
153 153 state.level -= 1
154 154 if ok:
155 + if state.pos <= pos:
156 + raise RuntimeError("inline rule didn't increment state.pos")
155 157 break
156 158 else:
157 159 # Too much nesting, just skip until the end of the paragraph.
@@ -173,12 +175,13 @@ def skipToken(self, state: StateInline) -> None:
173 175
174 176 def tokenize(self, state: StateInline) -> None:
175 177 """Generate tokens for input range."""
176 - ok = False
177 178 rules = self.ruler.getRules("")
178 179 end = state.posMax
179 180 maxNesting = state.md.options["maxNesting"]
180 181
181 182 while state.pos < end:
183 + pos = state.pos
184 + ok = False
182 185 # Try all possible rules.
183 186 # On success, rule should:
184 187 #
@@ -190,6 +193,8 @@ def tokenize(self, state: StateInline) -> None:
190 193 for rule in rules:
191 194 ok = rule(state, False)
192 195 if ok:
196 + if state.pos <= pos:
197 + raise RuntimeError("inline rule didn't increment state.pos")
193 198 break
194 199
195 200 if ok:

‎tests/test_parser_progress.py‎

Lines changed: 127 additions & 0 deletions
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
1 +"""Regression tests for custom rules that claim a match without consuming input."""
2 +
3 +import pytest
4 +
5 +from markdown_it import MarkdownIt
6 +from markdown_it.rules_block.state_block import StateBlock
7 +from markdown_it.rules_inline.state_inline import StateInline
8 +
9 +
10 +def test_block_rule_must_advance_line() -> None:
11 + md = MarkdownIt("commonmark")
12 + md.block.ruler.before("paragraph", "stuck", lambda state, start, end, silent: True)
13 +
14 + with pytest.raises(RuntimeError, match=r"block rule didn't increment state\.line"):
15 + md.parse("text\n")
16 +
17 +
18 +def test_inline_rule_must_advance_position() -> None:
19 + md = MarkdownIt("commonmark")
20 + md.inline.ruler.before("text", "stuck", lambda state, silent: True)
21 +
22 + with pytest.raises(RuntimeError, match=r"inline rule didn't increment state\.pos"):
23 + md.parse("text")
24 +
25 +
26 +def test_inline_validation_rule_must_advance_position() -> None:
27 + md = MarkdownIt("commonmark")
28 + md.inline.ruler.before("text", "stuck", lambda state, silent: True)
29 + state = StateInline("text", md, {}, [])
30 +
31 + with pytest.raises(RuntimeError, match=r"inline rule didn't increment state\.pos"):
32 + md.inline.skipToken(state)
33 +
34 +
35 +def test_no_block_rule_matched() -> None:
36 + """Without the paragraph fallback, a line no rule accepts must raise, not hang."""
37 + md = MarkdownIt("commonmark").disable("paragraph")
38 +
39 + with pytest.raises(RuntimeError, match=r"none of the block rules matched"):
40 + md.parse("text\n")
41 +
42 +
43 +def test_inline_ok_is_reset_at_max_nesting() -> None:
44 + """A match must not carry over to an iteration where nesting skips the rules.
45 +
46 + The rule below opens a ``sup`` token and never closes it, so with
47 + ``maxNesting=1`` the next iteration skips every rule. The text must then
48 + fall through as plain text, as in markdown-it, instead of looping.
49 + """
50 +
51 + def caret(state: StateInline, silent: bool) -> bool:
52 + if state.src[state.pos] != "^":
53 + return False
54 + if not silent:
55 + state.push("sup_open", "sup", 1)
56 + state.pos += 1
57 + return True
58 +
59 + md = MarkdownIt("commonmark", {"maxNesting": 1})
60 + md.inline.ruler.before("text", "caret", caret)
61 +
62 + assert md.render("^ab\n") == "<p><sup>ab</p>\n"
63 +
64 +
65 +def test_block_rule_must_not_move_line_backwards() -> None:
66 + """A rule that moves ``state.line`` back also fails to advance (``<=``, not ``==``)."""
67 + fired: list[bool] = []
68 +
69 + def rewind(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
70 + if startLine == 0 or fired:
71 + return False
72 + fired.append(True)
73 + state.line = startLine - 1
74 + return True
75 +
76 + md = MarkdownIt("commonmark")
77 + md.block.ruler.before("paragraph", "rewind", rewind)
78 +
79 + with pytest.raises(RuntimeError, match=r"block rule didn't increment state\.line"):
80 + md.parse("a\n\nb\n")
81 +
82 +
83 +def test_inline_rule_must_not_move_position_backwards() -> None:
84 + """A rule that moves ``state.pos`` back also fails to advance (``<=``, not ``==``)."""
85 + fired: list[bool] = []
86 +
87 + def rewind(state: StateInline, silent: bool) -> bool:
88 + if state.pos == 0 or fired:
89 + return False
90 + fired.append(True)
91 + state.pos -= 1
92 + return True
93 +
94 + md = MarkdownIt("commonmark")
95 + md.inline.ruler.before("text", "rewind", rewind)
96 +
97 + # the text rule consumes "a" in one step, so the rule first fires at "*"
98 + with pytest.raises(RuntimeError, match=r"inline rule didn't increment state\.pos"):
99 + md.parse("a*b")
100 +
101 +
102 +def test_silent_rule_must_advance_through_link_label() -> None:
103 + """``skipToken`` is reached through link-label scanning, in silent mode only."""
104 + md = MarkdownIt("commonmark")
105 + md.inline.ruler.before("text", "stuck", lambda state, silent: silent)
106 +
107 + with pytest.raises(RuntimeError, match=r"inline rule didn't increment state\.pos"):
108 + md.parse("[x](u)")
109 +
110 +
111 +def test_silent_rule_must_not_move_position_backwards() -> None:
112 + """``skipToken`` also rejects a backward move (``<=``, not ``==``)."""
113 + fired: list[bool] = []
114 +
115 + def rewind(state: StateInline, silent: bool) -> bool:
116 + if not silent or fired or state.pos == 0:
117 + return False
118 + fired.append(True)
119 + state.pos -= 1
120 + return True
121 +
122 + md = MarkdownIt("commonmark")
123 + md.inline.ruler.before("text", "rewind", rewind)
124 +
125 + # reached through link-label scanning, in silent mode
126 + with pytest.raises(RuntimeError, match=r"inline rule didn't increment state\.pos"):
127 + md.parse("[xy](u)")