on master help sign in
wip: Async async. Delay response handling with a callback.
2a3910cBlaž Hrastnik
Cargo.lock+2
@@ -549,6 +549,8 @@ dependencies = [
549 "num_cpus",
549 "num_cpus",
550 "once_cell",
550 "once_cell",
551 "pulldown-cmark",
551 "pulldown-cmark",
552+ "serde",
553+ "serde_json",
552 "smol",
554 "smol",
553 "smol-timeout",
555 "smol-timeout",
554 "toml",
556 "toml",
helix-lsp/src/client.rs+28−25
@@ -1,13 +1,12 @@
1use crate::{
1use crate::{
2 transport::{Payload, Transport},
2 transport::{Payload, Transport},
3− Call, Error,
3+ Call, Error, Result,
4};
4};
5
5
6−type Result<T> = core::result::Result<T, Error>;
7−
8use helix_core::{ChangeSet, Rope};
6use helix_core::{ChangeSet, Rope};
9
7
10// use std::collections::HashMap;
8// use std::collections::HashMap;
9+use std::future::Future;
11use std::sync::atomic::{AtomicU64, Ordering};
10use std::sync::atomic::{AtomicU64, Ordering};
12
11
13use jsonrpc_core as jsonrpc;
12use jsonrpc_core as jsonrpc;
@@ -96,6 +95,21 @@ impl Client {
96 where
95 where
97 R::Params: serde::Serialize,
96 R::Params: serde::Serialize,
98 R::Result: core::fmt::Debug, // TODO: temporary
97 R::Result: core::fmt::Debug, // TODO: temporary
98+ {
99+ // a future that resolves into the response
100+ let future = self.call::<R>(params).await?;
101+ let json = future.await?;
102+ let response = serde_json::from_value(json)?;
103+ Ok(response)
104+ }
105+
106+ /// Execute a RPC request on the language server.
107+ pub async fn call<R: lsp::request::Request>(
108+ &self,
109+ params: R::Params,
110+ ) -> Result<impl Future<Output = Result<Value>>>
111+ where
112+ R::Params: serde::Serialize,
99 {
113 {
100 let params = serde_json::to_value(params)?;
114 let params = serde_json::to_value(params)?;
101
115
@@ -119,15 +133,15 @@ impl Client {
119 use smol_timeout::TimeoutExt;
133 use smol_timeout::TimeoutExt;
120 use std::time::Duration;
134 use std::time::Duration;
121
135
136+ let future = async move {
137+ rx.recv()
122− let response = match rx.recv().timeout(Duration::from_secs(2)).await {
138+ .timeout(Duration::from_secs(2))
123− Some(response) => response,
139+ .await
124− None => return Err(Error::Timeout),
140+ .ok_or(Error::Timeout)? // return Timeout
125− }
126− .map_err(|e| Error::Other(e.into()))??;
141+ .map_err(|e| Error::Other(e.into()))?
127−
142+ };
128− let response = serde_json::from_value(response)?;
129
143
130− Ok(response)
144+ Ok(future)
131 }
145 }
132
146
133 /// Send a RPC notification to the language server.
147 /// Send a RPC notification to the language server.
@@ -447,7 +461,8 @@ impl Client {
447 &self,
461 &self,
448 text_document: lsp::TextDocumentIdentifier,
462 text_document: lsp::TextDocumentIdentifier,
449 position: lsp::Position,
463 position: lsp::Position,
464+ ) -> Result<impl Future<Output = Result<Value>>> {
450− ) -> Result<Vec<lsp::CompletionItem>> {
465+ // ) -> Result<Vec<lsp::CompletionItem>> {
451 let params = lsp::CompletionParams {
466 let params = lsp::CompletionParams {
452 text_document_position: lsp::TextDocumentPositionParams {
467 text_document_position: lsp::TextDocumentPositionParams {
453 text_document,
468 text_document,
@@ -464,19 +479,7 @@ impl Client {
464 // lsp::CompletionContext { trigger_kind: , trigger_character: Some(), }
479 // lsp::CompletionContext { trigger_kind: , trigger_character: Some(), }
465 };
480 };
466
481
467− let response = self.request::<lsp::request::Completion>(params).await?;
482+ self.call::<lsp::request::Completion>(params).await
468−
469− let items = match response {
470− Some(lsp::CompletionResponse::Array(items)) => items,
471− // TODO: do something with is_incomplete
472− Some(lsp::CompletionResponse::List(lsp::CompletionList {
473− is_incomplete: _is_incomplete,
474− items,
475− })) => items,
476− None => Vec::new(),
477− };
478−
479− Ok(items)
480 }
483 }
481
484
482 pub async fn text_document_signature_help(
485 pub async fn text_document_signature_help(
helix-lsp/src/lib.rs+2
@@ -8,6 +8,8 @@ pub use lsp_types as lsp;
8pub use client::Client;
8pub use client::Client;
9pub use lsp::{Position, Url};
9pub use lsp::{Position, Url};
10
10
11+pub type Result<T> = core::result::Result<T, Error>;
12+
11use helix_core::syntax::LanguageConfiguration;
13use helix_core::syntax::LanguageConfiguration;
12
14
13use thiserror::Error;
15use thiserror::Error;
helix-term/Cargo.toml+3
@@ -44,3 +44,6 @@ pulldown-cmark = { version = "0.8", default-features = false }
44
44
45# config
45# config
46toml = "0.5"
46toml = "0.5"
47+
48+serde_json = "1.0"
49+serde = { version = "1.0", features = ["derive"] }
helix-term/src/application.rs+29
@@ -24,11 +24,23 @@ use crossterm::{
24
24
25use tui::layout::Rect;
25use tui::layout::Rect;
26
26
27+// use futures_util::future::BoxFuture;
28+use futures_util::stream::FuturesUnordered;
29+use std::pin::Pin;
30+
31+type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
32+pub type LspCallback =
33+ BoxFuture<Result<Box<dyn FnOnce(&mut Editor, &mut Compositor) + Send>, anyhow::Error>>;
34+
35+pub type LspCallbacks = FuturesUnordered<LspCallback>;
36+pub type LspCallbackWrapper = Box<dyn FnOnce(&mut Editor, &mut Compositor) + Send>;
37+
27pub struct Application {
38pub struct Application {
28 compositor: Compositor,
39 compositor: Compositor,
29 editor: Editor,
40 editor: Editor,
30
41
31 executor: &'static smol::Executor<'static>,
42 executor: &'static smol::Executor<'static>,
43+ callbacks: LspCallbacks,
32}
44}
33
45
34impl Application {
46impl Application {
@@ -50,6 +62,7 @@ impl Application {
50 editor,
62 editor,
51
63
52 executor,
64 executor,
65+ callbacks: FuturesUnordered::new(),
53 };
66 };
54
67
55 Ok(app)
68 Ok(app)
@@ -59,10 +72,12 @@ impl Application {
59 let executor = &self.executor;
72 let executor = &self.executor;
60 let editor = &mut self.editor;
73 let editor = &mut self.editor;
61 let compositor = &mut self.compositor;
74 let compositor = &mut self.compositor;
75+ let callbacks = &mut self.callbacks;
62
76
63 let mut cx = crate::compositor::Context {
77 let mut cx = crate::compositor::Context {
64 editor,
78 editor,
65 executor,
79 executor,
80+ callbacks,
66 scroll: None,
81 scroll: None,
67 };
82 };
68
83
@@ -87,14 +102,28 @@ impl Application {
87 call = self.editor.language_servers.incoming.next().fuse() => {
102 call = self.editor.language_servers.incoming.next().fuse() => {
88 self.handle_language_server_message(call).await
103 self.handle_language_server_message(call).await
89 }
104 }
105+ callback = self.callbacks.next().fuse() => {
106+ self.handle_language_server_callback(callback)
107+ }
90 }
108 }
91 }
109 }
92 }
110 }
111+ pub fn handle_language_server_callback(
112+ &mut self,
113+ callback: Option<Result<LspCallbackWrapper, anyhow::Error>>,
114+ ) {
115+ if let Some(Ok(callback)) = callback {
116+ // TODO: handle Err()
117+ callback(&mut self.editor, &mut self.compositor);
118+ self.render();
119+ }
120+ }
93
121
94 pub fn handle_terminal_events(&mut self, event: Option<Result<Event, crossterm::ErrorKind>>) {
122 pub fn handle_terminal_events(&mut self, event: Option<Result<Event, crossterm::ErrorKind>>) {
95 let mut cx = crate::compositor::Context {
123 let mut cx = crate::compositor::Context {
96 editor: &mut self.editor,
124 editor: &mut self.editor,
97 executor: &self.executor,
125 executor: &self.executor,
126+ callbacks: &mut self.callbacks,
98 scroll: None,
127 scroll: None,
99 };
128 };
100 // Handle key events
129 // Handle key events
helix-term/src/commands.rs+152−79
@@ -10,7 +10,7 @@ use helix_core::{
10use once_cell::sync::Lazy;
10use once_cell::sync::Lazy;
11
11
12use crate::{
12use crate::{
13− compositor::{Callback, Compositor},
13+ compositor::{Callback, Component, Compositor},
14 ui::{self, Picker, Popup, Prompt, PromptEvent},
14 ui::{self, Picker, Popup, Prompt, PromptEvent},
15};
15};
16
16
@@ -26,14 +26,20 @@ use crossterm::event::{KeyCode, KeyEvent};
26
26
27use helix_lsp::lsp;
27use helix_lsp::lsp;
28
28
29+use crate::application::{LspCallbackWrapper, LspCallbacks};
30+
29pub struct Context<'a> {
31pub struct Context<'a> {
30 pub count: usize,
32 pub count: usize,
31 pub editor: &'a mut Editor,
33 pub editor: &'a mut Editor,
32
34
33 pub callback: Option<crate::compositor::Callback>,
35 pub callback: Option<crate::compositor::Callback>,
34 pub on_next_key_callback: Option<Box<dyn FnOnce(&mut Context, KeyEvent)>>,
36 pub on_next_key_callback: Option<Box<dyn FnOnce(&mut Context, KeyEvent)>>,
37+ pub callbacks: &'a mut LspCallbacks,
35}
38}
36
39
40+use futures_util::FutureExt;
41+use std::future::Future;
42+
37impl<'a> Context<'a> {
43impl<'a> Context<'a> {
38 #[inline]
44 #[inline]
39 pub fn view(&mut self) -> &mut View {
45 pub fn view(&mut self) -> &mut View {
@@ -47,7 +53,7 @@ impl<'a> Context<'a> {
47 }
53 }
48
54
49 /// Push a new component onto the compositor.
55 /// Push a new component onto the compositor.
50− pub fn push_layer(&mut self, mut component: Box<dyn crate::compositor::Component>) {
56+ pub fn push_layer(&mut self, mut component: Box<dyn Component>) {
51 self.callback = Some(Box::new(
57 self.callback = Some(Box::new(
52 |compositor: &mut Compositor, editor: &mut Editor| {
58 |compositor: &mut Compositor, editor: &mut Editor| {
53 let size = compositor.size();
59 let size = compositor.size();
@@ -65,6 +71,27 @@ impl<'a> Context<'a> {
65 ) {
71 ) {
66 self.on_next_key_callback = Some(Box::new(on_next_key_callback));
72 self.on_next_key_callback = Some(Box::new(on_next_key_callback));
67 }
73 }
74+
75+ #[inline]
76+ pub fn callback<T, F>(
77+ &mut self,
78+ call: impl Future<Output = helix_lsp::Result<serde_json::Value>> + 'static + Send,
79+ callback: F,
80+ ) where
81+ T: for<'de> serde::Deserialize<'de> + Send + 'static,
82+ F: FnOnce(&mut Editor, &mut Compositor, T) + Send + 'static,
83+ {
84+ let callback = Box::pin(async move {
85+ let json = call.await?;
86+ let response = serde_json::from_value(json)?;
87+ let call: LspCallbackWrapper =
88+ Box::new(move |editor: &mut Editor, compositor: &mut Compositor| {
89+ callback(editor, compositor, response)
90+ });
91+ Ok(call)
92+ });
93+ self.callbacks.push(callback);
94+ }
68}
95}
69
96
70/// A command is a function that takes the current state and a count, and does a side-effect on the
97/// A command is a function that takes the current state and a count, and does a side-effect on the
@@ -1564,6 +1591,24 @@ pub fn save(cx: &mut Context) {
1564}
1591}
1565
1592
1566pub fn completion(cx: &mut Context) {
1593pub fn completion(cx: &mut Context) {
1594+ // trigger on trigger char, or if user calls it
1595+ // (or on word char typing??)
1596+ // after it's triggered, if response marked is_incomplete, update on every subsequent keypress
1597+ //
1598+ // lsp calls are done via a callback: it sends a request and doesn't block.
1599+ // when we get the response similarly to notification, trigger a call to the completion popup
1600+ //
1601+ // language_server.completion(params, |cx: &mut Context, _meta, response| {
1602+ // // called at response time
1603+ // // compositor, lookup completion layer
1604+ // // downcast dyn Component to Completion component
1605+ // // emit response to completion (completion.complete/handle(response))
1606+ // })
1607+ // async {
1608+ // let (response, callback) = response.await?;
1609+ // callback(response)
1610+ // }
1611+
1567 let doc = cx.doc();
1612 let doc = cx.doc();
1568
1613
1569 let language_server = match doc.language_server() {
1614 let language_server = match doc.language_server() {
@@ -1576,91 +1621,119 @@ pub fn completion(cx: &mut Context) {
1576
1621
1577 // TODO: handle fails
1622 // TODO: handle fails
1578
1623
1579− let res = smol::block_on(language_server.completion(doc.identifier(), pos)).unwrap_or_default();
1624+ let res = smol::block_on(language_server.completion(doc.identifier(), pos)).unwrap();
1580−
1625+
1626+ cx.callback(
1627+ res,
1628+ |editor: &mut Editor,
1629+ compositor: &mut Compositor,
1630+ response: Option<lsp::CompletionResponse>| {
1631+ let items = match response {
1632+ Some(lsp::CompletionResponse::Array(items)) => items,
1633+ // TODO: do something with is_incomplete
1634+ Some(lsp::CompletionResponse::List(lsp::CompletionList {
1635+ is_incomplete: _is_incomplete,
1636+ items,
1637+ })) => items,
1638+ None => Vec::new(),
1639+ };
1640+
1581− // TODO: if no completion, show some message or something
1641+ // TODO: if no completion, show some message or something
1582− if !res.is_empty() {
1642+ if !items.is_empty() {
1583− // let snapshot = doc.state.clone();
1643+ // let snapshot = doc.state.clone();
1584− let mut menu = ui::Menu::new(
1644+ let mut menu = ui::Menu::new(
1585− res,
1645+ items,
1586− |item| {
1646+ |item| {
1587− // format_fn
1647+ // format_fn
1588− item.label.as_str().into()
1648+ item.label.as_str().into()
1589−
1649+
1590− // TODO: use item.filter_text for filtering
1650+ // TODO: use item.filter_text for filtering
1591− },
1651+ },
1592− move |editor: &mut Editor, item, event| {
1652+ move |editor: &mut Editor, item, event| {
1593− match event {
1653+ match event {
1594− PromptEvent::Abort => {
1654+ PromptEvent::Abort => {
1595− // revert state
1655+ // revert state
1596− // let id = editor.view().doc;
1656+ // let id = editor.view().doc;
1597− // let doc = &mut editor.documents[id];
1657+ // let doc = &mut editor.documents[id];
1598− // doc.state = snapshot.clone();
1658+ // doc.state = snapshot.clone();
1599− }
1659+ }
1600− PromptEvent::Validate => {
1660+ PromptEvent::Validate => {
1601− let id = editor.view().doc;
1661+ let id = editor.view().doc;
1602− let doc = &mut editor.documents[id];
1662+ let doc = &mut editor.documents[id];
1603−
1663+
1604− // revert state to what it was before the last update
1664+ // revert state to what it was before the last update
1605− // doc.state = snapshot.clone();
1665+ // doc.state = snapshot.clone();
1606−
1666+
1607− // extract as fn(doc, item):
1667+ // extract as fn(doc, item):
1608−
1668+
1609− // TODO: need to apply without composing state...
1669+ // TODO: need to apply without composing state...
1610− // TODO: need to update lsp on accept/cancel by diffing the snapshot with
1670+ // TODO: need to update lsp on accept/cancel by diffing the snapshot with
1611− // the final state?
1671+ // the final state?
1612− // -> on update simply update the snapshot, then on accept redo the call,
1672+ // -> on update simply update the snapshot, then on accept redo the call,
1613− // finally updating doc.changes + notifying lsp.
1673+ // finally updating doc.changes + notifying lsp.
1614− //
1674+ //
1615− // or we could simply use doc.undo + apply when changing between options
1675+ // or we could simply use doc.undo + apply when changing between options
1616−
1676+
1617− // always present here
1677+ // always present here
1618− let item = item.unwrap();
1678+ let item = item.unwrap();
1619−
1679+
1620− use helix_lsp::{lsp, util};
1680+ use helix_lsp::{lsp, util};
1621− // determine what to insert: text_edit | insert_text | label
1681+ // determine what to insert: text_edit | insert_text | label
1622− let edit = if let Some(edit) = &item.text_edit {
1682+ let edit = if let Some(edit) = &item.text_edit {
1623− match edit {
1683+ match edit {
1624− lsp::CompletionTextEdit::Edit(edit) => edit.clone(),
1684+ lsp::CompletionTextEdit::Edit(edit) => edit.clone(),
1625− lsp::CompletionTextEdit::InsertAndReplace(item) => {
1685+ lsp::CompletionTextEdit::InsertAndReplace(item) => {
1686+ unimplemented!(
1626− unimplemented!("completion: insert_and_replace {:?}", item)
1687+ "completion: insert_and_replace {:?}",
1688+ item
1689+ )
1690+ }
1691+ }
1692+ } else {
1693+ item.insert_text.as_ref().unwrap_or(&item.label);
1694+ unimplemented!();
1695+ // lsp::TextEdit::new(); TODO: calculate a TextEdit from insert_text
1696+ // and we insert at position.
1697+ };
1698+
1699+ // TODO: merge edit with additional_text_edits
1700+ if let Some(additional_edits) = &item.additional_text_edits {
1701+ if !additional_edits.is_empty() {
1702+ unimplemented!(
1703+ "completion: additional_text_edits: {:?}",
1704+ additional_edits
1705+ );
1706+ }
1627 }
1707 }
1708+
1709+ let transaction =
1710+ util::generate_transaction_from_edits(doc.text(), vec![edit]);
1711+ doc.apply(&transaction);
1712+ // TODO: doc.append_changes_to_history(); if not in insert mode?
1628 }
1713 }
1629− } else {
1714+ _ => (),
1630− item.insert_text.as_ref().unwrap_or(&item.label);
1631− unimplemented!();
1632− // lsp::TextEdit::new(); TODO: calculate a TextEdit from insert_text
1633− // and we insert at position.
1634 };
1715 };
1716+ },
1717+ );
1635
1718
1636− // TODO: merge edit with additional_text_edits
1719+ let popup = Popup::new(Box::new(menu));
1637− if let Some(additional_edits) = &item.additional_text_edits {
1720+ let mut component: Box<dyn Component> = Box::new(popup);
1638− if !additional_edits.is_empty() {
1639− unimplemented!(
1640− "completion: additional_text_edits: {:?}",
1641− additional_edits
1642− );
1643− }
1644− }
1645
1721
1646− // TODO: <-- if state has changed by further input, transaction will panic on len
1722+ // Server error: content modified
1647− let transaction =
1648− util::generate_transaction_from_edits(doc.text(), vec![edit]);
1649− doc.apply(&transaction);
1650− // TODO: doc.append_changes_to_history(); if not in insert mode?
1651− }
1652− _ => (),
1653− };
1654− },
1655− );
1656
1723
1657− let popup = Popup::new(Box::new(menu));
1658− cx.push_layer(Box::new(popup));
1724+ // TODO: this is shared with cx.push_layer
1725+ let size = compositor.size();
1726+ // trigger required_size on init
1727+ component.required_size((size.width, size.height));
1728+ compositor.push(component);
1729+ }
1730+ },
1731+ );
1659
1732
1660− // TODO!: when iterating over items, show the docs in popup
1733+ // // TODO!: when iterating over items, show the docs in popup
1661
1734
1662− // language server client needs to be accessible via a registry of some sort
1735+ // // language server client needs to be accessible via a registry of some sort
1663− }
1736+ //}
1664}
1737}
1665
1738
1666pub fn hover(cx: &mut Context) {
1739pub fn hover(cx: &mut Context) {
helix-term/src/compositor.rs+3
@@ -25,10 +25,13 @@ pub enum EventResult {
25
25
26use helix_view::{Editor, View};
26use helix_view::{Editor, View};
27
27
28+use crate::application::LspCallbacks;
29+
28pub struct Context<'a> {
30pub struct Context<'a> {
29 pub editor: &'a mut Editor,
31 pub editor: &'a mut Editor,
30 pub executor: &'static smol::Executor<'static>,
32 pub executor: &'static smol::Executor<'static>,
31 pub scroll: Option<usize>,
33 pub scroll: Option<usize>,
34+ pub callbacks: &'a mut LspCallbacks,
32}
35}
33
36
34pub trait Component {
37pub trait Component {
helix-term/src/ui/editor.rs+1
@@ -439,6 +439,7 @@ impl Component for EditorView {
439 editor: &mut cx.editor,
439 editor: &mut cx.editor,
440 count: 1,
440 count: 1,
441 callback: None,
441 callback: None,
442+ callbacks: cx.callbacks,
442 on_next_key_callback: None,
443 on_next_key_callback: None,
443 };
444 };
444
445