Skip to content

Commit b76751a

Browse files
MathS.Parse and Entity.TryParse return a refused call rather than throw it (#2500)
MathS.Parse is the parser that does not throw, and Entity.TryParse the IParsable one that says yes or no. Both threw where the grammar refuses a call: factorize(360) threw UnrecognizedFunctionParseException and norm(v, p, q) FunctionArgumentCountException, since a grammar action that throws has no error recorded against the input. Each is now the failure it describes, Unknown with the refusal's message, and TryParse says false. FromString and the conversion from a string still throw it with its own type. The MCP server's am_parse reported these as a tool that threw, and answers a failed parse now. Full check: 21117 of 21130 unit tests pass, 13 skipped; MCP 461 of 461; harnesses clean and the three baselines matched. Fixes #2498 Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 0cfc9ec commit b76751a

4 files changed

Lines changed: 111 additions & 2 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,21 @@ A not-equal written `<>` is read as `not (a = b)`, and printed that way.
4242

4343
## Unreleased — since 2.8.0
4444

45+
### `MathS.Parse` and `Entity.TryParse` return a refused call rather than throw it
46+
47+
**Not silent: what threw now returns.** `MathS.Parse` is the parser that does not throw, and `Entity.TryParse` the
48+
`IParsable` one that says yes or no. Both threw where the grammar refuses a call, a name refused by name or a function
49+
given the wrong number of arguments. Each now answers the failure, the refusal's message its reason. `FromString` and
50+
the conversion from a string still throw it, with its own type
51+
([#2498](https://github.com/asc-community/AngouriMath/issues/2498)).
52+
53+
| Input | Was (2.8.0) | Now |
54+
|---|---|---|
55+
| `MathS.Parse("factorize(360)")` | throws `UnrecognizedFunctionParseException` | a failure, `Unknown` with that message |
56+
| `MathS.Parse("norm(v, p, q)")` | throws `FunctionArgumentCountException` | a failure, `Unknown` with that message |
57+
| `Entity.TryParse("factorize(360)", null, out _)` | throws `UnrecognizedFunctionParseException` | `false` |
58+
| `"factorize(360)".ToEntity()` | throws `UnrecognizedFunctionParseException` | the same |
59+
4560
### An equation is not raised to clear a radical the rest of it still holds
4661

4762
**Silent.** `Solve` raised an equation to clear a radical even where the rest of it held one too, inside a function:

‎Sources/AngouriMath/Core/Parser.cs‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ public abstract record ReasonOfFailureWhileParsing
3434
{
3535
/// <summary>
3636
/// The error is an unclassified error returned by the
37-
/// ANTLR's parser.
37+
/// ANTLR's parser, or a call the grammar refuses: a name refused
38+
/// by name, or a function given the wrong number of arguments.
3839
/// </summary>
3940
public sealed record Unknown(string Reason);
4041

@@ -218,7 +219,31 @@ static bool OpensOnMod(IList<IToken> tokens, int parenthesis)
218219
&& AngouriMathLexer.DefaultVocabulary.GetDisplayName(tokens[after].Type) == "'mod'";
219220
}
220221

222+
/// <summary>
223+
/// The parse <see cref="MathS.Parse"/> answers, which does not throw: a refusal the grammar makes by
224+
/// throwing, a name refused by name or a call with the wrong number of arguments, is the failure it
225+
/// describes, its message the reason. <c>factorize(360)</c> threw
226+
/// <see cref="UnrecognizedFunctionParseException"/> out of the parser that says it does not, and the MCP
227+
/// server's <c>am_parse</c> reported it as a tool that threw. Only a <see cref="ParseException"/> is
228+
/// taken, so a defect still surfaces. https://github.com/asc-community/AngouriMath/issues/2498
229+
/// </summary>
221230
internal static Either<Entity, Failure<ReasonWhyParsingFailed>> ParseSilent(string source)
231+
{
232+
try
233+
{
234+
return ParseThrowingRefusals(source);
235+
}
236+
catch (ParseException refused)
237+
{
238+
return new Failure<ReasonWhyParsingFailed>(new Unknown(refused.Message));
239+
}
240+
}
241+
242+
/// <summary>
243+
/// The parse, with a refusal the grammar makes thrown as its own exception, which is what
244+
/// <see cref="Parse"/> and so <see cref="MathS.FromString(string)"/> throw.
245+
/// </summary>
246+
private static Either<Entity, Failure<ReasonWhyParsingFailed>> ParseThrowingRefusals(string source)
222247
{
223248
var writer = new AngouriMathTextWriter();
224249

@@ -329,7 +354,7 @@ private static Entity RationalLiterals(Entity parsed)
329354
=> parsed.Replace(static node => Antlr.ParsingHelpers.RationalLiteral(node));
330355

331356
internal static Entity Parse(string source)
332-
=> ParseSilent(source)
357+
=> ParseThrowingRefusals(source)
333358
.Switch(
334359
valid => valid,
335360
// ANTLR's diagnostic is a line and a column and nothing else, which names

‎Sources/Tests/McpUnitTests/ToolsTest.cs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,18 @@ public void AnUnknownNameBeforeABracketIsWarnedAboutAsAProduct(string expression
5959
Assert.Contains(answer.Warnings(), w => w.StartsWith(UnknownFunction));
6060
}
6161

62+
// A call the grammar refuses is a failed parse with the refusal's reason, not a tool that threw.
63+
// https://github.com/asc-community/AngouriMath/issues/2498
64+
[Theory]
65+
[InlineData("factorize(360)", "factorize")]
66+
[InlineData("norm(v, p, q)", "norm")]
67+
public void ARefusedCallIsAFailedParse(string expression, string named)
68+
{
69+
var answer = Mcp.Call("am_parse", $$"""{"expression":"{{expression}}"}""");
70+
Assert.Equal("failed", answer.Field("status"));
71+
Assert.Contains(named, answer.Field("error"));
72+
}
73+
6274
[Fact]
6375
public void StrictParsingRefusesAnImplicitProduct() =>
6476
Assert.Equal("failed", Mcp.Call("am_parse", """{"expression":"2x + 1","strict":true}""").Field("status"));
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
//
2+
// Copyright (c) 2019-2026 Angouri.
3+
// AngouriMath is licensed under MIT.
4+
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
5+
// Website: https://am.angouri.org.
6+
//
7+
8+
using AngouriMath;
9+
using AngouriMath.Core.Exceptions;
10+
using AngouriMath.Extensions;
11+
using Xunit;
12+
13+
namespace AngouriMath.Tests.Convenience
14+
{
15+
/// <summary>
16+
/// <see cref="MathS.Parse"/> does not throw: a call the grammar refuses, a name refused by name or a function given
17+
/// the wrong number of arguments, is the failure it describes. It threw the refusal's exception, and so did
18+
/// <c>Entity.TryParse</c>. <see cref="MathS.FromString(string)"/> still throws it, with its own type.
19+
/// https://github.com/asc-community/AngouriMath/issues/2498
20+
/// </summary>
21+
[Trait("Area", "Convenience")]
22+
public sealed class ParseReturnsARefusalTest
23+
{
24+
[Theory]
25+
[InlineData("factorize(360)", "factorize")]
26+
[InlineData("nextprime(10)", "nextprime")]
27+
[InlineData("norm(v, p, q)", "norm")]
28+
[InlineData("sin(x, y)", "sin")]
29+
public void ParseAnswersTheRefusal(string source, string named)
30+
{
31+
var reason = MathS.Parse(source).Switch(
32+
parsed => throw new Xunit.Sdk.XunitException($"{source} parsed as {parsed}"),
33+
failure => failure.Reason.Switch(
34+
unknown => unknown.Reason,
35+
missingOperator => throw new Xunit.Sdk.XunitException("a missing operator"),
36+
internalError => throw new Xunit.Sdk.XunitException($"an internal error: {internalError.Details}")));
37+
Assert.Contains(named, reason);
38+
}
39+
40+
[Theory]
41+
[InlineData("factorize(360)")]
42+
[InlineData("norm(v, p, q)")]
43+
public void TryParseSaysNo(string source)
44+
=> Assert.False(Entity.TryParse(source, null, out _));
45+
46+
[Fact]
47+
public void FromStringStillThrowsTheRefusal()
48+
{
49+
Assert.Throws<UnrecognizedFunctionParseException>(() => "factorize(360)".ToEntity());
50+
Assert.Throws<FunctionArgumentCountException>(() => "norm(v, p, q)".ToEntity());
51+
}
52+
53+
[Fact]
54+
public void AValidInputStillParses()
55+
=> Assert.Equal("sin(x) + 1".ToEntity(), MathS.Parse("sin(x) + 1").Switch(parsed => parsed, _ => null!));
56+
}
57+
}

0 commit comments

Comments
 (0)