plain-parser 0.2.1.dev23__py3-none-any.whl → 1.0.0.dev2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
plain_parser/graph.py CHANGED
@@ -1,164 +1,168 @@
1
- """Cycle search over a directed graph given as a mapping from node to its successors.
2
-
3
- Nodes that appear only as successors are treated as having no outgoing edges.
4
-
5
- The search is Johnson's algorithm, written from the pseudocode in the paper, with the
6
- strongly connected components found by Tarjan's algorithm as given on Wikipedia.
7
-
8
- - D. B. Johnson, "Finding all the elementary circuits of a directed graph",
9
- SIAM J. Comput. 4(1):77-84, 1975, doi:10.1137/0204007
10
- - R. Tarjan, "Depth-first search and linear graph algorithms",
11
- SIAM J. Comput. 1(2):146-160, 1972, doi:10.1137/0201010
12
- - https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
13
-
14
- Both searches keep their own stack of frames instead of recursing, so the depth of a
15
- tangle is not limited by Python's recursion limit.
16
- """
1
+ """Strongly connected components and simple cycles of a directed graph, without recursion."""
17
2
 
18
3
  import heapq
19
- from collections import defaultdict
20
- from collections.abc import Hashable, Iterable, Iterator, Mapping
21
- from typing import Optional, TypeVar
4
+ from typing import Dict, Hashable, Iterable, Iterator, List, Mapping, Optional, Set, Tuple, TypeVar
22
5
 
23
6
  Node = TypeVar("Node", bound=Hashable)
24
7
 
25
8
 
26
- def _successors(graph: Mapping[Node, Iterable[Node]]) -> dict[Node, list[Node]]:
27
- # a repeated edge would otherwise yield every cycle through it once per repeat
28
- successors = {node: list(dict.fromkeys(targets)) for node, targets in graph.items()}
29
- for targets in list(successors.values()):
30
- for target in targets:
31
- successors.setdefault(target, [])
32
- return successors
33
-
34
-
35
- def strongly_connected_components(graph: Mapping[Node, Iterable[Node]]) -> list[set[Node]]:
36
- """Tarjan: one depth-first walk, each node stamped with its visit index and the lowest
37
- index it can reach; a node whose lowest reachable index is its own closes a component."""
38
- successors = _successors(graph)
39
- index: dict[Node, int] = {}
40
- lowlink: dict[Node, int] = {}
41
- stack: list[Node] = []
42
- on_stack: set[Node] = set()
43
- components: list[set[Node]] = []
44
-
45
- def visit(node: Node) -> tuple[Node, Iterator[Node]]:
46
- index[node] = lowlink[node] = len(index)
47
- stack.append(node)
48
- on_stack.add(node)
49
- return node, iter(successors[node])
50
-
51
- for root in successors:
52
- if root in index:
9
+ def _normalize(graph: Mapping[Node, Iterable[Node]]) -> Tuple[List[Node], Dict[Node, List[Node]]]:
10
+ """Return the nodes in graph order and the successor lists, without repeated successors."""
11
+ adjacency: Dict[Node, List[Node]] = {}
12
+ for node, successors in graph.items():
13
+ unique: List[Node] = []
14
+ seen: Set[Node] = set()
15
+ for successor in successors:
16
+ if successor not in seen:
17
+ seen.add(successor)
18
+ unique.append(successor)
19
+ adjacency[node] = unique
20
+ nodes = list(adjacency)
21
+ for node in list(adjacency):
22
+ for successor in adjacency[node]:
23
+ if successor not in adjacency:
24
+ adjacency[successor] = []
25
+ nodes.append(successor)
26
+ return nodes, adjacency
27
+
28
+
29
+ def _components(nodes: Iterable[Node], adjacency: Mapping[Node, List[Node]], allowed: Optional[Set[Node]] = None):
30
+ """Tarjan's algorithm with an explicit stack of frames; successors outside `allowed` are ignored."""
31
+ index_of: Dict[Node, int] = {}
32
+ low: Dict[Node, int] = {}
33
+ on_stack: Set[Node] = set()
34
+ stack: List[Node] = []
35
+ components: List[Set[Node]] = []
36
+ counter = 0
37
+
38
+ for root in nodes:
39
+ if root in index_of:
53
40
  continue
54
- frames = [visit(root)]
41
+ index_of[root] = low[root] = counter
42
+ counter += 1
43
+ stack.append(root)
44
+ on_stack.add(root)
45
+ frames: List[List] = [[root, 0]]
55
46
  while frames:
56
- node, targets = frames[-1]
57
- for target in targets:
58
- if target not in index:
59
- frames.append(visit(target))
47
+ frame = frames[-1]
48
+ node, position = frame
49
+ successors = adjacency[node]
50
+ descended = False
51
+ while position < len(successors):
52
+ successor = successors[position]
53
+ position += 1
54
+ if allowed is not None and successor not in allowed:
55
+ continue
56
+ if successor not in index_of:
57
+ frame[1] = position
58
+ index_of[successor] = low[successor] = counter
59
+ counter += 1
60
+ stack.append(successor)
61
+ on_stack.add(successor)
62
+ frames.append([successor, 0])
63
+ descended = True
60
64
  break
61
- if target in on_stack:
62
- lowlink[node] = min(lowlink[node], index[target])
63
- else:
64
- frames.pop()
65
- if frames:
66
- parent = frames[-1][0]
67
- lowlink[parent] = min(lowlink[parent], lowlink[node])
68
- if lowlink[node] == index[node]:
69
- component: set[Node] = set()
70
- while True:
71
- member = stack.pop()
72
- on_stack.discard(member)
73
- component.add(member)
74
- if member == node:
75
- break
76
- components.append(component)
65
+ if successor in on_stack:
66
+ low[node] = min(low[node], index_of[successor])
67
+ if descended:
68
+ continue
69
+ frames.pop()
70
+ if frames:
71
+ parent = frames[-1][0]
72
+ low[parent] = min(low[parent], low[node])
73
+ if low[node] == index_of[node]:
74
+ component: Set[Node] = set()
75
+ while True:
76
+ member = stack.pop()
77
+ on_stack.discard(member)
78
+ component.add(member)
79
+ if member == node:
80
+ break
81
+ components.append(component)
77
82
  return components
78
83
 
79
84
 
80
- def _cycles_through(adjacency: dict[Node, list[Node]], s: Node) -> Iterator[list[Node]]:
81
- """Johnson's CIRCUIT: every elementary cycle through `s` in one strongly connected component.
85
+ def strongly_connected_components(graph: Mapping[Node, Iterable[Node]]) -> List[Set[Node]]:
86
+ """Return the strongly connected components of a graph as a list of node sets."""
87
+ nodes, adjacency = _normalize(graph)
88
+ return _components(nodes, adjacency)
89
+
82
90
 
83
- A node is blocked while it is on the path, and stays blocked after backtracking until a
84
- cycle is found through some node it was waiting on."""
85
- blocked: set[Node] = set()
86
- blocked_map: dict[Node, set[Node]] = defaultdict(set)
91
+ def _circuits_from(start: Node, adjacency: Mapping[Node, List[Node]], allowed: Set[Node]) -> Iterator[List[Node]]:
92
+ """Johnson's circuit search from `start` inside `allowed`, with an explicit stack of frames."""
93
+ successors_of = {node: [s for s in adjacency[node] if s in allowed] for node in allowed}
94
+ blocked: Set[Node] = {start}
95
+ blocked_by: Dict[Node, Set[Node]] = {node: set() for node in allowed}
96
+ closed: Set[Node] = set()
97
+ path: List[Node] = [start]
98
+ frames: List[List] = [[start, 0]]
87
99
 
88
100
  def unblock(node: Node) -> None:
89
101
  pending = [node]
90
102
  while pending:
91
103
  current = pending.pop()
92
- blocked.discard(current)
93
- pending.extend(waiting for waiting in blocked_map.pop(current, ()) if waiting in blocked)
104
+ if current in blocked:
105
+ blocked.discard(current)
106
+ pending.extend(blocked_by[current])
107
+ blocked_by[current].clear()
94
108
 
95
- path = [s]
96
- blocked.add(s)
97
- frames = [iter(adjacency[s])]
98
- found_below = [False]
99
109
  while frames:
100
- node = path[-1]
101
- for target in frames[-1]:
102
- if target == s:
103
- yield list(path)
104
- found_below[-1] = True
105
- elif target not in blocked:
106
- path.append(target)
107
- blocked.add(target)
108
- frames.append(iter(adjacency[target]))
109
- found_below.append(False)
110
- break
110
+ frame = frames[-1]
111
+ node, position = frame
112
+ successors = successors_of[node]
113
+ if position < len(successors):
114
+ frame[1] = position + 1
115
+ successor = successors[position]
116
+ if successor == start:
117
+ yield path[:]
118
+ closed.update(path)
119
+ elif successor not in blocked:
120
+ path.append(successor)
121
+ frames.append([successor, 0])
122
+ closed.discard(successor)
123
+ blocked.add(successor)
124
+ continue
125
+ if node in closed:
126
+ unblock(node)
111
127
  else:
112
- frames.pop()
113
- path.pop()
114
- if found_below.pop():
115
- unblock(node)
116
- if found_below:
117
- found_below[-1] = True
118
- else:
119
- for target in adjacency[node]:
120
- blocked_map[target].add(node)
121
-
122
-
123
- def _all_cycles(graph: Mapping[Node, Iterable[Node]]) -> Iterator[list[Node]]:
124
- """Johnson's main loop: every cycle lies inside one strongly connected component, and
125
- every cycle inside a component either passes through its least node or survives that
126
- node's removal. So search each component from its least node, drop the node, and split
127
- what is left into components again. Components are taken least node first, so a caller
128
- that stops early has seen the cycles through the earliest nodes."""
129
- successors = _successors(graph)
130
- for node, targets in successors.items():
131
- if node in targets:
128
+ for successor in successors:
129
+ blocked_by[successor].add(node)
130
+ frames.pop()
131
+ path.pop()
132
+
133
+
134
+ def simple_cycles(graph: Mapping[Node, Iterable[Node]], limit: Optional[int] = None) -> Iterator[List[Node]]:
135
+ """Yield every elementary cycle of a graph once, lazily, stopping after `limit` cycles when it is given."""
136
+ if limit is not None and limit <= 0:
137
+ return
138
+ nodes, adjacency = _normalize(graph)
139
+ position = {node: i for i, node in enumerate(nodes)}
140
+ yielded = 0
141
+
142
+ for node in nodes:
143
+ if node in adjacency[node]:
132
144
  yield [node]
133
- successors = {node: [t for t in targets if t != node] for node, targets in successors.items()}
134
- position = {node: i for i, node in enumerate(successors)}
135
-
136
- # components are disjoint, so no two entries share a least position and the sets are never compared
137
- components: list[tuple[int, set[Node]]] = []
138
-
139
- def push_components(adjacency: Mapping[Node, Iterable[Node]]) -> None:
140
- for component in strongly_connected_components(adjacency):
141
- if len(component) >= 2:
142
- heapq.heappush(components, (min(map(position.__getitem__, component)), component))
143
-
144
- push_components(successors)
145
- while components:
146
- _, component = heapq.heappop(components)
147
- s = min(component, key=position.__getitem__)
148
- adjacency = {n: [t for t in successors[n] if t in component] for n in component}
149
- yield from _cycles_through(adjacency, s)
150
- del adjacency[s]
151
- for targets in adjacency.values():
152
- if s in targets:
153
- targets.remove(s)
154
- push_components(adjacency)
155
-
156
-
157
- def simple_cycles(graph: Mapping[Node, Iterable[Node]], limit: Optional[int] = None) -> Iterator[list[Node]]:
158
- """Yield the elementary cycles of `graph`, each as its nodes in edge order, stopping
159
- after `limit` cycles when one is given. Self-loops come first; longer cycles follow in
160
- order of their earliest node in `graph`'s iteration order."""
161
- for found, cycle in enumerate(_all_cycles(graph), start=1):
162
- if limit is not None and found > limit:
163
- return
164
- yield cycle
145
+ yielded += 1
146
+ if limit is not None and yielded >= limit:
147
+ return
148
+
149
+ adjacency = {node: [s for s in successors if s != node] for node, successors in adjacency.items()}
150
+
151
+ heap: List[Tuple[int, Set[Node]]] = []
152
+
153
+ def push_components(members: Iterable[Node], allowed: Optional[Set[Node]]) -> None:
154
+ for component in _components(members, adjacency, allowed):
155
+ if len(component) > 1:
156
+ heapq.heappush(heap, (min(position[n] for n in component), id(component), component)) # type: ignore
157
+
158
+ push_components(nodes, None)
159
+ while heap:
160
+ _, _, component = heapq.heappop(heap) # type: ignore
161
+ start = min(component, key=position.__getitem__)
162
+ for cycle in _circuits_from(start, adjacency, component):
163
+ yield cycle
164
+ yielded += 1
165
+ if limit is not None and yielded >= limit:
166
+ return
167
+ rest = component - {start}
168
+ push_components(sorted(rest, key=position.__getitem__), rest)
@@ -1,109 +1,45 @@
1
- from pathlib import Path
2
- from typing import Mapping, Sequence, TextIO
1
+ """Liquid include tag that indents the included template, and the loader mixin that does the indenting."""
3
2
 
4
- from liquid2 import Environment, RenderContext, Template, TemplateNotFoundError
5
- from liquid2.builtin import IncludeTag
6
- from liquid2.builtin.tags.include_tag import IncludeNode
3
+ from contextvars import ContextVar
4
+ from typing import TYPE_CHECKING, Any, TextIO
7
5
 
6
+ from liquid2 import TemplateSource
7
+ from liquid2.builtin.tags.include_tag import IncludeNode, IncludeTag
8
8
 
9
- class Plain2CodeIncludeNode(IncludeNode):
10
- def render_to_output(self, context: RenderContext, buffer: TextIO) -> int:
11
- """Render the node to the output buffer."""
12
- name = self.name.evaluate(context)
13
- whitespaces = 0
14
- is_comment = False
15
- i = self.token.start
16
- while self.token.source[i] != "\n" and i >= 0:
17
- if self.token.source[i] == " ":
18
- whitespaces += 1
19
- elif self.token.source[i] == ">":
20
- is_comment = True
21
- break
22
- else:
23
- whitespaces = 0
24
- i -= 1
9
+ if TYPE_CHECKING:
10
+ from liquid2 import RenderContext
25
11
 
26
- if is_comment:
27
- return buffer.write(str(self))
12
+ _include_indent: ContextVar[int] = ContextVar("plain_include_indent", default=0)
28
13
 
29
- try:
30
- template = context.env.get_template(str(name), context=context, tag=self.tag, whitespaces=whitespaces)
31
- except TemplateNotFoundError as err:
32
- wrapped = TemplateNotFoundError(f"Template not found: {err}")
33
- wrapped.token = self.name.token
34
- wrapped.template_name = context.template.full_name()
35
- raise wrapped from err
36
14
 
37
- namespace: dict[str, object] = dict(arg.evaluate(context) for arg in self.args)
15
+ def indent_template(source: str, indent: int) -> str:
16
+ """Drop the trailing whitespace of a template source and indent every line after the first."""
17
+ return source.rstrip().replace("\n", "\n" + " " * indent)
38
18
 
39
- character_count = 0
40
19
 
41
- with context.extend(namespace, template=template):
42
- if self.var:
43
- val = self.var.evaluate(context)
44
- key = self.alias or template.name.split(".")[0]
20
+ class Plain2CodeLoaderMixin:
21
+ """Loader mixin: the template sources it loads are indented for the include tag being rendered."""
45
22
 
46
- if isinstance(val, Sequence) and not isinstance(val, str):
47
- context.raise_for_loop_limit(len(val))
48
- for itm in val:
49
- namespace[key] = itm
50
- character_count += template.render_with_context(context, buffer, partial=True)
51
- else:
52
- namespace[key] = val
53
- character_count = template.render_with_context(context, buffer, partial=True)
54
- else:
23
+ def get_source(self, env: Any, template_name: str, *, context: Any = None, **kwargs: object) -> TemplateSource:
24
+ loaded = super().get_source(env, template_name, context=context, **kwargs) # type: ignore[misc]
25
+ return loaded._replace(source=indent_template(loaded.source, _include_indent.get()))
55
26
 
56
- character_count = template.render_with_context(context, buffer, partial=True)
57
27
 
58
- return character_count
28
+ class Plain2CodeIncludeNode(IncludeNode):
29
+ def render_to_output(self, context: "RenderContext", buffer: TextIO) -> int:
30
+ source = self.token.source
31
+ start = self.token.start
32
+ prefix = source[source.rfind("\n", 0, start) + 1 : start]
33
+ if ">" in prefix:
34
+ text = str(self)
35
+ buffer.write(text)
36
+ return len(text)
37
+ reset = _include_indent.set(len(prefix) - len(prefix.lstrip(" ")))
38
+ try:
39
+ return super().render_to_output(context, buffer)
40
+ finally:
41
+ _include_indent.reset(reset)
59
42
 
60
43
 
61
44
  class Plain2CodeIncludeTag(IncludeTag):
62
45
  node_class = Plain2CodeIncludeNode
63
-
64
-
65
- class Plain2CodeLoaderMixin:
66
- def __init__(self, *args, **kwargs):
67
- if not hasattr(self, "get_source"):
68
- raise NotImplementedError("Class must implement get_source")
69
- super().__init__(*args, **kwargs)
70
-
71
- def load(
72
- self,
73
- env: Environment,
74
- name: str,
75
- *,
76
- globals: Mapping[str, object] | None = None,
77
- context: RenderContext | None = None,
78
- **kwargs: object,
79
- ) -> Template:
80
- """
81
- Find and parse template source code.
82
-
83
- Args:
84
- env: The `Environment` attempting to load the template source text.
85
- name: A name or identifier for a template's source text.
86
- globals: A mapping of render context variables attached to the
87
- resulting template.
88
- context: An optional render context that can be used to narrow the template
89
- source search space.
90
- kwargs: Arbitrary arguments that can be used to narrow the template source
91
- search space.
92
- """
93
- source, full_name, uptodate, matter = self.get_source(env, name, context=context, **kwargs)
94
- whitespaces = kwargs.get("whitespaces", 0)
95
- assert isinstance(whitespaces, int)
96
- source = source.rstrip().replace("\n", "\n" + " " * whitespaces)
97
-
98
- path = Path(full_name)
99
-
100
- template = env.from_string(
101
- source,
102
- name=path.name,
103
- path=path,
104
- globals=globals,
105
- overlay_data=matter,
106
- )
107
-
108
- template.uptodate = uptodate
109
- return template