From ab6204cf610d64f507d6d3da67992c4f3bccf18d Mon Sep 17 00:00:00 2001 From: Alexandre Mutel Date: Sat, 21 Feb 2026 14:25:17 +0100 Subject: [PATCH] Add parser authoring helper APIs and tests --- .../TestParserAuthoringHelpers.cs | 78 +++++++++++++++++++ src/Markdig/Parsers/BlockProcessor.cs | 19 ++++- src/Markdig/Parsers/InlineProcessor.cs | 63 +++++++++++++++ 3 files changed, 159 insertions(+), 1 deletion(-) create mode 100644 src/Markdig.Tests/TestParserAuthoringHelpers.cs diff --git a/src/Markdig.Tests/TestParserAuthoringHelpers.cs b/src/Markdig.Tests/TestParserAuthoringHelpers.cs new file mode 100644 index 00000000..46fe1b28 --- /dev/null +++ b/src/Markdig.Tests/TestParserAuthoringHelpers.cs @@ -0,0 +1,78 @@ +using Markdig.Helpers; +using Markdig.Parsers; +using Markdig.Parsers.Inlines; +using Markdig.Syntax; +using Markdig.Syntax.Inlines; + +namespace Markdig.Tests; + +[TestFixture] +public sealed class TestParserAuthoringHelpers +{ + [Test] + public void GetParserStateResetsBetweenLeafBlocksAndEmitAppendsInline() + { + var pipeline = new MarkdownPipelineBuilder(); + pipeline.InlineParsers.InsertBefore(new CountingInlineParser()); + + var html = Markdown.ToHtml( + """ + @@ + + @ + """.ReplaceLineEndings("\n"), + pipeline.Build()); + + Assert.That(html, Is.EqualTo("

12

\n

1

\n")); + } + + [Test] + public void TryDiscardOnlyDiscardsOpenNonRootBlocks() + { + var parser = new ParagraphBlockParser(); + var document = new MarkdownDocument(); + var processor = new BlockProcessor(document, new BlockParserList([parser]), context: null, trackTrivia: false); + + var detached = new ParagraphBlock(parser); + Assert.That(processor.TryDiscard(detached), Is.False); + + var paragraph = new ParagraphBlock(parser); + document.Add(paragraph); + processor.Open(paragraph); + + Assert.That(document.Count, Is.EqualTo(1)); + Assert.That(processor.TryDiscard(paragraph), Is.True); + Assert.That(document.Count, Is.EqualTo(0)); + Assert.That(paragraph.Parent, Is.Null); + + Assert.That(processor.TryDiscard(document), Is.False); + } + + private sealed class CountingInlineParser : InlineParser + { + public CountingInlineParser() + { + OpeningCharacters = ['@']; + } + + public override bool Match(InlineProcessor processor, ref StringSlice slice) + { + if (slice.CurrentChar != '@') + { + return false; + } + + var state = processor.GetParserState(this); + state.Count++; + + processor.Emit(new LiteralInline(state.Count.ToString())); + slice.SkipChar(); + return true; + } + } + + private sealed class CounterState + { + public int Count { get; set; } + } +} diff --git a/src/Markdig/Parsers/BlockProcessor.cs b/src/Markdig/Parsers/BlockProcessor.cs index 92d2c1ec..30f830a6 100644 --- a/src/Markdig/Parsers/BlockProcessor.cs +++ b/src/Markdig/Parsers/BlockProcessor.cs @@ -471,15 +471,30 @@ public class BlockProcessor /// The block. public void Discard(Block block) { + _ = TryDiscard(block); + } + + /// + /// Tries to discard the specified block from the open stack and remove it from its parent. + /// + /// The block to discard. + /// true if the block was discarded; otherwise false. + /// Thrown when is null. + public bool TryDiscard(Block block) + { + if (block is null) ThrowHelper.ArgumentNullException(nameof(block)); + for (int i = OpenedBlocks.Count - 1; i >= 1; i--) { if (ReferenceEquals(OpenedBlocks[i].Block, block)) { block.Parent!.Remove(block); OpenedBlocks.RemoveAt(i); - break; + return true; } } + + return false; } /// @@ -934,6 +949,7 @@ public class BlockProcessor while (newBlocks.Count > 0) { var block = newBlocks.Pop(); + Debug.Assert(block.Parser is not null, $"The new block [{block.GetType()}] must have a valid Parser property"); if (block.Parser is null) { @@ -960,6 +976,7 @@ public class BlockProcessor if (newBlocks.Count > 0) { + Debug.Assert(false, "The NewBlocks is not empty. This is happening if a LeafBlock is not the last to be pushed"); ThrowHelper.InvalidOperationException( "The NewBlocks is not empty. This is happening if a LeafBlock is not the last to be pushed"); } diff --git a/src/Markdig/Parsers/InlineProcessor.cs b/src/Markdig/Parsers/InlineProcessor.cs index b16b63c9..efc28ab3 100644 --- a/src/Markdig/Parsers/InlineProcessor.cs +++ b/src/Markdig/Parsers/InlineProcessor.cs @@ -396,6 +396,69 @@ public class InlineProcessor } } + /// + /// Gets or creates a parser state instance scoped to the current leaf processing pass. + /// + /// The type of state to get or create. + /// The parser requesting the state. + /// A factory used to create a state instance when none exists yet. + /// The existing or newly created state instance. + /// Thrown when or is null. + /// Thrown if returns null. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public TState GetParserState(InlineParser parser, Func factory) where TState : class + { + if (parser is null) ThrowHelper.ArgumentNullException(nameof(parser)); + if (factory is null) ThrowHelper.ArgumentNullException(nameof(factory)); + + ref var slot = ref ParserStates[parser.Index]; + if (slot is TState state) + { + return state; + } + + state = factory(); + if (state is null) + { + ThrowHelper.InvalidOperationException($"The state factory for [{typeof(TState)}] returned null"); + } + + slot = state; + return state; + } + + /// + /// Gets or creates a parser state instance scoped to the current leaf processing pass. + /// + /// The type of state to get or create. + /// The parser requesting the state. + /// The existing or newly created state instance. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public TState GetParserState(InlineParser parser) where TState : class, new() + { + return GetParserState(parser, static () => new TState()); + } + + /// + /// Emits an inline into the deepest open inline container for the current leaf. + /// + /// The inline to emit. + /// Thrown when is null. + /// Thrown when is already attached to a parent. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Emit(Inline inline) + { + if (inline is null) ThrowHelper.ArgumentNullException(nameof(inline)); + if (inline.Parent is not null) + { + ThrowHelper.ArgumentException("Inline has already a parent", nameof(inline)); + } + + var container = FindLastContainer(); + container.AppendChild(inline); + Inline = inline; + } + private ContainerInline FindLastContainer() { var container = Block!.Inline!;