Skip to content

Commit 4569e00

Browse files
committed
some more code cleanup, simplifications, refactorings
1 parent a044638 commit 4569e00

File tree

6 files changed

+95
-79
lines changed

6 files changed

+95
-79
lines changed

robotcode/language_server/robotframework/diagnostics/library_doc.py

Lines changed: 61 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -312,18 +312,7 @@ def get_full_doc(self, add_signature: bool = True, header_level: int = 0) -> str
312312
result = ""
313313

314314
if add_signature:
315-
result += (
316-
f"\n\n={'='*header_level} "
317-
f"{'Library' if self.is_initializer else 'Keyword'} *{self.name}* "
318-
f"={'='*header_level}\n"
319-
)
320-
if self.args:
321-
result += f"\n=={'='*header_level} Arguments: =={'='*header_level}\n"
322-
for a in self.args:
323-
result += f"\n| {str(a)}"
324-
325-
else:
326-
result = ""
315+
result += self._get_signature(header_level)
327316

328317
if self.doc:
329318
if result:
@@ -337,6 +326,19 @@ def get_full_doc(self, add_signature: bool = True, header_level: int = 0) -> str
337326

338327
return self.doc
339328

329+
def _get_signature(self, header_level: int) -> str:
330+
result = (
331+
f"\n\n={'='*header_level} "
332+
f"{'Library' if self.is_initializer else 'Keyword'} *{self.name}* "
333+
f"={'='*header_level}\n"
334+
)
335+
if self.args:
336+
result += f"\n=={'='*header_level} Arguments: =={'='*header_level}\n"
337+
for a in self.args:
338+
result += f"\n| {str(a)}"
339+
340+
return result
341+
340342
@property
341343
def signature(self) -> str:
342344
return f"({self.type}) \"{self.name}\": ({', '.join(str(a) for a in self.args)})"
@@ -539,42 +541,45 @@ def get_full_doc(self, only_doc: bool = True) -> str:
539541
else:
540542
doc = self.doc
541543

542-
if self.doc:
543-
result += "\n== Introduction ==\n\n"
544-
545544
if doc:
545+
result += "\n== Introduction ==\n\n"
546546
result += doc
547547

548548
if not only_doc:
549-
if any(v for v in self.inits.values() if v.args):
550-
result += "\n---\n\n"
551-
result += "\n== Importing == \n\n"
549+
result += self._get_doc_for_keywords()
552550

553-
first = True
551+
return self._process_inline_links(result)
554552

555-
for kw in self.inits.values():
556-
if not first:
557-
result += "\n---\n"
558-
first = False
553+
return self.doc
559554

560-
result += "\n" + kw.get_full_doc()
555+
def _get_doc_for_keywords(self) -> str:
556+
result = ""
557+
if any(v for v in self.inits.values() if v.args):
558+
result += "\n---\n\n"
559+
result += "\n== Importing == \n\n"
561560

562-
if self.keywords:
563-
result += "\n---\n\n"
564-
result += "\n== Keywords == \n\n"
561+
first = True
565562

566-
first = True
563+
for kw in self.inits.values():
564+
if not first:
565+
result += "\n---\n"
566+
first = False
567567

568-
for kw in self.keywords.values():
569-
if not first:
570-
result += "\n---\n"
571-
first = False
568+
result += "\n" + kw.get_full_doc()
572569

573-
result += "\n" + kw.get_full_doc(header_level=2)
570+
if self.keywords:
571+
result += "\n---\n\n"
572+
result += "\n== Keywords == \n\n"
574573

575-
return self._process_inline_links(result)
574+
first = True
576575

577-
return self.doc
576+
for kw in self.keywords.values():
577+
if not first:
578+
result += "\n---\n"
579+
first = False
580+
581+
result += "\n" + kw.get_full_doc(header_level=2)
582+
return result
578583

579584
def _add_toc(self, doc: str, only_doc: bool = True) -> str:
580585
toc = self._create_toc(doc, only_doc)
@@ -606,23 +611,7 @@ def _update_env(
606611
) -> None:
607612
import gc
608613

609-
global __PRELOADED_MODULES
610-
611-
if __PRELOADED_MODULES is None:
612-
try:
613-
__import__("robot.libraries.BuiltIn")
614-
except ImportError:
615-
pass
616-
617-
__PRELOADED_MODULES = set(sys.modules.values())
618-
else:
619-
for m in (f for f in set(sys.modules.values()) - __PRELOADED_MODULES if not f.__name__.startswith("robot.")):
620-
try:
621-
importlib.reload(m)
622-
except (SystemExit, KeyboardInterrupt):
623-
raise
624-
except BaseException:
625-
pass
614+
unload_preloaded_modules()
626615

627616
file = Path(__file__).resolve()
628617
top = file.parents[3]
@@ -647,6 +636,26 @@ def _update_env(
647636
os.environ[k] = v
648637

649638

639+
def unload_preloaded_modules() -> None:
640+
global __PRELOADED_MODULES
641+
642+
if __PRELOADED_MODULES is None:
643+
try:
644+
__import__("robot.libraries.BuiltIn")
645+
except ImportError:
646+
pass
647+
648+
__PRELOADED_MODULES = set(sys.modules.values())
649+
else:
650+
for m in (f for f in set(sys.modules.values()) - __PRELOADED_MODULES if not f.__name__.startswith("robot.")):
651+
try:
652+
importlib.reload(m)
653+
except (SystemExit, KeyboardInterrupt):
654+
raise
655+
except BaseException:
656+
pass
657+
658+
650659
def get_module_spec(module_name: str) -> Optional[ModuleSpec]:
651660
import importlib.util
652661

robotcode/language_server/robotframework/diagnostics/namespace.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from pathlib import Path
1111
from typing import (
1212
Any,
13-
AsyncIterator,
13+
AsyncGenerator,
1414
Callable,
1515
Dict,
1616
Iterable,
@@ -1216,7 +1216,7 @@ async def _get_keyword_from_self(self, name: str) -> Optional[KeywordDoc]:
12161216
self.self_library_doc = await self.namespace.get_library_doc()
12171217
return self.self_library_doc.keywords.get(name, None)
12181218

1219-
async def _yield_owner_and_kw_names(self, full_name: str) -> AsyncIterator[Tuple[str, ...]]:
1219+
async def _yield_owner_and_kw_names(self, full_name: str) -> AsyncGenerator[Tuple[str, ...], None]:
12201220
tokens = full_name.split(".")
12211221
for i in range(1, len(tokens)):
12221222
yield ".".join(tokens[:i]), ".".join(tokens[i:])

robotcode/language_server/robotframework/parts/completion.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from typing import (
1010
TYPE_CHECKING,
1111
Any,
12+
AsyncGenerator,
1213
AsyncIterator,
1314
Awaitable,
1415
Callable,
@@ -158,7 +159,7 @@ async def get_section_style(self) -> str:
158159

159160
return self._section_style or DEFAULT_SECTIONS_STYLE
160161

161-
async def _find_methods(self, cls: Type[Any]) -> AsyncIterator[_CompleteMethod]:
162+
async def _find_methods(self, cls: Type[Any]) -> AsyncGenerator[_CompleteMethod, None]:
162163
if cls is ast.AST:
163164
return
164165

robotcode/language_server/robotframework/utils/ast.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
)
1616

1717
from ...common.lsp_types import Position, Range
18-
from .async_ast import walk
18+
from . import async_ast
1919

2020

2121
def iter_nodes(node: ast.AST) -> Generator[ast.AST, None, None]:
@@ -176,7 +176,11 @@ def get_tokens_at_position(node: HasTokens, position: Position) -> List[Token]:
176176

177177

178178
def iter_nodes_at_position(node: ast.AST, position: Position) -> AsyncIterator[ast.AST]:
179-
return (n async for n in walk(node) if position.is_in_range(range := range_from_node(n)) or range.end == position)
179+
return (
180+
n
181+
async for n in async_ast.iter_nodes(node)
182+
if position.is_in_range(range := range_from_node(n)) or range.end == position
183+
)
180184

181185

182186
async def get_nodes_at_position(node: ast.AST, position: Position) -> List[ast.AST]:

robotcode/utils/async_event.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from types import MethodType
99
from typing import (
1010
Any,
11+
AsyncGenerator,
1112
AsyncIterator,
1213
Awaitable,
1314
Callable,
@@ -94,10 +95,8 @@ def __iter__(self) -> Iterator[_TCallable]:
9495
yield c
9596

9697
async def __aiter__(self) -> AsyncIterator[_TCallable]:
97-
for r in self._listeners:
98-
c = r()
99-
if c is not None:
100-
yield c
98+
for r in self.__iter__():
99+
yield r
101100

102101
async def _notify(
103102
self, *args: Any, callback_filter: Optional[Callable[[_TCallable], bool]] = None, **kwargs: Any
@@ -296,7 +295,7 @@ async def _notify( # type: ignore
296295
return_exceptions: Optional[bool] = True,
297296
callback_filter: Optional[Callable[[_TCallable], bool]] = None,
298297
**kwargs: Any,
299-
) -> AsyncIterator[Union[_TResult, BaseException]]:
298+
) -> AsyncGenerator[Union[_TResult, BaseException], None]:
300299
def _done(f: asyncio.Future[_TResult]) -> None:
301300
if result_callback is not None:
302301
try:

robotcode/utils/async_itertools.py

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import inspect
22
from typing import (
3+
AsyncGenerator,
34
AsyncIterable,
45
AsyncIterator,
56
Awaitable,
@@ -10,13 +11,13 @@
1011
cast,
1112
)
1213

13-
__all__ = ["async_chain", "async_chain_iterator"]
14+
__all__ = ["async_chain", "async_chain_iterator", "async_takewhile", "async_dropwhile"]
1415

1516
_T = TypeVar("_T")
1617
AnyIterable = Union[Iterable[_T], AsyncIterable[_T]]
1718

1819

19-
async def async_chain(*iterables: AnyIterable[_T]) -> AsyncIterator[_T]:
20+
async def async_chain(*iterables: AnyIterable[_T]) -> AsyncGenerator[_T, None]:
2021
for iterable in iterables:
2122
if isinstance(iterable, AsyncIterable):
2223
async for v in iterable:
@@ -26,7 +27,9 @@ async def async_chain(*iterables: AnyIterable[_T]) -> AsyncIterator[_T]:
2627
yield v
2728

2829

29-
async def async_chain_iterator(iterator: AsyncIterator[Union[Iterable[_T], AsyncIterable[_T]]]) -> AsyncIterator[_T]:
30+
async def async_chain_iterator(
31+
iterator: AsyncIterator[Union[Iterable[_T], AsyncIterable[_T]]]
32+
) -> AsyncGenerator[_T, None]:
3033
async for e in iterator:
3134
async for v in async_chain(e):
3235
yield v
@@ -35,40 +38,42 @@ async def async_chain_iterator(iterator: AsyncIterator[Union[Iterable[_T], Async
3538
async def async_takewhile(
3639
predicate: Union[Callable[[_T], bool], Callable[[_T], Awaitable[bool]]],
3740
iterable: AnyIterable[_T],
38-
) -> AsyncIterator[_T]:
41+
) -> AsyncGenerator[_T, None]:
3942
if isinstance(iterable, AsyncIterable):
4043
async for e in iterable:
41-
result = predicate(e)
42-
if inspect.isawaitable(result):
43-
result = await cast(Awaitable[bool], result)
44+
result = await __call_predicate(predicate, e)
4445
if result:
4546
yield e
4647
else:
4748
break
4849
else:
4950
for e in iterable:
50-
result = predicate(e)
51-
if inspect.isawaitable(result):
52-
result = await cast(Awaitable[bool], result)
51+
result = await __call_predicate(predicate, e)
5352
if result:
5453
yield e
5554
else:
5655
break
5756

5857

58+
async def __call_predicate(predicate: Union[Callable[[_T], bool], Callable[[_T], Awaitable[bool]]], e: _T) -> bool:
59+
result = predicate(e)
60+
if inspect.isawaitable(result):
61+
return await cast(Awaitable[bool], result)
62+
return cast(bool, result)
63+
64+
5965
async def async_dropwhile(
6066
predicate: Union[Callable[[_T], bool], Callable[[_T], Awaitable[bool]]],
6167
iterable: AnyIterable[_T],
62-
) -> AsyncIterator[_T]:
68+
) -> AsyncGenerator[_T, None]:
6369
result: Union[bool, Awaitable[bool]] = True
70+
6471
if isinstance(iterable, AsyncIterable):
6572
async for e in iterable:
6673
if not result:
6774
yield e
6875
else:
69-
result = predicate(e)
70-
if inspect.isawaitable(result):
71-
result = await cast(Awaitable[bool], result)
76+
result = await __call_predicate(predicate, e)
7277

7378
if not result:
7479
yield e
@@ -77,9 +82,7 @@ async def async_dropwhile(
7782
if not result:
7883
yield e
7984
else:
80-
result = predicate(e)
81-
if inspect.isawaitable(result):
82-
result = await cast(Awaitable[bool], result)
85+
result = await __call_predicate(predicate, e)
8386

8487
if not result:
8588
yield e

0 commit comments

Comments
 (0)