Add row and column numbers to formatted parse errors (#9321)

## Summary

We now render parse errors in the formatter identically to those in the
linter, e.g.:

```
❯ cargo run -p ruff_cli -- format foo.py
error: Failed to parse foo.py:1:17: Unexpected token '='
```

Closes https://github.com/astral-sh/ruff/issues/8338.

Closes https://github.com/astral-sh/ruff/issues/9311.
This commit is contained in:
Charlie Marsh 2023-12-31 08:10:45 -04:00 committed by GitHub
parent e80260a3c5
commit 48e04cc2c8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 88 additions and 59 deletions

View file

@ -35,6 +35,7 @@ use ruff_linter::settings::types::{FilePattern, FilePatternSet};
use ruff_python_formatter::{
format_module_source, FormatModuleError, MagicTrailingComma, PreviewMode, PyFormatOptions,
};
use ruff_python_parser::ParseError;
use ruff_workspace::resolver::{python_files_in_path, PyprojectConfig, ResolvedFile, Resolver};
/// Find files that ruff would check so we can format them. Adapted from `ruff_cli`.
@ -742,11 +743,11 @@ enum CheckFileError {
reformatted: String,
},
/// The input file was already invalid (not a bug)
SyntaxErrorInInput(FormatModuleError),
SyntaxErrorInInput(ParseError),
/// The formatter introduced a syntax error
SyntaxErrorInOutput {
formatted: String,
error: FormatModuleError,
error: ParseError,
},
/// The formatter failed (bug)
FormatError(FormatError),
@ -796,7 +797,7 @@ fn format_dev_file(
let start = Instant::now();
let printed = match format_module_source(&content, options.clone()) {
Ok(printed) => printed,
Err(err @ (FormatModuleError::LexError(_) | FormatModuleError::ParseError(_))) => {
Err(FormatModuleError::ParseError(err)) => {
return Err(CheckFileError::SyntaxErrorInInput(err));
}
Err(FormatModuleError::FormatError(err)) => {
@ -823,7 +824,7 @@ fn format_dev_file(
if stability_check {
let reformatted = match format_module_source(formatted, options) {
Ok(reformatted) => reformatted,
Err(err @ (FormatModuleError::LexError(_) | FormatModuleError::ParseError(_))) => {
Err(FormatModuleError::ParseError(err)) => {
return Err(CheckFileError::SyntaxErrorInOutput {
formatted: formatted.to_string(),
error: err,