From 7006a92d4a17396aa4984f4297149d7d508b2acd Mon Sep 17 00:00:00 2001 From: "Peter B. Johnson" Date: Fri, 27 Nov 2026 21:52:11 +0000 Subject: [PATCH] expression-parsing: read a number followed by j or J like 2i Python's tokenizer reads `2j` (also `2.5J`, `1e3j`) as one imaginary literal, so without complexNumbers `3i+2j+6k` parsed as `3*i + 2*I + 6*k`, whatever symbols the task defined. A new transformation, placed before auto_symbol and used only without complex_numbers, splits such a NUMBER token into the number and the name `j` or `J`. Implicit multiplication then reads it as `2*j`; with strict syntax it is a syntax error, like `2i`. With complex_numbers nothing changes. Names such as `x2j` are NAME tokens and unaffected. Fixes lambda-feedback/compareExpressions#321. Co-Authored-By: Claude Opus 5.5 --- expression_parsing/CHANGELOG.md | 1 + .../expression_parsing/sympy_parsing.py | 26 ++++++++++++-- expression_parsing/tests/test_regressions.py | 36 +++++++++++++++++++ 3 files changed, 61 insertions(+), 2 deletions(-) diff --git a/expression_parsing/CHANGELOG.md b/expression_parsing/CHANGELOG.md index f183325..19efdc7 100644 --- a/expression_parsing/CHANGELOG.md +++ b/expression_parsing/CHANGELOG.md @@ -69,6 +69,7 @@ The first public release. Further tidy-up after the 0.2.0 extraction: previewing - `is_number("2*10^3")` is true: the `^` in `NUMBER_REGEX` was an unescaped anchor, so the `*10^` exponent form never matched. - `compute_relative_tolerance_from_significant_decimals` counts only the mantissa for `1.5E3` and `1.5*10^3` (it counted the exponent's digits as significant figures, giving 5e-4 instead of 0.05). - `parse_latex` recognises `\pm`/`\mp` without a following space (`1\pm\sqrt{2}` failed to parse), and no longer runs symbol substitution over the LaTeX when expanding them (`\lambda` became `\lamda`). +- Without `complex_numbers`, a number followed by `j` or `J` is the number times the symbol `j` or `J`, like `2i`: `3i+2j+6k` is `3*i + 2*j + 6*k`, and `2.5J` is `5*J/2`. Python's tokenizer reads `2j` as an imaginary literal, so it was `2*I`, with `I` an ordinary symbol, whatever symbols the task defined. With strict syntax `2j` is now a syntax error, like `2i` (it was accepted as `2*I`). With `complex_numbers` nothing changes: `2j` is `2*I`, the imaginary number. A name ending in a number and `j` (`x2j`, `x_2j`) is unaffected. ## 0.2.0 (internal, not published) diff --git a/expression_parsing/src/lambdafeedback/expression_parsing/sympy_parsing.py b/expression_parsing/src/lambdafeedback/expression_parsing/sympy_parsing.py index c99e033..ea6bd98 100644 --- a/expression_parsing/src/lambdafeedback/expression_parsing/sympy_parsing.py +++ b/expression_parsing/src/lambdafeedback/expression_parsing/sympy_parsing.py @@ -9,7 +9,7 @@ from functools import cached_property from io import StringIO from keyword import iskeyword -from token import NAME, OP +from token import NAME, NUMBER, OP from tokenize import TokenError, generate_tokens from typing import Any @@ -90,6 +90,25 @@ def _keywords_as_names(tokens: list[Any], local_dict: dict[str, Any], global_dic return result +def _split_imaginary_literals(tokens: list[Any], local_dict: dict[str, Any], global_dict: Any) -> list[Any]: + """Read a number followed by ``j`` or ``J`` as the number and then the name ``j`` or ``J``. + + Python's tokenizer reads ``2j`` (also ``2.5J``, ``1e3j``) as one imaginary + literal, which ``auto_number`` would make ``2*I``, so ``3i+2j+6k`` was + ``3*i + 2*I + 6*k``. Split, it reads like ``2i``: ``2*j`` by implicit + multiplication, and a syntax error with strict syntax. Only used without + ``complex_numbers``, where ``2j`` keeps its meaning ``2*I``. A number that + is part of a name (``x2j``) is a NAME token and is not affected. + """ + result: list[Any] = [] + for kind, value in tokens: + if kind == NUMBER and value[-1] in "jJ": + result += [(NUMBER, value[:-1]), (NAME, value[-1])] + else: + result.append((kind, value)) + return result + + def sympy_symbols(symbols: Iterable[str]) -> dict[str, Symbol]: """``{name: Symbol(name)}`` for use as ``parse_expr``'s ``local_dict``.""" return {name: Symbol(name) for name in symbols} @@ -235,7 +254,10 @@ def transformations(self) -> tuple[Any, ...]: """ # _keywords_as_names goes after auto_symbol (which leaves keywords alone, and # would wrap our Symbol('in') again), before the symbol splitting. - leading = (lambda_notation, auto_symbol, _keywords_as_names, repeated_decimals, auto_number) + leading: tuple[Any, ...] = (lambda_notation, auto_symbol, _keywords_as_names, repeated_decimals, auto_number) + # _split_imaginary_literals goes before auto_symbol, which declares the new name j or J. + if not self.params.complex_numbers: + leading = (_split_imaginary_literals, *leading) transformations: tuple[Any, ...] if self.params.strict_syntax: transformations = (*leading, function_exponentiation) diff --git a/expression_parsing/tests/test_regressions.py b/expression_parsing/tests/test_regressions.py index 9605956..d14c0b8 100644 --- a/expression_parsing/tests/test_regressions.py +++ b/expression_parsing/tests/test_regressions.py @@ -11,6 +11,7 @@ Abs, Eq, Function, + I, Integral, Limit, Product, @@ -913,3 +914,38 @@ def test_parsing_logs_its_decisions_at_debug_only(caplog): assert any(message.startswith("preprocess '2 sin(x)'") for message in messages) assert any(message.startswith("parse ") and "sin(x)" in message for message in messages) assert all(record.levelno == logging.DEBUG for record in caplog.records) + + +class TestNumberFollowedByJ: + """Python reads ``2j`` as an imaginary literal; without ``complexNumbers`` it reads like ``2i``.""" + + @pytest.mark.parametrize( + "expr, expected", + [ + ("4j", "4*j"), + ("3i+2j+6k", "3*i + 2*j + 6*k"), + ("2.5J", "5*J/2"), + ("sin(2j)", "sin(2*j)"), + ("j", "j"), + ("x_2j", "x_2j"), + ], + ) + def test_is_multiplication(self, expr, expected): + config = parsing_params(strict_syntax=False, elementary_functions=True) + assert str(parse_expression(expr, config)) == expected + + def test_number_in_a_name_is_not_split_off(self): + config = SympyParsingConfig.from_params(ExpressionParams.from_dict({"strict_syntax": False}), ("x2j",)) + assert parse_expression("x2j", config) == Symbol("x2j") + assert parse_expression("0x1f", config) == 31 + + @pytest.mark.parametrize("expr", ["4j", "3i+2j+6k", "2.5J", "sin(2j)"]) + def test_is_rejected_with_strict_syntax(self, expr): + with pytest.raises(ExpressionParsingError): + parse_expression(expr, parsing_params(strict_syntax=True)) + + @pytest.mark.parametrize("strict_syntax", [False, True]) + @pytest.mark.parametrize("expr", ["4j", "2.5J"]) + def test_is_imaginary_with_complex_numbers(self, expr, strict_syntax): + config = parsing_params(complexNumbers=True, strict_syntax=strict_syntax) + assert parse_expression(expr, config).has(I)