Skip to content

Commit 42adf52

Browse files
committed
Add some documentation for printing error messages nicely
1 parent 2ae6c4e commit 42adf52

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

partiql-parser/src/lib.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@
77
//! # Usage
88
//!
99
//! ```
10+
//! use std::fmt;
11+
//! use std::fmt::Formatter;
12+
//! use itertools::Itertools;
13+
//! use partiql_common::syntax::location::LineAndColumn;
1014
//! use partiql_parser::{Parser, ParserError, ParserResult};
1115
//!
1216
//! let parser = Parser::default();
@@ -15,9 +19,35 @@
1519
//!
1620
//! let errs: ParserError = parser.parse("SELECT").expect_err("expected error");
1721
//!
22+
//! // Print out messages with byte offsets
1823
//! let errs_at: ParserError =
1924
//! parser.parse("SELECT * FROM a AY a CROSS JOIN c AS c AT q").unwrap_err();
2025
//! assert_eq!(errs_at.errors[0].to_string(), "Unexpected token `<a:UNQUOTED_IDENT>` at `(b19..b20)`");
26+
//!
27+
//! // Print out messages with line:column offsets
28+
//! let errs_at_nice: ParserError =
29+
//! parser.parse("SELECT * FROM a AY a CROSS JOIN c AS c AT q").unwrap_err();
30+
//! let offsets = &errs_at_nice.offsets;
31+
//! let source = &errs_at_nice.text;
32+
//! let err_msg = errs_at_nice.errors.iter().map(|e|
33+
//! e.clone().map_loc(|loc| LineAndColumn::from(offsets.at(source, loc).unwrap()).to_string())).join("\n");
34+
//! assert_eq!(err_msg, "Unexpected token `<a:UNQUOTED_IDENT>` at `(1:20..1:21)`");
35+
//!
36+
//!
37+
//!
38+
//! // Print out messages with custom line:column offsets
39+
//! #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
40+
//! pub struct VerboseLineAndColumn(LineAndColumn);
41+
//!
42+
//! impl fmt::Display for VerboseLineAndColumn {
43+
//! fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
44+
//! write!(f, "Line {}, Offset {}", self.0.line, self.0.column)
45+
//! }
46+
//! }
47+
//!
48+
//! let err_msg = errs_at_nice.errors.iter().map(|e|
49+
//! e.clone().map_loc(|loc| VerboseLineAndColumn(LineAndColumn::from(offsets.at(source, loc).unwrap())).to_string())).join("\n");
50+
//! assert_eq!(err_msg, "Unexpected token `<a:UNQUOTED_IDENT>` at `(Line 1, Offset 20..Line 1, Offset 21)`");
2151
//! ```
2252
//!
2353
//! [partiql]: https://partiql.org

0 commit comments

Comments
 (0)