robotcode-robot 2.9.0.dev186__tar.gz → 2.9.0.dev214__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 (53) hide show
  1. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/PKG-INFO +2 -2
  2. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/pyproject.toml +1 -1
  3. robotcode_robot-2.9.0.dev214/src/robotcode/robot/__version__.py +1 -0
  4. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/document_cache_helper.py +47 -9
  5. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/imports_manager.py +2 -1
  6. robotcode_robot-2.9.0.dev214/src/robotcode/robot/document_formats.py +110 -0
  7. robotcode_robot-2.9.0.dev214/src/robotcode/robot/language_definitions.py +39 -0
  8. robotcode_robot-2.9.0.dev214/src/robotcode/robot/utils/markdown_blocks.py +123 -0
  9. robotcode_robot-2.9.0.dev186/src/robotcode/robot/__version__.py +0 -1
  10. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/.gitignore +0 -0
  11. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/README.md +0 -0
  12. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/__init__.py +0 -0
  13. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/config/__init__.py +0 -0
  14. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/config/loader.py +0 -0
  15. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/config/model.py +0 -0
  16. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/config/utils.py +0 -0
  17. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/__init__.py +0 -0
  18. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/analyzer_result.py +0 -0
  19. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/data_cache.py +0 -0
  20. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/diagnostic_rules.py +0 -0
  21. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/diagnostics_modifier.py +0 -0
  22. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/entities.py +0 -0
  23. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/errors.py +0 -0
  24. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/import_resolver.py +0 -0
  25. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/keyword_finder.py +0 -0
  26. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/library_doc.py +0 -0
  27. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/model_helper.py +0 -0
  28. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/namespace.py +0 -0
  29. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/namespace_analyzer.py +0 -0
  30. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/project_index.py +0 -0
  31. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/scope_tree.py +0 -0
  32. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/semantic_analyzer/__init__.py +0 -0
  33. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/semantic_analyzer/analyzer.py +0 -0
  34. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/semantic_analyzer/enums.py +0 -0
  35. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/semantic_analyzer/json_dump.py +0 -0
  36. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/semantic_analyzer/model.py +0 -0
  37. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/semantic_analyzer/nodes.py +0 -0
  38. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/semantic_analyzer/run_keyword.py +0 -0
  39. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/semantic_analyzer/serialization.py +0 -0
  40. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/semantic_analyzer/variable_tokenizer.py +0 -0
  41. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/variable_scope.py +0 -0
  42. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/diagnostics/workspace_config.py +0 -0
  43. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/py.typed +0 -0
  44. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/utils/__init__.py +0 -0
  45. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/utils/ast.py +0 -0
  46. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/utils/markdown_docs.py +0 -0
  47. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/utils/markdownformatter.py +0 -0
  48. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/utils/match.py +0 -0
  49. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/utils/robot_patching.py +0 -0
  50. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/utils/robot_path.py +0 -0
  51. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/utils/stubs.py +0 -0
  52. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/utils/variables.py +0 -0
  53. {robotcode_robot-2.9.0.dev186 → robotcode_robot-2.9.0.dev214}/src/robotcode/robot/utils/visitor.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: robotcode-robot
3
- Version: 2.9.0-dev.186
3
+ Version: 2.9.0-dev.214
4
4
  Summary: Support classes for RobotCode for handling Robot Framework projects.
5
5
  Project-URL: Homepage, https://robotcode.io
6
6
  Project-URL: Donate, https://opencollective.com/robotcode
@@ -27,7 +27,7 @@ Classifier: Topic :: Utilities
27
27
  Classifier: Typing :: Typed
28
28
  Requires-Python: >=3.10
29
29
  Requires-Dist: platformdirs>=4.3
30
- Requires-Dist: robotcode-core==2.9.0-dev.186
30
+ Requires-Dist: robotcode-core==2.9.0-dev.214
31
31
  Requires-Dist: robotframework>=5.0.0
32
32
  Requires-Dist: tomli>=1.1.0; python_version < '3.11'
33
33
  Description-Content-Type: text/markdown
@@ -32,7 +32,7 @@ dependencies = [
32
32
  "robotframework>=5.0.0",
33
33
  "tomli>=1.1.0; python_version < '3.11'",
34
34
  "platformdirs>=4.3",
35
- "robotcode-core==2.9.0-dev.186",
35
+ "robotcode-core==2.9.0-dev.214",
36
36
  ]
37
37
  dynamic = ["version"]
38
38
 
@@ -0,0 +1 @@
1
+ __version__ = "2.9.0-dev.214"
@@ -8,6 +8,7 @@ from logging import CRITICAL
8
8
  from pathlib import Path
9
9
  from typing import (
10
10
  Any,
11
+ Callable,
11
12
  Dict,
12
13
  Iterable,
13
14
  Iterator,
@@ -34,7 +35,10 @@ from robotcode.robot.diagnostics.diagnostics_modifier import (
34
35
  )
35
36
 
36
37
  from ..config.model import RobotBaseProfile
38
+ from ..document_formats import is_markdown_file
39
+ from ..language_definitions import MARKDOWN_LANGUAGE_ID
37
40
  from ..utils import RF_VERSION
41
+ from ..utils.markdown_blocks import RobotBlock, find_robot_blocks, read_markdown_data
38
42
  from ..utils.stubs import Languages
39
43
  from .data_cache import CacheSection
40
44
  from .imports_manager import ImportsManager, NamespaceMetaData
@@ -60,6 +64,9 @@ class UnknownFileTypeError(Exception):
60
64
  pass
61
65
 
62
66
 
67
+ DataReader = Callable[[str], Tuple[str, Dict[int, int]]]
68
+
69
+
63
70
  def _namespace_cache_key(source: str, document_type: Optional[DocumentType]) -> str:
64
71
  """Disk-cache entry name for a namespace.
65
72
 
@@ -101,6 +108,8 @@ class DocumentsCacheHelper:
101
108
  self.robot_profile = robot_profile or RobotBaseProfile()
102
109
  self.analysis_config = analysis_config or WorkspaceAnalysisConfig()
103
110
 
111
+ self.data_readers: Dict[str, DataReader] = {MARKDOWN_LANGUAGE_ID: read_markdown_data}
112
+
104
113
  self._imports_managers_lock = threading.RLock()
105
114
  self._imports_managers: weakref.WeakKeyDictionary[WorkspaceFolder, ImportsManager] = weakref.WeakKeyDictionary()
106
115
  self._default_imports_manager: Optional[ImportsManager] = None
@@ -242,9 +251,44 @@ class DocumentsCacheHelper:
242
251
  return DocumentType.GENERAL
243
252
  if suffix == ".resource":
244
253
  return DocumentType.RESOURCE
254
+ if document.language_id == MARKDOWN_LANGUAGE_ID:
255
+ # like Robot Framework: `__init__.robot.md` is a suite file
256
+ return DocumentType.INIT if path.stem.lower() == "__init__" else DocumentType.GENERAL
245
257
 
246
258
  return DocumentType.UNKNOWN
247
259
 
260
+ def get_markdown_blocks(self, document: TextDocument) -> List[RobotBlock]:
261
+ """The code blocks Robot Framework executes, of a Markdown document."""
262
+ return document.get_cache(self.__get_markdown_blocks)
263
+
264
+ def __get_markdown_blocks(self, document: TextDocument) -> List[RobotBlock]:
265
+ return find_robot_blocks(document.text())
266
+
267
+ def __data_reader(self, document: TextDocument, resource: bool) -> Optional[DataReader]:
268
+ # Robot Framework picks the parser of a resource file by its suffix, also without an active format
269
+ if resource and is_markdown_file(document.uri.to_path()):
270
+ return read_markdown_data
271
+
272
+ return self.data_readers.get(document.language_id) if document.language_id is not None else None
273
+
274
+ def __tokenize(
275
+ self, document: TextDocument, tokenizer: Callable[..., Iterable[Token]], resource: bool = False
276
+ ) -> List[Token]:
277
+ lang = self.get_languages_for_document(document)
278
+
279
+ reader = self.__data_reader(document, resource)
280
+ if reader is None:
281
+ with io.StringIO(document.text()) as content:
282
+ return [e for e in tokenizer(content, lang=lang)]
283
+
284
+ data, offsets = reader(document.text())
285
+ with io.StringIO(data) as content:
286
+ tokens: List[Token] = [e for e in tokenizer(content, lang=lang)]
287
+ if offsets:
288
+ for token in tokens:
289
+ token.col_offset += offsets.get(token.lineno, 0)
290
+ return tokens
291
+
248
292
  def get_tokens(self, document: TextDocument) -> List[Token]:
249
293
  document_type = self.get_document_type(document)
250
294
  if document_type == DocumentType.INIT:
@@ -311,19 +355,13 @@ class DocumentsCacheHelper:
311
355
  return robot.api.get_init_tokens(source, data_only=False, tokenize_variables=tokenize_variables)
312
356
 
313
357
  def __get_general_tokens(self, document: TextDocument) -> List[Token]:
314
- lang = self.get_languages_for_document(document)
315
- with io.StringIO(document.text()) as content:
316
- return [e for e in self.__internal_get_tokens(content, lang=lang)]
358
+ return self.__tokenize(document, self.__internal_get_tokens)
317
359
 
318
360
  def __get_resource_tokens(self, document: TextDocument) -> List[Token]:
319
- lang = self.get_languages_for_document(document)
320
- with io.StringIO(document.text()) as content:
321
- return [e for e in self.__internal_get_resource_tokens(content, lang=lang)]
361
+ return self.__tokenize(document, self.__internal_get_resource_tokens, resource=True)
322
362
 
323
363
  def __get_init_tokens(self, document: TextDocument) -> List[Token]:
324
- lang = self.get_languages_for_document(document)
325
- with io.StringIO(document.text()) as content:
326
- return [e for e in self.__internal_get_init_tokens(content, lang=lang)]
364
+ return self.__tokenize(document, self.__internal_get_init_tokens)
327
365
 
328
366
  def get_model(self, document: TextDocument) -> ast.AST:
329
367
  document_type = self.get_document_type(document)
@@ -56,6 +56,7 @@ from robotcode.core.utils.path import (
56
56
  )
57
57
 
58
58
  from ..__version__ import __version__
59
+ from ..language_definitions import ROBOT_LANGUAGE_IDS
59
60
  from ..utils import RF_VERSION
60
61
  from ..utils.robot_path import find_file_ex
61
62
  from ..utils.stubs import Languages
@@ -1272,7 +1273,7 @@ class ImportsManager:
1272
1273
  # unresolved imports (file didn't exist yet) get invalidated and re-analyzed.
1273
1274
  self.imports_changed(self, uri)
1274
1275
 
1275
- @language_id("robotframework")
1276
+ @language_id(*ROBOT_LANGUAGE_IDS)
1276
1277
  def _on_possible_resource_document_modified(self, sender: Any, document: TextDocument) -> None:
1277
1278
  run_as_task(self.__on_possible_resource_document_modified, sender, document)
1278
1279
 
@@ -0,0 +1,110 @@
1
+ import os
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+ from typing import Callable, Dict, List, Optional, Tuple, Union
5
+
6
+ from robot.running.builder import TestSuiteBuilder
7
+ from robotcode.core.utils.dataclasses import CamelSnakeMixin
8
+
9
+ from .config.model import RobotBaseProfile, StringExpression
10
+ from .utils import RF_VERSION
11
+
12
+ # Robot Framework reads Markdown files since 7.5, with line and column numbers of the file since 7.5.1
13
+ MARKDOWN_SUPPORTED = RF_VERSION >= (7, 5, 1)
14
+
15
+ if MARKDOWN_SUPPORTED:
16
+ from robot.parsing.suitestructure import IncludedFiles
17
+
18
+ ROBOT_FORMAT_NAME = "robot"
19
+ MARKDOWN_FORMAT_NAME = "markdown"
20
+
21
+
22
+ # TODO: with Gherkin, also list the formats of the custom parsers in the profile's `parsers`, from
23
+ # `TestSuiteBuilder(custom_parsers=...).custom_parsers` per profile (each parser's `name` and `extensions`)
24
+ def _robot_framework_formats() -> Tuple[Tuple[str, ...], Dict[str, str]]:
25
+ """Robot Framework's default extensions, and the format of each extension it has a parser for."""
26
+ builder = TestSuiteBuilder()
27
+ defaults = tuple(e.lower().lstrip(".") for e in builder.included_extensions)
28
+ if RF_VERSION < (6, 1):
29
+ return defaults, {"rst": "rest", "rest": "rest"}
30
+ return defaults, {e: type(p).__name__.removesuffix("Parser").lower() for e, p in builder.standard_parsers.items()}
31
+
32
+
33
+ DEFAULT_EXTENSIONS, _FORMAT_OF_EXTENSION = _robot_framework_formats()
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class DocumentFormat(CamelSnakeMixin):
38
+ """A document format Robot Framework parses, with the extensions it parses with it (lower case, no dot)."""
39
+
40
+ name: str
41
+ extensions: List[str]
42
+
43
+
44
+ def _evaluated(value: Union[str, StringExpression]) -> str:
45
+ return value if isinstance(value, str) else value.evaluate()
46
+
47
+
48
+ def _parse_include_patterns(profile: RobotBaseProfile) -> List[str]:
49
+ return [_evaluated(p) for p in profile.parse_include or []]
50
+
51
+
52
+ def _robot_framework_extensions(profile: RobotBaseProfile) -> List[str]:
53
+ """Robot Framework's extension list for the profile: `extensions`, or the default extensions when it is not set,
54
+ plus the extension of each `parse-include` pattern, normalised like Robot Framework (lower case, no dot)."""
55
+ entries = _evaluated(profile.extensions).split(":") if profile.extensions else list(DEFAULT_EXTENSIONS)
56
+ entries += [os.path.splitext(p)[1] for p in _parse_include_patterns(profile)]
57
+
58
+ result: List[str] = []
59
+ for entry in entries:
60
+ extension = entry.lower().lstrip(".")
61
+ if extension and extension not in result:
62
+ result.append(extension)
63
+ return result
64
+
65
+
66
+ def document_formats(profile: RobotBaseProfile) -> List[DocumentFormat]:
67
+ """The document formats Robot Framework parses with the evaluated profile, in the order of their first extension."""
68
+ formats: Dict[str, List[str]] = {}
69
+ for extension in _robot_framework_extensions(profile):
70
+ formats.setdefault(_FORMAT_OF_EXTENSION.get(extension, ROBOT_FORMAT_NAME), []).append(extension)
71
+ return [DocumentFormat(name, extensions) for name, extensions in formats.items()]
72
+
73
+
74
+ def markdown_extensions(profile: RobotBaseProfile) -> List[str]:
75
+ """The extensions of the Markdown files RobotCode serves, from Robot Framework 7.5.1 on."""
76
+ if not MARKDOWN_SUPPORTED:
77
+ return []
78
+ return [e for f in document_formats(profile) if f.name == MARKDOWN_FORMAT_NAME for e in f.extensions]
79
+
80
+
81
+ def _pattern_from_root(pattern: str, root: Path) -> str:
82
+ # Robot Framework resolves a pattern that holds a `/`, has no `.` or names an existing path from its working
83
+ # directory, the project root for `robotcode robot`; other patterns match file names
84
+ normalized = os.path.normpath(pattern).replace("\\", "/")
85
+ if "/" in normalized or "." not in normalized or (root / normalized).exists():
86
+ return str(root / normalized)
87
+ return pattern
88
+
89
+
90
+ def parse_include_condition(profile: RobotBaseProfile, root: Path) -> Optional[Callable[[Path], bool]]:
91
+ """Whether Robot Framework parses a file of a valid extension, by the `parse-include` patterns of the profile;
92
+ `None` when it sets none. An `__init__` file needs no pattern, as in Robot Framework."""
93
+ patterns = _parse_include_patterns(profile)
94
+ if not MARKDOWN_SUPPORTED or not patterns:
95
+ return None
96
+
97
+ included = IncludedFiles([_pattern_from_root(p, root) for p in patterns])
98
+
99
+ def condition(path: Path) -> bool:
100
+ return path.stem.lower() == "__init__" or bool(included.match(path))
101
+
102
+ return condition
103
+
104
+
105
+ def is_markdown_file(path: Path) -> bool:
106
+ """Whether Robot Framework reads the file with its Markdown parser, from its code blocks.
107
+
108
+ Robot Framework picks the parser of a resource file by its suffix, so this holds also without an active format.
109
+ """
110
+ return MARKDOWN_SUPPORTED and path.suffix.lower() in (".md", ".markdown")
@@ -0,0 +1,39 @@
1
+ """The languages RobotCode serves: their ids and their language definitions."""
2
+
3
+ from pathlib import Path
4
+ from typing import Final, Optional
5
+
6
+ from robotcode.core.language import LanguageDefinition
7
+
8
+ from .config.model import RobotBaseProfile
9
+ from .document_formats import markdown_extensions, parse_include_condition
10
+
11
+ ROBOTFRAMEWORK_LANGUAGE_ID = "robotframework"
12
+
13
+ ROBOTFRAMEWORK_LANGUAGE = LanguageDefinition(
14
+ id=ROBOTFRAMEWORK_LANGUAGE_ID,
15
+ extensions=[".robot", ".resource"],
16
+ extensions_ignore_case=True,
17
+ aliases=["Robot Framework", "robotframework"],
18
+ )
19
+
20
+ # the language of the Markdown files Robot Framework parses; no editor sends it, the server detects it by file name
21
+ MARKDOWN_LANGUAGE_ID = "robotframework-markdown"
22
+
23
+ # the languages whose documents hold Robot Framework data
24
+ ROBOT_LANGUAGE_IDS: Final = (ROBOTFRAMEWORK_LANGUAGE_ID, MARKDOWN_LANGUAGE_ID)
25
+
26
+
27
+ def markdown_language_definition(profile: RobotBaseProfile, root: Path) -> Optional[LanguageDefinition]:
28
+ """The language of the Markdown files Robot Framework parses with the profile in the project `root`; `None` when
29
+ no Markdown extension is active."""
30
+ extensions = [f".{e}" for e in markdown_extensions(profile)]
31
+ if not extensions:
32
+ return None
33
+
34
+ return LanguageDefinition(
35
+ id=MARKDOWN_LANGUAGE_ID,
36
+ extensions=extensions,
37
+ extensions_ignore_case=True,
38
+ file_condition=parse_include_condition(profile, root),
39
+ )
@@ -0,0 +1,123 @@
1
+ import ast
2
+ import io
3
+ import re
4
+ from dataclasses import dataclass
5
+ from typing import Dict, Iterator, List, Optional, Sequence, Tuple, cast
6
+
7
+ from robot.parsing.lexer.tokens import Token
8
+ from robot.parsing.model.statements import Statement
9
+ from robot.utils import FileReader
10
+ from robotcode.core.lsp.types import Range
11
+
12
+ from .ast import range_from_token
13
+
14
+ # Robot Framework's rule for the code blocks it executes, see `MarkdownParser._read_markdown_data`
15
+ _FENCE_OPEN = re.compile(r"(\s*)(`{3,}|~{3,})\s*(\S+)")
16
+ _ROBOT_LANGUAGES = ("robotframework", "robot")
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class RobotBlock:
21
+ """A code block of a Markdown file that Robot Framework executes, with 0-based line numbers."""
22
+
23
+ opening_fence: int
24
+ # `None` when the block runs to the end of the file
25
+ closing_fence: Optional[int]
26
+ # the indentation of the opening fence, which Robot Framework removes from the content lines
27
+ indent: int = 0
28
+
29
+ def contains(self, line: int) -> bool:
30
+ """Whether the line is a content line of the block, between its fences."""
31
+ return line > self.opening_fence and (self.closing_fence is None or line < self.closing_fence)
32
+
33
+
34
+ def _read_lines(text: str) -> Iterator[str]:
35
+ # the lines as Robot Framework reads a Markdown file, with `\r\n` turned into `\n`
36
+ with FileReader(io.StringIO(text)) as reader:
37
+ yield from reader.readlines()
38
+
39
+
40
+ def find_robot_blocks(text: str) -> List[RobotBlock]:
41
+ """The `robot`/`robotframework` code blocks of a Markdown text."""
42
+ blocks: List[RobotBlock] = []
43
+ fence_close: Optional[re.Pattern[str]] = None
44
+ opening_fence = 0
45
+ fence_indent = 0
46
+
47
+ for line_index, line in enumerate(_read_lines(text)):
48
+ if fence_close is None:
49
+ match = _FENCE_OPEN.match(line)
50
+ if match:
51
+ indent, fence, lang = match.groups()
52
+ if lang.lower() in _ROBOT_LANGUAGES:
53
+ fence_close = re.compile(rf"\s*{fence[0]}{{{len(fence)},}}\s*")
54
+ opening_fence = line_index
55
+ fence_indent = len(indent)
56
+ elif fence_close.fullmatch(line):
57
+ blocks.append(RobotBlock(opening_fence, line_index, fence_indent))
58
+ fence_close = None
59
+
60
+ if fence_close is not None:
61
+ blocks.append(RobotBlock(opening_fence, None, fence_indent))
62
+
63
+ return blocks
64
+
65
+
66
+ def indent_for_block(text: str, block: Optional[RobotBlock]) -> str:
67
+ """The text with the indentation of the block before each line that is not empty, for code placed into it."""
68
+ if block is None or not block.indent:
69
+ return text
70
+ prefix = " " * block.indent
71
+ return "".join(prefix + line if line.strip() else line for line in text.splitlines(keepends=True))
72
+
73
+
74
+ def find_block(blocks: Sequence[RobotBlock], line: int) -> Optional[RobotBlock]:
75
+ """The block that holds the 0-based line as a content line."""
76
+ for block in blocks:
77
+ if block.contains(line):
78
+ return block
79
+ return None
80
+
81
+
82
+ _NON_DATA_TOKENS = {Token.SEPARATOR, Token.EOL, Token.EOS}
83
+
84
+
85
+ def range_in_blocks(node: ast.AST, blocks: Sequence[RobotBlock]) -> Optional[Range]:
86
+ """The range of a node in a Markdown document, inside the code blocks; `None` when no token is in one.
87
+
88
+ In Robot Framework's data the prose and fence lines after a node are empty lines of the node, and so are the
89
+ empty lines of a following block without data. The range ends with the last line with data and the empty lines
90
+ after it in the same block.
91
+ """
92
+ tokens = [
93
+ token
94
+ for statement in ast.walk(node)
95
+ if isinstance(statement, Statement)
96
+ for token in statement.tokens
97
+ if token.lineno >= 1 and find_block(blocks, token.lineno - 1) is not None
98
+ ]
99
+ if not tokens:
100
+ return None
101
+
102
+ first = min(tokens, key=lambda t: (t.lineno, t.col_offset))
103
+ data = [t for t in tokens if t.type not in _NON_DATA_TOKENS]
104
+ if data:
105
+ last_data = max(data, key=lambda t: (t.lineno, t.end_col_offset))
106
+ block = find_block(blocks, last_data.lineno - 1)
107
+ tokens = [t for t in tokens if t.lineno >= last_data.lineno and find_block(blocks, t.lineno - 1) == block]
108
+ last = max(tokens, key=lambda t: (t.lineno, t.end_col_offset))
109
+
110
+ return Range(range_from_token(first).start, range_from_token(last).end)
111
+
112
+
113
+ def read_markdown_data(text: str) -> Tuple[str, Dict[int, int]]:
114
+ """The Robot Framework data of a Markdown text and the column offsets of its dedented lines.
115
+
116
+ Lines outside the code blocks and the fence lines are empty; the offsets map 1-based line numbers to the
117
+ number of characters removed from the start of the line. Needs Robot Framework 7.5.1 or newer.
118
+ """
119
+ from robot.running.builder.parsers import MarkdownParser
120
+
121
+ # a private method of Robot Framework, the only place that gives its dedent of indented blocks exactly
122
+ with FileReader(io.StringIO(text)) as reader:
123
+ return cast(Tuple[str, Dict[int, int]], MarkdownParser()._read_markdown_data(reader))
@@ -1 +0,0 @@
1
- __version__ = "2.9.0-dev.186"