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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
use spirv_tools_sys::{diagnostics, shared};

pub use diagnostics::MessageLevel;
pub use shared::SpirvResult;

#[derive(Debug, PartialEq)]
pub struct Error {
    pub inner: shared::SpirvResult,
    pub diagnostic: Option<Diagnostic>,
}

use std::fmt;

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.diagnostic {
            Some(diag) => {
                f.write_fmt(format_args!(
                    "error:{}:{} - {}",
                    diag.line, diag.column, diag.message
                ))?;

                if !diag.notes.is_empty() {
                    f.write_fmt(format_args!("\n{}", diag.notes))?;
                }

                Ok(())
            }
            None => f.write_str("an unknown error occurred"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.inner)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    pub line: usize,
    pub column: usize,
    pub index: usize,
    pub message: String,
    pub notes: String,
    pub is_text: bool,
}

#[cfg(feature = "use-compiled-tools")]
impl Diagnostic {
    pub(crate) unsafe fn from_diag(
        diag: *mut diagnostics::Diagnostic,
    ) -> Result<Self, shared::SpirvResult> {
        if diag.is_null() {
            return Err(shared::SpirvResult::Success);
        }

        let (message, notes) = Message::message_and_notes_from_cstr((*diag).error);

        let res = Self {
            line: (*diag).position.line,
            column: (*diag).position.column,
            index: (*diag).position.index,
            message,
            notes,
            is_text: (*diag).is_text_source,
        };

        diagnostics::diagnostic_destroy(diag);
        Ok(res)
    }
}

impl From<String> for Diagnostic {
    fn from(message: String) -> Self {
        Self {
            line: 0,
            column: 0,
            index: 0,
            is_text: false,
            message,
            notes: String::new(),
        }
    }
}

impl From<Message> for Diagnostic {
    fn from(msg: Message) -> Self {
        Self {
            line: msg.line,
            column: msg.column,
            index: msg.index,
            message: msg.message,
            notes: msg.notes,
            is_text: false,
        }
    }
}

#[derive(Debug)]
pub struct Message {
    pub level: MessageLevel,
    pub source: Option<String>,
    pub line: usize,
    pub column: usize,
    pub index: usize,
    pub message: String,
    /// Some messages can include additional information, typically instructions
    pub notes: String,
}

impl Message {
    #[cfg(feature = "use-installed-tools")]
    pub(crate) fn fatal(message: String) -> Self {
        Self {
            level: MessageLevel::Fatal,
            source: None,
            line: 0,
            column: 0,
            index: 0,
            message,
            notes: String::new(),
        }
    }

    #[cfg(feature = "use-compiled-tools")]
    unsafe fn message_and_notes_from_cstr(msg: *const std::os::raw::c_char) -> (String, String) {
        let full_message = std::ffi::CStr::from_ptr(msg).to_string_lossy();

        if let Some(ind) = full_message.find('\n') {
            (
                full_message[..ind].to_owned(),
                full_message[ind + 1..].to_owned(),
            )
        } else {
            (full_message.into_owned(), String::new())
        }
    }

    #[cfg(feature = "use-compiled-tools")]
    pub(crate) fn from_parts(
        level: MessageLevel,
        source: *const std::os::raw::c_char,
        source_pos: *const diagnostics::Position,
        msg: *const std::os::raw::c_char,
    ) -> Self {
        unsafe {
            let source = if source.is_null() {
                None
            } else {
                Some(std::ffi::CStr::from_ptr(source).to_string_lossy())
            };

            let (message, notes) = Self::message_and_notes_from_cstr(msg);

            let (line, column, index) = if source_pos.is_null() {
                (0, 0, 0)
            } else {
                (
                    (*source_pos).line,
                    (*source_pos).column,
                    (*source_pos).index,
                )
            };

            Self {
                level,
                source: source.and_then(|source| {
                    if source.is_empty() {
                        None
                    } else {
                        Some(source.into_owned())
                    }
                }),
                line,
                column,
                index,
                message,
                notes,
            }
        }
    }

    #[cfg(feature = "use-installed-tools")]
    pub(crate) fn parse(s: &str) -> Option<Self> {
        s.find(": ")
            .and_then(|i| {
                let level = match &s[..i] {
                    "error" => MessageLevel::Error,
                    "warning" => MessageLevel::Warning,
                    "info" => MessageLevel::Info,
                    _ => return None,
                };

                Some((level, i))
            })
            .and_then(|(level, i)| {
                s[i + 7..]
                    .find(": ")
                    .and_then(|i2| {
                        s[i + 7..i + 7 + i2]
                            .parse::<usize>()
                            .ok()
                            .map(|index| (index, i2))
                    })
                    .map(|(index, i2)| (level, index, i + 7 + i2 + 2))
            })
            .map(|(level, index, last)| Self {
                level,
                index,
                message: s[last..].to_owned(),
                source: None,
                line: 0,
                column: 0,
                notes: String::new(),
            })
    }
}

pub trait MessageCallback {
    fn on_message(&mut self, msg: Message);
}

impl<F> MessageCallback for F
where
    F: FnMut(Message),
{
    fn on_message(&mut self, msg: Message) {
        self(msg);
    }
}