Repository navigation
Expand file tree
/
Copy pathbzl.py
More file actions
1736 lines (1427 loc) · 57.6 KB
/
Copy pathbzl.py
File metadata and controls
1736 lines (1427 loc) · 57.6 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
# Copyright 2024 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Sphinx extension for documenting Bazel/Starlark objects."""
import ast
import collections
import enum
import os
import typing
from collections.abc import Collection
from typing import Callable, Iterable, TypeVar
from docutils import nodes as docutils_nodes
from docutils.parsers.rst import directives as docutils_directives
from docutils.parsers.rst import states
from sphinx import addnodes, builders
from sphinx import directives as sphinx_directives
from sphinx import domains, environment, roles
from sphinx.highlighting import lexer_classes
from sphinx.locale import _
from sphinx.util import docfields
from sphinx.util import docutils as sphinx_docutils
from sphinx.util import inspect, logging
from sphinx.util import nodes as sphinx_nodes
from sphinx.util import typing as sphinx_typing
from typing_extensions import TypeAlias, override
_logger = logging.getLogger(__name__)
_LOG_PREFIX = f"[{_logger.name}] "
_INDEX_SUBTYPE_NORMAL = 0
_INDEX_SUBTYPE_ENTRY_WITH_SUB_ENTRIES = 1
_INDEX_SUBTYPE_SUB_ENTRY = 2
_T = TypeVar("_T")
# See https://www.sphinx-doc.org/en/master/extdev/domainapi.html#sphinx.domains.Domain.get_objects
_GetObjectsTuple: TypeAlias = tuple[str, str, str, str, str, int]
# See SphinxRole.run definition; the docs for role classes are pretty sparse.
_RoleRunResult: TypeAlias = tuple[
list[docutils_nodes.Node], list[docutils_nodes.system_message]
]
def _log_debug(message, *args):
# NOTE: Non-warning log messages go to stdout and are only
# visible when -q isn't passed to Sphinx. Note that the sphinx_docs build
# rule passes -q by default; use --//sphinxdocs:quiet=false to disable it.
_logger.debug("%s" + message, _LOG_PREFIX, *args)
def _position_iter(values: Collection[_T]) -> tuple[bool, bool, _T]:
last_i = len(values) - 1
for i, value in enumerate(values):
yield i == 0, i == last_i, value
class InvalidValueError(Exception):
"""Generic error for an invalid value instead of ValueError.
Sphinx treats regular ValueError to mean abort parsing the current
chunk and continue on as best it can. Their error means a more
fundamental problem that should cause a failure.
"""
class _ObjectEntry:
"""Metadata about a known object."""
def __init__(
self,
full_id: str,
display_name: str,
object_type: str,
search_priority: int,
index_entry: domains.IndexEntry,
):
"""Creates an instance.
Args:
full_id: The fully qualified id of the object. Should be
globally unique, even between projects.
display_name: What to display the object as in casual context.
object_type: The type of object, typically one of the values
known to the domain.
search_priority: The search priority, see
https://www.sphinx-doc.org/en/master/extdev/domainapi.html#sphinx.domains.Domain.get_objects
for valid values.
index_entry: Metadata about the object for the domain index.
"""
self.full_id = full_id
self.display_name = display_name
self.object_type = object_type
self.search_priority = search_priority
self.index_entry = index_entry
def to_get_objects_tuple(self) -> _GetObjectsTuple:
# For the tuple definition
return (
self.full_id,
self.display_name,
self.object_type,
self.index_entry.docname,
self.index_entry.anchor,
self.search_priority,
)
def __repr__(self):
return f"ObjectEntry({self.full_id=}, {self.object_type=}, {self.display_name=}, {self.index_entry.docname=})"
# A simple helper just to document what the index tuple nodes are.
def _index_node_tuple(
entry_type: str,
entry_name: str,
target: str,
main: typing.Union[str, None] = None,
category_key: typing.Union[str, None] = None,
) -> tuple[str, str, str, typing.Union[str, None], typing.Union[str, None]]:
# For this tuple definition, see:
# https://www.sphinx-doc.org/en/master/extdev/nodes.html#sphinx.addnodes.index
# For the definition of entry_type, see:
# And https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-index
return (entry_type, entry_name, target, main, category_key)
class _BzlObjectId:
"""Identifies an object defined by a directive.
This object is returned by `handle_signature()` and passed onto
`add_target_and_index()`. It contains information to identify the object
that is being described so that it can be indexed and tracked by the
domain.
"""
def __init__(
self,
*,
repo: str,
label: str,
namespace: str = None,
symbol: str = None,
):
"""Creates an instance.
Args:
repo: repository name, including leading "@".
bzl_file: label of file containing the object, e.g. //foo:bar.bzl
namespace: dotted name of the namespace the symbol is within.
symbol: dotted name, relative to `namespace` of the symbol.
"""
if not repo:
raise InvalidValueError("repo cannot be empty")
if not repo.startswith("@"):
raise InvalidValueError("repo must start with @")
if not label:
raise InvalidValueError("label cannot be empty")
if not label.startswith("//"):
raise InvalidValueError("label must start with //")
if not label.endswith(".bzl") and (symbol or namespace):
raise InvalidValueError(
"Symbol and namespace can only be specified for .bzl labels"
)
self.repo = repo
self.label = label
self.package, self.target_name = self.label.split(":")
self.namespace = namespace
self.symbol = symbol # Relative to namespace
# doc-relative identifier for this object
self.doc_id = symbol or self.target_name
if not self.doc_id:
raise InvalidValueError("doc_id is empty")
self.full_id = _full_id_from_parts(repo, label, [namespace, symbol])
@classmethod
def from_env(
cls, env: environment.BuildEnvironment, *, symbol: str = None, label: str = None
) -> "_BzlObjectId":
label = label or env.ref_context["bzl:file"]
if symbol:
namespace = ".".join(env.ref_context["bzl:doc_id_stack"])
else:
namespace = None
return cls(
repo=env.ref_context["bzl:repo"],
label=label,
namespace=namespace,
symbol=symbol,
)
def __repr__(self):
return f"_BzlObjectId({self.full_id=})"
def _full_id_from_env(env, object_ids=None):
return _full_id_from_parts(
env.ref_context["bzl:repo"],
env.ref_context["bzl:file"],
env.ref_context["bzl:object_id_stack"] + (object_ids or []),
)
def _full_id_from_parts(repo, bzl_file, symbol_names=None):
parts = [repo, bzl_file]
symbol_names = symbol_names or []
symbol_names = list(filter(None, symbol_names)) # Filter out empty values
if symbol_names:
parts.append("%")
parts.append(".".join(symbol_names))
full_id = "".join(parts)
return full_id
def _parse_full_id(full_id):
repo, slashes, label = full_id.partition("//")
label = slashes + label
label, _, symbol = label.partition("%")
return (repo, label, symbol)
class _TypeExprParser(ast.NodeVisitor):
"""Parsers a string description of types to doc nodes."""
def __init__(self, make_xref: Callable[[str], docutils_nodes.Node]):
self.root_node = addnodes.desc_inline("bzl", classes=["type-expr"])
self.make_xref = make_xref
self._doc_node_stack = [self.root_node]
@classmethod
def xrefs_from_type_expr(
cls,
type_expr_str: str,
make_xref: Callable[[str], docutils_nodes.Node],
) -> docutils_nodes.Node:
module = ast.parse(type_expr_str)
visitor = cls(make_xref)
visitor.visit(module.body[0])
return visitor.root_node
def _append(self, node: docutils_nodes.Node):
self._doc_node_stack[-1] += node
def _append_and_push(self, node: docutils_nodes.Node):
self._append(node)
self._doc_node_stack.append(node)
def visit_Attribute(self, node: ast.Attribute):
current = node
parts = []
while current:
if isinstance(current, ast.Attribute):
parts.append(current.attr)
current = current.value
elif isinstance(current, ast.Name):
parts.append(current.id)
break
else:
raise InvalidValueError(f"Unexpected Attribute.value node: {current}")
dotted_name = ".".join(reversed(parts))
self._append(self.make_xref(dotted_name))
def visit_Constant(self, node: ast.Constant):
if node.value is None:
self._append(self.make_xref("None"))
elif isinstance(node.value, str):
self._append(self.make_xref(node.value))
else:
raise InvalidValueError(
f"Unexpected Constant node value: ({type(node.value)}) {node.value=}"
)
def visit_Name(self, node: ast.Name):
xref_node = self.make_xref(node.id)
self._append(xref_node)
def visit_BinOp(self, node: ast.BinOp):
self.visit(node.left)
self._append(addnodes.desc_sig_space())
if isinstance(node.op, ast.BitOr):
self._append(addnodes.desc_sig_punctuation("", "|"))
else:
raise InvalidValueError(f"Unexpected BinOp: {node}")
self._append(addnodes.desc_sig_space())
self.visit(node.right)
def visit_Expr(self, node: ast.Expr):
self.visit(node.value)
def visit_Subscript(self, node: ast.Subscript):
self.visit(node.value)
self._append_and_push(addnodes.desc_type_parameter_list())
self.visit(node.slice)
self._doc_node_stack.pop()
def visit_Tuple(self, node: ast.Tuple):
for element in node.elts:
self._append_and_push(addnodes.desc_type_parameter())
self.visit(element)
self._doc_node_stack.pop()
def visit_List(self, node: ast.List):
self._append_and_push(addnodes.desc_type_parameter_list())
for element in node.elts:
self._append_and_push(addnodes.desc_type_parameter())
self.visit(element)
self._doc_node_stack.pop()
@override
def generic_visit(self, node):
raise InvalidValueError(f"Unexpected ast node: {type(node)} {node}")
class _BzlXrefField(docfields.Field):
"""Abstract base class to create cross references for fields."""
@override
def make_xrefs(
self,
rolename: str,
domain: str,
target: str,
innernode: type[sphinx_typing.TextlikeNode] = addnodes.literal_emphasis,
contnode: typing.Union[docutils_nodes.Node, None] = None,
env: typing.Union[environment.BuildEnvironment, None] = None,
inliner: typing.Union[states.Inliner, None] = None,
location: typing.Union[docutils_nodes.Element, None] = None,
) -> list[docutils_nodes.Node]:
if rolename in ("arg", "attr"):
return self._make_xrefs_for_arg_attr(
rolename, domain, target, innernode, contnode, env, inliner, location
)
else:
return super().make_xrefs(
rolename, domain, target, innernode, contnode, env, inliner, location
)
def _make_xrefs_for_arg_attr(
self,
rolename: str,
domain: str,
arg_name: str,
innernode: type[sphinx_typing.TextlikeNode] = addnodes.literal_emphasis,
contnode: typing.Union[docutils_nodes.Node, None] = None,
env: typing.Union[environment.BuildEnvironment, None] = None,
inliner: typing.Union[states.Inliner, None] = None,
location: typing.Union[docutils_nodes.Element, None] = None,
) -> list[docutils_nodes.Node]:
bzl_file = env.ref_context["bzl:file"]
anchor_prefix = ".".join(env.ref_context["bzl:doc_id_stack"])
if not anchor_prefix:
raise InvalidValueError(
f"doc_id_stack empty when processing arg {arg_name}"
)
index_description = f"{arg_name} ({self.name} in {bzl_file}%{anchor_prefix})"
anchor_id = f"{anchor_prefix}.{arg_name}"
full_id = _full_id_from_env(env, [arg_name])
env.get_domain(domain).add_object(
_ObjectEntry(
full_id=full_id,
display_name=arg_name,
object_type=self.name,
search_priority=1,
index_entry=domains.IndexEntry(
name=arg_name,
subtype=_INDEX_SUBTYPE_NORMAL,
docname=env.docname,
anchor=anchor_id,
extra="",
qualifier="",
descr=index_description,
),
),
# This allows referencing an arg as e.g `funcname.argname`
alt_names=[anchor_id],
)
# Two changes to how arg xrefs are created:
# 2. Use the full id instead of base name. This makes it unambiguous
# as to what it's referencing.
pending_xref = super().make_xref(
# The full_id is used as the target so its unambiguious.
rolename,
domain,
f"{arg_name} <{full_id}>",
innernode,
contnode,
env,
inliner,
location,
)
wrapper = docutils_nodes.inline(ids=[anchor_id])
index_node = addnodes.index(
entries=[
_index_node_tuple(
"single", f"{self.name}; {index_description}", anchor_id
),
_index_node_tuple("single", index_description, anchor_id),
]
)
wrapper += index_node
wrapper += pending_xref
return [wrapper]
class _BzlDocField(_BzlXrefField, docfields.Field):
"""A non-repeated field with xref support."""
class _BzlGroupedField(_BzlXrefField, docfields.GroupedField):
"""A repeated fieled grouped as a list with xref support."""
class _BzlCsvField(_BzlXrefField):
"""Field with a CSV list of values."""
def __init__(self, *args, body_domain: str = "", **kwargs):
super().__init__(*args, **kwargs)
self._body_domain = body_domain
def make_field(
self,
types: dict[str, list[docutils_nodes.Node]],
domain: str,
item: tuple,
env: environment.BuildEnvironment = None,
inliner: typing.Union[states.Inliner, None] = None,
location: typing.Union[docutils_nodes.Element, None] = None,
) -> docutils_nodes.field:
field_text = item[1][0].astext()
parts = [p.strip() for p in field_text.split(",")]
field_body = docutils_nodes.field_body()
for _, is_last, part in _position_iter(parts):
node = self.make_xref(
self.bodyrolename,
self._body_domain or domain,
part,
env=env,
inliner=inliner,
location=location,
)
field_body += node
if not is_last:
field_body += docutils_nodes.Text(", ")
field_name = docutils_nodes.field_name("", self.label)
return docutils_nodes.field("", field_name, field_body)
class _BzlCurrentFile(sphinx_docutils.SphinxDirective):
"""Sets what bzl file following directives are defined in.
The directive's argument is an absolute Bazel label, e.g. `//foo:bar.bzl`
or `@repo//foo:bar.bzl`. The repository portion is optional; if specified,
it will override the `bzl_default_repository_name` configuration setting.
Example MyST usage
```
:::{bzl:currentfile} //my:file.bzl
:::
```
"""
has_content = False
required_arguments = 1
final_argument_whitespace = False
@override
def run(self) -> list[docutils_nodes.Node]:
label = self.arguments[0].strip()
repo, slashes, file_label = label.partition("//")
file_label = slashes + file_label
if not repo:
repo = self.env.config.bzl_default_repository_name
self.env.ref_context["bzl:repo"] = repo
self.env.ref_context["bzl:file"] = file_label
self.env.ref_context["bzl:object_id_stack"] = []
self.env.ref_context["bzl:doc_id_stack"] = []
return []
class _BzlAttrInfo(sphinx_docutils.SphinxDirective):
has_content = False
required_arguments = 1
optional_arguments = 0
option_spec = {
"executable": docutils_directives.flag,
"mandatory": docutils_directives.flag,
}
def run(self):
content_node = docutils_nodes.paragraph("", "")
content_node += docutils_nodes.paragraph(
"", "mandatory" if "mandatory" in self.options else "optional"
)
if "executable" in self.options:
content_node += docutils_nodes.paragraph("", "Must be an executable")
return [content_node]
class _BzlObject(sphinx_directives.ObjectDescription[_BzlObjectId]):
"""Base class for describing a Bazel/Starlark object.
This directive takes a single argument: a string name with optional
function signature.
* The name can be a dotted name, e.g. `a.b.foo`
* The signature is in Python signature syntax, e.g. `foo(a=x) -> R`
* The signature supports default values.
* Arg type annotations are not supported; use `{bzl:type}` instead as
part of arg/attr documentation.
Example signatures:
* `foo`
* `foo(arg1, arg2)`
* `foo(arg1, arg2=default) -> returntype`
"""
option_spec = sphinx_directives.ObjectDescription.option_spec | {
"origin-key": docutils_directives.unchanged,
}
@override
def before_content(self) -> None:
symbol_name = self.names[-1].symbol
if symbol_name:
self.env.ref_context["bzl:object_id_stack"].append(symbol_name)
self.env.ref_context["bzl:doc_id_stack"].append(symbol_name)
@override
def transform_content(self, content_node: addnodes.desc_content) -> None:
def first_child_with_class_name(
root, class_name
) -> typing.Union[None, docutils_nodes.Element]:
matches = root.findall(
lambda node: isinstance(node, docutils_nodes.Element)
and class_name in node["classes"]
)
found = next(matches, None)
return found
def match_arg_field_name(node):
# fmt: off
return (
isinstance(node, docutils_nodes.field_name)
and node.astext().startswith(("arg ", "attr "))
)
# fmt: on
# Move the spans for the arg type and default value to be first.
arg_name_fields = list(content_node.findall(match_arg_field_name))
for arg_name_field in arg_name_fields:
arg_body_field = arg_name_field.next_node(descend=False, siblings=True)
# arg_type_node = first_child_with_class_name(arg_body_field, "arg-type-span")
arg_type_node = first_child_with_class_name(arg_body_field, "type-expr")
arg_default_node = first_child_with_class_name(
arg_body_field, "default-value-span"
)
# Inserting into the body field itself causes the elements
# to be grouped into the paragraph node containing the arg
# name (as opposed to the paragraph node containing the
# doc text)
if arg_default_node:
arg_default_node.parent.remove(arg_default_node)
arg_body_field.insert(0, arg_default_node)
if arg_type_node:
arg_type_node.parent.remove(arg_type_node)
decorated_arg_type_node = docutils_nodes.inline(
"",
"",
docutils_nodes.Text("("),
arg_type_node,
docutils_nodes.Text(") "),
classes=["arg-type-span"],
)
# arg_body_field.insert(0, arg_type_node)
arg_body_field.insert(0, decorated_arg_type_node)
@override
def after_content(self) -> None:
if self.names[-1].symbol:
self.env.ref_context["bzl:object_id_stack"].pop()
self.env.ref_context["bzl:doc_id_stack"].pop()
# docs on how to build signatures:
# https://www.sphinx-doc.org/en/master/extdev/nodes.html#sphinx.addnodes.desc_signature
@override
def handle_signature(
self, sig_text: str, sig_node: addnodes.desc_signature
) -> _BzlObjectId:
self._signature_add_object_type(sig_node)
relative_name, lparen, params_text = sig_text.partition("(")
if lparen:
params_text = lparen + params_text
relative_name = relative_name.strip()
name_prefix, _, base_symbol_name = relative_name.rpartition(".")
if name_prefix:
# Respect whatever the signature wanted
display_prefix = name_prefix
else:
# Otherwise, show the outermost name. This makes ctrl+f finding
# for a symbol a bit easier.
display_prefix = ".".join(self.env.ref_context["bzl:doc_id_stack"])
_, _, display_prefix = display_prefix.rpartition(".")
if display_prefix:
display_prefix = display_prefix + "."
sig_node += addnodes.desc_addname(display_prefix, display_prefix)
sig_node += addnodes.desc_name(base_symbol_name, base_symbol_name)
if type_expr := self.options.get("type"):
def make_xref(name, title=None):
content_node = addnodes.desc_type(name, name)
return addnodes.pending_xref(
"",
content_node,
refdomain="bzl",
reftype="type",
reftarget=name,
)
attr_annotation_node = addnodes.desc_annotation(
type_expr,
"",
addnodes.desc_sig_punctuation("", ":"),
addnodes.desc_sig_space(),
_TypeExprParser.xrefs_from_type_expr(type_expr, make_xref),
)
sig_node += attr_annotation_node
if params_text:
try:
signature = inspect.signature_from_str(params_text)
except SyntaxError:
# Stardoc doesn't provide accurate info, so the reconstructed
# signature might not be valid syntax. Rather than fail, just
# provide a plain-text description of the approximate signature.
# See https://github.com/bazelbuild/stardoc/issues/225
sig_node += addnodes.desc_parameterlist(
# Offset by 1 to remove the surrounding parentheses
params_text[1:-1],
params_text[1:-1],
)
else:
last_kind = None
paramlist_node = addnodes.desc_parameterlist()
for param in signature.parameters.values():
if param.kind == param.KEYWORD_ONLY and last_kind in (
param.POSITIONAL_OR_KEYWORD,
param.POSITIONAL_ONLY,
None,
):
# Add separator for keyword only parameter: *
paramlist_node += addnodes.desc_parameter(
"", "", addnodes.desc_sig_operator("", "*")
)
last_kind = param.kind
node = addnodes.desc_parameter()
if param.kind == param.VAR_POSITIONAL:
node += addnodes.desc_sig_operator("", "*")
elif param.kind == param.VAR_KEYWORD:
node += addnodes.desc_sig_operator("", "**")
node += addnodes.desc_sig_name(rawsource="", text=param.name)
if param.default is not param.empty:
node += addnodes.desc_sig_operator("", "=")
node += docutils_nodes.inline(
"",
param.default,
classes=["default_value"],
support_smartquotes=False,
)
paramlist_node += node
sig_node += paramlist_node
if signature.return_annotation is not signature.empty:
sig_node += addnodes.desc_returns("", signature.return_annotation)
obj_id = _BzlObjectId.from_env(self.env, symbol=relative_name)
sig_node["bzl:object_id"] = obj_id.full_id
return obj_id
def _signature_add_object_type(self, sig_node: addnodes.desc_signature):
if sig_object_type := self._get_signature_object_type():
sig_node += addnodes.desc_annotation("", self._get_signature_object_type())
sig_node += addnodes.desc_sig_space()
@override
def add_target_and_index(
self, obj_desc: _BzlObjectId, sig: str, sig_node: addnodes.desc_signature
) -> None:
super().add_target_and_index(obj_desc, sig, sig_node)
if obj_desc.symbol:
display_name = obj_desc.symbol
location = obj_desc.label
if obj_desc.namespace:
location += f"%{obj_desc.namespace}"
else:
display_name = obj_desc.target_name
location = obj_desc.package
anchor_prefix = ".".join(self.env.ref_context["bzl:doc_id_stack"])
if anchor_prefix:
anchor_id = f"{anchor_prefix}.{obj_desc.doc_id}"
else:
anchor_id = obj_desc.doc_id
sig_node["ids"].append(anchor_id)
object_type_display = self._get_object_type_display_name()
index_description = f"{display_name} ({object_type_display} in {location})"
self.indexnode["entries"].extend(
_index_node_tuple("single", f"{index_type}; {index_description}", anchor_id)
for index_type in [object_type_display] + self._get_additional_index_types()
)
self.indexnode["entries"].append(
_index_node_tuple("single", index_description, anchor_id),
)
object_entry = _ObjectEntry(
full_id=obj_desc.full_id,
display_name=display_name,
object_type=self.objtype,
search_priority=1,
index_entry=domains.IndexEntry(
name=display_name,
subtype=_INDEX_SUBTYPE_NORMAL,
docname=self.env.docname,
anchor=anchor_id,
extra="",
qualifier="",
descr=index_description,
),
)
alt_names = []
if origin_key := self.options.get("origin-key"):
alt_names.append(
origin_key
# Options require \@ for leading @, but don't
# remove the escaping slash, so we have to do it manually
.lstrip("\\")
)
extra_alt_names = self._get_alt_names(object_entry)
alt_names.extend(extra_alt_names)
self.env.get_domain(self.domain).add_object(object_entry, alt_names=alt_names)
def _get_additional_index_types(self):
return []
@override
def _object_hierarchy_parts(
self, sig_node: addnodes.desc_signature
) -> tuple[str, ...]:
return _parse_full_id(sig_node["bzl:object_id"])
@override
def _toc_entry_name(self, sig_node: addnodes.desc_signature) -> str:
return sig_node["_toc_parts"][-1]
def _get_object_type_display_name(self) -> str:
return self.env.get_domain(self.domain).object_types[self.objtype].lname
def _get_signature_object_type(self) -> str:
return self._get_object_type_display_name()
def _get_alt_names(self, object_entry):
alt_names = []
full_id = object_entry.full_id
label, _, symbol = full_id.partition("%")
if symbol:
# Allow referring to the file-relative fully qualified symbol name
alt_names.append(symbol)
if "." in symbol:
# Allow referring to the last component of the symbol
alt_names.append(symbol.split(".")[-1])
else:
# Otherwise, it's a target. Allow referring to just the target name
_, _, target_name = label.partition(":")
alt_names.append(target_name)
return alt_names
class _BzlCallable(_BzlObject):
"""Abstract base class for objects that are callable."""
class _BzlTypedef(_BzlObject):
"""Documents a typedef.
A typedef describes objects with well known attributes.
`````
::::{bzl:typedef} Square
:::{bzl:field} width
:type: int
:::
:::{bzl:function} new(size)
:::
:::{bzl:function} area()
:::
::::
`````
"""
class _BzlProvider(_BzlObject):
"""Documents a provider type.
Example MyST usage
```
::::{bzl:provider} MyInfo
Docs about MyInfo
:::{bzl:provider-field} some_field
:type: depset[str]
:::
::::
```
"""
class _BzlField(_BzlObject):
"""Documents a field of a provider.
Fields can optionally have a type specified using the `:type:` option.
The type can be any type expression understood by the `{bzl:type}` role.
```
:::{bzl:provider-field} foo
:type: str
:::
```
"""
option_spec = _BzlObject.option_spec.copy()
option_spec.update(
{
"type": docutils_directives.unchanged,
}
)
@override
def _get_signature_object_type(self) -> str:
return ""
@override
def _get_alt_names(self, object_entry):
alt_names = super()._get_alt_names(object_entry)
_, _, symbol = object_entry.full_id.partition("%")
# Allow refering to `mod_ext_name.tag_name`, even if the extension
# is nested within another object
alt_names.append(".".join(symbol.split(".")[-2:]))
return alt_names
class _BzlProviderField(_BzlField):
pass
class _BzlRepositoryRule(_BzlCallable):
"""Documents a repository rule.
Doc fields:
* attr: Documents attributes of the rule. Takes a single arg, the
attribute name. Can be repeated. The special roles `{default-value}`
and `{arg-type}` can be used to indicate the default value and
type of attribute, respectively.
* environment-variables: a CSV list of environment variable names.
They will be cross referenced with matching environment variables.
Example MyST usage
```
:::{bzl:repo-rule} myrule(foo)
:attr foo: {default-value}`"foo"` {arg-type}`attr.string` foo doc string
:environment-variables: FOO, BAR
:::
```
"""
doc_field_types = [
_BzlGroupedField(
"attr",
label=_("Attributes"),
names=["attr"],
rolename="attr",
can_collapse=False,
),
_BzlCsvField(
"environment-variables",
label=_("Environment Variables"),
names=["environment-variables"],
body_domain="std",
bodyrolename="envvar",
has_arg=False,
),
]
@override
def _get_signature_object_type(self) -> str:
return "repo rule"
class _BzlRule(_BzlCallable):
"""Documents a rule.
Doc fields:
* attr: Documents attributes of the rule. Takes a single arg, the
attribute name. Can be repeated. The special roles `{default-value}`
and `{arg-type}` can be used to indicate the default value and
type of attribute, respectively.
* provides: A type expression of the provider types the rule provides.
To indicate different groupings, use `|` and `[]`. For example,
`FooInfo | [BarInfo, BazInfo]` means it provides either `FooInfo`
or both of `BarInfo` and `BazInfo`.
Example MyST usage
```
:::{bzl:repo-rule} myrule(foo)
:attr foo: {default-value}`"foo"` {arg-type}`attr.string` foo doc string
:provides: FooInfo | BarInfo
:::
```
"""
doc_field_types = [
_BzlGroupedField(
"attr",
label=_("Attributes"),
names=["attr"],
rolename="attr",
can_collapse=False,
),
_BzlDocField(
"provides",
label="Provides",
has_arg=False,
names=["provides"],
bodyrolename="type",
),
]
class _BzlAspect(_BzlObject):
"""Documents an aspect.
Doc fields:
* attr: Documents attributes of the aspect. Takes a single arg, the
attribute name. Can be repeated. The special roles `{default-value}`
and `{arg-type}` can be used to indicate the default value and
type of attribute, respectively.
* aspect-attributes: A CSV list of attribute names the aspect
propagates along.