-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
responder.rs
196 lines (168 loc) · 6.02 KB
/
responder.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
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use actix::{Actor, Addr, Context, ContextFutureSpawner, Handler, WrapFuture};
use ast::range::Locatable;
use lexer::{result::LexErr, with_pos::WithPosExt, LexExt};
use log::warn;
use lsp::LspMessage;
use parser::ParseErr;
use serde_json::{json, Value as JsonValue};
use token::Token;
use valq::query_value;
use crate::{received_msg::ReceivedMsg, send_msg::SendMsg, sender::Sender};
fn text_document_uri(params_obj: &JsonValue) -> Option<&JsonValue> {
query_value!(params_obj.textDocument.uri)
}
fn lex(text: &str) -> (Vec<Token>, Vec<LexErr>) {
let (tokens, errors): (Vec<_>, Vec<_>) = text
.chars()
.with_pos()
.lex()
.flatten()
.partition(Result::is_ok);
let tokens = tokens.into_iter().map(Result::unwrap).collect::<Vec<_>>();
let errors = errors
.into_iter()
.map(Result::unwrap_err)
.collect::<Vec<_>>();
(tokens, errors)
}
fn locatable_to_json_range<L>(locatable: &L) -> JsonValue
where
L: Locatable,
{
let range = locatable.locate();
let start = range.start;
let end = range.end;
json!({
"start": { "line": start.line, "character": start.column },
"end": { "line": end.line, "character": end.column },
})
}
fn lex_err_to_diagnostic(err: &LexErr) -> JsonValue {
let range = locatable_to_json_range(err);
let message = err.to_string();
json!({ "range": range, "message": message })
}
fn parse_err_to_diagnostic(err: ParseErr) -> JsonValue {
let range = locatable_to_json_range(&err);
let message = err.to_string();
json!({ "range": range, "message": message })
}
async fn analyze_src_and_report_errs(
sender: Addr<Sender>,
uri: &JsonValue,
text: &str,
) -> anyhow::Result<()> {
let (tokens, errors) = lex(text);
let mut diagnostics: Vec<_> = errors.iter().map(lex_err_to_diagnostic).collect();
let (_stmts, errors): (Vec<_>, Vec<_>) = parser::parse(tokens.into_iter())
.into_iter()
.partition(Result::is_ok);
let diagnostics_from_parser = errors
.into_iter()
.map(Result::unwrap_err)
.map(parse_err_to_diagnostic)
.collect::<Vec<_>>();
diagnostics.extend(diagnostics_from_parser);
sender
.send(SendMsg(LspMessage::Notification {
method: "textDocument/publishDiagnostics".to_owned(),
params: json!({
"uri": uri,
"diagnostics": diagnostics,
}),
}))
.await?;
Ok(())
}
pub struct Responder {
pub sender: Addr<Sender>,
diagnostics_supported: Arc<AtomicBool>,
}
impl Responder {
pub fn new(sender: Addr<Sender>) -> Self {
Self {
sender,
diagnostics_supported: Arc::new(AtomicBool::new(false)),
}
}
}
impl Actor for Responder {
type Context = Context<Self>;
}
impl Handler<ReceivedMsg> for Responder {
type Result = ();
fn handle(&mut self, msg: ReceivedMsg, ctx: &mut Self::Context) {
let sender = self.sender.clone();
let diagnostics_supported = Arc::clone(&self.diagnostics_supported);
async move {
let diagnostics_currently_enabled = diagnostics_supported.load(Ordering::Relaxed);
match msg.0 {
LspMessage::Request { id, method, params } if method == "initialize" => {
diagnostics_supported.store(
query_value!(params.capabilities.textDocument.publishDiagnostics).is_some(),
Ordering::Relaxed,
);
sender
.send(SendMsg(LspMessage::Response {
id,
result: json!({
"capabilities": {
"textDocumentSync": 1,
}
}),
}))
.await
.unwrap()
}
LspMessage::Notification { method, params }
if diagnostics_currently_enabled && (method == "textDocument/didOpen") =>
{
if let (Some(uri), Some(text)) = (
text_document_uri(¶ms),
query_value!(params.textDocument.text -> str),
) {
analyze_src_and_report_errs(sender, uri, text)
.await
.unwrap()
} else {
warn!("Skipped: ({:?}) {:?}", method, params)
}
}
LspMessage::Notification { method, params }
if diagnostics_currently_enabled && (method == "textDocument/didChange") =>
{
if let (Some(uri), Some(text)) = (
text_document_uri(¶ms),
query_value!(params.contentChanges[0].text -> str),
) {
analyze_src_and_report_errs(sender, uri, text)
.await
.unwrap()
} else {
warn!("Skipped: ({:?}) {:?}", method, params)
}
}
LspMessage::Notification { method, params }
if diagnostics_currently_enabled && method == "textDocument/didClose" =>
{
if let Some(uri) = text_document_uri(¶ms) {
sender
.send(SendMsg(LspMessage::Notification {
method: "textDocument/publishDiagnostics".to_owned(),
params: json!({ "uri": uri, "diagnostics": [] }),
}))
.await
.unwrap()
}
}
_ => (),
}
}
.into_actor(self)
.wait(ctx);
}
}