Skip to content
Open
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
1 change: 1 addition & 0 deletions expression_parsing/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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}
Expand Down Expand Up @@ -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)
Expand Down
36 changes: 36 additions & 0 deletions expression_parsing/tests/test_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
Abs,
Eq,
Function,
I,
Integral,
Limit,
Product,
Expand Down Expand Up @@ -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)
Loading