fname
stringlengths
63
176
rel_fname
stringclasses
706 values
line
int64
-1
4.5k
name
stringlengths
1
81
kind
stringclasses
2 values
category
stringclasses
2 values
info
stringlengths
0
77.9k
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
405
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
408
as_string
ref
function
args=(part.as_string(),),
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
411
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
414
as_string
ref
function
args=(part.as_string(),),
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
419
inherit_from_std_ex
ref
function
not utils.inherit_from_std_ex(exc)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
422
has_known_bases
ref
function
if utils.has_known_bases(exc):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
423
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
427
_check_try_except_raise
def
function
def _check_try_except_raise(self, node): def gather_exceptions_from_handler( handler, ) -> Optional[List[nodes.NodeNG]]: exceptions: List[nodes.NodeNG] = [] if handler.type: exceptions_in_handler = utils.safe_infer(handler.type) if isinstance(exceptions_in_handler, nodes.Tuple): exceptions = list( { exception for exception in exceptions_in_handler.elts if isinstance(exception, nodes.Name) } ) elif exceptions_in_handler: exceptions = [exceptions_in_handler] else: # Break when we cannot infer anything reliably. return None return exceptions bare_raise = _False handler_having_bare_raise = None exceptions_in_bare_handler = [] for handler in node.handlers: if bare_raise: # check that subsequent handler is not parent of handler which had bare raise. # since utils.safe_infer can fail for bare except, check it before. # also break early if bare except is followed by bare except. excs_in_current_handler = gather_exceptions_from_handler(handler) if not excs_in_current_handler: break if exceptions_in_bare_handler is None: # It can be `None` when the inference failed break for exc_in_current_handler in excs_in_current_handler: inferred_current = utils.safe_infer(exc_in_current_handler) if any( utils.is_subclass_of(utils.safe_infer(e), inferred_current) for e in exceptions_in_bare_handler ): bare_raise = _False break # `raise` as the first operator inside the except handler if _is_raising([handler.body[0]]): # flags when there is a bare raise if handler.body[0].exc is None: bare_raise = _True handler_having_bare_raise = handler exceptions_in_bare_handler = gather_exceptions_from_handler(handler) else: if bare_raise: self.add_message("try-except-raise", node=handler_having_bare_raise) @utils.check_messages("wrong-exception-operation") def visit_binop(self, node: nodes.BinOp) -> None: if isinstance(node.parent, nodes.ExceptHandler): # except (V | A) suggestion = f"Did you mean '({node.left.as_string()}, {node.right.as_string()})' instead?" self.add_message("wrong-exception-operation", node=node, args=(suggestion,)) @utils.check_messages("wrong-exception-operation") def visit_compare(self, node: nodes.Compare) -> None: if isinstance(node.parent, nodes.ExceptHandler): # except (V < A) suggestion = f"Did you mean '({node.left.as_string()}, {', '.join(operand.as_string() for _, operand in node.ops)})' instead?" self.add_message("wrong-exception-operation", node=node, args=(suggestion,)) @utils.check_messages( "bare-except", "broad-except", "try-except-raise", "binary-op-exception", "bad-except-order", "catching-non-exception", "duplicate-except", ) def visit_tryexcept(self, node: nodes.TryExcept) -> None: """Check for empty except.""" self._check_try_except_raise(node) exceptions_classes: List[Any] = [] nb_handlers = len(node.handlers) for index, handler in enumerate(node.handlers): if handler.type is None: if not _is_raising(handler.body): self.add_message("bare-except", node=handler) # check if an "except:" is followed by some other # except if index < (nb_handlers - 1): msg = "empty except clause should always appear last" self.add_message("bad-except-order", node=node, args=msg) elif isinstance(handler.type, nodes.BoolOp): self.add_message( "binary-op-exception", node=handler, args=handler.type.op ) else: try: exceptions = list(_annotated_unpack_infer(handler.type)) except astroid.InferenceError: continue for part, exception in exceptions: if exception is astroid.Uninferable: continue if isinstance( exception, astroid.Instance ) and utils.inherit_from_std_ex(exception): exception = exception._proxied self._check_catching_non_exception(handler, exception, part) if not isinstance(exception, nodes.ClassDef): continue exc_ancestors = [ anc for anc in exception.ancestors() if isinstance(anc, nodes.ClassDef) ] for previous_exc in exceptions_classes: if previous_exc in exc_ancestors: msg = f"{previous_exc.name} is an ancestor class of {exception.name}" self.add_message( "bad-except-order", node=handler.type, args=msg ) if ( exception.name in self.config.overgeneral_exceptions and exception.root().name == utils.EXCEPTIONS_MODULE and not _is_raising(handler.body) ): self.add_message( "broad-except", args=exception.name, node=handler.type ) if exception in exceptions_classes: self.add_message( "duplicate-except", args=exception.name, node=handler.type ) exceptions_classes += [exc for _, exc in exceptions]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
428
gather_exceptions_from_handler
def
function
def gather_exceptions_from_handler( handler, ) -> Optional[List[nodes.NodeNG]]: exceptions: List[nodes.NodeNG] = [] if handler.type: exceptions_in_handler = utils.safe_infer(handler.type) if isinstance(exceptions_in_handler, nodes.Tuple): exceptions = list( { exception for exception in exceptions_in_handler.elts if isinstance(exception, nodes.Name) } ) elif exceptions_in_handler: exceptions = [exceptions_in_handler] else: # Break when we cannot infer anything reliably. return None return exceptions bare_raise = _False handler_having_bare_raise = None exceptions_in_bare_handler = [] for handler in node.handlers: if bare_raise: # check that subsequent handler is not parent of handler which had bare raise. # since utils.safe_infer can fail for bare except, check it before. # also break early if bare except is followed by bare except. excs_in_current_handler = gather_exceptions_from_handler(handler) if not excs_in_current_handler: break if exceptions_in_bare_handler is None: # It can be `None` when the inference failed break for exc_in_current_handler in excs_in_current_handler: inferred_current = utils.safe_infer(exc_in_current_handler) if any( utils.is_subclass_of(utils.safe_infer(e), inferred_current) for e in exceptions_in_bare_handler ): bare_raise = _False break # `raise` as the first operator inside the except handler if _is_raising([handler.body[0]]): # flags when there is a bare raise if handler.body[0].exc is None: bare_raise = _True handler_having_bare_raise = handler exceptions_in_bare_handler = gather_exceptions_from_handler(handler) else: if bare_raise: self.add_message("try-except-raise", node=handler_having_bare_raise) @utils.check_messages("wrong-exception-operation") def visit_binop(self, node: nodes.BinOp) -> None: if isinstance(node.parent, nodes.ExceptHandler): # except (V | A) suggestion = f"Did you mean '({node.left.as_string()}, {node.right.as_string()})' instead?" self.add_message("wrong-exception-operation", node=node, args=(suggestion,)) @utils.check_messages("wrong-exception-operation") def visit_compare(self, node: nodes.Compare) -> None: if isinstance(node.parent, nodes.ExceptHandler): # except (V < A) suggestion = f"Did you mean '({node.left.as_string()}, {', '.join(operand.as_string() for _, operand in node.ops)})' instead?" self.add_message("wrong-exception-operation", node=node, args=(suggestion,)) @utils.check_messages( "bare-except", "broad-except", "try-except-raise", "binary-op-exception", "bad-except-order", "catching-non-exception", "duplicate-except", ) def visit_tryexcept(self, node: nodes.TryExcept) -> None: """Check for empty except.""" self._check_try_except_raise(node) exceptions_classes: List[Any] = [] nb_handlers = len(node.handlers) for index, handler in enumerate(node.handlers): if handler.type is None: if not _is_raising(handler.body): self.add_message("bare-except", node=handler) # check if an "except:" is followed by some other # except if index < (nb_handlers - 1): msg = "empty except clause should always appear last" self.add_message("bad-except-order", node=node, args=msg) elif isinstance(handler.type, nodes.BoolOp): self.add_message( "binary-op-exception", node=handler, args=handler.type.op ) else: try: exceptions = list(_annotated_unpack_infer(handler.type)) except astroid.InferenceError: continue for part, exception in exceptions: if exception is astroid.Uninferable: continue if isinstance( exception, astroid.Instance ) and utils.inherit_from_std_ex(exception): exception = exception._proxied self._check_catching_non_exception(handler, exception, part) if not isinstance(exception, nodes.ClassDef): continue exc_ancestors = [ anc for anc in exception.ancestors() if isinstance(anc, nodes.ClassDef) ] for previous_exc in exceptions_classes: if previous_exc in exc_ancestors: msg = f"{previous_exc.name} is an ancestor class of {exception.name}" self.add_message( "bad-except-order", node=handler.type, args=msg ) if ( exception.name in self.config.overgeneral_exceptions and exception.root().name == utils.EXCEPTIONS_MODULE and not _is_raising(handler.body) ): self.add_message( "broad-except", args=exception.name, node=handler.type ) if exception in exceptions_classes: self.add_message( "duplicate-except", args=exception.name, node=handler.type ) exceptions_classes += [exc for _, exc in exceptions]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
433
safe_infer
ref
function
exceptions_in_handler = utils.safe_infer(handler.type)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
458
gather_exceptions_from_handler
ref
function
excs_in_current_handler = gather_exceptions_from_handler(handler)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
465
safe_infer
ref
function
inferred_current = utils.safe_infer(exc_in_current_handler)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
467
is_subclass_of
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
467
safe_infer
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
474
_is_raising
ref
function
if _is_raising([handler.body[0]]):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
479
gather_exceptions_from_handler
ref
function
exceptions_in_bare_handler = gather_exceptions_from_handler(handler)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
482
add_message
ref
function
self.add_message("try-except-raise", node=handler_having_bare_raise)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
484
check_messages
ref
function
@utils.check_messages("wrong-exception-operation")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
485
visit_binop
def
function
def visit_binop(self, node: nodes.BinOp) -> None: if isinstance(node.parent, nodes.ExceptHandler): # except (V | A) suggestion = f"Did you mean '({node.left.as_string()}, {node.right.as_string()})' instead?" self.add_message("wrong-exception-operation", node=node, args=(suggestion,)) @utils.check_messages("wrong-exception-operation") def visit_compare(self, node: nodes.Compare) -> None: if isinstance(node.parent, nodes.ExceptHandler): # except (V < A) suggestion = f"Did you mean '({node.left.as_string()}, {', '.join(operand.as_string() for _, operand in node.ops)})' instead?" self.add_message("wrong-exception-operation", node=node, args=(suggestion,)) @utils.check_messages( "bare-except", "broad-except", "try-except-raise", "binary-op-exception", "bad-except-order", "catching-non-exception", "duplicate-except", ) def visit_tryexcept(self, node: nodes.TryExcept) -> None: """Check for empty except.""" self._check_try_except_raise(node) exceptions_classes: List[Any] = [] nb_handlers = len(node.handlers) for index, handler in enumerate(node.handlers): if handler.type is None: if not _is_raising(handler.body): self.add_message("bare-except", node=handler) # check if an "except:" is followed by some other # except if index < (nb_handlers - 1): msg = "empty except clause should always appear last" self.add_message("bad-except-order", node=node, args=msg) elif isinstance(handler.type, nodes.BoolOp): self.add_message( "binary-op-exception", node=handler, args=handler.type.op ) else: try: exceptions = list(_annotated_unpack_infer(handler.type)) except astroid.InferenceError: continue for part, exception in exceptions: if exception is astroid.Uninferable: continue if isinstance( exception, astroid.Instance ) and utils.inherit_from_std_ex(exception): exception = exception._proxied self._check_catching_non_exception(handler, exception, part) if not isinstance(exception, nodes.ClassDef): continue exc_ancestors = [ anc for anc in exception.ancestors() if isinstance(anc, nodes.ClassDef) ] for previous_exc in exceptions_classes: if previous_exc in exc_ancestors: msg = f"{previous_exc.name} is an ancestor class of {exception.name}" self.add_message( "bad-except-order", node=handler.type, args=msg ) if ( exception.name in self.config.overgeneral_exceptions and exception.root().name == utils.EXCEPTIONS_MODULE and not _is_raising(handler.body) ): self.add_message( "broad-except", args=exception.name, node=handler.type ) if exception in exceptions_classes: self.add_message( "duplicate-except", args=exception.name, node=handler.type ) exceptions_classes += [exc for _, exc in exceptions]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
488
as_string
ref
function
suggestion = f"Did you mean '({node.left.as_string()}, {node.right.as_string()})' instead?"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
488
as_string
ref
function
suggestion = f"Did you mean '({node.left.as_string()}, {node.right.as_string()})' instead?"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
489
add_message
ref
function
self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
491
check_messages
ref
function
@utils.check_messages("wrong-exception-operation")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
492
visit_compare
def
function
def visit_compare(self, node: nodes.Compare) -> None: if isinstance(node.parent, nodes.ExceptHandler): # except (V < A) suggestion = f"Did you mean '({node.left.as_string()}, {', '.join(operand.as_string() for _, operand in node.ops)})' instead?" self.add_message("wrong-exception-operation", node=node, args=(suggestion,)) @utils.check_messages( "bare-except", "broad-except", "try-except-raise", "binary-op-exception", "bad-except-order", "catching-non-exception", "duplicate-except", ) def visit_tryexcept(self, node: nodes.TryExcept) -> None: """Check for empty except.""" self._check_try_except_raise(node) exceptions_classes: List[Any] = [] nb_handlers = len(node.handlers) for index, handler in enumerate(node.handlers): if handler.type is None: if not _is_raising(handler.body): self.add_message("bare-except", node=handler) # check if an "except:" is followed by some other # except if index < (nb_handlers - 1): msg = "empty except clause should always appear last" self.add_message("bad-except-order", node=node, args=msg) elif isinstance(handler.type, nodes.BoolOp): self.add_message( "binary-op-exception", node=handler, args=handler.type.op ) else: try: exceptions = list(_annotated_unpack_infer(handler.type)) except astroid.InferenceError: continue for part, exception in exceptions: if exception is astroid.Uninferable: continue if isinstance( exception, astroid.Instance ) and utils.inherit_from_std_ex(exception): exception = exception._proxied self._check_catching_non_exception(handler, exception, part) if not isinstance(exception, nodes.ClassDef): continue exc_ancestors = [ anc for anc in exception.ancestors() if isinstance(anc, nodes.ClassDef) ] for previous_exc in exceptions_classes: if previous_exc in exc_ancestors: msg = f"{previous_exc.name} is an ancestor class of {exception.name}" self.add_message( "bad-except-order", node=handler.type, args=msg ) if ( exception.name in self.config.overgeneral_exceptions and exception.root().name == utils.EXCEPTIONS_MODULE and not _is_raising(handler.body) ): self.add_message( "broad-except", args=exception.name, node=handler.type ) if exception in exceptions_classes: self.add_message( "duplicate-except", args=exception.name, node=handler.type ) exceptions_classes += [exc for _, exc in exceptions]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
495
as_string
ref
function
suggestion = f"Did you mean '({node.left.as_string()}, {', '.join(operand.as_string() for _, operand in node.ops)})' instead?"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
495
as_string
ref
function
suggestion = f"Did you mean '({node.left.as_string()}, {', '.join(operand.as_string() for _, operand in node.ops)})' instead?"
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
496
add_message
ref
function
self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
498
check_messages
ref
function
@utils.check_messages(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
507
visit_tryexcept
def
function
def visit_tryexcept(self, node: nodes.TryExcept) -> None: """Check for empty except.""" self._check_try_except_raise(node) exceptions_classes: List[Any] = [] nb_handlers = len(node.handlers) for index, handler in enumerate(node.handlers): if handler.type is None: if not _is_raising(handler.body): self.add_message("bare-except", node=handler) # check if an "except:" is followed by some other # except if index < (nb_handlers - 1): msg = "empty except clause should always appear last" self.add_message("bad-except-order", node=node, args=msg) elif isinstance(handler.type, nodes.BoolOp): self.add_message( "binary-op-exception", node=handler, args=handler.type.op ) else: try: exceptions = list(_annotated_unpack_infer(handler.type)) except astroid.InferenceError: continue for part, exception in exceptions: if exception is astroid.Uninferable: continue if isinstance( exception, astroid.Instance ) and utils.inherit_from_std_ex(exception): exception = exception._proxied self._check_catching_non_exception(handler, exception, part) if not isinstance(exception, nodes.ClassDef): continue exc_ancestors = [ anc for anc in exception.ancestors() if isinstance(anc, nodes.ClassDef) ] for previous_exc in exceptions_classes: if previous_exc in exc_ancestors: msg = f"{previous_exc.name} is an ancestor class of {exception.name}" self.add_message( "bad-except-order", node=handler.type, args=msg ) if ( exception.name in self.config.overgeneral_exceptions and exception.root().name == utils.EXCEPTIONS_MODULE and not _is_raising(handler.body) ): self.add_message( "broad-except", args=exception.name, node=handler.type ) if exception in exceptions_classes: self.add_message( "duplicate-except", args=exception.name, node=handler.type ) exceptions_classes += [exc for _, exc in exceptions]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
509
_check_try_except_raise
ref
function
self._check_try_except_raise(node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
514
_is_raising
ref
function
if not _is_raising(handler.body):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
515
add_message
ref
function
self.add_message("bare-except", node=handler)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
521
add_message
ref
function
self.add_message("bad-except-order", node=node, args=msg)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
524
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
529
_annotated_unpack_infer
ref
function
exceptions = list(_annotated_unpack_infer(handler.type))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
538
inherit_from_std_ex
ref
function
) and utils.inherit_from_std_ex(exception):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
541
_check_catching_non_exception
ref
function
self._check_catching_non_exception(handler, exception, part)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
548
ancestors
ref
function
for anc in exception.ancestors()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
555
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
560
root
ref
function
and exception.root().name == utils.EXCEPTIONS_MODULE
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
561
_is_raising
ref
function
and not _is_raising(handler.body)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
563
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
568
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
575
register
def
function
def register(linter: "PyLinter") -> None: linter.register_checker(ExceptionsChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
576
register_checker
ref
function
linter.register_checker(ExceptionsChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/exceptions.py
pylint/checkers/exceptions.py
576
ExceptionsChecker
ref
function
linter.register_checker(ExceptionsChecker(linter))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
190
_last_token_on_line_is
def
function
def _last_token_on_line_is(tokens, line_end, token): return ( line_end > 0 and tokens.token(line_end - 1) == token or line_end > 1 and tokens.token(line_end - 2) == token and tokens.type(line_end - 1) == tokenize.COMMENT )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
193
token
ref
function
and tokens.token(line_end - 1) == token
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
195
token
ref
function
and tokens.token(line_end - 2) == token
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
216
TokenWrapper
def
class
__init__ token type start_line start_col line
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
222
token
def
function
def token(self, idx): return self._tokens[idx][1] def type(self, idx): return self._tokens[idx][0] def start_line(self, idx): return self._tokens[idx][2][0] def start_col(self, idx): return self._tokens[idx][2][1] def line(self, idx): return self._tokens[idx][4]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
228
start_line
def
function
def start_line(self, idx): return self._tokens[idx][2][0] def start_col(self, idx): return self._tokens[idx][2][1] def line(self, idx): return self._tokens[idx][4]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
231
start_col
def
function
def start_col(self, idx): return self._tokens[idx][2][1] def line(self, idx): return self._tokens[idx][4]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
234
line
def
function
def line(self, idx): return self._tokens[idx][4]
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
238
FormatChecker
def
class
__init__ new_line process_module _check_keyword_parentheses _prepare_token_dispatcher process_tokens _check_line_ending visit_default _check_multi_statement_line check_line_ending check_line_length remove_pylint_option_from_lines is_line_length_check_activated specific_splitlines check_lines check_indent_level
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
349
new_line
def
function
def new_line(self, tokens, line_end, line_start): """A new line has been encountered, process it if necessary.""" if _last_token_on_line_is(tokens, line_end, ";"): self.add_message("unnecessary-semicolon", line=tokens.start_line(line_end)) line_num = tokens.start_line(line_start) line = tokens.line(line_start) if tokens.type(line_start) not in _JUNK_TOKENS: self._lines[line_num] = line.split("\n")[0] self.check_lines(line, line_num) def process_module(self, _node: nodes.Module) -> None: pass def _check_keyword_parentheses( self, tokens: List[tokenize.TokenInfo], start: int ) -> None: """Check that there are not unnecessary parentheses after a keyword. Parens are unnecessary if there is exactly one balanced outer pair on a line, and it is followed by a colon, and contains no commas (i.e. is not a tuple). Args: tokens: list of Tokens; the entire list of Tokens. start: int; the position of the keyword in the token list. """ # If the next token is not a paren, we're fine. if self._bracket_stack[-1] == ":" and tokens[start].string == "for": self._bracket_stack.pop() if tokens[start + 1].string != "(": return found_and_or = _False contains_walrus_operator = _False walrus_operator_depth = 0 contains_double_parens = 0 depth = 0 keyword_token = str(tokens[start].string) line_num = tokens[start].start[0] for i in range(start, len(tokens) - 1): token = tokens[i] # If we hit a newline, then assume any parens were for continuation. if token.type == tokenize.NL: return # Since the walrus operator doesn't exist below python3.8, the tokenizer # generates independent tokens if ( token.string == ":=" # <-- python3.8+ path or token.string + tokens[i + 1].string == ":=" ): contains_walrus_operator = _True walrus_operator_depth = depth if token.string == "(": depth += 1 if tokens[i + 1].string == "(": contains_double_parens = 1 elif token.string == ")": depth -= 1 if depth: if contains_double_parens and tokens[i + 1].string == ")": # For walrus operators in `if (not)` conditions and comprehensions if keyword_token in {"in", "if", "not"}: continue return contains_double_parens -= 1 continue # ')' can't happen after if (foo), since it would be a syntax error. if tokens[i + 1].string in {":", ")", "]", "}", "in"} or tokens[ i + 1 ].type in {tokenize.NEWLINE, tokenize.ENDMARKER, tokenize.COMMENT}: if contains_walrus_operator and walrus_operator_depth - 1 == depth: return # The empty tuple () is always accepted. if i == start + 2: return if keyword_token == "not": if not found_and_or: self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) elif keyword_token in {"return", "yield"}: self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) elif not found_and_or and keyword_token != "in": self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) return elif depth == 1: # This is a tuple, which is always acceptable. if token[1] == ",": return # 'and' and 'or' are the only boolean operators with lower precedence # than 'not', so parens are only required when they are found. if token[1] in {"and", "or"}: found_and_or = _True # A yield inside an expression must always be in parentheses, # quit early without error. elif token[1] == "yield": return # A generator expression always has a 'for' token in it, and # the 'for' token is only legal inside parens when it is in a # generator expression. The parens are necessary here, so bail # without an error. elif token[1] == "for": return # A generator expression can have an 'else' token in it. # We check the rest of the tokens to see if any problems incur after # the 'else'. elif token[1] == "else": if "(" in (i.string for i in tokens[i:]): self._check_keyword_parentheses(tokens[i:], 0) return def _prepare_token_dispatcher(self): dispatch = {} for tokens, handler in ((_KEYWORD_TOKENS, self._check_keyword_parentheses),): for token in tokens: dispatch[token] = handler return dispatch def process_tokens(self, tokens): """Process tokens and search for : _ too long lines (i.e. longer than <max_chars>) _ optionally bad construct (if given, bad_construct must be a compiled regular expression). """ self._bracket_stack = [None] indents = [0] check_equal = _False line_num = 0 self._lines = {} self._visited_lines = {} token_handlers = self._prepare_token_dispatcher() self._last_line_ending = None last_blank_line_num = 0 for idx, (tok_type, token, start, _, line) in enumerate(tokens): if start[0] != line_num: line_num = start[0] # A tokenizer oddity: if an indented line contains a multi-line # docstring, the line member of the INDENT token does not contain # the full line; therefore we check the next token on the line. if tok_type == tokenize.INDENT: self.new_line(TokenWrapper(tokens), idx - 1, idx + 1) else: self.new_line(TokenWrapper(tokens), idx - 1, idx) if tok_type == tokenize.NEWLINE: # a program statement, or ENDMARKER, will eventually follow, # after some (possibly empty) run of tokens of the form # (NL | COMMENT)* (INDENT | DEDENT+)? # If an INDENT appears, setting check_equal is wrong, and will # be undone when we see the INDENT. check_equal = _True self._check_line_ending(token, line_num) elif tok_type == tokenize.INDENT: check_equal = _False self.check_indent_level(token, indents[-1] + 1, line_num) indents.append(indents[-1] + 1) elif tok_type == tokenize.DEDENT: # there's nothing we need to check here! what's important is # that when the run of DEDENTs ends, the indentation of the # program statement (or ENDMARKER) that triggered the run is # equal to what's left at the top of the indents stack check_equal = _True if len(indents) > 1: del indents[-1] elif tok_type == tokenize.NL: if not line.strip("\r\n"): last_blank_line_num = line_num elif tok_type not in (tokenize.COMMENT, tokenize.ENCODING): # This is the first concrete token following a NEWLINE, so it # must be the first token of the next program statement, or an # ENDMARKER; the "line" argument exposes the leading whitespace # for this statement; in the case of ENDMARKER, line is an empty # string, so will properly match the empty string with which the # "indents" stack was seeded if check_equal: check_equal = _False self.check_indent_level(line, indents[-1], line_num) if tok_type == tokenize.NUMBER and token.endswith("l"): self.add_message("lowercase-l-suffix", line=line_num) try: handler = token_handlers[token] except KeyError: pass else: handler(tokens, idx) line_num -= 1 # to be ok with "wc -l" if line_num > self.config.max_module_lines: # Get the line where the too-many-lines (or its message id) # was disabled or default to 1. message_definition = self.linter.msgs_store.get_message_definitions( "too-many-lines" )[0] names = (message_definition.msgid, "too-many-lines") line = next( filter(None, (self.linter._pragma_lineno.get(name) for name in names)), 1, ) self.add_message( "too-many-lines", args=(line_num, self.config.max_module_lines), line=line, ) # See if there are any trailing lines. Do not complain about empty # files like __init__.py markers. if line_num == last_blank_line_num and line_num > 0: self.add_message("trailing-newlines", line=line_num) def _check_line_ending(self, line_ending, line_num): # check if line endings are mixed if self._last_line_ending is not None: # line_ending == "" indicates a synthetic newline added at # the end of a file that does not, in fact, end with a # newline. if line_ending and line_ending != self._last_line_ending: self.add_message("mixed-line-endings", line=line_num) self._last_line_ending = line_ending # check if line ending is as expected expected = self.config.expected_line_ending_format if expected: # reduce multiple \n\n\n\n to one \n line_ending = reduce(lambda x, y: x + y if x != y else x, line_ending, "") line_ending = "LF" if line_ending == "\n" else "CRLF" if line_ending != expected: self.add_message( "unexpected-line-ending-format", args=(line_ending, expected), line=line_num, ) @check_messages("multiple-statements") def visit_default(self, node: nodes.NodeNG) -> None: """Check the node line number and check it if not yet done.""" if not node.is_statement: return if not node.root().pure_python: return prev_sibl = node.previous_sibling() if prev_sibl is not None: prev_line = prev_sibl.fromlineno # The line on which a 'finally': occurs in a 'try/finally' # is not directly represented in the AST. We infer it # by taking the last line of the body and adding 1, which # should be the line of finally: elif ( isinstance(node.parent, nodes.TryFinally) and node in node.parent.finalbody ): prev_line = node.parent.body[0].tolineno + 1 elif isinstance(node.parent, nodes.Module): prev_line = 0 else: prev_line = node.parent.statement(future=_True).fromlineno line = node.fromlineno assert line, node if prev_line == line and self._visited_lines.get(line) != 2: self._check_multi_statement_line(node, line) return if line in self._visited_lines: return try: tolineno = node.blockstart_tolineno except AttributeError: tolineno = node.tolineno assert tolineno, node lines = [] for line in range(line, tolineno + 1): self._visited_lines[line] = 1 try: lines.append(self._lines[line].rstrip()) except KeyError: lines.append("") def _check_multi_statement_line(self, node, line): """Check for lines containing multiple statements.""" # Do not warn about multiple nested context managers # in with statements. if isinstance(node, nodes.With): return # For try... except... finally..., the two nodes # appear to be on the same line due to how the AST is built. if isinstance(node, nodes.TryExcept) and isinstance( node.parent, nodes.TryFinally ): return if ( isinstance(node.parent, nodes.If) and not node.parent.orelse and self.config.single_line_if_stmt ): return if ( isinstance(node.parent, nodes.ClassDef) and len(node.parent.body) == 1 and self.config.single_line_class_stmt ): return # Function overloads that use ``Ellipsis`` are exempted. if ( isinstance(node, nodes.Expr) and isinstance(node.value, nodes.Const) and node.value.value is Ellipsis ): frame = node.frame(future=_True) if is_overload_stub(frame) or is_protocol_class(node_frame_class(frame)): return self.add_message("multiple-statements", node=node) self._visited_lines[line] = 2 def check_line_ending(self, line: str, i: int) -> None: """Check that the final newline is not missing and that there is no trailing whitespace.""" if not line.endswith("\n"): self.add_message("missing-final-newline", line=i) return # exclude \f (formfeed) from the rstrip stripped_line = line.rstrip("\t\n\r\v ") if line[len(stripped_line) :] not in ("\n", "\r\n"): self.add_message( "trailing-whitespace", line=i, col_offset=len(stripped_line) ) def check_line_length(self, line: str, i: int, checker_off: bool) -> None: """Check that the line length is less than the authorized value.""" max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines line = line.rstrip() if len(line) > max_chars and not ignore_long_line.search(line): if checker_off: self.linter.add_ignored_message("line-too-long", i) else: self.add_message("line-too-long", line=i, args=(len(line), max_chars)) @staticmethod def remove_pylint_option_from_lines(options_pattern_obj) -> str: """Remove the `# pylint ...` pattern from lines.""" lines = options_pattern_obj.string purged_lines = ( lines[: options_pattern_obj.start(1)].rstrip() + lines[options_pattern_obj.end(1) :] ) return purged_lines @staticmethod def is_line_length_check_activated(pylint_pattern_match_object) -> bool: """Return true if the line length check is activated.""" try: for pragma in parse_pragma(pylint_pattern_match_object.group(2)): if pragma.action == "disable" and "line-too-long" in pragma.messages: return _False except PragmaParserError: # Printing useful information dealing with this error is done in the lint package pass return _True @staticmethod def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
351
_last_token_on_line_is
ref
function
if _last_token_on_line_is(tokens, line_end, ";"):
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
352
add_message
ref
function
self.add_message("unnecessary-semicolon", line=tokens.start_line(line_end))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
352
start_line
ref
function
self.add_message("unnecessary-semicolon", line=tokens.start_line(line_end))
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
354
start_line
ref
function
line_num = tokens.start_line(line_start)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
355
line
ref
function
line = tokens.line(line_start)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
358
check_lines
ref
function
self.check_lines(line, line_num)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
360
process_module
def
function
def process_module(self, _node: nodes.Module) -> None: pass def _check_keyword_parentheses( self, tokens: List[tokenize.TokenInfo], start: int ) -> None: """Check that there are not unnecessary parentheses after a keyword. Parens are unnecessary if there is exactly one balanced outer pair on a line, and it is followed by a colon, and contains no commas (i.e. is not a tuple). Args: tokens: list of Tokens; the entire list of Tokens. start: int; the position of the keyword in the token list. """ # If the next token is not a paren, we're fine. if self._bracket_stack[-1] == ":" and tokens[start].string == "for": self._bracket_stack.pop() if tokens[start + 1].string != "(": return found_and_or = _False contains_walrus_operator = _False walrus_operator_depth = 0 contains_double_parens = 0 depth = 0 keyword_token = str(tokens[start].string) line_num = tokens[start].start[0] for i in range(start, len(tokens) - 1): token = tokens[i] # If we hit a newline, then assume any parens were for continuation. if token.type == tokenize.NL: return # Since the walrus operator doesn't exist below python3.8, the tokenizer # generates independent tokens if ( token.string == ":=" # <-- python3.8+ path or token.string + tokens[i + 1].string == ":=" ): contains_walrus_operator = _True walrus_operator_depth = depth if token.string == "(": depth += 1 if tokens[i + 1].string == "(": contains_double_parens = 1 elif token.string == ")": depth -= 1 if depth: if contains_double_parens and tokens[i + 1].string == ")": # For walrus operators in `if (not)` conditions and comprehensions if keyword_token in {"in", "if", "not"}: continue return contains_double_parens -= 1 continue # ')' can't happen after if (foo), since it would be a syntax error. if tokens[i + 1].string in {":", ")", "]", "}", "in"} or tokens[ i + 1 ].type in {tokenize.NEWLINE, tokenize.ENDMARKER, tokenize.COMMENT}: if contains_walrus_operator and walrus_operator_depth - 1 == depth: return # The empty tuple () is always accepted. if i == start + 2: return if keyword_token == "not": if not found_and_or: self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) elif keyword_token in {"return", "yield"}: self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) elif not found_and_or and keyword_token != "in": self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) return elif depth == 1: # This is a tuple, which is always acceptable. if token[1] == ",": return # 'and' and 'or' are the only boolean operators with lower precedence # than 'not', so parens are only required when they are found. if token[1] in {"and", "or"}: found_and_or = _True # A yield inside an expression must always be in parentheses, # quit early without error. elif token[1] == "yield": return # A generator expression always has a 'for' token in it, and # the 'for' token is only legal inside parens when it is in a # generator expression. The parens are necessary here, so bail # without an error. elif token[1] == "for": return # A generator expression can have an 'else' token in it. # We check the rest of the tokens to see if any problems incur after # the 'else'. elif token[1] == "else": if "(" in (i.string for i in tokens[i:]): self._check_keyword_parentheses(tokens[i:], 0) return def _prepare_token_dispatcher(self): dispatch = {} for tokens, handler in ((_KEYWORD_TOKENS, self._check_keyword_parentheses),): for token in tokens: dispatch[token] = handler return dispatch def process_tokens(self, tokens): """Process tokens and search for : _ too long lines (i.e. longer than <max_chars>) _ optionally bad construct (if given, bad_construct must be a compiled regular expression). """ self._bracket_stack = [None] indents = [0] check_equal = _False line_num = 0 self._lines = {} self._visited_lines = {} token_handlers = self._prepare_token_dispatcher() self._last_line_ending = None last_blank_line_num = 0 for idx, (tok_type, token, start, _, line) in enumerate(tokens): if start[0] != line_num: line_num = start[0] # A tokenizer oddity: if an indented line contains a multi-line # docstring, the line member of the INDENT token does not contain # the full line; therefore we check the next token on the line. if tok_type == tokenize.INDENT: self.new_line(TokenWrapper(tokens), idx - 1, idx + 1) else: self.new_line(TokenWrapper(tokens), idx - 1, idx) if tok_type == tokenize.NEWLINE: # a program statement, or ENDMARKER, will eventually follow, # after some (possibly empty) run of tokens of the form # (NL | COMMENT)* (INDENT | DEDENT+)? # If an INDENT appears, setting check_equal is wrong, and will # be undone when we see the INDENT. check_equal = _True self._check_line_ending(token, line_num) elif tok_type == tokenize.INDENT: check_equal = _False self.check_indent_level(token, indents[-1] + 1, line_num) indents.append(indents[-1] + 1) elif tok_type == tokenize.DEDENT: # there's nothing we need to check here! what's important is # that when the run of DEDENTs ends, the indentation of the # program statement (or ENDMARKER) that triggered the run is # equal to what's left at the top of the indents stack check_equal = _True if len(indents) > 1: del indents[-1] elif tok_type == tokenize.NL: if not line.strip("\r\n"): last_blank_line_num = line_num elif tok_type not in (tokenize.COMMENT, tokenize.ENCODING): # This is the first concrete token following a NEWLINE, so it # must be the first token of the next program statement, or an # ENDMARKER; the "line" argument exposes the leading whitespace # for this statement; in the case of ENDMARKER, line is an empty # string, so will properly match the empty string with which the # "indents" stack was seeded if check_equal: check_equal = _False self.check_indent_level(line, indents[-1], line_num) if tok_type == tokenize.NUMBER and token.endswith("l"): self.add_message("lowercase-l-suffix", line=line_num) try: handler = token_handlers[token] except KeyError: pass else: handler(tokens, idx) line_num -= 1 # to be ok with "wc -l" if line_num > self.config.max_module_lines: # Get the line where the too-many-lines (or its message id) # was disabled or default to 1. message_definition = self.linter.msgs_store.get_message_definitions( "too-many-lines" )[0] names = (message_definition.msgid, "too-many-lines") line = next( filter(None, (self.linter._pragma_lineno.get(name) for name in names)), 1, ) self.add_message( "too-many-lines", args=(line_num, self.config.max_module_lines), line=line, ) # See if there are any trailing lines. Do not complain about empty # files like __init__.py markers. if line_num == last_blank_line_num and line_num > 0: self.add_message("trailing-newlines", line=line_num) def _check_line_ending(self, line_ending, line_num): # check if line endings are mixed if self._last_line_ending is not None: # line_ending == "" indicates a synthetic newline added at # the end of a file that does not, in fact, end with a # newline. if line_ending and line_ending != self._last_line_ending: self.add_message("mixed-line-endings", line=line_num) self._last_line_ending = line_ending # check if line ending is as expected expected = self.config.expected_line_ending_format if expected: # reduce multiple \n\n\n\n to one \n line_ending = reduce(lambda x, y: x + y if x != y else x, line_ending, "") line_ending = "LF" if line_ending == "\n" else "CRLF" if line_ending != expected: self.add_message( "unexpected-line-ending-format", args=(line_ending, expected), line=line_num, ) @check_messages("multiple-statements") def visit_default(self, node: nodes.NodeNG) -> None: """Check the node line number and check it if not yet done.""" if not node.is_statement: return if not node.root().pure_python: return prev_sibl = node.previous_sibling() if prev_sibl is not None: prev_line = prev_sibl.fromlineno # The line on which a 'finally': occurs in a 'try/finally' # is not directly represented in the AST. We infer it # by taking the last line of the body and adding 1, which # should be the line of finally: elif ( isinstance(node.parent, nodes.TryFinally) and node in node.parent.finalbody ): prev_line = node.parent.body[0].tolineno + 1 elif isinstance(node.parent, nodes.Module): prev_line = 0 else: prev_line = node.parent.statement(future=_True).fromlineno line = node.fromlineno assert line, node if prev_line == line and self._visited_lines.get(line) != 2: self._check_multi_statement_line(node, line) return if line in self._visited_lines: return try: tolineno = node.blockstart_tolineno except AttributeError: tolineno = node.tolineno assert tolineno, node lines = [] for line in range(line, tolineno + 1): self._visited_lines[line] = 1 try: lines.append(self._lines[line].rstrip()) except KeyError: lines.append("") def _check_multi_statement_line(self, node, line): """Check for lines containing multiple statements.""" # Do not warn about multiple nested context managers # in with statements. if isinstance(node, nodes.With): return # For try... except... finally..., the two nodes # appear to be on the same line due to how the AST is built. if isinstance(node, nodes.TryExcept) and isinstance( node.parent, nodes.TryFinally ): return if ( isinstance(node.parent, nodes.If) and not node.parent.orelse and self.config.single_line_if_stmt ): return if ( isinstance(node.parent, nodes.ClassDef) and len(node.parent.body) == 1 and self.config.single_line_class_stmt ): return # Function overloads that use ``Ellipsis`` are exempted. if ( isinstance(node, nodes.Expr) and isinstance(node.value, nodes.Const) and node.value.value is Ellipsis ): frame = node.frame(future=_True) if is_overload_stub(frame) or is_protocol_class(node_frame_class(frame)): return self.add_message("multiple-statements", node=node) self._visited_lines[line] = 2 def check_line_ending(self, line: str, i: int) -> None: """Check that the final newline is not missing and that there is no trailing whitespace.""" if not line.endswith("\n"): self.add_message("missing-final-newline", line=i) return # exclude \f (formfeed) from the rstrip stripped_line = line.rstrip("\t\n\r\v ") if line[len(stripped_line) :] not in ("\n", "\r\n"): self.add_message( "trailing-whitespace", line=i, col_offset=len(stripped_line) ) def check_line_length(self, line: str, i: int, checker_off: bool) -> None: """Check that the line length is less than the authorized value.""" max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines line = line.rstrip() if len(line) > max_chars and not ignore_long_line.search(line): if checker_off: self.linter.add_ignored_message("line-too-long", i) else: self.add_message("line-too-long", line=i, args=(len(line), max_chars)) @staticmethod def remove_pylint_option_from_lines(options_pattern_obj) -> str: """Remove the `# pylint ...` pattern from lines.""" lines = options_pattern_obj.string purged_lines = ( lines[: options_pattern_obj.start(1)].rstrip() + lines[options_pattern_obj.end(1) :] ) return purged_lines @staticmethod def is_line_length_check_activated(pylint_pattern_match_object) -> bool: """Return true if the line length check is activated.""" try: for pragma in parse_pragma(pylint_pattern_match_object.group(2)): if pragma.action == "disable" and "line-too-long" in pragma.messages: return _False except PragmaParserError: # Printing useful information dealing with this error is done in the lint package pass return _True @staticmethod def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
363
_check_keyword_parentheses
def
function
def _check_keyword_parentheses( self, tokens: List[tokenize.TokenInfo], start: int ) -> None: """Check that there are not unnecessary parentheses after a keyword. Parens are unnecessary if there is exactly one balanced outer pair on a line, and it is followed by a colon, and contains no commas (i.e. is not a tuple). Args: tokens: list of Tokens; the entire list of Tokens. start: int; the position of the keyword in the token list. """ # If the next token is not a paren, we're fine. if self._bracket_stack[-1] == ":" and tokens[start].string == "for": self._bracket_stack.pop() if tokens[start + 1].string != "(": return found_and_or = _False contains_walrus_operator = _False walrus_operator_depth = 0 contains_double_parens = 0 depth = 0 keyword_token = str(tokens[start].string) line_num = tokens[start].start[0] for i in range(start, len(tokens) - 1): token = tokens[i] # If we hit a newline, then assume any parens were for continuation. if token.type == tokenize.NL: return # Since the walrus operator doesn't exist below python3.8, the tokenizer # generates independent tokens if ( token.string == ":=" # <-- python3.8+ path or token.string + tokens[i + 1].string == ":=" ): contains_walrus_operator = _True walrus_operator_depth = depth if token.string == "(": depth += 1 if tokens[i + 1].string == "(": contains_double_parens = 1 elif token.string == ")": depth -= 1 if depth: if contains_double_parens and tokens[i + 1].string == ")": # For walrus operators in `if (not)` conditions and comprehensions if keyword_token in {"in", "if", "not"}: continue return contains_double_parens -= 1 continue # ')' can't happen after if (foo), since it would be a syntax error. if tokens[i + 1].string in {":", ")", "]", "}", "in"} or tokens[ i + 1 ].type in {tokenize.NEWLINE, tokenize.ENDMARKER, tokenize.COMMENT}: if contains_walrus_operator and walrus_operator_depth - 1 == depth: return # The empty tuple () is always accepted. if i == start + 2: return if keyword_token == "not": if not found_and_or: self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) elif keyword_token in {"return", "yield"}: self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) elif not found_and_or and keyword_token != "in": self.add_message( "superfluous-parens", line=line_num, args=keyword_token ) return elif depth == 1: # This is a tuple, which is always acceptable. if token[1] == ",": return # 'and' and 'or' are the only boolean operators with lower precedence # than 'not', so parens are only required when they are found. if token[1] in {"and", "or"}: found_and_or = _True # A yield inside an expression must always be in parentheses, # quit early without error. elif token[1] == "yield": return # A generator expression always has a 'for' token in it, and # the 'for' token is only legal inside parens when it is in a # generator expression. The parens are necessary here, so bail # without an error. elif token[1] == "for": return # A generator expression can have an 'else' token in it. # We check the rest of the tokens to see if any problems incur after # the 'else'. elif token[1] == "else": if "(" in (i.string for i in tokens[i:]): self._check_keyword_parentheses(tokens[i:], 0) return def _prepare_token_dispatcher(self): dispatch = {} for tokens, handler in ((_KEYWORD_TOKENS, self._check_keyword_parentheses),): for token in tokens: dispatch[token] = handler return dispatch def process_tokens(self, tokens): """Process tokens and search for : _ too long lines (i.e. longer than <max_chars>) _ optionally bad construct (if given, bad_construct must be a compiled regular expression). """ self._bracket_stack = [None] indents = [0] check_equal = _False line_num = 0 self._lines = {} self._visited_lines = {} token_handlers = self._prepare_token_dispatcher() self._last_line_ending = None last_blank_line_num = 0 for idx, (tok_type, token, start, _, line) in enumerate(tokens): if start[0] != line_num: line_num = start[0] # A tokenizer oddity: if an indented line contains a multi-line # docstring, the line member of the INDENT token does not contain # the full line; therefore we check the next token on the line. if tok_type == tokenize.INDENT: self.new_line(TokenWrapper(tokens), idx - 1, idx + 1) else: self.new_line(TokenWrapper(tokens), idx - 1, idx) if tok_type == tokenize.NEWLINE: # a program statement, or ENDMARKER, will eventually follow, # after some (possibly empty) run of tokens of the form # (NL | COMMENT)* (INDENT | DEDENT+)? # If an INDENT appears, setting check_equal is wrong, and will # be undone when we see the INDENT. check_equal = _True self._check_line_ending(token, line_num) elif tok_type == tokenize.INDENT: check_equal = _False self.check_indent_level(token, indents[-1] + 1, line_num) indents.append(indents[-1] + 1) elif tok_type == tokenize.DEDENT: # there's nothing we need to check here! what's important is # that when the run of DEDENTs ends, the indentation of the # program statement (or ENDMARKER) that triggered the run is # equal to what's left at the top of the indents stack check_equal = _True if len(indents) > 1: del indents[-1] elif tok_type == tokenize.NL: if not line.strip("\r\n"): last_blank_line_num = line_num elif tok_type not in (tokenize.COMMENT, tokenize.ENCODING): # This is the first concrete token following a NEWLINE, so it # must be the first token of the next program statement, or an # ENDMARKER; the "line" argument exposes the leading whitespace # for this statement; in the case of ENDMARKER, line is an empty # string, so will properly match the empty string with which the # "indents" stack was seeded if check_equal: check_equal = _False self.check_indent_level(line, indents[-1], line_num) if tok_type == tokenize.NUMBER and token.endswith("l"): self.add_message("lowercase-l-suffix", line=line_num) try: handler = token_handlers[token] except KeyError: pass else: handler(tokens, idx) line_num -= 1 # to be ok with "wc -l" if line_num > self.config.max_module_lines: # Get the line where the too-many-lines (or its message id) # was disabled or default to 1. message_definition = self.linter.msgs_store.get_message_definitions( "too-many-lines" )[0] names = (message_definition.msgid, "too-many-lines") line = next( filter(None, (self.linter._pragma_lineno.get(name) for name in names)), 1, ) self.add_message( "too-many-lines", args=(line_num, self.config.max_module_lines), line=line, ) # See if there are any trailing lines. Do not complain about empty # files like __init__.py markers. if line_num == last_blank_line_num and line_num > 0: self.add_message("trailing-newlines", line=line_num) def _check_line_ending(self, line_ending, line_num): # check if line endings are mixed if self._last_line_ending is not None: # line_ending == "" indicates a synthetic newline added at # the end of a file that does not, in fact, end with a # newline. if line_ending and line_ending != self._last_line_ending: self.add_message("mixed-line-endings", line=line_num) self._last_line_ending = line_ending # check if line ending is as expected expected = self.config.expected_line_ending_format if expected: # reduce multiple \n\n\n\n to one \n line_ending = reduce(lambda x, y: x + y if x != y else x, line_ending, "") line_ending = "LF" if line_ending == "\n" else "CRLF" if line_ending != expected: self.add_message( "unexpected-line-ending-format", args=(line_ending, expected), line=line_num, ) @check_messages("multiple-statements") def visit_default(self, node: nodes.NodeNG) -> None: """Check the node line number and check it if not yet done.""" if not node.is_statement: return if not node.root().pure_python: return prev_sibl = node.previous_sibling() if prev_sibl is not None: prev_line = prev_sibl.fromlineno # The line on which a 'finally': occurs in a 'try/finally' # is not directly represented in the AST. We infer it # by taking the last line of the body and adding 1, which # should be the line of finally: elif ( isinstance(node.parent, nodes.TryFinally) and node in node.parent.finalbody ): prev_line = node.parent.body[0].tolineno + 1 elif isinstance(node.parent, nodes.Module): prev_line = 0 else: prev_line = node.parent.statement(future=_True).fromlineno line = node.fromlineno assert line, node if prev_line == line and self._visited_lines.get(line) != 2: self._check_multi_statement_line(node, line) return if line in self._visited_lines: return try: tolineno = node.blockstart_tolineno except AttributeError: tolineno = node.tolineno assert tolineno, node lines = [] for line in range(line, tolineno + 1): self._visited_lines[line] = 1 try: lines.append(self._lines[line].rstrip()) except KeyError: lines.append("") def _check_multi_statement_line(self, node, line): """Check for lines containing multiple statements.""" # Do not warn about multiple nested context managers # in with statements. if isinstance(node, nodes.With): return # For try... except... finally..., the two nodes # appear to be on the same line due to how the AST is built. if isinstance(node, nodes.TryExcept) and isinstance( node.parent, nodes.TryFinally ): return if ( isinstance(node.parent, nodes.If) and not node.parent.orelse and self.config.single_line_if_stmt ): return if ( isinstance(node.parent, nodes.ClassDef) and len(node.parent.body) == 1 and self.config.single_line_class_stmt ): return # Function overloads that use ``Ellipsis`` are exempted. if ( isinstance(node, nodes.Expr) and isinstance(node.value, nodes.Const) and node.value.value is Ellipsis ): frame = node.frame(future=_True) if is_overload_stub(frame) or is_protocol_class(node_frame_class(frame)): return self.add_message("multiple-statements", node=node) self._visited_lines[line] = 2 def check_line_ending(self, line: str, i: int) -> None: """Check that the final newline is not missing and that there is no trailing whitespace.""" if not line.endswith("\n"): self.add_message("missing-final-newline", line=i) return # exclude \f (formfeed) from the rstrip stripped_line = line.rstrip("\t\n\r\v ") if line[len(stripped_line) :] not in ("\n", "\r\n"): self.add_message( "trailing-whitespace", line=i, col_offset=len(stripped_line) ) def check_line_length(self, line: str, i: int, checker_off: bool) -> None: """Check that the line length is less than the authorized value.""" max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines line = line.rstrip() if len(line) > max_chars and not ignore_long_line.search(line): if checker_off: self.linter.add_ignored_message("line-too-long", i) else: self.add_message("line-too-long", line=i, args=(len(line), max_chars)) @staticmethod def remove_pylint_option_from_lines(options_pattern_obj) -> str: """Remove the `# pylint ...` pattern from lines.""" lines = options_pattern_obj.string purged_lines = ( lines[: options_pattern_obj.start(1)].rstrip() + lines[options_pattern_obj.end(1) :] ) return purged_lines @staticmethod def is_line_length_check_activated(pylint_pattern_match_object) -> bool: """Return true if the line length check is activated.""" try: for pragma in parse_pragma(pylint_pattern_match_object.group(2)): if pragma.action == "disable" and "line-too-long" in pragma.messages: return _False except PragmaParserError: # Printing useful information dealing with this error is done in the lint package pass return _True @staticmethod def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
427
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
431
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
435
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
462
_check_keyword_parentheses
ref
function
self._check_keyword_parentheses(tokens[i:], 0)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
465
_prepare_token_dispatcher
def
function
def _prepare_token_dispatcher(self): dispatch = {} for tokens, handler in ((_KEYWORD_TOKENS, self._check_keyword_parentheses),): for token in tokens: dispatch[token] = handler return dispatch def process_tokens(self, tokens): """Process tokens and search for : _ too long lines (i.e. longer than <max_chars>) _ optionally bad construct (if given, bad_construct must be a compiled regular expression). """ self._bracket_stack = [None] indents = [0] check_equal = _False line_num = 0 self._lines = {} self._visited_lines = {} token_handlers = self._prepare_token_dispatcher() self._last_line_ending = None last_blank_line_num = 0 for idx, (tok_type, token, start, _, line) in enumerate(tokens): if start[0] != line_num: line_num = start[0] # A tokenizer oddity: if an indented line contains a multi-line # docstring, the line member of the INDENT token does not contain # the full line; therefore we check the next token on the line. if tok_type == tokenize.INDENT: self.new_line(TokenWrapper(tokens), idx - 1, idx + 1) else: self.new_line(TokenWrapper(tokens), idx - 1, idx) if tok_type == tokenize.NEWLINE: # a program statement, or ENDMARKER, will eventually follow, # after some (possibly empty) run of tokens of the form # (NL | COMMENT)* (INDENT | DEDENT+)? # If an INDENT appears, setting check_equal is wrong, and will # be undone when we see the INDENT. check_equal = _True self._check_line_ending(token, line_num) elif tok_type == tokenize.INDENT: check_equal = _False self.check_indent_level(token, indents[-1] + 1, line_num) indents.append(indents[-1] + 1) elif tok_type == tokenize.DEDENT: # there's nothing we need to check here! what's important is # that when the run of DEDENTs ends, the indentation of the # program statement (or ENDMARKER) that triggered the run is # equal to what's left at the top of the indents stack check_equal = _True if len(indents) > 1: del indents[-1] elif tok_type == tokenize.NL: if not line.strip("\r\n"): last_blank_line_num = line_num elif tok_type not in (tokenize.COMMENT, tokenize.ENCODING): # This is the first concrete token following a NEWLINE, so it # must be the first token of the next program statement, or an # ENDMARKER; the "line" argument exposes the leading whitespace # for this statement; in the case of ENDMARKER, line is an empty # string, so will properly match the empty string with which the # "indents" stack was seeded if check_equal: check_equal = _False self.check_indent_level(line, indents[-1], line_num) if tok_type == tokenize.NUMBER and token.endswith("l"): self.add_message("lowercase-l-suffix", line=line_num) try: handler = token_handlers[token] except KeyError: pass else: handler(tokens, idx) line_num -= 1 # to be ok with "wc -l" if line_num > self.config.max_module_lines: # Get the line where the too-many-lines (or its message id) # was disabled or default to 1. message_definition = self.linter.msgs_store.get_message_definitions( "too-many-lines" )[0] names = (message_definition.msgid, "too-many-lines") line = next( filter(None, (self.linter._pragma_lineno.get(name) for name in names)), 1, ) self.add_message( "too-many-lines", args=(line_num, self.config.max_module_lines), line=line, ) # See if there are any trailing lines. Do not complain about empty # files like __init__.py markers. if line_num == last_blank_line_num and line_num > 0: self.add_message("trailing-newlines", line=line_num) def _check_line_ending(self, line_ending, line_num): # check if line endings are mixed if self._last_line_ending is not None: # line_ending == "" indicates a synthetic newline added at # the end of a file that does not, in fact, end with a # newline. if line_ending and line_ending != self._last_line_ending: self.add_message("mixed-line-endings", line=line_num) self._last_line_ending = line_ending # check if line ending is as expected expected = self.config.expected_line_ending_format if expected: # reduce multiple \n\n\n\n to one \n line_ending = reduce(lambda x, y: x + y if x != y else x, line_ending, "") line_ending = "LF" if line_ending == "\n" else "CRLF" if line_ending != expected: self.add_message( "unexpected-line-ending-format", args=(line_ending, expected), line=line_num, ) @check_messages("multiple-statements") def visit_default(self, node: nodes.NodeNG) -> None: """Check the node line number and check it if not yet done.""" if not node.is_statement: return if not node.root().pure_python: return prev_sibl = node.previous_sibling() if prev_sibl is not None: prev_line = prev_sibl.fromlineno # The line on which a 'finally': occurs in a 'try/finally' # is not directly represented in the AST. We infer it # by taking the last line of the body and adding 1, which # should be the line of finally: elif ( isinstance(node.parent, nodes.TryFinally) and node in node.parent.finalbody ): prev_line = node.parent.body[0].tolineno + 1 elif isinstance(node.parent, nodes.Module): prev_line = 0 else: prev_line = node.parent.statement(future=_True).fromlineno line = node.fromlineno assert line, node if prev_line == line and self._visited_lines.get(line) != 2: self._check_multi_statement_line(node, line) return if line in self._visited_lines: return try: tolineno = node.blockstart_tolineno except AttributeError: tolineno = node.tolineno assert tolineno, node lines = [] for line in range(line, tolineno + 1): self._visited_lines[line] = 1 try: lines.append(self._lines[line].rstrip()) except KeyError: lines.append("") def _check_multi_statement_line(self, node, line): """Check for lines containing multiple statements.""" # Do not warn about multiple nested context managers # in with statements. if isinstance(node, nodes.With): return # For try... except... finally..., the two nodes # appear to be on the same line due to how the AST is built. if isinstance(node, nodes.TryExcept) and isinstance( node.parent, nodes.TryFinally ): return if ( isinstance(node.parent, nodes.If) and not node.parent.orelse and self.config.single_line_if_stmt ): return if ( isinstance(node.parent, nodes.ClassDef) and len(node.parent.body) == 1 and self.config.single_line_class_stmt ): return # Function overloads that use ``Ellipsis`` are exempted. if ( isinstance(node, nodes.Expr) and isinstance(node.value, nodes.Const) and node.value.value is Ellipsis ): frame = node.frame(future=_True) if is_overload_stub(frame) or is_protocol_class(node_frame_class(frame)): return self.add_message("multiple-statements", node=node) self._visited_lines[line] = 2 def check_line_ending(self, line: str, i: int) -> None: """Check that the final newline is not missing and that there is no trailing whitespace.""" if not line.endswith("\n"): self.add_message("missing-final-newline", line=i) return # exclude \f (formfeed) from the rstrip stripped_line = line.rstrip("\t\n\r\v ") if line[len(stripped_line) :] not in ("\n", "\r\n"): self.add_message( "trailing-whitespace", line=i, col_offset=len(stripped_line) ) def check_line_length(self, line: str, i: int, checker_off: bool) -> None: """Check that the line length is less than the authorized value.""" max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines line = line.rstrip() if len(line) > max_chars and not ignore_long_line.search(line): if checker_off: self.linter.add_ignored_message("line-too-long", i) else: self.add_message("line-too-long", line=i, args=(len(line), max_chars)) @staticmethod def remove_pylint_option_from_lines(options_pattern_obj) -> str: """Remove the `# pylint ...` pattern from lines.""" lines = options_pattern_obj.string purged_lines = ( lines[: options_pattern_obj.start(1)].rstrip() + lines[options_pattern_obj.end(1) :] ) return purged_lines @staticmethod def is_line_length_check_activated(pylint_pattern_match_object) -> bool: """Return true if the line length check is activated.""" try: for pragma in parse_pragma(pylint_pattern_match_object.group(2)): if pragma.action == "disable" and "line-too-long" in pragma.messages: return _False except PragmaParserError: # Printing useful information dealing with this error is done in the lint package pass return _True @staticmethod def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
472
process_tokens
def
function
def process_tokens(self, tokens): """Process tokens and search for : _ too long lines (i.e. longer than <max_chars>) _ optionally bad construct (if given, bad_construct must be a compiled regular expression). """ self._bracket_stack = [None] indents = [0] check_equal = _False line_num = 0 self._lines = {} self._visited_lines = {} token_handlers = self._prepare_token_dispatcher() self._last_line_ending = None last_blank_line_num = 0 for idx, (tok_type, token, start, _, line) in enumerate(tokens): if start[0] != line_num: line_num = start[0] # A tokenizer oddity: if an indented line contains a multi-line # docstring, the line member of the INDENT token does not contain # the full line; therefore we check the next token on the line. if tok_type == tokenize.INDENT: self.new_line(TokenWrapper(tokens), idx - 1, idx + 1) else: self.new_line(TokenWrapper(tokens), idx - 1, idx) if tok_type == tokenize.NEWLINE: # a program statement, or ENDMARKER, will eventually follow, # after some (possibly empty) run of tokens of the form # (NL | COMMENT)* (INDENT | DEDENT+)? # If an INDENT appears, setting check_equal is wrong, and will # be undone when we see the INDENT. check_equal = _True self._check_line_ending(token, line_num) elif tok_type == tokenize.INDENT: check_equal = _False self.check_indent_level(token, indents[-1] + 1, line_num) indents.append(indents[-1] + 1) elif tok_type == tokenize.DEDENT: # there's nothing we need to check here! what's important is # that when the run of DEDENTs ends, the indentation of the # program statement (or ENDMARKER) that triggered the run is # equal to what's left at the top of the indents stack check_equal = _True if len(indents) > 1: del indents[-1] elif tok_type == tokenize.NL: if not line.strip("\r\n"): last_blank_line_num = line_num elif tok_type not in (tokenize.COMMENT, tokenize.ENCODING): # This is the first concrete token following a NEWLINE, so it # must be the first token of the next program statement, or an # ENDMARKER; the "line" argument exposes the leading whitespace # for this statement; in the case of ENDMARKER, line is an empty # string, so will properly match the empty string with which the # "indents" stack was seeded if check_equal: check_equal = _False self.check_indent_level(line, indents[-1], line_num) if tok_type == tokenize.NUMBER and token.endswith("l"): self.add_message("lowercase-l-suffix", line=line_num) try: handler = token_handlers[token] except KeyError: pass else: handler(tokens, idx) line_num -= 1 # to be ok with "wc -l" if line_num > self.config.max_module_lines: # Get the line where the too-many-lines (or its message id) # was disabled or default to 1. message_definition = self.linter.msgs_store.get_message_definitions( "too-many-lines" )[0] names = (message_definition.msgid, "too-many-lines") line = next( filter(None, (self.linter._pragma_lineno.get(name) for name in names)), 1, ) self.add_message( "too-many-lines", args=(line_num, self.config.max_module_lines), line=line, ) # See if there are any trailing lines. Do not complain about empty # files like __init__.py markers. if line_num == last_blank_line_num and line_num > 0: self.add_message("trailing-newlines", line=line_num) def _check_line_ending(self, line_ending, line_num): # check if line endings are mixed if self._last_line_ending is not None: # line_ending == "" indicates a synthetic newline added at # the end of a file that does not, in fact, end with a # newline. if line_ending and line_ending != self._last_line_ending: self.add_message("mixed-line-endings", line=line_num) self._last_line_ending = line_ending # check if line ending is as expected expected = self.config.expected_line_ending_format if expected: # reduce multiple \n\n\n\n to one \n line_ending = reduce(lambda x, y: x + y if x != y else x, line_ending, "") line_ending = "LF" if line_ending == "\n" else "CRLF" if line_ending != expected: self.add_message( "unexpected-line-ending-format", args=(line_ending, expected), line=line_num, ) @check_messages("multiple-statements") def visit_default(self, node: nodes.NodeNG) -> None: """Check the node line number and check it if not yet done.""" if not node.is_statement: return if not node.root().pure_python: return prev_sibl = node.previous_sibling() if prev_sibl is not None: prev_line = prev_sibl.fromlineno # The line on which a 'finally': occurs in a 'try/finally' # is not directly represented in the AST. We infer it # by taking the last line of the body and adding 1, which # should be the line of finally: elif ( isinstance(node.parent, nodes.TryFinally) and node in node.parent.finalbody ): prev_line = node.parent.body[0].tolineno + 1 elif isinstance(node.parent, nodes.Module): prev_line = 0 else: prev_line = node.parent.statement(future=_True).fromlineno line = node.fromlineno assert line, node if prev_line == line and self._visited_lines.get(line) != 2: self._check_multi_statement_line(node, line) return if line in self._visited_lines: return try: tolineno = node.blockstart_tolineno except AttributeError: tolineno = node.tolineno assert tolineno, node lines = [] for line in range(line, tolineno + 1): self._visited_lines[line] = 1 try: lines.append(self._lines[line].rstrip()) except KeyError: lines.append("") def _check_multi_statement_line(self, node, line): """Check for lines containing multiple statements.""" # Do not warn about multiple nested context managers # in with statements. if isinstance(node, nodes.With): return # For try... except... finally..., the two nodes # appear to be on the same line due to how the AST is built. if isinstance(node, nodes.TryExcept) and isinstance( node.parent, nodes.TryFinally ): return if ( isinstance(node.parent, nodes.If) and not node.parent.orelse and self.config.single_line_if_stmt ): return if ( isinstance(node.parent, nodes.ClassDef) and len(node.parent.body) == 1 and self.config.single_line_class_stmt ): return # Function overloads that use ``Ellipsis`` are exempted. if ( isinstance(node, nodes.Expr) and isinstance(node.value, nodes.Const) and node.value.value is Ellipsis ): frame = node.frame(future=_True) if is_overload_stub(frame) or is_protocol_class(node_frame_class(frame)): return self.add_message("multiple-statements", node=node) self._visited_lines[line] = 2 def check_line_ending(self, line: str, i: int) -> None: """Check that the final newline is not missing and that there is no trailing whitespace.""" if not line.endswith("\n"): self.add_message("missing-final-newline", line=i) return # exclude \f (formfeed) from the rstrip stripped_line = line.rstrip("\t\n\r\v ") if line[len(stripped_line) :] not in ("\n", "\r\n"): self.add_message( "trailing-whitespace", line=i, col_offset=len(stripped_line) ) def check_line_length(self, line: str, i: int, checker_off: bool) -> None: """Check that the line length is less than the authorized value.""" max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines line = line.rstrip() if len(line) > max_chars and not ignore_long_line.search(line): if checker_off: self.linter.add_ignored_message("line-too-long", i) else: self.add_message("line-too-long", line=i, args=(len(line), max_chars)) @staticmethod def remove_pylint_option_from_lines(options_pattern_obj) -> str: """Remove the `# pylint ...` pattern from lines.""" lines = options_pattern_obj.string purged_lines = ( lines[: options_pattern_obj.start(1)].rstrip() + lines[options_pattern_obj.end(1) :] ) return purged_lines @staticmethod def is_line_length_check_activated(pylint_pattern_match_object) -> bool: """Return true if the line length check is activated.""" try: for pragma in parse_pragma(pylint_pattern_match_object.group(2)): if pragma.action == "disable" and "line-too-long" in pragma.messages: return _False except PragmaParserError: # Printing useful information dealing with this error is done in the lint package pass return _True @staticmethod def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
485
_prepare_token_dispatcher
ref
function
token_handlers = self._prepare_token_dispatcher()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
495
new_line
ref
function
self.new_line(TokenWrapper(tokens), idx - 1, idx + 1)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
495
TokenWrapper
ref
function
self.new_line(TokenWrapper(tokens), idx - 1, idx + 1)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
497
new_line
ref
function
self.new_line(TokenWrapper(tokens), idx - 1, idx)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
497
TokenWrapper
ref
function
self.new_line(TokenWrapper(tokens), idx - 1, idx)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
506
_check_line_ending
ref
function
self._check_line_ending(token, line_num)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
509
check_indent_level
ref
function
self.check_indent_level(token, indents[-1] + 1, line_num)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
531
check_indent_level
ref
function
self.check_indent_level(line, indents[-1], line_num)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
534
add_message
ref
function
self.add_message("lowercase-l-suffix", line=line_num)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
541
handler
ref
function
handler(tokens, idx)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
547
get_message_definitions
ref
function
message_definition = self.linter.msgs_store.get_message_definitions(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
555
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
564
add_message
ref
function
self.add_message("trailing-newlines", line=line_num)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
566
_check_line_ending
def
function
def _check_line_ending(self, line_ending, line_num): # check if line endings are mixed if self._last_line_ending is not None: # line_ending == "" indicates a synthetic newline added at # the end of a file that does not, in fact, end with a # newline. if line_ending and line_ending != self._last_line_ending: self.add_message("mixed-line-endings", line=line_num) self._last_line_ending = line_ending # check if line ending is as expected expected = self.config.expected_line_ending_format if expected: # reduce multiple \n\n\n\n to one \n line_ending = reduce(lambda x, y: x + y if x != y else x, line_ending, "") line_ending = "LF" if line_ending == "\n" else "CRLF" if line_ending != expected: self.add_message( "unexpected-line-ending-format", args=(line_ending, expected), line=line_num, ) @check_messages("multiple-statements") def visit_default(self, node: nodes.NodeNG) -> None: """Check the node line number and check it if not yet done.""" if not node.is_statement: return if not node.root().pure_python: return prev_sibl = node.previous_sibling() if prev_sibl is not None: prev_line = prev_sibl.fromlineno # The line on which a 'finally': occurs in a 'try/finally' # is not directly represented in the AST. We infer it # by taking the last line of the body and adding 1, which # should be the line of finally: elif ( isinstance(node.parent, nodes.TryFinally) and node in node.parent.finalbody ): prev_line = node.parent.body[0].tolineno + 1 elif isinstance(node.parent, nodes.Module): prev_line = 0 else: prev_line = node.parent.statement(future=_True).fromlineno line = node.fromlineno assert line, node if prev_line == line and self._visited_lines.get(line) != 2: self._check_multi_statement_line(node, line) return if line in self._visited_lines: return try: tolineno = node.blockstart_tolineno except AttributeError: tolineno = node.tolineno assert tolineno, node lines = [] for line in range(line, tolineno + 1): self._visited_lines[line] = 1 try: lines.append(self._lines[line].rstrip()) except KeyError: lines.append("") def _check_multi_statement_line(self, node, line): """Check for lines containing multiple statements.""" # Do not warn about multiple nested context managers # in with statements. if isinstance(node, nodes.With): return # For try... except... finally..., the two nodes # appear to be on the same line due to how the AST is built. if isinstance(node, nodes.TryExcept) and isinstance( node.parent, nodes.TryFinally ): return if ( isinstance(node.parent, nodes.If) and not node.parent.orelse and self.config.single_line_if_stmt ): return if ( isinstance(node.parent, nodes.ClassDef) and len(node.parent.body) == 1 and self.config.single_line_class_stmt ): return # Function overloads that use ``Ellipsis`` are exempted. if ( isinstance(node, nodes.Expr) and isinstance(node.value, nodes.Const) and node.value.value is Ellipsis ): frame = node.frame(future=_True) if is_overload_stub(frame) or is_protocol_class(node_frame_class(frame)): return self.add_message("multiple-statements", node=node) self._visited_lines[line] = 2 def check_line_ending(self, line: str, i: int) -> None: """Check that the final newline is not missing and that there is no trailing whitespace.""" if not line.endswith("\n"): self.add_message("missing-final-newline", line=i) return # exclude \f (formfeed) from the rstrip stripped_line = line.rstrip("\t\n\r\v ") if line[len(stripped_line) :] not in ("\n", "\r\n"): self.add_message( "trailing-whitespace", line=i, col_offset=len(stripped_line) ) def check_line_length(self, line: str, i: int, checker_off: bool) -> None: """Check that the line length is less than the authorized value.""" max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines line = line.rstrip() if len(line) > max_chars and not ignore_long_line.search(line): if checker_off: self.linter.add_ignored_message("line-too-long", i) else: self.add_message("line-too-long", line=i, args=(len(line), max_chars)) @staticmethod def remove_pylint_option_from_lines(options_pattern_obj) -> str: """Remove the `# pylint ...` pattern from lines.""" lines = options_pattern_obj.string purged_lines = ( lines[: options_pattern_obj.start(1)].rstrip() + lines[options_pattern_obj.end(1) :] ) return purged_lines @staticmethod def is_line_length_check_activated(pylint_pattern_match_object) -> bool: """Return true if the line length check is activated.""" try: for pragma in parse_pragma(pylint_pattern_match_object.group(2)): if pragma.action == "disable" and "line-too-long" in pragma.messages: return _False except PragmaParserError: # Printing useful information dealing with this error is done in the lint package pass return _True @staticmethod def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
573
add_message
ref
function
self.add_message("mixed-line-endings", line=line_num)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
584
add_message
ref
function
self.add_message(
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
590
check_messages
ref
function
@check_messages("multiple-statements")
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
591
visit_default
def
function
def visit_default(self, node: nodes.NodeNG) -> None: """Check the node line number and check it if not yet done.""" if not node.is_statement: return if not node.root().pure_python: return prev_sibl = node.previous_sibling() if prev_sibl is not None: prev_line = prev_sibl.fromlineno # The line on which a 'finally': occurs in a 'try/finally' # is not directly represented in the AST. We infer it # by taking the last line of the body and adding 1, which # should be the line of finally: elif ( isinstance(node.parent, nodes.TryFinally) and node in node.parent.finalbody ): prev_line = node.parent.body[0].tolineno + 1 elif isinstance(node.parent, nodes.Module): prev_line = 0 else: prev_line = node.parent.statement(future=_True).fromlineno line = node.fromlineno assert line, node if prev_line == line and self._visited_lines.get(line) != 2: self._check_multi_statement_line(node, line) return if line in self._visited_lines: return try: tolineno = node.blockstart_tolineno except AttributeError: tolineno = node.tolineno assert tolineno, node lines = [] for line in range(line, tolineno + 1): self._visited_lines[line] = 1 try: lines.append(self._lines[line].rstrip()) except KeyError: lines.append("") def _check_multi_statement_line(self, node, line): """Check for lines containing multiple statements.""" # Do not warn about multiple nested context managers # in with statements. if isinstance(node, nodes.With): return # For try... except... finally..., the two nodes # appear to be on the same line due to how the AST is built. if isinstance(node, nodes.TryExcept) and isinstance( node.parent, nodes.TryFinally ): return if ( isinstance(node.parent, nodes.If) and not node.parent.orelse and self.config.single_line_if_stmt ): return if ( isinstance(node.parent, nodes.ClassDef) and len(node.parent.body) == 1 and self.config.single_line_class_stmt ): return # Function overloads that use ``Ellipsis`` are exempted. if ( isinstance(node, nodes.Expr) and isinstance(node.value, nodes.Const) and node.value.value is Ellipsis ): frame = node.frame(future=_True) if is_overload_stub(frame) or is_protocol_class(node_frame_class(frame)): return self.add_message("multiple-statements", node=node) self._visited_lines[line] = 2 def check_line_ending(self, line: str, i: int) -> None: """Check that the final newline is not missing and that there is no trailing whitespace.""" if not line.endswith("\n"): self.add_message("missing-final-newline", line=i) return # exclude \f (formfeed) from the rstrip stripped_line = line.rstrip("\t\n\r\v ") if line[len(stripped_line) :] not in ("\n", "\r\n"): self.add_message( "trailing-whitespace", line=i, col_offset=len(stripped_line) ) def check_line_length(self, line: str, i: int, checker_off: bool) -> None: """Check that the line length is less than the authorized value.""" max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines line = line.rstrip() if len(line) > max_chars and not ignore_long_line.search(line): if checker_off: self.linter.add_ignored_message("line-too-long", i) else: self.add_message("line-too-long", line=i, args=(len(line), max_chars)) @staticmethod def remove_pylint_option_from_lines(options_pattern_obj) -> str: """Remove the `# pylint ...` pattern from lines.""" lines = options_pattern_obj.string purged_lines = ( lines[: options_pattern_obj.start(1)].rstrip() + lines[options_pattern_obj.end(1) :] ) return purged_lines @staticmethod def is_line_length_check_activated(pylint_pattern_match_object) -> bool: """Return true if the line length check is activated.""" try: for pragma in parse_pragma(pylint_pattern_match_object.group(2)): if pragma.action == "disable" and "line-too-long" in pragma.messages: return _False except PragmaParserError: # Printing useful information dealing with this error is done in the lint package pass return _True @staticmethod def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
595
root
ref
function
if not node.root().pure_python:
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
597
previous_sibling
ref
function
prev_sibl = node.previous_sibling()
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
611
statement
ref
function
prev_line = node.parent.statement(future=True).fromlineno
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
615
_check_multi_statement_line
ref
function
self._check_multi_statement_line(node, line)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
632
_check_multi_statement_line
def
function
def _check_multi_statement_line(self, node, line): """Check for lines containing multiple statements.""" # Do not warn about multiple nested context managers # in with statements. if isinstance(node, nodes.With): return # For try... except... finally..., the two nodes # appear to be on the same line due to how the AST is built. if isinstance(node, nodes.TryExcept) and isinstance( node.parent, nodes.TryFinally ): return if ( isinstance(node.parent, nodes.If) and not node.parent.orelse and self.config.single_line_if_stmt ): return if ( isinstance(node.parent, nodes.ClassDef) and len(node.parent.body) == 1 and self.config.single_line_class_stmt ): return # Function overloads that use ``Ellipsis`` are exempted. if ( isinstance(node, nodes.Expr) and isinstance(node.value, nodes.Const) and node.value.value is Ellipsis ): frame = node.frame(future=_True) if is_overload_stub(frame) or is_protocol_class(node_frame_class(frame)): return self.add_message("multiple-statements", node=node) self._visited_lines[line] = 2 def check_line_ending(self, line: str, i: int) -> None: """Check that the final newline is not missing and that there is no trailing whitespace.""" if not line.endswith("\n"): self.add_message("missing-final-newline", line=i) return # exclude \f (formfeed) from the rstrip stripped_line = line.rstrip("\t\n\r\v ") if line[len(stripped_line) :] not in ("\n", "\r\n"): self.add_message( "trailing-whitespace", line=i, col_offset=len(stripped_line) ) def check_line_length(self, line: str, i: int, checker_off: bool) -> None: """Check that the line length is less than the authorized value.""" max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines line = line.rstrip() if len(line) > max_chars and not ignore_long_line.search(line): if checker_off: self.linter.add_ignored_message("line-too-long", i) else: self.add_message("line-too-long", line=i, args=(len(line), max_chars)) @staticmethod def remove_pylint_option_from_lines(options_pattern_obj) -> str: """Remove the `# pylint ...` pattern from lines.""" lines = options_pattern_obj.string purged_lines = ( lines[: options_pattern_obj.start(1)].rstrip() + lines[options_pattern_obj.end(1) :] ) return purged_lines @staticmethod def is_line_length_check_activated(pylint_pattern_match_object) -> bool: """Return true if the line length check is activated.""" try: for pragma in parse_pragma(pylint_pattern_match_object.group(2)): if pragma.action == "disable" and "line-too-long" in pragma.messages: return _False except PragmaParserError: # Printing useful information dealing with this error is done in the lint package pass return _True @staticmethod def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
663
frame
ref
function
frame = node.frame(future=True)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
664
is_overload_stub
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
664
is_protocol_class
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
664
node_frame_class
ref
class
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
667
add_message
ref
function
self.add_message("multiple-statements", node=node)
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
670
check_line_ending
def
function
def check_line_ending(self, line: str, i: int) -> None: """Check that the final newline is not missing and that there is no trailing whitespace.""" if not line.endswith("\n"): self.add_message("missing-final-newline", line=i) return # exclude \f (formfeed) from the rstrip stripped_line = line.rstrip("\t\n\r\v ") if line[len(stripped_line) :] not in ("\n", "\r\n"): self.add_message( "trailing-whitespace", line=i, col_offset=len(stripped_line) ) def check_line_length(self, line: str, i: int, checker_off: bool) -> None: """Check that the line length is less than the authorized value.""" max_chars = self.config.max_line_length ignore_long_line = self.config.ignore_long_lines line = line.rstrip() if len(line) > max_chars and not ignore_long_line.search(line): if checker_off: self.linter.add_ignored_message("line-too-long", i) else: self.add_message("line-too-long", line=i, args=(len(line), max_chars)) @staticmethod def remove_pylint_option_from_lines(options_pattern_obj) -> str: """Remove the `# pylint ...` pattern from lines.""" lines = options_pattern_obj.string purged_lines = ( lines[: options_pattern_obj.start(1)].rstrip() + lines[options_pattern_obj.end(1) :] ) return purged_lines @staticmethod def is_line_length_check_activated(pylint_pattern_match_object) -> bool: """Return true if the line length check is activated.""" try: for pragma in parse_pragma(pylint_pattern_match_object.group(2)): if pragma.action == "disable" and "line-too-long" in pragma.messages: return _False except PragmaParserError: # Printing useful information dealing with this error is done in the lint package pass return _True @staticmethod def specific_splitlines(lines: str) -> List[str]: """Split lines according to universal newlines except those in a specific sets.""" unsplit_ends = { "\v", "\x0b", "\f", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029", } res = [] buffer = "" for atomic_line in lines.splitlines(_True): if atomic_line[-1] not in unsplit_ends: res.append(buffer + atomic_line) buffer = "" else: buffer += atomic_line return res def check_lines(self, lines: str, lineno: int) -> None: """Check lines have : - a final newline - no trailing whitespace - less than a maximum number of characters """ # we're first going to do a rough check whether any lines in this set # go over the line limit. If none of them do, then we don't need to # parse out the pylint options later on and can just assume that these # lines are clean # we'll also handle the line ending check here to avoid double-iteration # unless the line lengths are suspect max_chars = self.config.max_line_length split_lines = self.specific_splitlines(lines) for offset, line in enumerate(split_lines): self.check_line_ending(line, lineno + offset) # hold onto the initial lineno for later potential_line_length_warning = _False for offset, line in enumerate(split_lines): # this check is purposefully simple and doesn't rstrip # since this is running on every line you're checking it's # advantageous to avoid doing a lot of work if len(line) > max_chars: potential_line_length_warning = _True break # if there were no lines passing the max_chars config, we don't bother # running the full line check (as we've met an even more strict condition) if not potential_line_length_warning: return # Line length check may be deactivated through `pylint: disable` comment mobj = OPTION_PO.search(lines) checker_off = _False if mobj: if not self.is_line_length_check_activated(mobj): checker_off = _True # The 'pylint: disable whatever' should not be taken into account for line length count lines = self.remove_pylint_option_from_lines(mobj) # here we re-run specific_splitlines since we have filtered out pylint options above for offset, line in enumerate(self.specific_splitlines(lines)): self.check_line_length(line, lineno + offset, checker_off) def check_indent_level(self, string, expected, line_num): """Return the indent level of the string.""" indent = self.config.indent_string if indent == "\\t": # \t is not interpreted in the configuration file indent = "\t" level = 0 unit_size = len(indent) while string[:unit_size] == indent: string = string[unit_size:] level += 1 suppl = "" while string and string[0] in " \t": suppl += string[0] string = string[1:] if level != expected or suppl: i_type = "spaces" if indent[0] == "\t": i_type = "tabs" self.add_message( "bad-indentation", line=line_num, args=(level * unit_size + len(suppl), i_type, expected * unit_size), )
playground/e9b22a58-260b-483f-88d7-7a5fe9f8b1d4/pylint/pylint/checkers/format.py
pylint/checkers/format.py
673
add_message
ref
function
self.add_message("missing-final-newline", line=i)