Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

strings.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2009 Charles Hebert <charles.hebert@logilab.fr>
  3. # Copyright (c) 2010-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  4. # Copyright (c) 2010 Daniel Harding <dharding@gmail.com>
  5. # Copyright (c) 2012-2014 Google, Inc.
  6. # Copyright (c) 2013-2017 Claudiu Popa <pcmanticore@gmail.com>
  7. # Copyright (c) 2014 Brett Cannon <brett@python.org>
  8. # Copyright (c) 2014 Arun Persaud <arun@nubati.net>
  9. # Copyright (c) 2015 Rene Zhang <rz99@cornell.edu>
  10. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  11. # Copyright (c) 2016 Peter Dawyndt <Peter.Dawyndt@UGent.be>
  12. # Copyright (c) 2016 Jakub Wilk <jwilk@jwilk.net>
  13. # Copyright (c) 2017 Łukasz Rogalski <rogalski.91@gmail.com>
  14. # Copyright (c) 2017 Ville Skyttä <ville.skytta@iki.fi>
  15. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  16. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  17. """Checker for string formatting operations.
  18. """
  19. import sys
  20. import tokenize
  21. import string
  22. import numbers
  23. import six
  24. import astroid
  25. from pylint.interfaces import ITokenChecker, IAstroidChecker, IRawChecker
  26. from pylint.checkers import BaseChecker, BaseTokenChecker
  27. from pylint.checkers import utils
  28. from pylint.checkers.utils import check_messages
  29. _PY3K = sys.version_info[:2] >= (3, 0)
  30. _PY27 = sys.version_info[:2] == (2, 7)
  31. MSGS = {
  32. 'E1300': ("Unsupported format character %r (%#02x) at index %d",
  33. "bad-format-character",
  34. "Used when a unsupported format character is used in a format\
  35. string."),
  36. 'E1301': ("Format string ends in middle of conversion specifier",
  37. "truncated-format-string",
  38. "Used when a format string terminates before the end of a \
  39. conversion specifier."),
  40. 'E1302': ("Mixing named and unnamed conversion specifiers in format string",
  41. "mixed-format-string",
  42. "Used when a format string contains both named (e.g. '%(foo)d') \
  43. and unnamed (e.g. '%d') conversion specifiers. This is also \
  44. used when a named conversion specifier contains * for the \
  45. minimum field width and/or precision."),
  46. 'E1303': ("Expected mapping for format string, not %s",
  47. "format-needs-mapping",
  48. "Used when a format string that uses named conversion specifiers \
  49. is used with an argument that is not a mapping."),
  50. 'W1300': ("Format string dictionary key should be a string, not %s",
  51. "bad-format-string-key",
  52. "Used when a format string that uses named conversion specifiers \
  53. is used with a dictionary whose keys are not all strings."),
  54. 'W1301': ("Unused key %r in format string dictionary",
  55. "unused-format-string-key",
  56. "Used when a format string that uses named conversion specifiers \
  57. is used with a dictionary that contains keys not required by the \
  58. format string."),
  59. 'E1304': ("Missing key %r in format string dictionary",
  60. "missing-format-string-key",
  61. "Used when a format string that uses named conversion specifiers \
  62. is used with a dictionary that doesn't contain all the keys \
  63. required by the format string."),
  64. 'E1305': ("Too many arguments for format string",
  65. "too-many-format-args",
  66. "Used when a format string that uses unnamed conversion \
  67. specifiers is given too many arguments."),
  68. 'E1306': ("Not enough arguments for format string",
  69. "too-few-format-args",
  70. "Used when a format string that uses unnamed conversion \
  71. specifiers is given too few arguments"),
  72. 'E1310': ("Suspicious argument in %s.%s call",
  73. "bad-str-strip-call",
  74. "The argument to a str.{l,r,}strip call contains a"
  75. " duplicate character, "),
  76. 'W1302': ("Invalid format string",
  77. "bad-format-string",
  78. "Used when a PEP 3101 format string is invalid.",
  79. {'minversion': (2, 7)}),
  80. 'W1303': ("Missing keyword argument %r for format string",
  81. "missing-format-argument-key",
  82. "Used when a PEP 3101 format string that uses named fields "
  83. "doesn't receive one or more required keywords.",
  84. {'minversion': (2, 7)}),
  85. 'W1304': ("Unused format argument %r",
  86. "unused-format-string-argument",
  87. "Used when a PEP 3101 format string that uses named "
  88. "fields is used with an argument that "
  89. "is not required by the format string.",
  90. {'minversion': (2, 7)}),
  91. 'W1305': ("Format string contains both automatic field numbering "
  92. "and manual field specification",
  93. "format-combined-specification",
  94. "Used when a PEP 3101 format string contains both automatic "
  95. "field numbering (e.g. '{}') and manual field "
  96. "specification (e.g. '{0}').",
  97. {'minversion': (2, 7)}),
  98. 'W1306': ("Missing format attribute %r in format specifier %r",
  99. "missing-format-attribute",
  100. "Used when a PEP 3101 format string uses an "
  101. "attribute specifier ({0.length}), but the argument "
  102. "passed for formatting doesn't have that attribute.",
  103. {'minversion': (2, 7)}),
  104. 'W1307': ("Using invalid lookup key %r in format specifier %r",
  105. "invalid-format-index",
  106. "Used when a PEP 3101 format string uses a lookup specifier "
  107. "({a[1]}), but the argument passed for formatting "
  108. "doesn't contain or doesn't have that key as an attribute.",
  109. {'minversion': (2, 7)})
  110. }
  111. OTHER_NODES = (astroid.Const, astroid.List, astroid.Repr,
  112. astroid.Lambda, astroid.FunctionDef,
  113. astroid.ListComp, astroid.SetComp, astroid.GeneratorExp)
  114. if _PY3K:
  115. import _string # pylint: disable=wrong-import-position, wrong-import-order
  116. def split_format_field_names(format_string):
  117. return _string.formatter_field_name_split(format_string)
  118. else:
  119. def _field_iterator_convertor(iterator):
  120. for is_attr, key in iterator:
  121. if isinstance(key, numbers.Number):
  122. yield is_attr, int(key)
  123. else:
  124. yield is_attr, key
  125. def split_format_field_names(format_string):
  126. try:
  127. keyname, fielditerator = format_string._formatter_field_name_split()
  128. except ValueError:
  129. raise utils.IncompleteFormatString
  130. # it will return longs, instead of ints, which will complicate
  131. # the output
  132. return keyname, _field_iterator_convertor(fielditerator)
  133. def collect_string_fields(format_string):
  134. """ Given a format string, return an iterator
  135. of all the valid format fields. It handles nested fields
  136. as well.
  137. """
  138. formatter = string.Formatter()
  139. try:
  140. parseiterator = formatter.parse(format_string)
  141. for result in parseiterator:
  142. if all(item is None for item in result[1:]):
  143. # not a replacement format
  144. continue
  145. name = result[1]
  146. nested = result[2]
  147. yield name
  148. if nested:
  149. for field in collect_string_fields(nested):
  150. yield field
  151. except ValueError as exc:
  152. # Probably the format string is invalid.
  153. if exc.args[0].startswith("cannot switch from manual"):
  154. # On Jython, parsing a string with both manual
  155. # and automatic positions will fail with a ValueError,
  156. # while on CPython it will simply return the fields,
  157. # the validation being done in the interpreter (?).
  158. # We're just returning two mixed fields in order
  159. # to trigger the format-combined-specification check.
  160. yield ""
  161. yield "1"
  162. return
  163. raise utils.IncompleteFormatString(format_string)
  164. def parse_format_method_string(format_string):
  165. """
  166. Parses a PEP 3101 format string, returning a tuple of
  167. (keys, num_args, manual_pos_arg),
  168. where keys is the set of mapping keys in the format string, num_args
  169. is the number of arguments required by the format string and
  170. manual_pos_arg is the number of arguments passed with the position.
  171. """
  172. keys = []
  173. num_args = 0
  174. manual_pos_arg = set()
  175. for name in collect_string_fields(format_string):
  176. if name and str(name).isdigit():
  177. manual_pos_arg.add(str(name))
  178. elif name:
  179. keyname, fielditerator = split_format_field_names(name)
  180. if isinstance(keyname, numbers.Number):
  181. # In Python 2 it will return long which will lead
  182. # to different output between 2 and 3
  183. manual_pos_arg.add(str(keyname))
  184. keyname = int(keyname)
  185. try:
  186. keys.append((keyname, list(fielditerator)))
  187. except ValueError:
  188. raise utils.IncompleteFormatString()
  189. else:
  190. num_args += 1
  191. return keys, num_args, len(manual_pos_arg)
  192. def get_args(call):
  193. """Get the arguments from the given `Call` node.
  194. Return a tuple, where the first element is the
  195. number of positional arguments and the second element
  196. is the keyword arguments in a dict.
  197. """
  198. if call.keywords:
  199. named = {arg.arg: utils.safe_infer(arg.value)
  200. for arg in call.keywords}
  201. else:
  202. named = {}
  203. positional = len(call.args)
  204. return positional, named
  205. def get_access_path(key, parts):
  206. """ Given a list of format specifiers, returns
  207. the final access path (e.g. a.b.c[0][1]).
  208. """
  209. path = []
  210. for is_attribute, specifier in parts:
  211. if is_attribute:
  212. path.append(".{}".format(specifier))
  213. else:
  214. path.append("[{!r}]".format(specifier))
  215. return str(key) + "".join(path)
  216. class StringFormatChecker(BaseChecker):
  217. """Checks string formatting operations to ensure that the format string
  218. is valid and the arguments match the format string.
  219. """
  220. __implements__ = (IAstroidChecker,)
  221. name = 'string'
  222. msgs = MSGS
  223. @check_messages(*(MSGS.keys()))
  224. def visit_binop(self, node):
  225. if node.op != '%':
  226. return
  227. left = node.left
  228. args = node.right
  229. if not (isinstance(left, astroid.Const)
  230. and isinstance(left.value, six.string_types)):
  231. return
  232. format_string = left.value
  233. try:
  234. required_keys, required_num_args = \
  235. utils.parse_format_string(format_string)
  236. except utils.UnsupportedFormatCharacter as e:
  237. c = format_string[e.index]
  238. self.add_message('bad-format-character',
  239. node=node, args=(c, ord(c), e.index))
  240. return
  241. except utils.IncompleteFormatString:
  242. self.add_message('truncated-format-string', node=node)
  243. return
  244. if required_keys and required_num_args:
  245. # The format string uses both named and unnamed format
  246. # specifiers.
  247. self.add_message('mixed-format-string', node=node)
  248. elif required_keys:
  249. # The format string uses only named format specifiers.
  250. # Check that the RHS of the % operator is a mapping object
  251. # that contains precisely the set of keys required by the
  252. # format string.
  253. if isinstance(args, astroid.Dict):
  254. keys = set()
  255. unknown_keys = False
  256. for k, _ in args.items:
  257. if isinstance(k, astroid.Const):
  258. key = k.value
  259. if isinstance(key, six.string_types):
  260. keys.add(key)
  261. else:
  262. self.add_message('bad-format-string-key',
  263. node=node, args=key)
  264. else:
  265. # One of the keys was something other than a
  266. # constant. Since we can't tell what it is,
  267. # suppress checks for missing keys in the
  268. # dictionary.
  269. unknown_keys = True
  270. if not unknown_keys:
  271. for key in required_keys:
  272. if key not in keys:
  273. self.add_message('missing-format-string-key',
  274. node=node, args=key)
  275. for key in keys:
  276. if key not in required_keys:
  277. self.add_message('unused-format-string-key',
  278. node=node, args=key)
  279. elif isinstance(args, OTHER_NODES + (astroid.Tuple,)):
  280. type_name = type(args).__name__
  281. self.add_message('format-needs-mapping',
  282. node=node, args=type_name)
  283. # else:
  284. # The RHS of the format specifier is a name or
  285. # expression. It may be a mapping object, so
  286. # there's nothing we can check.
  287. else:
  288. # The format string uses only unnamed format specifiers.
  289. # Check that the number of arguments passed to the RHS of
  290. # the % operator matches the number required by the format
  291. # string.
  292. if isinstance(args, astroid.Tuple):
  293. rhs_tuple = utils.safe_infer(args)
  294. num_args = None
  295. if rhs_tuple not in (None, astroid.Uninferable):
  296. num_args = len(rhs_tuple.elts)
  297. elif isinstance(args, OTHER_NODES + (astroid.Dict, astroid.DictComp)):
  298. num_args = 1
  299. else:
  300. # The RHS of the format specifier is a name or
  301. # expression. It could be a tuple of unknown size, so
  302. # there's nothing we can check.
  303. num_args = None
  304. if num_args is not None:
  305. if num_args > required_num_args:
  306. self.add_message('too-many-format-args', node=node)
  307. elif num_args < required_num_args:
  308. self.add_message('too-few-format-args', node=node)
  309. @check_messages(*(MSGS.keys()))
  310. def visit_call(self, node):
  311. func = utils.safe_infer(node.func)
  312. if (isinstance(func, astroid.BoundMethod)
  313. and isinstance(func.bound, astroid.Instance)
  314. and func.bound.name in ('str', 'unicode', 'bytes')):
  315. if func.name in ('strip', 'lstrip', 'rstrip') and node.args:
  316. arg = utils.safe_infer(node.args[0])
  317. if not isinstance(arg, astroid.Const):
  318. return
  319. if len(arg.value) != len(set(arg.value)):
  320. self.add_message('bad-str-strip-call', node=node,
  321. args=(func.bound.name, func.name))
  322. elif func.name == 'format':
  323. if _PY27 or _PY3K:
  324. self._check_new_format(node, func)
  325. def _check_new_format(self, node, func):
  326. """ Check the new string formatting. """
  327. # TODO: skip (for now) format nodes which don't have
  328. # an explicit string on the left side of the format operation.
  329. # We do this because our inference engine can't properly handle
  330. # redefinitions of the original string.
  331. # For more details, see issue 287.
  332. #
  333. # Note that there may not be any left side at all, if the format method
  334. # has been assigned to another variable. See issue 351. For example:
  335. #
  336. # fmt = 'some string {}'.format
  337. # fmt('arg')
  338. if (isinstance(node.func, astroid.Attribute)
  339. and not isinstance(node.func.expr, astroid.Const)):
  340. return
  341. try:
  342. strnode = next(func.bound.infer())
  343. except astroid.InferenceError:
  344. return
  345. if not isinstance(strnode, astroid.Const):
  346. return
  347. if not isinstance(strnode.value, six.string_types):
  348. return
  349. if node.starargs or node.kwargs:
  350. return
  351. try:
  352. positional, named = get_args(node)
  353. except astroid.InferenceError:
  354. return
  355. try:
  356. fields, num_args, manual_pos = parse_format_method_string(strnode.value)
  357. except utils.IncompleteFormatString:
  358. self.add_message('bad-format-string', node=node)
  359. return
  360. named_fields = set(field[0] for field in fields
  361. if isinstance(field[0], six.string_types))
  362. if num_args and manual_pos:
  363. self.add_message('format-combined-specification',
  364. node=node)
  365. return
  366. check_args = False
  367. # Consider "{[0]} {[1]}" as num_args.
  368. num_args += sum(1 for field in named_fields
  369. if field == '')
  370. if named_fields:
  371. for field in named_fields:
  372. if field not in named and field:
  373. self.add_message('missing-format-argument-key',
  374. node=node,
  375. args=(field, ))
  376. for field in named:
  377. if field not in named_fields:
  378. self.add_message('unused-format-string-argument',
  379. node=node,
  380. args=(field, ))
  381. # num_args can be 0 if manual_pos is not.
  382. num_args = num_args or manual_pos
  383. if positional or num_args:
  384. empty = any(True for field in named_fields
  385. if field == '')
  386. if named or empty:
  387. # Verify the required number of positional arguments
  388. # only if the .format got at least one keyword argument.
  389. # This means that the format strings accepts both
  390. # positional and named fields and we should warn
  391. # when one of the them is missing or is extra.
  392. check_args = True
  393. else:
  394. check_args = True
  395. if check_args:
  396. # num_args can be 0 if manual_pos is not.
  397. num_args = num_args or manual_pos
  398. if positional > num_args:
  399. self.add_message('too-many-format-args', node=node)
  400. elif positional < num_args:
  401. self.add_message('too-few-format-args', node=node)
  402. self._check_new_format_specifiers(node, fields, named)
  403. def _check_new_format_specifiers(self, node, fields, named):
  404. """
  405. Check attribute and index access in the format
  406. string ("{0.a}" and "{0[a]}").
  407. """
  408. for key, specifiers in fields:
  409. # Obtain the argument. If it can't be obtained
  410. # or infered, skip this check.
  411. if key == '':
  412. # {[0]} will have an unnamed argument, defaulting
  413. # to 0. It will not be present in `named`, so use the value
  414. # 0 for it.
  415. key = 0
  416. if isinstance(key, numbers.Number):
  417. try:
  418. argname = utils.get_argument_from_call(node, key)
  419. except utils.NoSuchArgumentError:
  420. continue
  421. else:
  422. if key not in named:
  423. continue
  424. argname = named[key]
  425. if argname in (astroid.YES, None):
  426. continue
  427. try:
  428. argument = next(argname.infer())
  429. except astroid.InferenceError:
  430. continue
  431. if not specifiers or argument is astroid.Uninferable:
  432. # No need to check this key if it doesn't
  433. # use attribute / item access
  434. continue
  435. if argument.parent and isinstance(argument.parent, astroid.Arguments):
  436. # Ignore any object coming from an argument,
  437. # because we can't infer its value properly.
  438. continue
  439. previous = argument
  440. parsed = []
  441. for is_attribute, specifier in specifiers:
  442. if previous is astroid.Uninferable:
  443. break
  444. parsed.append((is_attribute, specifier))
  445. if is_attribute:
  446. try:
  447. previous = previous.getattr(specifier)[0]
  448. except astroid.NotFoundError:
  449. if (hasattr(previous, 'has_dynamic_getattr') and
  450. previous.has_dynamic_getattr()):
  451. # Don't warn if the object has a custom __getattr__
  452. break
  453. path = get_access_path(key, parsed)
  454. self.add_message('missing-format-attribute',
  455. args=(specifier, path),
  456. node=node)
  457. break
  458. else:
  459. warn_error = False
  460. if hasattr(previous, 'getitem'):
  461. try:
  462. previous = previous.getitem(astroid.Const(specifier))
  463. except (astroid.AstroidIndexError,
  464. astroid.AstroidTypeError,
  465. astroid.AttributeInferenceError):
  466. warn_error = True
  467. except astroid.InferenceError:
  468. break
  469. if previous is astroid.Uninferable:
  470. break
  471. else:
  472. try:
  473. # Lookup __getitem__ in the current node,
  474. # but skip further checks, because we can't
  475. # retrieve the looked object
  476. previous.getattr('__getitem__')
  477. break
  478. except astroid.NotFoundError:
  479. warn_error = True
  480. if warn_error:
  481. path = get_access_path(key, parsed)
  482. self.add_message('invalid-format-index',
  483. args=(specifier, path),
  484. node=node)
  485. break
  486. try:
  487. previous = next(previous.infer())
  488. except astroid.InferenceError:
  489. # can't check further if we can't infer it
  490. break
  491. class StringConstantChecker(BaseTokenChecker):
  492. """Check string literals"""
  493. __implements__ = (ITokenChecker, IRawChecker)
  494. name = 'string_constant'
  495. msgs = {
  496. 'W1401': ('Anomalous backslash in string: \'%s\'. '
  497. 'String constant might be missing an r prefix.',
  498. 'anomalous-backslash-in-string',
  499. 'Used when a backslash is in a literal string but not as an '
  500. 'escape.'),
  501. 'W1402': ('Anomalous Unicode escape in byte string: \'%s\'. '
  502. 'String constant might be missing an r or u prefix.',
  503. 'anomalous-unicode-escape-in-string',
  504. 'Used when an escape like \\u is encountered in a byte '
  505. 'string where it has no effect.'),
  506. }
  507. # Characters that have a special meaning after a backslash in either
  508. # Unicode or byte strings.
  509. ESCAPE_CHARACTERS = 'abfnrtvx\n\r\t\\\'\"01234567'
  510. # TODO(mbp): Octal characters are quite an edge case today; people may
  511. # prefer a separate warning where they occur. \0 should be allowed.
  512. # Characters that have a special meaning after a backslash but only in
  513. # Unicode strings.
  514. UNICODE_ESCAPE_CHARACTERS = 'uUN'
  515. def process_module(self, module):
  516. self._unicode_literals = 'unicode_literals' in module.future_imports
  517. def process_tokens(self, tokens):
  518. for (tok_type, token, (start_row, _), _, _) in tokens:
  519. if tok_type == tokenize.STRING:
  520. # 'token' is the whole un-parsed token; we can look at the start
  521. # of it to see whether it's a raw or unicode string etc.
  522. self.process_string_token(token, start_row)
  523. def process_string_token(self, token, start_row):
  524. for i, c in enumerate(token):
  525. if c in '\'\"':
  526. quote_char = c
  527. break
  528. # pylint: disable=undefined-loop-variable
  529. prefix = token[:i].lower() # markers like u, b, r.
  530. after_prefix = token[i:]
  531. if after_prefix[:3] == after_prefix[-3:] == 3 * quote_char:
  532. string_body = after_prefix[3:-3]
  533. else:
  534. string_body = after_prefix[1:-1] # Chop off quotes
  535. # No special checks on raw strings at the moment.
  536. if 'r' not in prefix:
  537. self.process_non_raw_string_token(prefix, string_body, start_row)
  538. def process_non_raw_string_token(self, prefix, string_body, start_row):
  539. """check for bad escapes in a non-raw string.
  540. prefix: lowercase string of eg 'ur' string prefix markers.
  541. string_body: the un-parsed body of the string, not including the quote
  542. marks.
  543. start_row: integer line number in the source.
  544. """
  545. # Walk through the string; if we see a backslash then escape the next
  546. # character, and skip over it. If we see a non-escaped character,
  547. # alert, and continue.
  548. #
  549. # Accept a backslash when it escapes a backslash, or a quote, or
  550. # end-of-line, or one of the letters that introduce a special escape
  551. # sequence <http://docs.python.org/reference/lexical_analysis.html>
  552. #
  553. # TODO(mbp): Maybe give a separate warning about the rarely-used
  554. # \a \b \v \f?
  555. #
  556. # TODO(mbp): We could give the column of the problem character, but
  557. # add_message doesn't seem to have a way to pass it through at present.
  558. i = 0
  559. while True:
  560. i = string_body.find('\\', i)
  561. if i == -1:
  562. break
  563. # There must be a next character; having a backslash at the end
  564. # of the string would be a SyntaxError.
  565. next_char = string_body[i+1]
  566. match = string_body[i:i+2]
  567. if next_char in self.UNICODE_ESCAPE_CHARACTERS:
  568. if 'u' in prefix:
  569. pass
  570. elif (_PY3K or self._unicode_literals) and 'b' not in prefix:
  571. pass # unicode by default
  572. else:
  573. self.add_message('anomalous-unicode-escape-in-string',
  574. line=start_row, args=(match, ))
  575. elif next_char not in self.ESCAPE_CHARACTERS:
  576. self.add_message('anomalous-backslash-in-string',
  577. line=start_row, args=(match, ))
  578. # Whether it was a valid escape or not, backslash followed by
  579. # another character can always be consumed whole: the second
  580. # character can never be the start of a new backslash escape.
  581. i += 2
  582. def register(linter):
  583. """required method to auto register this checker """
  584. linter.register_checker(StringFormatChecker(linter))
  585. linter.register_checker(StringConstantChecker(linter))