nu_protocol/errors/shell_error/
location.rs

1use thiserror::Error;
2
3/// Represents a specific location in the Rust code.
4///
5/// This data structure is used to provide detailed information about where in the Rust code
6/// an error occurred.
7/// While most errors in [`ShellError`](super::ShellError) are related to user-provided Nushell
8/// code, some originate from the underlying Rust implementation.
9/// With this type, we can pinpoint the exact location of such errors, improving debugging
10/// and error reporting.
11#[derive(Debug, Clone, PartialEq, Eq, Error)]
12#[error("{file}:{line}:{column}")]
13pub struct Location {
14    file: &'static str,
15    line: u32,
16    column: u32,
17}
18
19impl Location {
20    /// Internal constructor for [`Location`].
21    ///
22    /// This function is not intended to be called directly.
23    /// Instead, use the [`location!`] macro to create instances.
24    #[doc(hidden)]
25    #[deprecated(
26        note = "This function is not meant to be called directly. Use `nu_protocol::location` instead."
27    )]
28    pub fn new(file: &'static str, line: u32, column: u32) -> Self {
29        Location { file, line, column }
30    }
31}
32
33/// Macro to create a new [`Location`] for the exact position in your code.
34///
35/// This macro captures the current file, line, and column during compilation,
36/// providing an easy way to associate errors with specific locations in the Rust code.
37///
38/// # Note
39/// This macro relies on the [`file!`], [`line!`], and [`column!`] macros to fetch the
40/// compilation context.
41#[macro_export]
42macro_rules! location {
43    () => {{
44        #[allow(deprecated)]
45        $crate::shell_error::location::Location::new(file!(), line!(), column!())
46    }};
47}
48
49#[test]
50fn test_location_macro() {
51    let location = crate::location!();
52    let line = line!() - 1; // Adjust for the macro call being on the previous line.
53    let file = file!();
54    assert_eq!(location.line, line);
55    assert_eq!(location.file, file);
56}