format_grammar.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. #!/usr/bin/env python3
  2. """Formats parser.ypp and lexer.lpp with clang-format."""
  3. __copyright__ = """
  4. Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  5. Exceptions. See /LICENSE for license information.
  6. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. """
  8. import argparse
  9. import os
  10. import re
  11. import subprocess
  12. import sys
  13. import textwrap
  14. from dataclasses import dataclass
  15. from typing import cast
  16. from typing import Dict
  17. from typing import List
  18. from typing import Optional
  19. from typing import Tuple
  20. # Files to format.
  21. _FILES = (
  22. "executable_semantics/syntax/parser.ypp",
  23. "executable_semantics/syntax/lexer.lpp",
  24. )
  25. # Columns to format to.
  26. _COLS = 80
  27. # An arbitrary separator to use when formatting multiple code segments.
  28. _FORMAT_SEPARATOR = "\n// CLANG FORMAT CODE SEGMENT SEPARATOR\n"
  29. # The table begin and end comments, including table-bounding newlines.
  30. _TABLE_BEGIN = "/* Table begin. */\n"
  31. _TABLE_END = "\n/* Table end. */"
  32. _TABLE_END_WITH_SPACE = "\n /* Table end. */"
  33. @dataclass
  34. class _CppCode:
  35. """Information about a code segment for formatting."""
  36. # The index of the code segment in the list of all segments.
  37. segment_index: int
  38. # The code content with braces stripped.
  39. content: str
  40. # The column of the open brace in the original line.
  41. open_brace_column: int
  42. # The generated indent of the close brace when the formatted output is
  43. # multi-line.
  44. close_brace_indent: int
  45. # Whether to write `%}` or `}`.
  46. has_percent: bool
  47. @dataclass
  48. class _Table:
  49. """Information about a table segment for formatting."""
  50. # The index of the table segment in the list of all segments.
  51. segment_index: int
  52. # The table content, with wrapping comments stripped.
  53. content: str
  54. def _parse_args() -> argparse.Namespace:
  55. """Parses command-line arguments and flags."""
  56. parser = argparse.ArgumentParser(description=__doc__)
  57. parser.add_argument(
  58. "--debug",
  59. action="store_true",
  60. help="Whether to print debug details.",
  61. )
  62. return parser.parse_args()
  63. def _clang_format(code: str, base_style: str, cols: int) -> str:
  64. """Calls clang-format to format the given code."""
  65. style = "--style={%s, ColumnLimit: %d}" % (base_style, cols)
  66. output = subprocess.check_output(
  67. args=["clang-format", style],
  68. input=code.encode("utf-8"),
  69. )
  70. return output.decode("utf-8")
  71. def _find_string_end(content: str, start: int) -> int:
  72. """Returns the end of a string, skipping escapes."""
  73. i = start
  74. while i < len(content):
  75. c = content[i]
  76. if c == "\\":
  77. i += 1
  78. elif c == '"':
  79. return i
  80. i += 1
  81. exit("failed to find end of string: %s" % content[start : start + 20])
  82. def _find_brace_end(content: str, has_percent: bool, start: int) -> int:
  83. """Returns the end of a braced section, skipping escapes.
  84. If has_percent, expect `%}` instead of `}`.
  85. """
  86. i = start
  87. while i < len(content):
  88. c = content[i]
  89. if c == '"':
  90. # Skip over strings.
  91. i = _find_string_end(content, i + 1)
  92. elif c == "/" and content[i + 1 : i + 2] == "/":
  93. # Skip over line comments.
  94. i = content.find("\n", i + 2)
  95. if i == -1:
  96. i = len(content)
  97. elif c == "{":
  98. i = _find_brace_end(content, False, i + 1)
  99. elif c == "}" and (not has_percent or content[i - 1] == "%"):
  100. return i
  101. i += 1
  102. exit("failed to find end of brace: %s" % content[start : start + 20])
  103. def _add_text_segment(
  104. text_segments: List[Optional[str]],
  105. segment: str,
  106. debug: bool,
  107. ) -> None:
  108. """Adds a text segment to the list."""
  109. text_segments.append(segment)
  110. if debug:
  111. print("=== Text segment ===")
  112. print(segment)
  113. print("====================")
  114. def _maybe_add_cpp_segment(
  115. content: str,
  116. text_segments: List[Optional[str]],
  117. cpp_segments: Dict[int, List[_CppCode]],
  118. text_segment_start: int,
  119. cpp_segment_start: int,
  120. debug: bool,
  121. ) -> Tuple[int, bool]:
  122. """Checks if cpp_segment_start is really at a C++ segment, and adds if so.
  123. Returns a tuple of (end, added) where `end` indicates the new offset into
  124. content to parse at, and `added` indicates whether a C++ segment was really
  125. added.
  126. """
  127. # lexer.lpp uses %{ %} for code, so detect it here.
  128. has_percent = content[cpp_segment_start - 1] == "%"
  129. # Find the end of the braced section.
  130. end = _find_brace_end(content, has_percent, cpp_segment_start + 1)
  131. # Determine the braced content, stripping the % and whitespace.
  132. braced_content = content[cpp_segment_start + 1 : end]
  133. if has_percent:
  134. braced_content = braced_content.rstrip("% \n")
  135. braced_content = braced_content.strip()
  136. if not has_percent and braced_content[-1] not in (";", "}", '"'):
  137. # Code would end with one of the indicated characters. This is
  138. # likely a non-formattable braced section, such as `{AND}`.
  139. # Keep treating it as text.
  140. return (end, False)
  141. else:
  142. # Code has been found. First, record the text segment; then,
  143. # indicate the non-text segment.
  144. _add_text_segment(
  145. text_segments, content[text_segment_start:cpp_segment_start], debug
  146. )
  147. text_segments.append(None)
  148. # If the opening brace is the first character on its line, use
  149. # its indent when wrapping.
  150. close_brace_indent = 0
  151. line_offset = content.rfind("\n", 0, cpp_segment_start)
  152. if content[line_offset + 1 : cpp_segment_start].isspace():
  153. close_brace_indent = cpp_segment_start - line_offset - 1
  154. # Construct the code segment.
  155. cpp_segment = _CppCode(
  156. len(text_segments) - 1,
  157. braced_content,
  158. cpp_segment_start - (line_offset + 1),
  159. close_brace_indent,
  160. has_percent,
  161. )
  162. if debug:
  163. print("=== C++ segment ===")
  164. print(cpp_segment.content)
  165. print(
  166. "Structure: { at %d; } at %d; %%: %s"
  167. % (
  168. cpp_segment.open_brace_column,
  169. cpp_segment.close_brace_indent,
  170. cpp_segment.has_percent,
  171. )
  172. )
  173. print("===================")
  174. # Record the code segment.
  175. if close_brace_indent not in cpp_segments:
  176. cpp_segments[close_brace_indent] = []
  177. cpp_segments[close_brace_indent].append(cpp_segment)
  178. # Increment cursors.
  179. return (end, True)
  180. def _parse_block_comment(
  181. content: str,
  182. text_segments: List[Optional[str]],
  183. table_segments: List[_Table],
  184. text_segment_start: int,
  185. cursor: int,
  186. debug: bool,
  187. ) -> Tuple[int, int]:
  188. """Parses a comment, possibly adding a table segment.
  189. Returns a tuple of (new_segment_start, new_cursor). Note the
  190. new_segment_start may or may not change.
  191. """
  192. # Skip over block comments.
  193. comment_end = content.find("*/", cursor + 2)
  194. if comment_end == -1:
  195. exit(
  196. "failed to find end of /* comment: %s"
  197. % content[cursor : cursor + 20]
  198. )
  199. comment_end += 2
  200. if content[cursor : comment_end + 1] == _TABLE_BEGIN:
  201. for table_end_style in (_TABLE_END, _TABLE_END_WITH_SPACE):
  202. table_end = content.find(table_end_style, comment_end)
  203. if table_end != -1:
  204. break
  205. if table_end == -1:
  206. exit(
  207. "failed to find end of table: %s"
  208. % content[comment_end + 1 : comment_end + 20]
  209. )
  210. _add_text_segment(
  211. text_segments, content[text_segment_start : comment_end + 1], debug
  212. )
  213. text_segments.append(None)
  214. table_segments.append(
  215. _Table(len(text_segments) - 1, content[comment_end + 1 : table_end])
  216. )
  217. return table_end, table_end + len(_TABLE_END) - 1
  218. else:
  219. return text_segment_start, comment_end - 1
  220. def _parse_segments(
  221. content: str,
  222. debug: bool,
  223. ) -> Tuple[List[Optional[str]], Dict[int, List[_CppCode]], List[_Table]]:
  224. """Parses out text, code, and table segments.
  225. Returns a tuple `(text_segments, code_segments, table_segments)`:
  226. - text_segments is a list version of the input content, with None where
  227. other segments go.
  228. - cpp_segments groups _CppCode objects by their close_brace_indent.
  229. - table_segments is a list of _Table objects.
  230. """
  231. i = 0
  232. segment_start = 0
  233. text_segments: List[Optional[str]] = []
  234. cpp_segments: Dict[int, List[_CppCode]] = {}
  235. table_segments: List[_Table] = []
  236. while i < len(content):
  237. c = content[i]
  238. if c == '"':
  239. # Skip over strings.
  240. i = _find_string_end(content, i + 1)
  241. elif c == "/" and content[i + 1 : i + 2] == "*":
  242. segment_start, i = _parse_block_comment(
  243. content, text_segments, table_segments, segment_start, i, debug
  244. )
  245. elif c == "\\":
  246. # Skip over escapes.
  247. i += 1
  248. elif c == "{":
  249. i, added = _maybe_add_cpp_segment(
  250. content, text_segments, cpp_segments, segment_start, i, debug
  251. )
  252. if added:
  253. segment_start = i + 1
  254. i += 1
  255. _add_text_segment(text_segments, content[segment_start:], debug)
  256. return text_segments, cpp_segments, table_segments
  257. def _format_cpp_segments(
  258. base_style: str,
  259. text_segments: List[Optional[str]],
  260. cpp_segments: Dict[int, List[_CppCode]],
  261. debug: bool,
  262. ) -> None:
  263. """Does the actual C++ code formatting.
  264. Formatting is done in groups, divided by indent because that affects code
  265. formatting.
  266. """
  267. # Iterate through code segments, formatting them in groups.
  268. for close_brace_indent, code_list in cpp_segments.items():
  269. format_input = _FORMAT_SEPARATOR.join(
  270. [code.content for code in code_list]
  271. )
  272. code_indent = close_brace_indent + 2
  273. formatted_block = _clang_format(
  274. format_input, base_style, _COLS - code_indent
  275. )
  276. formatted_segments = formatted_block.split(_FORMAT_SEPARATOR)
  277. # If there's a mismatch in lengths, error with the formatted output to
  278. # help determine what was wrong with input.
  279. if len(code_list) != len(formatted_segments):
  280. if debug:
  281. sys.stderr.write(formatted_block)
  282. exit(
  283. (
  284. "Unexpected formatting error (likely bad input): wanted %d "
  285. "segments, got %d (see above code)"
  286. )
  287. % (len(code_list), len(formatted_segments))
  288. )
  289. for i in range(len(formatted_segments)):
  290. code = code_list[i]
  291. formatted = formatted_segments[i]
  292. # The '4' here is from the `{ }` wrapper that is otherwise added.
  293. if (
  294. code.has_percent
  295. or code.open_brace_column + len(formatted) + 4 > _COLS
  296. or "\n" in formatted
  297. ):
  298. close_percent = ""
  299. if code.has_percent:
  300. close_percent = "%"
  301. text_segments[code.segment_index] = "{\n%s\n%s%s}" % (
  302. textwrap.indent(formatted, " " * code_indent),
  303. " " * code.close_brace_indent,
  304. close_percent,
  305. )
  306. else:
  307. text_segments[code.segment_index] = "{ %s }" % formatted
  308. def _format_table_segments(
  309. text_segments: List[Optional[str]],
  310. table_segments: List[_Table],
  311. debug: bool,
  312. ) -> None:
  313. """Formats table segments."""
  314. for table in table_segments:
  315. lines = table.content.strip().splitlines()
  316. rows: List[List[str]] = []
  317. col_widths: List[int] = []
  318. for row_index in range(len(lines)):
  319. cols = re.findall("[^ ]+", lines[row_index])
  320. rows.append(cols)
  321. if not col_widths:
  322. if len(cols) == 0:
  323. exit("Black line in table")
  324. col_widths = [0] * len(cols)
  325. elif len(col_widths) != len(cols):
  326. exit(
  327. "Wanted %d columns, found %d in `%s`"
  328. % (len(col_widths), len(cols), lines[row_index])
  329. )
  330. for col_index in range(len(cols)):
  331. col_widths[col_index] = max(
  332. col_widths[col_index], len(cols[col_index])
  333. )
  334. # The last column should not add spaces.
  335. row_format = " ".join(
  336. ["%%-%ds" % width for width in col_widths[:-1]] + ["%s"]
  337. )
  338. text_segments[table.segment_index] = "\n".join(
  339. [row_format % tuple(cols) for cols in rows]
  340. )
  341. def _format_file(path: str, base_style: str, debug: bool) -> None:
  342. """Formats a file, writing the result."""
  343. content = open(path).read()
  344. text_segments, cpp_segments, table_segments = _parse_segments(
  345. content, debug
  346. )
  347. _format_cpp_segments(base_style, text_segments, cpp_segments, debug)
  348. _format_table_segments(text_segments, table_segments, debug)
  349. assert None not in text_segments
  350. open(path, "w").write("".join(cast(List[str], text_segments)))
  351. def main() -> None:
  352. """See the file comment."""
  353. parsed_args = _parse_args()
  354. # Go to the repository root so that paths will match bazel's view.
  355. os.chdir(os.path.join(os.path.dirname(__file__), "../.."))
  356. # TODO: Switch to `BasedOnStyle: InheritParentConfig`
  357. # (https://reviews.llvm.org/D93844) once releases support it.
  358. format_config = open(".clang-format").readlines()
  359. base_style = ", ".join(
  360. [
  361. x.strip()
  362. for x in format_config
  363. if x[0].isalpha()
  364. # Allow single-line blocks for short rules.
  365. and not x.startswith("AllowShortBlocksOnASingleLine:")
  366. ]
  367. )
  368. # Format the grammar files.
  369. for path in _FILES:
  370. _format_file(path, base_style, parsed_args.debug)
  371. if __name__ == "__main__":
  372. main()