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
15 changes: 15 additions & 0 deletions BREAKING-CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,21 @@ A not-equal written `<>` is read as `not (a = b)`, and printed that way.

## Unreleased — since 2.8.0

### `MathS.Parse` and `Entity.TryParse` return a refused call rather than throw it

**Not silent: what threw now returns.** `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, a name refused by name or a function
given the wrong number of arguments. Each now answers the failure, the refusal's message its reason. `FromString` and
the conversion from a string still throw it, with its own type
([#2498](https://github.com/asc-community/AngouriMath/issues/2498)).

| Input | Was (2.8.0) | Now |
|---|---|---|
| `MathS.Parse("factorize(360)")` | throws `UnrecognizedFunctionParseException` | a failure, `Unknown` with that message |
| `MathS.Parse("norm(v, p, q)")` | throws `FunctionArgumentCountException` | a failure, `Unknown` with that message |
| `Entity.TryParse("factorize(360)", null, out _)` | throws `UnrecognizedFunctionParseException` | `false` |
| `"factorize(360)".ToEntity()` | throws `UnrecognizedFunctionParseException` | the same |

### An equation is not raised to clear a radical the rest of it still holds

**Silent.** `Solve` raised an equation to clear a radical even where the rest of it held one too, inside a function:
Expand Down
29 changes: 27 additions & 2 deletions Sources/AngouriMath/Core/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ public abstract record ReasonOfFailureWhileParsing
{
/// <summary>
/// The error is an unclassified error returned by the
/// ANTLR's parser.
/// ANTLR's parser, or a call the grammar refuses: a name refused
/// by name, or a function given the wrong number of arguments.
/// </summary>
public sealed record Unknown(string Reason);

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

/// <summary>
/// The parse <see cref="MathS.Parse"/> answers, which does not throw: a refusal the grammar makes by
/// throwing, a name refused by name or a call with the wrong number of arguments, is the failure it
/// describes, its message the reason. <c>factorize(360)</c> threw
/// <see cref="UnrecognizedFunctionParseException"/> out of the parser that says it does not, and the MCP
/// server's <c>am_parse</c> reported it as a tool that threw. Only a <see cref="ParseException"/> is
/// taken, so a defect still surfaces. https://github.com/asc-community/AngouriMath/issues/2498
/// </summary>
internal static Either<Entity, Failure<ReasonWhyParsingFailed>> ParseSilent(string source)
{
try
{
return ParseThrowingRefusals(source);
}
catch (ParseException refused)
{
return new Failure<ReasonWhyParsingFailed>(new Unknown(refused.Message));
}
}

/// <summary>
/// The parse, with a refusal the grammar makes thrown as its own exception, which is what
/// <see cref="Parse"/> and so <see cref="MathS.FromString(string)"/> throw.
/// </summary>
private static Either<Entity, Failure<ReasonWhyParsingFailed>> ParseThrowingRefusals(string source)
{
var writer = new AngouriMathTextWriter();

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

internal static Entity Parse(string source)
=> ParseSilent(source)
=> ParseThrowingRefusals(source)
.Switch(
valid => valid,
// ANTLR's diagnostic is a line and a column and nothing else, which names
Expand Down
12 changes: 12 additions & 0 deletions Sources/Tests/McpUnitTests/ToolsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@ public void AnUnknownNameBeforeABracketIsWarnedAboutAsAProduct(string expression
Assert.Contains(answer.Warnings(), w => w.StartsWith(UnknownFunction));
}

// A call the grammar refuses is a failed parse with the refusal's reason, not a tool that threw.
// https://github.com/asc-community/AngouriMath/issues/2498
[Theory]
[InlineData("factorize(360)", "factorize")]
[InlineData("norm(v, p, q)", "norm")]
public void ARefusedCallIsAFailedParse(string expression, string named)
{
var answer = Mcp.Call("am_parse", $$"""{"expression":"{{expression}}"}""");
Assert.Equal("failed", answer.Field("status"));
Assert.Contains(named, answer.Field("error"));
}

[Fact]
public void StrictParsingRefusesAnImplicitProduct() =>
Assert.Equal("failed", Mcp.Call("am_parse", """{"expression":"2x + 1","strict":true}""").Field("status"));
Expand Down
57 changes: 57 additions & 0 deletions Sources/Tests/UnitTests/Convenience/ParseReturnsARefusalTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//
// Copyright (c) 2019-2026 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
// Website: https://am.angouri.org.
//

using AngouriMath;
using AngouriMath.Core.Exceptions;
using AngouriMath.Extensions;
using Xunit;

namespace AngouriMath.Tests.Convenience
{
/// <summary>
/// <see cref="MathS.Parse"/> does not throw: a call the grammar refuses, a name refused by name or a function given
/// the wrong number of arguments, is the failure it describes. It threw the refusal's exception, and so did
/// <c>Entity.TryParse</c>. <see cref="MathS.FromString(string)"/> still throws it, with its own type.
/// https://github.com/asc-community/AngouriMath/issues/2498
/// </summary>
[Trait("Area", "Convenience")]
public sealed class ParseReturnsARefusalTest
{
[Theory]
[InlineData("factorize(360)", "factorize")]
[InlineData("nextprime(10)", "nextprime")]
[InlineData("norm(v, p, q)", "norm")]
[InlineData("sin(x, y)", "sin")]
public void ParseAnswersTheRefusal(string source, string named)
{
var reason = MathS.Parse(source).Switch(
parsed => throw new Xunit.Sdk.XunitException($"{source} parsed as {parsed}"),
failure => failure.Reason.Switch(
unknown => unknown.Reason,
missingOperator => throw new Xunit.Sdk.XunitException("a missing operator"),
internalError => throw new Xunit.Sdk.XunitException($"an internal error: {internalError.Details}")));
Assert.Contains(named, reason);
}

[Theory]
[InlineData("factorize(360)")]
[InlineData("norm(v, p, q)")]
public void TryParseSaysNo(string source)
=> Assert.False(Entity.TryParse(source, null, out _));

[Fact]
public void FromStringStillThrowsTheRefusal()
{
Assert.Throws<UnrecognizedFunctionParseException>(() => "factorize(360)".ToEntity());
Assert.Throws<FunctionArgumentCountException>(() => "norm(v, p, q)".ToEntity());
}

[Fact]
public void AValidInputStillParses()
=> Assert.Equal("sin(x) + 1".ToEntity(), MathS.Parse("sin(x) + 1").Switch(parsed => parsed, _ => null!));
}
}
Loading