Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. These are now parsed in near-linear time: repeated `<plain>` (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 `<center>` 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

### Added
Expand Down
76 changes: 59 additions & 17 deletions lib/src/parser/block/center.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import '../../ast.dart';
import '../common/utils.dart';
import '../core/guards.dart';
import '../core/nest.dart';
import '../core/scan_cache.dart';

/// 中央寄せブロックパーサー
///
Expand All @@ -14,6 +15,11 @@ import '../core/nest.dart';
/// - `</center>` は行末でなければならない(入力末尾または直後が改行)
/// - 前後の改行はブロック構文として消費される
class CenterParser {
final _cache = FailedScanCache();

Parser<T> withSearchCache<T>(Parser<T> parser) =>
_cache.withSearchCache(parser);

/// center タグ(基本版)
Parser<MfmNode> build() {
final lineBreak = newline();
Expand Down Expand Up @@ -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仕様に基づくパーサー構造:
// [改行?, 行頭, <center>, 改行?, 内容, 改行?, </center>, 行末, 改行?]
final parser =
(lineBreak.optional() &
lineBegin() &
start &
optionalNewlineAfterStart &
innerList &
optionalNewlineBeforeEnd &
end &
lineEnd() &
lineBreak.optional())
.map<MfmNode>((result) {
final children = result[4] as List<MfmNode>;
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<MfmNode>();
}
}

class _CenterBody extends Parser<MfmNode> {
_CenterBody(this.inner, this.after, this.cache, this.state);
final Parser<MfmNode> inner;
final Parser<dynamic> after;
final FailedScanCache cache;
final NestState? state;

@override
Result<MfmNode> parseOn(Context context) {
// 行頭条件と開始タグを満たした後の内容部分だけをキャッシュする。
final scan = cache.start(context.buffer, state, this);
final children = <MfmNode>[];
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);
}
150 changes: 150 additions & 0 deletions lib/src/parser/core/scan_cache.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import 'package:petitparser/petitparser.dart';

import 'nest.dart';

/// 失敗した反復の接尾辞を、入力・深さ・予算切れの有無ごとに記録する。
///
/// 予算消費も再生するため、キャッシュの有無で後続構文の解釈を変えない。
/// 予算が途中で尽きた結果は、同じ残予算の場合だけ再利用できる。
class FailedScanCache {
Map<String, Map<(Object, int, int?), _FailuresByBudget>>? _buffers;
(String, int, int)? _textSpan;

Parser<T> withSearchCache<T>(Parser<T> parser) => _ScanScope(parser, this);

/// 通常テキストの内部から開始しても、同じ1要素になる区間を追跡する。
/// [parser] は状態や直前文字に依存しない通常テキストに限る。
Parser<T> trackText<T>(Parser<T> 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 = <int, _ScanFailure>{};
final zero = <int, _ScanFailure>{};
}

class _ScanFailure {
_ScanFailure(this.cost, this.message, {required this.exhausted});
final int cost;
final bool exhausted;
final String message;
}

class _ScanScope<T> extends DelegateParser<T, T> {
_ScanScope(super.delegate, this.cache);
final FailedScanCache cache;

@override
Result<T> 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<T> copy() => _ScanScope(delegate, cache);
}

class _TrackText<T> extends DelegateParser<T, T> {
_TrackText(super.delegate, this.cache);
final FailedScanCache cache;

@override
Result<T> 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<T> copy() => _TrackText(delegate, cache);
}
42 changes: 33 additions & 9 deletions lib/src/parser/inline/link.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/// リンクパーサー
Expand All @@ -14,6 +15,13 @@ import 'url.dart';
/// - ラベル内は再帰的にインラインパースを適用
/// - ラベル内ではURL、リンク、メンションは無効(linkLabel状態)
class LinkParser {
final _cache = FailedScanCache();

Parser<T> withSearchCache<T>(Parser<T> parser) =>
_cache.withSearchCache(parser);

Parser<T> trackLabelText<T>(Parser<T> parser) => _cache.trackText(parser);

/// リンクパーサーを構築
///
/// [labelInlineParser] はラベル内のインライン構文をパースするパーサー
Expand All @@ -23,7 +31,7 @@ class LinkParser {
Parser<MfmNode> labelInlineParser, {
required NestState state,
}) {
return _LinkParserImpl(labelInlineParser, state: state);
return _LinkParserImpl(labelInlineParser, _cache, state: state);
}

/// フォールバック付きリンクパーサー
Expand All @@ -47,7 +55,9 @@ class LinkParser {

/// リンクパーサーの実装
class _LinkParserImpl extends Parser<MfmNode> {
_LinkParserImpl(this._labelInlineParser, {required this.state});
_LinkParserImpl(this._labelInlineParser, this.cache, {required this.state});

final FailedScanCache cache;

final Parser<MfmNode> _labelInlineParser;

Expand All @@ -73,7 +83,7 @@ class _LinkParserImpl extends Parser<MfmNode> {

// サイレントリンクかどうかを判定
bool silent;
if (buffer.substring(position).startsWith('?[')) {
if (buffer.startsWith('?[', position)) {
silent = true;
position += 2;
} else if (position < buffer.length && buffer[position] == '[') {
Expand All @@ -86,6 +96,14 @@ class _LinkParserImpl extends Parser<MfmNode> {
// ラベル部分をパース(] まで)
final labelNodes = <MfmNode>[];
var labelContext = Context(buffer, position);
// silent は開始記号で確定し、ラベル以降の成否には影響しない。
// ラベル用パーサーはこの実装ごとに固定されている。
final scan = cache.start(buffer, state, this);

Result<MfmNode> fail(String message) {
scan?.fail(message);
return context.failure(message);
}

while (labelContext.position < buffer.length) {
final c = buffer[labelContext.position];
Expand All @@ -97,11 +115,16 @@ class _LinkParserImpl extends Parser<MfmNode> {

// 改行は許可しない
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);
}
Expand All @@ -110,13 +133,13 @@ class _LinkParserImpl extends Parser<MfmNode> {

// `]` で閉じることを確認
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++;

Expand All @@ -131,15 +154,15 @@ class _LinkParserImpl extends Parser<MfmNode> {
}

if (urlResult is Failure) {
return context.failure('invalid URL in link');
return fail('invalid URL in link');
}

final urlNode = urlResult.value as UrlNode;
position = urlResult.position;

// `)` で閉じることを確認
if (position >= buffer.length || buffer[position] != ')') {
return context.failure('expected )');
return fail('expected )');
}
position++;

Expand All @@ -164,5 +187,6 @@ class _LinkParserImpl extends Parser<MfmNode> {
}

@override
Parser<MfmNode> copy() => _LinkParserImpl(_labelInlineParser, state: state);
Parser<MfmNode> copy() =>
_LinkParserImpl(_labelInlineParser, cache, state: state);
}
Loading