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.
@@ -1,15 +1,19 @@
1
- import re
2
- from copy import deepcopy
3
- from graphlib import CycleError, TopologicalSorter
4
- from typing import Optional
1
+ """Concepts of a specification: extracting, validating and ordering their definitions."""
5
2
 
6
- import mistletoe.block_token
3
+ import graphlib
4
+ import re
5
+ from typing import Any, Dict, List, Set, Tuple
7
6
 
8
- from plain_parser import graph, plain_spec
9
7
  from plain_parser.exceptions import PlainSyntaxError
10
-
11
- # These are reserved concept names that are pre-defined and must not be redefined in the definitions section.
12
- DEFAULT_CONCEPTS = {
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] = {
13
17
  ":ConformanceTests:",
14
18
  ":UnitTests:",
15
19
  ":AcceptanceTest:",
@@ -21,221 +25,181 @@ DEFAULT_CONCEPTS = {
21
25
  ":plainTestReqs:",
22
26
  ":plainImplementationCode:",
23
27
  }
28
+ MAX_REPORTED_CYCLES = 10
24
29
 
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]+:)*)")
25
33
 
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
34
 
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 `:`)."
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)
38
+ if match is None:
39
+ return [], [
40
+ f"Syntax error: Invalid definition specification text: {text}. "
41
+ "Should start with `- :<concept>:` (where <concept> is any string that does not contain `:`)."
33
42
  ]
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)
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]):
47
+ concepts.append(candidate)
42
48
  else:
43
49
  errors.append(
44
- 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."
45
52
  )
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)
53
+ return concepts, errors
52
54
 
53
55
 
54
- def collect_concepts(plain_source) -> tuple[set[str], list[str]]:
55
- if plain_spec.DEFINITIONS not in plain_source:
56
- return set(), list()
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)
57
59
 
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
60
 
66
- return concepts, errors
61
+ def _item_markdown(item: Any) -> str:
62
+ return item["markdown"] if isinstance(item, dict) else str(item)
67
63
 
68
64
 
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)
72
- errors = []
73
- for used_concept in used_concepts:
74
- if used_concept not in concepts and used_concept not in DEFAULT_CONCEPTS:
75
- errors.append(
76
- f"Syntax error: Concept {used_concept} is not defined in the definitions. {spec_group}: {spec_text}"
77
- )
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
78
82
 
79
- return errors
80
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
+ ]
81
92
 
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
93
 
86
- errors = []
87
- for spec in plain_source[spec_group]:
94
+ def validate_concepts_in_spec_group(spec_group, plain_source, concepts: Set[str]) -> List[str]:
95
+ errors: List[str] = []
96
+ for spec in plain_source.get(spec_group, []):
88
97
  errors.extend(validate_concepts_in_spec(spec, concepts, spec_group))
89
-
90
98
  return errors
91
99
 
92
100
 
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
-
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."""
103
+ concepts, errors = collect_concepts(marshalled_plain_source)
104
+ defined = set(concepts)
105
+ for group in (NON_FUNCTIONAL_REQUIREMENTS, TEST_REQUIREMENTS, FUNCTIONAL_REQUIREMENTS, DEFINITIONS):
106
+ errors.extend(validate_concepts_in_spec_group(group, marshalled_plain_source, defined))
120
107
  return errors
121
108
 
122
109
 
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
-
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
179
120
 
180
- MAX_REPORTED_CYCLES = 10
181
121
 
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.
182
124
 
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.
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.
190
127
  """
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}.",
128
+ adjacency: Dict[str, List[str]] = {}
129
+ concept_definitions: Dict[str, Any] = {}
130
+ for item in definitions:
131
+ markdown = _item_markdown(item)
132
+ defined, _ = extract_concepts_from_definition(markdown)
133
+ for concept in defined:
134
+ adjacency.setdefault(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
207
140
  ]
141
+ for concept in mentioned:
142
+ adjacency.setdefault(concept, [])
143
+ for concept in mentioned:
144
+ for target in defined:
145
+ if target not in adjacency[concept]:
146
+ adjacency[concept].append(target)
147
+ return adjacency, concept_definitions
148
+
149
+
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:
165
+ head = (
166
+ f"Plain syntax error: Found more than {MAX_REPORTED_CYCLES} cycles in concept definitions. "
167
+ f"Cycles are not allowed.\nShowing the first {MAX_REPORTED_CYCLES}."
168
+ )
208
169
  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]:
219
- if len(definitions) <= 1:
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] = []
176
+ for concept in cycle:
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)
183
+
184
+
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:
220
188
  return
221
-
222
- adjacency_list, concept_definitions = build_adjacency_list(definitions)
223
-
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
226
- 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
-
189
+ adjacency, concept_definitions = build_adjacency_list(definitions)
190
+ sorter: graphlib.TopologicalSorter = graphlib.TopologicalSorter()
191
+ for concept, dependents in adjacency.items():
192
+ sorter.add(concept)
193
+ for dependent in dependents:
194
+ sorter.add(dependent, concept)
232
195
  try:
233
196
  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))])
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))
204
+
205
+ 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