gel_protocol/
annotations.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#[cfg(feature = "with-serde")]
use crate::encoding::Annotations;

/// CommandDataDescription1 may contain "warnings" annotations, whose value is
/// a JSON array of this [Warning] type.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "with-serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Warning {
    /// User-friendly explanation of the problem
    pub message: String,

    /// Name of the Python exception class
    pub r#type: String,

    /// Machine-friendly exception id
    pub code: u64,

    /// Name of the source file that caused the warning.
    #[cfg_attr(feature = "with-serde", serde(default))]
    pub filename: Option<String>,

    /// Additional user-friendly info
    #[cfg_attr(feature = "with-serde", serde(default))]
    pub hint: Option<String>,

    /// Developer-friendly explanation of why this problem occured
    #[cfg_attr(feature = "with-serde", serde(default))]
    pub details: Option<String>,

    /// Inclusive 0-based position within the source
    #[cfg_attr(
        feature = "with-serde",
        serde(deserialize_with = "deserialize_usize_from_str", default)
    )]
    pub start: Option<usize>,

    /// Exclusive 0-based position within the source
    #[cfg_attr(
        feature = "with-serde",
        serde(deserialize_with = "deserialize_usize_from_str", default)
    )]
    pub end: Option<usize>,

    /// 1-based index of the line of the start
    #[cfg_attr(
        feature = "with-serde",
        serde(deserialize_with = "deserialize_usize_from_str", default)
    )]
    pub line: Option<usize>,

    /// 1-based index of the column of the start
    #[cfg_attr(
        feature = "with-serde",
        serde(deserialize_with = "deserialize_usize_from_str", default)
    )]
    pub col: Option<usize>,
}

impl std::fmt::Display for Warning {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Warning {
            filename,
            line,
            col,
            r#type,
            message,
            ..
        } = self;
        let filename = filename
            .as_ref()
            .map(|f| format!("{f}:"))
            .unwrap_or_default();
        let line = line.clone().unwrap_or(1);
        let col = col.clone().unwrap_or(1);

        write!(f, "{type} at {filename}{line}:{col} {message}")
    }
}

#[cfg(feature = "with-serde")]
pub fn decode_warnings(annotations: &Annotations) -> Result<Vec<Warning>, gel_errors::Error> {
    use gel_errors::{ErrorKind, ProtocolEncodingError};

    const ANN_NAME: &str = "warnings";

    if let Some(warnings) = annotations.get(ANN_NAME) {
        serde_json::from_str::<Vec<_>>(warnings).map_err(|e| {
            ProtocolEncodingError::with_source(e)
                .context("Invalid JSON while decoding 'warnings' annotation")
        })
    } else {
        Ok(vec![])
    }
}

#[cfg(feature = "with-serde")]
fn deserialize_usize_from_str<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<usize>, D::Error> {
    use serde::Deserialize;

    #[derive(Deserialize)]
    #[serde(untagged)]
    enum StringOrInt {
        String(String),
        Number(usize),
    }

    Option::<StringOrInt>::deserialize(deserializer)?
        .map(|x| match x {
            StringOrInt::String(s) => s.parse::<usize>().map_err(serde::de::Error::custom),
            StringOrInt::Number(i) => Ok(i),
        })
        .transpose()
}

#[test]
#[cfg(feature = "with-serde")]
fn deserialize_warning() {
    let a: Warning =
        serde_json::from_str(r#"{"message": "a", "type": "WarningException", "code": 1}"#).unwrap();
    assert_eq!(
        a,
        Warning {
            message: "a".to_string(),
            r#type: "WarningException".to_string(),
            code: 1,
            filename: None,
            hint: None,
            details: None,
            start: None,
            end: None,
            line: None,
            col: None
        }
    );

    let a: Warning = serde_json::from_str(
        r#"{"message": "a", "type": "WarningException", "code": 1, "start": null}"#,
    )
    .unwrap();
    assert_eq!(
        a,
        Warning {
            message: "a".to_string(),
            r#type: "WarningException".to_string(),
            code: 1,
            filename: None,
            hint: None,
            details: None,
            start: None,
            end: None,
            line: None,
            col: None
        }
    );

    let a: Warning = serde_json::from_str(
        r#"{"message": "a", "type": "WarningException", "code": 1, "start": 23}"#,
    )
    .unwrap();
    assert_eq!(
        a,
        Warning {
            message: "a".to_string(),
            r#type: "WarningException".to_string(),
            code: 1,
            filename: None,
            hint: None,
            details: None,
            start: Some(23),
            end: None,
            line: None,
            col: None
        }
    );

    let a: Warning = serde_json::from_str(
        r#"{"message": "a", "type": "WarningException", "code": 1, "start": "23"}"#,
    )
    .unwrap();
    assert_eq!(
        a,
        Warning {
            message: "a".to_string(),
            r#type: "WarningException".to_string(),
            code: 1,
            filename: None,
            hint: None,
            details: None,
            start: Some(23),
            end: None,
            line: None,
            col: None
        }
    );
}