check-internal-format-escaping.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. #!/usr/bin/env python3
  2. #
  3. # Check gcc.pot file for stylistic issues as described in
  4. # https://gcc.gnu.org/onlinedocs/gccint/Guidelines-for-Diagnostics.html,
  5. # especially in gcc-internal-format messages.
  6. #
  7. # This file is part of GCC.
  8. #
  9. # GCC is free software; you can redistribute it and/or modify it under
  10. # the terms of the GNU General Public License as published by the Free
  11. # Software Foundation; either version 3, or (at your option) any later
  12. # version.
  13. #
  14. # GCC is distributed in the hope that it will be useful, but WITHOUT ANY
  15. # WARRANTY; without even the implied warranty of MERCHANTABILITY or
  16. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  17. # for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with GCC; see the file COPYING3. If not see
  21. # <http://www.gnu.org/licenses/>.
  22. import argparse
  23. import re
  24. from collections import Counter
  25. from typing import Dict, Match
  26. import polib
  27. seen_warnings = Counter()
  28. def location(msg: polib.POEntry):
  29. if msg.occurrences:
  30. occ = msg.occurrences[0]
  31. return f'{occ[0]}:{occ[1]}'
  32. return '<unknown location>'
  33. def warn(msg: polib.POEntry,
  34. diagnostic_id: str, diagnostic: str, include_msgid=True):
  35. """
  36. To suppress a warning for a particular message,
  37. add a line "#, gcclint:ignore:{diagnostic_id}" to the message.
  38. """
  39. if f'gcclint:ignore:{diagnostic_id}' in msg.flags:
  40. return
  41. seen_warnings[diagnostic] += 1
  42. if include_msgid:
  43. print(f'{location(msg)}: {diagnostic} in {repr(msg.msgid)}')
  44. else:
  45. print(f'{location(msg)}: {diagnostic}')
  46. def lint_gcc_internal_format(msg: polib.POEntry):
  47. """
  48. Checks a single message that has the gcc-internal-format. These
  49. messages use a variety of placeholders like %qs, %<quotes%> and
  50. %q#E.
  51. """
  52. msgid: str = msg.msgid
  53. def outside_quotes(m: Match[str]):
  54. before = msgid[:m.start(0)]
  55. return before.count('%<') == before.count('%>')
  56. def lint_matching_placeholders():
  57. """
  58. Warns when literal values in placeholders are not exactly equal
  59. in the translation. This can happen when doing copy-and-paste
  60. translations of similar messages.
  61. To avoid these mismatches in the first place,
  62. structurally equal messages are found by
  63. lint_diagnostics_differing_only_in_placeholders.
  64. This check only applies when checking a finished translation
  65. such as de.po, not gcc.pot.
  66. """
  67. if not msg.translated():
  68. return
  69. in_msgid = re.findall('%<[^%]+%>', msgid)
  70. in_msgstr = re.findall('%<[^%]+%>', msg.msgstr)
  71. if set(in_msgid) != set(in_msgstr):
  72. warn(msg,
  73. 'placeholder-mismatch',
  74. f'placeholder mismatch: msgid has {in_msgid}, '
  75. f'msgstr has {in_msgstr}',
  76. include_msgid=False)
  77. def lint_option_outside_quotes():
  78. for match in re.finditer(r'\S+', msgid):
  79. part = match.group()
  80. if not outside_quotes(match):
  81. continue
  82. if part.startswith('-'):
  83. if len(part) >= 2 and part[1].isalpha():
  84. if part == '-INF':
  85. continue
  86. warn(msg,
  87. 'option-outside-quotes',
  88. 'command line option outside %<quotes%>')
  89. if part.startswith('__builtin_'):
  90. warn(msg,
  91. 'builtin-outside-quotes',
  92. 'builtin function outside %<quotes%>')
  93. def lint_plain_apostrophe():
  94. for match in re.finditer("[^%]'", msgid):
  95. if outside_quotes(match):
  96. warn(msg, 'apostrophe', 'apostrophe without leading %')
  97. def lint_space_before_quote():
  98. """
  99. A space before %< is often the result of string literals that
  100. are joined by the C compiler and neither literal has a space
  101. to separate the words.
  102. """
  103. for match in re.finditer('(.?[a-zA-Z0-9])%<', msgid):
  104. if match.group(1) != '%s':
  105. warn(msg,
  106. 'no-space-before-quote',
  107. '%< directly following a letter or digit')
  108. def lint_underscore_outside_quotes():
  109. """
  110. An underscore outside of quotes is used in several contexts,
  111. and many of them violate the GCC Guidelines for Diagnostics:
  112. * names of GCC-internal compiler functions
  113. * names of GCC-internal data structures
  114. * static_cast and the like (which are legitimate)
  115. """
  116. for match in re.finditer('_', msgid):
  117. if outside_quotes(match):
  118. warn(msg,
  119. 'underscore-outside-quotes',
  120. 'underscore outside of %<quotes%>')
  121. return
  122. def lint_may_not():
  123. """
  124. The term "may not" may either mean "it could be the case"
  125. or "should not". These two different meanings are sometimes
  126. hard to tell apart.
  127. """
  128. if re.search(r'\bmay not\b', msgid):
  129. warn(msg,
  130. 'ambiguous-may-not',
  131. 'the term "may not" is ambiguous')
  132. def lint_unbalanced_quotes():
  133. if msgid.count('%<') != msgid.count('%>'):
  134. warn(msg,
  135. 'unbalanced-quotes',
  136. 'unbalanced %< and %> quotes')
  137. if msg.translated():
  138. if msg.msgstr.count('%<') != msg.msgstr.count('%>'):
  139. warn(msg,
  140. 'unbalanced-quotes',
  141. 'unbalanced %< and %> quotes')
  142. def lint_single_space_after_sentence():
  143. """
  144. After a sentence there should be two spaces.
  145. """
  146. if re.search(r'[.] [A-Z]', msgid):
  147. warn(msg,
  148. 'single-space-after-sentence',
  149. 'single space after sentence')
  150. def lint_non_canonical_quotes():
  151. """
  152. Catches %<%s%>, which can be written in the shorter form %qs.
  153. """
  154. match = re.search("%<%s%>|'%s'|\"%s\"|`%s'", msgid)
  155. if match:
  156. warn(msg,
  157. 'non-canonical-quotes',
  158. f'placeholder {match.group()} should be written as %qs')
  159. lint_option_outside_quotes()
  160. lint_plain_apostrophe()
  161. lint_space_before_quote()
  162. lint_underscore_outside_quotes()
  163. lint_may_not()
  164. lint_unbalanced_quotes()
  165. lint_matching_placeholders()
  166. lint_single_space_after_sentence()
  167. lint_non_canonical_quotes()
  168. def lint_diagnostics_differing_only_in_placeholders(po: polib.POFile):
  169. """
  170. Detects messages that are structurally the same, except that they
  171. use different plain strings inside %<quotes%>. These messages can
  172. be merged in order to prevent copy-and-paste mistakes by the
  173. translators.
  174. See bug 90119.
  175. """
  176. seen: Dict[str, polib.POEntry] = {}
  177. for msg in po:
  178. msg: polib.POEntry
  179. msgid = msg.msgid
  180. normalized = re.sub('%<[^%]+%>', '%qs', msgid)
  181. if normalized not in seen:
  182. seen[normalized] = msg
  183. seen[msgid] = msg
  184. continue
  185. prev = seen[normalized]
  186. warn(msg,
  187. 'same-pattern',
  188. f'same pattern for {repr(msgid)} and '
  189. f'{repr(prev.msgid)} in {location(prev)}',
  190. include_msgid=False)
  191. def lint_file(po: polib.POFile):
  192. for msg in po:
  193. msg: polib.POEntry
  194. if not msg.obsolete and not msg.fuzzy:
  195. if 'gcc-internal-format' in msg.flags:
  196. lint_gcc_internal_format(msg)
  197. lint_diagnostics_differing_only_in_placeholders(po)
  198. def main():
  199. parser = argparse.ArgumentParser(description='')
  200. parser.add_argument('file', help='pot file')
  201. args = parser.parse_args()
  202. po = polib.pofile(args.file)
  203. lint_file(po)
  204. print()
  205. print('summary:')
  206. for entry in seen_warnings.most_common():
  207. if entry[1] > 1:
  208. print(f'{entry[1]}\t{entry[0]}')
  209. if __name__ == '__main__':
  210. main()