otTraverse.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. """Methods for traversing trees of otData-driven OpenType tables."""
  2. from collections import deque
  3. from typing import Callable, Deque, Iterable, List, Optional, Tuple
  4. from .otBase import BaseTable
  5. __all__ = [
  6. "bfs_base_table",
  7. "dfs_base_table",
  8. "SubTablePath",
  9. ]
  10. class SubTablePath(Tuple[BaseTable.SubTableEntry, ...]):
  11. def __str__(self) -> str:
  12. path_parts = []
  13. for entry in self:
  14. path_part = entry.name
  15. if entry.index is not None:
  16. path_part += f"[{entry.index}]"
  17. path_parts.append(path_part)
  18. return ".".join(path_parts)
  19. # Given f(current frontier, new entries) add new entries to frontier
  20. AddToFrontierFn = Callable[[Deque[SubTablePath], List[SubTablePath]], None]
  21. def dfs_base_table(
  22. root: BaseTable,
  23. root_accessor: Optional[str] = None,
  24. skip_root: bool = False,
  25. predicate: Optional[Callable[[SubTablePath], bool]] = None,
  26. iter_subtables_fn: Optional[
  27. Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]]
  28. ] = None,
  29. ) -> Iterable[SubTablePath]:
  30. """Depth-first search tree of BaseTables.
  31. Args:
  32. root (BaseTable): the root of the tree.
  33. root_accessor (Optional[str]): attribute name for the root table, if any (mostly
  34. useful for debugging).
  35. skip_root (Optional[bool]): if True, the root itself is not visited, only its
  36. children.
  37. predicate (Optional[Callable[[SubTablePath], bool]]): function to filter out
  38. paths. If True, the path is yielded and its subtables are added to the
  39. queue. If False, the path is skipped and its subtables are not traversed.
  40. iter_subtables_fn (Optional[Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]]]):
  41. function to iterate over subtables of a table. If None, the default
  42. BaseTable.iterSubTables() is used.
  43. Yields:
  44. SubTablePath: tuples of BaseTable.SubTableEntry(name, table, index) namedtuples
  45. for each of the nodes in the tree. The last entry in a path is the current
  46. subtable, whereas preceding ones refer to its parent tables all the way up to
  47. the root.
  48. """
  49. yield from _traverse_ot_data(
  50. root,
  51. root_accessor,
  52. skip_root,
  53. predicate,
  54. lambda frontier, new: frontier.extendleft(reversed(new)),
  55. iter_subtables_fn,
  56. )
  57. def bfs_base_table(
  58. root: BaseTable,
  59. root_accessor: Optional[str] = None,
  60. skip_root: bool = False,
  61. predicate: Optional[Callable[[SubTablePath], bool]] = None,
  62. iter_subtables_fn: Optional[
  63. Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]]
  64. ] = None,
  65. ) -> Iterable[SubTablePath]:
  66. """Breadth-first search tree of BaseTables.
  67. Args:
  68. the root of the tree.
  69. root_accessor (Optional[str]): attribute name for the root table, if any (mostly
  70. useful for debugging).
  71. skip_root (Optional[bool]): if True, the root itself is not visited, only its
  72. children.
  73. predicate (Optional[Callable[[SubTablePath], bool]]): function to filter out
  74. paths. If True, the path is yielded and its subtables are added to the
  75. queue. If False, the path is skipped and its subtables are not traversed.
  76. iter_subtables_fn (Optional[Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]]]):
  77. function to iterate over subtables of a table. If None, the default
  78. BaseTable.iterSubTables() is used.
  79. Yields:
  80. SubTablePath: tuples of BaseTable.SubTableEntry(name, table, index) namedtuples
  81. for each of the nodes in the tree. The last entry in a path is the current
  82. subtable, whereas preceding ones refer to its parent tables all the way up to
  83. the root.
  84. """
  85. yield from _traverse_ot_data(
  86. root,
  87. root_accessor,
  88. skip_root,
  89. predicate,
  90. lambda frontier, new: frontier.extend(new),
  91. iter_subtables_fn,
  92. )
  93. def _traverse_ot_data(
  94. root: BaseTable,
  95. root_accessor: Optional[str],
  96. skip_root: bool,
  97. predicate: Optional[Callable[[SubTablePath], bool]],
  98. add_to_frontier_fn: AddToFrontierFn,
  99. iter_subtables_fn: Optional[
  100. Callable[[BaseTable], Iterable[BaseTable.SubTableEntry]]
  101. ] = None,
  102. ) -> Iterable[SubTablePath]:
  103. # no visited because general otData cannot cycle (forward-offset only)
  104. if root_accessor is None:
  105. root_accessor = type(root).__name__
  106. if predicate is None:
  107. def predicate(path):
  108. return True
  109. if iter_subtables_fn is None:
  110. def iter_subtables_fn(table):
  111. return table.iterSubTables()
  112. frontier: Deque[SubTablePath] = deque()
  113. root_entry = BaseTable.SubTableEntry(root_accessor, root)
  114. if not skip_root:
  115. frontier.append((root_entry,))
  116. else:
  117. add_to_frontier_fn(
  118. frontier,
  119. [
  120. (root_entry, subtable_entry)
  121. for subtable_entry in iter_subtables_fn(root)
  122. ],
  123. )
  124. while frontier:
  125. # path is (value, attr_name) tuples. attr_name is attr of parent to get value
  126. path = frontier.popleft()
  127. current = path[-1].value
  128. if not predicate(path):
  129. continue
  130. yield SubTablePath(path)
  131. new_entries = [
  132. path + (subtable_entry,) for subtable_entry in iter_subtables_fn(current)
  133. ]
  134. add_to_frontier_fn(frontier, new_entries)