Skip to content

Commit 9b0999c

Browse files
committed
refactor(all): some cache adjustments and removal of unnecessary code
1 parent c232cea commit 9b0999c

File tree

10 files changed

+73
-89
lines changed

10 files changed

+73
-89
lines changed

packages/core/src/robotcode/core/text_document.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def position_from_utf16(lines: List[str], position: Position) -> Position:
4848
return Position(line=position.line, character=utf32_offset)
4949

5050

51-
@functools.lru_cache(maxsize=2048)
51+
@functools.lru_cache(maxsize=8192)
5252
def has_multibyte_char(line: str) -> bool:
5353
return any(is_multibyte_char(c) for c in line)
5454

packages/core/src/robotcode/core/utils/glob_path.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def _glob_pattern_to_re(pattern: str) -> str:
6060
return result
6161

6262

63-
@functools.lru_cache(maxsize=256)
63+
@functools.lru_cache(maxsize=8192)
6464
def _compile_glob_pattern(pattern: str) -> "re.Pattern[str]":
6565
return re.compile(_glob_pattern_to_re(pattern))
6666

packages/language_server/src/robotcode/language_server/robotframework/parts/code_action_refactor.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@
3535
range_from_node,
3636
range_from_token,
3737
)
38-
from robotcode.robot.utils.stubs import BodyBlock
3938

4039
from ...common.decorators import code_action_kinds
4140
from .code_action_helper_mixin import (
@@ -188,9 +187,9 @@ def get_valid_nodes_in_range(self, model: ast.AST, range: Range, also_return: bo
188187

189188
result = []
190189

191-
blocks: List[BodyBlock] = []
190+
blocks: List[Block] = []
192191
for node in iter_nodes(model):
193-
if isinstance(node, Block) and isinstance(node, BodyBlock):
192+
if isinstance(node, Block) and hasattr(node, "body"):
194193
blocks.append(node)
195194

196195
r = range_from_node(node, skip_non_data=True, allow_comments=True)

packages/robot/src/robotcode/robot/utils/ast.py

Lines changed: 42 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -80,23 +80,23 @@ def visit_Statement(self, statement: ast.AST) -> None: # noqa: N802
8080
self.last_statement = statement
8181

8282

83+
_NON_DATA_TOKENS = {
84+
Token.SEPARATOR,
85+
Token.CONTINUATION,
86+
Token.EOL,
87+
Token.EOS,
88+
}
89+
90+
_NON_DATA_TOKENS_WITH_COMMENT = {*_NON_DATA_TOKENS, Token.COMMENT}
91+
92+
8393
def _get_non_data_range_from_node(
8494
node: ast.AST, only_start: bool = False, allow_comments: bool = False
8595
) -> Optional[Range]:
96+
non_data_tokens = _NON_DATA_TOKENS_WITH_COMMENT if allow_comments else _NON_DATA_TOKENS
8697
if cached_isinstance(node, Statement) and node.tokens:
8798
start_token = next(
88-
(
89-
v
90-
for v in node.tokens
91-
if v.type
92-
not in [
93-
Token.SEPARATOR,
94-
*([] if allow_comments else [Token.COMMENT]),
95-
Token.CONTINUATION,
96-
Token.EOL,
97-
Token.EOS,
98-
]
99-
),
99+
(v for v in node.tokens if v.type not in non_data_tokens),
100100
None,
101101
)
102102

@@ -106,18 +106,7 @@ def _get_non_data_range_from_node(
106106
end_tokens = node.tokens
107107

108108
end_token = next(
109-
(
110-
v
111-
for v in reversed(end_tokens)
112-
if v.type
113-
not in [
114-
Token.SEPARATOR,
115-
*([] if allow_comments else [Token.COMMENT]),
116-
Token.CONTINUATION,
117-
Token.EOL,
118-
Token.EOS,
119-
]
120-
),
109+
(v for v in reversed(end_tokens) if v.type not in non_data_tokens),
121110
None,
122111
)
123112
if start_token is not None and end_token is not None:
@@ -282,35 +271,35 @@ def tokenize_variables(
282271
return _tokenize_variables(token, variables)
283272

284273

285-
if get_robot_version() < (7, 0):
286-
287-
def _tokenize_variables(token: Token, variables: Any) -> Iterator[Token]:
288-
lineno = token.lineno
289-
col_offset = token.col_offset
290-
remaining = ""
291-
for before, variable, remaining in variables:
292-
if before:
293-
yield Token(token.type, before, lineno, col_offset)
294-
col_offset += len(before)
295-
yield Token(Token.VARIABLE, variable, lineno, col_offset)
296-
col_offset += len(variable)
297-
if remaining:
298-
yield Token(token.type, remaining, lineno, col_offset)
299-
300-
else:
301-
302-
def _tokenize_variables(token: Token, variables: Any) -> Iterator[Token]:
303-
lineno = token.lineno
304-
col_offset = token.col_offset
305-
after = ""
306-
for match in variables:
307-
if match.before:
308-
yield Token(token.type, match.before, lineno, col_offset)
309-
yield Token(Token.VARIABLE, match.match, lineno, col_offset + match.start)
310-
col_offset += match.end
311-
after = match.after
312-
if after:
313-
yield Token(token.type, after, lineno, col_offset)
274+
def _tokenize_variables_before7(token: Token, variables: Any) -> Iterator[Token]:
275+
lineno = token.lineno
276+
col_offset = token.col_offset
277+
remaining = ""
278+
for before, variable, remaining in variables:
279+
if before:
280+
yield Token(token.type, before, lineno, col_offset)
281+
col_offset += len(before)
282+
yield Token(Token.VARIABLE, variable, lineno, col_offset)
283+
col_offset += len(variable)
284+
if remaining:
285+
yield Token(token.type, remaining, lineno, col_offset)
286+
287+
288+
def _tokenize_variables_v7(token: Token, variables: Any) -> Iterator[Token]:
289+
lineno = token.lineno
290+
col_offset = token.col_offset
291+
after = ""
292+
for match in variables:
293+
if match.before:
294+
yield Token(token.type, match.before, lineno, col_offset)
295+
yield Token(Token.VARIABLE, match.match, lineno, col_offset + match.start)
296+
col_offset += match.end
297+
after = match.after
298+
if after:
299+
yield Token(token.type, after, lineno, col_offset)
300+
301+
302+
_tokenize_variables = _tokenize_variables_before7 if get_robot_version() < (7, 0) else _tokenize_variables_v7
314303

315304

316305
def iter_over_keyword_names_and_owners(

packages/robot/src/robotcode/robot/utils/markdownformatter.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import itertools
44
import re
55
from abc import ABC, abstractmethod
6-
from typing import Any, Callable, Iterator, List, Optional, Tuple
6+
from typing import Any, Callable, Final, Iterator, List, Optional, Tuple
77

88

99
class Formatter(ABC):
@@ -87,7 +87,7 @@ def format_line(self, line: str) -> str: ...
8787

8888

8989
class HeaderFormatter(SingleLineFormatter):
90-
_regex = re.compile(r"^(={1,5})\s+(\S.*?)\s+\1$")
90+
_regex: Final["re.Pattern[str]"] = re.compile(r"^(={1,5})\s+(\S.*?)\s+\1$")
9191

9292
def match(self, line: str) -> Optional[re.Match[str]]:
9393
return self._regex.match(line)
@@ -103,8 +103,8 @@ def format_line(self, line: str) -> str:
103103

104104
class LinkFormatter:
105105
_image_exts = (".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg")
106-
_link = re.compile(r"\[(.+?\|.*?)\]")
107-
_url = re.compile(
106+
_link: Final["re.Pattern[str]"] = re.compile(r"\[(.+?\|.*?)\]")
107+
_url: Final["re.Pattern[str]"] = re.compile(
108108
r"""
109109
((^|\ ) ["'(\[{]*) # begin of line or space and opt. any char "'([{
110110
([a-z][\w+-.]*://[^\s|]+?) # url
@@ -177,7 +177,7 @@ def _is_image(self, text: str) -> bool:
177177

178178

179179
class LineFormatter:
180-
_bold = re.compile(
180+
_bold: Final["re.Pattern[str]"] = re.compile(
181181
r"""
182182
( # prefix (group 1)
183183
(^|\ ) # begin of line or space
@@ -193,7 +193,7 @@ class LineFormatter:
193193
""",
194194
re.VERBOSE,
195195
)
196-
_italic = re.compile(
196+
_italic: Final["re.Pattern[str]"] = re.compile(
197197
r"""
198198
( (^|\ ) ["'(]* ) # begin of line or space and opt. any char "'(
199199
_ # start of italic
@@ -203,7 +203,7 @@ class LineFormatter:
203203
""",
204204
re.VERBOSE,
205205
)
206-
_code = re.compile(
206+
_code: Final["re.Pattern[str]"] = re.compile(
207207
r"""
208208
( (^|\ ) ["'(]* ) # same as above with _ changed to ``
209209
``
@@ -296,7 +296,7 @@ def _combine_lines(self, lines: List[str]) -> Iterator[str]:
296296

297297

298298
class RulerFormatter(SingleLineFormatter):
299-
regex = re.compile("^-{3,}$")
299+
regex: Final["re.Pattern[str]"] = re.compile("^-{3,}$")
300300

301301
def match(self, line: str) -> Optional[re.Match[str]]:
302302
return self.regex.match(line)
@@ -306,9 +306,9 @@ def format_line(self, line: str) -> str:
306306

307307

308308
class TableFormatter(Formatter):
309-
_table_line = re.compile(r"^\| (.* |)\|$")
310-
_line_splitter = re.compile(r" \|(?= )")
311-
_format_cell_content = _line_formatter.format
309+
_table_line: Final["re.Pattern[str]"] = re.compile(r"^\| (.* |)\|$")
310+
_line_splitter: Final["re.Pattern[str]"] = re.compile(r" \|(?= )")
311+
_format_cell_content: Final[Callable[[str], str]] = _line_formatter.format
312312

313313
def _handles(self, line: str) -> bool:
314314
return self._table_line.match(line) is not None

packages/robot/src/robotcode/robot/utils/match.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,17 @@
22

33
_transform_table = str.maketrans("", "", "_ ")
44

5+
_transform_table_namespace = str.maketrans("", "", " ")
56

6-
@lru_cache(maxsize=None)
7+
8+
@lru_cache(maxsize=8192)
79
def normalize(text: str) -> str:
8-
# return text.lower().replace("_", "").replace(" ", "")
9-
return text.casefold().translate(_transform_table)
10+
return text.translate(_transform_table).casefold()
1011

1112

12-
@lru_cache(maxsize=None)
13+
@lru_cache(maxsize=8192)
1314
def normalize_namespace(text: str) -> str:
14-
return text.lower().replace(" ", "")
15+
return text.translate(_transform_table_namespace).casefold()
1516

1617

1718
def eq(str1: str, str2: str) -> bool:

packages/robot/src/robotcode/robot/utils/stubs.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,6 @@
1-
from typing import Any, Dict, Iterator, List, Protocol, Set, runtime_checkable
1+
from typing import Any, Dict, Iterator, List, Protocol, Set
22

33

4-
@runtime_checkable
5-
class BodyBlock(Protocol):
6-
body: List[Any]
7-
8-
9-
@runtime_checkable
104
class Languages(Protocol):
115
languages: List[Any]
126
headers: Dict[str, str]

packages/robot/src/robotcode/robot/utils/variables.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,26 +47,26 @@
4747
]
4848

4949

50-
@functools.lru_cache(maxsize=512)
50+
@functools.lru_cache(maxsize=8192)
5151
def contains_variable(string: str, identifiers: str = "$@&") -> bool:
5252
return cast(bool, robot_contains_variable(string, identifiers))
5353

5454

55-
@functools.lru_cache(maxsize=512)
55+
@functools.lru_cache(maxsize=8192)
5656
def is_scalar_assign(string: str, allow_assign_mark: bool = False) -> bool:
5757
return cast(bool, robot_is_scalar_assign(string, allow_assign_mark))
5858

5959

60-
@functools.lru_cache(maxsize=512)
60+
@functools.lru_cache(maxsize=8192)
6161
def is_variable(string: str, identifiers: str = "$@&") -> bool:
6262
return cast(bool, robot_is_variable(string, identifiers))
6363

6464

65-
@functools.lru_cache(maxsize=512)
65+
@functools.lru_cache(maxsize=8192)
6666
def search_variable(string: str, identifiers: str = "$@&%*", ignore_errors: bool = False) -> RobotVariableMatch:
6767
return robot_search_variable(string, identifiers, ignore_errors)
6868

6969

70-
@functools.lru_cache(maxsize=512)
70+
@functools.lru_cache(maxsize=8192)
7171
def split_from_equals(string: str) -> Tuple[str, Optional[str]]:
7272
return cast(Tuple[str, Optional[str]], robot_split_from_equals(string))

packages/robot/src/robotcode/robot/utils/visitor.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from typing import (
44
Any,
55
Callable,
6+
ClassVar,
67
Dict,
78
Iterator,
89
Optional,
@@ -37,7 +38,7 @@ def iter_field_values(node: ast.AST) -> Iterator[Any]:
3738

3839

3940
class VisitorFinder(ABC):
40-
__cls_finder_cache__: Dict[Type[Any], Optional[Callable[..., Any]]]
41+
__cls_finder_cache__: ClassVar[Dict[Type[Any], Optional[Callable[..., Any]]]]
4142

4243
def __init_subclass__(cls, **kwargs: Any) -> None:
4344
super().__init_subclass__(**kwargs)

tests/robotcode/language_server/robotframework/parts/data/.vscode/settings.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
}
1414
},
1515
"robotcode.languageServer.extraArgs": [
16-
"--verbose",
17-
"--debugpy",
16+
// "--verbose",
17+
// "--debugpy",
1818
// "--debugpy-wait-for-client",
1919
// "--log",
2020
// "--log-level", "INFO",

0 commit comments

Comments
 (0)