Add parser authoring helper APIs and tests

This commit is contained in:
Alexandre Mutel
2026-02-21 14:25:17 +01:00
parent 5e5112ccca
commit ab6204cf61
3 changed files with 159 additions and 1 deletions

View File

@@ -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<AutolinkInlineParser>(new CountingInlineParser());
var html = Markdown.ToHtml(
"""
@@
@
""".ReplaceLineEndings("\n"),
pipeline.Build());
Assert.That(html, Is.EqualTo("<p>12</p>\n<p>1</p>\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<CounterState>(this);
state.Count++;
processor.Emit(new LiteralInline(state.Count.ToString()));
slice.SkipChar();
return true;
}
}
private sealed class CounterState
{
public int Count { get; set; }
}
}

View File

@@ -471,15 +471,30 @@ public class BlockProcessor
/// <param name="block">The block.</param>
public void Discard(Block block)
{
_ = TryDiscard(block);
}
/// <summary>
/// Tries to discard the specified block from the open stack and remove it from its parent.
/// </summary>
/// <param name="block">The block to discard.</param>
/// <returns><c>true</c> if the block was discarded; otherwise <c>false</c>.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="block"/> is null.</exception>
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;
}
/// <summary>
@@ -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");
}

View File

@@ -396,6 +396,69 @@ public class InlineProcessor
}
}
/// <summary>
/// Gets or creates a parser state instance scoped to the current leaf processing pass.
/// </summary>
/// <typeparam name="TState">The type of state to get or create.</typeparam>
/// <param name="parser">The parser requesting the state.</param>
/// <param name="factory">A factory used to create a state instance when none exists yet.</param>
/// <returns>The existing or newly created state instance.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="parser"/> or <paramref name="factory"/> is null.</exception>
/// <exception cref="InvalidOperationException">Thrown if <paramref name="factory"/> returns <c>null</c>.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TState GetParserState<TState>(InlineParser parser, Func<TState> 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;
}
/// <summary>
/// Gets or creates a parser state instance scoped to the current leaf processing pass.
/// </summary>
/// <typeparam name="TState">The type of state to get or create.</typeparam>
/// <param name="parser">The parser requesting the state.</param>
/// <returns>The existing or newly created state instance.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TState GetParserState<TState>(InlineParser parser) where TState : class, new()
{
return GetParserState(parser, static () => new TState());
}
/// <summary>
/// Emits an inline into the deepest open inline container for the current leaf.
/// </summary>
/// <param name="inline">The inline to emit.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="inline"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="inline"/> is already attached to a parent.</exception>
[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!;