plain-parser 0.2.1.dev22__py3-none-any.whl → 1.0.0.dev1__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,132 @@
1
- """Cycle search over a directed graph given as a mapping from node to its successors.
1
+ """Strongly connected components (Tarjan) and simple cycles (Johnson), both without recursion."""
2
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
- """
17
-
18
- import heapq
19
- from collections import defaultdict
20
- from collections.abc import Hashable, Iterable, Iterator, Mapping
21
- from typing import Optional, TypeVar
3
+ from typing import Dict, Hashable, Iterable, Iterator, List, Mapping, Optional, Set, TypeVar
22
4
 
23
5
  Node = TypeVar("Node", bound=Hashable)
24
6
 
25
7
 
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:
8
+ def _normalize(graph: Mapping[Node, Iterable[Node]]) -> tuple[List[Node], Dict[Node, List[Node]]]:
9
+ adj: Dict[Node, List[Node]] = {}
10
+ for node, succs in graph.items():
11
+ seen: Dict[Node, None] = {}
12
+ for s in succs:
13
+ seen.setdefault(s)
14
+ adj[node] = list(seen)
15
+ nodes = list(adj)
16
+ for succs in list(adj.values()):
17
+ for s in succs:
18
+ if s not in adj:
19
+ adj[s] = []
20
+ nodes.append(s)
21
+ return nodes, adj
22
+
23
+
24
+ def _tarjan(nodes: List[Node], adj: Mapping[Node, List[Node]]) -> List[Set[Node]]:
25
+ index: Dict[Node, int] = {}
26
+ low: Dict[Node, int] = {}
27
+ on_stack: Set[Node] = set()
28
+ stack: List[Node] = []
29
+ result: List[Set[Node]] = []
30
+ counter = 0
31
+ for root in nodes:
52
32
  if root in index:
53
33
  continue
54
- frames = [visit(root)]
34
+ index[root] = low[root] = counter
35
+ counter += 1
36
+ stack.append(root)
37
+ on_stack.add(root)
38
+ frames = [(root, iter(adj[root]))]
55
39
  while frames:
56
- node, targets = frames[-1]
57
- for target in targets:
58
- if target not in index:
59
- frames.append(visit(target))
40
+ v, it = frames[-1]
41
+ for w in it:
42
+ if w not in index:
43
+ index[w] = low[w] = counter
44
+ counter += 1
45
+ stack.append(w)
46
+ on_stack.add(w)
47
+ frames.append((w, iter(adj[w])))
60
48
  break
61
- if target in on_stack:
62
- lowlink[node] = min(lowlink[node], index[target])
49
+ if w in on_stack:
50
+ low[v] = min(low[v], index[w])
63
51
  else:
64
52
  frames.pop()
65
53
  if frames:
66
54
  parent = frames[-1][0]
67
- lowlink[parent] = min(lowlink[parent], lowlink[node])
68
- if lowlink[node] == index[node]:
69
- component: set[Node] = set()
55
+ low[parent] = min(low[parent], low[v])
56
+ if low[v] == index[v]:
57
+ comp: Set[Node] = set()
70
58
  while True:
71
- member = stack.pop()
72
- on_stack.discard(member)
73
- component.add(member)
74
- if member == node:
59
+ w = stack.pop()
60
+ on_stack.discard(w)
61
+ comp.add(w)
62
+ if w == v:
75
63
  break
76
- components.append(component)
77
- return components
78
-
79
-
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.
64
+ result.append(comp)
65
+ return result
82
66
 
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)
87
67
 
88
- def unblock(node: Node) -> None:
89
- pending = [node]
90
- while pending:
91
- current = pending.pop()
92
- blocked.discard(current)
93
- pending.extend(waiting for waiting in blocked_map.pop(current, ()) if waiting in blocked)
94
-
95
- path = [s]
96
- blocked.add(s)
97
- frames = [iter(adjacency[s])]
98
- found_below = [False]
99
- 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
111
- 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:
132
- 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)
68
+ def strongly_connected_components(graph: Mapping[Node, Iterable[Node]]) -> list[set[Node]]:
69
+ nodes, adj = _normalize(graph)
70
+ return _tarjan(nodes, adj)
155
71
 
156
72
 
157
73
  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
74
+ if limit is not None and limit <= 0:
75
+ return
76
+ nodes, adj = _normalize(graph)
77
+ yielded = 0
78
+ for n in nodes:
79
+ if n in adj[n]:
80
+ yield [n]
81
+ yielded += 1
82
+ if limit is not None and yielded >= limit:
83
+ return
84
+ order = {n: i for i, n in enumerate(nodes)}
85
+ for s in nodes:
86
+ rank = order[s]
87
+ sub_nodes = [n for n in nodes if order[n] >= rank]
88
+ sub = {n: [w for w in adj[n] if order[w] >= rank and w != n] for n in sub_nodes}
89
+ comp = next(c for c in _tarjan([s], sub) if s in c)
90
+ if len(comp) < 2:
91
+ continue
92
+ cadj = {n: [w for w in sub[n] if w in comp] for n in comp}
93
+ blocked: Set[Node] = {s}
94
+ b: Dict[Node, Set[Node]] = {n: set() for n in comp}
95
+ path = [s]
96
+ its = [iter(cadj[s])]
97
+ closed = [False]
98
+
99
+ def unblock(u: Node) -> None:
100
+ todo = [u]
101
+ while todo:
102
+ x = todo.pop()
103
+ if x in blocked:
104
+ blocked.discard(x)
105
+ todo.extend(b[x])
106
+ b[x].clear()
107
+
108
+ while its:
109
+ for w in its[-1]:
110
+ if w == s:
111
+ yield list(path)
112
+ yielded += 1
113
+ if limit is not None and yielded >= limit:
114
+ return
115
+ closed[-1] = True
116
+ elif w not in blocked:
117
+ path.append(w)
118
+ its.append(iter(cadj[w]))
119
+ closed.append(False)
120
+ blocked.add(w)
121
+ break
122
+ else:
123
+ v = path.pop()
124
+ its.pop()
125
+ found = closed.pop()
126
+ if found:
127
+ unblock(v)
128
+ if closed:
129
+ closed[-1] = True
130
+ else:
131
+ for w in cadj[v]:
132
+ b[w].add(v)
@@ -1,109 +1,63 @@
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 it."""
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 typing import TextIO
7
4
 
5
+ from liquid2 import RenderContext
6
+ from liquid2.builtin.tags.include_tag import IncludeNode, IncludeTag
7
+ from liquid2.exceptions import TemplateNotFoundError
8
+ from liquid2.loader import TemplateSource
8
9
 
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
25
10
 
26
- if is_comment:
27
- return buffer.write(str(self))
11
+ class Plain2CodeLoaderMixin:
12
+ """Loader mixin: strips trailing whitespace of a template and indents its lines after the first."""
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
14
+ def get_source(self, env, template_name, *, context=None, indent=0, **kwargs):
15
+ source = super().get_source(env, template_name, context=context, **kwargs) # type: ignore[misc]
16
+ text = source.source.rstrip()
17
+ if indent:
18
+ text = text.replace("\n", "\n" + " " * indent)
19
+ return TemplateSource(text, source.name, source.uptodate, source.matter)
36
20
 
37
- namespace: dict[str, object] = dict(arg.evaluate(context) for arg in self.args)
38
21
 
39
- character_count = 0
22
+ class Plain2CodeIncludeNode(IncludeNode):
23
+ __slots__ = ()
24
+
25
+ def _line_prefix(self) -> str:
26
+ source = self.token.source
27
+ start = self.token.start
28
+ return source[source.rfind("\n", 0, start) + 1 : start]
40
29
 
30
+ def render_to_output(self, context: RenderContext, buffer: TextIO) -> int:
31
+ prefix = self._line_prefix()
32
+ if ">" in prefix:
33
+ text = self.token.source[self.token.start : self.token.stop].replace('"', "'")
34
+ buffer.write(text)
35
+ return len(text)
36
+ indent = len(prefix) - len(prefix.lstrip(" "))
37
+ name = str(self.name.evaluate(context))
38
+ try:
39
+ template = context.env.get_template(name, context=context, tag=self.tag, indent=indent)
40
+ except TemplateNotFoundError as err:
41
+ err.token = self.name.token
42
+ err.template_name = context.template.full_name()
43
+ raise
44
+ namespace = dict(arg.evaluate(context) for arg in self.args)
41
45
  with context.extend(namespace, template=template):
42
46
  if self.var:
43
47
  val = self.var.evaluate(context)
44
48
  key = self.alias or template.name.split(".")[0]
49
+ if isinstance(val, (list, tuple)):
50
+ count = 0
51
+ for item in val:
52
+ namespace[key] = item
53
+ count += template.render_with_context(context, buffer, partial=True)
54
+ return count
55
+ namespace[key] = val
56
+ return template.render_with_context(context, buffer, partial=True)
45
57
 
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:
55
-
56
- character_count = template.render_with_context(context, buffer, partial=True)
57
-
58
- return character_count
58
+ async def render_to_output_async(self, context: RenderContext, buffer: TextIO) -> int:
59
+ return self.render_to_output(context, buffer)
59
60
 
60
61
 
61
62
  class Plain2CodeIncludeTag(IncludeTag):
62
63
  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