Files
PowerToys/src/modules/cmdpal/ext/Microsoft.CmdPal.Ext.Calc/Helper/CalculateEngine.cs

125 lines
4.2 KiB
C#
Raw Normal View History

// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
[CmdPal][AOT] Using ExprTk to make the Cal extension AOT-compatible (#39972) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR replaces the original Mages-based expression evaluation engine with a WinRT-wrapped version of Exprtk in the CmdPalCalculator module. ### Key Changes **Expression Engine:** - All expression parsing and evaluation now use Exprtk (via a WinRT wrapper) instead of Mages. **Base Conversion Handling:** - Since Exprtk does not support non-decimal (binary, octal, hexadecimal) input natively, added logic to convert all such inputs to decimal before evaluation. **Code Structure:** - The overall logic and API surface remain unchanged except for the engine and base conversion handling. - All previous Mages references and dependencies have been removed. <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist - [ ] **Closes:** #xxx - [ ] **Communication:** I've discussed this with core contributors already. If work hasn't been agreed, this work might be rejected - [ ] **Tests:** Added/updated and all pass - [ ] **Localization:** All end user facing strings can be localized - [ ] **Dev docs:** Added/updated - [ ] **New binaries:** Added on the required places - [ ] [JSON for signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json) for new binaries - [ ] [WXS for installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs) for new binaries and localization folder - [ ] [YML for CI pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml) for new test projects - [ ] [YML for signed pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml) - [ ] **Documentation updated:** If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys) and link it here: #xxx <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed
2025-06-13 12:27:53 +08:00
using CalculatorEngineCommon;
using Windows.Foundation.Collections;
namespace Microsoft.CmdPal.Ext.Calc.Helper;
public static class CalculateEngine
{
[CmdPal][AOT] Using ExprTk to make the Cal extension AOT-compatible (#39972) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR replaces the original Mages-based expression evaluation engine with a WinRT-wrapped version of Exprtk in the CmdPalCalculator module. ### Key Changes **Expression Engine:** - All expression parsing and evaluation now use Exprtk (via a WinRT wrapper) instead of Mages. **Base Conversion Handling:** - Since Exprtk does not support non-decimal (binary, octal, hexadecimal) input natively, added logic to convert all such inputs to decimal before evaluation. **Code Structure:** - The overall logic and API surface remain unchanged except for the engine and base conversion handling. - All previous Mages references and dependencies have been removed. <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist - [ ] **Closes:** #xxx - [ ] **Communication:** I've discussed this with core contributors already. If work hasn't been agreed, this work might be rejected - [ ] **Tests:** Added/updated and all pass - [ ] **Localization:** All end user facing strings can be localized - [ ] **Dev docs:** Added/updated - [ ] **New binaries:** Added on the required places - [ ] [JSON for signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json) for new binaries - [ ] [WXS for installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs) for new binaries and localization folder - [ ] [YML for CI pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml) for new test projects - [ ] [YML for signed pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml) - [ ] **Documentation updated:** If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys) and link it here: #xxx <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed
2025-06-13 12:27:53 +08:00
private static readonly PropertySet _constants = new()
{
[CmdPal][AOT] Using ExprTk to make the Cal extension AOT-compatible (#39972) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR replaces the original Mages-based expression evaluation engine with a WinRT-wrapped version of Exprtk in the CmdPalCalculator module. ### Key Changes **Expression Engine:** - All expression parsing and evaluation now use Exprtk (via a WinRT wrapper) instead of Mages. **Base Conversion Handling:** - Since Exprtk does not support non-decimal (binary, octal, hexadecimal) input natively, added logic to convert all such inputs to decimal before evaluation. **Code Structure:** - The overall logic and API surface remain unchanged except for the engine and base conversion handling. - All previous Mages references and dependencies have been removed. <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist - [ ] **Closes:** #xxx - [ ] **Communication:** I've discussed this with core contributors already. If work hasn't been agreed, this work might be rejected - [ ] **Tests:** Added/updated and all pass - [ ] **Localization:** All end user facing strings can be localized - [ ] **Dev docs:** Added/updated - [ ] **New binaries:** Added on the required places - [ ] [JSON for signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json) for new binaries - [ ] [WXS for installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs) for new binaries and localization folder - [ ] [YML for CI pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml) for new test projects - [ ] [YML for signed pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml) - [ ] **Documentation updated:** If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys) and link it here: #xxx <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed
2025-06-13 12:27:53 +08:00
{ "pi", Math.PI },
{ "e", Math.E },
};
private static readonly Calculator _calculator = new Calculator(_constants);
public const int RoundingDigits = 10;
public enum TrigMode
{
Radians,
Degrees,
Gradians,
}
/// <summary>
/// Interpret
/// </summary>
/// <param name="cultureInfo">Use CultureInfo.CurrentCulture if something is user facing</param>
public static CalculateResult Interpret(SettingsManager settings, string input, CultureInfo cultureInfo, out string error)
{
error = default;
if (!CalculateHelper.InputValid(input))
{
return default;
}
// check for division by zero
// We check if the string contains a slash followed by space (optional) and zero. Whereas the zero must not be followed by a dot, comma, 'b', 'o' or 'x' as these indicate a number with decimal digits or a binary/octal/hexadecimal value respectively. The zero must also not be followed by other digits.
if (new Regex("\\/\\s*0(?!(?:[,\\.0-9]|[box]0*[1-9a-f]))", RegexOptions.IgnoreCase).Match(input).Success)
{
error = Properties.Resources.calculator_division_by_zero;
return default;
}
// mages has quirky log representation
// mage has log == ln vs log10
input = input.
Replace("log(", "log10(", true, CultureInfo.CurrentCulture).
Replace("ln(", "log(", true, CultureInfo.CurrentCulture);
input = CalculateHelper.FixHumanMultiplicationExpressions(input);
// Get the user selected trigonometry unit
TrigMode trigMode = settings.TrigUnit;
// Modify trig functions depending on angle unit setting
input = CalculateHelper.UpdateTrigFunctions(input, trigMode);
// Expand conversions between trig units
input = CalculateHelper.ExpandTrigConversions(input, trigMode);
[CmdPal][AOT] Using ExprTk to make the Cal extension AOT-compatible (#39972) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR replaces the original Mages-based expression evaluation engine with a WinRT-wrapped version of Exprtk in the CmdPalCalculator module. ### Key Changes **Expression Engine:** - All expression parsing and evaluation now use Exprtk (via a WinRT wrapper) instead of Mages. **Base Conversion Handling:** - Since Exprtk does not support non-decimal (binary, octal, hexadecimal) input natively, added logic to convert all such inputs to decimal before evaluation. **Code Structure:** - The overall logic and API surface remain unchanged except for the engine and base conversion handling. - All previous Mages references and dependencies have been removed. <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist - [ ] **Closes:** #xxx - [ ] **Communication:** I've discussed this with core contributors already. If work hasn't been agreed, this work might be rejected - [ ] **Tests:** Added/updated and all pass - [ ] **Localization:** All end user facing strings can be localized - [ ] **Dev docs:** Added/updated - [ ] **New binaries:** Added on the required places - [ ] [JSON for signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json) for new binaries - [ ] [WXS for installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs) for new binaries and localization folder - [ ] [YML for CI pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml) for new test projects - [ ] [YML for signed pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml) - [ ] **Documentation updated:** If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys) and link it here: #xxx <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed
2025-06-13 12:27:53 +08:00
var result = _calculator.EvaluateExpression(input);
// This could happen for some incorrect queries, like pi(2)
[CmdPal][AOT] Using ExprTk to make the Cal extension AOT-compatible (#39972) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR replaces the original Mages-based expression evaluation engine with a WinRT-wrapped version of Exprtk in the CmdPalCalculator module. ### Key Changes **Expression Engine:** - All expression parsing and evaluation now use Exprtk (via a WinRT wrapper) instead of Mages. **Base Conversion Handling:** - Since Exprtk does not support non-decimal (binary, octal, hexadecimal) input natively, added logic to convert all such inputs to decimal before evaluation. **Code Structure:** - The overall logic and API surface remain unchanged except for the engine and base conversion handling. - All previous Mages references and dependencies have been removed. <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist - [ ] **Closes:** #xxx - [ ] **Communication:** I've discussed this with core contributors already. If work hasn't been agreed, this work might be rejected - [ ] **Tests:** Added/updated and all pass - [ ] **Localization:** All end user facing strings can be localized - [ ] **Dev docs:** Added/updated - [ ] **New binaries:** Added on the required places - [ ] [JSON for signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json) for new binaries - [ ] [WXS for installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs) for new binaries and localization folder - [ ] [YML for CI pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml) for new test projects - [ ] [YML for signed pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml) - [ ] **Documentation updated:** If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys) and link it here: #xxx <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed
2025-06-13 12:27:53 +08:00
if (result == "NaN")
{
error = Properties.Resources.calculator_expression_not_complete;
return default;
}
[CmdPal][AOT] Using ExprTk to make the Cal extension AOT-compatible (#39972) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR replaces the original Mages-based expression evaluation engine with a WinRT-wrapped version of Exprtk in the CmdPalCalculator module. ### Key Changes **Expression Engine:** - All expression parsing and evaluation now use Exprtk (via a WinRT wrapper) instead of Mages. **Base Conversion Handling:** - Since Exprtk does not support non-decimal (binary, octal, hexadecimal) input natively, added logic to convert all such inputs to decimal before evaluation. **Code Structure:** - The overall logic and API surface remain unchanged except for the engine and base conversion handling. - All previous Mages references and dependencies have been removed. <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist - [ ] **Closes:** #xxx - [ ] **Communication:** I've discussed this with core contributors already. If work hasn't been agreed, this work might be rejected - [ ] **Tests:** Added/updated and all pass - [ ] **Localization:** All end user facing strings can be localized - [ ] **Dev docs:** Added/updated - [ ] **New binaries:** Added on the required places - [ ] [JSON for signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json) for new binaries - [ ] [WXS for installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs) for new binaries and localization folder - [ ] [YML for CI pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml) for new test projects - [ ] [YML for signed pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml) - [ ] **Documentation updated:** If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys) and link it here: #xxx <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed
2025-06-13 12:27:53 +08:00
if (string.IsNullOrEmpty(result))
{
return default;
}
var decimalResult = Convert.ToDecimal(result, new CultureInfo("en-US"));
[CmdPal][AOT] Using ExprTk to make the Cal extension AOT-compatible (#39972) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR replaces the original Mages-based expression evaluation engine with a WinRT-wrapped version of Exprtk in the CmdPalCalculator module. ### Key Changes **Expression Engine:** - All expression parsing and evaluation now use Exprtk (via a WinRT wrapper) instead of Mages. **Base Conversion Handling:** - Since Exprtk does not support non-decimal (binary, octal, hexadecimal) input natively, added logic to convert all such inputs to decimal before evaluation. **Code Structure:** - The overall logic and API surface remain unchanged except for the engine and base conversion handling. - All previous Mages references and dependencies have been removed. <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist - [ ] **Closes:** #xxx - [ ] **Communication:** I've discussed this with core contributors already. If work hasn't been agreed, this work might be rejected - [ ] **Tests:** Added/updated and all pass - [ ] **Localization:** All end user facing strings can be localized - [ ] **Dev docs:** Added/updated - [ ] **New binaries:** Added on the required places - [ ] [JSON for signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json) for new binaries - [ ] [WXS for installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs) for new binaries and localization folder - [ ] [YML for CI pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml) for new test projects - [ ] [YML for signed pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml) - [ ] **Documentation updated:** If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys) and link it here: #xxx <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed
2025-06-13 12:27:53 +08:00
[CmdPal]Limit exprtk result to 15 total digits with proper rounding (#40194) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR addresses an issue where direct double output from exprtk evaluation led to precision artifacts (e.g., 12.2 + 10 resulting in 22.199999999999999). This behavior is due to how double represents decimal fractions in binary. - To improve user-facing precision, the result is now: - Converted to decimal for higher decimal accuracy. - Rounded to fit within 15 total significant digits (integer + fraction). - Formatted using "G29" to eliminate unnecessary trailing zeros. - Cleaned up to remove dangling decimal points. This ensures more intuitive and readable output like: - 1.9999999999 → "1.9999999999" - 100000.9999999999 → "100001" - 100000.999999999 → "100000.999999999" This change improves clarity, especially for users entering expressions expecting decimal-accurate results. <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist - [ ] **Closes:** #40097 - [ ] **Communication:** I've discussed this with core contributors already. If the work hasn't been agreed, this work might be rejected - [ ] **Tests:** Added/updated and all pass - [ ] **Localization:** All end-user-facing strings can be localized - [ ] **Dev docs:** Added/updated - [ ] **New binaries:** Added on the required places - [ ] [JSON for signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json) for new binaries - [ ] [WXS for installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs) for new binaries and localization folder - [ ] [YML for CI pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml) for new test projects - [ ] [YML for signed pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml) - [ ] **Documentation updated:** If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys) and link it here: #xxx <!-- Provide a more detailed description of the PR, other things fixed, or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed
2025-06-24 13:42:22 +08:00
var roundedResult = FormatMax15Digits(decimalResult, cultureInfo);
return new CalculateResult()
{
Result = decimalResult,
RoundedResult = roundedResult,
};
}
public static decimal Round(decimal value)
{
return Math.Round(value, RoundingDigits, MidpointRounding.AwayFromZero);
}
[CmdPal]Limit exprtk result to 15 total digits with proper rounding (#40194) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR addresses an issue where direct double output from exprtk evaluation led to precision artifacts (e.g., 12.2 + 10 resulting in 22.199999999999999). This behavior is due to how double represents decimal fractions in binary. - To improve user-facing precision, the result is now: - Converted to decimal for higher decimal accuracy. - Rounded to fit within 15 total significant digits (integer + fraction). - Formatted using "G29" to eliminate unnecessary trailing zeros. - Cleaned up to remove dangling decimal points. This ensures more intuitive and readable output like: - 1.9999999999 → "1.9999999999" - 100000.9999999999 → "100001" - 100000.999999999 → "100000.999999999" This change improves clarity, especially for users entering expressions expecting decimal-accurate results. <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist - [ ] **Closes:** #40097 - [ ] **Communication:** I've discussed this with core contributors already. If the work hasn't been agreed, this work might be rejected - [ ] **Tests:** Added/updated and all pass - [ ] **Localization:** All end-user-facing strings can be localized - [ ] **Dev docs:** Added/updated - [ ] **New binaries:** Added on the required places - [ ] [JSON for signing](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ESRPSigning_core.json) for new binaries - [ ] [WXS for installer](https://github.com/microsoft/PowerToys/blob/main/installer/PowerToysSetup/Product.wxs) for new binaries and localization folder - [ ] [YML for CI pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/ci/templates/build-powertoys-steps.yml) for new test projects - [ ] [YML for signed pipeline](https://github.com/microsoft/PowerToys/blob/main/.pipelines/release.yml) - [ ] **Documentation updated:** If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/windows-uwp/tree/docs/hub/powertoys) and link it here: #xxx <!-- Provide a more detailed description of the PR, other things fixed, or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed
2025-06-24 13:42:22 +08:00
/// <summary>
/// Format a decimal so that the output contains **at most 15 total digits**
/// (integer + fraction, not counting the decimal point or minus sign).
/// Any extra fractional digits are rounded using “away-from-zero” rounding.
/// Trailing zeros in the fractional part—and a dangling decimal point—are removed.
/// Examples
/// 1.9999999999 → "1.9999999999"
/// 100000.9999999999 → "100001"
/// 1234567890123.45 → "1234567890123.45"
/// </summary>
private static decimal FormatMax15Digits(decimal value, CultureInfo cultureInfo)
{
var absValue = Math.Abs(value);
var integerDigits = absValue >= 1 ? (int)Math.Floor(Math.Log10((double)absValue)) + 1 : 1;
var maxDecimalDigits = Math.Max(0, 15 - integerDigits);
var rounded = Math.Round(value, maxDecimalDigits, MidpointRounding.AwayFromZero);
var formatted = rounded.ToString("G29", cultureInfo);
return Convert.ToDecimal(formatted, cultureInfo);
}
}