From e72ac40b452795dd18c2a35eaba9796878f627cf Mon Sep 17 00:00:00 2001 From: isgav <51133755+isaranga@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:11:30 +0200 Subject: [PATCH 1/3] Compute isolating run sequences once, as rule X10 apply_bidi_algorithm now calls get_isolating_run_sequences once, right after phase X, and passes the result to apply_weak_rules and apply_neutral_rules, which used to compute it themselves. Comments explain why running each phase across all sequences matches the spec's per-sequence order, and why phase I can run on the whole paragraph. Verbose mode prints the sequences in a new X10 section (print_isolating_run_sequences in verbose_table.py). README.md, CLAUDE.md, example 7's note and the reviewing-functions command are updated to match. Both conformance suites still pass in full. --- .claude/commands/reviewing-functions.md | 2 +- CLAUDE.md | 7 ++-- README.md | 8 +++-- bidi.py | 47 +++++++++++++++++-------- demo.py | 5 +-- verbose_table.py | 41 +++++++++++++++++++++ 6 files changed, 87 insertions(+), 23 deletions(-) diff --git a/.claude/commands/reviewing-functions.md b/.claude/commands/reviewing-functions.md index d991248..9a0ff70 100644 --- a/.claude/commands/reviewing-functions.md +++ b/.claude/commands/reviewing-functions.md @@ -39,7 +39,7 @@ Work through the function body from the `def` statement through the last line be ### UAX#9 context for bidi.py -The data model centers on `CharacterInfo` — `original_type` is immutable, `character_type` is the working copy mutated per phase. Phase-orchestrating functions delegate to `_apply_*` helpers; the W and N phases (`apply_weak_rules`, `apply_neutral_rules`) also call `get_isolating_run_sequences`. `print_table` handles verbose output uniformly. Flag any divergence from these conventions. +The data model centers on `CharacterInfo` — `original_type` is immutable, `character_type` is the working copy mutated per phase. Phase-orchestrating functions delegate to `_apply_*` helpers; `apply_bidi_algorithm` computes the isolating run sequences once (X10, `get_isolating_run_sequences`) and passes them to the W and N phases (`apply_weak_rules`, `apply_neutral_rules`); the I phase works on the whole paragraph, since I1/I2 are per-character. `print_table` handles verbose output uniformly. Flag any divergence from these conventions. ## Step 3 — Produce the findings table diff --git a/CLAUDE.md b/CLAUDE.md index d1c69dc..bba8414 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -63,18 +63,19 @@ levels, reordered, para_level, visual_order = apply_bidi_algorithm("Hello שלו Rule P1 is `split_into_paragraphs`, which works on the raw string and runs before everything else: it splits after each type-B character (CR LF counts as one), keeping the separator at the end of its paragraph. `apply_bidi_algorithm` handles **one paragraph** (a B may only be its last character); callers with longer text call it once per paragraph. The conformance files contain no B except at the end, so P1 is not covered by them. -`apply_bidi_algorithm` orchestrates six phases in order, each corresponding to a section of UAX #9: +`apply_bidi_algorithm` orchestrates these steps in order, each corresponding to a section of UAX #9: | Phase | Function | UAX #9 rules | |-------|----------|--------------| | P | `determine_paragraph_embedding_level` | P2–P3 (P1 is applied beforehand) | | X | `apply_explicit_levels` | X1–X9 | +| X10 | `get_isolating_run_sequences` | X10 (BD13) | | W | `apply_weak_rules` | W1–W7 | | N | `apply_neutral_rules` | N0–N2 | | I | `apply_implicit_rules` | I1–I2 | | L | `apply_reorder_rules` | L1–L4 | -Phases W and N operate on **isolating run sequences** (BD13), computed by `get_isolating_run_sequences`. Each IRS chains contiguous level runs that are linked by isolate initiators (LRI/RLI/FSI) to their matching PDI, and carries `sos`/`eos` context types. +Phases W and N operate on **isolating run sequences** (BD13), computed by `get_isolating_run_sequences`. Each IRS chains contiguous level runs that are linked by isolate initiators (LRI/RLI/FSI) to their matching PDI, and carries `sos`/`eos` context types. `apply_bidi_algorithm` computes the list once (rule X10), right after phase X, and passes it to `apply_weak_rules` and `apply_neutral_rules`. The spec takes each IRS through W, N and I in turn, but the code runs each phase across all sequences. This is equivalent because no rule reads outside its own IRS (except through `sos`/`eos`). Phase I is not given the sequences: I1/I2 depend only on each character's own type and level, so `apply_implicit_rules` runs over the whole paragraph. Comments in `apply_bidi_algorithm` and `apply_implicit_rules` explain both points. The W and N phases each delegate to private per-rule helpers (`_apply_w1`…`_apply_w7`, `_apply_n0`, `_apply_n1`, `_apply_n2`). The L phase similarly delegates to `_apply_l1`…`_apply_l4`. @@ -82,7 +83,7 @@ Bracket pair detection for N0 is handled by `_find_bracket_pairs`, using `OPEN_B ### Verbose mode -Every phase function (and `_apply_i1`/`_apply_i2`) accepts `verbose=True`; the per-rule W, N and L helpers do not, and their phase function prints on their behalf. When enabled, `print_table` (in `verbose_table.py`, together with the helpers below) prints a before/after table for each rule application, with rows for character index, code point, the character itself, the type (or level, or position) before and after the rule, and embedding level. `print_table` decides "(no changes)" by comparing only the Before/After rows, so Phase X prints two tables: "X1-X8 (levels)" (Before is the paragraph level from X1) and "X1-X9 (types)" (overrides, FSI resolution, X9's BN). Without the levels table, an isolate or embedding with no override would show as "(no changes)". Columns are always in logical order, including the L2 and L4 tables, where Before/After give each character's position before and after reordering. +Every phase function (and `_apply_i1`/`_apply_i2`) accepts `verbose=True`; the per-rule W, N and L helpers do not, and their phase function prints on their behalf. When enabled, `print_table` (in `verbose_table.py`, together with the helpers below) prints a before/after table for each rule application, with rows for character index, code point, the character itself, the type (or level, or position) before and after the rule, and embedding level. `print_table` decides "(no changes)" by comparing only the Before/After rows, so Phase X prints two tables: "X1-X8 (levels)" (Before is the paragraph level from X1) and "X1-X9 (types)" (overrides, FSI resolution, X9's BN). Without the levels table, an isolate or embedding with no override would show as "(no changes)". After phase X, `apply_bidi_algorithm` calls `print_isolating_run_sequences` (also in `verbose_table.py`), which prints the X10 sequences one line each: level, character indices as ranges, `sos`/`eos`. Columns are always in logical order, including the L2 and L4 tables, where Before/After give each character's position before and after reordering. Characters in table cells go through `format_char_for_table`: controls and whitespace are left blank, combining marks are shown on a dotted circle, and each R/AL character is followed by an invisible LEFT-TO-RIGHT MARK so that bidi-aware viewers (Markdown previews, GitHub) don't reverse runs of the row. Cells are sized and centered by `display_width`/`center_in_column`, not `len()`, because those marks take no column on screen. The tracing example in README.md is copied from real output (LRMs included); update it whenever the table format changes. diff --git a/README.md b/README.md index a87559b..a719818 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ for paragraph in split_into_paragraphs("שלום\nHello"): ## Tracing the algorithm -Pass `verbose=True` to see every rule as it runs. Rules that change nothing print a single line; rules that do change something print a table showing each character's index, its code point, the character itself, its type (or level) before and after the rule, and its embedding level. Changed cells are highlighted in the terminal. Phase X prints two tables, one for the levels it assigns and one for the types it changes, so that an embedding or isolate shows up even when no type changes. +Pass `verbose=True` to see every rule as it runs. Rules that change nothing print a single line; rules that do change something print a table showing each character's index, its code point, the character itself, its type (or level) before and after the rule, and its embedding level. Changed cells are highlighted in the terminal. Phase X prints two tables, one for the levels it assigns and one for the types it changes, so that an embedding or isolate shows up even when no type changes. Rule X10 then lists the isolating run sequences, one line each, with their level, characters and `sos`/`eos`. ```python apply_bidi_algorithm("שלום 123 Hi", verbose=True) @@ -101,12 +101,13 @@ Here N1 turns the space between the Hebrew word and the digits into `R`, because ## How the code is organised -Rule P1 comes first: `split_into_paragraphs` cuts the text into paragraphs after each paragraph separator. `apply_bidi_algorithm` then runs six phases in order on one paragraph. Each matches a section of UAX #9: +Rule P1 comes first: `split_into_paragraphs` cuts the text into paragraphs after each paragraph separator. `apply_bidi_algorithm` then runs these steps in order on one paragraph. Each matches a section of UAX #9: | Phase | Function | UAX #9 rules | What it does | |-------|----------|--------------|--------------| | P | `determine_paragraph_embedding_level` | P2–P3 | Picks the paragraph direction | | X | `apply_explicit_levels` | X1–X9 | Applies explicit embeddings, overrides and isolates (LRE, RLO, LRI, PDF, PDI, …) | +| X10 | `get_isolating_run_sequences` | X10 (BD13) | Splits the paragraph into isolating run sequences | | W | `apply_weak_rules` | W1–W7 | Resolves weak types such as numbers and separators | | N | `apply_neutral_rules` | N0–N2 | Resolves neutrals: brackets first (N0), then spaces and punctuation | | I | `apply_implicit_rules` | I1–I2 | Turns the resolved types into final embedding levels | @@ -115,7 +116,8 @@ Rule P1 comes first: `split_into_paragraphs` cuts the text into paragraphs after Some things to know when reading the code: - **`CharacterInfo`** is the record passed through every phase. `original_type` is the character's Unicode bidi class and never changes; `character_type` is a working copy that the rules update. -- **Isolating run sequences** (definition BD13) are what phases W and N work on. `get_isolating_run_sequences` builds them by linking runs of the same level across an isolate (LRI/RLI/FSI … PDI), and attaches the `sos`/`eos` types at each end. +- **Isolating run sequences** (definition BD13) are what phases W and N work on. Rule X10 finds them: `get_isolating_run_sequences` builds them by linking runs of the same level across an isolate (LRI/RLI/FSI … PDI), and attaches the `sos`/`eos` types at each end. `apply_bidi_algorithm` computes them once and passes them to both phases; verbose mode lists them. UAX #9 also applies rules I1–I2 per sequence, but they look only at each character's own type and level, so `apply_implicit_rules` applies them to the whole paragraph at once, with the same result. +- UAX #9 takes each sequence through W, N and I before moving to the next one. The code instead runs phase W on every sequence, then phase N, then phase I. Each sequence's rules look only at that sequence's characters (and its `sos`/`eos`), so the order makes no difference. - **Bracket pairs** for rule N0 are found by `_find_bracket_pairs`, using pairs read from [ucd/BidiBrackets.txt](ucd/BidiBrackets.txt). - **Mirrored characters** for rule L4 are read from [ucd/BidiMirroring.txt](ucd/BidiMirroring.txt). - Both files are copied unchanged from the [Unicode Character Database](https://www.unicode.org/Public/17.0.0/ucd/) (currently Unicode 17.0.0). To update them, replace them with newer versions. diff --git a/bidi.py b/bidi.py index 570e505..b661481 100644 --- a/bidi.py +++ b/bidi.py @@ -27,7 +27,7 @@ from dataclasses import dataclass # Formatting of the verbose-mode tables; not part of the algorithm itself. -from verbose_table import print_table, format_char_for_table +from verbose_table import print_table, print_isolating_run_sequences, format_char_for_table # Three lookup tables are read, at import time, from the Unicode Character # Database (UCD) files kept unchanged in the ucd/ folder (see ucd_data.py for how): @@ -639,13 +639,14 @@ def _apply_w7(types: list[str], sos: str) -> list[str]: return result -def apply_weak_rules(chars: list[CharacterInfo], paragraph_embedding_level: int, +def apply_weak_rules(chars: list[CharacterInfo], sequences: list[dict], verbose: bool = False) -> None: """W1-W7: Resolve weak bidi types per isolating run sequence. - Mutates chars[i].character_type in place. Returns None. - """ - sequences = get_isolating_run_sequences(chars, paragraph_embedding_level) + `sequences` are the isolating run sequences computed by X10 + (get_isolating_run_sequences). Mutates chars[i].character_type in place. + Returns None. + """ for seq in sequences: run_indices = seq['run_indices'] sos = seq['sos'] @@ -926,7 +927,7 @@ def _apply_n2(types: list[str], embedding_level: int) -> list[str]: return result -def apply_neutral_rules(chars: list[CharacterInfo], paragraph_embedding_level: int, +def apply_neutral_rules(chars: list[CharacterInfo], sequences: list[dict], verbose: bool = False) -> None: """N0-N2: Resolve neutral and isolate formatting characters per isolating run sequence. @@ -936,12 +937,10 @@ def apply_neutral_rules(chars: list[CharacterInfo], paragraph_embedding_level: i takes that direction. N2: Any remaining NI characters take the embedding direction. - `paragraph_embedding_level` is used only to compute the isolating run sequences - (sos/eos context types and embedding levels). Mutates chars[i].character_type - in place. Returns None. + `sequences` are the isolating run sequences computed by X10 + (get_isolating_run_sequences). Mutates chars[i].character_type in place. + Returns None. """ - sequences = get_isolating_run_sequences(chars, paragraph_embedding_level) - for seq in sequences: run_indices = seq['run_indices'] sos = seq['sos'] @@ -1019,6 +1018,12 @@ def apply_implicit_rules(chars: list[CharacterInfo], verbose: bool = False) -> N I1: For characters at an even (L) level — R goes up one, AN and EN go up two. I2: For characters at an odd (R) level — L, EN, and AN go up one. + UAX #9 applies these rules to each isolating run sequence, like W and N. + Unlike W and N, though, I1 and I2 look only at each character's own type + and level (no neighbours, no sos/eos), and every character belongs to + exactly one sequence. So they are applied here to the whole paragraph at + once, which gives the same levels. + Precondition: weak and neutral rules must have resolved all character types to L, R, EN, AN, or BN before this function is called. BN characters are skipped and their levels are left unchanged. Mutates chars[i].embedding_level in place. @@ -1259,13 +1264,27 @@ def apply_bidi_algorithm( # Phase X: Explicit embedding levels apply_explicit_levels(chars, paragraph_level, verbose=verbose) + # X10: Split the paragraph into isolating run sequences, each with its + # sos and eos types. The sequences are computed once, here, and phases + # W and N then work on each sequence separately. + # + # UAX #9 takes each sequence through W1-W7, N0-N2 and I1-I2 before moving + # to the next sequence. Here, every sequence goes through phase W, then + # every sequence through phase N, then phase I. The result is the same, + # because the rules for one sequence look only at the characters in that + # sequence (and at its sos/eos), never at the other sequences. + sequences = get_isolating_run_sequences(chars, paragraph_level) + if verbose: + print_isolating_run_sequences(sequences) + # Phase W: Weak types - apply_weak_rules(chars, paragraph_level, verbose=verbose) + apply_weak_rules(chars, sequences, verbose=verbose) # Phase N: Neutral types - apply_neutral_rules(chars, paragraph_level, verbose=verbose) + apply_neutral_rules(chars, sequences, verbose=verbose) - # Phase I: Implicit levels + # Phase I: Implicit levels (applied to the whole paragraph at once; see + # apply_implicit_rules for why that matches applying them per sequence) apply_implicit_rules(chars, verbose=verbose) # Phase L: Reordering diff --git a/demo.py b/demo.py index 28615ef..7d9b1b0 100644 --- a/demo.py +++ b/demo.py @@ -70,8 +70,9 @@ ( "הוא אמר: ״[LRI]Car is מכונית in Hebrew[PDI]״.[RLM]", "LRI/PDI isolate", - "The X1-X8 (levels) table puts the text between LRI and PDI at level 2; it forms its own " - "isolating run sequence, separate from the Hebrew sentence around it (level 1).", + "The X1-X8 (levels) table puts the text between LRI and PDI at level 2. The X10 list then " + "shows it as its own isolating run sequence (characters 11-33), while the Hebrew sentence " + "around it forms one sequence at level 1 (characters 0-10 and 34-37), joined across the isolate.", ), ( "Hello שלום (עולם)", diff --git a/verbose_table.py b/verbose_table.py index 012b2ba..00ec93c 100644 --- a/verbose_table.py +++ b/verbose_table.py @@ -62,6 +62,47 @@ def center_in_column(text: str, column_width: int) -> str: return ' ' * left_padding + text + ' ' * right_padding +def format_index_ranges(indices: list[int]) -> str: + """ + Return a sorted list of character indices as ranges, e.g. [0, 1, 2, 7, 8] + becomes "0-2, 7-8" and [4] becomes "4". + """ + ranges = [] + start = indices[0] + previous = indices[0] + for index in indices[1:]: + if index == previous + 1: + previous = index + continue + ranges.append((start, previous)) + start = index + previous = index + ranges.append((start, previous)) + + parts = [] + for first, last in ranges: + if first == last: + parts.append(str(first)) + else: + parts.append(f"{first}-{last}") + return ", ".join(parts) + + +def print_isolating_run_sequences(sequences: list[dict]) -> None: + """ + Print the isolating run sequences found by rule X10, one line each: + the sequence's level, the indices of its characters, and its sos/eos. + + sequences is the list returned by bidi.get_isolating_run_sequences. + """ + print("=== X10: Isolating Run Sequences ===") + for seq in sequences: + indices = format_index_ranges(seq['run_indices']) + print(f"IRS level={seq['embedding_level']}: characters {indices}" + f" | sos={seq['sos']}, eos={seq['eos']}") + print() + + def print_table(rule_name: str, chars: list, types_before: list[str], types_after: list[str], irs_label: str = '') -> None: From e6fc1758c9322f8b9d86733b35a1bfbcaa171c21 Mon Sep 17 00:00:00 2001 From: isgav <51133755+isaranga@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:00:57 +0200 Subject: [PATCH 2/3] Leave characters removed by X9 out of the isolating run sequences get_isolating_run_sequences now builds level runs only from the characters that X9 did not remove, and skips removed characters when it computes sos and eos. Before, each BN took the level of the character before it, so a leading LRE got the paragraph level and formed a one-character sequence of its own (example 6). The sequences now match the reference implementation's trace. Verbose mode lists the removed characters after the X10 sequences. Results are unchanged: both conformance suites pass in full. --- CLAUDE.md | 4 +- README.md | 4 +- bidi.py | 127 ++++++++++++++++++++++------------------------- demo.py | 4 +- verbose_table.py | 14 +++++- 5 files changed, 78 insertions(+), 75 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index bba8414..f094953 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -75,7 +75,7 @@ Rule P1 is `split_into_paragraphs`, which works on the raw string and runs befor | I | `apply_implicit_rules` | I1–I2 | | L | `apply_reorder_rules` | L1–L4 | -Phases W and N operate on **isolating run sequences** (BD13), computed by `get_isolating_run_sequences`. Each IRS chains contiguous level runs that are linked by isolate initiators (LRI/RLI/FSI) to their matching PDI, and carries `sos`/`eos` context types. `apply_bidi_algorithm` computes the list once (rule X10), right after phase X, and passes it to `apply_weak_rules` and `apply_neutral_rules`. The spec takes each IRS through W, N and I in turn, but the code runs each phase across all sequences. This is equivalent because no rule reads outside its own IRS (except through `sos`/`eos`). Phase I is not given the sequences: I1/I2 depend only on each character's own type and level, so `apply_implicit_rules` runs over the whole paragraph. Comments in `apply_bidi_algorithm` and `apply_implicit_rules` explain both points. +Phases W and N operate on **isolating run sequences** (BD13), computed by `get_isolating_run_sequences`. Each IRS chains contiguous level runs that are linked by isolate initiators (LRI/RLI/FSI) to their matching PDI, and carries `sos`/`eos` context types. Characters removed by X9 (`character_type` BN) stay in `chars` but are left out of every level run and IRS: the characters on either side of them count as adjacent, and `sos`/`eos` skip them when looking at neighbouring levels. This matches the reference implementation's trace (removed characters have level `x` and belong to no run). As a result, the BN-skipping code in the W and N helpers is never reached. `apply_bidi_algorithm` computes the list once (rule X10), right after phase X, and passes it to `apply_weak_rules` and `apply_neutral_rules`. The spec takes each IRS through W, N and I in turn, but the code runs each phase across all sequences. This is equivalent because no rule reads outside its own IRS (except through `sos`/`eos`). Phase I is not given the sequences: I1/I2 depend only on each character's own type and level, so `apply_implicit_rules` runs over the whole paragraph. Comments in `apply_bidi_algorithm` and `apply_implicit_rules` explain both points. The W and N phases each delegate to private per-rule helpers (`_apply_w1`…`_apply_w7`, `_apply_n0`, `_apply_n1`, `_apply_n2`). The L phase similarly delegates to `_apply_l1`…`_apply_l4`. @@ -83,7 +83,7 @@ Bracket pair detection for N0 is handled by `_find_bracket_pairs`, using `OPEN_B ### Verbose mode -Every phase function (and `_apply_i1`/`_apply_i2`) accepts `verbose=True`; the per-rule W, N and L helpers do not, and their phase function prints on their behalf. When enabled, `print_table` (in `verbose_table.py`, together with the helpers below) prints a before/after table for each rule application, with rows for character index, code point, the character itself, the type (or level, or position) before and after the rule, and embedding level. `print_table` decides "(no changes)" by comparing only the Before/After rows, so Phase X prints two tables: "X1-X8 (levels)" (Before is the paragraph level from X1) and "X1-X9 (types)" (overrides, FSI resolution, X9's BN). Without the levels table, an isolate or embedding with no override would show as "(no changes)". After phase X, `apply_bidi_algorithm` calls `print_isolating_run_sequences` (also in `verbose_table.py`), which prints the X10 sequences one line each: level, character indices as ranges, `sos`/`eos`. Columns are always in logical order, including the L2 and L4 tables, where Before/After give each character's position before and after reordering. +Every phase function (and `_apply_i1`/`_apply_i2`) accepts `verbose=True`; the per-rule W, N and L helpers do not, and their phase function prints on their behalf. When enabled, `print_table` (in `verbose_table.py`, together with the helpers below) prints a before/after table for each rule application, with rows for character index, code point, the character itself, the type (or level, or position) before and after the rule, and embedding level. `print_table` decides "(no changes)" by comparing only the Before/After rows, so Phase X prints two tables: "X1-X8 (levels)" (Before is the paragraph level from X1) and "X1-X9 (types)" (overrides, FSI resolution, X9's BN). Without the levels table, an isolate or embedding with no override would show as "(no changes)". After phase X, `apply_bidi_algorithm` calls `print_isolating_run_sequences` (also in `verbose_table.py`), which prints the X10 sequences one line each (level, character indices as ranges, `sos`/`eos`), then the indices of the characters removed by X9. Columns are always in logical order, including the L2 and L4 tables, where Before/After give each character's position before and after reordering. Characters in table cells go through `format_char_for_table`: controls and whitespace are left blank, combining marks are shown on a dotted circle, and each R/AL character is followed by an invisible LEFT-TO-RIGHT MARK so that bidi-aware viewers (Markdown previews, GitHub) don't reverse runs of the row. Cells are sized and centered by `display_width`/`center_in_column`, not `len()`, because those marks take no column on screen. The tracing example in README.md is copied from real output (LRMs included); update it whenever the table format changes. diff --git a/README.md b/README.md index a719818..c93b737 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ for paragraph in split_into_paragraphs("שלום\nHello"): ## Tracing the algorithm -Pass `verbose=True` to see every rule as it runs. Rules that change nothing print a single line; rules that do change something print a table showing each character's index, its code point, the character itself, its type (or level) before and after the rule, and its embedding level. Changed cells are highlighted in the terminal. Phase X prints two tables, one for the levels it assigns and one for the types it changes, so that an embedding or isolate shows up even when no type changes. Rule X10 then lists the isolating run sequences, one line each, with their level, characters and `sos`/`eos`. +Pass `verbose=True` to see every rule as it runs. Rules that change nothing print a single line; rules that do change something print a table showing each character's index, its code point, the character itself, its type (or level) before and after the rule, and its embedding level. Changed cells are highlighted in the terminal. Phase X prints two tables, one for the levels it assigns and one for the types it changes, so that an embedding or isolate shows up even when no type changes. Rule X10 then lists the isolating run sequences, one line each, with their level, characters and `sos`/`eos`, followed by the characters removed by X9, which belong to no sequence. ```python apply_bidi_algorithm("שלום 123 Hi", verbose=True) @@ -116,7 +116,7 @@ Rule P1 comes first: `split_into_paragraphs` cuts the text into paragraphs after Some things to know when reading the code: - **`CharacterInfo`** is the record passed through every phase. `original_type` is the character's Unicode bidi class and never changes; `character_type` is a working copy that the rules update. -- **Isolating run sequences** (definition BD13) are what phases W and N work on. Rule X10 finds them: `get_isolating_run_sequences` builds them by linking runs of the same level across an isolate (LRI/RLI/FSI … PDI), and attaches the `sos`/`eos` types at each end. `apply_bidi_algorithm` computes them once and passes them to both phases; verbose mode lists them. UAX #9 also applies rules I1–I2 per sequence, but they look only at each character's own type and level, so `apply_implicit_rules` applies them to the whole paragraph at once, with the same result. +- **Isolating run sequences** (definition BD13) are what phases W and N work on. Rule X10 finds them: `get_isolating_run_sequences` builds them by linking runs of the same level across an isolate (LRI/RLI/FSI … PDI), and attaches the `sos`/`eos` types at each end. `apply_bidi_algorithm` computes them once and passes them to both phases; verbose mode lists them. Characters removed by rule X9 (embedding controls such as LRE and PDF, and type BN) are kept in the text, but they belong to no sequence, so the W and N rules never see them, just as if they had been removed. UAX #9 also applies rules I1–I2 per sequence, but they look only at each character's own type and level, so `apply_implicit_rules` applies them to the whole paragraph at once, with the same result. - UAX #9 takes each sequence through W, N and I before moving to the next one. The code instead runs phase W on every sequence, then phase N, then phase I. Each sequence's rules look only at that sequence's characters (and its `sos`/`eos`), so the order makes no difference. - **Bracket pairs** for rule N0 are found by `_find_bracket_pairs`, using pairs read from [ucd/BidiBrackets.txt](ucd/BidiBrackets.txt). - **Mirrored characters** for rule L4 are read from [ucd/BidiMirroring.txt](ucd/BidiMirroring.txt). diff --git a/bidi.py b/bidi.py index b661481..c273b9d 100644 --- a/bidi.py +++ b/bidi.py @@ -71,53 +71,56 @@ class CharacterInfo: def get_isolating_run_sequences(chars: list[CharacterInfo], paragraph_level: int) -> list[dict]: """ - Compute isolating run sequences per UAX#9 BD13. + X10: Compute the isolating run sequences (definition BD13). Returns list of dicts with keys: run_indices, embedding_level, sos, eos - BN characters (removed by X9) are transparent to level-run formation: each - BN inherits the effective level of the nearest preceding non-BN character - (falling back to paragraph_level at the start of the string). All - level-run boundaries and sos/eos values are computed from this effective - level array rather than from raw embedding levels. + Characters removed by rule X9 (type BN here) belong to no level run and + to no sequence, as if they were not in the text: the characters on either + side of them are adjacent. The W and N rules therefore never see them. sos and eos are computed per UAX #9 X10: each is 'R' or 'L' according to the higher of the two adjacent levels (the IRS level and the level of the neighbouring character outside the sequence, or paragraph_level at the - paragraph boundaries). + paragraph boundaries). Removed characters are skipped when looking for + the neighbouring character. """ - levels = [ci.embedding_level for ci in chars] n = len(chars) - # UAX #9 X9 removes BN characters before level runs are formed, so BN - # characters must not create run boundaries of their own. We build an - # effective_levels array where every BN character inherits the embedding - # level of the nearest preceding non-BN character (falling back to the - # paragraph level at the start of the string). This array is used for - # all level-run and sos/eos computations in place of the raw levels. - effective_levels = list(levels) - last_non_bn_level = paragraph_level + # The characters that X9 did not remove, in logical order. + remaining = [] for i in range(n): - if chars[i].character_type == 'BN': - effective_levels[i] = last_non_bn_level - else: - last_non_bn_level = levels[i] + if chars[i].character_type != 'BN': + remaining.append(i) - # Get level runs: contiguous runs of same effective level + # BD7: level runs are maximal runs of remaining characters with the same + # level. A removed character between two of them does not split a run. runs = [] - i = 0 - while i < n: - level = effective_levels[i] - j = i + 1 - while j < n and effective_levels[j] == level: + current_run = [] + for i in remaining: + if current_run and chars[i].embedding_level != chars[current_run[-1]].embedding_level: + runs.append(current_run) + current_run = [] + current_run.append(i) + if current_run: + runs.append(current_run) + + def level_before(index): + """Level of the nearest remaining character before index, or None.""" + j = index - 1 + while j >= 0 and chars[j].character_type == 'BN': + j -= 1 + if j < 0: + return None + return chars[j].embedding_level + + def level_after(index): + """Level of the nearest remaining character after index, or None.""" + j = index + 1 + while j < n and chars[j].character_type == 'BN': j += 1 - runs.append(list(range(i, j))) - i = j - - def last_non_bn_type(run_indices): - for idx in reversed(run_indices): - if chars[idx].character_type != 'BN': - return chars[idx].character_type - return None + if j >= n: + return None + return chars[j].embedding_level # Build isolating run sequences by chaining used = [False] * len(runs) @@ -132,16 +135,10 @@ def last_non_bn_type(run_indices): current_run = run while True: - last_type = last_non_bn_type(current_run) - if last_type not in ISOLATE_INITIATOR_TYPES: - break - # Find position of last non-BN char in current_run - initiator_pos = None - for idx in reversed(current_run): - if chars[idx].character_type != 'BN': - initiator_pos = idx - break - if initiator_pos is None: + # A run that ends with an isolate initiator continues at the + # run that starts with its matching PDI. + initiator_pos = current_run[-1] + if chars[initiator_pos].character_type not in ISOLATE_INITIATOR_TYPES: break # Find matching PDI by counting isolate initiators/terminators @@ -179,32 +176,27 @@ def last_non_bn_type(run_indices): for r in irs_runs: all_indices.extend(r) - # Compute embedding level = effective level of first run - irs_level = effective_levels[irs_runs[0][0]] - - # X10: Compute sos + # All runs of a sequence have the same level start_idx = irs_runs[0][0] - if start_idx == 0: + irs_level = chars[start_idx].embedding_level + + # X10: Compute sos from the remaining character before the sequence + prev_level = level_before(start_idx) + if prev_level is None: prev_level = paragraph_level - else: - prev_level = effective_levels[start_idx - 1] sos_level = max(prev_level, irs_level) sos = 'R' if (sos_level % 2) == 1 else 'L' - # X10: Compute eos - last_run = irs_runs[-1] - end_idx = last_run[-1] - last_run_level = effective_levels[last_run[0]] - last_type = last_non_bn_type(last_run) - # Per X10: use paragraph_level when at end of paragraph, or when the last - # character is an unmatched isolate initiator (a matched one would have - # caused the loop above to chain another run, so any isolate initiator - # still at the tail of irs_runs is necessarily unmatched). - if end_idx == n - 1 or last_type in ISOLATE_INITIATOR_TYPES: + # X10: Compute eos from the remaining character after the sequence. + # Per X10, use paragraph_level at the end of the paragraph, or when + # the last character is an unmatched isolate initiator (a matched one + # would have caused the loop above to chain another run, so any + # isolate initiator still at the end of the sequence is unmatched). + end_idx = irs_runs[-1][-1] + next_level = level_after(end_idx) + if next_level is None or chars[end_idx].character_type in ISOLATE_INITIATOR_TYPES: next_level = paragraph_level - else: - next_level = effective_levels[end_idx + 1] - eos_level = max(next_level, last_run_level) + eos_level = max(next_level, irs_level) eos = 'R' if (eos_level % 2) == 1 else 'L' sequences.append({ @@ -469,9 +461,8 @@ def apply_explicit_levels(chars: list[CharacterInfo], paragraph_embedding_level: overflow_embedding_count -= 1 elif not is_isolate and len(stack) >= 2: stack.pop() - # Assign the level of the new stack top (after any pop), so that - # PDF's BN does not create a spurious high-level run that would - # split the isolating run sequence around it. + # Assign the level of the new stack top (after any pop). X9 + # removes the PDF, so this level takes no part in the later rules. ci.embedding_level = stack[-1][0] # X8: paragraph separator resets to paragraph embedding level @@ -1275,7 +1266,7 @@ def apply_bidi_algorithm( # sequence (and at its sos/eos), never at the other sequences. sequences = get_isolating_run_sequences(chars, paragraph_level) if verbose: - print_isolating_run_sequences(sequences) + print_isolating_run_sequences(sequences, chars) # Phase W: Weak types apply_weak_rules(chars, sequences, verbose=verbose) diff --git a/demo.py b/demo.py index 7d9b1b0..788bd1e 100644 --- a/demo.py +++ b/demo.py @@ -65,7 +65,9 @@ "[LRE]Hello שלום[PDF]", "LRE/PDF explicit embedding", "The X1-X8 (levels) table puts the text between LRE and PDF at level 2, so the Hebrew word " - "ends up at level 3 after I1; the X1-X9 (types) table shows X9 turning LRE and PDF into BN.", + "ends up at level 3 after I1; the X1-X9 (types) table shows X9 turning LRE and PDF into BN. " + "X9 removes them, so X10 leaves them out of every isolating run sequence, and the W and N " + "tables show only characters 1-10.", ), ( "הוא אמר: ״[LRI]Car is מכונית in Hebrew[PDI]״.[RLM]", diff --git a/verbose_table.py b/verbose_table.py index 00ec93c..d334946 100644 --- a/verbose_table.py +++ b/verbose_table.py @@ -88,18 +88,28 @@ def format_index_ranges(indices: list[int]) -> str: return ", ".join(parts) -def print_isolating_run_sequences(sequences: list[dict]) -> None: +def print_isolating_run_sequences(sequences: list[dict], chars: list) -> None: """ Print the isolating run sequences found by rule X10, one line each: the sequence's level, the indices of its characters, and its sos/eos. + Then list the characters removed by rule X9, which belong to no sequence. - sequences is the list returned by bidi.get_isolating_run_sequences. + sequences is the list returned by bidi.get_isolating_run_sequences; + chars is the list of bidi.CharacterInfo objects (only character_type is + read, to find the removed characters, whose type is BN). """ print("=== X10: Isolating Run Sequences ===") for seq in sequences: indices = format_index_ranges(seq['run_indices']) print(f"IRS level={seq['embedding_level']}: characters {indices}" f" | sos={seq['sos']}, eos={seq['eos']}") + + removed = [] + for ci in chars: + if ci.character_type == 'BN': + removed.append(ci.index) + if removed: + print(f"Removed by X9 (in no sequence): characters {format_index_ranges(removed)}") print() From ac280ecfdf5920f43ca2fbfefd8b9bcbbfaa6b3d Mon Sep 17 00:00:00 2001 From: isgav <51133755+isaranga@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:12:51 +0200 Subject: [PATCH 3/3] Remove BN handling from the W and N rules Since X10 leaves the characters removed by X9 out of every isolating run sequence, the W and N helpers never see a BN. Remove the code that skipped over BN: the _get_prev_non_bn/_get_next_non_bn and _get_prev_non_et_bn/_get_next_non_et_bn helpers, and the BN branches in W1, W4, N0 and N1. W5 is rewritten to find each sequence of ETs and look at its two neighbours, as the rule is worded. Both conformance suites still pass in full. --- CLAUDE.md | 2 +- bidi.py | 136 +++++++++++++++++------------------------------------- 2 files changed, 44 insertions(+), 94 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index f094953..8c4597f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -75,7 +75,7 @@ Rule P1 is `split_into_paragraphs`, which works on the raw string and runs befor | I | `apply_implicit_rules` | I1–I2 | | L | `apply_reorder_rules` | L1–L4 | -Phases W and N operate on **isolating run sequences** (BD13), computed by `get_isolating_run_sequences`. Each IRS chains contiguous level runs that are linked by isolate initiators (LRI/RLI/FSI) to their matching PDI, and carries `sos`/`eos` context types. Characters removed by X9 (`character_type` BN) stay in `chars` but are left out of every level run and IRS: the characters on either side of them count as adjacent, and `sos`/`eos` skip them when looking at neighbouring levels. This matches the reference implementation's trace (removed characters have level `x` and belong to no run). As a result, the BN-skipping code in the W and N helpers is never reached. `apply_bidi_algorithm` computes the list once (rule X10), right after phase X, and passes it to `apply_weak_rules` and `apply_neutral_rules`. The spec takes each IRS through W, N and I in turn, but the code runs each phase across all sequences. This is equivalent because no rule reads outside its own IRS (except through `sos`/`eos`). Phase I is not given the sequences: I1/I2 depend only on each character's own type and level, so `apply_implicit_rules` runs over the whole paragraph. Comments in `apply_bidi_algorithm` and `apply_implicit_rules` explain both points. +Phases W and N operate on **isolating run sequences** (BD13), computed by `get_isolating_run_sequences`. Each IRS chains contiguous level runs that are linked by isolate initiators (LRI/RLI/FSI) to their matching PDI, and carries `sos`/`eos` context types. Characters removed by X9 (`character_type` BN) stay in `chars` but are left out of every level run and IRS: the characters on either side of them count as adjacent, and `sos`/`eos` skip them when looking at neighbouring levels. This matches the reference implementation's trace (removed characters have level `x` and belong to no run). As a result, the W and N helpers contain no BN handling; only phase I (which runs over the whole paragraph and skips BN) and the L rules (which use `original_type`) still meet removed characters. `apply_bidi_algorithm` computes the list once (rule X10), right after phase X, and passes it to `apply_weak_rules` and `apply_neutral_rules`. The spec takes each IRS through W, N and I in turn, but the code runs each phase across all sequences. This is equivalent because no rule reads outside its own IRS (except through `sos`/`eos`). Phase I is not given the sequences: I1/I2 depend only on each character's own type and level, so `apply_implicit_rules` runs over the whole paragraph. Comments in `apply_bidi_algorithm` and `apply_implicit_rules` explain both points. The W and N phases each delegate to private per-rule helpers (`_apply_w1`…`_apply_w7`, `_apply_n0`, `_apply_n1`, `_apply_n2`). The L phase similarly delegates to `_apply_l1`…`_apply_l4`. diff --git a/bidi.py b/bidi.py index c273b9d..debfbd0 100644 --- a/bidi.py +++ b/bidi.py @@ -498,20 +498,18 @@ def apply_explicit_levels(chars: list[CharacterInfo], paragraph_embedding_level: # ============================================================ def _apply_w1(types: list[str], sos: str) -> list[str]: - """W1: NSM takes type of preceding character (or sos), BN is transparent. + """W1: NSM takes type of preceding character (or sos). Exception: if the preceding character is an isolate initiator or PDI, NSM -> ON. """ result = list(types) prev_type = sos for i in range(len(types)): - t = result[i] - if t == 'NSM': + if result[i] == 'NSM': if prev_type in ISOLATE_INITIATOR_TYPES or prev_type == 'PDI': result[i] = 'ON' else: result[i] = prev_type - if t != 'BN': - prev_type = result[i] + prev_type = result[i] return result @@ -527,8 +525,7 @@ def _apply_w2(types: list[str], sos: str) -> list[str]: last_strong = t elif t == 'EN' and last_strong == 'AL': result[i] = 'AN' - # Non-strong types (including BN, neutrals, and weak types) are transparent: - # they do not update last_strong + # Non-strong types (neutrals and weak types) do not update last_strong return result @@ -537,32 +534,14 @@ def _apply_w3(types: list[str]) -> list[str]: return ['R' if t == 'AL' else t for t in types] -def _get_prev_non_bn(types: list[str], index: int) -> str | None: - """Return the nearest type before *index* that is not BN, or None.""" - j = index - 1 - while j >= 0 and types[j] == 'BN': - j -= 1 - return types[j] if j >= 0 else None - - -def _get_next_non_bn(types: list[str], index: int) -> str | None: - """Return the nearest type after *index* that is not BN, or None.""" - k = index + 1 - while k < len(types) and types[k] == 'BN': - k += 1 - return types[k] if k < len(types) else None - - def _apply_w4(types: list[str]) -> list[str]: - """W4: Single ES between EN-EN -> EN; single CS between EN-EN or AN-AN -> that type. - BN characters are transparent (UAX#9 section 5.2) and are skipped when - searching for the neighboring type on either side of the separator.""" + """W4: Single ES between EN-EN -> EN; single CS between EN-EN or AN-AN -> that type.""" result = list(types) for i in range(1, len(result) - 1): if result[i] not in ('ES', 'CS'): continue - prev_type = _get_prev_non_bn(result, i) - next_type = _get_next_non_bn(result, i) + prev_type = result[i - 1] + next_type = result[i + 1] if result[i] == 'ES': if prev_type == 'EN' and next_type == 'EN': result[i] = 'EN' @@ -574,37 +553,25 @@ def _apply_w4(types: list[str]) -> list[str]: return result -def _get_prev_non_et_bn(types: list[str], index: int) -> str | None: - """Return the nearest type before *index* that is not ET or BN, or None.""" - j = index - 1 - while j >= 0 and types[j] in ('ET', 'BN'): - j -= 1 - return types[j] if j >= 0 else None - - -def _get_next_non_et_bn(types: list[str], index: int) -> str | None: - """Return the nearest type after *index* that is not ET or BN, or None.""" - k = index + 1 - while k < len(types) and types[k] in ('ET', 'BN'): - k += 1 - return types[k] if k < len(types) else None - - def _apply_w5(types: list[str]) -> list[str]: - """W5: ET adjacent to EN -> EN (sequences of ET adjacent to EN become EN). - BN characters are transparent (UAX#9 section 5.2), so the scans skip both - ET and BN when searching for a bordering EN.""" + """W5: A sequence of ETs adjacent to an EN (before or after it) -> all EN.""" result = list(types) - # Forward pass: ET following EN - for i in range(len(result)): - if result[i] == 'ET': - if _get_prev_non_et_bn(result, i) == 'EN': - result[i] = 'EN' - # Backward pass: ET preceding EN - for i in range(len(result) - 1, -1, -1): - if result[i] == 'ET': - if _get_next_non_et_bn(result, i) == 'EN': - result[i] = 'EN' + n = len(result) + i = 0 + while i < n: + if result[i] != 'ET': + i += 1 + continue + # result[i:j] is a maximal sequence of ETs + j = i + while j < n and result[j] == 'ET': + j += 1 + en_before = i > 0 and result[i - 1] == 'EN' + en_after = j < n and result[j] == 'EN' + if en_before or en_after: + for k in range(i, j): + result[k] = 'EN' + i = j return result @@ -625,8 +592,7 @@ def _apply_w7(types: list[str], sos: str) -> list[str]: last_strong = t elif t == 'EN' and last_strong == 'L': result[i] = 'L' - # Non-strong types (including BN, neutrals, and weak types) are transparent: - # they do not update last_strong + # Non-strong types (neutrals and weak types) do not update last_strong return result @@ -755,8 +721,8 @@ def _apply_n0(chars: list[CharacterInfo], run_indices: list[int], direction is found, look at the last strong type before the open bracket (falling back to sos) and assign that direction instead. 2. If no strong type is found inside, leave both brackets as ON. - 3. Set any NSMs immediately following each bracket (skipping BN/X9 - characters) to the same direction as the bracket. + 3. Set any NSMs immediately following each bracket to the same + direction as the bracket. Mutates chars[...].character_type in place. Returns None. @@ -806,25 +772,19 @@ def _apply_n0(chars: list[CharacterInfo], run_indices: list[int], chars[open_idx].character_type = direction chars[close_idx].character_type = direction - # Set NSMs after open bracket (skip over BN/X9 characters) + # Set NSMs after open bracket for pos in range(open_ri + 1, len(run_indices)): idx = run_indices[pos] - if chars[idx].original_type == 'NSM': - chars[idx].character_type = direction - elif chars[idx].original_type in X9_REMOVE_TYPES: - continue - else: + if chars[idx].original_type != 'NSM': break + chars[idx].character_type = direction - # Set NSMs after close bracket (skip over BN/X9 characters) + # Set NSMs after close bracket for pos in range(close_ri + 1, len(run_indices)): idx = run_indices[pos] - if chars[idx].original_type == 'NSM': - chars[idx].character_type = direction - elif chars[idx].original_type in X9_REMOVE_TYPES: - continue - else: + if chars[idx].original_type != 'NSM': break + chars[idx].character_type = direction def _apply_n1(types: list[str], sos: str, eos: str) -> list[str]: @@ -837,10 +797,11 @@ def _apply_n1(types: list[str], sos: str, eos: str) -> list[str]: EN and AN are treated as R (strong right) for adjacency purposes. sos and eos supply the strong context at the edges of the sequence. - BN characters are transparent: they do not break NI runs, are skipped - when searching for adjacent strong types, and their type is not changed. `types` is not modified; a new list with resolved types is returned. + + Precondition: the W rules have run, so every type that is not NI is + L, R, EN or AN. """ result = list(types) n = len(result) @@ -854,39 +815,30 @@ def strong_equiv(t): return 'L' return None - # BN is treated as if not present (UAX#9 section 5.2): it does not start - # or end a neutral run, is skipped when looking for adjacent strong types, - # and its type is left unchanged during resolution. i = 0 while i < n: if result[i] in NEUTRAL_SET: - # Find extent of neutral run; BN is transparent, so extend through it + # result[i:j] is a maximal run of NI characters j = i - while j < n and (result[j] in NEUTRAL_SET or result[j] == 'BN'): + while j < n and result[j] in NEUTRAL_SET: j += 1 - # result[i:j] is the NI run (plus any interspersed BN) - # Determine strong type before; skip backward over BN + # Strong type before the run (sos at the start of the sequence) if i == 0: before = sos else: - k = i - 1 - while k >= 0 and result[k] == 'BN': - k -= 1 - before = (strong_equiv(result[k]) if k >= 0 else None) or sos + before = strong_equiv(result[i - 1]) - # Determine strong type after (scan already moved past BN) + # Strong type after the run (eos at the end of the sequence) if j == n: after = eos else: after = strong_equiv(result[j]) - # N1: both sides agree -> resolve NI characters to that direction; - # leave BN type unchanged + # N1: both sides agree -> resolve the NI characters to that direction if before == after: for k in range(i, j): - if result[k] != 'BN': - result[k] = before + result[k] = before i = j else: @@ -902,8 +854,6 @@ def _apply_n2(types: list[str], embedding_level: int) -> list[str]: Any remaining NI characters (those not resolved by N1) take the embedding direction. - BN characters are transparent and are left unchanged. - `types` is not modified; a new list with resolved types is returned. """ result = list(types)