lsp_core/feature/
diagnostics.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
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
use std::{collections::HashMap, fmt::Display, hash::Hash, ops::Range};

use bevy_ecs::{prelude::*, schedule::ScheduleLabel};
use chumsky::prelude::Simple;
use futures::channel::mpsc;
use lsp_types::{Diagnostic, DiagnosticSeverity, TextDocumentItem, Url};
/// [`ScheduleLabel`] related to the PrepareRename schedule
pub use systems::prefix::undefined_prefix;

use crate::prelude::*;
#[derive(ScheduleLabel, Clone, Eq, PartialEq, Debug, Hash)]
pub struct Label;

pub fn setup_schedule(world: &mut World) {
    let mut diagnostics = Schedule::new(Label);
    diagnostics.add_systems((undefined_prefix,));
    world.add_schedule(diagnostics);
}

#[derive(Resource)]
pub struct DiagnosticPublisher {
    tx: mpsc::UnboundedSender<DiagnosticItem>,
    diagnostics: HashMap<lsp_types::Url, Vec<(Diagnostic, &'static str)>>,
}

impl DiagnosticPublisher {
    pub fn new() -> (Self, mpsc::UnboundedReceiver<DiagnosticItem>) {
        let (tx, rx) = mpsc::unbounded();
        (
            Self {
                tx,
                diagnostics: HashMap::new(),
            },
            rx,
        )
    }

    pub fn publish(
        &mut self,
        params: &TextDocumentItem,
        diagnostics: Vec<Diagnostic>,
        reason: &'static str,
    ) -> Option<()> {
        let items = self.diagnostics.entry(params.uri.clone()).or_default();
        items.retain(|(_, r)| *r != reason);
        items.extend(diagnostics.into_iter().map(|x| (x, reason)));
        let diagnostics: Vec<_> = items.iter().map(|(x, _)| x).cloned().collect();
        let uri = params.uri.clone();
        let version = Some(params.version);
        let item = DiagnosticItem {
            diagnostics,
            uri,
            version,
        };
        self.tx.unbounded_send(item).ok()
    }
}

#[derive(Debug)]
pub struct SimpleDiagnostic {
    pub range: Range<usize>,
    pub msg: String,
    pub severity: Option<DiagnosticSeverity>,
}

impl SimpleDiagnostic {
    pub fn new(range: Range<usize>, msg: String) -> Self {
        Self {
            range,
            msg,
            severity: None,
        }
    }

    pub fn new_severity(range: Range<usize>, msg: String, severity: DiagnosticSeverity) -> Self {
        Self {
            range,
            msg,
            severity: Some(severity),
        }
    }
}

impl<T: Display + Eq + Hash> From<Simple<T>> for SimpleDiagnostic {
    fn from(e: Simple<T>) -> Self {
        let msg = if let chumsky::error::SimpleReason::Custom(msg) = e.reason() {
            msg.clone()
        } else {
            format!(
                "{}{}, expected {}",
                if e.found().is_some() {
                    "Unexpected token"
                } else {
                    "Unexpected end of input"
                },
                if let Some(label) = e.label() {
                    format!(" while parsing {}", label)
                } else {
                    String::new()
                },
                if e.expected().len() == 0 {
                    "something else".to_string()
                } else {
                    e.expected()
                        .map(|expected| match expected {
                            Some(expected) => format!("'{}'", expected),
                            None => "end of input".to_string(),
                        })
                        .collect::<Vec<_>>()
                        .join(" or ")
                },
            )
        };

        SimpleDiagnostic::new(e.span(), msg)
    }
}

impl<T: Display + Eq + Hash> From<(usize, Simple<T>)> for SimpleDiagnostic {
    fn from(this: (usize, Simple<T>)) -> Self {
        let (len, e) = this;
        let msg = if let chumsky::error::SimpleReason::Custom(msg) = e.reason() {
            msg.clone()
        } else {
            format!(
                "{}{}, expected {}",
                if e.found().is_some() {
                    "Unexpected token"
                } else {
                    "Unexpected end of input"
                },
                if let Some(label) = e.label() {
                    format!(" while parsing {}", label)
                } else {
                    String::new()
                },
                if e.expected().len() == 0 {
                    "something else".to_string()
                } else {
                    e.expected()
                        .map(|expected| match expected {
                            Some(expected) => format!("'{}'", expected),
                            None => "end of input".to_string(),
                        })
                        .collect::<Vec<_>>()
                        .join(" or ")
                },
            )
        };

        let range = (len - e.span().end)..(len - e.span().start);
        SimpleDiagnostic::new(range, msg)
    }
}

#[derive(Clone)]
pub struct DiagnosticSender {
    tx: mpsc::UnboundedSender<Vec<SimpleDiagnostic>>,
}

#[derive(Debug)]
pub struct DiagnosticItem {
    pub diagnostics: Vec<Diagnostic>,
    pub uri: Url,
    pub version: Option<i32>,
}
impl DiagnosticSender {
    pub fn push(&self, diagnostic: SimpleDiagnostic) -> Option<()> {
        let out = self.tx.unbounded_send(vec![diagnostic]).ok();
        out
    }

    pub fn push_all(&self, diagnostics: Vec<SimpleDiagnostic>) -> Option<()> {
        self.tx.unbounded_send(diagnostics).ok()
    }
}

pub fn publish_diagnostics<L: Lang>(
    query: Query<
        (
            &Errors<L::TokenError>,
            &Errors<L::ElementError>,
            &Wrapped<TextDocumentItem>,
            &RopeC,
            &crate::components::Label,
        ),
        (
            Or<(
                Changed<Errors<L::TokenError>>,
                Changed<Errors<L::ElementError>>,
            )>,
        ),
    >,
    mut client: ResMut<DiagnosticPublisher>,
) where
    L::TokenError: 'static + Clone,
    L::ElementError: 'static + Clone,
{
    for (token_errors, element_errors, params, rope, label) in &query {
        tracing::info!("Publish diagnostics for {}", label.0);
        use std::iter::Iterator as _;
        let token_iter = token_errors
            .0
            .iter()
            .cloned()
            .map(|x| Into::<SimpleDiagnostic>::into(x));
        let turtle_iter = element_errors
            .0
            .iter()
            .cloned()
            .map(|x| Into::<SimpleDiagnostic>::into(x));

        let diagnostics: Vec<_> = Iterator::chain(token_iter, turtle_iter)
            .flat_map(|item| {
                let (span, message) = (item.range, item.msg);
                let start_position = offset_to_position(span.start, &rope.0)?;
                let end_position = offset_to_position(span.end, &rope.0)?;
                Some(Diagnostic {
                    range: lsp_types::Range::new(start_position, end_position),
                    message,
                    severity: item.severity,
                    ..Default::default()
                })
            })
            .collect();

        let _ = client.publish(&params.0, diagnostics, "syntax");
    }
}