-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy path__init__.py
More file actions
1506 lines (1339 loc) · 53.7 KB
/
__init__.py
File metadata and controls
1506 lines (1339 loc) · 53.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""The standard domain."""
from __future__ import annotations
import operator
import os.path
import re
from copy import copy
from typing import TYPE_CHECKING, cast
from docutils import nodes
from docutils.parsers.rst import directives
from docutils.statemachine import StringList
from sphinx import addnodes
from sphinx.addnodes import pending_xref
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType
from sphinx.locale import _, __
from sphinx.roles import EmphasizedLiteral, XRefRole
from sphinx.util import docname_join, logging, ws_re
from sphinx.util.docutils import SphinxDirective
from sphinx.util.nodes import clean_astext, make_id, make_refnode
from sphinx.util.parsing import nested_parse_to_nodes
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Iterator, MutableSequence, Set
from typing import Any, ClassVar, Final
from docutils.nodes import Element, Node, system_message
from sphinx.addnodes import desc_signature
from sphinx.application import Sphinx
from sphinx.builders import Builder
from sphinx.environment import BuildEnvironment
from sphinx.util.typing import (
ExtensionMetadata,
OptionSpec,
)
logger = logging.getLogger(__name__)
# RE for option descriptions
option_desc_re = re.compile(r'((?:/|--|-|\+)?[^\s=]+)(=?\s*.*)')
# RE for grammar tokens
token_re = re.compile(r'`((~?[\w-]*:)?\w+)`')
samp_role = EmphasizedLiteral()
class GenericObject(ObjectDescription[str]):
"""A generic x-ref directive registered with Sphinx.add_object_type()."""
indextemplate: str = ''
parse_node: Callable[[BuildEnvironment, str, desc_signature], str] | None = None
def handle_signature(self, sig: str, signode: desc_signature) -> str:
if self.parse_node:
name = self.parse_node(self.env, sig, signode)
else:
signode.clear()
signode += addnodes.desc_name(sig, sig)
# normalize whitespace like XRefRole does
name = ws_re.sub(' ', sig)
return name
def add_target_and_index(
self, name: str, sig: str, signode: desc_signature
) -> None:
node_id = make_id(self.env, self.state.document, self.objtype, name)
signode['ids'].append(node_id)
self.state.document.note_explicit_target(signode)
if self.indextemplate:
colon = self.indextemplate.find(':')
if colon != -1:
indextype = self.indextemplate[:colon].strip()
indexentry = self.indextemplate[colon + 1 :].strip() % (name,)
else:
indextype = 'single'
indexentry = self.indextemplate % (name,)
self.indexnode['entries'].append((indextype, indexentry, node_id, '', None))
std = self.env.domains.standard_domain
std.note_object(self.objtype, name, node_id, location=signode)
class EnvVar(GenericObject):
indextemplate = _('environment variable; %s')
class EnvVarXRefRole(XRefRole):
"""Cross-referencing role for environment variables (adds an index entry)."""
def result_nodes(
self,
document: nodes.document,
env: BuildEnvironment,
node: Element,
is_ref: bool,
) -> tuple[list[Node], list[system_message]]:
if not is_ref:
return [node], []
varname = node['reftarget']
tgtid = 'index-%s' % env.new_serialno('index')
indexnode = addnodes.index()
indexnode['entries'] = [
('single', varname, tgtid, '', None),
('single', _('environment variable; %s') % varname, tgtid, '', None),
]
targetnode = nodes.target('', '', ids=[tgtid])
document.note_explicit_target(targetnode)
return [indexnode, targetnode, node], []
class ConfigurationValue(ObjectDescription[str]):
index_template: str = _('%s; configuration value')
option_spec: ClassVar[OptionSpec] = {
'no-index': directives.flag,
'no-index-entry': directives.flag,
'no-contents-entry': directives.flag,
'no-typesetting': directives.flag,
'type': directives.unchanged_required,
'default': directives.unchanged_required,
}
def handle_signature(self, sig: str, sig_node: desc_signature) -> str:
sig_node.clear()
sig_node += addnodes.desc_name(sig, sig)
name = ws_re.sub(' ', sig)
sig_node['fullname'] = name
return name
def _object_hierarchy_parts(self, sig_node: desc_signature) -> tuple[str, ...]:
return (sig_node['fullname'],)
def _toc_entry_name(self, sig_node: desc_signature) -> str:
if not sig_node.get('_toc_parts'):
return ''
(name,) = sig_node['_toc_parts']
return name
def add_target_and_index(
self, name: str, sig: str, signode: desc_signature
) -> None:
node_id = make_id(self.env, self.state.document, self.objtype, name)
signode['ids'].append(node_id)
self.state.document.note_explicit_target(signode)
index_entry = self.index_template % name
self.indexnode['entries'].append(('pair', index_entry, node_id, '', None))
domain = self.env.domains.standard_domain
domain.note_object(self.objtype, name, node_id, location=signode)
def transform_content(self, content_node: addnodes.desc_content) -> None:
"""Insert *type* and *default* as a field list."""
field_list = nodes.field_list()
if 'type' in self.options:
field, msgs = self.format_type(self.options['type'])
field_list.append(field)
field_list += msgs
if 'default' in self.options:
field, msgs = self.format_default(self.options['default'])
field_list.append(field)
field_list += msgs
if len(field_list.children) > 0:
content_node.insert(0, field_list)
def format_type(self, type_: str) -> tuple[nodes.field, list[system_message]]:
"""Formats the ``:type:`` option."""
parsed, msgs = self.parse_inline(type_, lineno=self.lineno)
field = nodes.field(
'',
nodes.field_name('', _('Type')),
nodes.field_body('', *parsed),
)
return field, msgs
def format_default(self, default: str) -> tuple[nodes.field, list[system_message]]:
"""Formats the ``:default:`` option."""
parsed, msgs = self.parse_inline(default, lineno=self.lineno)
field = nodes.field(
'',
nodes.field_name('', _('Default')),
nodes.field_body('', *parsed),
)
return field, msgs
class Target(SphinxDirective):
"""Generic target for user-defined cross-reference types."""
indextemplate = ''
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec: ClassVar[OptionSpec] = {}
def run(self) -> list[Node]:
# normalize whitespace in fullname like XRefRole does
fullname = ws_re.sub(' ', self.arguments[0].strip())
node_id = make_id(self.env, self.state.document, self.name, fullname)
node = nodes.target('', '', ids=[node_id])
self.set_source_info(node)
self.state.document.note_explicit_target(node)
ret: list[Node] = [node]
if self.indextemplate:
indexentry = self.indextemplate % (fullname,)
indextype = 'single'
colon = indexentry.find(':')
if colon != -1:
indextype = indexentry[:colon].strip()
indexentry = indexentry[colon + 1 :].strip()
inode = addnodes.index(entries=[(indextype, indexentry, node_id, '', None)])
ret.insert(0, inode)
name = self.name
if ':' in self.name:
name = self.name.partition(':')[-1]
std = self.env.domains.standard_domain
std.note_object(name, fullname, node_id, location=node)
return ret
class Cmdoption(ObjectDescription[str]):
"""Description of a command-line option (.. option)."""
def handle_signature(self, sig: str, signode: desc_signature) -> str:
"""Transform an option description into RST nodes."""
count = 0
firstname = ''
for potential_option in sig.split(', '):
potential_option = potential_option.strip()
m = option_desc_re.match(potential_option)
if not m:
logger.warning(
__(
'Malformed option description %r, should '
'look like "opt", "-opt args", "--opt args", '
'"/opt args" or "+opt args"'
),
potential_option,
location=signode,
)
continue
optname, args = m.groups()
if optname[-1] == '[' and args[-1] == ']':
# optional value surrounded by brackets (ex. foo[=bar])
optname = optname[:-1]
args = '[' + args
if count:
if self.config.option_emphasise_placeholders:
signode += addnodes.desc_sig_punctuation(',', ',')
signode += addnodes.desc_sig_space()
else:
signode += addnodes.desc_addname(', ', ', ')
signode += addnodes.desc_name(optname, optname)
if self.config.option_emphasise_placeholders:
add_end_bracket = False
if args:
if args[0] == '[' and args[-1] == ']':
add_end_bracket = True
signode += addnodes.desc_sig_punctuation('[', '[')
args = args[1:-1]
elif args[0] == ' ':
signode += addnodes.desc_sig_space()
args = args.strip()
elif args[0] == '=':
signode += addnodes.desc_sig_punctuation('=', '=')
args = args[1:]
for part in samp_role.parse(args):
if isinstance(part, nodes.Text):
signode += nodes.Text(part.astext())
else:
signode += part
if add_end_bracket:
signode += addnodes.desc_sig_punctuation(']', ']')
else:
signode += addnodes.desc_addname(args, args)
if not count:
firstname = optname
signode['allnames'] = [optname]
else:
signode['allnames'].append(optname)
count += 1
if not firstname:
raise ValueError
return firstname
def add_target_and_index(
self, firstname: str, sig: str, signode: desc_signature
) -> None:
currprogram = self.env.ref_context.get('std:program')
for optname in signode.get('allnames', []): # type: ignore[var-annotated]
prefixes = ['cmdoption']
if currprogram:
prefixes.append(currprogram)
if not optname.startswith(('-', '/')):
prefixes.append('arg')
prefix = '-'.join(prefixes)
node_id = make_id(self.env, self.state.document, prefix, optname)
signode['ids'].append(node_id)
self.state.document.note_explicit_target(signode)
domain = self.env.domains.standard_domain
for optname in signode.get('allnames', ()):
domain.add_program_option(
currprogram,
optname,
self.env.current_document.docname,
signode['ids'][0],
)
# create an index entry
if currprogram:
descr = _('%s command line option') % currprogram
else:
descr = _('command line option')
for option in signode.get('allnames', ()): # type: ignore[var-annotated]
entry = f'{descr}; {option}'
self.indexnode['entries'].append((
'pair',
entry,
signode['ids'][0],
'',
None,
))
class Program(SphinxDirective):
"""Directive to name the program for which options are documented."""
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec: ClassVar[OptionSpec] = {}
def run(self) -> list[Node]:
program = ws_re.sub('-', self.arguments[0].strip())
if program == 'None':
self.env.ref_context.pop('std:program', None)
else:
self.env.ref_context['std:program'] = program
return []
class OptionXRefRole(XRefRole):
def process_link(
self,
env: BuildEnvironment,
refnode: Element,
has_explicit_title: bool,
title: str,
target: str,
) -> tuple[str, str]:
refnode['std:program'] = env.ref_context.get('std:program')
return title, target
_term_classifiers_re = re.compile(' +: +')
def split_term_classifiers(line: str) -> tuple[str, str | None]:
# split line into a term and classifiers. if no classifier, None is used..
parts = _term_classifiers_re.split(line)
term = parts[0]
first_classifier = parts[1] if len(parts) >= 2 else None
return term, first_classifier
def make_glossary_term(
env: BuildEnvironment,
textnodes: Iterable[Node],
index_key: str | None,
source: str,
lineno: int,
node_id: str | None,
document: nodes.document,
) -> nodes.term:
# get a text-only representation of the term and register it
# as a cross-reference target
term = nodes.term('', '', *textnodes)
term.source = source
term.line = lineno
termtext = term.astext()
if node_id:
# node_id is given from outside (mainly i18n module), use it forcedly
term['ids'].append(node_id)
else:
node_id = make_id(env, document, 'term', termtext)
term['ids'].append(node_id)
document.note_explicit_target(term)
env.domains.standard_domain._note_term(termtext, node_id, location=term)
# add an index entry too
indexnode = addnodes.index()
indexnode['entries'] = [('single', termtext, node_id, 'main', index_key)]
indexnode.source, indexnode.line = term.source, term.line
term.append(indexnode)
return term
class Glossary(SphinxDirective):
"""Directive to create a glossary with cross-reference targets for :term:
roles.
"""
has_content = True
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
option_spec: ClassVar[OptionSpec] = {
'sorted': directives.flag,
}
def run(self) -> list[Node]:
node = addnodes.glossary()
node.document = self.state.document
node['sorted'] = 'sorted' in self.options
# This directive implements a custom format of the reST definition list
# that allows multiple lines of terms before the definition. This is
# easy to parse since we know that the contents of the glossary *must
# be* a definition list.
# first, collect single entries
entries: list[tuple[list[tuple[str, str, int]], StringList]] = []
in_definition = True
in_comment = False
was_empty = True
messages: list[Node] = []
indent_len = 0
for line, (source, lineno) in zip(
self.content, self.content.items, strict=True
):
# empty line -> add to last definition
if not line:
if in_definition and entries:
entries[-1][1].append('', source, lineno)
was_empty = True
continue
# unindented line -> a term
if line and not line[0].isspace():
# enable comments
if line.startswith('.. '):
in_comment = True
continue
in_comment = False
# first term of definition
if in_definition:
if not was_empty:
messages.append(
self.state.reporter.warning(
_('glossary term must be preceded by empty line'),
source=source,
line=lineno,
)
)
entries.append(([(line, source, lineno)], StringList()))
in_definition = False
# second term and following
else:
if was_empty:
messages.append(
self.state.reporter.warning(
_(
'glossary terms must not be separated by empty lines'
),
source=source,
line=lineno,
)
)
if entries:
entries[-1][0].append((line, source, lineno))
else:
messages.append(
self.state.reporter.warning(
_(
'glossary seems to be misformatted, check indentation'
),
source=source,
line=lineno,
)
)
elif in_comment:
pass
else:
if not in_definition:
# first line of definition, determines indentation
in_definition = True
indent_len = len(line) - len(line.lstrip())
if entries:
entries[-1][1].append(line[indent_len:], source, lineno)
else:
messages.append(
self.state.reporter.warning(
_('glossary seems to be misformatted, check indentation'),
source=source,
line=lineno,
)
)
was_empty = False
# now, parse all the entries into a big definition list
items: list[nodes.definition_list_item] = []
for terms, definition in entries:
termnodes: list[Node] = []
system_messages: list[Node] = []
for line, source, lineno in terms:
term_, first_classifier = split_term_classifiers(line)
# parse the term with inline markup
# classifiers (parts[1:]) will not be shown on doctree
textnodes, sysmsg = self.parse_inline(term_, lineno=lineno)
# use first classifier as a index key
term = make_glossary_term(
self.env,
textnodes,
first_classifier,
source,
lineno,
node_id=None,
document=self.state.document,
)
term.rawsource = line
system_messages.extend(sysmsg)
termnodes.append(term)
termnodes.extend(system_messages)
if definition:
offset = definition.items[0][1]
definition_nodes = nested_parse_to_nodes(
self.state,
definition,
offset=offset,
allow_section_headings=False,
)
else:
definition_nodes = []
termnodes.append(nodes.definition('', *definition_nodes))
items.append(nodes.definition_list_item('', *termnodes))
dlist = nodes.definition_list('', *items)
dlist['classes'].append('glossary')
node += dlist
return [*messages, node]
def token_xrefs(text: str, production_group: str = '') -> Iterable[Node]:
if len(production_group) != 0:
production_group += ':'
retnodes: list[Node] = []
pos = 0
for m in token_re.finditer(text):
if m.start() > pos:
txt = text[pos : m.start()]
retnodes.append(nodes.Text(txt))
token = m.group(1)
if ':' in token:
if token[0] == '~':
_, title = token.split(':')
target = token[1:]
elif token[0] == ':':
title = token[1:]
target = title
else:
title = token
target = token
else:
title = token
target = production_group + token
refnode = pending_xref(
title, reftype='token', refdomain='std', reftarget=target
)
refnode += nodes.literal(token, title, classes=['xref'])
retnodes.append(refnode)
pos = m.end()
if pos < len(text):
retnodes.append(nodes.Text(text[pos:]))
return retnodes
class ProductionList(SphinxDirective):
"""Directive to list grammar productions."""
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec: ClassVar[OptionSpec] = {}
# The backslash handling is from ObjectDescription.get_signatures
_nl_escape_re: Final = re.compile(r'\\\n')
# Get 'name' from triples of rawsource, name, definition (tokens)
_name_getter = operator.itemgetter(1)
def run(self) -> list[Node]:
name_getter = self._name_getter
lines = self._nl_escape_re.sub('', self.arguments[0]).splitlines()
# Extract production_group argument.
# Must be before extracting production definition triples.
production_group = self.production_group(lines=lines, options=self.options)
production_lines = list(self.production_definitions(lines))
max_name_len = max(map(len, map(name_getter, production_lines)))
node_location = self.get_location()
productions = [
self.make_production(
rawsource=rule,
name=name,
tokens=tokens,
production_group=production_group,
max_len=max_name_len,
location=node_location,
)
for rule, name, tokens in production_lines
]
node = addnodes.productionlist('', *productions)
self.set_source_info(node)
return [node]
@staticmethod
def production_group(
*,
lines: MutableSequence[str],
options: dict[str, Any], # NoQA: ARG004
) -> str:
# get production_group
if not lines or ':' in lines[0]:
return ''
production_group = lines[0].strip()
lines[:] = lines[1:]
return production_group
@staticmethod
def production_definitions(
lines: Iterable[str], /
) -> Iterator[tuple[str, str, str]]:
"""Yield triples of rawsource, name, definition (tokens)."""
for line in lines:
if ':' not in line:
break
name, _, tokens = line.partition(':')
yield line, name.strip(), tokens.strip()
def make_production(
self,
*,
rawsource: str,
name: str,
tokens: str,
production_group: str,
max_len: int,
location: str,
) -> addnodes.production:
production_node = addnodes.production(rawsource, tokenname=name)
if name:
production_node += self.make_name_target(
name=name, production_group=production_group, location=location
)
production_node.append(self.separator_node(name=name, max_len=max_len))
production_node += token_xrefs(text=tokens, production_group=production_group)
production_node.append(nodes.Text('\n'))
return production_node
def make_name_target(
self,
*,
name: str,
production_group: str,
location: str,
) -> addnodes.literal_strong:
"""Make a link target for the given production."""
name_node = addnodes.literal_strong(name, name)
prefix = f'grammar-token-{production_group}'
node_id = make_id(self.env, self.state.document, prefix, name)
name_node['ids'].append(node_id)
self.state.document.note_implicit_target(name_node, name_node)
obj_name = f'{production_group}:{name}' if production_group else name
std = self.env.domains.standard_domain
std.note_object('token', obj_name, node_id, location=location)
return name_node
@staticmethod
def separator_node(*, name: str, max_len: int) -> nodes.Text:
"""Return separator between 'name' and 'tokens'."""
if name:
return nodes.Text(' ::= '.rjust(max_len - len(name) + 5))
return nodes.Text(' ' * (max_len + 5))
class TokenXRefRole(XRefRole):
def process_link(
self,
env: BuildEnvironment,
refnode: Element,
has_explicit_title: bool,
title: str,
target: str,
) -> tuple[str, str]:
target = target.lstrip('~') # a title-specific thing
if not self.has_explicit_title and title[0] == '~':
if ':' in title:
_, title = title.split(':')
else:
title = title[1:]
return title, target
class StandardDomain(Domain):
"""Domain for all objects that don't fit into another domain or are added
via the application interface.
"""
name = 'std'
label = 'Default'
object_types = {
'term': ObjType(_('glossary term'), 'term', searchprio=-1),
'token': ObjType(_('grammar token'), 'token', searchprio=-1),
'label': ObjType(_('reference label'), 'ref', 'keyword', searchprio=-1),
'confval': ObjType('configuration value', 'confval'),
'envvar': ObjType(_('environment variable'), 'envvar'),
'cmdoption': ObjType(_('program option'), 'option'),
'doc': ObjType(_('document'), 'doc', searchprio=-1),
}
directives = {
'program': Program,
'cmdoption': Cmdoption, # old name for backwards compatibility
'option': Cmdoption,
'confval': ConfigurationValue,
'envvar': EnvVar,
'glossary': Glossary,
'productionlist': ProductionList,
}
roles = {
'option': OptionXRefRole(warn_dangling=True),
'confval': XRefRole(warn_dangling=True),
'envvar': EnvVarXRefRole(),
# links to tokens in grammar productions
'token': TokenXRefRole(),
# links to terms in glossary
'term': XRefRole(innernodeclass=nodes.inline, warn_dangling=True),
# links to headings or arbitrary labels
'ref': XRefRole(
lowercase=True, innernodeclass=nodes.inline, warn_dangling=True
),
# links to labels of numbered figures, tables and code-blocks
'numref': XRefRole(lowercase=True, warn_dangling=True),
# links to labels, without a different title
'keyword': XRefRole(warn_dangling=True),
# links to documents
'doc': XRefRole(warn_dangling=True, innernodeclass=nodes.inline),
}
initial_data: Final = { # type: ignore[misc]
'progoptions': {}, # (program, name) -> docname, labelid
'objects': {}, # (type, name) -> docname, labelid
'labels': { # labelname -> docname, labelid, sectionname
'genindex': ('genindex', '', _('Index')),
'modindex': ('py-modindex', '', _('Module Index')),
'search': ('search', '', _('Search Page')),
},
'anonlabels': { # labelname -> docname, labelid
'genindex': ('genindex', ''),
'modindex': ('py-modindex', ''),
'search': ('search', ''),
},
'labels_source': {}, # labelname -> source file path
}
# labelname -> docname, sectionname
_virtual_doc_names: Final = {
'genindex': ('genindex', _('Index')),
'modindex': ('py-modindex', _('Module Index')),
'search': ('search', _('Search Page')),
}
dangling_warnings = {
'term': 'term not in glossary: %(target)r',
'numref': 'undefined label: %(target)r',
'keyword': 'unknown keyword: %(target)r',
'doc': 'unknown document: %(target)r',
'option': 'unknown option: %(target)r',
}
# node_class -> (figtype, title_getter)
enumerable_nodes = {
nodes.figure: ('figure', None),
nodes.table: ('table', None),
nodes.container: ('code-block', None),
}
def __init__(self, env: BuildEnvironment) -> None:
super().__init__(env)
# set up enumerable nodes
# create a copy for this instance
self.enumerable_nodes = copy(self.enumerable_nodes) # type: ignore[misc]
for node, settings in env._registry.enumerable_nodes.items():
self.enumerable_nodes[node] = settings
def note_hyperlink_target(
self, name: str, docname: str, node_id: str, title: str = ''
) -> None:
"""Add a hyperlink target for cross reference.
.. warning::
This is only for internal use. Please don't use this from your extension.
``document.note_explicit_target()`` or ``note_implicit_target()`` are recommended to
add a hyperlink target to the document.
This only adds a hyperlink target to the StandardDomain. And this does not add a
node_id to node. Therefore, it is very fragile to calling this without
understanding hyperlink target framework in both docutils and Sphinx.
.. versionadded:: 3.0
"""
if name in self.anonlabels and self.anonlabels[name] != (docname, node_id):
logger.warning(
__('duplicate label %s, other instance in %s'),
name,
self.env.doc2path(self.anonlabels[name][0]),
)
self.anonlabels[name] = (docname, node_id)
if title:
self.labels[name] = (docname, node_id, title)
@property
def objects(self) -> dict[tuple[str, str], tuple[str, str]]:
# (objtype, name) -> docname, labelid
return self.data.setdefault('objects', {})
def note_object(
self, objtype: str, name: str, labelid: str, location: Any = None
) -> None:
"""Note a generic object for cross reference.
.. versionadded:: 3.0
"""
if (objtype, name) in self.objects:
docname = self.objects[objtype, name][0]
logger.warning(
__('duplicate %s description of %s, other instance in %s'),
objtype,
name,
docname,
location=location,
)
self.objects[objtype, name] = (self.env.current_document.docname, labelid)
@property
def _terms(self) -> dict[str, tuple[str, str]]:
""".. note:: Will be removed soon. internal use only."""
return self.data.setdefault('terms', {}) # (name) -> docname, labelid
def _note_term(self, term: str, labelid: str, location: Any = None) -> None:
"""Note a term for cross reference.
.. note:: Will be removed soon. internal use only.
"""
self.note_object('term', term, labelid, location)
self._terms[term.lower()] = (self.env.current_document.docname, labelid)
@property
def progoptions(self) -> dict[tuple[str | None, str], tuple[str, str]]:
return self.data.setdefault(
'progoptions', {}
) # (program, name) -> docname, labelid
@property
def labels(self) -> dict[str, tuple[str, str, str]]:
return self.data.setdefault(
'labels', {}
) # labelname -> docname, labelid, sectionname
@property
def anonlabels(self) -> dict[str, tuple[str, str]]:
return self.data.setdefault('anonlabels', {}) # labelname -> docname, labelid
@property
def labels_source(self) -> dict[str, str]:
return self.data.setdefault(
'labels_source', {}
) # labelname -> source file path
def clear_doc(self, docname: str) -> None:
to_remove1 = [
key for key, (fn, _l) in self.progoptions.items() if fn == docname
]
for key1 in to_remove1:
del self.progoptions[key1]
to_remove2 = [key for key, (fn, _l) in self.objects.items() if fn == docname]
for key2 in to_remove2:
del self.objects[key2]
to_remove3 = [key for key, (fn, _l) in self._terms.items() if fn == docname]
for key3 in to_remove3:
del self._terms[key3]
to_remove3 = [key for key, (fn, _l, _l) in self.labels.items() if fn == docname]
for key3 in to_remove3:
del self.labels[key3]
self.labels_source.pop(key3, None)
to_remove3 = [key for key, (fn, _l) in self.anonlabels.items() if fn == docname]
for key3 in to_remove3:
del self.anonlabels[key3]
def merge_domaindata(self, docnames: Set[str], otherdata: dict[str, Any]) -> None:
# XXX duplicates?
for key, data in otherdata['progoptions'].items():
if data[0] in docnames:
self.progoptions[key] = data
for key, data in otherdata['objects'].items():
if data[0] in docnames:
self.objects[key] = data
for key, data in otherdata['terms'].items():
if data[0] in docnames:
self._terms[key] = data
for key, data in otherdata['labels'].items():
if data[0] in docnames:
self.labels[key] = data
for key, data in otherdata['anonlabels'].items():
if data[0] in docnames:
self.anonlabels[key] = data
for key, data in otherdata.get('labels_source', {}).items():
if key in self.labels:
self.labels_source[key] = data
def process_doc(
self, env: BuildEnvironment, docname: str, document: nodes.document
) -> None:
for name, explicit in document.nametypes.items():
if not explicit:
continue
labelid = document.nameids[name]
if labelid is None:
continue
node = document.ids[labelid]
if isinstance(node, nodes.target) and 'refid' in node:
# indirect hyperlink targets
node = document.ids[node['refid']]
labelid = node['names'][0]
if (
node.tagname == 'footnote'
or 'refuri' in node
or node.tagname.startswith('desc_')
):
# ignore footnote labels, labels automatically generated from a
# link and object descriptions
continue
if name in self.labels:
current_source = getattr(node, 'source', None)
existing_source = self.labels_source.get(name)
existing_docname = self.labels[name][0]
# Check if both labels come from the same source file
if current_source and existing_source:
current_norm = os.path.normcase(os.path.normpath(current_source))
existing_norm = os.path.normcase(os.path.normpath(existing_source))
same_source = current_norm == existing_norm
else:
same_source = False
if same_source:
# Same source file included in multiple documents.
# Prefer the including document for proper figure numbering.
if existing_docname not in env.included.get(docname, set()):
continue
else:
logger.warning(
__('duplicate label %s, other instance in %s'),
name,
env.doc2path(existing_docname),
location=node,
)
self.anonlabels[name] = docname, labelid
if node.tagname == 'section':
title = cast('nodes.title', node[0])
sectname = clean_astext(title)
elif node.tagname == 'rubric':