Skip to content

expression-parsing: read a number followed by j or J like 2i - #33

Open
peterbjohnson wants to merge 1 commit into
mainfrom
fix/number-followed-by-j
Open

peterbjohnson wants to merge 1 commit into
mainfrom
fix/number-followed-by-j

Conversation

@peterbjohnson

Copy link
Copy Markdown
Member

Fixes lambda-feedback/compareExpressions#321.

Python's tokenizer reads 2j (also 2.5J, 1e3j) as one imaginary literal, and auto_number turns it into 2*I. So without complexNumbers, 3i+2j+6k parsed as 3*i + 2*I + 6*k (with I just an ordinary symbol), whatever input symbols the task defined.

Change

A new token transformation _split_imaginary_literals in SympyParsingConfig.transformations(). It runs first, before auto_symbol, and only when complex_numbers is off. It splits a NUMBER token ending in j/J into the number and the NAME j/J, without inserting *, so the existing rules apply:

input complexNumbers off, loose off, strict on
4j 4*j syntax error (was 4*I) 4*I, unchanged
3i+2j+6k 3*i + 2*j + 6*k syntax error, unchanged unchanged
2.5J 5*J/2 syntax error (was 5*I/2) unchanged
j, x2j, x_2j, 0x1f unchanged unchanged unchanged

In strict syntax 2j is now rejected, the same as 2i. 1e3j still runs into compareExpressions#322 (e with elementary_functions), which is out of scope here.

Physical quantities still need a space between value and unit: 2J keeps its "J was not interpreted as a unit" feedback.

Checks

  • ruff check, ruff format --check, mypy: clean
  • scripts/test.sh: all pass. The 15 new tests are in TestNumberFollowedByJ, and 7 of them fail without the fix.
  • tools/parity/check.py: 0 unexpected, 0 mismatched
  • compareExpressions main with this branch installed: 1281 passed, 2 skipped, 1 xfailed

Releasing needs a version bump and tag (e.g. v0.3.0-rc.6) after merge, so compareExpressions can pin it.

🤖 Generated with Claude Code

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 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Number followed by j or J parses as a Python complex literal

1 participant