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.
- plain_parser/__init__.py +3 -3
- plain_parser/cli.py +194 -163
- plain_parser/concept_utils.py +141 -124
- plain_parser/graph.py +145 -109
- plain_parser/liquid_nodes.py +25 -43
- plain_parser/loaders.py +103 -90
- plain_parser/plain_file.py +614 -530
- plain_parser/plain_spec.py +135 -134
- plain_parser/project.py +94 -80
- plain_parser/test_plain_file.py +195 -175
- {plain_parser-1.0.0.dev1.dist-info → plain_parser-1.0.0.dev2.dist-info}/METADATA +15 -2
- plain_parser-1.0.0.dev2.dist-info/RECORD +16 -0
- plain_parser-1.0.0.dev2.dist-info/licenses/LICENSE +21 -0
- plain_parser-1.0.0.dev1.dist-info/RECORD +0 -15
- {plain_parser-1.0.0.dev1.dist-info → plain_parser-1.0.0.dev2.dist-info}/WHEEL +0 -0
- {plain_parser-1.0.0.dev1.dist-info → plain_parser-1.0.0.dev2.dist-info}/entry_points.txt +0 -0
plain_parser/concept_utils.py
CHANGED
|
@@ -1,120 +1,143 @@
|
|
|
1
|
-
"""
|
|
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
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
"
|
|
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
|
-
|
|
21
|
-
|
|
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) ->
|
|
26
|
-
"""Return
|
|
27
|
-
match =
|
|
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:
|
|
34
|
-
errors:
|
|
35
|
-
for candidate in re.findall(r":
|
|
36
|
-
if
|
|
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:
|
|
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) ->
|
|
46
|
-
"""Return every concept token
|
|
47
|
-
return
|
|
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
|
|
51
|
-
""
|
|
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
|
|
62
|
-
"""
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
|
|
73
|
-
|
|
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
|
|
80
|
-
"""Validate the concepts of a tree
|
|
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 (
|
|
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
|
-
|
|
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
|
|
103
|
-
"""
|
|
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
|
|
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:
|
|
108
|
-
concept_definitions:
|
|
128
|
+
adjacency: Dict[str, List[str]] = {}
|
|
129
|
+
concept_definitions: Dict[str, Any] = {}
|
|
109
130
|
for item in definitions:
|
|
110
|
-
|
|
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
|
|
114
|
-
mentioned
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
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
|
|
128
|
-
"""
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
for
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
found = list(simple_cycles(
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
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(
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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
|
-
|
|
158
|
-
if
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
return "\n\n".join(
|
|
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:
|
|
166
|
-
"""Sort definition items in place so
|
|
167
|
-
if len(definitions)
|
|
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
|
-
|
|
175
|
-
|
|
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
|
|
181
|
-
sorter.add(
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
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
|
|
1
|
+
"""Strongly connected components and simple cycles of a directed graph, without recursion."""
|
|
2
2
|
|
|
3
|
-
|
|
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]]) ->
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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
|
-
|
|
35
|
+
components: List[Set[Node]] = []
|
|
30
36
|
counter = 0
|
|
37
|
+
|
|
31
38
|
for root in nodes:
|
|
32
|
-
if root in
|
|
39
|
+
if root in index_of:
|
|
33
40
|
continue
|
|
34
|
-
|
|
41
|
+
index_of[root] = low[root] = counter
|
|
35
42
|
counter += 1
|
|
36
43
|
stack.append(root)
|
|
37
44
|
on_stack.add(root)
|
|
38
|
-
frames = [
|
|
45
|
+
frames: List[List] = [[root, 0]]
|
|
39
46
|
while frames:
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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(
|
|
46
|
-
on_stack.add(
|
|
47
|
-
frames.append(
|
|
60
|
+
stack.append(successor)
|
|
61
|
+
on_stack.add(successor)
|
|
62
|
+
frames.append([successor, 0])
|
|
63
|
+
descended = True
|
|
48
64
|
break
|
|
49
|
-
if
|
|
50
|
-
low[
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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,
|
|
138
|
+
nodes, adjacency = _normalize(graph)
|
|
139
|
+
position = {node: i for i, node in enumerate(nodes)}
|
|
77
140
|
yielded = 0
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
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
|
-
|
|
85
|
-
for s in
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
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)
|