Debian Codegraph @

doc/arm/_ext/iscconf.py

raw
1 ############################################################################
2 # Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3 #
4 # SPDX-License-Identifier: MPL-2.0
5 #
6 # This Source Code Form is subject to the terms of the Mozilla Public
7 # License, v. 2.0. If a copy of the MPL was not distributed with this
8 # file, you can obtain one at https://mozilla.org/MPL/2.0/.
9 #
10 # See the COPYRIGHT file distributed with this work for additional
11 # information regarding copyright ownership.
12 ############################################################################
13
14 """
15 Sphinx domains for ISC configuration files.
16
17 Use setup() to install new Sphinx domains for ISC configuration files.
18
19 This extension is based on combination of two Sphinx extension tutorials:
20 https://www.sphinx-doc.org/en/master/development/tutorials/todo.html
21 https://www.sphinx-doc.org/en/master/development/tutorials/recipe.html
22 """
23
24 from collections import namedtuple
25
26 from docutils import nodes
27 from docutils.parsers.rst import Directive, directives
28 from sphinx import addnodes
29 from sphinx.directives import ObjectDescription
30 from sphinx.domains import Domain
31 from sphinx.roles import XRefRole
32 from sphinx.util import logging
33 from sphinx.util.nodes import make_refnode
34
35 import checkgrammar
36
37 logger = logging.getLogger(__name__)
38
39
40 def split_csv(argument, required):
41 argument = argument or ""
42 outlist = list(filter(len, (s.strip() for s in argument.split(","))))
43 if required and not outlist:
44 raise ValueError(
45 "a non-empty list required; provide at least one value or remove"
46 " this option"
47 )
48 if not len(outlist) == len(set(outlist)):
49 raise ValueError("duplicate value detected")
50 return outlist
51
52
53 def domain_factory(domainname, domainlabel, todolist, grammar):
54 """
55 Return parametrized Sphinx domain object.
56 @param domainname Name used when referencing domain in .rst: e.g. namedconf
57 @param confname Humand-readable name for texts, e.g. named.conf
58 @param todolist A placeholder object which must be pickable.
59 See StatementListDirective.
60 """
61
62 class StatementListDirective(Directive):
63 """A custom directive to generate list of statements.
64 It only installs placeholder which is later replaced by
65 process_statementlist_nodes() callback.
66 """
67
68 option_spec = {
69 "filter_blocks": lambda arg: split_csv(arg, required=True),
70 "filter_tags": lambda arg: split_csv(arg, required=True),
71 }
72
73 def run(self):
74 placeholder = todolist("")
75 placeholder["isc_filter_tags"] = self.options.get("filter_tags", [])
76 placeholder["isc_filter_blocks"] = self.options.get("filter_blocks", [])
77 return [placeholder]
78
79 class ISCConfDomain(Domain):
80 """
81 Custom Sphinx domain for ISC config.
82 Provides .. statement:: directive to define config statement and
83 .. statementlist:: to generate summary tables.
84 :ref:`statementname` works as usual.
85
86 See https://www.sphinx-doc.org/en/master/extdev/domainapi.html
87 """
88
89 class StatementDirective(ObjectDescription):
90 """
91 A custom directive that describes a statement,
92 e.g. max-cache-size.
93 """
94
95 has_content = True
96 required_arguments = 1
97 option_spec = {
98 "tags": lambda arg: split_csv(arg, required=False),
99 # one-sentece description for use in summary tables
100 "short": directives.unchanged_required,
101 "suppress_grammar": directives.flag,
102 }
103
104 @property
105 def isc_name(self):
106 names = self.get_signatures()
107 if len(names) != 1:
108 raise NotImplementedError(
109 "statements with more than one name are not supported", names
110 )
111 return names[0]
112
113 def handle_signature(self, sig, signode):
114 signode += addnodes.desc_name(text=sig)
115 return sig
116
117 def add_target_and_index(self, _name_cls, sig, signode):
118 signode["ids"].append(domainname + "-statement-" + sig)
119
120 iscconf = self.env.get_domain(domainname)
121 iscconf.add_statement(
122 sig, self.isc_tags, self.isc_short, self.isc_short_node, self.lineno
123 )
124
125 @property
126 def isc_tags(self):
127 return self.options.get("tags", [])
128
129 @property
130 def isc_short(self):
131 return self.options.get("short", "")
132
133 @property
134 def isc_short_node(self):
135 """Short description parsed from rst to docutils node"""
136 return self.parse_nested_str(self.isc_short)
137
138 def format_path(self, path):
139 assert path[0] == "_top"
140 if len(path) == 1:
141 return "topmost"
142 return ".".join(path[1:])
143
144 def format_paths(self, paths):
145 zone_types = set()
146 nozone_paths = []
147 for path in paths:
148 try:
149 zone_idx = path.index("zone")
150 zone_type_txt = path[zone_idx + 1]
151 if zone_type_txt.startswith("type "):
152 zone_types.add(zone_type_txt[len("type ") :])
153 else:
154 assert zone_type_txt == "in-view"
155 zone_types.add(zone_type_txt)
156 except (ValueError, IndexError):
157 nozone_paths.append(path)
158 condensed_paths = nozone_paths[:]
159 if zone_types:
160 condensed_paths.append(
161 ("_top", "zone (" + ", ".join(sorted(zone_types)) + ")")
162 )
163 condensed_paths = sorted(condensed_paths, key=len)
164 return list(self.format_path(path) for path in condensed_paths)
165
166 def format_blocks(self, grammar_blocks):
167 """Generate node with list of all allowed blocks"""
168 blocks = nodes.paragraph()
169 blocks += nodes.strong(text="Blocks: ")
170 blocks += nodes.Text(", ".join(self.format_paths(grammar_blocks)))
171 return blocks
172
173 def format_grammar(self, list_blocks, grammar_grp):
174 """
175 Generate grammar description node, optionally with list of
176 blocks accepting this particular grammar.
177 Example: Grammar (block1, block2): grammar;
178 """
179 grammarnode = nodes.paragraph()
180 if list_blocks:
181 separator = " "
182 paths = ", ".join(
183 self.format_paths(variant.path for variant in grammar_grp)
184 )
185 else:
186 separator = ""
187 paths = ""
188 subgrammar = grammar_grp[0].subgrammar
189 subgrammar_txt = checkgrammar.pformat_grammar(subgrammar).strip()
190 grammar_txt = subgrammar.get("_pprint_name", self.isc_name)
191 if subgrammar_txt != ";":
192 grammar_txt += " "
193 grammar_txt += subgrammar_txt
194 if "\n" in grammar_txt.strip():
195 nodetype = nodes.literal_block
196 else:
197 nodetype = nodes.literal
198 grammarnode += nodes.strong(text=f"Grammar{separator}{paths}: ")
199 grammarnode += nodetype(text=grammar_txt)
200 return grammarnode
201
202 def format_warnings(self, flags):
203 """Return node with a warning box about deprecated and
204 experimental options"""
205 warn = nodes.warning()
206 if "deprecated" in flags:
207 warn += nodes.paragraph(
208 text=(
209 "This option is deprecated and will be removed in a future"
210 " version of BIND."
211 )
212 )
213 if "experimental" in flags:
214 warn += nodes.paragraph(
215 text="This option is experimental and subject to change."
216 )
217 return warn
218
219 def parse_nested_str(self, instr):
220 """Parse string as nested rst syntax and produce a node"""
221 raw = nodes.paragraph(text=instr)
222 parsed = nodes.paragraph()
223 self.state.nested_parse(raw, self.content_offset, parsed)
224 return parsed
225
226 def transform_content(self, content_node: addnodes.desc_content) -> None:
227 """autogenerate content from structured data"""
228 self.workaround_transform_content = True
229 if self.isc_short:
230 content_node.insert(0, self.isc_short_node)
231 if self.isc_tags:
232 tags = nodes.paragraph()
233 tags += nodes.strong(text="Tags: ")
234 tags += nodes.Text(", ".join(self.isc_tags))
235 content_node.insert(0, tags)
236
237 iscconf = self.env.get_domain(domainname)
238
239 name = self.isc_name
240 if name not in iscconf.statement_blocks:
241 return # not defined in grammar, nothing to render
242
243 blocks = self.format_blocks(iscconf.statement_blocks[name])
244 content_node.insert(0, blocks)
245
246 grammars = iscconf.statement_grammar_groups[name]
247 multi_grammar = len(grammars) > 1
248 union_flags = set()
249 for grammar_grp in grammars:
250 for one_grammar_dict in grammar_grp:
251 union_flags = union_flags.union(
252 set(one_grammar_dict.subgrammar.get("_flags", []))
253 )
254 if "suppress_grammar" in self.options:
255 continue
256 grammarnode = self.format_grammar(multi_grammar, grammar_grp)
257 content_node.insert(0, grammarnode)
258
259 warn = self.format_warnings(union_flags)
260 if len(warn):
261 content_node.insert(0, warn)
262
263 def __init__(self, *args, **kwargs):
264 """Compability with Sphinx < 3.0.0"""
265 self.workaround_transform_content = False
266 super().__init__(*args, **kwargs)
267
268 def run(self):
269 """Compability with Sphinx < 3.0.0"""
270 nodelist = super().run()
271 if not self.workaround_transform_content:
272 # get access to "contentnode" created inside super.run()
273 self.transform_content(nodelist[1][-1])
274 return nodelist
275
276 name = domainname
277 label = domainlabel
278
279 directives = {
280 "statement": StatementDirective,
281 "statementlist": StatementListDirective,
282 }
283
284 roles = {"ref": XRefRole(warn_dangling=True)}
285 initial_data = {
286 # name -> {"tags": [list of tags], ...}; see add_statement()
287 "statements": {},
288 }
289
290 indices = {} # no custom indicies
291
292 def __init__(self, *args, **kwargs):
293 super().__init__(*args, **kwargs)
294 self.grammar = grammar
295 self.statement_blocks = checkgrammar.statement2block(grammar, ["_top"])
296 self.statement_grammar_groups = checkgrammar.diff_statements(
297 self.grammar, self.statement_blocks
298 )
299
300 def get_objects(self):
301 """
302 Sphinx API:
303 Iterable of Sphinx object descriptions (tuples defined in the API).
304 """
305 for obj in self.data["statements"].values():
306 yield tuple(
307 obj[key]
308 for key in [
309 "fullname",
310 "signature",
311 "label",
312 "docname",
313 "anchor",
314 "priority",
315 ]
316 )
317
318 def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
319 """
320 Sphinx API:
321 Resolve the pending_xref *node* with the given typ and target.
322 """
323 try:
324 obj = self.data["statements"][self.get_statement_name(target)]
325 except KeyError:
326 return None
327
328 refnode = make_refnode(
329 builder,
330 fromdocname,
331 obj["docname"],
332 obj["anchor"],
333 contnode,
334 obj["anchor"],
335 )
336 return refnode
337
338 def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode):
339 """
340 Sphinx API:
341 Raising NotImplementedError uses fall-back bassed on resolve_xref.
342 """
343 raise NotImplementedError
344
345 @staticmethod
346 def log_statement_overlap(new, old):
347 assert new["fullname"] == old["fullname"]
348 logger.warning(
349 "duplicite detected! %s previously defined at %s:%d",
350 new["fullname"],
351 old["filename"],
352 old["lineno"],
353 location=(new["docname"], new["lineno"]),
354 )
355
356 def get_statement_name(self, signature):
357 return f"{domainname}.statement.{signature}"
358
359 def add_statement(self, signature, tags, short, short_node, lineno):
360 """
361 Add a new statement to the domain data structures.
362 No visible effect.
363 """
364 name = self.get_statement_name(signature)
365 anchor = f"{domainname}-statement-{signature}"
366
367 new = {
368 "tags": tags,
369 "short": short,
370 "short_node": short_node,
371 "filename": self.env.doc2path(self.env.docname),
372 "lineno": lineno,
373 # Sphinx API
374 "fullname": name, # internal name
375 "signature": signature, # display name
376 "label": domainlabel + " statement", # description for index
377 "docname": self.env.docname,
378 "anchor": anchor,
379 "priority": 1, # search priority
380 }
381
382 if name in self.data["statements"]:
383 self.log_statement_overlap(new, self.data["statements"][name])
384 self.data["statements"][name] = new
385
386 def clear_doc(self, docname):
387 """
388 Sphinx API: like env-purge-doc event, but in a domain.
389
390 Remove traces of a document in the domain-specific inventories.
391 """
392 self.data["statements"] = dict(
393 {
394 key: obj
395 for key, obj in self.data["statements"].items()
396 if obj["docname"] != docname
397 }
398 )
399
400 def merge_domaindata(self, docnames, otherdata):
401 """Sphinx API: Merge in data regarding *docnames* from a different
402 domaindata inventory (coming from a subprocess in parallel builds).
403
404 @param otherdata is self.data equivalent from another process
405 """
406 old = self.data["statements"]
407 new = otherdata["statements"]
408 for name in set(old).intersection(set(new)):
409 self.log_statement_overlap(new[name], old[name])
410 old.update(new)
411
412 def check_consistency(self):
413 """Sphinx API"""
414 defined_statements = set(
415 obj["signature"] for obj in self.data["statements"].values()
416 )
417 statements_in_grammar = set(self.statement_blocks)
418 missing_statement_sigs = statements_in_grammar.difference(
419 defined_statements
420 )
421 for missing in missing_statement_sigs:
422 grammars = self.statement_grammar_groups[missing]
423 if len(grammars) == 1:
424 flags = grammars[0][0].subgrammar.get("_flags", [])
425 if ("obsolete" in flags) or ("test only" in flags):
426 continue
427
428 logger.warning(
429 "statement %s is defined in %s grammar but is not described"
430 " using .. statement:: directive",
431 missing,
432 domainlabel,
433 )
434
435 extra_statement_sigs = defined_statements.difference(statements_in_grammar)
436 for extra in extra_statement_sigs:
437 fullname = self.get_statement_name(extra)
438 desc = self.data["statements"][fullname]
439 logger.warning(
440 ".. statement:: %s found but matching definition in %s grammar is"
441 " missing",
442 extra,
443 domainlabel,
444 location=(desc["docname"], desc["lineno"]),
445 )
446
447 @classmethod
448 def process_statementlist_nodes(cls, app, doctree):
449 """
450 Replace todolist objects (placed into document using
451 .. statementlist::) with automatically generated table
452 of statements.
453 """
454
455 def gen_replacement_table(acceptable_blocks, acceptable_tags):
456 table_header = [
457 TableColumn("ref", "Statement"),
458 TableColumn("short_node", "Description"),
459 ]
460 tag_header = []
461 if len(acceptable_tags) != 1:
462 # tags column only if tag filter is not applied
463 tag_header = [
464 TableColumn("tags_txt", "Tags"),
465 ]
466
467 table_b = DictToDocutilsTableBuilder(table_header + tag_header)
468 table_b.append_iterable(
469 sorted(
470 filter(
471 lambda item: (
472 (
473 not acceptable_tags
474 or set(item["tags"]).intersection(acceptable_tags)
475 )
476 and (
477 not acceptable_blocks
478 or set(item["block_names"]).intersection(
479 acceptable_blocks
480 )
481 )
482 ),
483 iscconf.list_all(),
484 ),
485 key=lambda x: x["fullname"],
486 )
487 )
488 return table_b.get_docutils()
489
490 env = app.builder.env
491 iscconf = env.get_domain(cls.name)
492
493 for node in doctree.traverse(todolist):
494 acceptable_tags = node["isc_filter_tags"]
495 acceptable_blocks = node["isc_filter_blocks"]
496 node.replace_self(
497 gen_replacement_table(acceptable_blocks, acceptable_tags)
498 )
499
500 def list_all(self):
501 for statement in self.data["statements"].values():
502 sig = statement["signature"]
503 block_names = set(
504 path[-1] for path in self.statement_blocks.get(sig, [])
505 )
506 tags_txt = ", ".join(statement["tags"])
507
508 refpara = nodes.inline()
509 refnode = addnodes.pending_xref(
510 sig,
511 reftype="statement",
512 refdomain=domainname,
513 reftarget=sig,
514 refwarn=True,
515 )
516 refnode += nodes.Text(sig)
517 refpara += refnode
518
519 copy = statement.copy()
520 copy["block_names"] = block_names
521 copy["ref"] = refpara
522 copy["tags_txt"] = tags_txt
523 yield copy
524
525 return ISCConfDomain
526
527
528 # source dict key: human description
529 TableColumn = namedtuple("TableColumn", ["dictkey", "description"])
530
531
532 class DictToDocutilsTableBuilder:
533 """generate docutils table"""
534
535 def __init__(self, header):
536 """@param header: [ordered list of TableColumn]s"""
537 self.header = header
538 self.table = nodes.table()
539 self.table["classes"] += ["colwidths-auto"]
540 self.returned = False
541 # inner nodes of the table
542 self.tgroup = nodes.tgroup(cols=len(self.header))
543 for _ in range(len(self.header)):
544 # ignored because of colwidths-auto, but must be present
545 colspec = nodes.colspec(colwidth=1)
546 self.tgroup.append(colspec)
547 self.table += self.tgroup
548 self._gen_header()
549
550 self.tbody = nodes.tbody()
551 self.tgroup += self.tbody
552
553 def _gen_header(self):
554 thead = nodes.thead()
555
556 row = nodes.row()
557 for column in self.header:
558 entry = nodes.entry()
559 entry += nodes.paragraph(text=column.description)
560 row += entry
561
562 thead.append(row)
563 self.tgroup += thead
564
565 def append_iterable(self, objects):
566 """Append rows for each object (dict), ir order.
567 Extract column values from keys listed in self.header."""
568 for obj in objects:
569 row = nodes.row()
570 for column in self.header:
571 entry = nodes.entry()
572 value = obj[column.dictkey]
573 if isinstance(value, str):
574 value = nodes.paragraph(text=value)
575 else:
576 value = value.deepcopy()
577 entry += value
578 row += entry
579 self.tbody.append(row)
580
581 def get_docutils(self):
582 # guard against table reuse - that's most likely an error
583 assert not self.returned
584 self.returned = True
585 return self.table
586
587
588 def setup(app, domainname, confname, docutilsplaceholder, grammar):
589 """
590 Install new parametrized Sphinx domain.
591 """
592
593 Conf = domain_factory(domainname, confname, docutilsplaceholder, grammar)
594 app.add_domain(Conf)
595 app.connect("doctree-read", Conf.process_statementlist_nodes)
596
597 return {
598 "version": "0.1",
599 "parallel_read_safe": True,
600 "parallel_write_safe": True,
601 }