errors.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  1. from __future__ import annotations
  2. import os.path
  3. import sys
  4. import traceback
  5. from collections import defaultdict
  6. from typing import Callable, Final, Iterable, NoReturn, Optional, TextIO, Tuple, TypeVar
  7. from typing_extensions import Literal, TypeAlias as _TypeAlias
  8. from mypy import errorcodes as codes
  9. from mypy.errorcodes import IMPORT, ErrorCode
  10. from mypy.message_registry import ErrorMessage
  11. from mypy.options import Options
  12. from mypy.scope import Scope
  13. from mypy.util import DEFAULT_SOURCE_OFFSET, is_typeshed_file
  14. from mypy.version import __version__ as mypy_version
  15. T = TypeVar("T")
  16. # Show error codes for some note-level messages (these usually appear alone
  17. # and not as a comment for a previous error-level message).
  18. SHOW_NOTE_CODES: Final = {codes.ANNOTATION_UNCHECKED}
  19. # Do not add notes with links to error code docs to errors with these codes.
  20. # We can tweak this set as we get more experience about what is helpful and what is not.
  21. HIDE_LINK_CODES: Final = {
  22. # This is a generic error code, so it has no useful docs
  23. codes.MISC,
  24. # These are trivial and have some custom notes (e.g. for list being invariant)
  25. codes.ASSIGNMENT,
  26. codes.ARG_TYPE,
  27. codes.RETURN_VALUE,
  28. # Undefined name/attribute errors are self-explanatory
  29. codes.ATTR_DEFINED,
  30. codes.NAME_DEFINED,
  31. # Overrides have a custom link to docs
  32. codes.OVERRIDE,
  33. }
  34. allowed_duplicates: Final = ["@overload", "Got:", "Expected:"]
  35. BASE_RTD_URL: Final = "https://mypy.rtfd.io/en/stable/_refs.html#code"
  36. # Keep track of the original error code when the error code of a message is changed.
  37. # This is used to give notes about out-of-date "type: ignore" comments.
  38. original_error_codes: Final = {codes.LITERAL_REQ: codes.MISC, codes.TYPE_ABSTRACT: codes.MISC}
  39. class ErrorInfo:
  40. """Representation of a single error message."""
  41. # Description of a sequence of imports that refer to the source file
  42. # related to this error. Each item is a (path, line number) tuple.
  43. import_ctx: list[tuple[str, int]]
  44. # The path to source file that was the source of this error.
  45. file = ""
  46. # The fully-qualified id of the source module for this error.
  47. module: str | None = None
  48. # The name of the type in which this error is located at.
  49. type: str | None = "" # Unqualified, may be None
  50. # The name of the function or member in which this error is located at.
  51. function_or_member: str | None = "" # Unqualified, may be None
  52. # The line number related to this error within file.
  53. line = 0 # -1 if unknown
  54. # The column number related to this error with file.
  55. column = 0 # -1 if unknown
  56. # The end line number related to this error within file.
  57. end_line = 0 # -1 if unknown
  58. # The end column number related to this error with file.
  59. end_column = 0 # -1 if unknown
  60. # Either 'error' or 'note'
  61. severity = ""
  62. # The error message.
  63. message = ""
  64. # The error code.
  65. code: ErrorCode | None = None
  66. # If True, we should halt build after the file that generated this error.
  67. blocker = False
  68. # Only report this particular messages once per program.
  69. only_once = False
  70. # Do not remove duplicate copies of this message (ignored if only_once is True).
  71. allow_dups = False
  72. # Actual origin of the error message as tuple (path, line number, end line number)
  73. # If end line number is unknown, use line number.
  74. origin: tuple[str, Iterable[int]]
  75. # Fine-grained incremental target where this was reported
  76. target: str | None = None
  77. # If True, don't show this message in output, but still record the error (needed
  78. # by mypy daemon)
  79. hidden = False
  80. def __init__(
  81. self,
  82. import_ctx: list[tuple[str, int]],
  83. *,
  84. file: str,
  85. module: str | None,
  86. typ: str | None,
  87. function_or_member: str | None,
  88. line: int,
  89. column: int,
  90. end_line: int,
  91. end_column: int,
  92. severity: str,
  93. message: str,
  94. code: ErrorCode | None,
  95. blocker: bool,
  96. only_once: bool,
  97. allow_dups: bool,
  98. origin: tuple[str, Iterable[int]] | None = None,
  99. target: str | None = None,
  100. priority: int = 0,
  101. ) -> None:
  102. self.import_ctx = import_ctx
  103. self.file = file
  104. self.module = module
  105. self.type = typ
  106. self.function_or_member = function_or_member
  107. self.line = line
  108. self.column = column
  109. self.end_line = end_line
  110. self.end_column = end_column
  111. self.severity = severity
  112. self.message = message
  113. self.code = code
  114. self.blocker = blocker
  115. self.only_once = only_once
  116. self.allow_dups = allow_dups
  117. self.origin = origin or (file, [line])
  118. self.target = target
  119. self.priority = priority
  120. # Type used internally to represent errors:
  121. # (path, line, column, end_line, end_column, severity, message, allow_dups, code)
  122. ErrorTuple: _TypeAlias = Tuple[
  123. Optional[str], int, int, int, int, str, str, bool, Optional[ErrorCode]
  124. ]
  125. class ErrorWatcher:
  126. """Context manager that can be used to keep track of new errors recorded
  127. around a given operation.
  128. Errors maintain a stack of such watchers. The handler is called starting
  129. at the top of the stack, and is propagated down the stack unless filtered
  130. out by one of the ErrorWatcher instances.
  131. """
  132. def __init__(
  133. self,
  134. errors: Errors,
  135. *,
  136. filter_errors: bool | Callable[[str, ErrorInfo], bool] = False,
  137. save_filtered_errors: bool = False,
  138. ):
  139. self.errors = errors
  140. self._has_new_errors = False
  141. self._filter = filter_errors
  142. self._filtered: list[ErrorInfo] | None = [] if save_filtered_errors else None
  143. def __enter__(self) -> ErrorWatcher:
  144. self.errors._watchers.append(self)
  145. return self
  146. def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> Literal[False]:
  147. last = self.errors._watchers.pop()
  148. assert last == self
  149. return False
  150. def on_error(self, file: str, info: ErrorInfo) -> bool:
  151. """Handler called when a new error is recorded.
  152. The default implementation just sets the has_new_errors flag
  153. Return True to filter out the error, preventing it from being seen by other
  154. ErrorWatcher further down the stack and from being recorded by Errors
  155. """
  156. self._has_new_errors = True
  157. if isinstance(self._filter, bool):
  158. should_filter = self._filter
  159. elif callable(self._filter):
  160. should_filter = self._filter(file, info)
  161. else:
  162. raise AssertionError(f"invalid error filter: {type(self._filter)}")
  163. if should_filter and self._filtered is not None:
  164. self._filtered.append(info)
  165. return should_filter
  166. def has_new_errors(self) -> bool:
  167. return self._has_new_errors
  168. def filtered_errors(self) -> list[ErrorInfo]:
  169. assert self._filtered is not None
  170. return self._filtered
  171. class Errors:
  172. """Container for compile errors.
  173. This class generates and keeps tracks of compile errors and the
  174. current error context (nested imports).
  175. """
  176. # Map from files to generated error messages. Is an OrderedDict so
  177. # that it can be used to order messages based on the order the
  178. # files were processed.
  179. error_info_map: dict[str, list[ErrorInfo]]
  180. # optimization for legacy codebases with many files with errors
  181. has_blockers: set[str]
  182. # Files that we have reported the errors for
  183. flushed_files: set[str]
  184. # Current error context: nested import context/stack, as a list of (path, line) pairs.
  185. import_ctx: list[tuple[str, int]]
  186. # Path name prefix that is removed from all paths, if set.
  187. ignore_prefix: str | None = None
  188. # Path to current file.
  189. file: str = ""
  190. # Ignore some errors on these lines of each file
  191. # (path -> line -> error-codes)
  192. ignored_lines: dict[str, dict[int, list[str]]]
  193. # Lines that were skipped during semantic analysis e.g. due to ALWAYS_FALSE, MYPY_FALSE,
  194. # or platform/version checks. Those lines would not be type-checked.
  195. skipped_lines: dict[str, set[int]]
  196. # Lines on which an error was actually ignored.
  197. used_ignored_lines: dict[str, dict[int, list[str]]]
  198. # Files where all errors should be ignored.
  199. ignored_files: set[str]
  200. # Collection of reported only_once messages.
  201. only_once_messages: set[str]
  202. # Set to True to show "In function "foo":" messages.
  203. show_error_context: bool = False
  204. # Set to True to show column numbers in error messages.
  205. show_column_numbers: bool = False
  206. # Set to True to show end line and end column in error messages.
  207. # Ths implies `show_column_numbers`.
  208. show_error_end: bool = False
  209. # Set to True to show absolute file paths in error messages.
  210. show_absolute_path: bool = False
  211. # State for keeping track of the current fine-grained incremental mode target.
  212. # (See mypy.server.update for more about targets.)
  213. # Current module id.
  214. target_module: str | None = None
  215. scope: Scope | None = None
  216. # Have we seen an import-related error so far? If yes, we filter out other messages
  217. # in some cases to avoid reporting huge numbers of errors.
  218. seen_import_error = False
  219. _watchers: list[ErrorWatcher] = []
  220. def __init__(
  221. self,
  222. options: Options,
  223. *,
  224. read_source: Callable[[str], list[str] | None] | None = None,
  225. hide_error_codes: bool | None = None,
  226. ) -> None:
  227. self.options = options
  228. self.hide_error_codes = (
  229. hide_error_codes if hide_error_codes is not None else options.hide_error_codes
  230. )
  231. # We use fscache to read source code when showing snippets.
  232. self.read_source = read_source
  233. self.initialize()
  234. def initialize(self) -> None:
  235. self.error_info_map = {}
  236. self.flushed_files = set()
  237. self.import_ctx = []
  238. self.function_or_member = [None]
  239. self.ignored_lines = {}
  240. self.skipped_lines = {}
  241. self.used_ignored_lines = defaultdict(lambda: defaultdict(list))
  242. self.ignored_files = set()
  243. self.only_once_messages = set()
  244. self.has_blockers = set()
  245. self.scope = None
  246. self.target_module = None
  247. self.seen_import_error = False
  248. def reset(self) -> None:
  249. self.initialize()
  250. def set_ignore_prefix(self, prefix: str) -> None:
  251. """Set path prefix that will be removed from all paths."""
  252. prefix = os.path.normpath(prefix)
  253. # Add separator to the end, if not given.
  254. if os.path.basename(prefix) != "":
  255. prefix += os.sep
  256. self.ignore_prefix = prefix
  257. def simplify_path(self, file: str) -> str:
  258. if self.options.show_absolute_path:
  259. return os.path.abspath(file)
  260. else:
  261. file = os.path.normpath(file)
  262. return remove_path_prefix(file, self.ignore_prefix)
  263. def set_file(
  264. self, file: str, module: str | None, options: Options, scope: Scope | None = None
  265. ) -> None:
  266. """Set the path and module id of the current file."""
  267. # The path will be simplified later, in render_messages. That way
  268. # * 'file' is always a key that uniquely identifies a source file
  269. # that mypy read (simplified paths might not be unique); and
  270. # * we only have to simplify in one place, while still supporting
  271. # reporting errors for files other than the one currently being
  272. # processed.
  273. self.file = file
  274. self.target_module = module
  275. self.scope = scope
  276. self.options = options
  277. def set_file_ignored_lines(
  278. self, file: str, ignored_lines: dict[int, list[str]], ignore_all: bool = False
  279. ) -> None:
  280. self.ignored_lines[file] = ignored_lines
  281. if ignore_all:
  282. self.ignored_files.add(file)
  283. def set_skipped_lines(self, file: str, skipped_lines: set[int]) -> None:
  284. self.skipped_lines[file] = skipped_lines
  285. def current_target(self) -> str | None:
  286. """Retrieves the current target from the associated scope.
  287. If there is no associated scope, use the target module."""
  288. if self.scope is not None:
  289. return self.scope.current_target()
  290. return self.target_module
  291. def current_module(self) -> str | None:
  292. return self.target_module
  293. def import_context(self) -> list[tuple[str, int]]:
  294. """Return a copy of the import context."""
  295. return self.import_ctx.copy()
  296. def set_import_context(self, ctx: list[tuple[str, int]]) -> None:
  297. """Replace the entire import context with a new value."""
  298. self.import_ctx = ctx.copy()
  299. def report(
  300. self,
  301. line: int,
  302. column: int | None,
  303. message: str,
  304. code: ErrorCode | None = None,
  305. *,
  306. blocker: bool = False,
  307. severity: str = "error",
  308. file: str | None = None,
  309. only_once: bool = False,
  310. allow_dups: bool = False,
  311. origin_span: Iterable[int] | None = None,
  312. offset: int = 0,
  313. end_line: int | None = None,
  314. end_column: int | None = None,
  315. ) -> None:
  316. """Report message at the given line using the current error context.
  317. Args:
  318. line: line number of error
  319. column: column number of error
  320. message: message to report
  321. code: error code (defaults to 'misc'; not shown for notes)
  322. blocker: if True, don't continue analysis after this error
  323. severity: 'error' or 'note'
  324. file: if non-None, override current file as context
  325. only_once: if True, only report this exact message once per build
  326. allow_dups: if True, allow duplicate copies of this message (ignored if only_once)
  327. origin_span: if non-None, override current context as origin
  328. (type: ignores have effect here)
  329. end_line: if non-None, override current context as end
  330. """
  331. if self.scope:
  332. type = self.scope.current_type_name()
  333. if self.scope.ignored > 0:
  334. type = None # Omit type context if nested function
  335. function = self.scope.current_function_name()
  336. else:
  337. type = None
  338. function = None
  339. if column is None:
  340. column = -1
  341. if end_column is None:
  342. if column == -1:
  343. end_column = -1
  344. else:
  345. end_column = column + 1
  346. if file is None:
  347. file = self.file
  348. if offset:
  349. message = " " * offset + message
  350. if origin_span is None:
  351. origin_span = [line]
  352. if end_line is None:
  353. end_line = line
  354. code = code or (codes.MISC if not blocker else None)
  355. info = ErrorInfo(
  356. import_ctx=self.import_context(),
  357. file=file,
  358. module=self.current_module(),
  359. typ=type,
  360. function_or_member=function,
  361. line=line,
  362. column=column,
  363. end_line=end_line,
  364. end_column=end_column,
  365. severity=severity,
  366. message=message,
  367. code=code,
  368. blocker=blocker,
  369. only_once=only_once,
  370. allow_dups=allow_dups,
  371. origin=(self.file, origin_span),
  372. target=self.current_target(),
  373. )
  374. self.add_error_info(info)
  375. def _add_error_info(self, file: str, info: ErrorInfo) -> None:
  376. assert file not in self.flushed_files
  377. # process the stack of ErrorWatchers before modifying any internal state
  378. # in case we need to filter out the error entirely
  379. if self._filter_error(file, info):
  380. return
  381. if file not in self.error_info_map:
  382. self.error_info_map[file] = []
  383. self.error_info_map[file].append(info)
  384. if info.blocker:
  385. self.has_blockers.add(file)
  386. if info.code is IMPORT:
  387. self.seen_import_error = True
  388. def _filter_error(self, file: str, info: ErrorInfo) -> bool:
  389. """
  390. process ErrorWatcher stack from top to bottom,
  391. stopping early if error needs to be filtered out
  392. """
  393. i = len(self._watchers)
  394. while i > 0:
  395. i -= 1
  396. w = self._watchers[i]
  397. if w.on_error(file, info):
  398. return True
  399. return False
  400. def add_error_info(self, info: ErrorInfo) -> None:
  401. file, lines = info.origin
  402. # process the stack of ErrorWatchers before modifying any internal state
  403. # in case we need to filter out the error entirely
  404. # NB: we need to do this both here and in _add_error_info, otherwise we
  405. # might incorrectly update the sets of ignored or only_once messages
  406. if self._filter_error(file, info):
  407. return
  408. if not info.blocker: # Blockers cannot be ignored
  409. if file in self.ignored_lines:
  410. # Check each line in this context for "type: ignore" comments.
  411. # line == end_line for most nodes, so we only loop once.
  412. for scope_line in lines:
  413. if self.is_ignored_error(scope_line, info, self.ignored_lines[file]):
  414. # Annotation requests us to ignore all errors on this line.
  415. self.used_ignored_lines[file][scope_line].append(
  416. (info.code or codes.MISC).code
  417. )
  418. return
  419. if file in self.ignored_files:
  420. return
  421. if info.only_once:
  422. if info.message in self.only_once_messages:
  423. return
  424. self.only_once_messages.add(info.message)
  425. if self.seen_import_error and info.code is not IMPORT and self.has_many_errors():
  426. # Missing stubs can easily cause thousands of errors about
  427. # Any types, especially when upgrading to mypy 0.900,
  428. # which no longer bundles third-party library stubs. Avoid
  429. # showing too many errors to make it easier to see
  430. # import-related errors.
  431. info.hidden = True
  432. self.report_hidden_errors(info)
  433. self._add_error_info(file, info)
  434. ignored_codes = self.ignored_lines.get(file, {}).get(info.line, [])
  435. if ignored_codes and info.code:
  436. # Something is ignored on the line, but not this error, so maybe the error
  437. # code is incorrect.
  438. msg = f'Error code "{info.code.code}" not covered by "type: ignore" comment'
  439. if info.code in original_error_codes:
  440. # If there seems to be a "type: ignore" with a stale error
  441. # code, report a more specific note.
  442. old_code = original_error_codes[info.code].code
  443. if old_code in ignored_codes:
  444. msg = (
  445. f'Error code changed to {info.code.code}; "type: ignore" comment '
  446. + "may be out of date"
  447. )
  448. note = ErrorInfo(
  449. import_ctx=info.import_ctx,
  450. file=info.file,
  451. module=info.module,
  452. typ=info.type,
  453. function_or_member=info.function_or_member,
  454. line=info.line,
  455. column=info.column,
  456. end_line=info.end_line,
  457. end_column=info.end_column,
  458. severity="note",
  459. message=msg,
  460. code=None,
  461. blocker=False,
  462. only_once=False,
  463. allow_dups=False,
  464. )
  465. self._add_error_info(file, note)
  466. if (
  467. self.options.show_error_code_links
  468. and not self.options.hide_error_codes
  469. and info.code is not None
  470. and info.code not in HIDE_LINK_CODES
  471. ):
  472. message = f"See {BASE_RTD_URL}-{info.code.code} for more info"
  473. if message in self.only_once_messages:
  474. return
  475. self.only_once_messages.add(message)
  476. info = ErrorInfo(
  477. import_ctx=info.import_ctx,
  478. file=info.file,
  479. module=info.module,
  480. typ=info.type,
  481. function_or_member=info.function_or_member,
  482. line=info.line,
  483. column=info.column,
  484. end_line=info.end_line,
  485. end_column=info.end_column,
  486. severity="note",
  487. message=message,
  488. code=info.code,
  489. blocker=False,
  490. only_once=True,
  491. allow_dups=False,
  492. priority=20,
  493. )
  494. self._add_error_info(file, info)
  495. def has_many_errors(self) -> bool:
  496. if self.options.many_errors_threshold < 0:
  497. return False
  498. if len(self.error_info_map) >= self.options.many_errors_threshold:
  499. return True
  500. if (
  501. sum(len(errors) for errors in self.error_info_map.values())
  502. >= self.options.many_errors_threshold
  503. ):
  504. return True
  505. return False
  506. def report_hidden_errors(self, info: ErrorInfo) -> None:
  507. message = (
  508. "(Skipping most remaining errors due to unresolved imports or missing stubs; "
  509. + "fix these first)"
  510. )
  511. if message in self.only_once_messages:
  512. return
  513. self.only_once_messages.add(message)
  514. new_info = ErrorInfo(
  515. import_ctx=info.import_ctx,
  516. file=info.file,
  517. module=info.module,
  518. typ=None,
  519. function_or_member=None,
  520. line=info.line,
  521. column=info.column,
  522. end_line=info.end_line,
  523. end_column=info.end_column,
  524. severity="note",
  525. message=message,
  526. code=None,
  527. blocker=False,
  528. only_once=True,
  529. allow_dups=False,
  530. origin=info.origin,
  531. target=info.target,
  532. )
  533. self._add_error_info(info.origin[0], new_info)
  534. def is_ignored_error(self, line: int, info: ErrorInfo, ignores: dict[int, list[str]]) -> bool:
  535. if info.blocker:
  536. # Blocking errors can never be ignored
  537. return False
  538. if info.code and not self.is_error_code_enabled(info.code):
  539. return True
  540. if line not in ignores:
  541. return False
  542. if not ignores[line]:
  543. # Empty list means that we ignore all errors
  544. return True
  545. if info.code and self.is_error_code_enabled(info.code):
  546. return (
  547. info.code.code in ignores[line]
  548. or info.code.sub_code_of is not None
  549. and info.code.sub_code_of.code in ignores[line]
  550. )
  551. return False
  552. def is_error_code_enabled(self, error_code: ErrorCode) -> bool:
  553. if self.options:
  554. current_mod_disabled = self.options.disabled_error_codes
  555. current_mod_enabled = self.options.enabled_error_codes
  556. else:
  557. current_mod_disabled = set()
  558. current_mod_enabled = set()
  559. if error_code in current_mod_disabled:
  560. return False
  561. elif error_code in current_mod_enabled:
  562. return True
  563. elif error_code.sub_code_of is not None and error_code.sub_code_of in current_mod_disabled:
  564. return False
  565. else:
  566. return error_code.default_enabled
  567. def clear_errors_in_targets(self, path: str, targets: set[str]) -> None:
  568. """Remove errors in specific fine-grained targets within a file."""
  569. if path in self.error_info_map:
  570. new_errors = []
  571. has_blocker = False
  572. for info in self.error_info_map[path]:
  573. if info.target not in targets:
  574. new_errors.append(info)
  575. has_blocker |= info.blocker
  576. elif info.only_once:
  577. self.only_once_messages.remove(info.message)
  578. self.error_info_map[path] = new_errors
  579. if not has_blocker and path in self.has_blockers:
  580. self.has_blockers.remove(path)
  581. def generate_unused_ignore_errors(self, file: str) -> None:
  582. if (
  583. is_typeshed_file(self.options.abs_custom_typeshed_dir if self.options else None, file)
  584. or file in self.ignored_files
  585. ):
  586. return
  587. ignored_lines = self.ignored_lines[file]
  588. used_ignored_lines = self.used_ignored_lines[file]
  589. for line, ignored_codes in ignored_lines.items():
  590. if line in self.skipped_lines[file]:
  591. continue
  592. if codes.UNUSED_IGNORE.code in ignored_codes:
  593. continue
  594. used_ignored_codes = used_ignored_lines[line]
  595. unused_ignored_codes = set(ignored_codes) - set(used_ignored_codes)
  596. # `ignore` is used
  597. if not ignored_codes and used_ignored_codes:
  598. continue
  599. # All codes appearing in `ignore[...]` are used
  600. if ignored_codes and not unused_ignored_codes:
  601. continue
  602. # Display detail only when `ignore[...]` specifies more than one error code
  603. unused_codes_message = ""
  604. if len(ignored_codes) > 1 and unused_ignored_codes:
  605. unused_codes_message = f"[{', '.join(sorted(unused_ignored_codes))}]"
  606. message = f'Unused "type: ignore{unused_codes_message}" comment'
  607. for unused in unused_ignored_codes:
  608. narrower = set(used_ignored_codes) & codes.sub_code_map[unused]
  609. if narrower:
  610. message += f", use narrower [{', '.join(narrower)}] instead of [{unused}] code"
  611. # Don't use report since add_error_info will ignore the error!
  612. info = ErrorInfo(
  613. import_ctx=self.import_context(),
  614. file=file,
  615. module=self.current_module(),
  616. typ=None,
  617. function_or_member=None,
  618. line=line,
  619. column=-1,
  620. end_line=line,
  621. end_column=-1,
  622. severity="error",
  623. message=message,
  624. code=codes.UNUSED_IGNORE,
  625. blocker=False,
  626. only_once=False,
  627. allow_dups=False,
  628. )
  629. self._add_error_info(file, info)
  630. def generate_ignore_without_code_errors(
  631. self, file: str, is_warning_unused_ignores: bool
  632. ) -> None:
  633. if (
  634. is_typeshed_file(self.options.abs_custom_typeshed_dir if self.options else None, file)
  635. or file in self.ignored_files
  636. ):
  637. return
  638. used_ignored_lines = self.used_ignored_lines[file]
  639. # If the whole file is ignored, ignore it.
  640. if used_ignored_lines:
  641. _, used_codes = min(used_ignored_lines.items())
  642. if codes.FILE.code in used_codes:
  643. return
  644. for line, ignored_codes in self.ignored_lines[file].items():
  645. if ignored_codes:
  646. continue
  647. # If the ignore is itself unused and that would be warned about, let
  648. # that error stand alone
  649. if is_warning_unused_ignores and not used_ignored_lines[line]:
  650. continue
  651. codes_hint = ""
  652. ignored_codes = sorted(set(used_ignored_lines[line]))
  653. if ignored_codes:
  654. codes_hint = f' (consider "type: ignore[{", ".join(ignored_codes)}]" instead)'
  655. message = f'"type: ignore" comment without error code{codes_hint}'
  656. # Don't use report since add_error_info will ignore the error!
  657. info = ErrorInfo(
  658. import_ctx=self.import_context(),
  659. file=file,
  660. module=self.current_module(),
  661. typ=None,
  662. function_or_member=None,
  663. line=line,
  664. column=-1,
  665. end_line=line,
  666. end_column=-1,
  667. severity="error",
  668. message=message,
  669. code=codes.IGNORE_WITHOUT_CODE,
  670. blocker=False,
  671. only_once=False,
  672. allow_dups=False,
  673. )
  674. self._add_error_info(file, info)
  675. def num_messages(self) -> int:
  676. """Return the number of generated messages."""
  677. return sum(len(x) for x in self.error_info_map.values())
  678. def is_errors(self) -> bool:
  679. """Are there any generated messages?"""
  680. return bool(self.error_info_map)
  681. def is_blockers(self) -> bool:
  682. """Are the any errors that are blockers?"""
  683. return bool(self.has_blockers)
  684. def blocker_module(self) -> str | None:
  685. """Return the module with a blocking error, or None if not possible."""
  686. for path in self.has_blockers:
  687. for err in self.error_info_map[path]:
  688. if err.blocker:
  689. return err.module
  690. return None
  691. def is_errors_for_file(self, file: str) -> bool:
  692. """Are there any errors for the given file?"""
  693. return file in self.error_info_map
  694. def prefer_simple_messages(self) -> bool:
  695. """Should we generate simple/fast error messages?
  696. Return True if errors are not shown to user, i.e. errors are ignored
  697. or they are collected for internal use only.
  698. If True, we should prefer to generate a simple message quickly.
  699. All normal errors should still be reported.
  700. """
  701. if self.file in self.ignored_files:
  702. # Errors ignored, so no point generating fancy messages
  703. return True
  704. for _watcher in self._watchers:
  705. if _watcher._filter is True and _watcher._filtered is None:
  706. # Errors are filtered
  707. return True
  708. return False
  709. def raise_error(self, use_stdout: bool = True) -> NoReturn:
  710. """Raise a CompileError with the generated messages.
  711. Render the messages suitable for displaying.
  712. """
  713. # self.new_messages() will format all messages that haven't already
  714. # been returned from a file_messages() call.
  715. raise CompileError(
  716. self.new_messages(), use_stdout=use_stdout, module_with_blocker=self.blocker_module()
  717. )
  718. def format_messages(
  719. self, error_info: list[ErrorInfo], source_lines: list[str] | None
  720. ) -> list[str]:
  721. """Return a string list that represents the error messages.
  722. Use a form suitable for displaying to the user. If self.pretty
  723. is True also append a relevant trimmed source code line (only for
  724. severity 'error').
  725. """
  726. a: list[str] = []
  727. error_info = [info for info in error_info if not info.hidden]
  728. errors = self.render_messages(self.sort_messages(error_info))
  729. errors = self.remove_duplicates(errors)
  730. for (
  731. file,
  732. line,
  733. column,
  734. end_line,
  735. end_column,
  736. severity,
  737. message,
  738. allow_dups,
  739. code,
  740. ) in errors:
  741. s = ""
  742. if file is not None:
  743. if self.options.show_column_numbers and line >= 0 and column >= 0:
  744. srcloc = f"{file}:{line}:{1 + column}"
  745. if self.options.show_error_end and end_line >= 0 and end_column >= 0:
  746. srcloc += f":{end_line}:{end_column}"
  747. elif line >= 0:
  748. srcloc = f"{file}:{line}"
  749. else:
  750. srcloc = file
  751. s = f"{srcloc}: {severity}: {message}"
  752. else:
  753. s = message
  754. if (
  755. not self.hide_error_codes
  756. and code
  757. and (severity != "note" or code in SHOW_NOTE_CODES)
  758. ):
  759. # If note has an error code, it is related to a previous error. Avoid
  760. # displaying duplicate error codes.
  761. s = f"{s} [{code.code}]"
  762. a.append(s)
  763. if self.options.pretty:
  764. # Add source code fragment and a location marker.
  765. if severity == "error" and source_lines and line > 0:
  766. source_line = source_lines[line - 1]
  767. source_line_expanded = source_line.expandtabs()
  768. if column < 0:
  769. # Something went wrong, take first non-empty column.
  770. column = len(source_line) - len(source_line.lstrip())
  771. # Shifts column after tab expansion
  772. column = len(source_line[:column].expandtabs())
  773. end_column = len(source_line[:end_column].expandtabs())
  774. # Note, currently coloring uses the offset to detect source snippets,
  775. # so these offsets should not be arbitrary.
  776. a.append(" " * DEFAULT_SOURCE_OFFSET + source_line_expanded)
  777. marker = "^"
  778. if end_line == line and end_column > column:
  779. marker = f'^{"~" * (end_column - column - 1)}'
  780. a.append(" " * (DEFAULT_SOURCE_OFFSET + column) + marker)
  781. return a
  782. def file_messages(self, path: str) -> list[str]:
  783. """Return a string list of new error messages from a given file.
  784. Use a form suitable for displaying to the user.
  785. """
  786. if path not in self.error_info_map:
  787. return []
  788. self.flushed_files.add(path)
  789. source_lines = None
  790. if self.options.pretty:
  791. assert self.read_source
  792. source_lines = self.read_source(path)
  793. return self.format_messages(self.error_info_map[path], source_lines)
  794. def new_messages(self) -> list[str]:
  795. """Return a string list of new error messages.
  796. Use a form suitable for displaying to the user.
  797. Errors from different files are ordered based on the order in which
  798. they first generated an error.
  799. """
  800. msgs = []
  801. for path in self.error_info_map.keys():
  802. if path not in self.flushed_files:
  803. msgs.extend(self.file_messages(path))
  804. return msgs
  805. def targets(self) -> set[str]:
  806. """Return a set of all targets that contain errors."""
  807. # TODO: Make sure that either target is always defined or that not being defined
  808. # is okay for fine-grained incremental checking.
  809. return {
  810. info.target for errs in self.error_info_map.values() for info in errs if info.target
  811. }
  812. def render_messages(self, errors: list[ErrorInfo]) -> list[ErrorTuple]:
  813. """Translate the messages into a sequence of tuples.
  814. Each tuple is of form (path, line, col, severity, message, allow_dups, code).
  815. The rendered sequence includes information about error contexts.
  816. The path item may be None. If the line item is negative, the
  817. line number is not defined for the tuple.
  818. """
  819. result: list[ErrorTuple] = []
  820. prev_import_context: list[tuple[str, int]] = []
  821. prev_function_or_member: str | None = None
  822. prev_type: str | None = None
  823. for e in errors:
  824. # Report module import context, if different from previous message.
  825. if not self.options.show_error_context:
  826. pass
  827. elif e.import_ctx != prev_import_context:
  828. last = len(e.import_ctx) - 1
  829. i = last
  830. while i >= 0:
  831. path, line = e.import_ctx[i]
  832. fmt = "{}:{}: note: In module imported here"
  833. if i < last:
  834. fmt = "{}:{}: note: ... from here"
  835. if i > 0:
  836. fmt += ","
  837. else:
  838. fmt += ":"
  839. # Remove prefix to ignore from path (if present) to
  840. # simplify path.
  841. path = remove_path_prefix(path, self.ignore_prefix)
  842. result.append(
  843. (None, -1, -1, -1, -1, "note", fmt.format(path, line), e.allow_dups, None)
  844. )
  845. i -= 1
  846. file = self.simplify_path(e.file)
  847. # Report context within a source file.
  848. if not self.options.show_error_context:
  849. pass
  850. elif e.function_or_member != prev_function_or_member or e.type != prev_type:
  851. if e.function_or_member is None:
  852. if e.type is None:
  853. result.append(
  854. (file, -1, -1, -1, -1, "note", "At top level:", e.allow_dups, None)
  855. )
  856. else:
  857. result.append(
  858. (
  859. file,
  860. -1,
  861. -1,
  862. -1,
  863. -1,
  864. "note",
  865. f'In class "{e.type}":',
  866. e.allow_dups,
  867. None,
  868. )
  869. )
  870. else:
  871. if e.type is None:
  872. result.append(
  873. (
  874. file,
  875. -1,
  876. -1,
  877. -1,
  878. -1,
  879. "note",
  880. f'In function "{e.function_or_member}":',
  881. e.allow_dups,
  882. None,
  883. )
  884. )
  885. else:
  886. result.append(
  887. (
  888. file,
  889. -1,
  890. -1,
  891. -1,
  892. -1,
  893. "note",
  894. 'In member "{}" of class "{}":'.format(
  895. e.function_or_member, e.type
  896. ),
  897. e.allow_dups,
  898. None,
  899. )
  900. )
  901. elif e.type != prev_type:
  902. if e.type is None:
  903. result.append(
  904. (file, -1, -1, -1, -1, "note", "At top level:", e.allow_dups, None)
  905. )
  906. else:
  907. result.append(
  908. (file, -1, -1, -1, -1, "note", f'In class "{e.type}":', e.allow_dups, None)
  909. )
  910. if isinstance(e.message, ErrorMessage):
  911. result.append(
  912. (
  913. file,
  914. e.line,
  915. e.column,
  916. e.end_line,
  917. e.end_column,
  918. e.severity,
  919. e.message.value,
  920. e.allow_dups,
  921. e.code,
  922. )
  923. )
  924. else:
  925. result.append(
  926. (
  927. file,
  928. e.line,
  929. e.column,
  930. e.end_line,
  931. e.end_column,
  932. e.severity,
  933. e.message,
  934. e.allow_dups,
  935. e.code,
  936. )
  937. )
  938. prev_import_context = e.import_ctx
  939. prev_function_or_member = e.function_or_member
  940. prev_type = e.type
  941. return result
  942. def sort_messages(self, errors: list[ErrorInfo]) -> list[ErrorInfo]:
  943. """Sort an array of error messages locally by line number.
  944. I.e., sort a run of consecutive messages with the same
  945. context by line number, but otherwise retain the general
  946. ordering of the messages.
  947. """
  948. result: list[ErrorInfo] = []
  949. i = 0
  950. while i < len(errors):
  951. i0 = i
  952. # Find neighbouring errors with the same context and file.
  953. while (
  954. i + 1 < len(errors)
  955. and errors[i + 1].import_ctx == errors[i].import_ctx
  956. and errors[i + 1].file == errors[i].file
  957. ):
  958. i += 1
  959. i += 1
  960. # Sort the errors specific to a file according to line number and column.
  961. a = sorted(errors[i0:i], key=lambda x: (x.line, x.column))
  962. a = self.sort_within_context(a)
  963. result.extend(a)
  964. return result
  965. def sort_within_context(self, errors: list[ErrorInfo]) -> list[ErrorInfo]:
  966. """For the same location decide which messages to show first/last.
  967. Currently, we only compare within the same error code, to decide the
  968. order of various additional notes.
  969. """
  970. result = []
  971. i = 0
  972. while i < len(errors):
  973. i0 = i
  974. # Find neighbouring errors with the same position and error code.
  975. while (
  976. i + 1 < len(errors)
  977. and errors[i + 1].line == errors[i].line
  978. and errors[i + 1].column == errors[i].column
  979. and errors[i + 1].end_line == errors[i].end_line
  980. and errors[i + 1].end_column == errors[i].end_column
  981. and errors[i + 1].code == errors[i].code
  982. ):
  983. i += 1
  984. i += 1
  985. # Sort the messages specific to a given error by priority.
  986. a = sorted(errors[i0:i], key=lambda x: x.priority)
  987. result.extend(a)
  988. return result
  989. def remove_duplicates(self, errors: list[ErrorTuple]) -> list[ErrorTuple]:
  990. """Remove duplicates from a sorted error list."""
  991. res: list[ErrorTuple] = []
  992. i = 0
  993. while i < len(errors):
  994. dup = False
  995. # Use slightly special formatting for member conflicts reporting.
  996. conflicts_notes = False
  997. j = i - 1
  998. # Find duplicates, unless duplicates are allowed.
  999. if not errors[i][7]:
  1000. while j >= 0 and errors[j][0] == errors[i][0]:
  1001. if errors[j][6].strip() == "Got:":
  1002. conflicts_notes = True
  1003. j -= 1
  1004. j = i - 1
  1005. while j >= 0 and errors[j][0] == errors[i][0] and errors[j][1] == errors[i][1]:
  1006. if (
  1007. errors[j][5] == errors[i][5]
  1008. and
  1009. # Allow duplicate notes in overload conflicts reporting.
  1010. not (
  1011. (errors[i][5] == "note" and errors[i][6].strip() in allowed_duplicates)
  1012. or (errors[i][6].strip().startswith("def ") and conflicts_notes)
  1013. )
  1014. and errors[j][6] == errors[i][6]
  1015. ): # ignore column
  1016. dup = True
  1017. break
  1018. j -= 1
  1019. if not dup:
  1020. res.append(errors[i])
  1021. i += 1
  1022. return res
  1023. class CompileError(Exception):
  1024. """Exception raised when there is a compile error.
  1025. It can be a parse, semantic analysis, type check or other
  1026. compilation-related error.
  1027. CompileErrors raised from an errors object carry all of the
  1028. messages that have not been reported out by error streaming.
  1029. This is patched up by build.build to contain either all error
  1030. messages (if errors were streamed) or none (if they were not).
  1031. """
  1032. messages: list[str]
  1033. use_stdout = False
  1034. # Can be set in case there was a module with a blocking error
  1035. module_with_blocker: str | None = None
  1036. def __init__(
  1037. self, messages: list[str], use_stdout: bool = False, module_with_blocker: str | None = None
  1038. ) -> None:
  1039. super().__init__("\n".join(messages))
  1040. self.messages = messages
  1041. self.use_stdout = use_stdout
  1042. self.module_with_blocker = module_with_blocker
  1043. def remove_path_prefix(path: str, prefix: str | None) -> str:
  1044. """If path starts with prefix, return copy of path with the prefix removed.
  1045. Otherwise, return path. If path is None, return None.
  1046. """
  1047. if prefix is not None and path.startswith(prefix):
  1048. return path[len(prefix) :]
  1049. else:
  1050. return path
  1051. def report_internal_error(
  1052. err: Exception,
  1053. file: str | None,
  1054. line: int,
  1055. errors: Errors,
  1056. options: Options,
  1057. stdout: TextIO | None = None,
  1058. stderr: TextIO | None = None,
  1059. ) -> NoReturn:
  1060. """Report internal error and exit.
  1061. This optionally starts pdb or shows a traceback.
  1062. """
  1063. stdout = stdout or sys.stdout
  1064. stderr = stderr or sys.stderr
  1065. # Dump out errors so far, they often provide a clue.
  1066. # But catch unexpected errors rendering them.
  1067. try:
  1068. for msg in errors.new_messages():
  1069. print(msg)
  1070. except Exception as e:
  1071. print("Failed to dump errors:", repr(e), file=stderr)
  1072. # Compute file:line prefix for official-looking error messages.
  1073. if file:
  1074. if line:
  1075. prefix = f"{file}:{line}: "
  1076. else:
  1077. prefix = f"{file}: "
  1078. else:
  1079. prefix = ""
  1080. # Print "INTERNAL ERROR" message.
  1081. print(
  1082. f"{prefix}error: INTERNAL ERROR --",
  1083. "Please try using mypy master on GitHub:\n"
  1084. "https://mypy.readthedocs.io/en/stable/common_issues.html"
  1085. "#using-a-development-mypy-build",
  1086. file=stderr,
  1087. )
  1088. if options.show_traceback:
  1089. print("Please report a bug at https://github.com/python/mypy/issues", file=stderr)
  1090. else:
  1091. print(
  1092. "If this issue continues with mypy master, "
  1093. "please report a bug at https://github.com/python/mypy/issues",
  1094. file=stderr,
  1095. )
  1096. print(f"version: {mypy_version}", file=stderr)
  1097. # If requested, drop into pdb. This overrides show_tb.
  1098. if options.pdb:
  1099. print("Dropping into pdb", file=stderr)
  1100. import pdb
  1101. pdb.post_mortem(sys.exc_info()[2])
  1102. # If requested, print traceback, else print note explaining how to get one.
  1103. if options.raise_exceptions:
  1104. raise err
  1105. if not options.show_traceback:
  1106. if not options.pdb:
  1107. print(
  1108. "{}: note: please use --show-traceback to print a traceback "
  1109. "when reporting a bug".format(prefix),
  1110. file=stderr,
  1111. )
  1112. else:
  1113. tb = traceback.extract_stack()[:-2]
  1114. tb2 = traceback.extract_tb(sys.exc_info()[2])
  1115. print("Traceback (most recent call last):")
  1116. for s in traceback.format_list(tb + tb2):
  1117. print(s.rstrip("\n"))
  1118. print(f"{type(err).__name__}: {err}", file=stdout)
  1119. print(f"{prefix}: note: use --pdb to drop into pdb", file=stderr)
  1120. # Exit. The caller has nothing more to say.
  1121. # We use exit code 2 to signal that this is no ordinary error.
  1122. raise SystemExit(2)