From 5a3d1f47e6fc18cc6db2836b303b088fb061573a Mon Sep 17 00:00:00 2001 From: librarian <57712678+LibraryLibrarian@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:14:11 +0900 Subject: [PATCH 1/4] =?UTF-8?q?perf:=20=E6=9C=AA=E9=96=89=E3=81=98=20=20=E3=81=AE=E5=8F=8D=E5=BE=A9=E3=81=A7=E9=96=89=E3=81=98?= =?UTF-8?q?=E3=82=BF=E3=82=B0=E3=81=AE=E6=8E=A2=E7=B4=A2=E7=B5=90=E6=9E=9C?= =?UTF-8?q?=E3=82=92=E5=86=8D=E5=88=A9=E7=94=A8=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1 回の解析中だけ の探索結果(発見位置または不在)を共有し、二次の再走査を無くす。 あわせて url/link の substring(position).startsWith を startsWith(pattern, position) に置き換えて全文コピーを避ける。 Co-Authored-By: Codex Sol --- lib/src/parser/inline/link.dart | 2 +- lib/src/parser/inline/plain.dart | 90 +++++- lib/src/parser/inline/url.dart | 8 +- lib/src/parser/parser.dart | 12 +- test/core/parser/inline/plain_cache_test.dart | 259 ++++++++++++++++++ 5 files changed, 352 insertions(+), 19 deletions(-) create mode 100644 test/core/parser/inline/plain_cache_test.dart diff --git a/lib/src/parser/inline/link.dart b/lib/src/parser/inline/link.dart index 061b4b2..4a9e3f5 100644 --- a/lib/src/parser/inline/link.dart +++ b/lib/src/parser/inline/link.dart @@ -73,7 +73,7 @@ class _LinkParserImpl extends Parser { // サイレントリンクかどうかを判定 bool silent; - if (buffer.substring(position).startsWith('?[')) { + if (buffer.startsWith('?[', position)) { silent = true; position += 2; } else if (position < buffer.length && buffer[position] == '[') { diff --git a/lib/src/parser/inline/plain.dart b/lib/src/parser/inline/plain.dart index d607094..4ef3a62 100644 --- a/lib/src/parser/inline/plain.dart +++ b/lib/src/parser/inline/plain.dart @@ -12,6 +12,28 @@ import '../../ast.dart'; /// - 内部の改行は許可される /// - 内容はTextNodeとして扱われる(MFM構文は解釈されない) class PlainParser { + Map? _searchSpans; + + /// [parser] の1回の解析中だけ、閉じタグの探索結果を共有する。 + /// + /// 引用内の再パースなどで使う別バッファは、同一性で区別する。 + /// 最上位のパーサーだけを包み、解析後は入力への参照も破棄する。 + Parser withSearchCache(Parser parser) => + _PlainSearchCacheParser(parser, this); + + int _findClose(String buffer, int start) { + final spans = _searchSpans; + final span = spans?[buffer]; + if (span != null && + start >= span.start && + (span.close < 0 || start <= span.close)) { + return span.close; + } + final close = buffer.indexOf('', start); + spans?[buffer] = _PlainSearchSpan(start, close); + return close; + } + /// plain タグパーサー /// /// 内部はパースせず、TextNodeとしてそのまま扱う @@ -28,15 +50,63 @@ class PlainParser { .flatten(); // seq5で型安全なシーケンスパース - return seq5( - open, - lineBreak.optional(), - content, - lineBreak.optional(), - close, - ).map5((openTag, leadingNewline, text, trailingNewline, closeTag) { - // PlainNodeは子ノードとしてTextNodeのリストを持つ - return PlainNode([TextNode(text)]); - }); + final parser = + seq5( + open, + lineBreak.optional(), + content, + lineBreak.optional(), + close, + ).map5((openTag, leadingNewline, text, trailingNewline, closeTag) { + // PlainNodeは子ノードとしてTextNodeのリストを持つ + return PlainNode([TextNode(text)]); + }); + return _PlainCloseGuard(parser, this); } } + +class _PlainSearchSpan { + _PlainSearchSpan(this.start, this.close); + final int start; + final int close; +} + +class _PlainSearchCacheParser extends DelegateParser { + _PlainSearchCacheParser(super.delegate, this.plain); + final PlainParser plain; + + @override + Result parseOn(Context context) { + final previous = plain._searchSpans; + plain._searchSpans = Map.identity(); + try { + return delegate.parseOn(context); + } finally { + plain._searchSpans = previous; + } + } + + @override + _PlainSearchCacheParser copy() => + _PlainSearchCacheParser(delegate, plain); +} + +class _PlainCloseGuard extends DelegateParser { + _PlainCloseGuard(super.delegate, this.plain); + final PlainParser plain; + + @override + Result parseOn(Context context) { + final buffer = context.buffer; + final position = context.position; + if (buffer.startsWith('', position) && + plain._findClose(buffer, position + ''.length) < 0) { + // 未閉じでも入力を消費せず、既存の通常構文へのフォールバックを保つ。 + return context.failure('"" expected', buffer.length); + } + return delegate.parseOn(context); + } + + @override + _PlainCloseGuard copy() => _PlainCloseGuard(delegate, plain); +} diff --git a/lib/src/parser/inline/url.dart b/lib/src/parser/inline/url.dart index 693fc90..81301e7 100644 --- a/lib/src/parser/inline/url.dart +++ b/lib/src/parser/inline/url.dart @@ -76,10 +76,10 @@ class _UrlParserImpl extends Parser { // スキーマをチェック(https:// または http://) String? schema; - if (buffer.substring(position).startsWith('https://')) { + if (buffer.startsWith('https://', position)) { schema = 'https://'; position += 8; - } else if (buffer.substring(position).startsWith('http://')) { + } else if (buffer.startsWith('http://', position)) { schema = 'http://'; position += 7; } else { @@ -213,10 +213,10 @@ class _UrlAltParserImpl extends Parser { // スキーマをチェック(https:// または http://) String? schema; - if (buffer.substring(position).startsWith('https://')) { + if (buffer.startsWith('https://', position)) { schema = 'https://'; position += 8; - } else if (buffer.substring(position).startsWith('http://')) { + } else if (buffer.startsWith('http://', position)) { schema = 'http://'; position += 7; } else { diff --git a/lib/src/parser/parser.dart b/lib/src/parser/parser.dart index 5b91e6b..4ee1d27 100644 --- a/lib/src/parser/parser.dart +++ b/lib/src/parser/parser.dart @@ -74,7 +74,8 @@ class MfmParser { final inlineCode = InlineCodeParser().buildWithFallback(); // plainタグパーサー(パース無効化) - final plainTag = PlainParser().build(); + final plain = PlainParser(); + final plainTag = plain.build(); // インライン数式パーサー final mathInline = MathInlineParser().build(); @@ -280,7 +281,7 @@ class MfmParser { final start = full.plus().map(mergeAdjacentTextNodes).end(); - return withNestBudget(start, nestState); + return plain.withSearchCache(withNestBudget(start, nestState)); } /// Builds and returns a simple parser. @@ -316,7 +317,8 @@ class MfmParser { final emojiCode = EmojiCodeParser().build(); // plainタグパーサー(emojiCodeを内部でパースしないため必要) - final plainTag = PlainParser().build(); + final plain = PlainParser(); + final plainTag = plain.build(); // stopper: 各構文の開始文字 // mfm-js仕様: unicodeEmoji > emojiCode > plainTag > text @@ -335,6 +337,8 @@ class MfmParser { final simple = (unicodeEmoji | emojiCode | plainTag | textParser | oneChar) .cast(); - return simple.plus().map(mergeAdjacentTextNodes).end(); + return plain.withSearchCache( + simple.plus().map(mergeAdjacentTextNodes).end(), + ); } } diff --git a/test/core/parser/inline/plain_cache_test.dart b/test/core/parser/inline/plain_cache_test.dart new file mode 100644 index 0000000..4f6b1be --- /dev/null +++ b/test/core/parser/inline/plain_cache_test.dart @@ -0,0 +1,259 @@ +import 'dart:convert'; + +import 'package:misskey_mfm_parser/src/ast.dart'; +import 'package:misskey_mfm_parser/src/parser/parser.dart'; +import 'package:petitparser/petitparser.dart'; +import 'package:test/test.dart'; + +import '../../../support/ast_json.dart'; + +// Expected ASTs were checked against mfm.js 0.28.0 parse/parseSimple. +// Keep the oracle output here so these tests do not depend on Node.js. +void main() { + const commonCases = [ + ( + name: 'closed plain', + input: 'abc', + expected: ''' + [{"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"abc"},"children":[]} + ]}] + ''', + ), + ( + name: 'nested opening tag uses the first closing tag', + input: 'x', + expected: ''' + [{"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"x"},"children":[]} + ]},{"type":"text","props":{"text":""},"children":[]}] + ''', + ), + ( + name: 'closing tag in the middle leaves an unclosed suffix', + input: 'x:wave:', + expected: ''' + [{"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"x"},"children":[]} + ]},{"type":"text","props":{"text":""},"children":[]}, + {"type":"emojiCode","props":{"name":"wave"},"children":[]}] + ''', + ), + ( + name: 'search advances beyond an earlier closing tag', + input: 'ab', + expected: ''' + [{"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"a"},"children":[]} + ]},{"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"b"},"children":[]} + ]}] + ''', + ), + ( + name: 'empty plain fails without hiding a later valid plain', + input: 'x', + expected: ''' + [{"type":"text","props":{"text":""},"children":[]}, + {"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"x"},"children":[]} + ]}] + ''', + ), + ( + name: 'newline-only content is still invalid', + input: '\n', + expected: r''' + [{"type":"text","props":{"text":"\n"},"children":[]}] + ''', + ), + ( + name: 'one leading and trailing CRLF are stripped', + input: '\r\nabc\r\n', + expected: ''' + [{"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"abc"},"children":[]} + ]}] + ''', + ), + ( + name: 'one leading and trailing CR are stripped', + input: '\ra\r', + expected: ''' + [{"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"a"},"children":[]} + ]}] + ''', + ), + ( + name: 'additional newlines are preserved', + input: '\n\nabc\n\n', + expected: r''' + [{"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"\nabc\n"},"children":[]} + ]}] + ''', + ), + ( + name: 'backtracking to an earlier opening tag keeps its closing tag', + input: '[:wave:](https://example.com) x', + expected: ''' + [{"type":"text","props":{"text":"["},"children":[]}, + {"type":"plain","props":{},"children":[ + {"type":"text","props":{ + "text":":wave:](https://example.com) x" + },"children":[]} + ]}] + ''', + ), + ]; + + for (final simple in [false, true]) { + group('plain search cache (${simple ? 'simple' : 'full'})', () { + final parser = simple ? MfmParser().buildSimple() : MfmParser().build(); + + void expectAst(String input, Object? expected) { + final result = parser.parse(input); + expect(result, isA>>()); + expect(result.position, input.length); + expect( + serializeMfmAst((result as Success>).value), + expected, + ); + } + + for (final fixture in commonCases) { + test(fixture.name, () { + expectAst(fixture.input, jsonDecode(fixture.expected)); + }); + } + + test('3000 unclosed opening tags preserve all text', () { + final input = '' * 3000; + expectAst(input, [ + { + 'type': 'text', + 'props': {'text': input}, + 'children': [], + }, + ]); + }); + + test('unclosed plain keeps subsequent syntax parsing', () { + expectAst( + ':wave: **bold**', + jsonDecode( + simple + ? ''' + [{"type":"text","props":{"text":""},"children":[]}, + {"type":"emojiCode","props":{"name":"wave"},"children":[]}, + {"type":"text","props":{"text":" **bold**"},"children":[]}] + ''' + : ''' + [{"type":"text","props":{"text":""},"children":[]}, + {"type":"emojiCode","props":{"name":"wave"},"children":[]}, + {"type":"text","props":{"text":" "},"children":[]}, + {"type":"bold","props":{},"children":[ + {"type":"text","props":{"text":"bold"},"children":[]} + ]}] + ''', + ), + ); + }); + + test('parser reuse handles present and absent closing tags', () { + for (var i = 0; i < 3; i++) { + expectAst( + ':wave:', + jsonDecode(''' + [{"type":"text","props":{"text":""},"children":[]}, + {"type":"emojiCode","props":{"name":"wave"},"children":[]}] + '''), + ); + expectAst( + ':wave:', + jsonDecode(''' + [{"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":":wave:"},"children":[]} + ]}] + '''), + ); + } + }); + + test('plain inside formatting keeps the existing AST', () { + expectAst( + '**x**', + jsonDecode( + simple + ? ''' + [{"type":"text","props":{"text":"**"},"children":[]}, + {"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"x"},"children":[]} + ]},{"type":"text","props":{"text":"**"},"children":[]}] + ''' + : ''' + [{"type":"bold","props":{},"children":[ + {"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"x"},"children":[]} + ]} + ]}] + ''', + ), + ); + }); + + test('plain inside a link label keeps the existing AST', () { + expectAst( + '[x](https://example.com)', + jsonDecode( + simple + ? ''' + [{"type":"text","props":{"text":"["},"children":[]}, + {"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"x"},"children":[]} + ]},{"type":"text","props":{ + "text":"](https://example.com)" + },"children":[]}] + ''' + : ''' + [{"type":"link","props":{ + "silent":false,"url":"https://example.com" + },"children":[ + {"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"x"},"children":[]} + ]} + ]}] + ''', + ), + ); + }); + + test('quote buffers do not reuse outer-buffer search results', () { + expectAst( + '> unclosed\n\nx', + jsonDecode( + simple + ? r''' + [{"type":"text","props":{"text":"> "},"children":[]}, + {"type":"plain","props":{},"children":[ + {"type":"text","props":{ + "text":"unclosed\n\nx" + },"children":[]} + ]}] + ''' + : ''' + [{"type":"quote","props":{},"children":[ + {"type":"text","props":{ + "text":"unclosed" + },"children":[]} + ]},{"type":"plain","props":{},"children":[ + {"type":"text","props":{"text":"x"},"children":[]} + ]}] + ''', + ), + ); + }); + }); + } +} From c9767c2bdc633c46cc2ad4cdd31fb5d8e8be8b85 Mon Sep 17 00:00:00 2001 From: librarian <57712678+LibraryLibrarian@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:27:24 +0900 Subject: [PATCH 2/4] =?UTF-8?q?perf:=20=E6=9C=AA=E9=96=89=E3=81=98=20[=20/?= =?UTF-8?q?=20\(=20/=20
=20=E3=81=AE=E5=8F=8D=E5=BE=A9=E3=81=A7?= =?UTF-8?q?=E5=A4=B1=E6=95=97=E3=81=97=E3=81=9F=E8=B5=B0=E6=9F=BB=E3=82=92?= =?UTF-8?q?=E5=86=8D=E5=88=A9=E7=94=A8=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1 回の解析中だけ、失敗した走査区間とネスト予算の消費量を記録して再生し、二次の再走査を無くす。 予算の消費量と AST は変えない。 Co-Authored-By: Codex Sol --- lib/src/parser/block/center.dart | 76 +++-- lib/src/parser/core/scan_cache.dart | 150 ++++++++++ lib/src/parser/inline/link.dart | 40 ++- lib/src/parser/inline/math_inline.dart | 61 +++- lib/src/parser/parser.dart | 26 +- test/core/parser/failed_scan_cache_test.dart | 282 +++++++++++++++++++ 6 files changed, 601 insertions(+), 34 deletions(-) create mode 100644 lib/src/parser/core/scan_cache.dart create mode 100644 test/core/parser/failed_scan_cache_test.dart diff --git a/lib/src/parser/block/center.dart b/lib/src/parser/block/center.dart index bfe2a52..b03b905 100644 --- a/lib/src/parser/block/center.dart +++ b/lib/src/parser/block/center.dart @@ -4,6 +4,7 @@ import '../../ast.dart'; import '../common/utils.dart'; import '../core/guards.dart'; import '../core/nest.dart'; +import '../core/scan_cache.dart'; /// 中央寄せブロックパーサー /// @@ -14,6 +15,11 @@ import '../core/nest.dart'; /// - `
` は行末でなければならない(入力末尾または直後が改行) /// - 前後の改行はブロック構文として消費される class CenterParser { + final _cache = FailedScanCache(); + + Parser withSearchCache(Parser parser) => + _cache.withSearchCache(parser); + /// center タグ(基本版) Parser build() { final lineBreak = newline(); @@ -64,30 +70,66 @@ class CenterParser { // P.seq(newLine.option(), close) // ), nest(r.inline) // ).select(1).many(1) - final innerList = seq2( + final inner = seq2( (lineBreak.optional() & end).not(), nest(inline, state: state), - ).map((r) => r.$2).plus(); + ).map((r) => r.$2); // 終了タグ直前の改行チェック final optionalNewlineBeforeEnd = lineBreak.optional(); // mfm-js仕様に基づくパーサー構造: // [改行?, 行頭,
, 改行?, 内容, 改行?,
, 行末, 改行?] - final parser = - (lineBreak.optional() & - lineBegin() & - start & - optionalNewlineAfterStart & - innerList & - optionalNewlineBeforeEnd & - end & - lineEnd() & - lineBreak.optional()) - .map((result) { - final children = result[4] as List; - return CenterNode(mergeAdjacentTextNodes(children)); - }); - return parser; + final after = + optionalNewlineBeforeEnd & end & lineEnd() & lineBreak.optional(); + final body = _CenterBody(inner, after, _cache, state); + return (lineBreak.optional() & + lineBegin() & + start & + optionalNewlineAfterStart & + body) + .pick(4) + .cast(); } } + +class _CenterBody extends Parser { + _CenterBody(this.inner, this.after, this.cache, this.state); + final Parser inner; + final Parser after; + final FailedScanCache cache; + final NestState? state; + + @override + Result parseOn(Context context) { + // 行頭条件と開始タグを満たした後の内容部分だけをキャッシュする。 + final scan = cache.start(context.buffer, state, this); + final children = []; + var current = context; + while (true) { + final cachedFailure = scan?.replay(current.position); + if (cachedFailure != null) { + scan?.fail(cachedFailure); + return context.failure(cachedFailure); + } + scan?.visit(current.position); + final result = inner.parseOn(current); + if (result is Failure) break; + children.add(result.value); + current = Context(context.buffer, result.position); + } + if (children.isEmpty) return context.failure('center content expected'); + final result = after.parseOn(current); + if (result is Failure) { + scan?.fail(result.message); + return result; + } + return context.success( + CenterNode(mergeAdjacentTextNodes(children)), + result.position, + ); + } + + @override + _CenterBody copy() => _CenterBody(inner, after, cache, state); +} diff --git a/lib/src/parser/core/scan_cache.dart b/lib/src/parser/core/scan_cache.dart new file mode 100644 index 0000000..18fbc64 --- /dev/null +++ b/lib/src/parser/core/scan_cache.dart @@ -0,0 +1,150 @@ +import 'package:petitparser/petitparser.dart'; + +import 'nest.dart'; + +/// 失敗した反復の接尾辞を、入力・深さ・予算切れの有無ごとに記録する。 +/// +/// 予算消費も再生するため、キャッシュの有無で後続構文の解釈を変えない。 +/// 予算が途中で尽きた結果は、同じ残予算の場合だけ再利用できる。 +class FailedScanCache { + Map>? _buffers; + (String, int, int)? _textSpan; + + Parser withSearchCache(Parser parser) => _ScanScope(parser, this); + + /// 通常テキストの内部から開始しても、同じ1要素になる区間を追跡する。 + /// [parser] は状態や直前文字に依存しない通常テキストに限る。 + Parser trackText(Parser parser) => _TrackText(parser, this); + + FailedScan? start(String buffer, NestState? state, Object parser) { + final buffers = _buffers; + final budget = state?.budget; + if (buffers == null || state == null || budget == null) return null; + final states = buffers.putIfAbsent(buffer, () => {}); + final failures = states.putIfAbsent( + (parser, state.depth, state.limit), + _FailuresByBudget.new, + ); + return FailedScan._(this, buffer, state, failures); + } +} + +class FailedScan { + FailedScan._(this.cache, this.buffer, this.state, this._failures); + final FailedScanCache cache; + final String buffer; + final NestState state; + final _FailuresByBudget _failures; + final _visits = <({int start, int end, int budget})>[]; + + /// 接尾辞の失敗が確定済みなら、走査を省略して同じ予算を消費する。 + String? replay(int position) { + final remaining = state.budget!; + final failure = (remaining == 0 + ? _failures.zero + : _failures.positive)[position]; + if (failure == null || + (failure.exhausted + ? remaining != failure.cost + : remaining <= failure.cost)) { + return null; + } + state.budget = remaining - failure.cost; + return failure.message; + } + + void visit(int position) { + _visits.add((start: position, end: position + 1, budget: state.budget!)); + } + + void text(int start, int end) { + final span = cache._textSpan; + if (_visits.isEmpty || + span == null || + !identical(span.$1, buffer) || + span.$2 != start || + span.$3 != end) { + return; + } + final visit = _visits.last; + // nest が通常テキストを1要素として解析した場合だけ、内部位置も登録。 + if (visit.budget - state.budget! == 1) { + _visits[_visits.length - 1] = ( + start: visit.start, + end: end, + budget: visit.budget, + ); + } + } + + void fail(String message) { + final remaining = state.budget!; + for (final visit in _visits) { + final failures = visit.budget == 0 ? _failures.zero : _failures.positive; + final failure = _ScanFailure( + visit.budget - remaining, + message, + exhausted: remaining == 0, + ); + for (var position = visit.start; position < visit.end; position++) { + // link の改行チェックはテキスト走査より先に行われる。 + if (position != visit.start && + (buffer[position] == '\n' || buffer[position] == '\r')) { + continue; + } + failures[position] = failure; + } + } + } +} + +class _FailuresByBudget { + final positive = {}; + final zero = {}; +} + +class _ScanFailure { + _ScanFailure(this.cost, this.message, {required this.exhausted}); + final int cost; + final bool exhausted; + final String message; +} + +class _ScanScope extends DelegateParser { + _ScanScope(super.delegate, this.cache); + final FailedScanCache cache; + + @override + Result parseOn(Context context) { + final previous = cache._buffers; + final previousText = cache._textSpan; + cache._buffers = Map.identity(); + cache._textSpan = null; + try { + return delegate.parseOn(context); + } finally { + cache._buffers = previous; + cache._textSpan = previousText; + } + } + + @override + _ScanScope copy() => _ScanScope(delegate, cache); +} + +class _TrackText extends DelegateParser { + _TrackText(super.delegate, this.cache); + final FailedScanCache cache; + + @override + Result parseOn(Context context) { + final result = delegate.parseOn(context); + if (result is Success && cache._buffers != null) { + cache._textSpan = (context.buffer, context.position, result.position); + } + return result; + } + + @override + _TrackText copy() => _TrackText(delegate, cache); +} diff --git a/lib/src/parser/inline/link.dart b/lib/src/parser/inline/link.dart index 4a9e3f5..c2239c6 100644 --- a/lib/src/parser/inline/link.dart +++ b/lib/src/parser/inline/link.dart @@ -3,6 +3,7 @@ import 'package:petitparser/petitparser.dart'; import '../../ast.dart'; import '../common/utils.dart'; import '../core/nest.dart'; +import '../core/scan_cache.dart'; import 'url.dart'; /// リンクパーサー @@ -14,6 +15,13 @@ import 'url.dart'; /// - ラベル内は再帰的にインラインパースを適用 /// - ラベル内ではURL、リンク、メンションは無効(linkLabel状態) class LinkParser { + final _cache = FailedScanCache(); + + Parser withSearchCache(Parser parser) => + _cache.withSearchCache(parser); + + Parser trackLabelText(Parser parser) => _cache.trackText(parser); + /// リンクパーサーを構築 /// /// [labelInlineParser] はラベル内のインライン構文をパースするパーサー @@ -23,7 +31,7 @@ class LinkParser { Parser labelInlineParser, { required NestState state, }) { - return _LinkParserImpl(labelInlineParser, state: state); + return _LinkParserImpl(labelInlineParser, _cache, state: state); } /// フォールバック付きリンクパーサー @@ -47,7 +55,9 @@ class LinkParser { /// リンクパーサーの実装 class _LinkParserImpl extends Parser { - _LinkParserImpl(this._labelInlineParser, {required this.state}); + _LinkParserImpl(this._labelInlineParser, this.cache, {required this.state}); + + final FailedScanCache cache; final Parser _labelInlineParser; @@ -86,6 +96,14 @@ class _LinkParserImpl extends Parser { // ラベル部分をパース(] まで) final labelNodes = []; var labelContext = Context(buffer, position); + // silent は開始記号で確定し、ラベル以降の成否には影響しない。 + // ラベル用パーサーはこの実装ごとに固定されている。 + final scan = cache.start(buffer, state, this); + + Result fail(String message) { + scan?.fail(message); + return context.failure(message); + } while (labelContext.position < buffer.length) { final c = buffer[labelContext.position]; @@ -97,11 +115,16 @@ class _LinkParserImpl extends Parser { // 改行は許可しない if (c == '\n' || c == '\r') { - return context.failure('newline in link label'); + return fail('newline in link label'); } + final cachedFailure = scan?.replay(labelContext.position); + if (cachedFailure != null) return fail(cachedFailure); + scan?.visit(labelContext.position); + // インラインパーサーでラベル内容をパース final result = _nestedLabelInlineParser.parseOn(labelContext); + scan?.text(labelContext.position, result.position); labelNodes.add(result.value); labelContext = Context(buffer, result.position); } @@ -110,13 +133,13 @@ class _LinkParserImpl extends Parser { // `]` で閉じることを確認 if (position >= buffer.length || buffer[position] != ']') { - return context.failure('expected ]'); + return fail('expected ]'); } position++; // `(` が続くことを確認 if (position >= buffer.length || buffer[position] != '(') { - return context.failure('expected ('); + return fail('expected ('); } position++; @@ -131,7 +154,7 @@ class _LinkParserImpl extends Parser { } if (urlResult is Failure) { - return context.failure('invalid URL in link'); + return fail('invalid URL in link'); } final urlNode = urlResult.value as UrlNode; @@ -139,7 +162,7 @@ class _LinkParserImpl extends Parser { // `)` で閉じることを確認 if (position >= buffer.length || buffer[position] != ')') { - return context.failure('expected )'); + return fail('expected )'); } position++; @@ -164,5 +187,6 @@ class _LinkParserImpl extends Parser { } @override - Parser copy() => _LinkParserImpl(_labelInlineParser, state: state); + Parser copy() => + _LinkParserImpl(_labelInlineParser, cache, state: state); } diff --git a/lib/src/parser/inline/math_inline.dart b/lib/src/parser/inline/math_inline.dart index 807a25e..4e4539b 100644 --- a/lib/src/parser/inline/math_inline.dart +++ b/lib/src/parser/inline/math_inline.dart @@ -11,6 +11,20 @@ import '../../ast.dart'; /// - 改行を含めることはできない /// - 空の数式は無効 class MathInlineParser { + Map? _spans; + static final _terminator = RegExp(r'\\\)|[\r\n]'); + + Parser withSearchCache(Parser parser) => _MathScope(parser, this); + + int _findEnd(String buffer, int start) { + final span = _spans?[buffer]; + if (span != null && span.$1 <= start && start <= span.$2) return span.$2; + final matches = _terminator.allMatches(buffer, start).iterator; + final end = matches.moveNext() ? matches.current.start : buffer.length; + _spans?[buffer] = (start, end); + return end; + } + /// インライン数式パーサー Parser build() { final open = string(r'\('); @@ -26,8 +40,53 @@ class MathInlineParser { final formula = formulaChar.plus().flatten(); // seq3で型安全なシーケンスパース - return seq3(open, formula, close).map3((openTag, formulaStr, closeTag) { + final parser = seq3(open, formula, close).map3(( + openTag, + formulaStr, + closeTag, + ) { return MathInlineNode(formulaStr); }); + return _MathCloseGuard(parser, this); + } +} + +class _MathCloseGuard extends DelegateParser { + _MathCloseGuard(super.delegate, this.math); + final MathInlineParser math; + + @override + Result parseOn(Context context) { + final buffer = context.buffer; + final position = context.position; + if (buffer.startsWith(r'\(', position)) { + final end = math._findEnd(buffer, position + 2); + if (!buffer.startsWith(r'\)', end)) { + return context.failure('"\\)" expected', end); + } + } + return delegate.parseOn(context); } + + @override + _MathCloseGuard copy() => _MathCloseGuard(delegate, math); +} + +class _MathScope extends DelegateParser { + _MathScope(super.delegate, this.math); + final MathInlineParser math; + + @override + Result parseOn(Context context) { + final previous = math._spans; + math._spans = Map.identity(); + try { + return delegate.parseOn(context); + } finally { + math._spans = previous; + } + } + + @override + _MathScope copy() => _MathScope(delegate, math); } diff --git a/lib/src/parser/parser.dart b/lib/src/parser/parser.dart index 4ee1d27..7031f40 100644 --- a/lib/src/parser/parser.dart +++ b/lib/src/parser/parser.dart @@ -78,7 +78,8 @@ class MfmParser { final plainTag = plain.build(); // インライン数式パーサー - final mathInline = MathInlineParser().build(); + final math = MathInlineParser(); + final mathInline = math.build(); // 絵文字パーサー final emojiCode = EmojiCodeParser().build(); @@ -98,6 +99,7 @@ class MfmParser { // リンクラベル用インラインパーサー(URL、リンク、メンションを除外) // mfm-js仕様: リンクラベル内ではURL、リンク、メンションは無効 final labelInline = undefined(); + final links = LinkParser(); final labelStopper = char('`') | char(':') | // emojiCode用 @@ -121,10 +123,11 @@ class MfmParser { string('__') | // boldUnder用(_より先にチェック) string('*') | string('_'); - final labelTextParser = (labelStopper.not() & unicodeEmoji.not() & any()) - .plus() - .flatten() - .map(TextNode.new); + final labelTextParser = links.trackLabelText( + (labelStopper.not() & unicodeEmoji.not() & any()).plus().flatten().map( + TextNode.new, + ), + ); final labelOneChar = any().map(TextNode.new); // ラベル内用パーサー(labelInlineを使用) @@ -182,7 +185,7 @@ class MfmParser { ); // リンクパーサー(ラベル用インラインパーサーを使用) - final link = LinkParser().buildWithFallback(labelInline, state: nestState); + final link = links.buildWithFallback(labelInline, state: nestState); final stopper = char('`') | @@ -254,7 +257,8 @@ class MfmParser { // blocks: code block > math block > center > quote final codeBlock = CodeBlockParser().build(); final mathBlock = MathBlockParser().build(); - final center = CenterParser().buildWithInner(inline, state: nestState); + final centers = CenterParser(); + final center = centers.buildWithInner(inline, state: nestState); final search = SearchParser().build(); // fullParserはblocks + inlineの組み合わせ(quote内で再帰的に使用) @@ -281,7 +285,13 @@ class MfmParser { final start = full.plus().map(mergeAdjacentTextNodes).end(); - return plain.withSearchCache(withNestBudget(start, nestState)); + return plain.withSearchCache( + math.withSearchCache( + links.withSearchCache( + centers.withSearchCache(withNestBudget(start, nestState)), + ), + ), + ); } /// Builds and returns a simple parser. diff --git a/test/core/parser/failed_scan_cache_test.dart b/test/core/parser/failed_scan_cache_test.dart new file mode 100644 index 0000000..c952a9a --- /dev/null +++ b/test/core/parser/failed_scan_cache_test.dart @@ -0,0 +1,282 @@ +import 'package:misskey_mfm_parser/src/ast.dart'; +import 'package:misskey_mfm_parser/src/parser/block/center.dart'; +import 'package:misskey_mfm_parser/src/parser/common/utils.dart'; +import 'package:misskey_mfm_parser/src/parser/core/nest.dart'; +import 'package:misskey_mfm_parser/src/parser/inline/bold.dart'; +import 'package:misskey_mfm_parser/src/parser/inline/link.dart'; +import 'package:misskey_mfm_parser/src/parser/parser.dart'; +import 'package:petitparser/petitparser.dart'; +import 'package:test/test.dart'; + +import '../../support/ast_json.dart'; + +void main() { + final parser = MfmParser().build(); + + void expectAst(String input, List expected) { + final result = parser.parse(input) as Success>; + expect(result.position, input.length); + expect(serializeMfmAst(result.value), serializeMfmAst(expected)); + } + + // These expected ASTs were captured before introducing the scan caches. + group('failed scan AST compatibility', () { + test('ordinary and silent links with nested formatting', () { + expectAst( + '[a](https://example.com) ?[a **b**](https://example.com)', + const [ + LinkNode( + silent: false, + url: 'https://example.com', + children: [TextNode('a')], + ), + TextNode(' '), + LinkNode( + silent: true, + url: 'https://example.com', + children: [ + TextNode('a '), + BoldNode([TextNode('b')]), + ], + ), + ], + ); + }); + + test('a closing bracket in plain is not the label terminator', () { + expectAst('[]x](https://example.com)', const [ + LinkNode( + silent: false, + url: 'https://example.com', + children: [ + PlainNode([TextNode(']x')]), + ], + ), + ]); + }); + + test('a close in the middle leaves an unclosed link suffix', () { + expectAst('[a[a](https://example.com)[a[a', const [ + LinkNode( + silent: false, + url: 'https://example.com', + children: [TextNode('a[a')], + ), + TextNode('[a[a'), + ]); + }); + + test('empty and invalid links do not hide a later valid link', () { + expectAst('[][a](no)[b](https://example.com)', const [ + TextNode('[][a](no)'), + LinkNode( + silent: false, + url: 'https://example.com', + children: [TextNode('b')], + ), + ]); + }); + + test('math uses the first close and leaves an unclosed suffix', () { + expectAst(r'\(\(a\)\(', const [ + MathInlineNode(r'\(a'), + TextNode(r'\('), + ]); + }); + + for (final newline in ['\n', '\r', '\r\n']) { + test('math search stops at ${newline.codeUnits}', () { + expectAst('\\(a$newline\\(b\\)', [ + TextNode('\\(a$newline'), + const MathInlineNode('b'), + ]); + }); + test('center trims ${newline.codeUnits}', () { + expectAst('
${newline}a$newline
', const [ + CenterNode([TextNode('a')]), + ]); + }); + } + + test('center opening tags in the body are ordinary inline text', () { + expectAst('
\n
\nx\n
\n
\n', const [ + CenterNode([TextNode('
\nx')]), + TextNode('
\n'), + ]); + }); + + test('center still checks both line boundaries', () { + expectAst('x
\na\n
', const [ + TextNode('x
\na\n
'), + ]); + expectAst('
\na
x\n
\nb\n
', const [ + TextNode('
\na
x'), + CenterNode([TextNode('b')]), + ]); + }); + + test('quote buffers have independent link and center caches', () { + expectAst('> [a[a\n\n[a](https://example.com)', const [ + QuoteNode([TextNode('[a[a')]), + LinkNode( + silent: false, + url: 'https://example.com', + children: [TextNode('a')], + ), + ]); + expectAst('>
\na\n\n
\nx\n
', const [ + QuoteNode([TextNode('
')]), + TextNode('a\n'), + CenterNode([TextNode('x')]), + ]); + }); + + for (final unit in ['[', '[a', r'\(', '
\n']) { + for (final count in [2, 20, 70]) { + final repeated = unit * count; + test('$unit x$count preserves surrounding plain and bold', () { + expectAst( + 'before **head** $repeated ' + '**tail** after', + [ + const PlainNode([TextNode('before')]), + const TextNode(' '), + const BoldNode([TextNode('head')]), + TextNode(' $repeated '), + const BoldNode([TextNode('tail')]), + const TextNode(' '), + const PlainNode([TextNode('after')]), + ], + ); + }); + test('$unit x$count inside bold and a link label', () { + expectAst('**$repeated**', [ + BoldNode([TextNode(repeated)]), + ]); + expectAst('[${repeated}x](https://example.com)', [ + LinkNode( + silent: false, + url: 'https://example.com', + children: [TextNode('${repeated}x')], + ), + ]); + }); + } + test('5000 unclosed $unit preserve all input', () { + final input = unit * 5000; + expectAst(input, [TextNode(input)]); + }); + } + + test('failed center attempts still exhaust the nesting budget', () { + final repeated = '
\n' * 70; + expectAst('$repeated **tail** #a(b(c))', [ + TextNode('$repeated '), + const BoldNode([TextNode('tail')]), + const TextNode(' '), + const HashtagNode('a'), + const TextNode('(b(c))'), + ]); + }); + + test('reuse resets failed spans, including equal length inputs', () { + for (var i = 0; i < 3; i++) { + expectAst(r'\(a!!', const [TextNode(r'\(a!!')]); + expectAst(r'\(a\)', const [MathInlineNode('a')]); + expectAst('[a](no)', const [TextNode('[a](no)')]); + expectAst('[a](https://a)', const [ + LinkNode(silent: false, url: 'https://a', children: [TextNode('a')]), + ]); + expectAst('
\na\nxxxxxxxxx', const [ + TextNode('
\na\nxxxxxxxxx'), + ]); + expectAst('
\na\n
', const [ + CenterNode([TextNode('a')]), + ]); + } + }); + }); + + group('failed scan nesting budget compatibility', () { + for (final center in [false, true]) { + for (final limit in [1, 2, 4, 20]) { + test('${center ? 'center' : 'link'} depth limit $limit', () { + final cases = center + ? [ + '
\n' * 8, + '${'
\n' * 8}**tail**', + '
\nx
bad\n
\ny\n
', + ] + : [ + '[a' * 20, + '${'[a' * 20} **tail**', + '[a**b**[a**c**](bad)[a](https://a/(b))', + '?[a[a\n**b**[a', + ]; + final cached = _buildScanParser( + center: center, + cached: true, + limit: limit, + ); + final uncached = _buildScanParser( + center: center, + cached: false, + limit: limit, + ); + for (var budget = 0; budget < 200; budget++) { + for (final input in cases) { + cached.state.budget = budget; + uncached.state.budget = budget; + final actual = + cached.parser.parse(input) as Success>; + final expected = + uncached.parser.parse(input) as Success>; + expect( + serializeMfmAst(actual.value), + serializeMfmAst(expected.value), + reason: 'budget=$budget input=$input', + ); + expect( + cached.state.budget, + uncached.state.budget, + reason: 'budget=$budget input=$input', + ); + expect(cached.state.depth, 0); + } + } + }); + } + } + }); +} + +({Parser> parser, NestState state}) _buildScanParser({ + required bool center, + required bool cached, + required int limit, +}) { + final state = NestState(limit: limit); + final links = LinkParser(); + final centers = CenterParser(); + final inline = undefined(); + final bold = BoldParser().buildWithInner(inline, state: state); + final text = links.trackLabelText( + noneOf(']*').plus().flatten().map(TextNode.new), + ); + final oneChar = any().map(TextNode.new); + inline.set((bold | text | oneChar).cast()); + final syntax = center + ? centers.buildWithInner(inline, state: state) + : links.buildWithFallback(inline, state: state); + final parser = (syntax | bold | oneChar) + .cast() + .plus() + .map(mergeAdjacentTextNodes) + .end(); + return ( + parser: cached + ? links.withSearchCache(centers.withSearchCache(parser)) + : parser, + state: state, + ); +} From 1c5d05364e1b87e28db6d656b35d8001e364998d Mon Sep 17 00:00:00 2001 From: librarian <57712678+LibraryLibrarian@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:27:25 +0900 Subject: [PATCH 3/4] =?UTF-8?q?docs:=20CHANGELOG=20=E3=81=AB=E6=9C=AA?= =?UTF-8?q?=E9=96=89=E3=81=98=E6=A7=8B=E6=96=87=E3=81=AE=E6=80=A7=E8=83=BD?= =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E3=82=92=E8=BF=BD=E8=A8=98=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa7dcf2..d19bc66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Parsing now has the same nesting budget as mfm.js (`input.length * 20 + 1000` nested-syntax attempts per input). Once it is used up, further nested syntax is treated as text, which bounds the work done on adversarial input. Ordinary input never reaches it - Excluded `test/` and `tool/` from the published package, reducing the archive from 94 KB to 43 KB. The `third_party/` license notice for the bundled Unicode emoji regular expression is still included +### Fixed + +- Fixed quadratic parse time for input that repeats unclosed syntax, which made the parser freeze for seconds on adversarial input. Repeated `` (21,000 characters: 3 s to 20 ms), `[` and `[a` (5,000 repetitions: 4.7 s to 7 ms), `\(` and `
` followed by line breaks are now parsed in near-linear time. The resulting nodes and the nesting budget used are unchanged + ## [2.0.1] - 2026-09-15 ### Added From 4433e302190bed62ce3343ffcc210dd0f2180ffb Mon Sep 17 00:00:00 2001 From: librarian <57712678+LibraryLibrarian@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:33:36 +0900 Subject: [PATCH 4/4] =?UTF-8?q?docs:=20=E6=80=A7=E8=83=BD=E4=BF=AE?= =?UTF-8?q?=E6=AD=A3=E3=81=AE=20CHANGELOG=20=E3=81=AE=E6=95=B0=E5=80=A4?= =?UTF-8?q?=E3=81=A8=E8=A8=98=E8=BF=B0=E3=82=92=E5=AE=9F=E6=B8=AC=E3=81=AB?= =?UTF-8?q?=E5=90=88=E3=82=8F=E3=81=9B=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d19bc66..651d3cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fixed quadratic parse time for input that repeats unclosed syntax, which made the parser freeze for seconds on adversarial input. Repeated `` (21,000 characters: 3 s to 20 ms), `[` and `[a` (5,000 repetitions: 4.7 s to 7 ms), `\(` and `
` followed by line breaks are now parsed in near-linear time. The resulting nodes and the nesting budget used are unchanged +- Fixed quadratic parse time for input that repeats unclosed syntax, which made the parser freeze for seconds on adversarial input. These are now parsed in near-linear time: repeated `` (21,000 characters: 3 s to 20 ms), `[` (5,000 repetitions: 4.5 s to 6 ms), `[a` (5,000 repetitions: 9.4 s to 15 ms), `\(` with or without line breaks, and `
` followed by line breaks (5,000 repetitions: 47 s to 0.1 s). The resulting nodes and the nesting budget used are unchanged ## [2.0.1] - 2026-09-15