Debian Codegraph @

doc/misc/checkgrammar.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 Utility to check ISC config grammar consistency. It detects statement names
16 which use different grammar depending on position in the configuration file.
17 E.g. "max-zone-ttl" in dnssec-policy uses '<duration>'
18 vs. '( unlimited | <duration> ) used in options.
19 """
20
21 from collections import namedtuple
22 from itertools import groupby
23
24 import fileinput
25
26 import parsegrammar
27
28
29 def statement2block(grammar, path):
30 """Return mapping statement name to "path" where it is allowed.
31 _top is placeholder name for the namesless topmost context.
32
33 E.g. {
34 'options: [('_top',)],
35 'server': [('_top', 'view'), ('_top',)],
36 'rate-limit': [('_top', 'options'), ('_top', 'view')],
37 'slip': [('_top', 'options', 'rate-limit'), ('_top', 'view', 'rate-limit')]
38 }
39 """
40 key2place = {}
41
42 for key in grammar:
43 assert not key.startswith("_")
44 key2place.setdefault(key, []).append(tuple(path))
45 if "_mapbody" in grammar[key]:
46 nested2block = statement2block(grammar[key]["_mapbody"], path + [key])
47 # merge to uppermost output dictionary
48 for nested_key, nested_path in nested2block.items():
49 key2place.setdefault(nested_key, []).extend(nested_path)
50 return key2place
51
52
53 def get_statement_grammar(grammar, path, name):
54 """Descend into grammar dict using provided path
55 and return final dict found there.
56
57 Intermediate steps into "_mapbody" subkeys are done automatically.
58 """
59 assert path[0] == "_top"
60 path = list(path) + [name]
61 for step in path[1:]:
62 if "_mapbody" in grammar:
63 grammar = grammar["_mapbody"]
64 grammar = grammar[step]
65 return grammar
66
67
68 Statement = namedtuple("Statement", ["path", "name", "subgrammar"])
69
70
71 def groupby_grammar(statements):
72 """
73 Return groups of Statement tuples with identical grammars and flags.
74 See itertools.groupby.
75 """
76
77 def keyfunc(statement):
78 return sorted(statement.subgrammar.items())
79
80 groups = []
81 statements = sorted(statements, key=keyfunc)
82 for _key, group in groupby(statements, keyfunc):
83 groups.append(list(group)) # Store group iterator as a list
84 return groups
85
86
87 def diff_statements(whole_grammar, places):
88 """
89 Return map {statement name: [groups of [Statement]s with identical grammar].
90 """
91 out = {}
92 for statement_name, paths in places.items():
93 grammars = []
94 for path in paths:
95 statement_grammar = get_statement_grammar(
96 whole_grammar, path, statement_name
97 )
98 grammars.append(Statement(path, statement_name, statement_grammar))
99 groups = groupby_grammar(grammars)
100 out[statement_name] = groups
101 return out
102
103
104 def pformat_grammar(node, level=1):
105 """Pretty print a given grammar node in the same way as cfg_test would"""
106
107 def sortkey(item):
108 """Treat 'type' specially and always put it first, for zone types"""
109 key, _ = item
110 if key == "type":
111 return ""
112 return key
113
114 if "_grammar" in node: # no nesting
115 assert "_id" not in node
116 assert "_mapbody" not in node
117 out = node["_grammar"] + ";"
118 if "_flags" in node:
119 out += " // " + ", ".join(node["_flags"])
120 return out + "\n"
121
122 # a nested map
123 out = ""
124 indent = level * "\t"
125 if not node.get("_ignore_this_level"):
126 if "_id" in node:
127 out += node["_id"] + " "
128 out += "{\n"
129
130 for key, subnode in sorted(node["_mapbody"].items(), key=sortkey):
131 if not subnode.get("_ignore_this_level"):
132 out += f"{indent}{subnode.get('_pprint_name', key)}"
133 inner_grammar = pformat_grammar(node["_mapbody"][key], level=level + 1)
134 else: # act as if we were not in a map
135 inner_grammar = pformat_grammar(node["_mapbody"][key], level=level)
136 if inner_grammar[0] != ";": # we _did_ find some arguments
137 out += " "
138 out += inner_grammar
139
140 if not node.get("_ignore_this_level"):
141 out += indent[:-1] + "};" # unindent the closing bracket
142 if "_flags" in node:
143 out += " // " + ", ".join(node["_flags"])
144 return out + "\n"
145
146
147 def main():
148 """
149 Ingest output from cfg_test --grammar and print out statements which use
150 different grammar in different contexts.
151 """
152 with fileinput.input() as filein:
153 grammar = parsegrammar.parse_mapbody(filein)
154 places = statement2block(grammar, ["_top"])
155
156 for statementname, groups in diff_statements(grammar, places).items():
157 if len(groups) > 1:
158 print(f'statement "{statementname}" is inconsistent across blocks')
159 for group in groups:
160 print(
161 "- path:", ", ".join(" -> ".join(variant.path) for variant in group)
162 )
163 print(" ", pformat_grammar(group[0].subgrammar, level=1))
164 print()
165
166
167 if __name__ == "__main__":
168 main()