Return leaves that are inside matching brackets. The input `leaves` can have non-matching brackets at the head or tail parts. Matching brackets are included.
(leaves: Sequence[Leaf])
| 355 | |
| 356 | |
| 357 | def get_leaves_inside_matching_brackets(leaves: Sequence[Leaf]) -> set[LeafID]: |
| 358 | """Return leaves that are inside matching brackets. |
| 359 | |
| 360 | The input `leaves` can have non-matching brackets at the head or tail parts. |
| 361 | Matching brackets are included. |
| 362 | """ |
| 363 | try: |
| 364 | # Start with the first opening bracket and ignore closing brackets before. |
| 365 | start_index = next( |
| 366 | i for i, l in enumerate(leaves) if l.type in OPENING_BRACKETS |
| 367 | ) |
| 368 | except StopIteration: |
| 369 | return set() |
| 370 | bracket_stack = [] |
| 371 | ids = set() |
| 372 | for i in range(start_index, len(leaves)): |
| 373 | leaf = leaves[i] |
| 374 | if leaf.type in OPENING_BRACKETS: |
| 375 | bracket_stack.append((BRACKET[leaf.type], i)) |
| 376 | if leaf.type in CLOSING_BRACKETS: |
| 377 | if bracket_stack and leaf.type == bracket_stack[-1][0]: |
| 378 | _, start = bracket_stack.pop() |
| 379 | for j in range(start, i + 1): |
| 380 | ids.add(id(leaves[j])) |
| 381 | else: |
| 382 | break |
| 383 | return ids |
no test coverage detected