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.
@@ -1,241 +1,188 @@
1
- import re
2
- from copy import deepcopy
3
- from graphlib import CycleError, TopologicalSorter
4
- from typing import Optional
5
-
6
- import mistletoe.block_token
1
+ """Concept extraction and validation for plain source trees."""
7
2
 
8
- from plain_parser import graph, plain_spec
9
- from plain_parser.exceptions import PlainSyntaxError
3
+ import re
4
+ from typing import Any
10
5
 
11
- # These are reserved concept names that are pre-defined and must not be redefined in the definitions section.
12
6
  DEFAULT_CONCEPTS = {
13
- ":ConformanceTests:",
14
- ":UnitTests:",
15
- ":AcceptanceTest:",
16
- ":AcceptanceTests:",
17
- ":Implementation:",
18
- ":plainDefinitions:",
19
- ":plainImplementationReqs:",
20
- ":plainFunctionality:",
21
- ":plainTestReqs:",
22
- ":plainImplementationCode:",
7
+ "ConformanceTests",
8
+ "UnitTests",
9
+ "AcceptanceTest",
10
+ "AcceptanceTests",
11
+ "Implementation",
12
+ "plainDefinitions",
13
+ "plainImplementationReqs",
14
+ "plainFunctionality",
15
+ "plainTestReqs",
16
+ "plainImplementationCode",
23
17
  }
24
18
 
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*:[^:]*:)*)")
25
23
 
26
- def extract_concepts_from_definition(text: str) -> tuple[list[str], list[str]]:
27
- pattern = r"-\s(:[^\:]+:)(?:,\s*:[^\:]+:)*"
28
- match = re.search(pattern, text)
29
24
 
30
- if not match:
31
- return list(), [
32
- f"Syntax error: Invalid definition specification text: {text}. Should start with `- :<concept>:` (where <concept> is any string that does not contain `:`)."
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)
28
+ if match is None:
29
+ return [], [
30
+ f"Syntax error: Invalid definition specification text: {text}. "
31
+ "Should start with `- :<concept>:` (where <concept> is any string that does not contain `:`)."
33
32
  ]
34
-
35
- concept_candidates = re.findall(r":[^\:]+:", match.group())
36
- valid_concepts = list[str]()
37
- concept_re = r":[+\-\.0-9A-Z_a-z]+:"
38
- errors = list[str]()
39
- for candidate in concept_candidates:
40
- if re.match(concept_re, candidate):
41
- valid_concepts.append(candidate)
33
+ concepts: list[str] = []
34
+ errors: list[str] = []
35
+ for candidate in re.findall(r":([^:]*):", match.group(1)):
36
+ if _CONCEPT_RE.fullmatch(candidate):
37
+ concepts.append(candidate)
42
38
  else:
43
39
  errors.append(
44
- f"Syntax error: Invalid concept: {candidate}. Should contain only letters, numbers, hyphens and dots."
40
+ f"Syntax error: Invalid concept: :{candidate}:. Should contain only letters, numbers, hyphens and dots."
45
41
  )
46
-
47
- return valid_concepts, errors
48
-
49
-
50
- def extract_concepts_from_spec_text(text: str) -> str:
51
- return re.findall(r":[+\-\.0-9A-Z_a-z]+:", text)
42
+ return concepts, errors
52
43
 
53
44
 
54
- def collect_concepts(plain_source) -> tuple[set[str], list[str]]:
55
- if plain_spec.DEFINITIONS not in plain_source:
56
- return set(), list()
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)
57
48
 
58
- concepts = list[str]()
59
- errors = list[str]()
60
- for definition in plain_source[plain_spec.DEFINITIONS]:
61
- spec_text = definition["markdown"]
62
- new_concepts, new_errors = extract_concepts_from_definition(spec_text)
63
- errors.extend(new_errors)
64
- concepts.extend(new_concepts)
65
49
 
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)
66
58
  return concepts, errors
67
59
 
68
60
 
69
- def validate_concepts_in_spec(spec: dict, concepts: set[str], spec_group: str) -> list[str]:
70
- spec_text = spec["markdown"]
71
- used_concepts = extract_concepts_from_spec_text(spec_text)
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."""
72
63
  errors = []
73
- for used_concept in used_concepts:
74
- if used_concept not in concepts and used_concept not in DEFAULT_CONCEPTS:
64
+ for concept in extract_concepts_from_spec_text(spec["markdown"]):
65
+ if concept not in concepts and concept not in DEFAULT_CONCEPTS:
75
66
  errors.append(
76
- f"Syntax error: Concept {used_concept} is not defined in the definitions. {spec_group}: {spec_text}"
67
+ f"Syntax error: Concept :{concept}: is not defined in the definitions. {spec_group}: {spec['markdown']}"
77
68
  )
78
-
79
69
  return errors
80
70
 
81
71
 
82
- def validate_concepts_in_spec_group(spec_group, plain_source, concepts: set[str]) -> list[str]:
83
- if spec_group not in plain_source:
84
- return []
85
-
86
- errors = []
87
- for spec in plain_source[spec_group]:
72
+ def validate_concepts_in_spec_group(spec_group: str, plain_source: dict[str, Any], concepts: set[str]) -> list[str]:
73
+ errors: list[str] = []
74
+ for spec in plain_source.get(spec_group, []):
88
75
  errors.extend(validate_concepts_in_spec(spec, concepts, spec_group))
89
-
90
76
  return errors
91
77
 
92
78
 
93
- def validate_concepts(marshalled_plain_source) -> list[str]:
94
- errors = list[str]()
95
- concepts = deepcopy(DEFAULT_CONCEPTS)
96
- tree_based_concepts = deepcopy(DEFAULT_CONCEPTS)
97
-
98
- new_concepts, new_errors = collect_concepts(marshalled_plain_source)
99
- errors.extend(new_errors)
100
-
101
- unique_new_concepts = set(new_concepts)
102
- intersection = unique_new_concepts.intersection(concepts)
103
-
104
- if len(unique_new_concepts) < len(new_concepts) or (len(intersection) > 0):
105
- misused_concepts = {concept for concept in new_concepts if new_concepts.count(concept) > 1}
106
- misused_concepts.update(intersection)
107
- errors.append(f"Syntax error: Concepts were defined multiple times: {', '.join(misused_concepts)} .")
108
-
109
- concepts.update(unique_new_concepts)
110
- tmp_tree_based_concepts = tree_based_concepts.union(unique_new_concepts)
111
-
112
- for spec_group in [
113
- plain_spec.NON_FUNCTIONAL_REQUIREMENTS,
114
- plain_spec.TEST_REQUIREMENTS,
115
- plain_spec.FUNCTIONAL_REQUIREMENTS,
116
- plain_spec.DEFINITIONS,
117
- ]:
118
- errors.extend(validate_concepts_in_spec_group(spec_group, marshalled_plain_source, tmp_tree_based_concepts))
119
-
79
+ def validate_concepts(marshalled_plain_source: dict[str, Any]) -> list[str]:
80
+ """Validate the concepts of a tree; empty list when valid."""
81
+ 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
+ defined = set(concepts)
94
+ for group in ("implementation reqs", "test reqs", "functional specs", "definitions"):
95
+ errors.extend(validate_concepts_in_spec_group(group, marshalled_plain_source, defined))
120
96
  return errors
121
97
 
122
98
 
123
- def find_concept_definitions_in_plain_source(
124
- concept: str,
125
- plain_source: dict,
126
- renderer,
127
- ) -> list[mistletoe.block_token.token]:
128
- definitions = list[mistletoe.block_token.token]()
129
- if plain_source[plain_spec.DEFINITIONS] is None:
130
- return definitions
131
-
132
- for definition in plain_source[plain_spec.DEFINITIONS].children:
133
- rendered_definition = renderer.render(definition)
134
- defined_concepts, _ = extract_concepts_from_definition(rendered_definition)
135
- if concept in defined_concepts:
136
- definitions.append(definition)
137
- used_concepts = [
138
- used_concept
139
- for used_concept in extract_concepts_from_spec_text(rendered_definition)
140
- if used_concept != concept and used_concept not in DEFAULT_CONCEPTS
141
- ]
142
- for used_concept in used_concepts:
143
- definitions.extend(find_concept_definitions_in_plain_source(used_concept, plain_source, renderer))
144
-
145
- return definitions
146
-
147
-
148
- def build_adjacency_list(definitions: Optional[list[dict]]) -> tuple[dict, dict]:
149
- adjacency_list = dict[str, list[str]]()
150
- concept_definitions = dict[str, dict]()
151
- if definitions is None or len(definitions) == 0:
152
- return adjacency_list, concept_definitions
153
-
154
- for definition in definitions:
155
- def_text = definition["markdown"]
156
- new_concepts, _ = extract_concepts_from_definition(def_text)
157
- used_concepts = [
158
- used_concept
159
- for used_concept in extract_concepts_from_spec_text(def_text)
160
- if used_concept not in new_concepts and used_concept not in DEFAULT_CONCEPTS
161
- ]
162
- used_concepts = set(used_concepts)
163
-
164
- for new_concept in new_concepts:
165
- if new_concept not in adjacency_list:
166
- adjacency_list[new_concept] = []
167
-
168
- for used_concept in used_concepts:
169
- if used_concept not in adjacency_list:
170
- adjacency_list[used_concept] = []
171
-
172
- adjacency_list[used_concept].extend(new_concepts)
173
-
174
- for new_concept in new_concepts:
175
- concept_definitions[new_concept] = definition
176
-
177
- return adjacency_list, concept_definitions
178
-
179
-
180
99
  MAX_REPORTED_CYCLES = 10
181
100
 
182
101
 
183
- def format_cycles_error(adjacency_list: dict[str, list[str]], concept_definitions: dict[str, dict]) -> str:
184
- """
185
- List the elementary cycles in the graph, each as a "Cycle N: :A: -> :B: -> :A:" line
186
- followed by the definition of every concept in the cycle. Arrows point from a definition
187
- to a concept it mentions, each cycle starts at its earliest-defined concept, and cycles
188
- are ordered by definition position, so the report reads top to bottom like the file.
189
- At most MAX_REPORTED_CYCLES are listed; the search stops once one more than that is found.
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).
104
+
105
+ The graph maps a concept to the concepts whose definitions mention it.
190
106
  """
191
- position = {concept: index for index, concept in enumerate(concept_definitions)}
192
- cycles = []
193
- # key the graph in definition order so a search cut short by the limit has found the earliest cycles
194
- by_position = {concept: adjacency_list[concept] for concept in [*concept_definitions, *adjacency_list]}
195
- for cycle in graph.simple_cycles(by_position, limit=MAX_REPORTED_CYCLES + 1):
196
- # reverse since simple_cycles edges point from a used concept to the one defined with it
197
- cycle = cycle[::-1]
198
- first = min(range(len(cycle)), key=lambda i: position[cycle[i]])
199
- cycles.append(cycle[first:] + cycle[:first])
200
- cycles.sort(key=lambda cycle: (position[cycle[0]], len(cycle), [position[c] for c in cycle]))
201
-
202
- if len(cycles) > MAX_REPORTED_CYCLES:
203
- cycles = cycles[:MAX_REPORTED_CYCLES]
204
- lines = [
205
- f"Plain syntax error: Found more than {MAX_REPORTED_CYCLES} cycles in concept definitions. Cycles are not allowed.",
206
- f"Showing the first {MAX_REPORTED_CYCLES}.",
207
- ]
107
+ adjacency: dict[str, list[str]] = {}
108
+ concept_definitions: dict[str, dict[str, Any]] = {}
109
+ for item in definitions:
110
+ defined, _ = extract_concepts_from_definition(item["markdown"])
111
+ for concept in defined:
112
+ 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)
118
+ for concept in mentioned:
119
+ adjacency.setdefault(concept, [])
120
+ for concept in mentioned:
121
+ for target in defined:
122
+ if target not in adjacency[concept]:
123
+ adjacency[concept].append(target)
124
+ return adjacency, concept_definitions
125
+
126
+
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:
146
+ head = (
147
+ f"Plain syntax error: Found more than {MAX_REPORTED_CYCLES} cycles in concept definitions. "
148
+ f"Cycles are not allowed.\nShowing the first {MAX_REPORTED_CYCLES}."
149
+ )
208
150
  else:
209
- lines = [f"Plain syntax error: Found {len(cycles)} cycle(s) in concept definitions. Cycles are not allowed."]
210
- for number, cycle in enumerate(cycles, start=1):
211
- lines.append("")
212
- lines.append(f"Cycle {number}: " + " -> ".join(cycle + [cycle[0]]))
213
- # concepts defined on one line can share a cycle; print that line once
214
- lines.extend(dict.fromkeys(concept_definitions[concept]["markdown"] for concept in cycle))
215
- return "\n".join(lines)
216
-
217
-
218
- def sort_definitions(definitions: list[dict]) -> list[dict]:
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] = []
156
+ 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)
163
+
164
+
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."""
219
167
  if len(definitions) <= 1:
220
168
  return
169
+ from graphlib import TopologicalSorter
221
170
 
222
- adjacency_list, concept_definitions = build_adjacency_list(definitions)
171
+ from plain_parser.exceptions import PlainSyntaxError
223
172
 
224
- # adjacency_list maps a used concept to the concepts defined in terms of it,
225
- # so the used concept is a predecessor of each of them
173
+ adjacency, concept_definitions = build_adjacency_list(definitions)
174
+ message = format_cycles_error(adjacency, concept_definitions)
175
+ if message:
176
+ raise PlainSyntaxError(message)
226
177
  sorter: TopologicalSorter[str] = TopologicalSorter()
227
- for node, neighbors in adjacency_list.items():
228
- sorter.add(node)
229
- for neighbour in neighbors:
230
- sorter.add(neighbour, node)
231
-
232
- try:
233
- order = list(sorter.static_order())
234
- except CycleError:
235
- raise PlainSyntaxError(format_cycles_error(adjacency_list, concept_definitions)) from None
236
-
237
- if len(order) > 0:
238
- definition_to_order_idx = {
239
- plain_spec.hash_text(str(concept_definitions[concept])): idx for idx, concept in enumerate(order)
240
- }
241
- definitions.sort(key=lambda definition: definition_to_order_idx[plain_spec.hash_text(str(definition))])
178
+ for concept, successors in adjacency.items():
179
+ 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))
187
+
188
+ definitions.sort(key=key)
@@ -1,3 +1,6 @@
1
+ """Error classes of plain-parser."""
2
+
3
+
1
4
  class PlainSyntaxError(Exception):
2
5
  pass
3
6
 
@@ -23,23 +26,12 @@ class ModuleDoesNotExistError(Exception):
23
26
 
24
27
 
25
28
  class MissingFunctionalitiesError(Exception):
26
- """Raised when a module to be rendered has no functionalities specified at all."""
27
-
28
29
  pass
29
30
 
30
31
 
31
32
  class ImportedModuleWithFunctionalitiesError(Exception):
32
- """Raised when a module brought in via ``import`` contains functional specs.
33
-
34
- This is a usage error, not a syntax error: the module is syntactically valid
35
- and would be fine as a render target, but functionalities are not allowed in
36
- the import role.
37
- """
38
-
39
33
  pass
40
34
 
41
35
 
42
36
  class MissingTestPlainFileError(Exception):
43
- """Raised when conformance tests are enabled and a functionality has no test plain file bound to it."""
44
-
45
37
  pass