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.
- plain_parser/__init__.py +1 -1
- plain_parser/cli.py +189 -215
- plain_parser/concept_utils.py +158 -194
- plain_parser/exceptions.py +3 -11
- plain_parser/graph.py +146 -142
- plain_parser/liquid_nodes.py +30 -94
- plain_parser/loaders.py +112 -101
- plain_parser/plain_file.py +635 -796
- plain_parser/plain_spec.py +153 -212
- plain_parser/project.py +123 -114
- plain_parser/test_plain_file.py +187 -184
- plain_parser-1.0.0.dev2.dist-info/METADATA +28 -0
- plain_parser-1.0.0.dev2.dist-info/RECORD +16 -0
- {plain_parser-0.2.1.dev23.dist-info → plain_parser-1.0.0.dev2.dist-info}/licenses/LICENSE +1 -1
- plain_parser-0.2.1.dev23.dist-info/METADATA +0 -145
- plain_parser-0.2.1.dev23.dist-info/RECORD +0 -16
- {plain_parser-0.2.1.dev23.dist-info → plain_parser-1.0.0.dev2.dist-info}/WHEEL +0 -0
- {plain_parser-0.2.1.dev23.dist-info → plain_parser-1.0.0.dev2.dist-info}/entry_points.txt +0 -0
plain_parser/plain_file.py
CHANGED
|
@@ -1,21 +1,17 @@
|
|
|
1
|
-
|
|
1
|
+
"""Parsing of spec plain files: sections, functionalities, imports, links, code variables and module checks."""
|
|
2
|
+
|
|
2
3
|
import os
|
|
3
|
-
|
|
4
|
-
from
|
|
5
|
-
from
|
|
6
|
-
from
|
|
4
|
+
import re
|
|
5
|
+
from contextlib import contextmanager
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any, Dict, Iterator, List, Optional, Set, Tuple
|
|
7
8
|
|
|
8
9
|
import frontmatter
|
|
9
|
-
import
|
|
10
|
-
import
|
|
11
|
-
from liquid2 import DictLoader, Environment
|
|
12
|
-
from mistletoe.block_token import Heading, List, Paragraph, Quote
|
|
10
|
+
from liquid2 import DictLoader
|
|
11
|
+
from mistletoe import Document, block_token, span_token
|
|
13
12
|
from mistletoe.markdown_renderer import BlankLine, Fragment, MarkdownRenderer
|
|
14
|
-
from mistletoe.span_token import Emphasis, Link, RawText, SpanToken, Strong
|
|
15
|
-
from mistletoe.token import Token
|
|
16
|
-
from mistletoe.utils import traverse
|
|
17
13
|
|
|
18
|
-
from plain_parser import concept_utils
|
|
14
|
+
from plain_parser import concept_utils
|
|
19
15
|
from plain_parser.exceptions import (
|
|
20
16
|
ImportedModuleWithFunctionalitiesError,
|
|
21
17
|
MissingFunctionalitiesError,
|
|
@@ -23,334 +19,69 @@ from plain_parser.exceptions import (
|
|
|
23
19
|
PlainSyntaxError,
|
|
24
20
|
UnsupportedBase64Content,
|
|
25
21
|
)
|
|
26
|
-
from plain_parser.liquid_nodes import
|
|
27
|
-
from plain_parser.loaders import find_large_base64_blob
|
|
22
|
+
from plain_parser.liquid_nodes import Plain2CodeLoaderMixin
|
|
23
|
+
from plain_parser.loaders import _render, find_large_base64_blob, make_environment, open_from, resolve_linked_resource
|
|
24
|
+
from plain_parser.plain_spec import (
|
|
25
|
+
ACCEPTANCE_TEST_HEADING,
|
|
26
|
+
ACCEPTANCE_TESTS,
|
|
27
|
+
ALLOWED_SPECIFICATION_HEADINGS,
|
|
28
|
+
CONFORMANCE_TEST_HEADING,
|
|
29
|
+
CONFORMANCE_TESTS,
|
|
30
|
+
DEFINITIONS,
|
|
31
|
+
FUNCTIONAL_REQUIREMENTS,
|
|
32
|
+
LIST_SECTION_HEADINGS,
|
|
33
|
+
NON_FUNCTIONAL_REQUIREMENTS,
|
|
34
|
+
is_semantic_id,
|
|
35
|
+
)
|
|
28
36
|
|
|
29
37
|
RESOURCE_MARKER = "[resource]"
|
|
30
|
-
|
|
31
38
|
IMPORT_DIRECTIVE = "import"
|
|
32
39
|
REQUIRES_DIRECTIVE = "requires"
|
|
33
|
-
PREVIOUS_SYNTAX_HINT = (
|
|
34
|
-
"A functionality is a `# <func-id>` heading followed by its body; the previous syntax is not supported."
|
|
35
|
-
)
|
|
36
40
|
REQUIRED_CONCEPTS_DIRECTIVE = "required_concepts"
|
|
37
41
|
EXPORTED_CONCEPTS_DIRECTIVE = "exported_concepts"
|
|
38
|
-
|
|
39
42
|
PLAIN_SOURCE_FILE_EXTENSION = ".plain"
|
|
40
43
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
class Functionality:
|
|
50
|
-
"""A functionality of ***functional specs***: its func-id and the block tokens of its body."""
|
|
51
|
-
|
|
52
|
-
id: str
|
|
53
|
-
line_number: int
|
|
54
|
-
# The statement paragraph and the lists under it, in source order.
|
|
55
|
-
body: list = field(default_factory=list)
|
|
56
|
-
linked_resources: list[dict] = field(default_factory=list)
|
|
44
|
+
_SECTION_LINE = re.compile(r"\*\*\*(.+)\*\*\*")
|
|
45
|
+
_TEST_SECTION_LINE = re.compile(
|
|
46
|
+
rf"^[ \t]*\*\*\*({re.escape(CONFORMANCE_TEST_HEADING)}|{re.escape(ACCEPTANCE_TEST_HEADING)})\*\*\*[ \t]*$",
|
|
47
|
+
re.MULTILINE,
|
|
48
|
+
)
|
|
49
|
+
_FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})")
|
|
50
|
+
_LIST_LEADER = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+")
|
|
51
|
+
_URL_SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
|
|
57
52
|
|
|
58
53
|
|
|
59
54
|
@dataclass
|
|
60
55
|
class PlainFileParseResult:
|
|
61
56
|
plain_source: dict
|
|
62
57
|
plain_source_obj: frontmatter.Post
|
|
63
|
-
required_modules:
|
|
64
|
-
required_concepts:
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
class PlainRenderer(MarkdownRenderer):
|
|
68
|
-
def render_link(self, token: Link) -> Iterable[Fragment]:
|
|
69
|
-
yield from self.embed_span(
|
|
70
|
-
Fragment(f"`{RESOURCE_MARKER}"),
|
|
71
|
-
cast("Iterable[SpanToken]", token.children),
|
|
72
|
-
Fragment("`"),
|
|
73
|
-
)
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
def get_filename_from_module_name(module_name: str) -> str:
|
|
77
|
-
return f"{module_name}{PLAIN_SOURCE_FILE_EXTENSION}"
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
def get_module_name_from_filename(filename: str) -> str:
|
|
81
|
-
return filename.replace(PLAIN_SOURCE_FILE_EXTENSION, "")
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
def remove_quotes(token):
|
|
85
|
-
# If the token has no children, there's nothing to remove.
|
|
86
|
-
if not hasattr(token, "children") or token.children is None:
|
|
87
|
-
return
|
|
88
|
-
|
|
89
|
-
# Convert children to a list for easy filtering.
|
|
90
|
-
children_list = list(token.children)
|
|
91
|
-
|
|
92
|
-
# Build a filtered list that excludes Quote tokens.
|
|
93
|
-
new_children = []
|
|
94
|
-
for child in children_list:
|
|
95
|
-
if not isinstance(child, Quote):
|
|
96
|
-
# Recursively remove quotes in any nested children.
|
|
97
|
-
remove_quotes(child)
|
|
98
|
-
new_children.append(child)
|
|
99
|
-
|
|
100
|
-
# Convert the filtered list back to a tuple (or a list, if you prefer).
|
|
101
|
-
# Mistletoe tokens often expect a tuple, so tuple is safest.
|
|
102
|
-
token.children = tuple(new_children)
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
def find_linked_resources(tokens, template_dirs, where: str = "") -> list[dict]:
|
|
106
|
-
"""The links in the tokens, each checked to be a relative path to an existing file that is not a .plain file.
|
|
107
|
-
|
|
108
|
-
``where`` names the place of the links in error messages, e.g. " in test plain file 'tests/m/f.plain'".
|
|
109
|
-
"""
|
|
110
|
-
linked_resources = []
|
|
111
|
-
for link in (link for token in tokens for link in traverse(token, klass=Link)):
|
|
112
|
-
parsed_url = urlparse(link.node.target)
|
|
113
|
-
if parsed_url.scheme != "" or os.path.isabs(link.node.target):
|
|
114
|
-
raise PlainSyntaxError(
|
|
115
|
-
f"Plain syntax error: Only relative links are allowed{where} (text: {link.node.children[0].content}, target: {link.node.target})."
|
|
116
|
-
)
|
|
117
|
-
|
|
118
|
-
resolved_target = loaders.resolve_linked_resource(template_dirs, link.node.target)
|
|
119
|
-
if resolved_target is None:
|
|
120
|
-
searched_dirs = "\n".join(f" {position}. {dir}" for position, dir in enumerate(template_dirs, start=1))
|
|
121
|
-
raise PlainSyntaxError(
|
|
122
|
-
f"Plain syntax error: Link {link.node.target}{where} does not exist. "
|
|
123
|
-
f"Linked resources are looked up relative to the following directories "
|
|
124
|
-
f"(highest to lowest precedence):\n{searched_dirs}"
|
|
125
|
-
)
|
|
126
|
-
|
|
127
|
-
if not os.path.isfile(resolved_target):
|
|
128
|
-
raise PlainSyntaxError(
|
|
129
|
-
f"Plain syntax error: Link {link.node.target}{where} must be a file (resolved to {resolved_target})."
|
|
130
|
-
)
|
|
131
|
-
|
|
132
|
-
if len(link.node.children) != 1:
|
|
133
|
-
raise PlainSyntaxError(
|
|
134
|
-
f"Plain syntax error: Link{where} must have text specified (link: {link.node.target})."
|
|
135
|
-
)
|
|
136
|
-
|
|
137
|
-
linked_resource_file_extension = os.path.splitext(os.path.basename(link.node.target))[1]
|
|
138
|
-
if linked_resource_file_extension == ".plain":
|
|
139
|
-
raise PlainSyntaxError(
|
|
140
|
-
f"Referenced resource '{link.node.target}'{where} is a .plain file. "
|
|
141
|
-
f"Referencing .plain files through Linked Resources is not supported. "
|
|
142
|
-
"Please use the import section to include definitions or implementation/test requirements from another module."
|
|
143
|
-
)
|
|
144
|
-
|
|
145
|
-
linked_resources.append({"text": link.node.children[0].content, "target": link.node.target})
|
|
146
|
-
|
|
147
|
-
return linked_resources
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
def check_section_for_linked_resources(section, template_dirs):
|
|
151
|
-
linked_resources = find_linked_resources([section], template_dirs)
|
|
152
|
-
if linked_resources:
|
|
153
|
-
section.linked_resources = linked_resources
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
def check_for_linked_resources(plain_source, template_dirs):
|
|
157
|
-
for specification_heading in plain_spec.LIST_SECTION_HEADINGS:
|
|
158
|
-
if specification_heading in plain_source and hasattr(plain_source[specification_heading], "children"):
|
|
159
|
-
for requirement in plain_source[specification_heading].children:
|
|
160
|
-
check_section_for_linked_resources(requirement, template_dirs)
|
|
161
|
-
|
|
162
|
-
for functionality in plain_source.get(plain_spec.FUNCTIONAL_REQUIREMENTS) or []:
|
|
163
|
-
functionality.linked_resources = find_linked_resources(functionality.body, template_dirs)
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
def process_section_code_variables(section, code_variables, text_key="markdown"):
|
|
167
|
-
"""Put `{{ name }}` placeholders back into the section text and record the code variables it uses."""
|
|
168
|
-
if text_key not in section:
|
|
169
|
-
return
|
|
170
|
-
|
|
171
|
-
code_variables_array = []
|
|
172
|
-
for key, value in code_variables.items():
|
|
173
|
-
if key not in section[text_key]:
|
|
174
|
-
continue
|
|
175
|
-
|
|
176
|
-
variable_name = next(iter(value))
|
|
177
|
-
section[text_key] = section[text_key].replace(key, f"{{{{ {variable_name} }}}}")
|
|
178
|
-
|
|
179
|
-
code_variables_array.append({"name": variable_name, "value": value[variable_name]})
|
|
180
|
-
|
|
181
|
-
if code_variables_array:
|
|
182
|
-
section["code_variables"] = code_variables_array
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
def process_code_variables(plain_source, code_variables):
|
|
186
|
-
for specification_heading in plain_spec.ALLOWED_SPECIFICATION_HEADINGS:
|
|
187
|
-
if specification_heading in plain_source:
|
|
188
|
-
for requirement in plain_source[specification_heading]:
|
|
189
|
-
process_section_code_variables(requirement, code_variables)
|
|
58
|
+
required_modules: List[str]
|
|
59
|
+
required_concepts: List[str]
|
|
190
60
|
|
|
191
61
|
|
|
192
|
-
|
|
193
|
-
"""
|
|
194
|
-
return plain_spec.FUNCTIONAL_REQUIREMENTS in plain_source
|
|
62
|
+
class _PlainMarkdownRenderer(MarkdownRenderer):
|
|
63
|
+
"""Markdown renderer that writes a link as a code span holding the resource marker and the link text."""
|
|
195
64
|
|
|
65
|
+
def render_link(self, token):
|
|
66
|
+
return self.embed_span(Fragment(f"`{RESOURCE_MARKER}"), token.children, Fragment("`"))
|
|
196
67
|
|
|
197
|
-
def count_functionalities(plain_source) -> int:
|
|
198
|
-
"""Number of functionalities under the ***functional specs*** section (0 if absent or empty)."""
|
|
199
|
-
functionalities = plain_source.get(plain_spec.FUNCTIONAL_REQUIREMENTS)
|
|
200
|
-
return len(functionalities) if functionalities is not None else 0
|
|
201
68
|
|
|
202
|
-
|
|
203
|
-
def validate_functionalities_have_implementation_reqs(plain_source, module_name, has_requires=False) -> None:
|
|
204
|
-
"""Raise if the module has functionalities but no implementation reqs are specified.
|
|
205
|
-
|
|
206
|
-
``has_requires`` indicates whether the module depends on another module via ``requires``.
|
|
207
|
-
Unlike ``import``, ``requires`` does not inherit implementation reqs, so a hint is added to
|
|
208
|
-
steer users who expected inheritance.
|
|
209
|
-
"""
|
|
210
|
-
implementation_reqs = plain_source[plain_spec.NON_FUNCTIONAL_REQUIREMENTS]
|
|
211
|
-
has_implementation_reqs = (
|
|
212
|
-
implementation_reqs is not None
|
|
213
|
-
and hasattr(implementation_reqs, "children")
|
|
214
|
-
and len(implementation_reqs.children) > 0
|
|
215
|
-
)
|
|
216
|
-
if not has_implementation_reqs:
|
|
217
|
-
message = (
|
|
218
|
-
f"Plain syntax error: Module '{module_name}' defines functionalities but specifies no "
|
|
219
|
-
f"{plain_spec.NON_FUNCTIONAL_REQUIREMENTS}. At least one implementation req is required."
|
|
220
|
-
)
|
|
221
|
-
if has_requires:
|
|
222
|
-
message += (
|
|
223
|
-
" Implementation reqs are not inherited through 'requires' — "
|
|
224
|
-
"add them to this module, or 'import' a module that provides them."
|
|
225
|
-
)
|
|
226
|
-
raise PlainSyntaxError(message)
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
def get_raw_text(token):
|
|
230
|
-
if isinstance(token, RawText):
|
|
231
|
-
yield token.content
|
|
232
|
-
elif hasattr(token, "children"):
|
|
233
|
-
if token.children is None:
|
|
234
|
-
return
|
|
235
|
-
for child in token.children:
|
|
236
|
-
yield from get_raw_text(child)
|
|
237
|
-
elif hasattr(token, "content"):
|
|
238
|
-
yield token.content
|
|
239
|
-
else:
|
|
240
|
-
raise Exception(f"Unknown token type: {type(token)}")
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
def render_tokens(renderer: MarkdownRenderer, tokens) -> str:
|
|
244
|
-
"""The block tokens rendered as one markdown text, without leading and trailing blank lines."""
|
|
245
|
-
document = mistletoe.Document("")
|
|
246
|
-
document.children = list(tokens)
|
|
247
|
-
return renderer.render(document).strip("\n")
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
def marshall_functionality(renderer: MarkdownRenderer, functionality: Functionality) -> dict:
|
|
251
|
-
return {
|
|
252
|
-
"id": functionality.id,
|
|
253
|
-
"markdown": render_tokens(renderer, functionality.body),
|
|
254
|
-
"linked_resources": functionality.linked_resources,
|
|
255
|
-
plain_spec.CONFORMANCE_TESTS: [],
|
|
256
|
-
plain_spec.ACCEPTANCE_TESTS: [],
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
def marshall_plain_source(input_plain_source):
|
|
261
|
-
plain_source = {}
|
|
262
|
-
with PlainRenderer() as renderer:
|
|
263
|
-
for specification_heading in plain_spec.LIST_SECTION_HEADINGS:
|
|
264
|
-
if specification_heading in input_plain_source and hasattr(
|
|
265
|
-
input_plain_source[specification_heading], "children"
|
|
266
|
-
):
|
|
267
|
-
list_of_requirements = []
|
|
268
|
-
for requirement in input_plain_source[specification_heading].children:
|
|
269
|
-
requirement_section = {"markdown": renderer.render(requirement).strip()}
|
|
270
|
-
if hasattr(requirement, "linked_resources"):
|
|
271
|
-
requirement_section["linked_resources"] = requirement.linked_resources
|
|
272
|
-
|
|
273
|
-
list_of_requirements.append(requirement_section)
|
|
274
|
-
|
|
275
|
-
plain_source[specification_heading] = list_of_requirements
|
|
276
|
-
|
|
277
|
-
if plain_spec.FUNCTIONAL_REQUIREMENTS in input_plain_source:
|
|
278
|
-
plain_source[plain_spec.FUNCTIONAL_REQUIREMENTS] = [
|
|
279
|
-
marshall_functionality(renderer, functionality)
|
|
280
|
-
for functionality in input_plain_source[plain_spec.FUNCTIONAL_REQUIREMENTS] or []
|
|
281
|
-
]
|
|
282
|
-
|
|
283
|
-
return plain_source
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
class Plain2CodeDictLoader(Plain2CodeLoaderMixin, DictLoader):
|
|
69
|
+
class _IndentingDictLoader(Plain2CodeLoaderMixin, DictLoader):
|
|
287
70
|
pass
|
|
288
71
|
|
|
289
72
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
env.filters["prohibited_chars"] = plain_spec.prohibited_chars_liquid_filter
|
|
295
|
-
|
|
296
|
-
template = env.from_string(plain_source)
|
|
297
|
-
|
|
298
|
-
return template.render(code_variables=code_variables)
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
def process_imports(
|
|
302
|
-
plain_source: dict,
|
|
303
|
-
imports: list[str],
|
|
304
|
-
code_variables: dict,
|
|
305
|
-
template_dirs: list[str],
|
|
306
|
-
imported_modules: list[str],
|
|
307
|
-
modules_trace: list[str],
|
|
308
|
-
) -> list[str]:
|
|
309
|
-
required_concepts = list[str]()
|
|
310
|
-
for module_name in imports:
|
|
311
|
-
if module_name in modules_trace:
|
|
312
|
-
raise PlainSyntaxError(f"Plain syntax error: Circular import detected: {module_name}.")
|
|
313
|
-
|
|
314
|
-
if module_name in imported_modules:
|
|
315
|
-
continue
|
|
316
|
-
|
|
317
|
-
plain_file_parse_result = parse_plain_file(
|
|
318
|
-
module_name, code_variables, template_dirs, imported_modules, modules_trace
|
|
319
|
-
)
|
|
320
|
-
|
|
321
|
-
if has_functional_specs_section(plain_file_parse_result.plain_source):
|
|
322
|
-
raise ImportedModuleWithFunctionalitiesError(
|
|
323
|
-
f"Module '{module_name}' is imported but contains functional specs. "
|
|
324
|
-
f"Imported modules may only provide definitions, implementation reqs, and test reqs — "
|
|
325
|
-
f"use 'requires' instead of 'import' if this module's functionalities should be built on."
|
|
326
|
-
)
|
|
327
|
-
|
|
328
|
-
for specification_heading in plain_file_parse_result.plain_source:
|
|
329
|
-
if specification_heading not in plain_spec.ALLOWED_IMPORT_SPECIFICATION_HEADINGS:
|
|
330
|
-
raise PlainSyntaxError(
|
|
331
|
-
f"Plain syntax error: Invalid specification heading (`{specification_heading}`). Allowed headings: {', '.join(plain_spec.ALLOWED_IMPORT_SPECIFICATION_HEADINGS)}"
|
|
332
|
-
)
|
|
333
|
-
|
|
334
|
-
if plain_source[specification_heading] is None:
|
|
335
|
-
plain_source[specification_heading] = plain_file_parse_result.plain_source[specification_heading]
|
|
336
|
-
elif plain_file_parse_result.plain_source[specification_heading] is not None:
|
|
337
|
-
plain_source[specification_heading].children.extend(
|
|
338
|
-
plain_file_parse_result.plain_source[specification_heading].children
|
|
339
|
-
)
|
|
73
|
+
@contextmanager
|
|
74
|
+
def _renderer() -> Iterator[_PlainMarkdownRenderer]:
|
|
75
|
+
with _PlainMarkdownRenderer() as renderer:
|
|
76
|
+
yield renderer
|
|
340
77
|
|
|
341
|
-
if REQUIRED_CONCEPTS_DIRECTIVE in plain_file_parse_result.plain_source_obj.metadata:
|
|
342
|
-
for item in plain_file_parse_result.plain_source_obj.metadata[REQUIRED_CONCEPTS_DIRECTIVE]:
|
|
343
|
-
assert isinstance(
|
|
344
|
-
item, str
|
|
345
|
-
), f"Syntax error: Invalid {REQUIRED_CONCEPTS_DIRECTIVE} metadata. Expected a string."
|
|
346
|
-
new_concepts, _ = concept_utils.extract_concepts_from_definition(item)
|
|
347
|
-
required_concepts.extend(new_concepts)
|
|
348
78
|
|
|
349
|
-
|
|
79
|
+
def get_filename_from_module_name(module_name: str) -> str:
|
|
80
|
+
return module_name + PLAIN_SOURCE_FILE_EXTENSION
|
|
350
81
|
|
|
351
|
-
imported_modules.append(module_name)
|
|
352
82
|
|
|
353
|
-
|
|
83
|
+
def get_module_name_from_filename(filename: str) -> str:
|
|
84
|
+
return filename.replace(PLAIN_SOURCE_FILE_EXTENSION, "")
|
|
354
85
|
|
|
355
86
|
|
|
356
87
|
def normalize_line_endings(plain_source_text: str) -> str:
|
|
@@ -358,559 +89,667 @@ def normalize_line_endings(plain_source_text: str) -> str:
|
|
|
358
89
|
|
|
359
90
|
|
|
360
91
|
def restore_stripped_lines(plain_source_text: str, content: str) -> str:
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
92
|
+
"""Give the content the blank lines the frontmatter reader stripped, so that its line numbers are the file's."""
|
|
93
|
+
end = len(plain_source_text.rstrip())
|
|
94
|
+
trailing = plain_source_text[end:]
|
|
95
|
+
if not content:
|
|
96
|
+
return "\n" * plain_source_text.count("\n")
|
|
97
|
+
start = max(end - len(content), 0)
|
|
98
|
+
return "\n" * plain_source_text.count("\n", 0, start) + content + trailing
|
|
99
|
+
|
|
364
100
|
|
|
365
|
-
|
|
366
|
-
|
|
101
|
+
def render_plain_source(plain_source, loaded_templates, code_variables) -> str:
|
|
102
|
+
"""Render a text with Liquid over already loaded templates, recording code variables in the mapping."""
|
|
103
|
+
environment = make_environment(_IndentingDictLoader(loaded_templates))
|
|
104
|
+
return environment.from_string(plain_source).render(code_variables=code_variables)
|
|
367
105
|
|
|
368
106
|
|
|
369
|
-
def
|
|
370
|
-
"""`Syntax error at line N in module 'm'`, without the parts that are not known."""
|
|
107
|
+
def _where(line: Optional[int], module_name: Optional[str]) -> str:
|
|
371
108
|
where = "Syntax error"
|
|
372
|
-
if
|
|
373
|
-
where += f" at line {
|
|
109
|
+
if line is not None:
|
|
110
|
+
where += f" at line {line}"
|
|
374
111
|
if module_name:
|
|
375
112
|
where += f" in module '{module_name}'"
|
|
376
113
|
return where
|
|
377
114
|
|
|
378
115
|
|
|
379
|
-
def
|
|
380
|
-
|
|
381
|
-
plain_source_obj = frontmatter.loads(plain_source_text)
|
|
382
|
-
except Exception as e:
|
|
383
|
-
raise PlainSyntaxError(f"Plain syntax error: Invalid frontmatter: {e}")
|
|
384
|
-
|
|
385
|
-
for directive in [EXPORTED_CONCEPTS_DIRECTIVE, REQUIRED_CONCEPTS_DIRECTIVE]:
|
|
386
|
-
if directive in plain_source_obj.metadata:
|
|
387
|
-
assert isinstance(
|
|
388
|
-
plain_source_obj.metadata[directive], list
|
|
389
|
-
), f"Syntax error: Invalid {directive} metadata. Expected a list."
|
|
390
|
-
prepared_metadata = []
|
|
391
|
-
for item in plain_source_obj.metadata[directive]:
|
|
392
|
-
if isinstance(item, dict):
|
|
393
|
-
for k, v in item.items():
|
|
394
|
-
prepared_metadata.append(f"- {k}: {v}")
|
|
395
|
-
elif isinstance(item, str):
|
|
396
|
-
prepared_metadata.append(f"- {item}")
|
|
397
|
-
else:
|
|
398
|
-
raise PlainSyntaxError(
|
|
399
|
-
f"Plain syntax error: Invalid {directive} metadata. Expected a dictionary or a string."
|
|
400
|
-
)
|
|
401
|
-
|
|
402
|
-
plain_source_obj.metadata[directive] = prepared_metadata
|
|
403
|
-
|
|
404
|
-
return plain_source_obj
|
|
116
|
+
def _syntax_error(line: Optional[int], module_name: Optional[str], message: str) -> PlainSyntaxError:
|
|
117
|
+
return PlainSyntaxError(f"Plain syntax error: {_where(line, module_name)}: {message}")
|
|
405
118
|
|
|
406
119
|
|
|
407
|
-
|
|
120
|
+
def _walk(token) -> Iterator[Any]:
|
|
121
|
+
yield token
|
|
122
|
+
for child in getattr(token, "children", None) or []:
|
|
123
|
+
yield from _walk(child)
|
|
408
124
|
|
|
409
125
|
|
|
410
|
-
def
|
|
411
|
-
"""
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
def section_marker(token: Paragraph) -> str | None:
|
|
422
|
-
"""The name in a `***name***` paragraph, or None when the paragraph is not a section marker."""
|
|
423
|
-
paragraph_children = cast("Sequence[Token]", token.children)
|
|
424
|
-
if len(paragraph_children) != 1 or not isinstance(paragraph_children[0], Emphasis):
|
|
425
|
-
return None
|
|
426
|
-
emphasis_children = cast("Sequence[Token]", paragraph_children[0].children)
|
|
427
|
-
if len(emphasis_children) != 1 or not isinstance(emphasis_children[0], Strong):
|
|
428
|
-
return None
|
|
429
|
-
strong_children = cast("Sequence[Token]", emphasis_children[0].children)
|
|
430
|
-
return cast(RawText, strong_children[0]).content
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
def read_sections(plain_source: dict, document: mistletoe.Document, module_name: str | None) -> None: # noqa: C901
|
|
434
|
-
"""Add the sections of the rendered spec plain file to ``plain_source``.
|
|
435
|
-
|
|
436
|
-
A list section holds a mistletoe Document whose children are its list items; ``functional specs`` holds a list
|
|
437
|
-
of Functionality items, one per `# <func-id>` heading, each with every block token up to the next heading or
|
|
438
|
-
section marker. Raise on the first structural error.
|
|
439
|
-
"""
|
|
440
|
-
current_specification_heading = None
|
|
441
|
-
current_functionality: Functionality | None = None
|
|
442
|
-
processed_specification_headings = set[str]()
|
|
443
|
-
functionality_lines: dict[str, int] = {} # func-id to the line of its heading
|
|
444
|
-
|
|
445
|
-
def close_functionality():
|
|
446
|
-
if current_functionality is not None and all(isinstance(t, BlankLine) for t in current_functionality.body):
|
|
447
|
-
raise PlainSyntaxError(
|
|
448
|
-
f"Plain syntax error: {syntax_error_at(current_functionality.line_number, module_name)}: "
|
|
449
|
-
f"Functionality `{current_functionality.id}` has no body."
|
|
450
|
-
)
|
|
451
|
-
|
|
452
|
-
for token in document.children:
|
|
453
|
-
if isinstance(token, BlankLine):
|
|
454
|
-
# Kept inside a functionality body, so its paragraphs stay apart; meaningless anywhere else.
|
|
455
|
-
if current_functionality is not None:
|
|
456
|
-
current_functionality.body.append(token)
|
|
457
|
-
continue
|
|
458
|
-
token_text = "".join(get_raw_text(token)).strip()
|
|
459
|
-
where = syntax_error_at(token.line_number, module_name)
|
|
460
|
-
in_functional_specs = current_specification_heading == plain_spec.FUNCTIONAL_REQUIREMENTS
|
|
461
|
-
if isinstance(token, Heading):
|
|
462
|
-
if not in_functional_specs:
|
|
126
|
+
def find_linked_resources(tokens, template_dirs, where: str = "") -> List[Dict[str, str]]:
|
|
127
|
+
"""Return every markdown link of the tokens as a text and target pair, after resolving it over the directories."""
|
|
128
|
+
linked_resources: List[Dict[str, str]] = []
|
|
129
|
+
for root in tokens:
|
|
130
|
+
for token in _walk(root):
|
|
131
|
+
if not isinstance(token, span_token.Link):
|
|
132
|
+
continue
|
|
133
|
+
target = token.target
|
|
134
|
+
children: Any = token.children or []
|
|
135
|
+
if _URL_SCHEME.match(target) or os.path.isabs(target) or target.startswith(("/", "\\")):
|
|
463
136
|
raise PlainSyntaxError(
|
|
464
|
-
f"Plain syntax error:
|
|
465
|
-
f"
|
|
137
|
+
f"Plain syntax error: Only relative links are allowed{where} (text: {_link_text(token)}, "
|
|
138
|
+
f"target: {target})."
|
|
466
139
|
)
|
|
467
|
-
if
|
|
140
|
+
if len(children) != 1 or not hasattr(children[0], "content") or not children[0].content:
|
|
141
|
+
raise PlainSyntaxError(f"Plain syntax error: Link{where} must have text specified (link: {target}).")
|
|
142
|
+
text = children[0].content
|
|
143
|
+
if target.endswith(PLAIN_SOURCE_FILE_EXTENSION):
|
|
468
144
|
raise PlainSyntaxError(
|
|
469
|
-
f"
|
|
470
|
-
|
|
145
|
+
f"Referenced resource '{target}'{where} is a .plain file. Referencing .plain files through Linked "
|
|
146
|
+
"Resources is not supported. Please use the import section to include definitions or "
|
|
147
|
+
"implementation/test requirements from another module."
|
|
471
148
|
)
|
|
472
|
-
|
|
149
|
+
resolved = resolve_linked_resource(template_dirs, target)
|
|
150
|
+
if resolved is None:
|
|
151
|
+
directories = "\n".join(f" {i}. {os.path.abspath(d)}" for i, d in enumerate(template_dirs, start=1))
|
|
473
152
|
raise PlainSyntaxError(
|
|
474
|
-
f"Plain syntax error: {where}
|
|
475
|
-
f"
|
|
153
|
+
f"Plain syntax error: Link {target}{where} does not exist. Linked resources are looked up "
|
|
154
|
+
f"relative to the following directories (highest to lowest precedence):\n{directories}"
|
|
476
155
|
)
|
|
477
|
-
if
|
|
156
|
+
if not os.path.isfile(resolved):
|
|
478
157
|
raise PlainSyntaxError(
|
|
479
|
-
f"Plain syntax error: {
|
|
480
|
-
f"{functionality_lines[token_text]}."
|
|
158
|
+
f"Plain syntax error: Link {target}{where} must be a file (resolved to {resolved})."
|
|
481
159
|
)
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
current_functionality = Functionality(token_text, token.line_number)
|
|
485
|
-
plain_source[plain_spec.FUNCTIONAL_REQUIREMENTS].append(current_functionality)
|
|
486
|
-
elif isinstance(token, Paragraph):
|
|
487
|
-
specification_heading = section_marker(token)
|
|
488
|
-
if specification_heading is None:
|
|
489
|
-
if not in_functional_specs:
|
|
490
|
-
raise PlainSyntaxError(f"Plain syntax error: {where}: Invalid specification (`{token_text}`)")
|
|
491
|
-
if current_functionality is None:
|
|
492
|
-
raise PlainSyntaxError(
|
|
493
|
-
f"Plain syntax error: {where}: Content before the first `# <func-id>` heading in the "
|
|
494
|
-
f"{plain_spec.FUNCTIONAL_REQUIREMENTS} section (`{token_text}`). {PREVIOUS_SYNTAX_HINT}"
|
|
495
|
-
)
|
|
496
|
-
current_functionality.body.append(token)
|
|
497
|
-
continue
|
|
160
|
+
linked_resources.append({"text": text, "target": target})
|
|
161
|
+
return linked_resources
|
|
498
162
|
|
|
499
|
-
if specification_heading not in plain_spec.ALLOWED_SPECIFICATION_HEADINGS:
|
|
500
|
-
raise PlainSyntaxError(
|
|
501
|
-
f"Plain syntax error: {where}: Invalid specification heading (`{specification_heading}`). "
|
|
502
|
-
f"Allowed headings: {', '.join(plain_spec.ALLOWED_SPECIFICATION_HEADINGS)}"
|
|
503
|
-
)
|
|
504
163
|
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
f"Plain syntax error: {where}: Duplicate specification heading (`{specification_heading}`)"
|
|
508
|
-
)
|
|
164
|
+
def _link_text(token) -> str:
|
|
165
|
+
return "".join(getattr(child, "content", "") for child in token.children or [])
|
|
509
166
|
|
|
510
|
-
if specification_heading == plain_spec.DEFINITIONS and current_specification_heading is not None:
|
|
511
|
-
raise PlainSyntaxError(
|
|
512
|
-
f"Plain syntax error: {where}: Definitions specification must be the first specification in "
|
|
513
|
-
f"the section (`{token_text}`)"
|
|
514
|
-
)
|
|
515
167
|
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
raise PlainSyntaxError(f"Plain syntax error: {where}: Missing specification heading (`{token_text}`)")
|
|
528
|
-
plain_source[current_specification_heading].children.extend(token.children)
|
|
529
|
-
elif in_functional_specs:
|
|
530
|
-
# The body of a functionality is free text: a list at any indentation, a code block, or any other block.
|
|
531
|
-
if current_functionality is None:
|
|
532
|
-
raise PlainSyntaxError(
|
|
533
|
-
f"Plain syntax error: {where}: Content before the first `# <func-id>` heading in the "
|
|
534
|
-
f"{plain_spec.FUNCTIONAL_REQUIREMENTS} section (`{token_text}`). {PREVIOUS_SYNTAX_HINT}"
|
|
535
|
-
)
|
|
536
|
-
current_functionality.body.append(token)
|
|
537
|
-
else:
|
|
538
|
-
raise PlainSyntaxError(f"Plain syntax error: {where}: Invalid source structure (`{token_text}`)")
|
|
168
|
+
def process_section_code_variables(section, code_variables, text_key="markdown") -> None:
|
|
169
|
+
"""Replace the code variable tokens in the texts of a section with placeholders and record the variables."""
|
|
170
|
+
if not code_variables:
|
|
171
|
+
return
|
|
172
|
+
for item in section:
|
|
173
|
+
for token, variable in code_variables.items():
|
|
174
|
+
if token not in item[text_key]:
|
|
175
|
+
continue
|
|
176
|
+
(name, value), *_ = variable.items()
|
|
177
|
+
item[text_key] = item[text_key].replace(token, "{{ " + name + " }}")
|
|
178
|
+
item.setdefault("code_variables", []).append({"name": name, "value": value})
|
|
539
179
|
|
|
540
|
-
close_functionality()
|
|
541
180
|
|
|
181
|
+
def _drop_quotes(token) -> None:
|
|
182
|
+
children = getattr(token, "children", None)
|
|
183
|
+
if not children:
|
|
184
|
+
return
|
|
185
|
+
kept = [child for child in children if not isinstance(child, block_token.Quote)]
|
|
186
|
+
if len(kept) != len(children):
|
|
187
|
+
token.children = kept
|
|
188
|
+
for child in kept:
|
|
189
|
+
_drop_quotes(child)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _blank_risky_comments(text: str) -> str:
|
|
193
|
+
"""Blank a comment line that a block quote would continue lazily into the next, non-blank line."""
|
|
194
|
+
lines = text.split("\n")
|
|
195
|
+
fence: Optional[str] = None
|
|
196
|
+
for index, line in enumerate(lines):
|
|
197
|
+
match = _FENCE.match(line)
|
|
198
|
+
if fence is None and match:
|
|
199
|
+
fence = match.group(1)[0]
|
|
200
|
+
continue
|
|
201
|
+
if fence is not None:
|
|
202
|
+
if match and match.group(1)[0] == fence and line.strip().strip(fence) == "":
|
|
203
|
+
fence = None
|
|
204
|
+
continue
|
|
205
|
+
if not line.lstrip().startswith(">") or index + 1 >= len(lines):
|
|
206
|
+
continue
|
|
207
|
+
following = lines[index + 1]
|
|
208
|
+
if following.strip() and not following.lstrip().startswith(">"):
|
|
209
|
+
lines[index] = ""
|
|
210
|
+
return "\n".join(lines)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _block_text(renderer, token) -> str:
|
|
214
|
+
if isinstance(token, (block_token.CodeFence, block_token.BlockCode)):
|
|
215
|
+
return "".join(getattr(child, "content", "") for child in token.children or []).strip()
|
|
216
|
+
return renderer.render(token).strip()
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _item_text(renderer, token) -> str:
|
|
220
|
+
items: Any = token.children if isinstance(token, block_token.List) else None
|
|
221
|
+
if items:
|
|
222
|
+
return _LIST_LEADER.sub("", renderer.render(items[0]).strip(), count=1)
|
|
223
|
+
return _block_text(renderer, token)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _reject_test_sections(rendered: str, module_name: Optional[str]) -> None:
|
|
227
|
+
match = _TEST_SECTION_LINE.search(rendered)
|
|
228
|
+
if match:
|
|
229
|
+
line = rendered.count("\n", 0, match.start()) + 1
|
|
230
|
+
raise _syntax_error(
|
|
231
|
+
line,
|
|
232
|
+
module_name,
|
|
233
|
+
f"The `{match.group(1)}` section is not allowed in a spec plain file; "
|
|
234
|
+
"test scenarios live in test plain files.",
|
|
235
|
+
)
|
|
542
236
|
|
|
543
|
-
def parse_plain_source( # noqa: C901
|
|
544
|
-
plain_source_text: str,
|
|
545
|
-
code_variables: dict,
|
|
546
|
-
template_dirs: list[str],
|
|
547
|
-
imported_modules: list[str],
|
|
548
|
-
modules_trace: list[str],
|
|
549
|
-
module_name: str | None = None,
|
|
550
|
-
) -> PlainFileParseResult:
|
|
551
|
-
plain_source_text = normalize_line_endings(plain_source_text)
|
|
552
237
|
|
|
553
|
-
|
|
238
|
+
def _is_blank(token) -> bool:
|
|
239
|
+
return isinstance(token, BlankLine)
|
|
554
240
|
|
|
555
|
-
plain_source = PLAIN_SOURCE_TEMPLATE.copy()
|
|
556
241
|
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
code_variables,
|
|
562
|
-
template_dirs,
|
|
563
|
-
imported_modules,
|
|
564
|
-
modules_trace,
|
|
242
|
+
def _finish_functionality(functionality: Optional[dict], module_name: Optional[str]) -> None:
|
|
243
|
+
if functionality is not None and all(_is_blank(token) for token in functionality["tokens"]):
|
|
244
|
+
raise _syntax_error(
|
|
245
|
+
functionality["line_number"], module_name, f"Functionality `{functionality['id']}` has no body."
|
|
565
246
|
)
|
|
566
|
-
else:
|
|
567
|
-
required_concepts = list[str]()
|
|
568
|
-
|
|
569
|
-
[_, loaded_templates] = loaders.get_loaded_templates(template_dirs, plain_source_text, module_name)
|
|
570
247
|
|
|
571
|
-
plain_source_content = restore_stripped_lines(plain_source_text, plain_source_obj.content)
|
|
572
248
|
|
|
573
|
-
|
|
249
|
+
class _SectionParser:
|
|
250
|
+
"""Reads the top-level blocks of a rendered module into list sections and functionalities."""
|
|
251
|
+
|
|
252
|
+
def __init__(self, renderer: Any, module_name: Optional[str]) -> None:
|
|
253
|
+
self.renderer = renderer
|
|
254
|
+
self.module_name = module_name
|
|
255
|
+
self.sections: Dict[str, Any] = {}
|
|
256
|
+
self.current: Optional[str] = None
|
|
257
|
+
self.functionality: Optional[dict] = None
|
|
258
|
+
|
|
259
|
+
def error(self, token: Any, message: str) -> PlainSyntaxError:
|
|
260
|
+
return _syntax_error(token.line_number, self.module_name, message)
|
|
261
|
+
|
|
262
|
+
def section_name(self, token: Any) -> Optional[str]:
|
|
263
|
+
if not isinstance(token, block_token.Paragraph):
|
|
264
|
+
return None
|
|
265
|
+
text = self.renderer.render(token).strip()
|
|
266
|
+
match = _SECTION_LINE.fullmatch(text) if "\n" not in text else None
|
|
267
|
+
return match.group(1) if match else None
|
|
268
|
+
|
|
269
|
+
def start_section(self, token: Any, name: str) -> None:
|
|
270
|
+
_finish_functionality(self.functionality, self.module_name)
|
|
271
|
+
self.functionality = None
|
|
272
|
+
if name not in ALLOWED_SPECIFICATION_HEADINGS:
|
|
273
|
+
raise self.error(
|
|
274
|
+
token,
|
|
275
|
+
f"Invalid specification heading (`{name}`). Allowed headings: "
|
|
276
|
+
+ ", ".join(ALLOWED_SPECIFICATION_HEADINGS),
|
|
277
|
+
)
|
|
278
|
+
if name in self.sections:
|
|
279
|
+
raise self.error(token, f"Duplicate specification heading (`{name}`)")
|
|
280
|
+
if name == DEFINITIONS and self.sections:
|
|
281
|
+
raise self.error(
|
|
282
|
+
token, f"Definitions specification must be the first specification in the section (`{name}`)"
|
|
283
|
+
)
|
|
284
|
+
self.sections[name] = []
|
|
285
|
+
self.current = name
|
|
286
|
+
|
|
287
|
+
def reject(self, token: Any, missing_heading: bool = False) -> PlainSyntaxError:
|
|
288
|
+
text = _item_text(self.renderer, token)
|
|
289
|
+
if isinstance(token, (block_token.Heading, block_token.SetextHeading)):
|
|
290
|
+
return self.error(
|
|
291
|
+
token,
|
|
292
|
+
"A `# <func-id>` heading is allowed only in the functional specs section "
|
|
293
|
+
f"(`{self.renderer.render_inner(token).strip()}`).",
|
|
294
|
+
)
|
|
295
|
+
if missing_heading and isinstance(token, block_token.List):
|
|
296
|
+
return self.error(token, f"Missing specification heading (`{text}`)")
|
|
297
|
+
if isinstance(token, block_token.Paragraph):
|
|
298
|
+
return self.error(token, f"Invalid specification (`{text}`)")
|
|
299
|
+
return self.error(token, f"Invalid source structure (`{text}`)")
|
|
300
|
+
|
|
301
|
+
def start_functionality(self, token: Any) -> None:
|
|
302
|
+
heading = self.renderer.render_inner(token).strip()
|
|
303
|
+
if token.level != 1:
|
|
304
|
+
raise self.error(
|
|
305
|
+
token,
|
|
306
|
+
f"Invalid heading level {token.level} (`{heading}`). A functionality heading is `# <func-id>`.",
|
|
307
|
+
)
|
|
308
|
+
if not is_semantic_id(heading):
|
|
309
|
+
raise self.error(
|
|
310
|
+
token,
|
|
311
|
+
f"Invalid func-id (`{heading}`). A func-id is lowercase letters and digits, with single "
|
|
312
|
+
"hyphens between them.",
|
|
313
|
+
)
|
|
314
|
+
for earlier in self.sections[FUNCTIONAL_REQUIREMENTS]:
|
|
315
|
+
if earlier["id"] == heading:
|
|
316
|
+
raise self.error(
|
|
317
|
+
token, f"Duplicate func-id `{heading}`; it is first used at line {earlier['line_number']}."
|
|
318
|
+
)
|
|
319
|
+
_finish_functionality(self.functionality, self.module_name)
|
|
320
|
+
self.functionality = {"id": heading, "line_number": token.line_number, "tokens": [], "linked_resources": []}
|
|
321
|
+
self.sections[FUNCTIONAL_REQUIREMENTS].append(self.functionality)
|
|
322
|
+
|
|
323
|
+
def add_to_functionality(self, token: Any) -> None:
|
|
324
|
+
if self.functionality is not None:
|
|
325
|
+
self.functionality["tokens"].append(token)
|
|
326
|
+
elif not isinstance(token, BlankLine):
|
|
327
|
+
raise self.error(
|
|
328
|
+
token,
|
|
329
|
+
"Content before the first `# <func-id>` heading in the functional specs section "
|
|
330
|
+
f"(`{_item_text(self.renderer, token)}`). A functionality is a `# <func-id>` heading followed by its "
|
|
331
|
+
"body; the previous syntax is not supported.",
|
|
332
|
+
)
|
|
574
333
|
|
|
575
|
-
|
|
334
|
+
def read(self, token: Any) -> None:
|
|
335
|
+
name = self.section_name(token)
|
|
336
|
+
if name is not None:
|
|
337
|
+
self.start_section(token, name)
|
|
338
|
+
elif self.current is None:
|
|
339
|
+
if not isinstance(token, BlankLine):
|
|
340
|
+
raise self.reject(token, missing_heading=True)
|
|
341
|
+
elif self.current == FUNCTIONAL_REQUIREMENTS:
|
|
342
|
+
if isinstance(token, (block_token.Heading, block_token.SetextHeading)):
|
|
343
|
+
self.start_functionality(token)
|
|
344
|
+
else:
|
|
345
|
+
self.add_to_functionality(token)
|
|
346
|
+
elif isinstance(token, block_token.List):
|
|
347
|
+
self.sections[self.current].extend(token.children)
|
|
348
|
+
elif not isinstance(token, BlankLine):
|
|
349
|
+
raise self.reject(token)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _parse_sections(rendered: str, module_name: Optional[str]) -> Dict[str, Any]:
|
|
353
|
+
"""Split the rendered text into list sections of items and the list of functionalities."""
|
|
354
|
+
with _renderer() as renderer:
|
|
355
|
+
document = Document(_blank_risky_comments(rendered))
|
|
356
|
+
_drop_quotes(document)
|
|
357
|
+
parser = _SectionParser(renderer, module_name)
|
|
358
|
+
for token in document.children or []:
|
|
359
|
+
parser.read(token)
|
|
360
|
+
_finish_functionality(parser.functionality, module_name)
|
|
361
|
+
sections = parser.sections
|
|
362
|
+
for name in LIST_SECTION_HEADINGS:
|
|
363
|
+
if name in sections:
|
|
364
|
+
sections[name] = _items_document(sections[name])
|
|
365
|
+
return sections
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _items_document(items: list) -> Document:
|
|
369
|
+
document = Document("")
|
|
370
|
+
document.children = list(items)
|
|
371
|
+
return document
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _items(plain_source: dict, heading: str) -> list:
|
|
375
|
+
section = plain_source.get(heading)
|
|
376
|
+
return list(section.children) if section is not None else []
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _normalize_concept_list(metadata: dict, directive: str) -> None:
|
|
380
|
+
if directive not in metadata:
|
|
381
|
+
return
|
|
382
|
+
entries = metadata[directive]
|
|
383
|
+
assert isinstance(entries, list), f"Syntax error: Invalid {directive} metadata. Expected a list."
|
|
384
|
+
texts: List[str] = []
|
|
385
|
+
for entry in entries:
|
|
386
|
+
if isinstance(entry, str):
|
|
387
|
+
texts.append(f"- {entry}")
|
|
388
|
+
elif isinstance(entry, dict):
|
|
389
|
+
texts.extend(f"- {key}: {value}" for key, value in entry.items())
|
|
390
|
+
else:
|
|
391
|
+
raise PlainSyntaxError(
|
|
392
|
+
f"Plain syntax error: Invalid {directive} metadata. Expected a dictionary or a string."
|
|
393
|
+
)
|
|
394
|
+
metadata[directive] = texts
|
|
576
395
|
|
|
577
|
-
# Parsed inside a renderer context, so blank lines become BlankLine tokens and survive in functionality bodies.
|
|
578
|
-
with PlainRenderer():
|
|
579
|
-
plain_file = mistletoe.Document(io.StringIO(plain_source_full_text))
|
|
580
396
|
|
|
581
|
-
|
|
397
|
+
def _names(value: Any) -> List[str]:
|
|
398
|
+
if value is None:
|
|
399
|
+
return []
|
|
400
|
+
return [value] if isinstance(value, str) else [str(v) for v in value]
|
|
582
401
|
|
|
583
|
-
read_sections(plain_source, plain_file, module_name)
|
|
584
402
|
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
for concept in new_concepts:
|
|
593
|
-
if concept in required_concepts:
|
|
594
|
-
required_concepts.remove(concept)
|
|
403
|
+
def _defined_concepts(plain_source: dict) -> Set[str]:
|
|
404
|
+
defined: Set[str] = set()
|
|
405
|
+
with _renderer() as renderer:
|
|
406
|
+
for item in _items(plain_source, DEFINITIONS):
|
|
407
|
+
concepts, _ = concept_utils.extract_concepts_from_definition(renderer.render(item).strip())
|
|
408
|
+
defined.update(concepts)
|
|
409
|
+
return defined
|
|
595
410
|
|
|
596
|
-
if EXPORTED_CONCEPTS_DIRECTIVE in plain_source_obj.metadata:
|
|
597
|
-
module_name = modules_trace[-1] if modules_trace else None
|
|
598
|
-
subject = f"Module '{module_name}'" if module_name else "Module"
|
|
599
411
|
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
412
|
+
def _check_exported_concepts(
|
|
413
|
+
metadata: dict, plain_source: dict, requires: List[str], module_name: Optional[str]
|
|
414
|
+
) -> None:
|
|
415
|
+
subject = f"Module '{module_name}'" if module_name else "Module"
|
|
416
|
+
defined = _defined_concepts(plain_source)
|
|
417
|
+
for entry in metadata.get(EXPORTED_CONCEPTS_DIRECTIVE, []):
|
|
418
|
+
concepts, errors = concept_utils.extract_concepts_from_definition(entry)
|
|
419
|
+
if errors or not concepts:
|
|
420
|
+
raise PlainSyntaxError(
|
|
421
|
+
f"Plain syntax error: {subject} exports an invalid concept (`{entry}`). "
|
|
422
|
+
"Expected a concept token, e.g. :ConceptName:."
|
|
423
|
+
)
|
|
424
|
+
for concept in concepts:
|
|
425
|
+
if concept in concept_utils.DEFAULT_CONCEPTS:
|
|
603
426
|
raise PlainSyntaxError(
|
|
604
|
-
f"Plain syntax error: {subject}
|
|
605
|
-
|
|
427
|
+
f"Plain syntax error: {subject} cannot export default concept {concept}. "
|
|
428
|
+
"Only user-defined concepts can be exported."
|
|
606
429
|
)
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
if
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
430
|
+
if concept not in defined:
|
|
431
|
+
message = f"Plain syntax error: {subject} exports undefined concept {concept}."
|
|
432
|
+
if requires:
|
|
433
|
+
message += (
|
|
434
|
+
" An exported concept must be defined in this module's definitions or in an imported module; "
|
|
435
|
+
"a concept inherited through requires cannot be re-exported."
|
|
613
436
|
)
|
|
437
|
+
raise PlainSyntaxError(message)
|
|
614
438
|
|
|
615
|
-
if exported_concept not in defined_concepts:
|
|
616
|
-
message = f"Plain syntax error: {subject} exports undefined concept {exported_concept}."
|
|
617
|
-
if REQUIRES_DIRECTIVE in plain_source_obj.metadata:
|
|
618
|
-
message += (
|
|
619
|
-
" An exported concept must be defined in this module's definitions or in an "
|
|
620
|
-
"imported module; a concept inherited through requires cannot be re-exported."
|
|
621
|
-
)
|
|
622
|
-
raise PlainSyntaxError(message)
|
|
623
|
-
|
|
624
|
-
required_modules = []
|
|
625
|
-
if REQUIRES_DIRECTIVE in plain_source_obj.metadata:
|
|
626
|
-
required_modules = plain_source_obj.metadata[REQUIRES_DIRECTIVE]
|
|
627
|
-
|
|
628
|
-
return PlainFileParseResult(
|
|
629
|
-
plain_source=plain_source,
|
|
630
|
-
plain_source_obj=plain_source_obj,
|
|
631
|
-
required_modules=required_modules,
|
|
632
|
-
required_concepts=required_concepts,
|
|
633
|
-
)
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
def read_module_plain_source(module_name: str, template_dirs: list[str]) -> str:
|
|
637
|
-
plain_source_text = loaders.open_from(template_dirs, module_name + PLAIN_SOURCE_FILE_EXTENSION)
|
|
638
|
-
if plain_source_text is None:
|
|
639
|
-
raise ModuleDoesNotExistError(f"Module does not exist ({module_name}).")
|
|
640
439
|
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
raise UnsupportedBase64Content(
|
|
644
|
-
f"Module '{module_name}' contains a base64-encoded blob ({len(blob)} characters) "
|
|
645
|
-
"inlined in the specification. This is not supported. "
|
|
646
|
-
"Remove the base64 data from the .plain file or if necessary, "
|
|
647
|
-
"include the binary file path in the specification."
|
|
648
|
-
)
|
|
649
|
-
|
|
650
|
-
return plain_source_text
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
def parse_plain_file(
|
|
654
|
-
module_name: str,
|
|
440
|
+
def parse_plain_source(
|
|
441
|
+
plain_source_text: str,
|
|
655
442
|
code_variables: dict,
|
|
656
|
-
template_dirs:
|
|
657
|
-
imported_modules:
|
|
658
|
-
modules_trace:
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
# Marshalled plain source tree, set once the module is validated.
|
|
683
|
-
tree: dict | None = None
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
def process_required_modules(
|
|
687
|
-
required_modules: list[str],
|
|
688
|
-
template_dirs: list[str],
|
|
689
|
-
all_required_modules: list[str],
|
|
690
|
-
modules_trace: list[str],
|
|
691
|
-
required: dict[str, RequiredModule],
|
|
692
|
-
) -> list[mistletoe.block_token.token]:
|
|
693
|
-
"""Parse every required module, deepest first, without validating it.
|
|
694
|
-
|
|
695
|
-
Records each module in ``required`` the first time it is reached (deepest ancestors first) and returns
|
|
696
|
-
the exported definitions of the directly required modules.
|
|
697
|
-
"""
|
|
698
|
-
exported_definitions = list[mistletoe.block_token.token]()
|
|
699
|
-
for module_name in required_modules:
|
|
700
|
-
if module_name in modules_trace:
|
|
701
|
-
raise PlainSyntaxError(f"Plain syntax error: Circular required module detected: {module_name}.")
|
|
702
|
-
|
|
703
|
-
if len(all_required_modules) > 0 and module_name == all_required_modules[-1]:
|
|
704
|
-
# Already processed as an earlier entry; its exports are still visible to this module.
|
|
705
|
-
exported_definitions.extend(required[module_name].exported_definitions)
|
|
443
|
+
template_dirs: List[str],
|
|
444
|
+
imported_modules: List[str],
|
|
445
|
+
modules_trace: List[str],
|
|
446
|
+
module_name: Optional[str] = None,
|
|
447
|
+
) -> PlainFileParseResult:
|
|
448
|
+
"""Parse the text of a module into its list sections and functionalities, merging its imports first."""
|
|
449
|
+
text = normalize_line_endings(plain_source_text)
|
|
450
|
+
try:
|
|
451
|
+
post = frontmatter.loads(text)
|
|
452
|
+
except Exception as error:
|
|
453
|
+
raise PlainSyntaxError(f"Plain syntax error: Invalid frontmatter: {error}") from error
|
|
454
|
+
metadata = post.metadata
|
|
455
|
+
for directive in (EXPORTED_CONCEPTS_DIRECTIVE, REQUIRED_CONCEPTS_DIRECTIVE):
|
|
456
|
+
_normalize_concept_list(metadata, directive)
|
|
457
|
+
|
|
458
|
+
rendered, _ = _render(template_dirs, restore_stripped_lines(text, post.content), module_name, code_variables)
|
|
459
|
+
_reject_test_sections(rendered, module_name)
|
|
460
|
+
own = _parse_sections(rendered, module_name)
|
|
461
|
+
|
|
462
|
+
trace = [*modules_trace, module_name] if module_name else list(modules_trace)
|
|
463
|
+
merged: Dict[str, list] = {}
|
|
464
|
+
required_concepts: List[str] = []
|
|
465
|
+
for imported_name in _names(metadata.get(IMPORT_DIRECTIVE)):
|
|
466
|
+
if imported_name in trace:
|
|
467
|
+
raise PlainSyntaxError(f"Plain syntax error: Circular import detected: {imported_name}.")
|
|
468
|
+
if imported_name in imported_modules:
|
|
706
469
|
continue
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
ancestor_exported_definitions: list[mistletoe.block_token.token] = []
|
|
714
|
-
if len(plain_file_parse_result.required_modules) == 0:
|
|
715
|
-
if len(all_required_modules) > 0:
|
|
716
|
-
# For now we require that there is fixed order how required modules are dependent.
|
|
717
|
-
# In the future we will support the cases where required modules can be rendered independently
|
|
718
|
-
# and then merged (somehow).
|
|
719
|
-
raise PlainSyntaxError(
|
|
720
|
-
f"Plain syntax error: There must be a fixed order how required modules are dependent ({module_name})."
|
|
721
|
-
)
|
|
722
|
-
else:
|
|
723
|
-
ancestor_exported_definitions = process_required_modules(
|
|
724
|
-
plain_file_parse_result.required_modules,
|
|
725
|
-
template_dirs,
|
|
726
|
-
all_required_modules,
|
|
727
|
-
modules_trace + [module_name],
|
|
728
|
-
required,
|
|
470
|
+
imported = parse_plain_file(imported_name, code_variables, template_dirs, imported_modules, trace)
|
|
471
|
+
if FUNCTIONAL_REQUIREMENTS in imported.plain_source:
|
|
472
|
+
raise ImportedModuleWithFunctionalitiesError(
|
|
473
|
+
f"Module '{imported_name}' is imported but contains functional specs. Imported modules may only "
|
|
474
|
+
"provide definitions, implementation reqs, and test reqs — use 'requires' instead of 'import' if "
|
|
475
|
+
"this module's functionalities should be built on."
|
|
729
476
|
)
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
with PlainRenderer() as renderer:
|
|
738
|
-
for exported_concept in exported_concepts:
|
|
739
|
-
own_exported_definitions.extend(
|
|
740
|
-
concept_utils.find_concept_definitions_in_plain_source(
|
|
741
|
-
exported_concept, plain_file_parse_result.plain_source, renderer
|
|
742
|
-
)
|
|
743
|
-
)
|
|
744
|
-
required[module_name] = RequiredModule(
|
|
745
|
-
plain_file_parse_result, ancestor_exported_definitions, code_variables, own_exported_definitions
|
|
477
|
+
imported_modules.append(imported_name)
|
|
478
|
+
for heading in LIST_SECTION_HEADINGS:
|
|
479
|
+
if heading in imported.plain_source:
|
|
480
|
+
merged.setdefault(heading, []).extend(_items(imported.plain_source, heading))
|
|
481
|
+
required_concepts.extend(
|
|
482
|
+
_concepts_of(imported.plain_source_obj.metadata.get(REQUIRED_CONCEPTS_DIRECTIVE, [])) # type: ignore[arg-type]
|
|
746
483
|
)
|
|
747
|
-
|
|
484
|
+
required_concepts.extend(imported.required_concepts)
|
|
748
485
|
|
|
749
|
-
|
|
486
|
+
plain_source: Dict[str, Any] = {}
|
|
487
|
+
for heading in LIST_SECTION_HEADINGS:
|
|
488
|
+
if heading in merged or heading in own:
|
|
489
|
+
plain_source[heading] = _items_document(merged.get(heading, []) + _items(own, heading))
|
|
490
|
+
if FUNCTIONAL_REQUIREMENTS in own:
|
|
491
|
+
plain_source[FUNCTIONAL_REQUIREMENTS] = own[FUNCTIONAL_REQUIREMENTS]
|
|
750
492
|
|
|
751
|
-
|
|
493
|
+
requires = _names(metadata.get(REQUIRES_DIRECTIVE))
|
|
494
|
+
_check_exported_concepts(metadata, plain_source, requires, module_name)
|
|
495
|
+
defined = _defined_concepts(plain_source)
|
|
496
|
+
still_required = [c for c in dict.fromkeys(required_concepts) if c not in defined]
|
|
497
|
+
return PlainFileParseResult(plain_source, post, requires, still_required)
|
|
752
498
|
|
|
753
499
|
|
|
754
|
-
def
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
if module.tree is not None:
|
|
761
|
-
continue
|
|
762
|
-
|
|
763
|
-
validate_module_structure(module.parse_result, module_name)
|
|
764
|
-
module.tree = validate_and_build_module_tree(
|
|
765
|
-
module.parse_result, module_name, module.ancestor_exported_definitions, module.code_variables, template_dirs
|
|
766
|
-
)
|
|
767
|
-
validate_required_modules(module.parse_result.required_modules, required, template_dirs)
|
|
500
|
+
def _concepts_of(entries: List[str]) -> List[str]:
|
|
501
|
+
concepts: List[str] = []
|
|
502
|
+
for entry in entries:
|
|
503
|
+
found, _ = concept_utils.extract_concepts_from_definition(entry)
|
|
504
|
+
concepts.extend(found)
|
|
505
|
+
return concepts
|
|
768
506
|
|
|
769
507
|
|
|
770
|
-
def
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
508
|
+
def parse_plain_file(
|
|
509
|
+
module_name: str,
|
|
510
|
+
code_variables: dict,
|
|
511
|
+
template_dirs: List[str],
|
|
512
|
+
imported_modules: List[str],
|
|
513
|
+
modules_trace: List[str],
|
|
514
|
+
) -> PlainFileParseResult:
|
|
515
|
+
"""Read a module by name from the template directories and parse it."""
|
|
516
|
+
text = open_from(template_dirs, get_filename_from_module_name(module_name))
|
|
517
|
+
if text is None:
|
|
518
|
+
raise ModuleDoesNotExistError(f"Module does not exist ({module_name}).")
|
|
519
|
+
blob = find_large_base64_blob(text)
|
|
520
|
+
if blob is not None:
|
|
521
|
+
raise UnsupportedBase64Content(
|
|
522
|
+
f"Module '{module_name}' contains a base64-encoded blob ({len(blob)} characters) inlined in the "
|
|
523
|
+
"specification. This is not supported. Remove the base64 data from the .plain file or if necessary, "
|
|
524
|
+
"include the binary file path in the specification."
|
|
525
|
+
)
|
|
526
|
+
return parse_plain_source(text, code_variables, template_dirs, imported_modules, modules_trace, module_name)
|
|
780
527
|
|
|
781
|
-
exported_rendered_definition = renderer.render(exported_definition).strip()
|
|
782
|
-
for definition in plain_source[plain_spec.DEFINITIONS].children:
|
|
783
|
-
rendered_definition = renderer.render(definition).strip()
|
|
784
|
-
if exported_rendered_definition == rendered_definition:
|
|
785
|
-
add_defintion = False
|
|
786
|
-
break
|
|
787
528
|
|
|
788
|
-
|
|
789
|
-
|
|
529
|
+
def marshall_plain_source(input_plain_source) -> dict:
|
|
530
|
+
"""Turn the parsed sections of a module into a plain source tree."""
|
|
531
|
+
tree: Dict[str, Any] = {}
|
|
532
|
+
with _renderer() as renderer:
|
|
533
|
+
for heading in LIST_SECTION_HEADINGS:
|
|
534
|
+
if heading not in input_plain_source:
|
|
535
|
+
continue
|
|
536
|
+
items = []
|
|
537
|
+
for item in input_plain_source[heading].children:
|
|
538
|
+
entry: Dict[str, Any] = {"markdown": renderer.render(item).strip()}
|
|
539
|
+
links = getattr(item, "linked_resources", None)
|
|
540
|
+
if links:
|
|
541
|
+
entry["linked_resources"] = links
|
|
542
|
+
items.append(entry)
|
|
543
|
+
tree[heading] = items
|
|
544
|
+
if FUNCTIONAL_REQUIREMENTS in input_plain_source:
|
|
545
|
+
tree[FUNCTIONAL_REQUIREMENTS] = [
|
|
546
|
+
{
|
|
547
|
+
"id": functionality["id"],
|
|
548
|
+
"markdown": "".join(renderer.render(token) for token in functionality["tokens"]).strip("\n"),
|
|
549
|
+
"linked_resources": functionality.get("linked_resources", []),
|
|
550
|
+
CONFORMANCE_TESTS: [],
|
|
551
|
+
ACCEPTANCE_TESTS: [],
|
|
552
|
+
}
|
|
553
|
+
for functionality in input_plain_source[FUNCTIONAL_REQUIREMENTS]
|
|
554
|
+
]
|
|
555
|
+
return tree
|
|
790
556
|
|
|
791
557
|
|
|
792
|
-
def
|
|
793
|
-
|
|
794
|
-
if len(plain_file_parse_result.required_concepts) > 0:
|
|
795
|
-
missing_required_concepts_msg = "Missing required concepts: "
|
|
796
|
-
missing_required_concepts_msg += ", ".join(plain_file_parse_result.required_concepts)
|
|
558
|
+
def _check_module_shape(result: PlainFileParseResult, module_name: str) -> None:
|
|
559
|
+
if result.required_concepts:
|
|
797
560
|
raise PlainSyntaxError(
|
|
798
|
-
|
|
561
|
+
"Plain syntax error: Not all required concepts were defined. Missing required concepts: "
|
|
562
|
+
+ ", ".join(result.required_concepts)
|
|
563
|
+
+ "."
|
|
799
564
|
)
|
|
800
|
-
|
|
801
|
-
if not has_functional_specs_section(plain_file_parse_result.plain_source):
|
|
802
|
-
# No ***functional specs*** section at all: valid as an import, but not renderable. Usage error.
|
|
565
|
+
if FUNCTIONAL_REQUIREMENTS not in result.plain_source:
|
|
803
566
|
raise MissingFunctionalitiesError(
|
|
804
567
|
f"Module '{module_name}' does not have any functionality specified. "
|
|
805
|
-
|
|
568
|
+
"At least one functionality is required for rendering."
|
|
806
569
|
)
|
|
807
|
-
|
|
808
|
-
if count_functionalities(plain_file_parse_result.plain_source) == 0:
|
|
809
|
-
# ***functional specs*** section present but empty: invalid in every role. Syntax error.
|
|
570
|
+
if not result.plain_source[FUNCTIONAL_REQUIREMENTS]:
|
|
810
571
|
raise PlainSyntaxError(
|
|
811
|
-
f"Plain syntax error: Module '{module_name}' has a '
|
|
812
|
-
|
|
572
|
+
f"Plain syntax error: Module '{module_name}' has a 'functional specs' section without a "
|
|
573
|
+
"`# <func-id>` heading. A functionality is a `# <func-id>` heading followed by its body; "
|
|
574
|
+
"the previous syntax is not supported."
|
|
813
575
|
)
|
|
576
|
+
if not _items(result.plain_source, NON_FUNCTIONAL_REQUIREMENTS):
|
|
577
|
+
message = (
|
|
578
|
+
f"Plain syntax error: Module '{module_name}' defines functionalities but specifies no implementation "
|
|
579
|
+
"reqs. At least one implementation req is required."
|
|
580
|
+
)
|
|
581
|
+
if result.required_modules:
|
|
582
|
+
message += (
|
|
583
|
+
" Implementation reqs are not inherited through 'requires' — add them to this module, "
|
|
584
|
+
"or 'import' a module that provides them."
|
|
585
|
+
)
|
|
586
|
+
raise PlainSyntaxError(message)
|
|
814
587
|
|
|
815
|
-
validate_functionalities_have_implementation_reqs(
|
|
816
|
-
plain_file_parse_result.plain_source,
|
|
817
|
-
module_name,
|
|
818
|
-
has_requires=bool(plain_file_parse_result.required_modules),
|
|
819
|
-
)
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
def validate_and_build_module_tree(
|
|
823
|
-
plain_file_parse_result: PlainFileParseResult,
|
|
824
|
-
module_name: str,
|
|
825
|
-
exported_definitions: list[mistletoe.block_token.token],
|
|
826
|
-
code_variables: dict,
|
|
827
|
-
template_dirs: list[str],
|
|
828
|
-
) -> dict:
|
|
829
|
-
"""Merge exported definitions, validate linked resources and concepts, and return the marshalled plain source
|
|
830
|
-
tree."""
|
|
831
|
-
process_exported_definitions(plain_file_parse_result.plain_source, exported_definitions)
|
|
832
|
-
|
|
833
|
-
check_for_linked_resources(plain_file_parse_result.plain_source, template_dirs)
|
|
834
|
-
|
|
835
|
-
marshalled_plain_source = marshall_plain_source(plain_file_parse_result.plain_source)
|
|
836
|
-
|
|
837
|
-
process_code_variables(marshalled_plain_source, code_variables)
|
|
838
588
|
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
589
|
+
def _resolve_links(plain_source: dict, template_dirs: List[str]) -> None:
|
|
590
|
+
for heading in LIST_SECTION_HEADINGS:
|
|
591
|
+
for item in _items(plain_source, heading):
|
|
592
|
+
if not hasattr(item, "linked_resources"):
|
|
593
|
+
setattr(item, "linked_resources", find_linked_resources([item], template_dirs))
|
|
594
|
+
for functionality in plain_source.get(FUNCTIONAL_REQUIREMENTS, []):
|
|
595
|
+
functionality["linked_resources"] = find_linked_resources(functionality["tokens"], template_dirs)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _build_tree(plain_source: dict, template_dirs: List[str], code_variables: dict) -> dict:
|
|
599
|
+
"""Resolve links, marshall, record code variables, validate and sort the concepts of a parsed module."""
|
|
600
|
+
_resolve_links(plain_source, template_dirs)
|
|
601
|
+
tree = marshall_plain_source(plain_source)
|
|
602
|
+
for heading in LIST_SECTION_HEADINGS:
|
|
603
|
+
process_section_code_variables(tree.get(heading, []), code_variables)
|
|
604
|
+
process_section_code_variables(tree.get(FUNCTIONAL_REQUIREMENTS, []), code_variables)
|
|
605
|
+
errors = concept_utils.validate_concepts(tree)
|
|
606
|
+
if errors:
|
|
607
|
+
raise PlainSyntaxError(
|
|
608
|
+
f"Plain syntax error: Found {len(errors)} errors in the plain file:\n" + "\n".join(errors)
|
|
609
|
+
)
|
|
610
|
+
if DEFINITIONS in tree:
|
|
611
|
+
concept_utils.sort_definitions(tree[DEFINITIONS])
|
|
612
|
+
return tree
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _exported_definitions(result: PlainFileParseResult) -> list:
|
|
616
|
+
"""The definition items of the concepts a module exports, each followed by those of the concepts it mentions."""
|
|
617
|
+
items = _items(result.plain_source, DEFINITIONS)
|
|
618
|
+
with _renderer() as renderer:
|
|
619
|
+
texts = [renderer.render(item).strip() for item in items]
|
|
620
|
+
index_of: Dict[str, int] = {}
|
|
621
|
+
for index, text in enumerate(texts):
|
|
622
|
+
for concept in concept_utils.extract_concepts_from_definition(text)[0]:
|
|
623
|
+
index_of.setdefault(concept, index)
|
|
624
|
+
exported: List[Any] = []
|
|
625
|
+
seen: Set[int] = set()
|
|
626
|
+
|
|
627
|
+
def visit(concept: str) -> None:
|
|
628
|
+
index = index_of.get(concept)
|
|
629
|
+
if index is None or index in seen:
|
|
630
|
+
return
|
|
631
|
+
seen.add(index)
|
|
632
|
+
exported.append(items[index])
|
|
633
|
+
for mentioned in concept_utils.extract_concepts_from_spec_text(texts[index]):
|
|
634
|
+
if mentioned not in concept_utils.DEFAULT_CONCEPTS:
|
|
635
|
+
visit(mentioned)
|
|
636
|
+
|
|
637
|
+
entries: Any = result.plain_source_obj.metadata.get(EXPORTED_CONCEPTS_DIRECTIVE, [])
|
|
638
|
+
for entry in entries:
|
|
639
|
+
for concept in concept_utils.extract_concepts_from_definition(entry)[0]:
|
|
640
|
+
visit(concept)
|
|
641
|
+
return exported
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def _merge_exported_definitions(plain_source: dict, exported: list) -> None:
|
|
645
|
+
"""Add exported definition items after the own and imported ones, leaving out items already present."""
|
|
646
|
+
if not exported:
|
|
647
|
+
return
|
|
648
|
+
items = _items(plain_source, DEFINITIONS)
|
|
649
|
+
with _renderer() as renderer:
|
|
650
|
+
present = {renderer.render(item).strip() for item in items}
|
|
651
|
+
for item in exported:
|
|
652
|
+
text = renderer.render(item).strip()
|
|
653
|
+
if text not in present:
|
|
654
|
+
present.add(text)
|
|
655
|
+
items.append(item)
|
|
656
|
+
plain_source[DEFINITIONS] = _items_document(items)
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def _walk_requires(
|
|
660
|
+
requires: List[str],
|
|
661
|
+
template_dirs: List[str],
|
|
662
|
+
trace: List[str],
|
|
663
|
+
recorded: List[str],
|
|
664
|
+
parsed: Dict[str, Tuple[PlainFileParseResult, dict]],
|
|
665
|
+
) -> None:
|
|
666
|
+
"""Parse the modules reached through `requires` lists, depth first, recording each after its own requires."""
|
|
667
|
+
for name in requires:
|
|
668
|
+
if recorded and recorded[-1] == name:
|
|
669
|
+
continue
|
|
670
|
+
if name in trace:
|
|
671
|
+
raise PlainSyntaxError(f"Plain syntax error: Circular required module detected: {name}.")
|
|
672
|
+
code_variables: Dict[str, Any] = {}
|
|
673
|
+
result = parse_plain_file(name, code_variables, template_dirs, [], [])
|
|
674
|
+
parsed[name] = (result, code_variables)
|
|
675
|
+
if not result.required_modules and recorded:
|
|
676
|
+
raise PlainSyntaxError(
|
|
677
|
+
f"Plain syntax error: There must be a fixed order how required modules are dependent ({name})."
|
|
678
|
+
)
|
|
679
|
+
_walk_requires(result.required_modules, template_dirs, [*trace, name], recorded, parsed)
|
|
680
|
+
recorded.append(name)
|
|
844
681
|
|
|
845
|
-
if plain_spec.DEFINITIONS in marshalled_plain_source:
|
|
846
|
-
concept_utils.sort_definitions(marshalled_plain_source[plain_spec.DEFINITIONS])
|
|
847
682
|
|
|
848
|
-
|
|
683
|
+
def _validation_order(
|
|
684
|
+
requires: List[str], parsed: Dict[str, Tuple[PlainFileParseResult, dict]], order: List[str]
|
|
685
|
+
) -> List[str]:
|
|
686
|
+
for name in requires:
|
|
687
|
+
if name not in order:
|
|
688
|
+
order.append(name)
|
|
689
|
+
_validation_order(parsed[name][0].required_modules, parsed, order)
|
|
690
|
+
return order
|
|
849
691
|
|
|
850
692
|
|
|
851
|
-
def
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
693
|
+
def _module_tree(
|
|
694
|
+
name: str,
|
|
695
|
+
result: PlainFileParseResult,
|
|
696
|
+
code_variables: dict,
|
|
697
|
+
parsed: Dict[str, Tuple[PlainFileParseResult, dict]],
|
|
698
|
+
template_dirs: List[str],
|
|
699
|
+
) -> dict:
|
|
700
|
+
"""Check the shape of a module, merge the definitions its required modules export and build its tree."""
|
|
701
|
+
_check_module_shape(result, name)
|
|
702
|
+
exported: List[Any] = []
|
|
703
|
+
for required in result.required_modules:
|
|
704
|
+
required_result, required_variables = parsed[required]
|
|
705
|
+
exported.extend(_exported_definitions(required_result))
|
|
706
|
+
code_variables.update(required_variables)
|
|
707
|
+
_merge_exported_definitions(result.plain_source, exported)
|
|
708
|
+
return _build_tree(result.plain_source, template_dirs, code_variables)
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def _module_name_of(plain_source_file_name: str) -> Tuple[str, List[str]]:
|
|
712
|
+
name = plain_source_file_name.replace(os.sep, "/")
|
|
713
|
+
if os.path.isabs(plain_source_file_name):
|
|
714
|
+
return get_module_name_from_filename(os.path.basename(plain_source_file_name)), [
|
|
715
|
+
os.path.dirname(plain_source_file_name)
|
|
716
|
+
]
|
|
717
|
+
return get_module_name_from_filename(name), []
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def _parse_chain(plain_source_file_name: str, template_dirs: List[str]) -> Tuple[List[Tuple[str, dict]], List[str]]:
|
|
721
|
+
suffix = os.path.splitext(plain_source_file_name)[1]
|
|
722
|
+
if suffix != PLAIN_SOURCE_FILE_EXTENSION:
|
|
856
723
|
raise PlainSyntaxError(
|
|
857
|
-
f"Plain syntax error: Invalid plain file extension: {
|
|
724
|
+
f"Plain syntax error: Invalid plain file extension: {suffix}. Expected: {PLAIN_SOURCE_FILE_EXTENSION}."
|
|
858
725
|
)
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
)
|
|
890
|
-
|
|
891
|
-
marshalled_plain_source = validate_and_build_module_tree(
|
|
892
|
-
plain_file_parse_result, module_name, exported_definitions, code_variables, template_dirs
|
|
893
|
-
)
|
|
894
|
-
|
|
895
|
-
validate_required_modules(plain_file_parse_result.required_modules, required, template_dirs)
|
|
896
|
-
# The walk records modules deepest first, which is the chain order.
|
|
897
|
-
chain = [(chain_module_name, module.tree) for chain_module_name, module in required.items()]
|
|
898
|
-
|
|
899
|
-
return module_name, marshalled_plain_source, plain_file_parse_result.required_modules, chain
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
def plain_file_parser(plain_source_file_name: str, template_dirs: list[str]) -> tuple[str, dict, list[str]]:
|
|
903
|
-
"""Parse a module, validating it and every module in its ``requires`` chain."""
|
|
904
|
-
module_name, marshalled_plain_source, required_modules, _ = _parse_module(plain_source_file_name, template_dirs)
|
|
905
|
-
return module_name, marshalled_plain_source, required_modules
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
def parse_module_chain(plain_file_name: str, template_dirs: list[str]) -> list[tuple[str, dict]]:
|
|
909
|
-
"""Parse a module and every module in its ``requires`` chain.
|
|
910
|
-
|
|
911
|
-
Returns ``(module name, marshalled plain source tree)`` pairs: every required module
|
|
912
|
-
first, deepest ancestors first, then the module itself. A module reached through more
|
|
913
|
-
than one ``requires`` path appears once, at its first (deepest) position.
|
|
914
|
-
"""
|
|
915
|
-
module_name, marshalled_plain_source, _, chain = _parse_module(plain_file_name, template_dirs)
|
|
916
|
-
return chain + [(module_name, marshalled_plain_source)]
|
|
726
|
+
module_name, extra_dirs = _module_name_of(plain_source_file_name)
|
|
727
|
+
dirs = [*extra_dirs, *[d for d in template_dirs if os.path.abspath(d) not in map(os.path.abspath, extra_dirs)]]
|
|
728
|
+
code_variables: Dict[str, Any] = {}
|
|
729
|
+
entry = parse_plain_file(module_name, code_variables, dirs, [], [])
|
|
730
|
+
_check_module_shape(entry, module_name)
|
|
731
|
+
|
|
732
|
+
parsed: Dict[str, Tuple[PlainFileParseResult, dict]] = {}
|
|
733
|
+
recorded: List[str] = []
|
|
734
|
+
_walk_requires(entry.required_modules, dirs, [module_name], recorded, parsed)
|
|
735
|
+
|
|
736
|
+
entry_tree = _module_tree(module_name, entry, code_variables, parsed, dirs)
|
|
737
|
+
trees: Dict[str, dict] = {}
|
|
738
|
+
for name in _validation_order(entry.required_modules, parsed, []):
|
|
739
|
+
result, variables = parsed[name]
|
|
740
|
+
trees[name] = _module_tree(name, result, variables, parsed, dirs)
|
|
741
|
+
chain = [(name, trees[name]) for name in recorded]
|
|
742
|
+
chain.append((module_name, entry_tree))
|
|
743
|
+
return chain, entry.required_modules
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def parse_module_chain(plain_file_name: str, template_dirs: List[str]) -> List[Tuple[str, dict]]:
|
|
747
|
+
"""Parse an entry module and every module it requires; the deepest ancestor comes first, the entry last."""
|
|
748
|
+
return _parse_chain(plain_file_name, template_dirs)[0]
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
def plain_file_parser(plain_source_file_name: str, template_dirs: List[str]) -> Tuple[str, dict, List[str]]:
|
|
752
|
+
"""Parse an entry module file into its module name, plain source tree and `requires` list."""
|
|
753
|
+
chain, requires = _parse_chain(plain_source_file_name, template_dirs)
|
|
754
|
+
module_name, tree = chain[-1]
|
|
755
|
+
return module_name, tree, requires
|