strings.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
  4. """Checker for string formatting operations."""
  5. from __future__ import annotations
  6. import collections
  7. import re
  8. import sys
  9. import tokenize
  10. from collections import Counter
  11. from collections.abc import Iterable, Sequence
  12. from typing import TYPE_CHECKING
  13. import astroid
  14. from astroid import bases, nodes, util
  15. from astroid.typing import SuccessfulInferenceResult
  16. from pylint.checkers import BaseChecker, BaseRawFileChecker, BaseTokenChecker, utils
  17. from pylint.checkers.utils import only_required_for_messages
  18. from pylint.interfaces import HIGH
  19. from pylint.typing import MessageDefinitionTuple
  20. if TYPE_CHECKING:
  21. from pylint.lint import PyLinter
  22. if sys.version_info >= (3, 8):
  23. from typing import Literal
  24. else:
  25. from typing_extensions import Literal
  26. _AST_NODE_STR_TYPES = ("__builtin__.unicode", "__builtin__.str", "builtins.str")
  27. # Prefixes for both strings and bytes literals per
  28. # https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
  29. _PREFIXES = {
  30. "r",
  31. "u",
  32. "R",
  33. "U",
  34. "f",
  35. "F",
  36. "fr",
  37. "Fr",
  38. "fR",
  39. "FR",
  40. "rf",
  41. "rF",
  42. "Rf",
  43. "RF",
  44. "b",
  45. "B",
  46. "br",
  47. "Br",
  48. "bR",
  49. "BR",
  50. "rb",
  51. "rB",
  52. "Rb",
  53. "RB",
  54. }
  55. SINGLE_QUOTED_REGEX = re.compile(f"({'|'.join(_PREFIXES)})?'''")
  56. DOUBLE_QUOTED_REGEX = re.compile(f"({'|'.join(_PREFIXES)})?\"\"\"")
  57. QUOTE_DELIMITER_REGEX = re.compile(f"({'|'.join(_PREFIXES)})?(\"|')", re.DOTALL)
  58. MSGS: dict[
  59. str, MessageDefinitionTuple
  60. ] = { # pylint: disable=consider-using-namedtuple-or-dataclass
  61. "E1300": (
  62. "Unsupported format character %r (%#02x) at index %d",
  63. "bad-format-character",
  64. "Used when an unsupported format character is used in a format string.",
  65. ),
  66. "E1301": (
  67. "Format string ends in middle of conversion specifier",
  68. "truncated-format-string",
  69. "Used when a format string terminates before the end of a "
  70. "conversion specifier.",
  71. ),
  72. "E1302": (
  73. "Mixing named and unnamed conversion specifiers in format string",
  74. "mixed-format-string",
  75. "Used when a format string contains both named (e.g. '%(foo)d') "
  76. "and unnamed (e.g. '%d') conversion specifiers. This is also "
  77. "used when a named conversion specifier contains * for the "
  78. "minimum field width and/or precision.",
  79. ),
  80. "E1303": (
  81. "Expected mapping for format string, not %s",
  82. "format-needs-mapping",
  83. "Used when a format string that uses named conversion specifiers "
  84. "is used with an argument that is not a mapping.",
  85. ),
  86. "W1300": (
  87. "Format string dictionary key should be a string, not %s",
  88. "bad-format-string-key",
  89. "Used when a format string that uses named conversion specifiers "
  90. "is used with a dictionary whose keys are not all strings.",
  91. ),
  92. "W1301": (
  93. "Unused key %r in format string dictionary",
  94. "unused-format-string-key",
  95. "Used when a format string that uses named conversion specifiers "
  96. "is used with a dictionary that contains keys not required by the "
  97. "format string.",
  98. ),
  99. "E1304": (
  100. "Missing key %r in format string dictionary",
  101. "missing-format-string-key",
  102. "Used when a format string that uses named conversion specifiers "
  103. "is used with a dictionary that doesn't contain all the keys "
  104. "required by the format string.",
  105. ),
  106. "E1305": (
  107. "Too many arguments for format string",
  108. "too-many-format-args",
  109. "Used when a format string that uses unnamed conversion "
  110. "specifiers is given too many arguments.",
  111. ),
  112. "E1306": (
  113. "Not enough arguments for format string",
  114. "too-few-format-args",
  115. "Used when a format string that uses unnamed conversion "
  116. "specifiers is given too few arguments",
  117. ),
  118. "E1307": (
  119. "Argument %r does not match format type %r",
  120. "bad-string-format-type",
  121. "Used when a type required by format string "
  122. "is not suitable for actual argument type",
  123. ),
  124. "E1310": (
  125. "Suspicious argument in %s.%s call",
  126. "bad-str-strip-call",
  127. "The argument to a str.{l,r,}strip call contains a duplicate character,",
  128. ),
  129. "W1302": (
  130. "Invalid format string",
  131. "bad-format-string",
  132. "Used when a PEP 3101 format string is invalid.",
  133. ),
  134. "W1303": (
  135. "Missing keyword argument %r for format string",
  136. "missing-format-argument-key",
  137. "Used when a PEP 3101 format string that uses named fields "
  138. "doesn't receive one or more required keywords.",
  139. ),
  140. "W1304": (
  141. "Unused format argument %r",
  142. "unused-format-string-argument",
  143. "Used when a PEP 3101 format string that uses named "
  144. "fields is used with an argument that "
  145. "is not required by the format string.",
  146. ),
  147. "W1305": (
  148. "Format string contains both automatic field numbering "
  149. "and manual field specification",
  150. "format-combined-specification",
  151. "Used when a PEP 3101 format string contains both automatic "
  152. "field numbering (e.g. '{}') and manual field "
  153. "specification (e.g. '{0}').",
  154. ),
  155. "W1306": (
  156. "Missing format attribute %r in format specifier %r",
  157. "missing-format-attribute",
  158. "Used when a PEP 3101 format string uses an "
  159. "attribute specifier ({0.length}), but the argument "
  160. "passed for formatting doesn't have that attribute.",
  161. ),
  162. "W1307": (
  163. "Using invalid lookup key %r in format specifier %r",
  164. "invalid-format-index",
  165. "Used when a PEP 3101 format string uses a lookup specifier "
  166. "({a[1]}), but the argument passed for formatting "
  167. "doesn't contain or doesn't have that key as an attribute.",
  168. ),
  169. "W1308": (
  170. "Duplicate string formatting argument %r, consider passing as named argument",
  171. "duplicate-string-formatting-argument",
  172. "Used when we detect that a string formatting is "
  173. "repeating an argument instead of using named string arguments",
  174. ),
  175. "W1309": (
  176. "Using an f-string that does not have any interpolated variables",
  177. "f-string-without-interpolation",
  178. "Used when we detect an f-string that does not use any interpolation variables, "
  179. "in which case it can be either a normal string or a bug in the code.",
  180. ),
  181. "W1310": (
  182. "Using formatting for a string that does not have any interpolated variables",
  183. "format-string-without-interpolation",
  184. "Used when we detect a string that does not have any interpolation variables, "
  185. "in which case it can be either a normal string without formatting or a bug in the code.",
  186. ),
  187. }
  188. OTHER_NODES = (
  189. nodes.Const,
  190. nodes.List,
  191. nodes.Lambda,
  192. nodes.FunctionDef,
  193. nodes.ListComp,
  194. nodes.SetComp,
  195. nodes.GeneratorExp,
  196. )
  197. def get_access_path(key: str | Literal[0], parts: list[tuple[bool, str]]) -> str:
  198. """Given a list of format specifiers, returns
  199. the final access path (e.g. a.b.c[0][1]).
  200. """
  201. path = []
  202. for is_attribute, specifier in parts:
  203. if is_attribute:
  204. path.append(f".{specifier}")
  205. else:
  206. path.append(f"[{specifier!r}]")
  207. return str(key) + "".join(path)
  208. def arg_matches_format_type(
  209. arg_type: SuccessfulInferenceResult, format_type: str
  210. ) -> bool:
  211. if format_type in "sr":
  212. # All types can be printed with %s and %r
  213. return True
  214. if isinstance(arg_type, astroid.Instance):
  215. arg_type = arg_type.pytype()
  216. if arg_type == "builtins.str":
  217. return format_type == "c"
  218. if arg_type == "builtins.float":
  219. return format_type in "deEfFgGn%"
  220. if arg_type == "builtins.int":
  221. # Integers allow all types
  222. return True
  223. return False
  224. return True
  225. class StringFormatChecker(BaseChecker):
  226. """Checks string formatting operations to ensure that the format string
  227. is valid and the arguments match the format string.
  228. """
  229. name = "string"
  230. msgs = MSGS
  231. # pylint: disable = too-many-branches, too-many-locals, too-many-statements
  232. @only_required_for_messages(
  233. "bad-format-character",
  234. "truncated-format-string",
  235. "mixed-format-string",
  236. "bad-format-string-key",
  237. "missing-format-string-key",
  238. "unused-format-string-key",
  239. "bad-string-format-type",
  240. "format-needs-mapping",
  241. "too-many-format-args",
  242. "too-few-format-args",
  243. "format-string-without-interpolation",
  244. )
  245. def visit_binop(self, node: nodes.BinOp) -> None:
  246. if node.op != "%":
  247. return
  248. left = node.left
  249. args = node.right
  250. if not (isinstance(left, nodes.Const) and isinstance(left.value, str)):
  251. return
  252. format_string = left.value
  253. try:
  254. (
  255. required_keys,
  256. required_num_args,
  257. required_key_types,
  258. required_arg_types,
  259. ) = utils.parse_format_string(format_string)
  260. except utils.UnsupportedFormatCharacter as exc:
  261. formatted = format_string[exc.index]
  262. self.add_message(
  263. "bad-format-character",
  264. node=node,
  265. args=(formatted, ord(formatted), exc.index),
  266. )
  267. return
  268. except utils.IncompleteFormatString:
  269. self.add_message("truncated-format-string", node=node)
  270. return
  271. if not required_keys and not required_num_args:
  272. self.add_message("format-string-without-interpolation", node=node)
  273. return
  274. if required_keys and required_num_args:
  275. # The format string uses both named and unnamed format
  276. # specifiers.
  277. self.add_message("mixed-format-string", node=node)
  278. elif required_keys:
  279. # The format string uses only named format specifiers.
  280. # Check that the RHS of the % operator is a mapping object
  281. # that contains precisely the set of keys required by the
  282. # format string.
  283. if isinstance(args, nodes.Dict):
  284. keys = set()
  285. unknown_keys = False
  286. for k, _ in args.items:
  287. if isinstance(k, nodes.Const):
  288. key = k.value
  289. if isinstance(key, str):
  290. keys.add(key)
  291. else:
  292. self.add_message(
  293. "bad-format-string-key", node=node, args=key
  294. )
  295. else:
  296. # One of the keys was something other than a
  297. # constant. Since we can't tell what it is,
  298. # suppress checks for missing keys in the
  299. # dictionary.
  300. unknown_keys = True
  301. if not unknown_keys:
  302. for key in required_keys:
  303. if key not in keys:
  304. self.add_message(
  305. "missing-format-string-key", node=node, args=key
  306. )
  307. for key in keys:
  308. if key not in required_keys:
  309. self.add_message(
  310. "unused-format-string-key", node=node, args=key
  311. )
  312. for key, arg in args.items:
  313. if not isinstance(key, nodes.Const):
  314. continue
  315. format_type = required_key_types.get(key.value, None)
  316. arg_type = utils.safe_infer(arg)
  317. if (
  318. format_type is not None
  319. and arg_type
  320. and not isinstance(arg_type, util.UninferableBase)
  321. and not arg_matches_format_type(arg_type, format_type)
  322. ):
  323. self.add_message(
  324. "bad-string-format-type",
  325. node=node,
  326. args=(arg_type.pytype(), format_type),
  327. )
  328. elif isinstance(args, (OTHER_NODES, nodes.Tuple)):
  329. type_name = type(args).__name__
  330. self.add_message("format-needs-mapping", node=node, args=type_name)
  331. # else:
  332. # The RHS of the format specifier is a name or
  333. # expression. It may be a mapping object, so
  334. # there's nothing we can check.
  335. else:
  336. # The format string uses only unnamed format specifiers.
  337. # Check that the number of arguments passed to the RHS of
  338. # the % operator matches the number required by the format
  339. # string.
  340. args_elts = []
  341. if isinstance(args, nodes.Tuple):
  342. rhs_tuple = utils.safe_infer(args)
  343. num_args = None
  344. if isinstance(rhs_tuple, nodes.BaseContainer):
  345. args_elts = rhs_tuple.elts
  346. num_args = len(args_elts)
  347. elif isinstance(args, (OTHER_NODES, (nodes.Dict, nodes.DictComp))):
  348. args_elts = [args]
  349. num_args = 1
  350. elif isinstance(args, nodes.Name):
  351. inferred = utils.safe_infer(args)
  352. if isinstance(inferred, nodes.Tuple):
  353. # The variable is a tuple, so we need to get the elements
  354. # from it for further inspection
  355. args_elts = inferred.elts
  356. num_args = len(args_elts)
  357. elif isinstance(inferred, nodes.Const):
  358. args_elts = [inferred]
  359. num_args = 1
  360. else:
  361. num_args = None
  362. else:
  363. # The RHS of the format specifier is an expression.
  364. # It could be a tuple of unknown size, so
  365. # there's nothing we can check.
  366. num_args = None
  367. if num_args is not None:
  368. if num_args > required_num_args:
  369. self.add_message("too-many-format-args", node=node)
  370. elif num_args < required_num_args:
  371. self.add_message("too-few-format-args", node=node)
  372. for arg, format_type in zip(args_elts, required_arg_types):
  373. if not arg:
  374. continue
  375. arg_type = utils.safe_infer(arg)
  376. if (
  377. arg_type
  378. and not isinstance(arg_type, util.UninferableBase)
  379. and not arg_matches_format_type(arg_type, format_type)
  380. ):
  381. self.add_message(
  382. "bad-string-format-type",
  383. node=node,
  384. args=(arg_type.pytype(), format_type),
  385. )
  386. @only_required_for_messages("f-string-without-interpolation")
  387. def visit_joinedstr(self, node: nodes.JoinedStr) -> None:
  388. self._check_interpolation(node)
  389. def _check_interpolation(self, node: nodes.JoinedStr) -> None:
  390. if isinstance(node.parent, nodes.FormattedValue):
  391. return
  392. for value in node.values:
  393. if isinstance(value, nodes.FormattedValue):
  394. return
  395. self.add_message("f-string-without-interpolation", node=node)
  396. def visit_call(self, node: nodes.Call) -> None:
  397. func = utils.safe_infer(node.func)
  398. if (
  399. isinstance(func, astroid.BoundMethod)
  400. and isinstance(func.bound, astroid.Instance)
  401. and func.bound.name in {"str", "unicode", "bytes"}
  402. ):
  403. if func.name in {"strip", "lstrip", "rstrip"} and node.args:
  404. arg = utils.safe_infer(node.args[0])
  405. if not isinstance(arg, nodes.Const) or not isinstance(arg.value, str):
  406. return
  407. if len(arg.value) != len(set(arg.value)):
  408. self.add_message(
  409. "bad-str-strip-call",
  410. node=node,
  411. args=(func.bound.name, func.name),
  412. )
  413. elif func.name == "format":
  414. self._check_new_format(node, func)
  415. def _detect_vacuous_formatting(
  416. self, node: nodes.Call, positional_arguments: list[SuccessfulInferenceResult]
  417. ) -> None:
  418. counter = collections.Counter(
  419. arg.name for arg in positional_arguments if isinstance(arg, nodes.Name)
  420. )
  421. for name, count in counter.items():
  422. if count == 1:
  423. continue
  424. self.add_message(
  425. "duplicate-string-formatting-argument", node=node, args=(name,)
  426. )
  427. def _check_new_format(self, node: nodes.Call, func: bases.BoundMethod) -> None:
  428. """Check the new string formatting."""
  429. # Skip format nodes which don't have an explicit string on the
  430. # left side of the format operation.
  431. # We do this because our inference engine can't properly handle
  432. # redefinition of the original string.
  433. # Note that there may not be any left side at all, if the format method
  434. # has been assigned to another variable. See issue 351. For example:
  435. #
  436. # fmt = 'some string {}'.format
  437. # fmt('arg')
  438. if isinstance(node.func, nodes.Attribute) and not isinstance(
  439. node.func.expr, nodes.Const
  440. ):
  441. return
  442. if node.starargs or node.kwargs:
  443. return
  444. try:
  445. strnode = next(func.bound.infer())
  446. except astroid.InferenceError:
  447. return
  448. if not (isinstance(strnode, nodes.Const) and isinstance(strnode.value, str)):
  449. return
  450. try:
  451. call_site = astroid.arguments.CallSite.from_call(node)
  452. except astroid.InferenceError:
  453. return
  454. try:
  455. fields, num_args, manual_pos = utils.parse_format_method_string(
  456. strnode.value
  457. )
  458. except utils.IncompleteFormatString:
  459. self.add_message("bad-format-string", node=node)
  460. return
  461. positional_arguments = call_site.positional_arguments
  462. named_arguments = call_site.keyword_arguments
  463. named_fields = {field[0] for field in fields if isinstance(field[0], str)}
  464. if num_args and manual_pos:
  465. self.add_message("format-combined-specification", node=node)
  466. return
  467. check_args = False
  468. # Consider "{[0]} {[1]}" as num_args.
  469. num_args += sum(1 for field in named_fields if not field)
  470. if named_fields:
  471. for field in named_fields:
  472. if field and field not in named_arguments:
  473. self.add_message(
  474. "missing-format-argument-key", node=node, args=(field,)
  475. )
  476. for field in named_arguments:
  477. if field not in named_fields:
  478. self.add_message(
  479. "unused-format-string-argument", node=node, args=(field,)
  480. )
  481. # num_args can be 0 if manual_pos is not.
  482. num_args = num_args or manual_pos
  483. if positional_arguments or num_args:
  484. empty = not all(field for field in named_fields)
  485. if named_arguments or empty:
  486. # Verify the required number of positional arguments
  487. # only if the .format got at least one keyword argument.
  488. # This means that the format strings accepts both
  489. # positional and named fields and we should warn
  490. # when one of them is missing or is extra.
  491. check_args = True
  492. else:
  493. check_args = True
  494. if check_args:
  495. # num_args can be 0 if manual_pos is not.
  496. num_args = num_args or manual_pos
  497. if not num_args:
  498. self.add_message("format-string-without-interpolation", node=node)
  499. return
  500. if len(positional_arguments) > num_args:
  501. self.add_message("too-many-format-args", node=node)
  502. elif len(positional_arguments) < num_args:
  503. self.add_message("too-few-format-args", node=node)
  504. self._detect_vacuous_formatting(node, positional_arguments)
  505. self._check_new_format_specifiers(node, fields, named_arguments)
  506. # pylint: disable = too-many-statements
  507. def _check_new_format_specifiers(
  508. self,
  509. node: nodes.Call,
  510. fields: list[tuple[str, list[tuple[bool, str]]]],
  511. named: dict[str, SuccessfulInferenceResult],
  512. ) -> None:
  513. """Check attribute and index access in the format
  514. string ("{0.a}" and "{0[a]}").
  515. """
  516. key: Literal[0] | str
  517. for key, specifiers in fields:
  518. # Obtain the argument. If it can't be obtained
  519. # or inferred, skip this check.
  520. if not key:
  521. # {[0]} will have an unnamed argument, defaulting
  522. # to 0. It will not be present in `named`, so use the value
  523. # 0 for it.
  524. key = 0
  525. if isinstance(key, int):
  526. try:
  527. argname = utils.get_argument_from_call(node, key)
  528. except utils.NoSuchArgumentError:
  529. continue
  530. else:
  531. if key not in named:
  532. continue
  533. argname = named[key]
  534. if argname is None or isinstance(argname, util.UninferableBase):
  535. continue
  536. try:
  537. argument = utils.safe_infer(argname)
  538. except astroid.InferenceError:
  539. continue
  540. if not specifiers or not argument:
  541. # No need to check this key if it doesn't
  542. # use attribute / item access
  543. continue
  544. if argument.parent and isinstance(argument.parent, nodes.Arguments):
  545. # Ignore any object coming from an argument,
  546. # because we can't infer its value properly.
  547. continue
  548. previous = argument
  549. parsed: list[tuple[bool, str]] = []
  550. for is_attribute, specifier in specifiers:
  551. if isinstance(previous, util.UninferableBase):
  552. break
  553. parsed.append((is_attribute, specifier))
  554. if is_attribute:
  555. try:
  556. previous = previous.getattr(specifier)[0]
  557. except astroid.NotFoundError:
  558. if (
  559. hasattr(previous, "has_dynamic_getattr")
  560. and previous.has_dynamic_getattr()
  561. ):
  562. # Don't warn if the object has a custom __getattr__
  563. break
  564. path = get_access_path(key, parsed)
  565. self.add_message(
  566. "missing-format-attribute",
  567. args=(specifier, path),
  568. node=node,
  569. )
  570. break
  571. else:
  572. warn_error = False
  573. if hasattr(previous, "getitem"):
  574. try:
  575. previous = previous.getitem(nodes.Const(specifier))
  576. except (
  577. astroid.AstroidIndexError,
  578. astroid.AstroidTypeError,
  579. astroid.AttributeInferenceError,
  580. ):
  581. warn_error = True
  582. except astroid.InferenceError:
  583. break
  584. if isinstance(previous, util.UninferableBase):
  585. break
  586. else:
  587. try:
  588. # Lookup __getitem__ in the current node,
  589. # but skip further checks, because we can't
  590. # retrieve the looked object
  591. previous.getattr("__getitem__")
  592. break
  593. except astroid.NotFoundError:
  594. warn_error = True
  595. if warn_error:
  596. path = get_access_path(key, parsed)
  597. self.add_message(
  598. "invalid-format-index", args=(specifier, path), node=node
  599. )
  600. break
  601. try:
  602. previous = next(previous.infer())
  603. except astroid.InferenceError:
  604. # can't check further if we can't infer it
  605. break
  606. class StringConstantChecker(BaseTokenChecker, BaseRawFileChecker):
  607. """Check string literals."""
  608. name = "string"
  609. msgs = {
  610. "W1401": (
  611. "Anomalous backslash in string: '%s'. "
  612. "String constant might be missing an r prefix.",
  613. "anomalous-backslash-in-string",
  614. "Used when a backslash is in a literal string but not as an escape.",
  615. ),
  616. "W1402": (
  617. "Anomalous Unicode escape in byte string: '%s'. "
  618. "String constant might be missing an r or u prefix.",
  619. "anomalous-unicode-escape-in-string",
  620. "Used when an escape like \\u is encountered in a byte "
  621. "string where it has no effect.",
  622. ),
  623. "W1404": (
  624. "Implicit string concatenation found in %s",
  625. "implicit-str-concat",
  626. "String literals are implicitly concatenated in a "
  627. "literal iterable definition : "
  628. "maybe a comma is missing ?",
  629. {"old_names": [("W1403", "implicit-str-concat-in-sequence")]},
  630. ),
  631. "W1405": (
  632. "Quote delimiter %s is inconsistent with the rest of the file",
  633. "inconsistent-quotes",
  634. "Quote delimiters are not used consistently throughout a module "
  635. "(with allowances made for avoiding unnecessary escaping).",
  636. ),
  637. "W1406": (
  638. "The u prefix for strings is no longer necessary in Python >=3.0",
  639. "redundant-u-string-prefix",
  640. "Used when we detect a string with a u prefix. These prefixes were necessary "
  641. "in Python 2 to indicate a string was Unicode, but since Python 3.0 strings "
  642. "are Unicode by default.",
  643. ),
  644. }
  645. options = (
  646. (
  647. "check-str-concat-over-line-jumps",
  648. {
  649. "default": False,
  650. "type": "yn",
  651. "metavar": "<y or n>",
  652. "help": "This flag controls whether the "
  653. "implicit-str-concat should generate a warning "
  654. "on implicit string concatenation in sequences defined over "
  655. "several lines.",
  656. },
  657. ),
  658. (
  659. "check-quote-consistency",
  660. {
  661. "default": False,
  662. "type": "yn",
  663. "metavar": "<y or n>",
  664. "help": "This flag controls whether inconsistent-quotes generates a "
  665. "warning when the character used as a quote delimiter is used "
  666. "inconsistently within a module.",
  667. },
  668. ),
  669. )
  670. # Characters that have a special meaning after a backslash in either
  671. # Unicode or byte strings.
  672. ESCAPE_CHARACTERS = "abfnrtvx\n\r\t\\'\"01234567"
  673. # Characters that have a special meaning after a backslash but only in
  674. # Unicode strings.
  675. UNICODE_ESCAPE_CHARACTERS = "uUN"
  676. def __init__(self, linter: PyLinter) -> None:
  677. super().__init__(linter)
  678. self.string_tokens: dict[
  679. tuple[int, int], tuple[str, tokenize.TokenInfo | None]
  680. ] = {}
  681. """Token position -> (token value, next token)."""
  682. def process_module(self, node: nodes.Module) -> None:
  683. self._unicode_literals = "unicode_literals" in node.future_imports
  684. def process_tokens(self, tokens: list[tokenize.TokenInfo]) -> None:
  685. encoding = "ascii"
  686. for i, (token_type, token, start, _, line) in enumerate(tokens):
  687. if token_type == tokenize.ENCODING:
  688. # this is always the first token processed
  689. encoding = token
  690. elif token_type == tokenize.STRING:
  691. # 'token' is the whole un-parsed token; we can look at the start
  692. # of it to see whether it's a raw or unicode string etc.
  693. self.process_string_token(token, start[0], start[1])
  694. # We figure the next token, ignoring comments & newlines:
  695. j = i + 1
  696. while j < len(tokens) and tokens[j].type in (
  697. tokenize.NEWLINE,
  698. tokenize.NL,
  699. tokenize.COMMENT,
  700. ):
  701. j += 1
  702. next_token = tokens[j] if j < len(tokens) else None
  703. if encoding != "ascii":
  704. # We convert `tokenize` character count into a byte count,
  705. # to match with astroid `.col_offset`
  706. start = (start[0], len(line[: start[1]].encode(encoding)))
  707. self.string_tokens[start] = (str_eval(token), next_token)
  708. if self.linter.config.check_quote_consistency:
  709. self.check_for_consistent_string_delimiters(tokens)
  710. @only_required_for_messages("implicit-str-concat")
  711. def visit_call(self, node: nodes.Call) -> None:
  712. self.check_for_concatenated_strings(node.args, "call")
  713. @only_required_for_messages("implicit-str-concat")
  714. def visit_list(self, node: nodes.List) -> None:
  715. self.check_for_concatenated_strings(node.elts, "list")
  716. @only_required_for_messages("implicit-str-concat")
  717. def visit_set(self, node: nodes.Set) -> None:
  718. self.check_for_concatenated_strings(node.elts, "set")
  719. @only_required_for_messages("implicit-str-concat")
  720. def visit_tuple(self, node: nodes.Tuple) -> None:
  721. self.check_for_concatenated_strings(node.elts, "tuple")
  722. def visit_assign(self, node: nodes.Assign) -> None:
  723. if isinstance(node.value, nodes.Const) and isinstance(node.value.value, str):
  724. self.check_for_concatenated_strings([node.value], "assignment")
  725. def check_for_consistent_string_delimiters(
  726. self, tokens: Iterable[tokenize.TokenInfo]
  727. ) -> None:
  728. """Adds a message for each string using inconsistent quote delimiters.
  729. Quote delimiters are used inconsistently if " and ' are mixed in a module's
  730. shortstrings without having done so to avoid escaping an internal quote
  731. character.
  732. Args:
  733. tokens: The tokens to be checked against for consistent usage.
  734. """
  735. string_delimiters: Counter[str] = collections.Counter()
  736. # First, figure out which quote character predominates in the module
  737. for tok_type, token, _, _, _ in tokens:
  738. if tok_type == tokenize.STRING and _is_quote_delimiter_chosen_freely(token):
  739. string_delimiters[_get_quote_delimiter(token)] += 1
  740. if len(string_delimiters) > 1:
  741. # Ties are broken arbitrarily
  742. most_common_delimiter = string_delimiters.most_common(1)[0][0]
  743. for tok_type, token, start, _, _ in tokens:
  744. if tok_type != tokenize.STRING:
  745. continue
  746. quote_delimiter = _get_quote_delimiter(token)
  747. if (
  748. _is_quote_delimiter_chosen_freely(token)
  749. and quote_delimiter != most_common_delimiter
  750. ):
  751. self.add_message(
  752. "inconsistent-quotes", line=start[0], args=(quote_delimiter,)
  753. )
  754. def check_for_concatenated_strings(
  755. self, elements: Sequence[nodes.NodeNG], iterable_type: str
  756. ) -> None:
  757. for elt in elements:
  758. if not (
  759. isinstance(elt, nodes.Const) and elt.pytype() in _AST_NODE_STR_TYPES
  760. ):
  761. continue
  762. if elt.col_offset < 0:
  763. # This can happen in case of escaped newlines
  764. continue
  765. token_index = (elt.lineno, elt.col_offset)
  766. if token_index not in self.string_tokens:
  767. # This may happen with Latin1 encoding
  768. # cf. https://github.com/PyCQA/pylint/issues/2610
  769. continue
  770. matching_token, next_token = self.string_tokens[token_index]
  771. # We detect string concatenation: the AST Const is the
  772. # combination of 2 string tokens
  773. if matching_token != elt.value and next_token is not None:
  774. if next_token.type == tokenize.STRING and (
  775. next_token.start[0] == elt.lineno
  776. or self.linter.config.check_str_concat_over_line_jumps
  777. ):
  778. self.add_message(
  779. "implicit-str-concat",
  780. line=elt.lineno,
  781. args=(iterable_type,),
  782. confidence=HIGH,
  783. )
  784. def process_string_token(self, token: str, start_row: int, start_col: int) -> None:
  785. quote_char = None
  786. for _index, char in enumerate(token):
  787. if char in "'\"":
  788. quote_char = char
  789. break
  790. if quote_char is None:
  791. return
  792. # pylint: disable=undefined-loop-variable
  793. prefix = token[:_index].lower() # markers like u, b, r.
  794. after_prefix = token[_index:]
  795. # pylint: enable=undefined-loop-variable
  796. # Chop off quotes
  797. quote_length = (
  798. 3 if after_prefix[:3] == after_prefix[-3:] == 3 * quote_char else 1
  799. )
  800. string_body = after_prefix[quote_length:-quote_length]
  801. # No special checks on raw strings at the moment.
  802. if "r" not in prefix:
  803. self.process_non_raw_string_token(
  804. prefix,
  805. string_body,
  806. start_row,
  807. start_col + len(prefix) + quote_length,
  808. )
  809. def process_non_raw_string_token(
  810. self, prefix: str, string_body: str, start_row: int, string_start_col: int
  811. ) -> None:
  812. """Check for bad escapes in a non-raw string.
  813. prefix: lowercase string of string prefix markers ('ur').
  814. string_body: the un-parsed body of the string, not including the quote
  815. marks.
  816. start_row: line number in the source.
  817. string_start_col: col number of the string start in the source.
  818. """
  819. # Walk through the string; if we see a backslash then escape the next
  820. # character, and skip over it. If we see a non-escaped character,
  821. # alert, and continue.
  822. #
  823. # Accept a backslash when it escapes a backslash, or a quote, or
  824. # end-of-line, or one of the letters that introduce a special escape
  825. # sequence <https://docs.python.org/reference/lexical_analysis.html>
  826. #
  827. index = 0
  828. while True:
  829. index = string_body.find("\\", index)
  830. if index == -1:
  831. break
  832. # There must be a next character; having a backslash at the end
  833. # of the string would be a SyntaxError.
  834. next_char = string_body[index + 1]
  835. match = string_body[index : index + 2]
  836. # The column offset will vary depending on whether the string token
  837. # is broken across lines. Calculate relative to the nearest line
  838. # break or relative to the start of the token's line.
  839. last_newline = string_body.rfind("\n", 0, index)
  840. if last_newline == -1:
  841. line = start_row
  842. col_offset = index + string_start_col
  843. else:
  844. line = start_row + string_body.count("\n", 0, index)
  845. col_offset = index - last_newline - 1
  846. if next_char in self.UNICODE_ESCAPE_CHARACTERS:
  847. if "u" in prefix:
  848. pass
  849. elif "b" not in prefix:
  850. pass # unicode by default
  851. else:
  852. self.add_message(
  853. "anomalous-unicode-escape-in-string",
  854. line=line,
  855. args=(match,),
  856. col_offset=col_offset,
  857. )
  858. elif next_char not in self.ESCAPE_CHARACTERS:
  859. self.add_message(
  860. "anomalous-backslash-in-string",
  861. line=line,
  862. args=(match,),
  863. col_offset=col_offset,
  864. )
  865. # Whether it was a valid escape or not, backslash followed by
  866. # another character can always be consumed whole: the second
  867. # character can never be the start of a new backslash escape.
  868. index += 2
  869. @only_required_for_messages("redundant-u-string-prefix")
  870. def visit_const(self, node: nodes.Const) -> None:
  871. if node.pytype() == "builtins.str" and not isinstance(
  872. node.parent, nodes.JoinedStr
  873. ):
  874. self._detect_u_string_prefix(node)
  875. def _detect_u_string_prefix(self, node: nodes.Const) -> None:
  876. """Check whether strings include a 'u' prefix like u'String'."""
  877. if node.kind == "u":
  878. self.add_message(
  879. "redundant-u-string-prefix",
  880. line=node.lineno,
  881. col_offset=node.col_offset,
  882. )
  883. def register(linter: PyLinter) -> None:
  884. linter.register_checker(StringFormatChecker(linter))
  885. linter.register_checker(StringConstantChecker(linter))
  886. def str_eval(token: str) -> str:
  887. """Mostly replicate `ast.literal_eval(token)` manually to avoid any performance hit.
  888. This supports f-strings, contrary to `ast.literal_eval`.
  889. We have to support all string literal notations:
  890. https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
  891. """
  892. if token[0:2].lower() in {"fr", "rf"}:
  893. token = token[2:]
  894. elif token[0].lower() in {"r", "u", "f"}:
  895. token = token[1:]
  896. if token[0:3] in {'"""', "'''"}:
  897. return token[3:-3]
  898. return token[1:-1]
  899. def _is_long_string(string_token: str) -> bool:
  900. """Is this string token a "longstring" (is it triple-quoted)?
  901. Long strings are triple-quoted as defined in
  902. https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
  903. This function only checks characters up through the open quotes. Because it's meant
  904. to be applied only to tokens that represent string literals, it doesn't bother to
  905. check for close-quotes (demonstrating that the literal is a well-formed string).
  906. Args:
  907. string_token: The string token to be parsed.
  908. Returns:
  909. A boolean representing whether this token matches a longstring
  910. regex.
  911. """
  912. return bool(
  913. SINGLE_QUOTED_REGEX.match(string_token)
  914. or DOUBLE_QUOTED_REGEX.match(string_token)
  915. )
  916. def _get_quote_delimiter(string_token: str) -> str:
  917. """Returns the quote character used to delimit this token string.
  918. This function checks whether the token is a well-formed string.
  919. Args:
  920. string_token: The token to be parsed.
  921. Returns:
  922. A string containing solely the first quote delimiter character in the
  923. given string.
  924. Raises:
  925. ValueError: No quote delimiter characters are present.
  926. """
  927. match = QUOTE_DELIMITER_REGEX.match(string_token)
  928. if not match:
  929. raise ValueError(f"string token {string_token} is not a well-formed string")
  930. return match.group(2)
  931. def _is_quote_delimiter_chosen_freely(string_token: str) -> bool:
  932. """Was there a non-awkward option for the quote delimiter?
  933. Args:
  934. string_token: The quoted string whose delimiters are to be checked.
  935. Returns:
  936. Whether there was a choice in this token's quote character that would
  937. not have involved backslash-escaping an interior quote character. Long
  938. strings are excepted from this analysis under the assumption that their
  939. quote characters are set by policy.
  940. """
  941. quote_delimiter = _get_quote_delimiter(string_token)
  942. unchosen_delimiter = '"' if quote_delimiter == "'" else "'"
  943. return bool(
  944. quote_delimiter
  945. and not _is_long_string(string_token)
  946. and unchosen_delimiter not in str_eval(string_token)
  947. )