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
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ init-only record: `Display`, `Strict`, `PreserveFormatting`, `LaTeXFlavor` stand

- `EquationPipeline` picks the parser of a format by pattern matching on the format and the source;
`EquationSerializer` picks the serializer.
- A stack overflow cannot be caught, and ends the process: the XML of a source and every equation read are refused
(`FormatException`, "The equation is nested too deeply.") beyond `EquationStylesheets.MaxDepth` levels, and every
method that recurses over an equation (the readers, the writers, the templates the XSLT generator compiles) starts
with `RuntimeHelpers.EnsureSufficientExecutionStack()`: its exception is a `FormatException` (`InvalidDataException`
for MTEF) when reading and an `InsufficientExecutionStackException` when writing. A new recursive method calls it too.
- `MathMLParser.Normalize` gives every equation the one form an `Equation` holds and compares: MathML namespace without
prefixes, no `mfenced`, `a` or invisible fences, no formatting unless kept, intents with plain letters, letters as
MathML Core writes them (`<mi>x</mi>` for an italic letter, `𝐲` rather than `mathvariant="bold"`, plain letters with
Expand Down
2 changes: 1 addition & 1 deletion BuildVersion.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<!-- The release version: bump this, and merging to main tags and publishes vX.Y.Z.
CI passes a pre-release VersionSuffix for pull request builds (pr.12.34 -> 1.0.0-pr.12.34). -->
<VersionPrefix>1.1.1</VersionPrefix>
<VersionPrefix>1.1.2</VersionPrefix>
</PropertyGroup>

<PropertyGroup>
Expand Down
5 changes: 5 additions & 0 deletions src/SharpEquations.XsltGenerator/StylesheetCompiler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,9 @@ private string Assemble()

// templates

// the templates recurse over the input, and a stack overflow cannot be caught
private const string EnsureStack = "System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack();";

private void CompileTemplate(XElement template, int index)
{
var name = Attr(template, "name", false);
Expand All @@ -319,6 +322,7 @@ private void CompileTemplate(XElement template, int index)
var signature = string.Concat(named.Parameters.Select((p, i) => ", object? a" + i));
var w = new CodeWriter(2);
w.Line().Open("private void " + named.Method + "(XObject n0, int p0, int s0" + signature + ")");
w.Line(EnsureStack);
CompileBody(template, parameters, i => "a" + i, w);
w.Close();
members.Append(w);
Expand Down Expand Up @@ -525,6 +529,7 @@ private void CompileDispatch(int mode)
w.Close();

w.Line().Open("private void Dispatch" + mode + "(XObject node, int position, int size, TemplateArguments? args)");
w.Line(EnsureStack);
w.Open("switch (node)");

w.Line("case XElement element:").Open();
Expand Down
38 changes: 34 additions & 4 deletions src/SharpEquations/Internal/EquationPipeline.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,30 @@ public static XElement Read(object? source, EquationFormat format, EquationOptio
throw new ArgumentNullException(nameof(source));
CheckDefined(format);
cancellationToken.ThrowIfCancellationRequested();
try
{
return ReadSource(source, format, options, cancellationToken);
}
catch (InsufficientExecutionStackException e)
{
throw new FormatException(EquationStylesheets.TooDeep, e);
}
}

private static XElement ReadSource(object source, EquationFormat format, EquationOptions options, CancellationToken cancellationToken)
{
var math = (format, source) switch
{
(EquationFormat.MathML, XElement element) => element,
(EquationFormat.MathML, string text) => MathMLParser.ParseXml(text, format),
(EquationFormat.MathML, XElement element) => Shallow(element),
(EquationFormat.MathML, string text) => Shallow(MathMLParser.ParseXml(text, format)),
(EquationFormat.Omml, XElement element) => ReadOmml(element, options),
(EquationFormat.Omml, string text) => ReadOmml(MathMLParser.ParseXml(text, format), options),
(EquationFormat.UnicodeMath, string text) => UnicodeMathParser.Parse(text, options.Display, options.Strict, cancellationToken),
(EquationFormat.LaTeX, string text) => LaTeXParser.Parse(text, options.Display, LaTeXParser.Macros(options.LaTeXMacros), options.Strict, cancellationToken),
(EquationFormat.Mtef, _) => throw new ArgumentException("MTEF equations are binary: pass them as bytes.", nameof(format)),
_ => throw new ArgumentException(format + " equations are text, not XML: pass them as strings.", nameof(format)),
};
return MathMLParser.Normalize(math, options, format == EquationFormat.MathML);
return Shallow(MathMLParser.Normalize(math, options, format == EquationFormat.MathML));
}

/// <summary>Reads a binary source, MTEF, without copying it.</summary>
Expand All @@ -58,9 +70,26 @@ public static XElement Read(ReadOnlySpan<byte> source, EquationFormat format, Eq
CheckDefined(format);
if (format != EquationFormat.Mtef)
throw new ArgumentException(format + " equations are not binary: pass them as " + (IsXml(format) ? "text or XML." : "text."), nameof(format));
return MathMLParser.Normalize(MtefParser.Parse(source), options, false);
try
{
var math = MathMLParser.Normalize(MtefParser.Parse(source), options, false);
if (EquationStylesheets.IsTooDeep(math))
throw new InvalidDataException("The MTEF equation is nested too deeply.");
return math;
}
catch (InsufficientExecutionStackException e)
{
throw new InvalidDataException("The MTEF equation is nested too deeply.", e);
}
}

/// <summary>
/// The equation, unless it is nested more deeply than <see cref="EquationStylesheets.MaxDepth"/>: what reads and
/// writes it recurses over its tree, and a stack overflow cannot be caught.
/// </summary>
private static XElement Shallow(XElement math) =>
EquationStylesheets.IsTooDeep(math) ? throw new FormatException(EquationStylesheets.TooDeep) : math;

private static void CheckDefined(EquationFormat format)
{
if (!IsDefined(format))
Expand All @@ -69,6 +98,7 @@ private static void CheckDefined(EquationFormat format)

private static XElement ReadOmml(XElement omml, EquationOptions options)
{
Shallow(omml);
if (options.Strict)
OmmlParser.Validate(omml);
try
Expand Down
22 changes: 16 additions & 6 deletions src/SharpEquations/Internal/EquationSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace SharpEquations.Internal
{
using System;
using System.Xml.Linq;
using SharpEquations.Internal.LaTeX;
using SharpEquations.Internal.MathML;
Expand All @@ -12,16 +13,25 @@ namespace SharpEquations.Internal
internal static class EquationSerializer
{
/// <returns>An XElement for the XML formats, a string for the others.</returns>
/// <exception cref="InsufficientExecutionStackException">The equation is nested too deeply to be written on this thread.</exception>
public static object Serialize(XElement math, EquationFormat format, EquationOptions options)
{
EquationPipeline.CheckWritable(format);
return format switch
try
{
EquationFormat.MathML => MathMLSerializer.Serialize(math),
EquationFormat.Omml => OmmlSerializer.Serialize(math),
EquationFormat.UnicodeMath => UnicodeMathSerializer.Serialize(math),
_ => LaTeXSerializer.Serialize(math, options.LaTeXFlavor == LaTeXFlavor.Standard),
};
return format switch
{
EquationFormat.MathML => MathMLSerializer.Serialize(math),
EquationFormat.Omml => OmmlSerializer.Serialize(math),
EquationFormat.UnicodeMath => UnicodeMathSerializer.Serialize(math),
_ => LaTeXSerializer.Serialize(math, options.LaTeXFlavor == LaTeXFlavor.Standard),
};
}
catch (InsufficientExecutionStackException e) when (e.Message != EquationStylesheets.TooDeep)
{
// the writers recurse over the equation, and a stack overflow cannot be caught
throw new InsufficientExecutionStackException(EquationStylesheets.TooDeep, e);
}
}

public static string ToText(object serialized) =>
Expand Down
58 changes: 42 additions & 16 deletions src/SharpEquations/Internal/EquationStylesheets.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
namespace SharpEquations.Internal
{
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using SharpEquations.Internal.Xslt;

Expand All @@ -16,12 +15,18 @@ internal static class EquationStylesheets
/// </summary>
public const int MaxDepth = 512;

/// <summary>The message of the exceptions thrown for an equation nested more deeply than can be handled.</summary>
public const string TooDeep = "The equation is nested too deeply.";

/// <summary>Whether the element is nested more than <see cref="MaxDepth"/> levels deep.</summary>
public static bool IsTooDeep(XElement element) => Depth(element) > MaxDepth;

/// <summary>Runs the stylesheet, or returns null when its output is empty.</summary>
/// <exception cref="ArgumentException">The input is nested more than <see cref="MaxDepth"/> levels deep.</exception>
/// <exception cref="InsufficientExecutionStackException">The input is nested more than <see cref="MaxDepth"/> levels deep.</exception>
public static XElement Transform(string name, XElement input)
{
if (Depth(input) > MaxDepth)
throw new ArgumentException("The equation is nested too deeply.", nameof(input));
if (IsTooDeep(input))
throw new InsufficientExecutionStackException(TooDeep);
switch (name)
{
case "omml2mml.xsl":
Expand All @@ -37,22 +42,43 @@ public static XElement Transform(string name, XElement input)
}
}

// without allocating: the input of every equation read goes through it (FirstNode would make an XText of
// the text of a token)
private static int Depth(XElement root)
{
var depth = 0;
var stack = new Stack<(XElement Element, int Depth)>();
stack.Push((root, 1));
while (stack.Count > 0)
int depth = 1, deepest = 1;
var element = root;
while (true)
{
var (element, level) = stack.Pop();
if (level > depth)
depth = level;
if (depth > MaxDepth)
break;
foreach (var child in element.Elements())
stack.Push((child, level + 1));
var child = element.HasElements ? NextElement(element.FirstNode) : null;
if (child != null)
{
element = child;
if (++depth > deepest && (deepest = depth) > MaxDepth)
return deepest;
continue;
}
while (true)
{
if (element == root)
return deepest;
var sibling = NextElement(element.NextNode);
if (sibling != null)
{
element = sibling;
break;
}
element = element.Parent;
depth--;
}
}
return depth;
}

private static XElement NextElement(XNode node)
{
while (node != null && node is not XElement)
node = node.NextNode;
return (XElement)node;
}
}
}
3 changes: 3 additions & 0 deletions src/SharpEquations/Internal/LaTeX/LaTeXReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ namespace SharpEquations.Internal.LaTeX
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using SharpEquations.Internal.UnicodeMath;
using static SharpEquations.Internal.UnicodeMath.UnicodeMathText;
Expand Down Expand Up @@ -484,6 +485,7 @@ private static bool AngleCloses(Text tex, int i)
/// </summary>
private static string RewriteTeXOnly(string latex)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
var tex = new Text(latex);
var result = new StringBuilder();
// between ⟨ and ⟩ a bar parts a bra from a ket (│), as in UnicodeMath: ⟨a│b⟩
Expand Down Expand Up @@ -2096,6 +2098,7 @@ private static (string, int) ApplyMacro(Text tex, int i, bool accentsAfter)
/// <summary>TeX2UMath: pass 2, LaTeX with UnicodeMath characters to UnicodeMath.</summary>
private string Pass2(string latex)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
var tex = new Text(latex);
var uniTeX = new StringBuilder();
int j, k;
Expand Down
2 changes: 2 additions & 0 deletions src/SharpEquations/Internal/LaTeX/LaTeXSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ namespace SharpEquations.Internal.LaTeX
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Xml.Linq;
using SharpEquations.Internal.UnicodeMath;
using static SharpEquations.Internal.UnicodeMath.Js;
Expand Down Expand Up @@ -229,6 +230,7 @@ private static string EquationNumber(string eq)

private string TeX(XElement value, bool noAddParens = false)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
if (value == null)
return "";

Expand Down
3 changes: 3 additions & 0 deletions src/SharpEquations/Internal/UnicodeMath/JsObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,7 @@ public static object V(object value)

public static object Clone(object value)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
switch (value)
{
case JsObject o: return o.Clone();
Expand All @@ -276,6 +277,7 @@ public static object Clone(object value)
/// <summary>The string conversion of JavaScript (String(value)).</summary>
public static string Str(object value)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
switch (value)
{
case null: return "undefined";
Expand All @@ -290,6 +292,7 @@ public static string Str(object value)

public static string Stringify(object value)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
switch (value)
{
case null: return "null";
Expand Down
3 changes: 3 additions & 0 deletions src/SharpEquations/Internal/UnicodeMath/UnicodeMathHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace SharpEquations.Internal.UnicodeMath
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using static Js;
using static UnicodeMathText;
Expand Down Expand Up @@ -54,6 +55,7 @@ private static object DropSingletonLists(object uast)

private static object DropOutermostParens(object uast)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
if (Truthy(Get(uast, "expr")))
return O("expr", DropOutermostParens(Get(uast, "expr")));

Expand Down Expand Up @@ -625,6 +627,7 @@ private static bool IsLeviCivita(object basE, object low, List<object> arr)

private static object GetTextContent(object ast)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
if (Truthy(Get(ast, "expr")))
ast = Get(ast, "expr");
if (!(ast is List<object> list))
Expand Down
2 changes: 2 additions & 0 deletions src/SharpEquations/Internal/UnicodeMath/UnicodeMathInput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace SharpEquations.Internal.UnicodeMath
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using SharpEquations.Internal.Text;
Expand Down Expand Up @@ -333,6 +334,7 @@ public static string MapFromPrivate(string s)
/// <summary>astMapFromPrivate: <see cref="MapFromPrivate"/> over every string of a syntax tree.</summary>
public static object AstMapFromPrivate(object ast)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
switch (ast)
{
case null:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ namespace SharpEquations.Internal.UnicodeMath
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using static Js;
using static UnicodeMathText;

Expand Down Expand Up @@ -39,6 +40,7 @@ private sealed class PreprocessStyle

private object Preprocess(PreprocessStyle dsty, object uast, int? index = null, List<object> arr = null)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
bool intentSup = false;

if (uast is List<object> list)
Expand Down
2 changes: 2 additions & 0 deletions src/SharpEquations/Internal/UnicodeMath/UnicodeMathPretty.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ namespace SharpEquations.Internal.UnicodeMath
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using static Js;
using static UnicodeMathText;
Expand Down Expand Up @@ -55,6 +56,7 @@ private static void PromoteAttributelessMrowChildren(List<object> value)
/// <summary>pretty: the MathML text of a MathML syntax tree.</summary>
private string Pretty(object mast)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
if (mast is List<object> list)
{
var sb = new StringBuilder();
Expand Down
Loading
Loading