A simple CPU rendered GUI IDE experience.
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
use std::backtrace::Backtrace;
use std::fmt::{Debug, Display};
use std::marker::PhantomData;

use crossbeam::channel::SendError;
use lsp_server::{Message, Response as Re};
use lsp_types::DiagnosticServerCancellationData;
use lsp_types::request::Request;
use serde::{Deserialize, Serialize};
use tokio::sync::oneshot;
use tokio::task;
use tokio_util::task::AbortOnDropHandle;

use crate::lsp::Void;

#[derive(Serialize, Deserialize)]
pub enum RequestError<X> {
    Rx(PhantomData<X>),
    Failure(Re, #[serde(skip)] Option<Backtrace>),
    Cancelled(Re, DiagnosticServerCancellationData),
    Send(Message),
    // Unsupported,
}
pub type AQErr = RequestError<LSPError>;
impl Request for LSPError {
    type Params = ();
    type Result = ();
    const METHOD: &'static str = "<unknown method>";
}
#[derive(Debug)]
pub struct LSPError {}
pub trait Anonymize<T> {
    fn anonymize(self) -> Result<T, RequestError<LSPError>>;
}
impl<T, E> Anonymize<T> for Result<T, RequestError<E>> {
    fn anonymize(self) -> Result<T, RequestError<LSPError>> {
        self.map_err(|e| match e {
            RequestError::Send(x) => RequestError::Send(x),
            RequestError::Rx(_) => RequestError::Rx(PhantomData),
            RequestError::Failure(r, b) => RequestError::Failure(r, b),
            RequestError::Cancelled(r, d) => RequestError::Cancelled(r, d),
            // RequestError::Unsupported => RequestError::Unsupported,
        })
    }
}

// impl<X> Debug for RequestError<X> {}
impl<X> From<oneshot::error::RecvError> for RequestError<X> {
    fn from(_: oneshot::error::RecvError) -> Self {
        Self::Rx(PhantomData)
    }
}
impl<X: Request> std::error::Error for RequestError<X> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}
impl<X> From<SendError<Message>> for RequestError<X> {
    fn from(x: SendError<Message>) -> Self {
        Self::Send(x.into_inner())
    }
}
impl<X: Request> std::fmt::Display for RequestError<X> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Send(x) =>
                write!(f, "{} failed; couldnt send {x:?}", X::METHOD),
            Self::Rx(_) =>
                write!(f, "{} failed; couldnt get from thingy", X::METHOD),
            // RequestError::Unsupported =>
            // write!(f, "{} failed; detected as unsupported", X::METHOD),
            Self::Failure(x, bt) => write!(
                f,
                "{} failed; returned badge :( {x:?} ({bt:?})",
                X::METHOD
            ),
            Self::Cancelled(x, y) =>
                write!(f, "server cancelled {}. {x:?} {y:?}", X::METHOD),
        }
    }
}
impl<R: Request> Debug for RequestError<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self, f)
    }
}
pub trait Require<const R: &'static str> {
    fn require(&self) -> Requiring<R, ()>;
}
impl<T, const R: &'static str> Require<R> for Option<T> {
    fn require(&self) -> Requiring<R, ()> {
        self.void().ok_or(Unsupported)
    }
}
pub struct Unsupported<const R: &'static str>;
pub type Requiring<const R: &'static str, T> = Result<T, Unsupported<R>>;
impl<const R: &'static str> Display for Unsupported<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "request {} isnt supported by this LSP", R)
    }
}
pub trait Peel<E> {
    fn peel(self) -> Result<(), E>;
}
impl<E, N> Peel<E> for Result<Result<(), E>, N> {
    fn peel(self) -> Result<(), E> {
        match self {
            Ok(Err(e)) => Err(e),
            Ok(Ok(_)) | Err(_) => Ok(()),
        }
    }
}
// impl<const R: &'static str> Debug for Unsupported<R> {
//     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//         std::fmt::Display::fmt(&self, f)
//     }
// }
// impl<const X: &'static str> std::error::Error for Unsupported<X> {
//     fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
//         None
//     }
// }

fn none<T>() -> Option<T> {
    None
}
impl<T: Clone, R, D, E> Clone for Rq<T, R, D, E> {
    fn clone(&self) -> Self {
        Self { result: self.result.clone(), request: None }
    }
}
#[derive(serde_derive::Serialize, serde_derive::Deserialize)]
pub struct Rq<T, R, D = (), E = RequestError<R>> {
    #[serde(skip_serializing_if = "Option::is_none", default = "none")]
    pub result: Option<T>,
    #[serde(skip, default = "none")]
    pub request: Option<(AbortOnDropHandle<Result<R, E>>, D)>,
}
impl<T: Debug, R, D: Debug, E> Debug for Rq<T, R, D, E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct(&format!("Rq<{}>", std::any::type_name::<R>()))
            .field("result", &self.result)
            .field("request", &self.request)
            .finish()
    }
}

pub type RqS<T, R: Request, D = ()> = Rq<T, R::Result, D, RequestError<R>>;
impl<T, R, D, E> Default for Rq<T, R, D, E> {
    fn default() -> Self {
        Self { result: None, request: None }
    }
}
impl<T, R, E> Rq<T, R, (), E> {
    pub fn new(f: task::JoinHandle<Result<R, E>>) -> Self {
        Self {
            request: Some((AbortOnDropHandle::new(f), ())),
            result: None,
        }
    }
    pub fn request(&mut self, f: task::JoinHandle<Result<R, E>>) {
        self.request_d(f, ());
    }
}
impl<T, R, D, E> Rq<T, R, D, E> {
    pub fn request_d(&mut self, f: task::JoinHandle<Result<R, E>>, d: D) {
        self.request = Some((AbortOnDropHandle::new(f), d));
    }
}
impl<T, R, D, E: std::fmt::Debug> Rq<T, R, D, E> {
    pub fn running(&self) -> bool {
        matches!(
            self,
            Self { result: Some(_), .. } | Self { request: Some(_), .. },
        )
    }
    pub fn poll(
        &mut self,
        f: impl FnOnce(Result<R, E>, (D, Option<T>)) -> Option<T>,
    ) -> bool {
        if self.request.as_mut().is_some_and(|(x, _)| x.is_finished())
            && let Some((task, _)) = self.request.as_mut()
            && let Some(x) = futures::FutureExt::now_or_never(task)
        {
            let (_, d) = self.request.take().unwrap();
            self.result = f(
                match x {
                    Ok(x) => x.inspect_err(|x| {
                        dbg!(&x);
                    }),
                    Err(e) => {
                        log::error!(
                            "unexpected join error from request poll: {e}"
                        );
                        return false;
                    }
                },
                (d, self.result.take()),
            );
            true
        } else {
            false
        }
    }
}