mirror of
https://github.com/astral-sh/ruff.git
synced 2025-08-13 15:18:06 +00:00
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:
parent
e80260a3c5
commit
48e04cc2c8
9 changed files with 88 additions and 59 deletions
|
@ -6,8 +6,7 @@ use ruff_formatter::{format, FormatError, Formatted, PrintError, Printed, Source
|
|||
use ruff_python_ast::AstNode;
|
||||
use ruff_python_ast::Mod;
|
||||
use ruff_python_index::tokens_and_ranges;
|
||||
use ruff_python_parser::lexer::LexicalError;
|
||||
use ruff_python_parser::{parse_ok_tokens, AsMode, ParseError};
|
||||
use ruff_python_parser::{parse_ok_tokens, AsMode, ParseError, ParseErrorType};
|
||||
use ruff_python_trivia::CommentRanges;
|
||||
use ruff_source_file::Locator;
|
||||
|
||||
|
@ -108,35 +107,25 @@ where
|
|||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum FormatModuleError {
|
||||
#[error("source contains syntax errors: {0}")]
|
||||
LexError(LexicalError),
|
||||
#[error("source contains syntax errors: {0}")]
|
||||
ParseError(ParseError),
|
||||
#[error(transparent)]
|
||||
ParseError(#[from] ParseError),
|
||||
#[error(transparent)]
|
||||
FormatError(#[from] FormatError),
|
||||
#[error(transparent)]
|
||||
PrintError(#[from] PrintError),
|
||||
}
|
||||
|
||||
impl From<LexicalError> for FormatModuleError {
|
||||
fn from(value: LexicalError) -> Self {
|
||||
Self::LexError(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ParseError> for FormatModuleError {
|
||||
fn from(value: ParseError) -> Self {
|
||||
Self::ParseError(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(name = "format", level = Level::TRACE, skip_all)]
|
||||
pub fn format_module_source(
|
||||
source: &str,
|
||||
options: PyFormatOptions,
|
||||
) -> Result<Printed, FormatModuleError> {
|
||||
let source_type = options.source_type();
|
||||
let (tokens, comment_ranges) = tokens_and_ranges(source, source_type)?;
|
||||
let (tokens, comment_ranges) =
|
||||
tokens_and_ranges(source, source_type).map_err(|err| ParseError {
|
||||
offset: err.location,
|
||||
error: ParseErrorType::Lexical(err.error),
|
||||
})?;
|
||||
let module = parse_ok_tokens(tokens, source, source_type.as_mode())?;
|
||||
let formatted = format_module_ast(&module, &comment_ranges, source, options)?;
|
||||
Ok(formatted.print()?)
|
||||
|
@ -180,7 +169,6 @@ mod tests {
|
|||
|
||||
use ruff_python_ast::PySourceType;
|
||||
use ruff_python_index::tokens_and_ranges;
|
||||
|
||||
use ruff_python_parser::{parse_ok_tokens, AsMode};
|
||||
|
||||
use crate::{format_module_ast, format_module_source, PyFormatOptions};
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue