Debian Codegraph @

clang/docs/tools/dump_format_style.py

raw
1 #!/usr/bin/env python3
2 # A tool to parse the FormatStyle struct from Format.h and update the
3 # documentation in ../ClangFormatStyleOptions.rst automatically.
4 # Run from the directory in which this file is located to update the docs.
5
6 import inspect
7 import os
8 import re
9 import sys
10 from io import TextIOWrapper
11 from typing import Set
12
13 CLANG_DIR = os.path.join(os.path.dirname(__file__), "../..")
14 FORMAT_STYLE_FILE = os.path.join(CLANG_DIR, "include/clang/Format/Format.h")
15 INCLUDE_STYLE_FILE = os.path.join(
16 CLANG_DIR, "include/clang/Tooling/Inclusions/IncludeStyle.h"
17 )
18 DOC_FILE = os.path.join(CLANG_DIR, "docs/ClangFormatStyleOptions.rst")
19
20 PLURALS_FILE = os.path.join(os.path.dirname(__file__), "plurals.txt")
21
22 plurals: Set[str] = set()
23 with open(PLURALS_FILE, "a+") as f:
24 f.seek(0)
25 plurals = set(f.read().splitlines())
26
27
28 def substitute(text, tag, contents):
29 replacement = "\n.. START_%s\n\n%s\n\n.. END_%s\n" % (tag, contents, tag)
30 pattern = r"\n\.\. START_%s\n.*\n\.\. END_%s\n" % (tag, tag)
31 return re.sub(pattern, "%s", text, flags=re.S) % replacement
32
33
34 def register_plural(singular: str, plural: str):
35 if plural not in plurals:
36 if not hasattr(register_plural, "generated_new_plural"):
37 print(
38 "Plural generation: you can use "
39 f"`git checkout -- {os.path.relpath(PLURALS_FILE)}` "
40 "to reemit warnings or `git add` to include new plurals\n"
41 )
42 register_plural.generated_new_plural = True
43
44 plurals.add(plural)
45 with open(PLURALS_FILE, "a") as f:
46 f.write(plural + "\n")
47 cf = inspect.currentframe()
48 lineno = ""
49 if cf and cf.f_back:
50 lineno = ":" + str(cf.f_back.f_lineno)
51 print(
52 f"{__file__}{lineno} check if plural of {singular} is {plural}",
53 file=sys.stderr,
54 )
55 return plural
56
57
58 def pluralize(word: str):
59 lword = word.lower()
60 if len(lword) >= 2 and lword[-1] == "y" and lword[-2] not in "aeiou":
61 return register_plural(word, word[:-1] + "ies")
62 elif lword.endswith(("s", "sh", "ch", "x", "z")):
63 return register_plural(word, word[:-1] + "es")
64 elif lword.endswith("fe"):
65 return register_plural(word, word[:-2] + "ves")
66 elif lword.endswith("f") and not lword.endswith("ff"):
67 return register_plural(word, word[:-1] + "ves")
68 else:
69 return register_plural(word, word + "s")
70
71
72 def to_yaml_type(typestr: str):
73 if typestr == "bool":
74 return "Boolean"
75 elif typestr == "int":
76 return "Integer"
77 elif typestr == "unsigned":
78 return "Unsigned"
79 elif typestr == "std::string":
80 return "String"
81
82 match = re.match(r"std::vector<(.*)>$", typestr)
83 if match:
84 return "List of " + pluralize(to_yaml_type(match.group(1)))
85
86 match = re.match(r"std::optional<(.*)>$", typestr)
87 if match:
88 return to_yaml_type(match.group(1))
89
90 return typestr
91
92
93 def doxygen2rst(text):
94 text = re.sub(r"<tt>\s*(.*?)\s*<\/tt>", r"``\1``", text)
95 text = re.sub(r"\\c ([^ ,;\.]+)", r"``\1``", text)
96 text = re.sub(r"\\\w+ ", "", text)
97 return text
98
99
100 def indent(text, columns, indent_first_line=True):
101 indent_str = " " * columns
102 s = re.sub(r"\n([^\n])", "\n" + indent_str + "\\1", text, flags=re.S)
103 if not indent_first_line or s.startswith("\n"):
104 return s
105 return indent_str + s
106
107
108 class Option(object):
109 def __init__(self, name, opt_type, comment, version):
110 self.name = name
111 self.type = opt_type
112 self.comment = comment.strip()
113 self.enum = None
114 self.nested_struct = None
115 self.version = version
116
117 def __str__(self):
118 s = ".. _%s:\n\n**%s** (``%s``) " % (
119 self.name,
120 self.name,
121 to_yaml_type(self.type),
122 )
123 if self.version:
124 s += ":versionbadge:`clang-format %s` " % self.version
125 s += ":ref:`ΒΆ <%s>`\n%s" % (self.name, doxygen2rst(indent(self.comment, 2)))
126 if self.enum and self.enum.values:
127 s += indent("\n\nPossible values:\n\n%s\n" % self.enum, 2)
128 if self.nested_struct:
129 s += indent(
130 "\n\nNested configuration flags:\n\n%s\n" % self.nested_struct, 2
131 )
132 s = s.replace("<option-name>", self.name)
133 return s
134
135
136 class NestedStruct(object):
137 def __init__(self, name, comment):
138 self.name = name
139 self.comment = comment.strip()
140 self.values = []
141
142 def __str__(self):
143 return self.comment + "\n" + "\n".join(map(str, self.values))
144
145
146 class NestedField(object):
147 def __init__(self, name, comment, version):
148 self.name = name
149 self.comment = comment.strip()
150 self.version = version
151
152 def __str__(self):
153 if self.version:
154 return "\n* ``%s`` :versionbadge:`clang-format %s`\n%s" % (
155 self.name,
156 self.version,
157 doxygen2rst(indent(self.comment, 2, indent_first_line=False)),
158 )
159 return "\n* ``%s`` %s" % (
160 self.name,
161 doxygen2rst(indent(self.comment, 2, indent_first_line=False)),
162 )
163
164
165 class Enum(object):
166 def __init__(self, name, comment):
167 self.name = name
168 self.comment = comment.strip()
169 self.values = []
170
171 def __str__(self):
172 return "\n".join(map(str, self.values))
173
174
175 class NestedEnum(object):
176 def __init__(self, name, enumtype, comment, version, values):
177 self.name = name
178 self.comment = comment
179 self.values = values
180 self.type = enumtype
181 self.version = version
182
183 def __str__(self):
184 s = ""
185 if self.version:
186 s = "\n* ``%s %s`` :versionbadge:`clang-format %s`\n\n%s" % (
187 to_yaml_type(self.type),
188 self.name,
189 self.version,
190 doxygen2rst(indent(self.comment, 2)),
191 )
192 else:
193 s = "\n* ``%s %s``\n%s" % (
194 to_yaml_type(self.type),
195 self.name,
196 doxygen2rst(indent(self.comment, 2)),
197 )
198 s += indent("\nPossible values:\n\n", 2)
199 s += indent("\n".join(map(str, self.values)), 2)
200 return s
201
202
203 class EnumValue(object):
204 def __init__(self, name, comment, config):
205 self.name = name
206 self.comment = comment
207 self.config = config
208
209 def __str__(self):
210 return "* ``%s`` (in configuration: ``%s``)\n%s" % (
211 self.name,
212 re.sub(".*_", "", self.config),
213 doxygen2rst(indent(self.comment, 2)),
214 )
215
216
217 class OptionsReader:
218 def __init__(self, header: TextIOWrapper):
219 self.header = header
220 self.in_code_block = False
221 self.code_indent = 0
222 self.lineno = 0
223 self.last_err_lineno = -1
224
225 def __file_path(self):
226 return os.path.relpath(self.header.name)
227
228 def __print_line(self, line: str):
229 print(f"{self.lineno:>6} | {line}", file=sys.stderr)
230
231 def __warning(self, msg: str, line: str):
232 print(f"{self.__file_path()}:{self.lineno}: warning: {msg}:", file=sys.stderr)
233 self.__print_line(line)
234
235 def __clean_comment_line(self, line: str):
236 match = re.match(r"^/// (?P<indent> +)?\\code(\{.(?P<lang>\w+)\})?$", line)
237 if match:
238 if self.in_code_block:
239 self.__warning("`\\code` in another `\\code`", line)
240 self.in_code_block = True
241 indent_str = match.group("indent")
242 if not indent_str:
243 indent_str = ""
244 self.code_indent = len(indent_str)
245 lang = match.group("lang")
246 if not lang:
247 lang = "c++"
248 return f"\n{indent_str}.. code-block:: {lang}\n\n"
249
250 endcode_match = re.match(r"^/// +\\endcode$", line)
251 if endcode_match:
252 if not self.in_code_block:
253 self.__warning(
254 "no correct `\\code` found before this `\\endcode`", line
255 )
256 self.in_code_block = False
257 return ""
258
259 # check code block indentation
260 if (
261 self.in_code_block
262 and not line == "///"
263 and not line.startswith("/// " + " " * self.code_indent)
264 ):
265 if self.last_err_lineno == self.lineno - 1:
266 self.__print_line(line)
267 else:
268 self.__warning("code block should be indented", line)
269 self.last_err_lineno = self.lineno
270
271 match = re.match(r"^/// \\warning$", line)
272 if match:
273 return "\n.. warning::\n\n"
274
275 endwarning_match = re.match(r"^/// +\\endwarning$", line)
276 if endwarning_match:
277 return ""
278
279 match = re.match(r"^/// \\note$", line)
280 if match:
281 return "\n.. note::\n\n"
282
283 endnote_match = re.match(r"^/// +\\endnote$", line)
284 if endnote_match:
285 return ""
286 return line[4:] + "\n"
287
288 def read_options(self):
289 class State:
290 (
291 BeforeStruct,
292 Finished,
293 InStruct,
294 InNestedStruct,
295 InNestedFieldComment,
296 InFieldComment,
297 InEnum,
298 InEnumMemberComment,
299 InNestedEnum,
300 InNestedEnumMemberComment,
301 ) = range(10)
302
303 state = State.BeforeStruct
304
305 options = []
306 enums = {}
307 nested_structs = {}
308 comment = ""
309 enum = None
310 nested_struct = None
311 version = None
312 deprecated = False
313
314 for line in self.header:
315 self.lineno += 1
316 line = line.strip()
317 if state == State.BeforeStruct:
318 if line in ("struct FormatStyle {", "struct IncludeStyle {"):
319 state = State.InStruct
320 elif state == State.InStruct:
321 if line.startswith("///"):
322 state = State.InFieldComment
323 comment = self.__clean_comment_line(line)
324 elif line == "};":
325 state = State.Finished
326 break
327 elif state == State.InFieldComment:
328 if line.startswith(r"/// \version"):
329 match = re.match(r"/// \\version\s*(?P<version>[0-9.]+)*", line)
330 if match:
331 version = match.group("version")
332 elif line.startswith("/// @deprecated"):
333 deprecated = True
334 elif line.startswith("///"):
335 comment += self.__clean_comment_line(line)
336 elif line.startswith("enum"):
337 state = State.InEnum
338 name = re.sub(r"enum\s+(\w+)\s*(:((\s*\w+)+)\s*)?\{", "\\1", line)
339 enum = Enum(name, comment)
340 elif line.startswith("struct"):
341 state = State.InNestedStruct
342 name = re.sub(r"struct\s+(\w+)\s*\{", "\\1", line)
343 nested_struct = NestedStruct(name, comment)
344 elif line.endswith(";"):
345 prefix = "// "
346 if line.startswith(prefix):
347 line = line[len(prefix) :]
348 state = State.InStruct
349 field_type, field_name = re.match(
350 r"([<>:\w(,\s)]+)\s+(\w+);", line
351 ).groups()
352 if deprecated:
353 field_type = "deprecated"
354 deprecated = False
355
356 if not version:
357 self.__warning(f"missing version for {field_name}", line)
358 option = Option(str(field_name), str(field_type), comment, version)
359 options.append(option)
360 version = None
361 else:
362 raise Exception(
363 "Invalid format, expected comment, field or enum\n" + line
364 )
365 elif state == State.InNestedStruct:
366 if line.startswith("///"):
367 state = State.InNestedFieldComment
368 comment = self.__clean_comment_line(line)
369 elif line == "};":
370 state = State.InStruct
371 nested_structs[nested_struct.name] = nested_struct
372 elif state == State.InNestedFieldComment:
373 if line.startswith(r"/// \version"):
374 match = re.match(r"/// \\version\s*(?P<version>[0-9.]+)*", line)
375 if match:
376 version = match.group("version")
377 elif line.startswith("///"):
378 comment += self.__clean_comment_line(line)
379 elif line.startswith("enum"):
380 state = State.InNestedEnum
381 name = re.sub(r"enum\s+(\w+)\s*(:((\s*\w+)+)\s*)?\{", "\\1", line)
382 enum = Enum(name, comment)
383 else:
384 state = State.InNestedStruct
385 field_type, field_name = re.match(
386 r"([<>:\w(,\s)]+)\s+(\w+);", line
387 ).groups()
388 # if not version:
389 # self.__warning(f"missing version for {field_name}", line)
390 if field_type in enums:
391 nested_struct.values.append(
392 NestedEnum(
393 field_name,
394 field_type,
395 comment,
396 version,
397 enums[field_type].values,
398 )
399 )
400 else:
401 nested_struct.values.append(
402 NestedField(field_type + " " + field_name, comment, version)
403 )
404 version = None
405 elif state == State.InEnum:
406 if line.startswith("///"):
407 state = State.InEnumMemberComment
408 comment = self.__clean_comment_line(line)
409 elif line == "};":
410 state = State.InStruct
411 enums[enum.name] = enum
412 else:
413 # Enum member without documentation. Must be documented where the enum
414 # is used.
415 pass
416 elif state == State.InNestedEnum:
417 if line.startswith("///"):
418 state = State.InNestedEnumMemberComment
419 comment = self.__clean_comment_line(line)
420 elif line == "};":
421 state = State.InNestedStruct
422 enums[enum.name] = enum
423 else:
424 # Enum member without documentation. Must be
425 # documented where the enum is used.
426 pass
427 elif state == State.InEnumMemberComment:
428 if line.startswith("///"):
429 comment += self.__clean_comment_line(line)
430 else:
431 state = State.InEnum
432 val = line.replace(",", "")
433 pos = val.find(" // ")
434 if pos != -1:
435 config = val[pos + 4 :]
436 val = val[:pos]
437 else:
438 config = val
439 enum.values.append(EnumValue(val, comment, config))
440 elif state == State.InNestedEnumMemberComment:
441 if line.startswith("///"):
442 comment += self.__clean_comment_line(line)
443 else:
444 state = State.InNestedEnum
445 val = line.replace(",", "")
446 pos = val.find(" // ")
447 if pos != -1:
448 config = val[pos + 4 :]
449 val = val[:pos]
450 else:
451 config = val
452 enum.values.append(EnumValue(val, comment, config))
453 if state != State.Finished:
454 raise Exception("Not finished by the end of file")
455
456 for option in options:
457 if option.type not in [
458 "bool",
459 "unsigned",
460 "int",
461 "std::string",
462 "std::vector<std::string>",
463 "std::vector<IncludeCategory>",
464 "std::vector<RawStringFormat>",
465 "std::optional<unsigned>",
466 "deprecated",
467 ]:
468 if option.type in enums:
469 option.enum = enums[option.type]
470 elif option.type in nested_structs:
471 option.nested_struct = nested_structs[option.type]
472 else:
473 raise Exception("Unknown type: %s" % option.type)
474 return options
475
476
477 with open(FORMAT_STYLE_FILE) as f:
478 opts = OptionsReader(f).read_options()
479 with open(INCLUDE_STYLE_FILE) as f:
480 opts += OptionsReader(f).read_options()
481
482 opts = sorted(opts, key=lambda x: x.name)
483 options_text = "\n\n".join(map(str, opts))
484
485 with open(DOC_FILE, encoding="utf-8") as f:
486 contents = f.read()
487
488 contents = substitute(contents, "FORMAT_STYLE_OPTIONS", options_text)
489
490 with open(DOC_FILE, "wb") as output:
491 output.write(contents.encode())