Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better (post-parser) errors #1058

Closed
wants to merge 14 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 67 additions & 27 deletions askama_parser/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,36 +102,10 @@ impl<'a> Ast<'a> {
Err(nom::Err::Incomplete(_)) => return Err(ParseError("parsing incomplete".into())),
};

let offset = src.len() - input.len();
let (source_before, source_after) = src.split_at(offset);

let source_after = match source_after.char_indices().enumerate().take(41).last() {
Some((40, (i, _))) => format!("{:?}...", &source_after[..i]),
_ => format!("{source_after:?}"),
};

let (row, last_line) = source_before.lines().enumerate().last().unwrap_or_default();
let column = last_line.chars().count();

let file_info = file_path.and_then(|file_path| {
let cwd = std::env::current_dir().ok()?;
Some((cwd, file_path))
});
let message = message
.map(|message| format!("{message}\n"))
.unwrap_or_default();
let error_msg = if let Some((cwd, file_path)) = file_info {
format!(
"{message}failed to parse template source\n --> {path}:{row}:{column}\n{source_after}",
path = strip_common(&cwd, &file_path),
row = row + 1,
)
} else {
format!(
"{message}failed to parse template source at row {}, column {column} near:\n{source_after}",
row + 1,
)
};
let error_msg = generate_error_message(&message, src, input, &file_path);

Err(ParseError(error_msg))
}
Expand All @@ -155,6 +129,72 @@ impl fmt::Display for ParseError {
pub(crate) type ParseErr<'a> = nom::Err<ErrorContext<'a>>;
pub(crate) type ParseResult<'a, T = &'a str> = Result<(&'a str, T), ParseErr<'a>>;

pub struct ErrorInfo {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although the direction is good, this still has too much going on. Suggest a few steps, maybe in a separate PR?

  • Extract all of this code from Ast::from_str() into a ParseError::new() function
  • Unify the row/column display to {row}:{column} for both path and non-path errors
  • Extract an ErrorInfo type with an impl Display that takes care of the final formatting step, which will need to include a path: Option<Rc<Path>>
  • To the extent that you need what is here generate_row_and_column() and generate_error_info() later in the PR, they should perhaps be constructors on ErrorInfo.

Also please keep functions in top-down order -- maybe do more self-review to check for style issues? Reviewing your changes is taking many round trips.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feedback is appreciated. I don't plan to send another PR for this, all changes are tied together and at this point your suggestions (even if great) are only improvements over this code. I'll implement what you suggested though.

Also please keep functions in top-down order -- maybe do more self-review to check for style issues? Reviewing your changes is taking many round trips.

Well, as you said, it's code styling, so we're entering personal preferences. I don't mind following a project code's style but if there is no test to enforce it and tell me what and where I did something wrong, then you shouldn't expect people to remember it or to implement it as such. Therefore, I don't plan to try to remember what style you want to apply until there is a check for it, I work on way too many different codebases to have motivation for this. If this is a blocker for you, then I'll just fork askama from this point and implement what I need on my side while backporting changes from your repository to mine. Just to be clear: this is not a hostile take or anything, I really love askama and really enjoy your suggestions. It's just that you have high expectations for PRs, and I don't have the tools nor the time to live up to your expectations. So I'll let it up to you. I don't mind if you send commits to my PRs to fix code formatting, this is very welcome as well.

pub row: usize,
pub column: usize,
pub source_after: String,
}

pub fn generate_row_and_column(src: &str, input: &str) -> ErrorInfo {
let offset = src.len() - input.len();
let (source_before, source_after) = src.split_at(offset);

let source_after = match source_after.char_indices().enumerate().take(41).last() {
Some((40, (i, _))) => format!("{:?}...", &source_after[..i]),
_ => format!("{source_after:?}"),
};

let (row, last_line) = source_before.lines().enumerate().last().unwrap_or_default();
let column = last_line.chars().count();
ErrorInfo {
row,
column,
source_after,
}
}

/// Return the error related information and its display file path.
pub fn generate_error_info(src: &str, input: &str, file_path: &Path) -> (ErrorInfo, String) {
let file_path = match std::env::current_dir() {
Ok(cwd) => strip_common(&cwd, file_path),
Err(_) => file_path.display().to_string(),
};
let error_info = generate_row_and_column(src, input);
(error_info, file_path)
}

fn generate_error_message(
message: &str,
src: &str,
input: &str,
file_path: &Option<Rc<Path>>,
) -> String {
if let Some(file_path) = file_path {
let (
ErrorInfo {
row,
column,
source_after,
},
file_path,
) = generate_error_info(src, input, file_path);
format!(
"{message}failed to parse template source\n --> {file_path}:{row}:{column}\n{source_after}",
row = row + 1,
)
} else {
let ErrorInfo {
row,
column,
source_after,
} = generate_row_and_column(src, input);
format!(
"{message}failed to parse template source at row {}, column {column} near:\n{source_after}",
row + 1,
)
}
}

/// This type is used to handle `nom` errors and in particular to add custom error messages.
/// It used to generate `ParserError`.
///
Expand Down