strings.py 44 KB

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