format_grammar.py 15 KB

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