plain-parser 1.0.0.dev1__tar.gz → 1.0.0.dev2__tar.gz

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.
Files changed (51) hide show
  1. plain_parser-1.0.0.dev2/.flake8 +3 -0
  2. plain_parser-1.0.0.dev2/LICENSE +21 -0
  3. {plain_parser-1.0.0.dev1 → plain_parser-1.0.0.dev2}/PKG-INFO +15 -2
  4. plain_parser-1.0.0.dev2/README.md +9 -0
  5. {plain_parser-1.0.0.dev1 → plain_parser-1.0.0.dev2}/pyproject.toml +22 -5
  6. {plain_parser-1.0.0.dev1 → plain_parser-1.0.0.dev2}/src/plain_parser/__init__.py +3 -3
  7. plain_parser-1.0.0.dev2/src/plain_parser/cli.py +277 -0
  8. plain_parser-1.0.0.dev2/src/plain_parser/concept_utils.py +205 -0
  9. plain_parser-1.0.0.dev2/src/plain_parser/graph.py +168 -0
  10. plain_parser-1.0.0.dev2/src/plain_parser/liquid_nodes.py +45 -0
  11. plain_parser-1.0.0.dev2/src/plain_parser/loaders.py +162 -0
  12. plain_parser-1.0.0.dev2/src/plain_parser/plain_file.py +755 -0
  13. plain_parser-1.0.0.dev2/src/plain_parser/plain_spec.py +224 -0
  14. plain_parser-1.0.0.dev2/src/plain_parser/project.py +169 -0
  15. plain_parser-1.0.0.dev2/src/plain_parser/test_plain_file.py +250 -0
  16. plain_parser-1.0.0.dev2/tests/__init__.py +0 -0
  17. plain_parser-1.0.0.dev2/tests/test_cli.py +66 -0
  18. plain_parser-1.0.0.dev2/tests/test_concept_utils.py +44 -0
  19. plain_parser-1.0.0.dev2/tests/test_graph.py +17 -0
  20. plain_parser-1.0.0.dev2/tests/test_loaders.py +62 -0
  21. plain_parser-1.0.0.dev2/tests/test_plainfileparser.py +95 -0
  22. plain_parser-1.0.0.dev2/tests/test_plainspec.py +43 -0
  23. plain_parser-1.0.0.dev2/tests/test_project.py +29 -0
  24. plain_parser-1.0.0.dev2/tests/test_test_plain_file.py +17 -0
  25. plain_parser-1.0.0.dev1/resources/error_messages.md +0 -154
  26. plain_parser-1.0.0.dev1/resources/python_api.md +0 -199
  27. plain_parser-1.0.0.dev1/src/plain_parser/cli.py +0 -246
  28. plain_parser-1.0.0.dev1/src/plain_parser/concept_utils.py +0 -188
  29. plain_parser-1.0.0.dev1/src/plain_parser/graph.py +0 -132
  30. plain_parser-1.0.0.dev1/src/plain_parser/liquid_nodes.py +0 -63
  31. plain_parser-1.0.0.dev1/src/plain_parser/loaders.py +0 -149
  32. plain_parser-1.0.0.dev1/src/plain_parser/plain_file.py +0 -671
  33. plain_parser-1.0.0.dev1/src/plain_parser/plain_spec.py +0 -223
  34. plain_parser-1.0.0.dev1/src/plain_parser/project.py +0 -155
  35. plain_parser-1.0.0.dev1/src/plain_parser/test_plain_file.py +0 -230
  36. plain_parser-1.0.0.dev1/tests/test_cli.py +0 -174
  37. plain_parser-1.0.0.dev1/tests/test_concept_utils.py +0 -103
  38. plain_parser-1.0.0.dev1/tests/test_exceptions.py +0 -24
  39. plain_parser-1.0.0.dev1/tests/test_graph.py +0 -58
  40. plain_parser-1.0.0.dev1/tests/test_import_modules.py +0 -114
  41. plain_parser-1.0.0.dev1/tests/test_liquid_rendering.py +0 -107
  42. plain_parser-1.0.0.dev1/tests/test_loaders.py +0 -61
  43. plain_parser-1.0.0.dev1/tests/test_parse_scenarios.py +0 -88
  44. plain_parser-1.0.0.dev1/tests/test_parse_sections.py +0 -181
  45. plain_parser-1.0.0.dev1/tests/test_parse_single_module.py +0 -82
  46. plain_parser-1.0.0.dev1/tests/test_plain_file.py +0 -20
  47. plain_parser-1.0.0.dev1/tests/test_plain_spec.py +0 -185
  48. plain_parser-1.0.0.dev1/tests/test_project.py +0 -146
  49. plain_parser-1.0.0.dev1/tests/test_requires_chain.py +0 -116
  50. plain_parser-1.0.0.dev1/tests/test_test_plain_file.py +0 -37
  51. {plain_parser-1.0.0.dev1 → plain_parser-1.0.0.dev2}/src/plain_parser/exceptions.py +0 -0
@@ -0,0 +1,3 @@
1
+ [flake8]
2
+ max-line-length = 120
3
+ extend-ignore = E203
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) plain-parser authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,7 +1,9 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: plain-parser
3
- Version: 1.0.0.dev1
4
- License-Expression: MIT
3
+ Version: 1.0.0.dev2
4
+ Summary: Parser for the plain specification language.
5
+ License: MIT
6
+ License-File: LICENSE
5
7
  Requires-Python: >=3.11
6
8
  Requires-Dist: mistletoe<2,>=1.6.0
7
9
  Requires-Dist: python-frontmatter<2,>=1.3.0
@@ -13,3 +15,14 @@ Requires-Dist: flake8==7.5.0; extra == 'dev'
13
15
  Requires-Dist: isort==9.0.2; extra == 'dev'
14
16
  Requires-Dist: mypy==2.4.1; extra == 'dev'
15
17
  Requires-Dist: pytest==9.2.0; extra == 'dev'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # plain-parser
21
+
22
+ Parser for the plain specification language. It checks and parses a module together with its `requires` chain and its
23
+ test plain files.
24
+
25
+ ```
26
+ plain-parser check path/to/module.plain
27
+ plain-parser parse path/to/module.plain
28
+ ```
@@ -0,0 +1,9 @@
1
+ # plain-parser
2
+
3
+ Parser for the plain specification language. It checks and parses a module together with its `requires` chain and its
4
+ test plain files.
5
+
6
+ ```
7
+ plain-parser check path/to/module.plain
8
+ plain-parser parse path/to/module.plain
9
+ ```
@@ -5,16 +5,29 @@ build-backend = "hatchling.build"
5
5
  [project]
6
6
  name = "plain-parser"
7
7
  dynamic = ["version"]
8
- license = "MIT"
8
+ description = "Parser for the plain specification language."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
9
11
  requires-python = ">=3.11"
10
- dependencies = ["python-liquid2>=0.4.0,<0.5", "mistletoe>=1.6.0,<2", "python-frontmatter>=1.3.0,<2", "pyyaml>=6,<7"]
12
+ dependencies = [
13
+ "python-liquid2>=0.4.0,<0.5",
14
+ "mistletoe>=1.6.0,<2",
15
+ "python-frontmatter>=1.3.0,<2",
16
+ "pyyaml>=6,<7",
17
+ ]
18
+
19
+ [project.optional-dependencies]
20
+ dev = [
21
+ "pytest==9.2.0",
22
+ "flake8==7.5.0",
23
+ "black==26.10.1",
24
+ "isort==9.0.2",
25
+ "mypy==2.4.1",
26
+ ]
11
27
 
12
28
  [project.scripts]
13
29
  plain-parser = "plain_parser.cli:main"
14
30
 
15
- [project.optional-dependencies]
16
- dev = ["pytest==9.2.0", "flake8==7.5.0", "black==26.10.1", "isort==9.0.2", "mypy==2.4.1"]
17
-
18
31
  [tool.hatch.version]
19
32
  source = "vcs"
20
33
 
@@ -28,5 +41,9 @@ line-length = 120
28
41
  profile = "black"
29
42
  line_length = 120
30
43
 
44
+ [tool.mypy]
45
+ ignore_missing_imports = true
46
+
31
47
  [tool.pytest.ini_options]
32
48
  testpaths = ["tests"]
49
+ pythonpath = ["src"]
@@ -1,7 +1,7 @@
1
- """plain-parser."""
1
+ """plain-parser: parser for the plain specification language."""
2
2
 
3
- from . import concept_utils, exceptions, loaders, plain_file, plain_spec, project, test_plain_file
4
- from .plain_file import (
3
+ from plain_parser import concept_utils, exceptions, loaders, plain_file, plain_spec, project, test_plain_file
4
+ from plain_parser.plain_file import (
5
5
  PlainFileParseResult,
6
6
  get_filename_from_module_name,
7
7
  get_module_name_from_filename,
@@ -0,0 +1,277 @@
1
+ """The plain-parser command line: `check` and `parse` an entry module with its requires chain and test plain files."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import sys
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Dict, List, Optional, Tuple
9
+
10
+ import yaml
11
+
12
+ from plain_parser.loaders import find_resource_dir, load_linked_resources, relative_resource_path
13
+ from plain_parser.plain_spec import collect_linked_resources, get_frids, get_specifications_for_frid
14
+ from plain_parser.project import parse_project
15
+
16
+ DEFAULT_CONFIG_NAME = "config.yaml"
17
+ PARSE_FORMAT_VERSION = 2
18
+
19
+ _NO_TESTS_FOLDER = (
20
+ "conformance-tests-script is set in the config file, but no tests folder is given. "
21
+ "Pass --tests-folder or set tests-folder in the config file."
22
+ )
23
+
24
+
25
+ class AmbiguousConfigFileError(Exception):
26
+ pass
27
+
28
+
29
+ @dataclass
30
+ class Config:
31
+ template_dir: Optional[str] = None
32
+ tests_folders: Optional[List[str]] = None
33
+ conformance_tests_enabled: bool = False
34
+
35
+
36
+ @dataclass
37
+ class ParseResult:
38
+ modules: List[Tuple[str, dict]]
39
+ resources: Dict[str, str]
40
+ test_plain_files: Dict[str, dict] = field(default_factory=dict)
41
+
42
+
43
+ def build_parser() -> argparse.ArgumentParser:
44
+ parser = argparse.ArgumentParser(prog="plain-parser", description="Check and parse plain specification modules.")
45
+ subparsers = parser.add_subparsers(dest="command", required=True)
46
+ for name, help_text in (("check", "validate a module and its requires chain"), ("parse", "print a module as JSON")):
47
+ subparser = subparsers.add_parser(name, help=help_text)
48
+ subparser.add_argument("plain_file", help="path of the module file")
49
+ subparser.add_argument("--template-dir", metavar="DIR", default=None, help="template directory")
50
+ subparser.add_argument(
51
+ "--tests-folder", metavar="DIR", action="append", default=None, help="tests folder (repeatable)"
52
+ )
53
+ subparser.add_argument(
54
+ "--config-name", metavar="NAME", default=DEFAULT_CONFIG_NAME, help="name of the config file"
55
+ )
56
+ return parser
57
+
58
+
59
+ def resolve_config_file(config_name: str, plain_file_path: str) -> Optional[str]:
60
+ """Find the config file in the directory of the module file, then in the working directory."""
61
+ plain_dir = os.path.dirname(os.path.abspath(plain_file_path))
62
+ cwd = os.getcwd()
63
+ candidates = [os.path.join(directory, config_name) for directory in (plain_dir, cwd)]
64
+ found = [path for path in candidates if os.path.isfile(path)]
65
+ if len(found) == 2 and not os.path.samefile(found[0], found[1]):
66
+ raise AmbiguousConfigFileError(
67
+ f"Config file '{config_name}' was found in two locations:\n"
68
+ f" - Plain file directory: {plain_dir}\n"
69
+ f" - Current working directory: {cwd}\n"
70
+ "Remove the config file from one of these locations to resolve the ambiguity."
71
+ )
72
+ return found[0] if found else None
73
+
74
+
75
+ def _value(data: dict, key: str) -> Any:
76
+ dashed = data.get(key)
77
+ return dashed if dashed else data.get(key.replace("-", "_"))
78
+
79
+
80
+ def _resolve(path: str, base: str) -> str:
81
+ return os.path.abspath(os.path.join(base, os.path.expanduser(str(path))))
82
+
83
+
84
+ def read_config(config_file: str) -> Config:
85
+ """Read the template directory, the tests folders and the conformance check switch of a config file."""
86
+ with open(config_file, encoding="utf-8") as file:
87
+ data = yaml.safe_load(file)
88
+ if not isinstance(data, dict):
89
+ data = {}
90
+ base = os.path.dirname(os.path.abspath(config_file))
91
+ template_dir = _value(data, "template-dir")
92
+ folders = _value(data, "tests-folder")
93
+ if folders and not isinstance(folders, list):
94
+ folders = [folders]
95
+ return Config(
96
+ template_dir=_resolve(template_dir, base) if template_dir else None,
97
+ tests_folders=[_resolve(folder, base) for folder in folders if folder] if folders else None,
98
+ conformance_tests_enabled=bool(_value(data, "conformance-tests-script")),
99
+ )
100
+
101
+
102
+ def _template_dirs(plain_file_path: str, template_dir: Optional[str]) -> List[str]:
103
+ directories = [os.path.dirname(os.path.abspath(plain_file_path))]
104
+ if template_dir:
105
+ directories.append(os.path.abspath(template_dir))
106
+ return directories
107
+
108
+
109
+ def parse_spec(
110
+ plain_file_path: str,
111
+ template_dir: Optional[str],
112
+ load_resources: bool,
113
+ tests_folders: Optional[List[str]] = None,
114
+ require_test_plain_files: bool = False,
115
+ ) -> ParseResult:
116
+ """Parse an entry module file with its requires chain, resource map and test plain file map."""
117
+ template_dirs = _template_dirs(plain_file_path, template_dir)
118
+ entry_dir = template_dirs[0]
119
+ project = parse_project(
120
+ os.path.abspath(plain_file_path), template_dirs, list(tests_folders or []), require_test_plain_files
121
+ )
122
+ resources: Dict[str, str] = {}
123
+ for module_name, tree in project.chain:
124
+ links: List[dict] = []
125
+ collect_linked_resources(tree, links, None, True)
126
+ if load_resources:
127
+ load_linked_resources(template_dirs, links, module_name)
128
+ for link in links:
129
+ target = link["target"]
130
+ resource_dir = find_resource_dir(template_dirs, target)
131
+ if resource_dir is not None and target not in resources:
132
+ resources[target] = relative_resource_path(entry_dir, resource_dir, target)
133
+ entry_tree = project.chain[-1][1]
134
+ for frid in get_frids(entry_tree):
135
+ get_specifications_for_frid(entry_tree, frid)
136
+ test_plain_files = {
137
+ file.name: {"module": file.parsed.module, "func_id": file.parsed.func_id} for file in project.test_plain_files
138
+ }
139
+ return ParseResult(project.chain, resources, test_plain_files)
140
+
141
+
142
+ def check(
143
+ plain_file_path: str,
144
+ template_dir: Optional[str],
145
+ tests_folders: Optional[List[str]] = None,
146
+ require_test_plain_files: bool = False,
147
+ ) -> None:
148
+ """Validate an entry module, loading its linked files; raise the first error found."""
149
+ parse_spec(plain_file_path, template_dir, True, tests_folders, require_test_plain_files)
150
+
151
+
152
+ def _error_document(error: BaseException) -> dict:
153
+ message = str(error).encode("utf-8", "backslashreplace").decode("utf-8")
154
+ return {"format_version": PARSE_FORMAT_VERSION, "type": type(error).__name__, "message": message}
155
+
156
+
157
+ def _render(document: dict) -> Tuple[bytes, int]:
158
+ """Render a parse document as UTF-8 JSON; a document that cannot be written becomes an error document."""
159
+ try:
160
+ text = json.dumps(document, indent=2, ensure_ascii=False) + "\n"
161
+ except (TypeError, ValueError) as error:
162
+ return _render(_error_document(error))[0], 1
163
+ try:
164
+ return text.encode("utf-8"), 0
165
+ except UnicodeEncodeError as error:
166
+ if document.get("type") is not None and document.get("format_version") == PARSE_FORMAT_VERSION:
167
+ fixed = dict(document)
168
+ fixed["message"] = str(document.get("message", "")).encode("utf-8", "backslashreplace").decode("utf-8")
169
+ return json.dumps(fixed, indent=2, ensure_ascii=False).encode("utf-8", "backslashreplace") + b"\n", 1
170
+ for line in text.split("\n"):
171
+ try:
172
+ line.encode("utf-8")
173
+ except UnicodeEncodeError:
174
+ shown = line.strip().rstrip(",").encode("ascii", "backslashreplace").decode("ascii")
175
+ break
176
+ else:
177
+ shown = str(error)
178
+ failure = {
179
+ "format_version": PARSE_FORMAT_VERSION,
180
+ "type": type(error).__name__,
181
+ "message": f"The parse result holds text that is not valid UTF-8: {shown}",
182
+ }
183
+ return json.dumps(failure, indent=2, ensure_ascii=False).encode("utf-8") + b"\n", 1
184
+
185
+
186
+ def _write_stdout(data: bytes) -> None:
187
+ stream = sys.stdout
188
+ stream.flush()
189
+ buffer = getattr(stream, "buffer", None)
190
+ if buffer is None:
191
+ stream.write(data.decode("utf-8"))
192
+ return
193
+ buffer.write(data)
194
+ buffer.flush()
195
+
196
+
197
+ def _silence_stdout() -> None:
198
+ try:
199
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
200
+ except (OSError, ValueError, AttributeError):
201
+ pass
202
+
203
+
204
+ def parse(
205
+ plain_file_path: str,
206
+ template_dir: Optional[str],
207
+ tests_folders: Optional[List[str]] = None,
208
+ require_test_plain_files: bool = False,
209
+ ) -> int:
210
+ """Print an entry module as one JSON document and return the exit code."""
211
+ try:
212
+ result = parse_spec(plain_file_path, template_dir, False, tests_folders, require_test_plain_files)
213
+ document: dict = {
214
+ "format_version": PARSE_FORMAT_VERSION,
215
+ "modules": [{"module": name, "tree": tree} for name, tree in result.modules],
216
+ "resources": result.resources,
217
+ "test_plain_files": result.test_plain_files,
218
+ }
219
+ exit_code = 0
220
+ except KeyboardInterrupt:
221
+ return 130
222
+ except Exception as error:
223
+ document, exit_code = _error_document(error), 1
224
+ data, failed = _render(document)
225
+ try:
226
+ _write_stdout(data)
227
+ except BrokenPipeError:
228
+ _silence_stdout()
229
+ return exit_code or failed
230
+
231
+
232
+ def _settings(
233
+ parser: argparse.ArgumentParser, args: argparse.Namespace
234
+ ) -> Tuple[Optional[str], Optional[List[str]], bool]:
235
+ """Combine the config file with the options into the template directory, tests folders and check switch."""
236
+ try:
237
+ config_file = resolve_config_file(args.config_name, args.plain_file)
238
+ except AmbiguousConfigFileError as error:
239
+ parser.error(str(error))
240
+ config = Config()
241
+ if config_file:
242
+ try:
243
+ config = read_config(config_file)
244
+ except Exception as error:
245
+ parser.error(f"Error reading config file: {error}")
246
+ template_dir = config.template_dir
247
+ if args.template_dir is not None:
248
+ template_dir = os.path.abspath(args.template_dir) if args.template_dir else None
249
+ tests_folders = config.tests_folders
250
+ if args.tests_folder:
251
+ tests_folders = [os.path.abspath(folder) for folder in args.tests_folder]
252
+ if config.conformance_tests_enabled and not tests_folders:
253
+ parser.error(_NO_TESTS_FOLDER)
254
+ return template_dir, tests_folders, config.conformance_tests_enabled
255
+
256
+
257
+ def main(argv: Optional[List[str]] = None) -> int:
258
+ parser = build_parser()
259
+ try:
260
+ args = parser.parse_args(argv)
261
+ template_dir, tests_folders, require = _settings(parser, args)
262
+ except SystemExit as exit_request:
263
+ return exit_request.code if isinstance(exit_request.code, int) else 2
264
+ except KeyboardInterrupt:
265
+ return 130
266
+
267
+ if args.command == "parse":
268
+ return parse(args.plain_file, template_dir, tests_folders, require)
269
+ try:
270
+ check(args.plain_file, template_dir, tests_folders, require)
271
+ except KeyboardInterrupt:
272
+ return 130
273
+ except Exception as error:
274
+ sys.stderr.write(f"Error: {error}\n")
275
+ return 1
276
+ sys.stdout.write(f"{args.plain_file}: OK\n")
277
+ return 0
@@ -0,0 +1,205 @@
1
+ """Concepts of a specification: extracting, validating and ordering their definitions."""
2
+
3
+ import graphlib
4
+ import re
5
+ from typing import Any, Dict, List, Set, Tuple
6
+
7
+ from plain_parser.exceptions import PlainSyntaxError
8
+ from plain_parser.graph import simple_cycles
9
+ from plain_parser.plain_spec import (
10
+ DEFINITIONS,
11
+ FUNCTIONAL_REQUIREMENTS,
12
+ NON_FUNCTIONAL_REQUIREMENTS,
13
+ TEST_REQUIREMENTS,
14
+ )
15
+
16
+ DEFAULT_CONCEPTS: Set[str] = {
17
+ ":ConformanceTests:",
18
+ ":UnitTests:",
19
+ ":AcceptanceTest:",
20
+ ":AcceptanceTests:",
21
+ ":Implementation:",
22
+ ":plainDefinitions:",
23
+ ":plainImplementationReqs:",
24
+ ":plainFunctionality:",
25
+ ":plainTestReqs:",
26
+ ":plainImplementationCode:",
27
+ }
28
+ MAX_REPORTED_CYCLES = 10
29
+
30
+ _CONCEPT_NAME = re.compile(r"[A-Za-z0-9+\-._]+")
31
+ _CONCEPT_TOKEN = re.compile(r":[A-Za-z0-9+\-._]+:")
32
+ _DEFINITION_START = re.compile(r"\s*-\s+(:[^:\n]+:(?:[ \t]*,[ \t]*:[^:\n]+:)*)")
33
+
34
+
35
+ def extract_concepts_from_definition(text: str) -> Tuple[List[str], List[str]]:
36
+ """Return the concepts a definition text defines and the errors found in it."""
37
+ match = _DEFINITION_START.match(text)
38
+ if match is None:
39
+ return [], [
40
+ f"Syntax error: Invalid definition specification text: {text}. "
41
+ "Should start with `- :<concept>:` (where <concept> is any string that does not contain `:`)."
42
+ ]
43
+ concepts: List[str] = []
44
+ errors: List[str] = []
45
+ for candidate in re.findall(r":[^:\n]+:", match.group(1)):
46
+ if _CONCEPT_NAME.fullmatch(candidate[1:-1]):
47
+ concepts.append(candidate)
48
+ else:
49
+ errors.append(
50
+ f"Syntax error: Invalid concept: {candidate}. "
51
+ "Should contain only letters, numbers, hyphens and dots."
52
+ )
53
+ return concepts, errors
54
+
55
+
56
+ def extract_concepts_from_spec_text(text: str) -> List[str]:
57
+ """Return every concept token a text mentions, in order, repeats kept."""
58
+ return _CONCEPT_TOKEN.findall(text)
59
+
60
+
61
+ def _item_markdown(item: Any) -> str:
62
+ return item["markdown"] if isinstance(item, dict) else str(item)
63
+
64
+
65
+ def collect_concepts(plain_source) -> Tuple[List[str], List[str]]:
66
+ """Return the concepts the definitions define, and the errors found in the definitions."""
67
+ concepts: List[str] = []
68
+ errors: List[str] = []
69
+ for item in plain_source.get(DEFINITIONS, []):
70
+ defined, item_errors = extract_concepts_from_definition(_item_markdown(item))
71
+ concepts.extend(defined)
72
+ errors.extend(item_errors)
73
+ seen: Set[str] = set()
74
+ duplicated: List[str] = []
75
+ for concept in concepts:
76
+ if (concept in seen or concept in DEFAULT_CONCEPTS) and concept not in duplicated:
77
+ duplicated.append(concept)
78
+ seen.add(concept)
79
+ if duplicated:
80
+ errors.append(f"Syntax error: Concepts were defined multiple times: {', '.join(duplicated)} .")
81
+ return list(dict.fromkeys(concepts)), errors
82
+
83
+
84
+ def validate_concepts_in_spec(spec: dict, concepts: Set[str], spec_group: str) -> List[str]:
85
+ """Return an error for every mention in one specification item of a concept that is not defined."""
86
+ markdown = spec["markdown"]
87
+ return [
88
+ f"Syntax error: Concept {concept} is not defined in the definitions. {spec_group}: {markdown}"
89
+ for concept in extract_concepts_from_spec_text(markdown)
90
+ if concept not in concepts and concept not in DEFAULT_CONCEPTS
91
+ ]
92
+
93
+
94
+ def validate_concepts_in_spec_group(spec_group, plain_source, concepts: Set[str]) -> List[str]:
95
+ errors: List[str] = []
96
+ for spec in plain_source.get(spec_group, []):
97
+ errors.extend(validate_concepts_in_spec(spec, concepts, spec_group))
98
+ return errors
99
+
100
+
101
+ def validate_concepts(marshalled_plain_source) -> List[str]:
102
+ """Validate the concepts of a plain source tree and return a list of error texts."""
103
+ concepts, errors = collect_concepts(marshalled_plain_source)
104
+ defined = set(concepts)
105
+ for group in (NON_FUNCTIONAL_REQUIREMENTS, TEST_REQUIREMENTS, FUNCTIONAL_REQUIREMENTS, DEFINITIONS):
106
+ errors.extend(validate_concepts_in_spec_group(group, marshalled_plain_source, defined))
107
+ return errors
108
+
109
+
110
+ def find_concept_definitions_in_plain_source(concept: str, plain_source: dict, renderer) -> list:
111
+ """Return the definition tokens of a parsed module that define a concept."""
112
+ definitions = plain_source.get(DEFINITIONS)
113
+ tokens = getattr(definitions, "children", definitions) or []
114
+ found = []
115
+ for token in tokens:
116
+ defined, _ = extract_concepts_from_definition(renderer.render(token))
117
+ if concept in defined:
118
+ found.append(token)
119
+ return found
120
+
121
+
122
+ def build_adjacency_list(definitions) -> Tuple[Dict[str, List[str]], Dict[str, Any]]:
123
+ """Build the concept graph and the definition of every concept.
124
+
125
+ The graph has an edge from concept A to concept B when the definition of B mentions A. The definitions
126
+ mapping is in definition order.
127
+ """
128
+ adjacency: Dict[str, List[str]] = {}
129
+ concept_definitions: Dict[str, Any] = {}
130
+ for item in definitions:
131
+ markdown = _item_markdown(item)
132
+ defined, _ = extract_concepts_from_definition(markdown)
133
+ for concept in defined:
134
+ adjacency.setdefault(concept, [])
135
+ concept_definitions.setdefault(concept, item)
136
+ mentioned = [
137
+ concept
138
+ for concept in dict.fromkeys(extract_concepts_from_spec_text(markdown))
139
+ if concept not in defined and concept not in DEFAULT_CONCEPTS
140
+ ]
141
+ for concept in mentioned:
142
+ adjacency.setdefault(concept, [])
143
+ for concept in mentioned:
144
+ for target in defined:
145
+ if target not in adjacency[concept]:
146
+ adjacency[concept].append(target)
147
+ return adjacency, concept_definitions
148
+
149
+
150
+ def format_cycles_error(adjacency_list, concept_definitions) -> str:
151
+ """Describe the elementary cycles of the concept graph, at most MAX_REPORTED_CYCLES of them."""
152
+ order = list(concept_definitions)
153
+ position = {concept: index for index, concept in enumerate(order)}
154
+ mentions: Dict[str, List[str]] = {concept: [] for concept in order}
155
+ for mentioned, defined_list in adjacency_list.items():
156
+ for defined in defined_list:
157
+ mentions.setdefault(defined, []).append(mentioned)
158
+ mentions.setdefault(mentioned, [])
159
+
160
+ found = list(simple_cycles(mentions, limit=MAX_REPORTED_CYCLES + 1))
161
+ found.sort(key=lambda cycle: (position.get(cycle[0], len(position)), len(cycle)))
162
+ shown = found[:MAX_REPORTED_CYCLES]
163
+
164
+ if len(found) > MAX_REPORTED_CYCLES:
165
+ head = (
166
+ f"Plain syntax error: Found more than {MAX_REPORTED_CYCLES} cycles in concept definitions. "
167
+ f"Cycles are not allowed.\nShowing the first {MAX_REPORTED_CYCLES}."
168
+ )
169
+ else:
170
+ head = f"Plain syntax error: Found {len(shown)} cycle(s) in concept definitions. Cycles are not allowed."
171
+
172
+ blocks = [head]
173
+ for number, cycle in enumerate(shown, start=1):
174
+ lines = [f"Cycle {number}: {' -> '.join([*cycle, cycle[0]])}"]
175
+ texts: List[str] = []
176
+ for concept in cycle:
177
+ text = _item_markdown(concept_definitions[concept]) if concept in concept_definitions else None
178
+ if text is not None and text not in texts:
179
+ texts.append(text)
180
+ lines.extend(texts)
181
+ blocks.append("\n".join(lines))
182
+ return "\n\n".join(blocks)
183
+
184
+
185
+ def sort_definitions(definitions: List[dict]) -> None:
186
+ """Sort definition items in place so that every concept comes after the concepts its definition mentions."""
187
+ if len(definitions) < 2:
188
+ return
189
+ adjacency, concept_definitions = build_adjacency_list(definitions)
190
+ sorter: graphlib.TopologicalSorter = graphlib.TopologicalSorter()
191
+ for concept, dependents in adjacency.items():
192
+ sorter.add(concept)
193
+ for dependent in dependents:
194
+ sorter.add(dependent, concept)
195
+ try:
196
+ order = list(sorter.static_order())
197
+ except graphlib.CycleError as error:
198
+ raise PlainSyntaxError(format_cycles_error(adjacency, concept_definitions)) from error
199
+ position = {concept: index for index, concept in enumerate(order)}
200
+
201
+ def key(item: dict) -> int:
202
+ defined, _ = extract_concepts_from_definition(_item_markdown(item))
203
+ return max((position[concept] for concept in defined), default=len(position))
204
+
205
+ definitions.sort(key=key)