Debian Codegraph @

doc/misc/parsegrammar.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 Read ISC config grammar description produced by "cfg_test --grammar",
16 transform it into JSON, and print it to stdout.
17
18 Beware: This parser is pretty dumb and heavily depends on cfg_test output
19 format. See parse_mapbody() for more details.
20
21 Maps are recursively parsed into sub-dicts, all other elements (lists etc.)
22 are left intact and returned as one string.
23
24 Output example from named.conf grammar showing three variants follow.
25 Keys "_flags" and "_id" are present only if non-empty. Key "_grammar" denotes
26 end node, key "_mapbody" denotes a nested map.
27
28 {
29 "acl": {
30 "_flags": [
31 "may occur multiple times"
32 ],
33 "_grammar": "<string> { <address_match_element>; ... }"
34 },
35 "http": {
36 "_flags": [
37 "may occur multiple times"
38 ],
39 "_id": "<string>",
40 "_mapbody": {
41 "endpoints": {
42 "_grammar": "{ <quoted_string>; ... }"
43 },
44 "streams-per-connection": {
45 "_grammar": "<integer>"
46 }
47 }
48 },
49 "options": {
50 "_mapbody": {
51 "rate-limit": {
52 "_mapbody": {
53 "all-per-second": {
54 "_grammar": "<integer>"
55 }
56 }
57 }
58 }
59 }
60 }
61 """
62
63 import fileinput
64 import json
65 import re
66
67 FLAGS = [
68 "may occur multiple times",
69 "obsolete",
70 "deprecated",
71 "experimental",
72 "test only",
73 ]
74
75 KEY_REGEX = re.compile("[a-zA-Z0-9-]+")
76
77
78 def split_comments(line):
79 """Split line on comment boundary and strip right-side whitespace.
80 Supports only #, //, and /* comments which end at the end of line.
81 It does NOT handle:
82 - quoted strings
83 - /* comments which do not end at line boundary
84 - multiple /* comments on a single line
85 """
86 assert '"' not in line, 'lines with " are not supported'
87 data_end_idx = len(line)
88 for delimiter in ["#", "//", "/*"]:
89 try:
90 data_end_idx = min(line.index(delimiter), data_end_idx)
91 except ValueError:
92 continue
93 if delimiter == "/*":
94 # sanity checks
95 if not line.rstrip().endswith("*/"):
96 raise NotImplementedError(
97 "unsupported /* comment, does not end at the end of line", line
98 )
99 if "/*" in line[data_end_idx + 1 :]:
100 raise NotImplementedError(
101 "unsupported line with multiple /* comments", line
102 )
103
104 noncomment = line[:data_end_idx]
105 comment = line[data_end_idx:]
106 return noncomment, comment
107
108
109 def parse_line(filein):
110 """Consume single line from input, return non-comment and comment."""
111 for line in filein:
112 line, comment = split_comments(line)
113 line = line.strip()
114 comment = comment.strip()
115 if not line:
116 continue
117 yield line, comment
118
119
120 def parse_flags(comments):
121 """Extract known flags from comments. Must match exact strings used by cfg_test."""
122 out = []
123 for flag in FLAGS:
124 if flag in comments:
125 out.append(flag)
126 return out
127
128
129 def parse_mapbody(filein):
130 """Parse body of a "map" in ISC config format.
131
132 Input lines can be only:
133 - whitespace & comments only -> ignore
134 - <keyword> <anything>; -> store <anything> as "_grammar" for this keyword
135 - <keyword> <anything> { -> parse sub-map and store (optional) <anything> as "_id",
136 producing nested dict under "_mapbody"
137 Also store known strings found at the end of line in "_flags".
138
139 Returns:
140 - tuple (map dict, map comment) when }; line is reached
141 - map dict when we run out of lines without the closing };
142 """
143 thismap = {}
144 for line, comment in parse_line(filein):
145 flags = parse_flags(comment)
146 if line == "};": # end of a nested map
147 return thismap, flags
148
149 # first word - a map key name
150 # beware: some statements do not have parameters, e.g. "null;"
151 key = line.split()[0].rstrip(";")
152 # map key sanity check
153 if not KEY_REGEX.fullmatch(key):
154 raise NotImplementedError("suspicious keyword detected", line)
155
156 # omit keyword from the grammar
157 grammar = line[len(key) :].strip()
158 # also skip final ; or {
159 grammar = grammar[:-1].strip()
160
161 thismap[key] = {}
162 if line.endswith("{"):
163 # nested map, recurse, but keep "extra identifiers" if any
164 try:
165 subkeys, flags = parse_mapbody(filein)
166 except ValueError:
167 raise ValueError("unfinished nested map, missing }; detected") from None
168 if flags:
169 thismap[key]["_flags"] = flags
170 if grammar:
171 # for lines which look like "view <name> {" store "<name>"
172 thismap[key]["_id"] = grammar
173 thismap[key]["_mapbody"] = subkeys
174 else:
175 assert line.endswith(";")
176 if flags:
177 thismap[key]["_flags"] = flags
178 thismap[key]["_grammar"] = grammar
179
180 # Ran out of lines: can happen only on the end of the top-level map-body!
181 # Intentionally do not return second parameter to cause ValueError
182 # if we reach this spot with a missing }; in a nested map.
183 assert len(thismap)
184 return thismap
185
186
187 def main():
188 """Read stdin or filename provided on command line"""
189 with fileinput.input() as filein:
190 grammar = parse_mapbody(filein)
191 print(json.dumps(grammar, indent=4))
192
193
194 if __name__ == "__main__":
195 main()