plain-parser 1.0.0.dev1__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.
@@ -1,120 +1,143 @@
1
- """Concept extraction and validation for plain source trees."""
1
+ """Concepts of a specification: extracting, validating and ordering their definitions."""
2
2
 
3
+ import graphlib
3
4
  import re
4
- from typing import Any
5
-
6
- DEFAULT_CONCEPTS = {
7
- "ConformanceTests",
8
- "UnitTests",
9
- "AcceptanceTest",
10
- "AcceptanceTests",
11
- "Implementation",
12
- "plainDefinitions",
13
- "plainImplementationReqs",
14
- "plainFunctionality",
15
- "plainTestReqs",
16
- "plainImplementationCode",
5
+ from typing import Any, Dict, List, Set, Tuple
6
+
7
+ from plain_parser.exceptions import PlainSyntaxError
8
+ from plain_parser.graph import simple_cycles
9
+ from plain_parser.plain_spec import (
10
+ DEFINITIONS,
11
+ FUNCTIONAL_REQUIREMENTS,
12
+ NON_FUNCTIONAL_REQUIREMENTS,
13
+ TEST_REQUIREMENTS,
14
+ )
15
+
16
+ DEFAULT_CONCEPTS: Set[str] = {
17
+ ":ConformanceTests:",
18
+ ":UnitTests:",
19
+ ":AcceptanceTest:",
20
+ ":AcceptanceTests:",
21
+ ":Implementation:",
22
+ ":plainDefinitions:",
23
+ ":plainImplementationReqs:",
24
+ ":plainFunctionality:",
25
+ ":plainTestReqs:",
26
+ ":plainImplementationCode:",
17
27
  }
28
+ MAX_REPORTED_CYCLES = 10
18
29
 
19
- _CONCEPT_NAME = r"[A-Za-z0-9+\-._]+"
20
- _CONCEPT_RE = re.compile(_CONCEPT_NAME)
21
- _CONCEPT_TOKEN_RE = re.compile(r":(" + _CONCEPT_NAME + r"):")
22
- _DEFINITION_START_RE = re.compile(r"- (:[^:]*:(?:\s*,\s*:[^:]*:)*)")
30
+ _CONCEPT_NAME = re.compile(r"[A-Za-z0-9+\-._]+")
31
+ _CONCEPT_TOKEN = re.compile(r":[A-Za-z0-9+\-._]+:")
32
+ _DEFINITION_START = re.compile(r"\s*-\s+(:[^:\n]+:(?:[ \t]*,[ \t]*:[^:\n]+:)*)")
23
33
 
24
34
 
25
- def extract_concepts_from_definition(text: str) -> tuple[list[str], list[str]]:
26
- """Return (defined concepts, errors) of a definition text."""
27
- match = _DEFINITION_START_RE.search(text)
35
+ def extract_concepts_from_definition(text: str) -> Tuple[List[str], List[str]]:
36
+ """Return the concepts a definition text defines and the errors found in it."""
37
+ match = _DEFINITION_START.match(text)
28
38
  if match is None:
29
39
  return [], [
30
40
  f"Syntax error: Invalid definition specification text: {text}. "
31
41
  "Should start with `- :<concept>:` (where <concept> is any string that does not contain `:`)."
32
42
  ]
33
- concepts: list[str] = []
34
- errors: list[str] = []
35
- for candidate in re.findall(r":([^:]*):", match.group(1)):
36
- if _CONCEPT_RE.fullmatch(candidate):
43
+ concepts: List[str] = []
44
+ errors: List[str] = []
45
+ for candidate in re.findall(r":[^:\n]+:", match.group(1)):
46
+ if _CONCEPT_NAME.fullmatch(candidate[1:-1]):
37
47
  concepts.append(candidate)
38
48
  else:
39
49
  errors.append(
40
- f"Syntax error: Invalid concept: :{candidate}:. Should contain only letters, numbers, hyphens and dots."
50
+ f"Syntax error: Invalid concept: {candidate}. "
51
+ "Should contain only letters, numbers, hyphens and dots."
41
52
  )
42
53
  return concepts, errors
43
54
 
44
55
 
45
- def extract_concepts_from_spec_text(text: str) -> list[str]:
46
- """Return every concept token mentioned in text, in order, repeats kept."""
47
- return _CONCEPT_TOKEN_RE.findall(text)
56
+ def extract_concepts_from_spec_text(text: str) -> List[str]:
57
+ """Return every concept token a text mentions, in order, repeats kept."""
58
+ return _CONCEPT_TOKEN.findall(text)
48
59
 
49
60
 
50
- def collect_concepts(plain_source: dict[str, Any]) -> tuple[list[str], list[str]]:
51
- """Return (defined concepts, errors) of the definitions of a tree."""
52
- concepts: list[str] = []
53
- errors: list[str] = []
54
- for item in plain_source.get("definitions", []):
55
- found, errs = extract_concepts_from_definition(item["markdown"])
56
- concepts.extend(found)
57
- errors.extend(errs)
58
- return concepts, errors
61
+ def _item_markdown(item: Any) -> str:
62
+ return item["markdown"] if isinstance(item, dict) else str(item)
59
63
 
60
64
 
61
- def validate_concepts_in_spec(spec: dict[str, Any], concepts: set[str], spec_group: str) -> list[str]:
62
- """Errors for mentions in one item that are not defined."""
63
- errors = []
64
- for concept in extract_concepts_from_spec_text(spec["markdown"]):
65
- if concept not in concepts and concept not in DEFAULT_CONCEPTS:
66
- errors.append(
67
- f"Syntax error: Concept :{concept}: is not defined in the definitions. {spec_group}: {spec['markdown']}"
68
- )
69
- return errors
65
+ def collect_concepts(plain_source) -> Tuple[List[str], List[str]]:
66
+ """Return the concepts the definitions define, and the errors found in the definitions."""
67
+ concepts: List[str] = []
68
+ errors: List[str] = []
69
+ for item in plain_source.get(DEFINITIONS, []):
70
+ defined, item_errors = extract_concepts_from_definition(_item_markdown(item))
71
+ concepts.extend(defined)
72
+ errors.extend(item_errors)
73
+ seen: Set[str] = set()
74
+ duplicated: List[str] = []
75
+ for concept in concepts:
76
+ if (concept in seen or concept in DEFAULT_CONCEPTS) and concept not in duplicated:
77
+ duplicated.append(concept)
78
+ seen.add(concept)
79
+ if duplicated:
80
+ errors.append(f"Syntax error: Concepts were defined multiple times: {', '.join(duplicated)} .")
81
+ return list(dict.fromkeys(concepts)), errors
82
+
70
83
 
84
+ def validate_concepts_in_spec(spec: dict, concepts: Set[str], spec_group: str) -> List[str]:
85
+ """Return an error for every mention in one specification item of a concept that is not defined."""
86
+ markdown = spec["markdown"]
87
+ return [
88
+ f"Syntax error: Concept {concept} is not defined in the definitions. {spec_group}: {markdown}"
89
+ for concept in extract_concepts_from_spec_text(markdown)
90
+ if concept not in concepts and concept not in DEFAULT_CONCEPTS
91
+ ]
71
92
 
72
- def validate_concepts_in_spec_group(spec_group: str, plain_source: dict[str, Any], concepts: set[str]) -> list[str]:
73
- errors: list[str] = []
93
+
94
+ def validate_concepts_in_spec_group(spec_group, plain_source, concepts: Set[str]) -> List[str]:
95
+ errors: List[str] = []
74
96
  for spec in plain_source.get(spec_group, []):
75
97
  errors.extend(validate_concepts_in_spec(spec, concepts, spec_group))
76
98
  return errors
77
99
 
78
100
 
79
- def validate_concepts(marshalled_plain_source: dict[str, Any]) -> list[str]:
80
- """Validate the concepts of a tree; empty list when valid."""
101
+ def validate_concepts(marshalled_plain_source) -> List[str]:
102
+ """Validate the concepts of a plain source tree and return a list of error texts."""
81
103
  concepts, errors = collect_concepts(marshalled_plain_source)
82
- errors = list(errors)
83
- seen: set[str] = set()
84
- problem: list[str] = []
85
- for concept in concepts:
86
- if (concept in seen or concept in DEFAULT_CONCEPTS) and concept not in problem:
87
- problem.append(concept)
88
- seen.add(concept)
89
- if problem:
90
- errors.append(
91
- f"Syntax error: Concepts were defined multiple times: {', '.join(':' + p + ':' for p in problem)} ."
92
- )
93
104
  defined = set(concepts)
94
- for group in ("implementation reqs", "test reqs", "functional specs", "definitions"):
105
+ for group in (NON_FUNCTIONAL_REQUIREMENTS, TEST_REQUIREMENTS, FUNCTIONAL_REQUIREMENTS, DEFINITIONS):
95
106
  errors.extend(validate_concepts_in_spec_group(group, marshalled_plain_source, defined))
96
107
  return errors
97
108
 
98
109
 
99
- MAX_REPORTED_CYCLES = 10
110
+ def find_concept_definitions_in_plain_source(concept: str, plain_source: dict, renderer) -> list:
111
+ """Return the definition tokens of a parsed module that define a concept."""
112
+ definitions = plain_source.get(DEFINITIONS)
113
+ tokens = getattr(definitions, "children", definitions) or []
114
+ found = []
115
+ for token in tokens:
116
+ defined, _ = extract_concepts_from_definition(renderer.render(token))
117
+ if concept in defined:
118
+ found.append(token)
119
+ return found
100
120
 
101
121
 
102
- def build_adjacency_list(definitions: list[dict[str, Any]]) -> tuple[dict[str, list[str]], dict[str, dict[str, Any]]]:
103
- """Return (concept graph, concept -> definition item).
122
+ def build_adjacency_list(definitions) -> Tuple[Dict[str, List[str]], Dict[str, Any]]:
123
+ """Build the concept graph and the definition of every concept.
104
124
 
105
- The graph maps a concept to the concepts whose definitions mention it.
125
+ The graph has an edge from concept A to concept B when the definition of B mentions A. The definitions
126
+ mapping is in definition order.
106
127
  """
107
- adjacency: dict[str, list[str]] = {}
108
- concept_definitions: dict[str, dict[str, Any]] = {}
128
+ adjacency: Dict[str, List[str]] = {}
129
+ concept_definitions: Dict[str, Any] = {}
109
130
  for item in definitions:
110
- defined, _ = extract_concepts_from_definition(item["markdown"])
131
+ markdown = _item_markdown(item)
132
+ defined, _ = extract_concepts_from_definition(markdown)
111
133
  for concept in defined:
112
134
  adjacency.setdefault(concept, [])
113
- concept_definitions[concept] = item
114
- mentioned: list[str] = []
115
- for concept in extract_concepts_from_spec_text(item["markdown"]):
116
- if concept not in DEFAULT_CONCEPTS and concept not in defined and concept not in mentioned:
117
- mentioned.append(concept)
135
+ concept_definitions.setdefault(concept, item)
136
+ mentioned = [
137
+ concept
138
+ for concept in dict.fromkeys(extract_concepts_from_spec_text(markdown))
139
+ if concept not in defined and concept not in DEFAULT_CONCEPTS
140
+ ]
118
141
  for concept in mentioned:
119
142
  adjacency.setdefault(concept, [])
120
143
  for concept in mentioned:
@@ -124,65 +147,59 @@ def build_adjacency_list(definitions: list[dict[str, Any]]) -> tuple[dict[str, l
124
147
  return adjacency, concept_definitions
125
148
 
126
149
 
127
- def format_cycles_error(adjacency_list: dict[str, list[str]], concept_definitions: dict[str, dict[str, Any]]) -> str:
128
- """Return the cycle error text, or an empty string when the graph has no cycle."""
129
- from plain_parser.graph import simple_cycles
130
-
131
- position: dict[str, int] = {}
132
- for concept in concept_definitions:
133
- position.setdefault(concept, len(position))
134
- for concept in adjacency_list:
135
- position.setdefault(concept, len(position))
136
- ordered = {c: adjacency_list[c] for c in sorted(adjacency_list, key=position.__getitem__)}
137
- found = list(simple_cycles(ordered, limit=MAX_REPORTED_CYCLES + 1))
138
- if not found:
139
- return ""
140
- # An edge A -> B means B's definition mentions A, so the written direction is the reverse.
141
- cycles = [[c[0], *reversed(c[1:])] for c in found]
142
- cycles.sort(key=lambda c: (position[c[0]], len(c)))
143
- more = len(cycles) > MAX_REPORTED_CYCLES
144
- cycles = cycles[:MAX_REPORTED_CYCLES]
145
- if more:
150
+ def format_cycles_error(adjacency_list, concept_definitions) -> str:
151
+ """Describe the elementary cycles of the concept graph, at most MAX_REPORTED_CYCLES of them."""
152
+ order = list(concept_definitions)
153
+ position = {concept: index for index, concept in enumerate(order)}
154
+ mentions: Dict[str, List[str]] = {concept: [] for concept in order}
155
+ for mentioned, defined_list in adjacency_list.items():
156
+ for defined in defined_list:
157
+ mentions.setdefault(defined, []).append(mentioned)
158
+ mentions.setdefault(mentioned, [])
159
+
160
+ found = list(simple_cycles(mentions, limit=MAX_REPORTED_CYCLES + 1))
161
+ found.sort(key=lambda cycle: (position.get(cycle[0], len(position)), len(cycle)))
162
+ shown = found[:MAX_REPORTED_CYCLES]
163
+
164
+ if len(found) > MAX_REPORTED_CYCLES:
146
165
  head = (
147
166
  f"Plain syntax error: Found more than {MAX_REPORTED_CYCLES} cycles in concept definitions. "
148
167
  f"Cycles are not allowed.\nShowing the first {MAX_REPORTED_CYCLES}."
149
168
  )
150
169
  else:
151
- head = f"Plain syntax error: Found {len(cycles)} cycle(s) in concept definitions. Cycles are not allowed."
152
- parts = [head]
153
- for number, cycle in enumerate(cycles, 1):
154
- lines = [f"Cycle {number}: {' -> '.join(':' + c + ':' for c in [*cycle, cycle[0]])}"]
155
- seen: list[int] = []
170
+ head = f"Plain syntax error: Found {len(shown)} cycle(s) in concept definitions. Cycles are not allowed."
171
+
172
+ blocks = [head]
173
+ for number, cycle in enumerate(shown, start=1):
174
+ lines = [f"Cycle {number}: {' -> '.join([*cycle, cycle[0]])}"]
175
+ texts: List[str] = []
156
176
  for concept in cycle:
157
- item = concept_definitions[concept]
158
- if id(item) not in seen:
159
- seen.append(id(item))
160
- lines.append(item["markdown"])
161
- parts.append("\n".join(lines))
162
- return "\n\n".join(parts)
177
+ text = _item_markdown(concept_definitions[concept]) if concept in concept_definitions else None
178
+ if text is not None and text not in texts:
179
+ texts.append(text)
180
+ lines.extend(texts)
181
+ blocks.append("\n".join(lines))
182
+ return "\n\n".join(blocks)
163
183
 
164
184
 
165
- def sort_definitions(definitions: list[dict[str, Any]]) -> None:
166
- """Sort definition items in place so each concept follows the concepts its definition mentions."""
167
- if len(definitions) <= 1:
185
+ def sort_definitions(definitions: List[dict]) -> None:
186
+ """Sort definition items in place so that every concept comes after the concepts its definition mentions."""
187
+ if len(definitions) < 2:
168
188
  return
169
- from graphlib import TopologicalSorter
170
-
171
- from plain_parser.exceptions import PlainSyntaxError
172
-
173
189
  adjacency, concept_definitions = build_adjacency_list(definitions)
174
- message = format_cycles_error(adjacency, concept_definitions)
175
- if message:
176
- raise PlainSyntaxError(message)
177
- sorter: TopologicalSorter[str] = TopologicalSorter()
178
- for concept, successors in adjacency.items():
190
+ sorter: graphlib.TopologicalSorter = graphlib.TopologicalSorter()
191
+ for concept, dependents in adjacency.items():
179
192
  sorter.add(concept)
180
- for successor in successors:
181
- sorter.add(successor, concept)
182
- order = {concept: index for index, concept in enumerate(sorter.static_order())}
183
-
184
- def key(item: dict[str, Any]) -> int:
185
- defined, _ = extract_concepts_from_definition(item["markdown"])
186
- return max((order[c] for c in defined), default=len(order))
193
+ for dependent in dependents:
194
+ sorter.add(dependent, concept)
195
+ try:
196
+ order = list(sorter.static_order())
197
+ except graphlib.CycleError as error:
198
+ raise PlainSyntaxError(format_cycles_error(adjacency, concept_definitions)) from error
199
+ position = {concept: index for index, concept in enumerate(order)}
200
+
201
+ def key(item: dict) -> int:
202
+ defined, _ = extract_concepts_from_definition(_item_markdown(item))
203
+ return max((position[concept] for concept in defined), default=len(position))
187
204
 
188
205
  definitions.sort(key=key)
plain_parser/graph.py CHANGED
@@ -1,132 +1,168 @@
1
- """Strongly connected components (Tarjan) and simple cycles (Johnson), both without recursion."""
1
+ """Strongly connected components and simple cycles of a directed graph, without recursion."""
2
2
 
3
- from typing import Dict, Hashable, Iterable, Iterator, List, Mapping, Optional, Set, TypeVar
3
+ import heapq
4
+ from typing import Dict, Hashable, Iterable, Iterator, List, Mapping, Optional, Set, Tuple, TypeVar
4
5
 
5
6
  Node = TypeVar("Node", bound=Hashable)
6
7
 
7
8
 
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] = {}
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] = {}
26
32
  low: Dict[Node, int] = {}
27
33
  on_stack: Set[Node] = set()
28
34
  stack: List[Node] = []
29
- result: List[Set[Node]] = []
35
+ components: List[Set[Node]] = []
30
36
  counter = 0
37
+
31
38
  for root in nodes:
32
- if root in index:
39
+ if root in index_of:
33
40
  continue
34
- index[root] = low[root] = counter
41
+ index_of[root] = low[root] = counter
35
42
  counter += 1
36
43
  stack.append(root)
37
44
  on_stack.add(root)
38
- frames = [(root, iter(adj[root]))]
45
+ frames: List[List] = [[root, 0]]
39
46
  while frames:
40
- v, it = frames[-1]
41
- for w in it:
42
- if w not in index:
43
- index[w] = low[w] = counter
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
44
59
  counter += 1
45
- stack.append(w)
46
- on_stack.add(w)
47
- frames.append((w, iter(adj[w])))
60
+ stack.append(successor)
61
+ on_stack.add(successor)
62
+ frames.append([successor, 0])
63
+ descended = True
48
64
  break
49
- if w in on_stack:
50
- low[v] = min(low[v], index[w])
51
- else:
52
- frames.pop()
53
- if frames:
54
- parent = frames[-1][0]
55
- low[parent] = min(low[parent], low[v])
56
- if low[v] == index[v]:
57
- comp: Set[Node] = set()
58
- while True:
59
- w = stack.pop()
60
- on_stack.discard(w)
61
- comp.add(w)
62
- if w == v:
63
- break
64
- result.append(comp)
65
- return result
66
-
67
-
68
- def strongly_connected_components(graph: Mapping[Node, Iterable[Node]]) -> list[set[Node]]:
69
- nodes, adj = _normalize(graph)
70
- return _tarjan(nodes, adj)
71
-
72
-
73
- def simple_cycles(graph: Mapping[Node, Iterable[Node]], limit: Optional[int] = None) -> Iterator[list[Node]]:
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)
82
+ return components
83
+
84
+
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
+
90
+
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]]
99
+
100
+ def unblock(node: Node) -> None:
101
+ pending = [node]
102
+ while pending:
103
+ current = pending.pop()
104
+ if current in blocked:
105
+ blocked.discard(current)
106
+ pending.extend(blocked_by[current])
107
+ blocked_by[current].clear()
108
+
109
+ while frames:
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)
127
+ else:
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."""
74
136
  if limit is not None and limit <= 0:
75
137
  return
76
- nodes, adj = _normalize(graph)
138
+ nodes, adjacency = _normalize(graph)
139
+ position = {node: i for i, node in enumerate(nodes)}
77
140
  yielded = 0
78
- for n in nodes:
79
- if n in adj[n]:
80
- yield [n]
141
+
142
+ for node in nodes:
143
+ if node in adjacency[node]:
144
+ yield [node]
81
145
  yielded += 1
82
146
  if limit is not None and yielded >= limit:
83
147
  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)
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)