Skip to content

Commit feda8bf

Browse files
committed
WIP
1 parent 1e00163 commit feda8bf

1 file changed

Lines changed: 26 additions & 14 deletions

File tree

src/docstub/_docstrings.py

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import logging
44
import traceback
5+
from contextlib import contextmanager
56
from dataclasses import dataclass, field
67
from functools import cached_property
78
from pathlib import Path
@@ -31,7 +32,7 @@
3132
_lark = lark.Lark(_grammar, propagate_positions=True, strict=True)
3233

3334

34-
def _find_one_token(tree: lark.Tree, *, name: str) -> lark.Token:
35+
def _find_one_token(tree, *, name):
3536
"""Find token with a specific type name in tree.
3637
3738
Parameters
@@ -285,25 +286,13 @@ def doctype_to_annotation(self, doctype):
285286
A set containing tuples. Each tuple contains a qualname, its start and its
286287
end index relative to the given `doctype`.
287288
"""
288-
try:
289-
self._collected_imports = set()
290-
self._unknown_qualnames = []
289+
with self._prepare_transformation():
291290
tree = _lark.parse(doctype)
292291
value = super().transform(tree=tree)
293292
annotation = Annotation(
294293
value=value, imports=frozenset(self._collected_imports)
295294
)
296295
return annotation, self._unknown_qualnames
297-
except (
298-
lark.exceptions.LexError,
299-
lark.exceptions.ParseError,
300-
QualnameIsKeyword,
301-
):
302-
self.stats["syntax_errors"] += 1
303-
raise
304-
finally:
305-
self._collected_imports = None
306-
self._unknown_qualnames = None
307296

308297
def qualname(self, tree):
309298
"""
@@ -509,6 +498,29 @@ def __default__(self, data, children, meta):
509498
out = children
510499
return out
511500

501+
@contextmanager
502+
def _prepare_transformation(self):
503+
"""Reset transformation state before entering context and restore it on exit."""
504+
collected_imports = self._collected_imports
505+
unknown_qualnames = self._unknown_qualnames
506+
507+
try:
508+
self._collected_imports = set()
509+
self._unknown_qualnames = []
510+
yield
511+
512+
except (
513+
lark.exceptions.LexError,
514+
lark.exceptions.ParseError,
515+
QualnameIsKeyword,
516+
):
517+
self.stats["syntax_errors"] += 1
518+
raise
519+
520+
finally:
521+
self._collected_imports = collected_imports
522+
self._unknown_qualnames = unknown_qualnames
523+
512524
def _match_import(self, qualname, *, meta):
513525
"""Match `qualname` to known imports or alias to "Incomplete".
514526

0 commit comments

Comments
 (0)