-
Notifications
You must be signed in to change notification settings - Fork 17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
WIP: Add substitution definition code and tests #385
Open
melissawm
wants to merge
12
commits into
jupyter:main
Choose a base branch
from
melissawm:substitution-definition
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
7647201
WIP: Add substitution definition code and tests
melissawm a6b700e
reformat
Carreau 61867dc
Try some refactor to handle more cases.
Carreau 6d4ff18
more tests
Carreau 265836e
some explanations
Carreau 52627c8
exclude numpy tables
Carreau 0604b1d
fix flake8
Carreau a67ad20
add MComent to SAI
Carreau 42054cf
Minor cleanup and Make SubstitutionDef unserialisable.
Carreau 2b642ba
fix stray f-string
Carreau 1025213
more details
Carreau 1ebeaa4
try to implement global substitutions
Carreau File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -79,6 +79,7 @@ | |
RefInfo, | ||
Section, | ||
SeeAlsoItem, | ||
SubstitutionDef, | ||
parse_rst_section, | ||
) | ||
from .toc import make_tree | ||
|
@@ -98,6 +99,8 @@ | |
# delayed import | ||
if True: | ||
from .myst_ast import MText | ||
from .myst_ast import ReplaceNode | ||
from .myst_ast import MParagraph | ||
|
||
|
||
class ErrorCollector: | ||
|
@@ -432,6 +435,7 @@ class Config: | |
fail_unseen_error: bool = False | ||
execute_doctests: bool = True | ||
directives: Dict[str, str] = dataclasses.field(default_factory=lambda: {}) | ||
substitution_definitions: Dict[str, str] = dataclasses.field(default_factory=dict) | ||
|
||
def replace(self, **kwargs): | ||
return dataclasses.replace(self, **kwargs) | ||
|
@@ -1388,8 +1392,15 @@ def debugprint(*args): | |
docstring=example_code, | ||
) | ||
if config.execute_doctests: | ||
doctest_runner.run(doctests, out=debugprint, clear_globs=False) | ||
doctest_runner.globs.update(doctests.globs) | ||
with warnings.catch_warnings(): | ||
warnings.filterwarnings( | ||
"ignore", | ||
"FigureCanvasAgg is non-interactive.*", | ||
UserWarning, | ||
) | ||
|
||
doctest_runner.run(doctests, out=debugprint, clear_globs=False) | ||
doctest_runner.globs.update(doctests.globs) | ||
example_section_data.extend( | ||
doctest_runner.get_example_section_data() | ||
) | ||
|
@@ -1403,7 +1414,7 @@ def debugprint(*args): | |
# TODO fix this if plt.close not called and still a lingering figure. | ||
fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() | ||
if len(fig_managers) != 0: | ||
print_(f"Unclosed figures in {qa}!!") | ||
self.log.debug("Unclosed figures in %s!!", qa) | ||
plt.close("all") | ||
|
||
return processed_example_data(example_section_data), doctest_runner.figs | ||
|
@@ -1448,6 +1459,18 @@ def collect_narrative_docs(self): | |
trees = {} | ||
title_map = {} | ||
blbs = {} | ||
global_substitutions = {} | ||
for k, v in self.config.substitution_definitions.items(): | ||
res = ts.parse(v.encode(), qa="global_substitution") | ||
# HERE are some assumptions as we are parsing a "full document" with tree sitter | ||
# this is going to give a single Section with a single paragraph. | ||
sec: Section | ||
[sec] = res | ||
assert isinstance(sec, Section) | ||
[par] = sec.children | ||
assert isinstance(par, MParagraph) | ||
par: MParagraph | ||
global_substitutions["|" + k + "|"] = [ReplaceNode(k, v, par.children)] | ||
with self.progress() as p2: | ||
task = p2.add_task("Parsing narrative", total=len(files)) | ||
|
||
|
@@ -1469,10 +1492,16 @@ def collect_narrative_docs(self): | |
blob = DocBlob.new() | ||
key = ":".join(parts)[:-4] | ||
try: | ||
from copy import copy | ||
|
||
G = copy(global_substitutions) | ||
G.update({}) | ||
ref_set: frozenset[RefInfo] = frozenset({}) | ||
dv = DVR( | ||
key, | ||
set(), | ||
ref_set, | ||
local_refs=set(), | ||
substitution_defs=G, | ||
aliases={}, | ||
version=self._meta["version"], | ||
config=self.config.directives, | ||
|
@@ -1503,7 +1532,11 @@ def collect_narrative_docs(self): | |
|
||
blbs[key] = blob | ||
for k, b in blbs.items(): | ||
self.docs[k] = b.to_json() | ||
try: | ||
self.docs[k] = b.to_json() | ||
except Exception as e: | ||
e.add_note(f"serializing {k}") | ||
raise | ||
|
||
self._doctree = {"tree": make_tree(trees), "titles": title_map} | ||
|
||
|
@@ -1526,7 +1559,11 @@ def write_api(self, where: Path): | |
""" | ||
(where / "module").mkdir(exist_ok=True) | ||
for k, v in self.data.items(): | ||
(where / "module" / (k + ".json")).write_bytes(v.to_json()) | ||
try: | ||
(where / "module" / (k + ".json")).write_bytes(v.to_json()) | ||
except Exception as e: | ||
e.add_note(f"serializing {k}") | ||
raise | ||
|
||
def partial_write(self, where): | ||
self.write_api(where) | ||
|
@@ -1931,6 +1968,7 @@ def collect_examples(self, folder: Path, config): | |
example.name, | ||
frozenset(), | ||
local_refs=frozenset(), | ||
substitution_defs={}, | ||
aliases={}, | ||
version=self.version, | ||
config=self.config.directives, | ||
|
@@ -2255,20 +2293,46 @@ def collect_api_docs(self, root: str, limit_to: List[str]) -> None: | |
if new_ref: | ||
_local_refs = _local_refs + new_ref | ||
|
||
# substitution_defs: Dict[str, Union(MImage, ReplaceNode)] = {} | ||
substitution_defs = {} | ||
sections = [] | ||
for section in doc_blob.sections: | ||
sections.append(doc_blob.content.get(section, [])) | ||
# arbitrary is usually raw RST that typically is a module docstring that can't be | ||
# parsed by numpydoc | ||
sections.extend(arbitrary) | ||
for section in sections: | ||
for child in section: | ||
if isinstance(child, SubstitutionDef): | ||
if child.value in substitution_defs: | ||
self.log.warn( | ||
"The same substitution definition was found twice: %s", | ||
child.value, | ||
) | ||
substitution_defs[child.value] = child.children | ||
|
||
if substitution_defs: | ||
self.log.debug( | ||
"Found substitution def for %s : %s", qa, substitution_defs | ||
) | ||
|
||
# def flat(l) -> List[str]: | ||
# return [y for x in l for y in x] | ||
for lr1 in _local_refs: | ||
assert isinstance(lr1, str) | ||
# lr: FrozenSet[str] = frozenset(flat(_local_refs)) | ||
lr: FrozenSet[str] = frozenset(_local_refs) | ||
|
||
dv = DVR( | ||
qa, | ||
known_refs, | ||
local_refs=lr, | ||
substitution_defs=substitution_defs, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
aliases={}, | ||
version=self.version, | ||
config=self.config.directives, | ||
) | ||
|
||
doc_blob.arbitrary = [dv.visit(s) for s in arbitrary] | ||
doc_blob.example_section_data = dv.visit(doc_blob.example_section_data) | ||
doc_blob._content = {k: dv.visit(v) for (k, v) in doc_blob._content.items()} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is currently failing on a table because of the
|<table cell>|
syntax in https://numpy.org/doc/stable/reference/generated/numpy.isscalar.htmlThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I think we can just add the part that fail on a table on hte ignore list. I don't think tree-sitter-rst plan to parse tables, and I'm wondering if having a
.. table::
directive could be a good workaround, we can add it to sphinx as well, so that projects work on both papyri and sphinx at the same time.