diff --git a/CLAUDE.md b/CLAUDE.md index 6387bf0..fdc4f3e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -77,7 +77,7 @@ Rule P1 is `split_into_paragraphs`, which works on the raw string and runs befor 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`. `get_isolating_run_sequences` (X10) keeps only the BD13 chaining loop and delegates to `_find_level_runs` (BD7), `_find_matching_pdi` (BD9) and `_compute_sos_eos`. +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`. `apply_explicit_levels` is the exception: X2–X8 share the directional status stack (a list of `DirectionalStatus` named tuples: `level`, `override`, `isolate`) and three counters, so they stay as one loop with one labelled branch per rule, in spec order. Only `_apply_override` (the override step repeated in X5a–X6a) and `_apply_x9` (a separate pass after the loop) are pulled out. `get_isolating_run_sequences` (X10) keeps only the BD13 chaining loop and delegates to `_find_level_runs` (BD7), `_find_matching_pdi` (BD9) and `_compute_sos_eos`. Bracket pair detection for N0 is handled by `_find_bracket_pairs`, using `OPEN_BRACKET_TO_CLOSE` / `CLOSE_BRACKET_TO_OPEN` tables. L4 mirroring uses `BIDI_MIRROR_TABLE`. All three tables are imported from `ucd_data.py`, which builds them at import time: `load_bracket_pairs` reads `ucd/BidiBrackets.txt` and `load_mirror_pairs` reads `ucd/BidiMirroring.txt`, both through `read_ucd_file`. A comment above the import in `bidi.py` describes the tables and the rules that use them. diff --git a/bidi.py b/bidi.py index c541bc5..0ba1537 100644 --- a/bidi.py +++ b/bidi.py @@ -25,6 +25,7 @@ import unicodedata from dataclasses import dataclass +from typing import NamedTuple # Formatting of the verbose-mode tables; not part of the algorithm itself. from verbose_table import print_table, print_isolating_run_sequences, format_char_for_table @@ -49,6 +50,13 @@ class CharacterInfo: embedding_level: int # assigned in X phase, adjusted in I phase +class DirectionalStatus(NamedTuple): + """One entry of the directional status stack used by rules X1-X8.""" + level: int # embedding level + override: str # directional override status: 'neutral', 'left-to-right' or 'right-to-left' + isolate: bool # directional isolate status: True if pushed by an isolate initiator + + # ============================================================ # SECTION: Constants # ============================================================ @@ -175,6 +183,28 @@ def _resolve_fsi_direction(chars: list[CharacterInfo], fsi_index: int) -> str: return 'LRI' # default +def _apply_override(ci: CharacterInfo, override: str) -> None: + """ + X5a-X6a: If the directional override status is not neutral, reset the + character's type to L (left-to-right override) or R (right-to-left override). + """ + if override == 'left-to-right': + ci.character_type = 'L' + elif override == 'right-to-left': + ci.character_type = 'R' + + +def _apply_x9(chars: list[CharacterInfo]) -> None: + """ + X9: Remove the explicit embedding and override characters (RLE, LRE, RLO, + LRO, PDF) and BN. They stay in chars, but their character_type becomes + 'BN', and the later rules leave them out. + """ + for ci in chars: + if ci.original_type in X9_REMOVE_TYPES: + ci.character_type = 'BN' + + def apply_explicit_levels(chars: list[CharacterInfo], paragraph_embedding_level: int, verbose: bool = False) -> None: """ @@ -188,7 +218,7 @@ def apply_explicit_levels(chars: list[CharacterInfo], paragraph_embedding_level: level from X1) and one for the types. """ # X1: Initialize - stack = [(paragraph_embedding_level, 'neutral', False)] + stack = [DirectionalStatus(level=paragraph_embedding_level, override='neutral', isolate=False)] overflow_isolate_count = 0 overflow_embedding_count = 0 valid_isolate_count = 0 @@ -201,14 +231,18 @@ def apply_explicit_levels(chars: list[CharacterInfo], paragraph_embedding_level: for ci in chars: t = ci.character_type - level, override, is_isolate = stack[-1] + current = stack[-1] + level = current.level # X2: RLE pushes a new right-to-left embedding level onto the stack if t == 'RLE': ci.embedding_level = level new_level = _least_greater_odd(level) - if new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0: - stack.append((new_level, 'neutral', False)) + # The spec's test, used by X2-X5c: the initiator "is valid" if the + # new level is at most MAX_DEPTH and both overflow counts are zero. + is_valid = new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0 + if is_valid: + stack.append(DirectionalStatus(level=new_level, override='neutral', isolate=False)) else: if overflow_isolate_count == 0: overflow_embedding_count += 1 @@ -217,8 +251,9 @@ def apply_explicit_levels(chars: list[CharacterInfo], paragraph_embedding_level: elif t == 'LRE': ci.embedding_level = level new_level = _least_greater_even(level) - if new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0: - stack.append((new_level, 'neutral', False)) + is_valid = new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0 + if is_valid: + stack.append(DirectionalStatus(level=new_level, override='neutral', isolate=False)) else: if overflow_isolate_count == 0: overflow_embedding_count += 1 @@ -227,8 +262,9 @@ def apply_explicit_levels(chars: list[CharacterInfo], paragraph_embedding_level: elif t == 'RLO': ci.embedding_level = level new_level = _least_greater_odd(level) - if new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0: - stack.append((new_level, 'right-to-left', False)) + is_valid = new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0 + if is_valid: + stack.append(DirectionalStatus(level=new_level, override='right-to-left', isolate=False)) else: if overflow_isolate_count == 0: overflow_embedding_count += 1 @@ -237,8 +273,9 @@ def apply_explicit_levels(chars: list[CharacterInfo], paragraph_embedding_level: elif t == 'LRO': ci.embedding_level = level new_level = _least_greater_even(level) - if new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0: - stack.append((new_level, 'left-to-right', False)) + is_valid = new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0 + if is_valid: + stack.append(DirectionalStatus(level=new_level, override='left-to-right', isolate=False)) else: if overflow_isolate_count == 0: overflow_embedding_count += 1 @@ -246,28 +283,24 @@ def apply_explicit_levels(chars: list[CharacterInfo], paragraph_embedding_level: # X5a: RLI pushes a right-to-left isolate entry onto the stack elif t == 'RLI': ci.embedding_level = level - if override == 'left-to-right': - ci.character_type = 'L' - elif override == 'right-to-left': - ci.character_type = 'R' + _apply_override(ci, current.override) new_level = _least_greater_odd(level) - if new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0: + is_valid = new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0 + if is_valid: valid_isolate_count += 1 - stack.append((new_level, 'neutral', True)) + stack.append(DirectionalStatus(level=new_level, override='neutral', isolate=True)) else: overflow_isolate_count += 1 # X5b: LRI pushes a left-to-right isolate entry onto the stack elif t == 'LRI': ci.embedding_level = level - if override == 'left-to-right': - ci.character_type = 'L' - elif override == 'right-to-left': - ci.character_type = 'R' + _apply_override(ci, current.override) new_level = _least_greater_even(level) - if new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0: + is_valid = new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0 + if is_valid: valid_isolate_count += 1 - stack.append((new_level, 'neutral', True)) + stack.append(DirectionalStatus(level=new_level, override='neutral', isolate=True)) else: overflow_isolate_count += 1 @@ -276,19 +309,17 @@ def apply_explicit_levels(chars: list[CharacterInfo], paragraph_embedding_level: direction = _resolve_fsi_direction(chars, ci.index) ci.character_type = direction ci.embedding_level = level - if override == 'left-to-right': - ci.character_type = 'L' - elif override == 'right-to-left': - ci.character_type = 'R' + _apply_override(ci, current.override) # Level is determined by the resolved direction, not by the # (possibly overridden) character_type above. if direction == 'RLI': new_level = _least_greater_odd(level) else: new_level = _least_greater_even(level) - if new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0: + is_valid = new_level <= MAX_DEPTH and overflow_isolate_count == 0 and overflow_embedding_count == 0 + if is_valid: valid_isolate_count += 1 - stack.append((new_level, 'neutral', True)) + stack.append(DirectionalStatus(level=new_level, override='neutral', isolate=True)) else: overflow_isolate_count += 1 @@ -298,16 +329,13 @@ def apply_explicit_levels(chars: list[CharacterInfo], paragraph_embedding_level: overflow_isolate_count -= 1 elif valid_isolate_count > 0: overflow_embedding_count = 0 - while not stack[-1][2]: # pop until isolate entry + while not stack[-1].isolate: # pop embeddings until the isolate entry stack.pop() - stack.pop() + stack.pop() # pop the isolate entry itself valid_isolate_count -= 1 - level, override, is_isolate = stack[-1] - ci.embedding_level = level - if override == 'left-to-right': - ci.character_type = 'L' - elif override == 'right-to-left': - ci.character_type = 'R' + # The PDI gets the level and override of the entry now on top. + ci.embedding_level = stack[-1].level + _apply_override(ci, stack[-1].override) # X7: PDF closes the matching embedding entry elif t == 'PDF': @@ -315,28 +343,26 @@ def apply_explicit_levels(chars: list[CharacterInfo], paragraph_embedding_level: pass elif overflow_embedding_count > 0: overflow_embedding_count -= 1 - elif not is_isolate and len(stack) >= 2: + elif not current.isolate and len(stack) >= 2: stack.pop() # 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] + ci.embedding_level = stack[-1].level # X8: paragraph separator resets to paragraph embedding level elif t == 'B': ci.embedding_level = paragraph_embedding_level - # X6: all other characters get the current level; apply override type if active + # X6: all other characters get the current level; apply override type if active. + # This rule covers every type not handled above, so it comes last, as the + # final else. The spec also excludes BN from X6, but BN characters land here + # too. That is harmless: X9 (below) resets their type to BN, and the later + # rules ignore removed characters. else: ci.embedding_level = level - if override == 'left-to-right': - ci.character_type = 'L' - elif override == 'right-to-left': - ci.character_type = 'R' + _apply_override(ci, current.override) - # X9: replace explicit formatting types and BN with 'BN' in character_type - for ci in chars: - if ci.original_type in X9_REMOVE_TYPES: - ci.character_type = 'BN' + _apply_x9(chars) if verbose: print("=== Phase X: Explicit Embedding Levels ===")