plain-parser 1.0.0.dev1__py3-none-any.whl → 1.0.0.dev2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,22 +1,17 @@
1
- """Module file helpers and section parsing of plain-parser."""
1
+ """Parsing of spec plain files: sections, functionalities, imports, links, code variables and module checks."""
2
2
 
3
3
  import os
4
4
  import re
5
+ from contextlib import contextmanager
5
6
  from dataclasses import dataclass
6
- from typing import Any
7
+ from typing import Any, Dict, Iterator, List, Optional, Set, Tuple
7
8
 
8
9
  import frontmatter
9
- import yaml # type: ignore[import-untyped]
10
- from mistletoe import Document, block_token, markdown_renderer, span_token
11
- from mistletoe.markdown_renderer import Fragment, MarkdownRenderer
12
-
13
- from plain_parser.concept_utils import (
14
- DEFAULT_CONCEPTS,
15
- extract_concepts_from_definition,
16
- extract_concepts_from_spec_text,
17
- sort_definitions,
18
- validate_concepts,
19
- )
10
+ from liquid2 import DictLoader
11
+ from mistletoe import Document, block_token, span_token
12
+ from mistletoe.markdown_renderer import BlankLine, Fragment, MarkdownRenderer
13
+
14
+ from plain_parser import concept_utils
20
15
  from plain_parser.exceptions import (
21
16
  ImportedModuleWithFunctionalitiesError,
22
17
  MissingFunctionalitiesError,
@@ -24,64 +19,92 @@ from plain_parser.exceptions import (
24
19
  PlainSyntaxError,
25
20
  UnsupportedBase64Content,
26
21
  )
27
- from plain_parser.loaders import find_large_base64_blob, get_loaded_templates, open_from, resolve_linked_resource
28
- from plain_parser.plain_spec import is_semantic_id
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
+ )
29
36
 
37
+ RESOURCE_MARKER = "[resource]"
38
+ IMPORT_DIRECTIVE = "import"
39
+ REQUIRES_DIRECTIVE = "requires"
40
+ REQUIRED_CONCEPTS_DIRECTIVE = "required_concepts"
41
+ EXPORTED_CONCEPTS_DIRECTIVE = "exported_concepts"
30
42
  PLAIN_SOURCE_FILE_EXTENSION = ".plain"
31
43
 
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+.-]*:")
32
52
 
33
- def get_filename_from_module_name(module_name: str) -> str:
34
- return module_name + PLAIN_SOURCE_FILE_EXTENSION
35
53
 
54
+ @dataclass
55
+ class PlainFileParseResult:
56
+ plain_source: dict
57
+ plain_source_obj: frontmatter.Post
58
+ required_modules: List[str]
59
+ required_concepts: List[str]
36
60
 
37
- def get_module_name_from_filename(filename: str) -> str:
38
- return filename.replace(PLAIN_SOURCE_FILE_EXTENSION, "")
39
61
 
62
+ class _PlainMarkdownRenderer(MarkdownRenderer):
63
+ """Markdown renderer that writes a link as a code span holding the resource marker and the link text."""
40
64
 
41
- def normalize_line_endings(plain_source_text: str) -> str:
42
- return plain_source_text.replace("\r\n", "\n").replace("\r", "\n")
65
+ def render_link(self, token):
66
+ return self.embed_span(Fragment(f"`{RESOURCE_MARKER}"), token.children, Fragment("`"))
43
67
 
44
68
 
45
- # ---------------------------------------------------------------------------
46
- # Parsing of the section structure of a module
47
- # ---------------------------------------------------------------------------
69
+ class _IndentingDictLoader(Plain2CodeLoaderMixin, DictLoader):
70
+ pass
48
71
 
49
- RESOURCE_MARKER = "[resource]"
50
- IMPORT_DIRECTIVE = "import"
51
- REQUIRES_DIRECTIVE = "requires"
52
- REQUIRED_CONCEPTS_DIRECTIVE = "required_concepts"
53
- EXPORTED_CONCEPTS_DIRECTIVE = "exported_concepts"
54
72
 
55
- ALLOWED_HEADINGS = ["definitions", "implementation reqs", "test reqs", "functional specs"]
56
- _SECTION_LINE = re.compile(r"^\*\*\*(.+?)\*\*\*$")
57
- _TEST_SECTION_LINE = re.compile(r"^[ \t]*\*\*\*(conformance tests|acceptance tests)\*\*\*[ \t]*$", re.MULTILINE)
73
+ @contextmanager
74
+ def _renderer() -> Iterator[_PlainMarkdownRenderer]:
75
+ with _PlainMarkdownRenderer() as renderer:
76
+ yield renderer
58
77
 
59
78
 
60
- @dataclass
61
- class PlainFileParseResult:
62
- plain_source: dict
63
- plain_source_obj: frontmatter.Post
64
- required_modules: list[str]
65
- required_concepts: list[str]
79
+ def get_filename_from_module_name(module_name: str) -> str:
80
+ return module_name + PLAIN_SOURCE_FILE_EXTENSION
66
81
 
67
82
 
68
- class _PlainRenderer(MarkdownRenderer):
69
- """MarkdownRenderer writing a link as a code span `[resource]text`."""
83
+ def get_module_name_from_filename(filename: str) -> str:
84
+ return filename.replace(PLAIN_SOURCE_FILE_EXTENSION, "")
70
85
 
71
- def render_link_or_image(self, token: Any, target: str) -> Any:
72
- if isinstance(token, span_token.Link):
73
- children: Any = token.children or []
74
- return self.embed_span(Fragment("`" + RESOURCE_MARKER), children, Fragment("`"))
75
- return super().render_link_or_image(token, target)
86
+
87
+ def normalize_line_endings(plain_source_text: str) -> str:
88
+ return plain_source_text.replace("\r\n", "\n").replace("\r", "\n")
76
89
 
77
90
 
78
- class _Item(dict):
79
- """List item dict that remembers its block token."""
91
+ def restore_stripped_lines(plain_source_text: str, content: str) -> str:
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
80
99
 
81
- token: Any = None
82
100
 
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)
83
105
 
84
- def _where(line: int | None, module_name: str | None) -> str:
106
+
107
+ def _where(line: Optional[int], module_name: Optional[str]) -> str:
85
108
  where = "Syntax error"
86
109
  if line is not None:
87
110
  where += f" at line {line}"
@@ -90,582 +113,643 @@ def _where(line: int | None, module_name: str | None) -> str:
90
113
  return where
91
114
 
92
115
 
93
- def _strip_quotes(token: Any) -> None:
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}")
118
+
119
+
120
+ def _walk(token) -> Iterator[Any]:
121
+ yield token
122
+ for child in getattr(token, "children", None) or []:
123
+ yield from _walk(child)
124
+
125
+
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(("/", "\\")):
136
+ raise PlainSyntaxError(
137
+ f"Plain syntax error: Only relative links are allowed{where} (text: {_link_text(token)}, "
138
+ f"target: {target})."
139
+ )
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):
144
+ raise PlainSyntaxError(
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."
148
+ )
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))
152
+ raise PlainSyntaxError(
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}"
155
+ )
156
+ if not os.path.isfile(resolved):
157
+ raise PlainSyntaxError(
158
+ f"Plain syntax error: Link {target}{where} must be a file (resolved to {resolved})."
159
+ )
160
+ linked_resources.append({"text": text, "target": target})
161
+ return linked_resources
162
+
163
+
164
+ def _link_text(token) -> str:
165
+ return "".join(getattr(child, "content", "") for child in token.children or [])
166
+
167
+
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})
179
+
180
+
181
+ def _drop_quotes(token) -> None:
94
182
  children = getattr(token, "children", None)
95
183
  if not children:
96
184
  return
97
- token.children = [c for c in children if not isinstance(c, block_token.Quote)]
98
- for child in token.children:
99
- _strip_quotes(child)
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)
100
211
 
101
212
 
102
- def _heading_text(block: Any, renderer: Any) -> str:
103
- parts = []
104
- for child in block.children or []:
105
- parts.append(child.content if isinstance(child, span_token.RawText) else renderer.render(child))
106
- return "".join(parts).strip()
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()
107
217
 
108
218
 
109
- def _collect_links(token: Any) -> list[dict]:
110
- links: list[dict] = []
111
- for child in getattr(token, "children", None) or []:
112
- if isinstance(child, span_token.Link):
113
- text = "".join(getattr(c, "content", "") for c in child.children or [])
114
- links.append({"text": text, "target": child.target})
115
- links.extend(_collect_links(child))
116
- return links
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
+ )
117
236
 
118
237
 
119
- def _plain_text(block: Any, text: str) -> str:
120
- """Offending block text without markup."""
121
- if isinstance(block, block_token.List):
122
- text = re.sub(r"^\s*(?:[-*+]|\d+[.)])\s+", "", text)
123
- elif isinstance(block, (block_token.CodeFence, block_token.BlockCode)):
124
- inner = block.children[0].content if block.children else ""
125
- return inner.strip()
126
- return text
238
+ def _is_blank(token) -> bool:
239
+ return isinstance(token, BlankLine)
127
240
 
128
241
 
129
- def _check_body(entries: list, module_name: str | None) -> None:
130
- if not entries:
131
- return
132
- last = entries[-1]
133
- if not any(not isinstance(t, markdown_renderer.BlankLine) for t in last["tokens"]):
134
- where = _where(last["line_number"], module_name)
135
- raise PlainSyntaxError(f"Plain syntax error: {where}: Functionality `{last['id']}` has no body.")
136
- tokens = last["tokens"]
137
- while tokens and isinstance(tokens[-1], markdown_renderer.BlankLine):
138
- tokens.pop()
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."
246
+ )
139
247
 
140
248
 
141
- def _normalize_concept_list(value: Any, directive: str) -> list[str]:
142
- if value is None:
143
- return []
144
- if not isinstance(value, list):
145
- raise AssertionError(f"Syntax error: Invalid {directive} metadata. Expected a list.")
146
- result: list[str] = []
147
- for entry in value:
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
+ )
333
+
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:
148
386
  if isinstance(entry, str):
149
- result.append(f"- {entry}")
387
+ texts.append(f"- {entry}")
150
388
  elif isinstance(entry, dict):
151
- result.extend(f"- {key}: {val}" for key, val in entry.items())
389
+ texts.extend(f"- {key}: {value}" for key, value in entry.items())
152
390
  else:
153
391
  raise PlainSyntaxError(
154
392
  f"Plain syntax error: Invalid {directive} metadata. Expected a dictionary or a string."
155
393
  )
156
- return result
394
+ metadata[directive] = texts
395
+
396
+
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]
157
401
 
158
402
 
159
- def _defined_concepts(sections: dict[str, list]) -> set[str]:
160
- defined: set[str] = set()
161
- for item in sections.get("definitions", []):
162
- defined.update(extract_concepts_from_definition(item["markdown"])[0])
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)
163
409
  return defined
164
410
 
165
411
 
166
412
  def _check_exported_concepts(
167
- exported: list[str], defined: set[str], module_name: str | None, has_requires: bool
413
+ metadata: dict, plain_source: dict, requires: List[str], module_name: Optional[str]
168
414
  ) -> None:
169
415
  subject = f"Module '{module_name}'" if module_name else "Module"
170
- for entry in exported:
171
- concepts, errors = extract_concepts_from_definition(entry)
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)
172
419
  if errors or not concepts:
173
420
  raise PlainSyntaxError(
174
421
  f"Plain syntax error: {subject} exports an invalid concept (`{entry}`). "
175
422
  "Expected a concept token, e.g. :ConceptName:."
176
423
  )
177
424
  for concept in concepts:
178
- if concept in DEFAULT_CONCEPTS:
425
+ if concept in concept_utils.DEFAULT_CONCEPTS:
179
426
  raise PlainSyntaxError(
180
- f"Plain syntax error: {subject} cannot export default concept :{concept}:. "
427
+ f"Plain syntax error: {subject} cannot export default concept {concept}. "
181
428
  "Only user-defined concepts can be exported."
182
429
  )
183
430
  if concept not in defined:
184
- message = f"Plain syntax error: {subject} exports undefined concept :{concept}:."
185
- if has_requires:
431
+ message = f"Plain syntax error: {subject} exports undefined concept {concept}."
432
+ if requires:
186
433
  message += (
187
- " An exported concept must be defined in this module's definitions or in an imported "
188
- "module; a concept inherited through requires cannot be re-exported."
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."
189
436
  )
190
437
  raise PlainSyntaxError(message)
191
438
 
192
439
 
193
- def read_module_text(module_name: str, template_dirs: list[str]) -> str:
194
- """Return the UTF-8 text of `<module_name>.plain` from the first template dir holding it."""
195
- text = open_from(template_dirs, get_filename_from_module_name(module_name))
196
- if text is None:
197
- raise ModuleDoesNotExistError(f"Module does not exist ({module_name}).")
198
- blob = find_large_base64_blob(text)
199
- if blob is not None:
200
- raise UnsupportedBase64Content(
201
- f"Module '{module_name}' contains a base64-encoded blob ({len(blob)} characters) inlined in the "
202
- "specification. This is not supported. Remove the base64 data from the .plain file or if necessary, "
203
- "include the binary file path in the specification."
204
- )
205
- return text
206
-
207
-
208
- def parse_plain_file(
209
- module_name: str,
210
- code_variables: dict,
211
- template_dirs: list[str],
212
- imported_modules: list[str],
213
- modules_trace: list[str],
214
- ) -> PlainFileParseResult:
215
- text = read_module_text(module_name, template_dirs)
216
- return parse_plain_source(text, code_variables, template_dirs, imported_modules, modules_trace, module_name)
217
-
218
-
219
440
  def parse_plain_source(
220
441
  plain_source_text: str,
221
442
  code_variables: dict,
222
- template_dirs: list[str],
223
- imported_modules: list[str],
224
- modules_trace: list[str],
225
- module_name: str | None = None,
443
+ template_dirs: List[str],
444
+ imported_modules: List[str],
445
+ modules_trace: List[str],
446
+ module_name: Optional[str] = None,
226
447
  ) -> PlainFileParseResult:
448
+ """Parse the text of a module into its list sections and functionalities, merging its imports first."""
227
449
  text = normalize_line_endings(plain_source_text)
228
450
  try:
229
451
  post = frontmatter.loads(text)
230
- except yaml.YAMLError as e:
231
- raise PlainSyntaxError(f"Plain syntax error: Invalid frontmatter: {e}") from e
232
- if not isinstance(post.metadata, dict):
233
- raise PlainSyntaxError(f"Plain syntax error: Invalid frontmatter: {post.metadata!r} is not a mapping")
234
- content = post.content
235
- if content and text.endswith(content + text[len(text.rstrip()) :]):
236
- content += text[len(text.rstrip()) :]
237
- index = text.find(content) if content else len(text)
238
- line_offset = text.count("\n", 0, max(index, 0))
239
-
240
- rendered, _ = get_loaded_templates(template_dirs, content, module_name, code_variables)
241
-
242
- match = _TEST_SECTION_LINE.search(rendered)
243
- if match:
244
- line = rendered.count("\n", 0, match.start()) + 1 + line_offset
245
- raise PlainSyntaxError(
246
- f"Plain syntax error: {_where(line, module_name)}: The `{match.group(1)}` section is not allowed "
247
- "in a spec plain file; test scenarios live in test plain files."
248
- )
249
-
250
- with _PlainRenderer() as renderer:
251
- document = Document(rendered)
252
- _strip_quotes(document)
253
- sections: dict[str, list] = {}
254
- current: str | None = None
255
- for block in document.children or []:
256
- if isinstance(block, markdown_renderer.BlankLine):
257
- if current == "functional specs" and sections[current]:
258
- sections[current][-1]["tokens"].append(block)
259
- continue
260
- line = (getattr(block, "line_number", 1) or 1) + line_offset
261
- where = _where(line, module_name)
262
- block_text = renderer.render(block).strip()
263
- if isinstance(block, block_token.Paragraph) and _SECTION_LINE.match(block_text):
264
- heading = _SECTION_LINE.match(block_text).group(1) # type: ignore[union-attr]
265
- if heading not in ALLOWED_HEADINGS:
266
- raise PlainSyntaxError(
267
- f"Plain syntax error: {where}: Invalid specification heading (`{heading}`). "
268
- "Allowed headings: definitions, implementation reqs, test reqs, functional specs"
269
- )
270
- if heading in sections:
271
- raise PlainSyntaxError(
272
- f"Plain syntax error: {where}: Duplicate specification heading (`{heading}`)"
273
- )
274
- if heading == "definitions" and sections:
275
- raise PlainSyntaxError(
276
- f"Plain syntax error: {where}: Definitions specification must be the first "
277
- f"specification in the section (`{heading}`)"
278
- )
279
- if current == "functional specs":
280
- _check_body(sections[current], module_name)
281
- sections[heading] = []
282
- current = heading
283
- continue
284
- if isinstance(block, block_token.Heading):
285
- if current != "functional specs":
286
- raise PlainSyntaxError(
287
- f"Plain syntax error: {where}: A `# <func-id>` heading is allowed only in the "
288
- f"functional specs section (`{_heading_text(block, renderer)}`)."
289
- )
290
- htext = _heading_text(block, renderer)
291
- if block.level != 1:
292
- raise PlainSyntaxError(
293
- f"Plain syntax error: {where}: Invalid heading level {block.level} (`{htext}`). "
294
- "A functionality heading is `# <func-id>`."
295
- )
296
- if not is_semantic_id(htext):
297
- raise PlainSyntaxError(
298
- f"Plain syntax error: {where}: Invalid func-id (`{htext}`). A func-id is lowercase "
299
- "letters and digits, with single hyphens between them."
300
- )
301
- for existing in sections[current]:
302
- if existing["id"] == htext:
303
- raise PlainSyntaxError(
304
- f"Plain syntax error: {where}: Duplicate func-id `{htext}`; "
305
- f"it is first used at line {existing['line_number']}."
306
- )
307
- _check_body(sections[current], module_name)
308
- sections[current].append({"id": htext, "line_number": line, "tokens": [], "linked_resources": []})
309
- continue
310
- if current == "functional specs":
311
- if not sections[current]:
312
- raise PlainSyntaxError(
313
- f"Plain syntax error: {where}: Content before the first `# <func-id>` heading in the "
314
- f"functional specs section (`{_plain_text(block, block_text)}`). A functionality is a `# <func-id>` heading "
315
- "followed by its body; the previous syntax is not supported."
316
- )
317
- entry = sections[current][-1]
318
- entry["tokens"].append(block)
319
- entry["linked_resources"].extend(_collect_links(block))
320
- continue
321
- if current is None:
322
- if isinstance(block, block_token.List):
323
- raise PlainSyntaxError(
324
- f"Plain syntax error: {where}: Missing specification heading (`{block_text}`)"
325
- )
326
- raise PlainSyntaxError(f"Plain syntax error: {where}: Invalid specification (`{block_text}`)")
327
- if isinstance(block, block_token.List):
328
- document_children = sections[current]
329
- for item in block.children or []:
330
- entry_item = _Item(markdown=renderer.render(item).strip())
331
- entry_item.token = item
332
- document_children.append(entry_item)
333
- elif isinstance(block, block_token.Paragraph):
334
- raise PlainSyntaxError(f"Plain syntax error: {where}: Invalid specification (`{block_text}`)")
335
- else:
336
- raise PlainSyntaxError(
337
- f"Plain syntax error: {where}: Invalid source structure (`{_plain_text(block, block_text)}`)"
338
- )
339
-
340
- if current == "functional specs":
341
- _check_body(sections[current], module_name)
342
-
343
- imports: Any = post.metadata.get(IMPORT_DIRECTIVE) or []
344
- if isinstance(imports, str):
345
- imports = [imports]
346
- trace = modules_trace + [module_name] if module_name else list(modules_trace)
347
- merged: dict[str, list] = {}
348
- imported_required: list[str] = []
349
- for imported in imports:
350
- if imported in trace:
351
- raise PlainSyntaxError(f"Plain syntax error: Circular import detected: {imported}.")
352
- if imported in imported_modules:
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:
353
469
  continue
354
- result = parse_plain_file(imported, code_variables, template_dirs, imported_modules, trace)
355
- if "functional specs" in result.plain_source:
470
+ imported = parse_plain_file(imported_name, code_variables, template_dirs, imported_modules, trace)
471
+ if FUNCTIONAL_REQUIREMENTS in imported.plain_source:
356
472
  raise ImportedModuleWithFunctionalitiesError(
357
- f"Module '{imported}' is imported but contains functional specs. Imported modules may only provide "
358
- "definitions, implementation reqs, and test reqs \u2014 use 'requires' instead of 'import' if this "
359
- "module's functionalities should be built on."
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."
360
476
  )
361
- imported_modules.append(imported)
362
- imported_required.extend(result.required_concepts)
363
- for name, items in result.plain_source.items():
364
- merged.setdefault(name, []).extend(items)
365
- if merged:
366
- for name, items in sections.items():
367
- merged.setdefault(name, []).extend(items)
368
- sections = {name: merged[name] for name in ALLOWED_HEADINGS if name in merged}
369
-
370
- requires: Any = post.metadata.get(REQUIRES_DIRECTIVE) or []
371
- if isinstance(requires, str):
372
- requires = [requires]
373
- has_requires = bool(requires)
374
- defined = _defined_concepts(sections)
375
- exported_list = _normalize_concept_list(post.metadata.get(EXPORTED_CONCEPTS_DIRECTIVE), EXPORTED_CONCEPTS_DIRECTIVE)
376
- if EXPORTED_CONCEPTS_DIRECTIVE in post.metadata:
377
- post.metadata[EXPORTED_CONCEPTS_DIRECTIVE] = exported_list
378
- _check_exported_concepts(
379
- exported_list,
380
- defined,
381
- module_name,
382
- has_requires,
383
- )
384
- required_concepts = _normalize_concept_list(
385
- post.metadata.get(REQUIRED_CONCEPTS_DIRECTIVE), REQUIRED_CONCEPTS_DIRECTIVE
386
- )
387
- if REQUIRED_CONCEPTS_DIRECTIVE in post.metadata:
388
- post.metadata[REQUIRED_CONCEPTS_DIRECTIVE] = required_concepts
389
- for entry in imported_required:
390
- concepts = extract_concepts_from_definition(entry)[0]
391
- if (not concepts or not all(c in defined for c in concepts)) and entry not in required_concepts:
392
- required_concepts.append(entry)
393
- parsed = PlainFileParseResult(sections, post, list(requires), required_concepts)
394
- parsed.code_variables = code_variables # type: ignore[attr-defined]
395
- return parsed
396
-
397
-
398
- _URL_SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.\-]*:")
399
-
400
-
401
- def find_linked_resources(tokens: Any, template_dirs: list[str], where: str = "") -> list[dict]:
402
- """Return the links of the token(s) in text order as {"text", "target"}, validated over template_dirs."""
403
- if not isinstance(tokens, (list, tuple)):
404
- tokens = [tokens]
405
- found: list[dict] = []
406
- for token in tokens:
407
- for link in _iter_links(token):
408
- children = link.children or []
409
- target = link.target
410
- if len(children) != 1 or not isinstance(children[0], span_token.RawText) or not children[0].content:
411
- raise PlainSyntaxError(f"Plain syntax error: Link{where} must have text specified (link: {target}).")
412
- text = children[0].content
413
- if _URL_SCHEME.match(target) or target.startswith(("/", "\\")) or os.path.isabs(target):
414
- raise PlainSyntaxError(
415
- f"Plain syntax error: Only relative links are allowed{where} (text: {text}, target: {target})."
416
- )
417
- resolved = resolve_linked_resource(template_dirs, target)
418
- if resolved is None:
419
- dirs = "\n".join(f" {i}. {d}" for i, d in enumerate(template_dirs, 1))
420
- raise PlainSyntaxError(
421
- f"Plain syntax error: Link {target}{where} does not exist. Linked resources are looked up "
422
- f"relative to the following directories (highest to lowest precedence):\n{dirs}"
423
- )
424
- if not os.path.isfile(resolved):
425
- raise PlainSyntaxError(
426
- f"Plain syntax error: Link {target}{where} must be a file (resolved to {resolved})."
427
- )
428
- if target.endswith(PLAIN_SOURCE_FILE_EXTENSION):
429
- raise PlainSyntaxError(
430
- f"Referenced resource '{target}'{where} is a .plain file. Referencing .plain files through "
431
- "Linked Resources is not supported. Please use the import section to include definitions "
432
- "or implementation/test requirements from another module."
433
- )
434
- found.append({"text": text, "target": target})
435
- return found
436
-
437
-
438
- def _iter_links(token: Any) -> Any:
439
- if isinstance(token, span_token.Link):
440
- yield token
441
- for child in getattr(token, "children", None) or []:
442
- yield from _iter_links(child)
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]
483
+ )
484
+ required_concepts.extend(imported.required_concepts)
443
485
 
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]
444
492
 
445
- _TOKEN = re.compile(r"[0-9a-f]{32}")
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)
446
498
 
447
499
 
448
- def _record_code_variables(item: dict, code_variables: dict | None) -> None:
449
- """Replace recorded code-variable tokens in item['markdown'] with placeholders; list them in the item."""
450
- if not code_variables:
451
- return
452
- found: list[dict] = []
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
453
506
 
454
- def replace(match: Any) -> str:
455
- entry = code_variables.get(match.group(0))
456
- if not isinstance(entry, dict) or len(entry) != 1:
457
- return match.group(0)
458
- name, value = next(iter(entry.items()))
459
- found.append({"name": name, "value": value})
460
- return "{{ " + name + " }}"
461
507
 
462
- item["markdown"] = _TOKEN.sub(replace, item["markdown"])
463
- if found:
464
- item["code_variables"] = found
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)
465
527
 
466
528
 
467
- def marshall_plain_source(
468
- input_plain_source: Any, template_dirs: list[str] | None = None, code_variables: dict | None = None
469
- ) -> dict:
470
- """Turn the sections of a parse result (or its section dict) into a plain source tree.
471
-
472
- With template_dirs, the links of each item and body are resolved and recorded as linked_resources.
473
- """
474
- sections = getattr(input_plain_source, "plain_source", input_plain_source)
475
- if code_variables is None:
476
- code_variables = getattr(input_plain_source, "code_variables", None)
477
- tree: dict = {}
478
- with _PlainRenderer() as renderer:
479
- for name, entries in sections.items():
480
- if name != "functional specs":
481
- items = []
482
- for entry in entries:
483
- item: dict = {"markdown": entry["markdown"]}
484
- token = getattr(entry, "token", None)
485
- if token is not None and template_dirs is not None:
486
- links = find_linked_resources(token, template_dirs)
487
- if links:
488
- item["linked_resources"] = links
489
- _record_code_variables(item, code_variables)
490
- items.append(item)
491
- tree[name] = items
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:
492
535
  continue
493
- funcs = []
494
- for entry in entries:
495
- tokens = list(entry["tokens"])
496
- while tokens and isinstance(tokens[-1], markdown_renderer.BlankLine):
497
- tokens.pop()
498
- markdown = "\n".join(renderer.blocks_to_lines(tokens, max_line_length=None)).strip("\n")
499
- if template_dirs is not None:
500
- links = find_linked_resources(tokens, template_dirs, _where(entry["line_number"], None)[12:])
501
- else:
502
- links = list(entry["linked_resources"])
503
- func = {
504
- "id": entry["id"],
505
- "markdown": markdown,
506
- "linked_resources": links,
507
- "conformance_tests": [],
508
- "acceptance_tests": [],
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: [],
509
552
  }
510
- _record_code_variables(func, code_variables)
511
- funcs.append(func)
512
- tree[name] = funcs
553
+ for functionality in input_plain_source[FUNCTIONAL_REQUIREMENTS]
554
+ ]
513
555
  return tree
514
556
 
515
557
 
516
- def check_module_shape(parse_result: PlainFileParseResult, module_name: str) -> None:
517
- """Check that a parsed module has the shape needed for rendering."""
518
- if parse_result.required_concepts:
519
- missing: list[str] = []
520
- for entry in parse_result.required_concepts:
521
- concepts = extract_concepts_from_definition(entry)[0]
522
- missing.extend(f":{c}:" for c in concepts) if concepts else missing.append(entry)
558
+ def _check_module_shape(result: PlainFileParseResult, module_name: str) -> None:
559
+ if result.required_concepts:
523
560
  raise PlainSyntaxError(
524
- f"Plain syntax error: Not all required concepts were defined. Missing required concepts: "
525
- f"{', '.join(missing)}."
561
+ "Plain syntax error: Not all required concepts were defined. Missing required concepts: "
562
+ + ", ".join(result.required_concepts)
563
+ + "."
526
564
  )
527
- sections = parse_result.plain_source
528
- if "functional specs" not in sections:
565
+ if FUNCTIONAL_REQUIREMENTS not in result.plain_source:
529
566
  raise MissingFunctionalitiesError(
530
567
  f"Module '{module_name}' does not have any functionality specified. "
531
568
  "At least one functionality is required for rendering."
532
569
  )
533
- if not sections["functional specs"]:
570
+ if not result.plain_source[FUNCTIONAL_REQUIREMENTS]:
534
571
  raise PlainSyntaxError(
535
572
  f"Plain syntax error: Module '{module_name}' has a 'functional specs' section without a "
536
573
  "`# <func-id>` heading. A functionality is a `# <func-id>` heading followed by its body; "
537
574
  "the previous syntax is not supported."
538
575
  )
539
- if not sections.get("implementation reqs"):
576
+ if not _items(result.plain_source, NON_FUNCTIONAL_REQUIREMENTS):
540
577
  message = (
541
578
  f"Plain syntax error: Module '{module_name}' defines functionalities but specifies no implementation "
542
579
  "reqs. At least one implementation req is required."
543
580
  )
544
- if parse_result.required_modules:
581
+ if result.required_modules:
545
582
  message += (
546
- " Implementation reqs are not inherited through 'requires' \u2014 add them to this module, "
583
+ " Implementation reqs are not inherited through 'requires' — add them to this module, "
547
584
  "or 'import' a module that provides them."
548
585
  )
549
586
  raise PlainSyntaxError(message)
550
587
 
551
588
 
552
- def _exported_definitions(required_modules: list[str], template_dirs: list[str]) -> list[dict]:
553
- """Exported definition items of the required modules, each followed by the items of the concepts it mentions."""
554
- items: list[dict] = []
555
- seen: set[str] = set()
556
- for required in required_modules:
557
- result = parse_plain_file(required, {}, template_dirs, [], [])
558
- exported = result.plain_source_obj.metadata.get(EXPORTED_CONCEPTS_DIRECTIVE) or []
559
- definitions = result.plain_source.get("definitions", [])
560
- by_concept: dict[str, dict] = {}
561
- for item in definitions:
562
- for concept in extract_concepts_from_definition(item["markdown"])[0]:
563
- by_concept.setdefault(concept, item)
564
- visited: set[str] = set()
565
-
566
- def add(concept: str) -> None:
567
- item = by_concept.get(concept)
568
- if concept in visited or item is None:
569
- return
570
- visited.add(concept)
571
- if item["markdown"] not in seen:
572
- seen.add(item["markdown"])
573
- items.append({"markdown": item["markdown"]})
574
- for mentioned in extract_concepts_from_spec_text(item["markdown"]):
575
- if mentioned not in DEFAULT_CONCEPTS:
576
- add(mentioned)
577
-
578
- for entry in exported:
579
- for concept in extract_concepts_from_definition(entry)[0]:
580
- add(concept)
581
- return items
582
-
583
-
584
- def _validate_required(
585
- requires: list[str], template_dirs: list[str], trees: dict[str, dict], seen: set[str] | None = None
586
- ) -> None:
587
- """Validate each required module once (shape, then tree): the requires list order, each module's own first-after."""
588
- seen = set() if seen is None else seen
589
- for name in requires:
590
- if name in seen:
591
- continue
592
- seen.add(name)
593
- trees[name], own = _parse_module(name, template_dirs, walk=False)
594
- _validate_required(own, template_dirs, trees, seen)
595
-
596
-
597
- def _parse_module(
598
- module_name: str, template_dirs: list[str], walk: bool = True, trees: dict[str, dict] | None = None
599
- ) -> tuple[dict, list[str]]:
600
- code_variables: dict = {}
601
- result = parse_plain_file(module_name, code_variables, template_dirs, [], [])
602
- check_module_shape(result, module_name)
603
- if walk:
604
- _walk_requires(module_name, template_dirs, [], [])
605
- exported = _exported_definitions(result.required_modules, template_dirs)
606
- if exported:
607
- own = result.plain_source.get("definitions", [])
608
- known = {i["markdown"] for i in own}
609
- merged = [i for i in exported if i["markdown"] not in known]
610
- sections = dict(result.plain_source)
611
- sections["definitions"] = list(own) + merged
612
- result.plain_source = {n: sections[n] for n in ALLOWED_HEADINGS if n in sections}
613
- tree = marshall_plain_source(result, template_dirs, code_variables)
614
- errors = validate_concepts(tree)
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)
615
606
  if errors:
616
607
  raise PlainSyntaxError(
617
608
  f"Plain syntax error: Found {len(errors)} errors in the plain file:\n" + "\n".join(errors)
618
609
  )
619
- if "definitions" in tree:
620
- sort_definitions(tree["definitions"])
621
- if walk:
622
- _validate_required(list(result.required_modules), template_dirs, trees if trees is not None else {})
623
- return tree, list(result.required_modules)
624
-
625
-
626
- def plain_file_parser(plain_source_file_name: str, template_dirs: list[str]) -> tuple[str, dict, list[str]]:
627
- """Parse an entry module file into (module name, plain source tree, its requires list)."""
628
- suffix = os.path.splitext(plain_source_file_name)[1]
629
- if suffix != PLAIN_SOURCE_FILE_EXTENSION:
630
- raise PlainSyntaxError(f"Plain syntax error: Invalid plain file extension: {suffix}. Expected: .plain.")
631
- if os.path.isabs(plain_source_file_name):
632
- module_name = get_module_name_from_filename(os.path.basename(plain_source_file_name))
633
- else:
634
- module_name = get_module_name_from_filename(plain_source_file_name.replace(os.sep, "/"))
635
- tree, requires = _parse_module(module_name, template_dirs)
636
- return module_name, tree, requires
610
+ if DEFINITIONS in tree:
611
+ concept_utils.sort_definitions(tree[DEFINITIONS])
612
+ return tree
637
613
 
638
614
 
639
- def _walk_requires(module_name: str, template_dirs: list[str], recorded: list[str], trace: list[str]) -> None:
640
- requires = parse_plain_file(module_name, {}, template_dirs, [], []).required_modules
641
- trace = trace + [module_name]
642
- for required in requires:
643
- if recorded and recorded[-1] == required:
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:
644
669
  continue
645
- if required in trace:
646
- raise PlainSyntaxError(f"Plain syntax error: Circular required module detected: {required}.")
647
- required_requires = parse_plain_file(required, {}, template_dirs, [], []).required_modules
648
- if not required_requires and recorded:
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:
649
676
  raise PlainSyntaxError(
650
- f"Plain syntax error: There must be a fixed order how required modules are dependent ({required})."
677
+ f"Plain syntax error: There must be a fixed order how required modules are dependent ({name})."
651
678
  )
652
- _walk_requires(required, template_dirs, recorded, trace)
653
- if module_name not in recorded:
654
- recorded.append(module_name)
679
+ _walk_requires(result.required_modules, template_dirs, [*trace, name], recorded, parsed)
680
+ recorded.append(name)
655
681
 
656
682
 
657
- def parse_module_chain(plain_file_name: str, template_dirs: list[str]) -> list[tuple[str, dict]]:
658
- """Parse an entry module and every module reached through requires: deepest first, entry last."""
659
- suffix = os.path.splitext(plain_file_name)[1]
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
691
+
692
+
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]
660
722
  if suffix != PLAIN_SOURCE_FILE_EXTENSION:
661
- raise PlainSyntaxError(f"Plain syntax error: Invalid plain file extension: {suffix}. Expected: .plain.")
662
- if os.path.isabs(plain_file_name):
663
- entry = get_module_name_from_filename(os.path.basename(plain_file_name))
664
- else:
665
- entry = get_module_name_from_filename(plain_file_name.replace(os.sep, "/"))
666
- trees: dict[str, dict] = {}
667
- tree, _ = _parse_module(entry, template_dirs, trees=trees)
668
- trees[entry] = tree
669
- recorded: list[str] = []
670
- _walk_requires(entry, template_dirs, recorded, [])
671
- return [(name, trees[name]) for name in recorded]
723
+ raise PlainSyntaxError(
724
+ f"Plain syntax error: Invalid plain file extension: {suffix}. Expected: {PLAIN_SOURCE_FILE_EXTENSION}."
725
+ )
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