Skip to content

Commit

Permalink
Merge branch 'main' into ashar/config
Browse files Browse the repository at this point in the history
  • Loading branch information
coder3101 committed Jan 11, 2025
2 parents 0db5ddf + 8ffe219 commit 0de56c4
Show file tree
Hide file tree
Showing 16 changed files with 600 additions and 86 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "protols"
description = "Language server for proto3 files"
version = "0.8.0"
version = "0.9.0"
edition = "2021"
license = "MIT"
homepage = "https://github.com/coder3101/protols"
Expand Down
6 changes: 5 additions & 1 deletion sample/simple.proto
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ message Book {
google.protobuf.Any data = 4;
BookState state = 5;

// Author is a author of a book
// # Author is a author of a book
// Usage is as follow:
// ```rust
// println!("hello world")
// ```
message Author {
string name = 1;
int64 age = 2;
Expand Down
18 changes: 10 additions & 8 deletions src/formatter/clang.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ struct Replacement<'a> {
text: Cow<'a, str>,
}

impl<'a> Replacement<'a> {
impl Replacement<'_> {
fn offset_to_position(offset: usize, content: &str) -> Option<Position> {
if offset > content.len() {
return None;
Expand Down Expand Up @@ -81,11 +81,12 @@ impl ClangFormatter {
Some(p)
}

fn get_command(&self, u: &Path) -> Command {
fn get_command(&self, f: &str, u: &Path) -> Option<Command> {
let mut c = Command::new(self.path.as_str());
c.current_dir(self.working_dir.as_str());
c.args([u.to_str().unwrap(), "--output-replacements-xml"]);
c
c.stdin(File::open(u).ok()?);
c.args(["--output-replacements-xml", format!("--assume-filename={f}").as_str()]);
Some(c)
}

fn output_to_textedit(&self, output: &str, content: &str) -> Option<Vec<TextEdit>> {
Expand All @@ -101,9 +102,10 @@ impl ClangFormatter {
}

impl ProtoFormatter for ClangFormatter {
fn format_document(&self, content: &str) -> Option<Vec<TextEdit>> {
fn format_document(&self, filename: &str, content: &str) -> Option<Vec<TextEdit>> {
let p = self.get_temp_file_path(content)?;
let output = self.get_command(p.as_ref()).output().ok()?;
let mut cmd = self.get_command(filename, p.as_ref())?;
let output = cmd.output().ok()?;
if !output.status.success() {
tracing::error!(
status = output.status.code(),
Expand All @@ -114,12 +116,12 @@ impl ProtoFormatter for ClangFormatter {
self.output_to_textedit(&String::from_utf8_lossy(&output.stdout), content)
}

fn format_document_range(&self, r: &Range, content: &str) -> Option<Vec<TextEdit>> {
fn format_document_range(&self, r: &Range, filename: &str, content: &str) -> Option<Vec<TextEdit>> {
let p = self.get_temp_file_path(content)?;
let start = r.start.line + 1;
let end = r.end.line + 1;
let output = self
.get_command(p.as_ref())
.get_command(filename, p.as_ref())?
.args(["--lines", format!("{start}:{end}").as_str()])
.output()
.ok()?;
Expand Down
4 changes: 2 additions & 2 deletions src/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ use async_lsp::lsp_types::{Range, TextEdit};
pub mod clang;

pub trait ProtoFormatter: Sized {
fn format_document(&self, content: &str) -> Option<Vec<TextEdit>>;
fn format_document_range(&self, r: &Range, content: &str) -> Option<Vec<TextEdit>>;
fn format_document(&self, filename: &str, content: &str) -> Option<Vec<TextEdit>>;
fn format_document_range(&self, r: &Range, filename: &str, content: &str) -> Option<Vec<TextEdit>>;
}
31 changes: 12 additions & 19 deletions src/lsp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ use async_lsp::lsp_types::{
FileOperationPatternKind, FileOperationRegistrationOptions, GotoDefinitionParams,
GotoDefinitionResponse, Hover, HoverContents, HoverParams, HoverProviderCapability,
InitializeParams, InitializeResult, Location, OneOf, PrepareRenameResponse, ProgressParams,
ReferenceParams, RenameFilesParams, RenameOptions, RenameParams, ServerCapabilities, ServerInfo,
TextDocumentPositionParams, TextDocumentSyncCapability, TextDocumentSyncKind, TextEdit, Url,
WorkspaceEdit, WorkspaceFileOperationsServerCapabilities, WorkspaceFoldersServerCapabilities,
WorkspaceServerCapabilities,
ReferenceParams, RenameFilesParams, RenameOptions, RenameParams, ServerCapabilities,
ServerInfo, TextDocumentPositionParams, TextDocumentSyncCapability, TextDocumentSyncKind,
TextEdit, Url, WorkspaceEdit, WorkspaceFileOperationsServerCapabilities,
WorkspaceFoldersServerCapabilities, WorkspaceServerCapabilities,
};
use async_lsp::{LanguageClient, LanguageServer, ResponseError};
use futures::future::BoxFuture;
Expand Down Expand Up @@ -165,23 +165,16 @@ impl LanguageServer for ProtoLanguageServer {
return Box::pin(async move { Ok(None) });
};

let comments = self
let result = self
.state
.hover(current_package_name.as_ref(), identifier.as_ref());

let response = match comments.len() {
0 => None,
1 => Some(Hover {
contents: HoverContents::Scalar(comments[0].clone()),
range: None,
}),
2.. => Some(Hover {
contents: HoverContents::Array(comments),
Box::pin(async move {
Ok(result.map(|r| Hover {
range: None,
}),
};

Box::pin(async move { Ok(response) })
contents: HoverContents::Markup(r),
}))
})
}
fn completion(
&mut self,
Expand Down Expand Up @@ -372,7 +365,7 @@ impl LanguageServer for ProtoLanguageServer {
let response = self
.configs
.get_formatter_for_uri(&uri)
.and_then(|f| f.format_document(content.as_str()));
.and_then(|f| f.format_document(uri.path(), content.as_str()));

Box::pin(async move { Ok(response) })
}
Expand All @@ -387,7 +380,7 @@ impl LanguageServer for ProtoLanguageServer {
let response = self
.configs
.get_formatter_for_uri(&uri)
.and_then(|f| f.format_document_range(&params.range, content.as_str()));
.and_then(|f| f.format_document_range(&params.range, uri.path(), content.as_str()));

Box::pin(async move { Ok(response) })
}
Expand Down
8 changes: 7 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,24 @@ use server::{ProtoLanguageServer, TickEvent};
use tower::ServiceBuilder;
use tracing::Level;

mod formatter;
mod lsp;
mod nodekind;
mod parser;
mod server;
mod state;
mod utils;
mod workspace;
mod formatter;
mod config;

#[tokio::main(flavor = "current_thread")]
async fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() == 2 && args[1] == "--version" {
println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
return;
}

let (server, _) = async_lsp::MainLoop::new_server(|client| {
tokio::spawn({
let client = client.clone();
Expand Down
8 changes: 3 additions & 5 deletions src/parser/hover.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use async_lsp::lsp_types::MarkedString;
use tree_sitter::Node;

use crate::nodekind::NodeKind;
Expand Down Expand Up @@ -47,7 +46,7 @@ impl ParsedTree {
}
}

pub fn hover(&self, identifier: &str, content: impl AsRef<[u8]>) -> Vec<MarkedString> {
pub fn hover(&self, identifier: &str, content: impl AsRef<[u8]>) -> Vec<String> {
let mut results = vec![];
self.hover_impl(identifier, self.tree.root_node(), &mut results, content);
results
Expand All @@ -57,7 +56,7 @@ impl ParsedTree {
&self,
identifier: &str,
n: Node,
v: &mut Vec<MarkedString>,
v: &mut Vec<String>,
content: impl AsRef<[u8]>,
) {
if identifier.is_empty() {
Expand All @@ -77,14 +76,13 @@ impl ParsedTree {
}
}
None => {
let comments: Vec<MarkedString> = self
let comments: Vec<String> = self
.filter_nodes_from(n, NodeKind::is_userdefined)
.into_iter()
.filter(|n| {
n.utf8_text(content.as_ref()).expect("utf-8 parse error") == identifier
})
.filter_map(|n| self.find_preceding_comments(n.id(), content.as_ref()))
.map(MarkedString::String)
.collect();

v.extend(comments);
Expand Down
2 changes: 1 addition & 1 deletion src/parser/rename.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ impl ParsedTree {
.filter(|n| {
let ntext = n.utf8_text(content.as_ref()).expect("utf-8 parse error");
let sc = format!("{old_identifier}.");
return ntext == old_identifier || ntext.starts_with(&sc);
ntext == old_identifier || ntext.starts_with(&sc)
})
.map(|n| {
let text = n.utf8_text(content.as_ref()).expect("utf-8 parse error");
Expand Down
2 changes: 1 addition & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub fn split_identifier_package(s: &str) -> (&str, &str) {
});

let (package, identifier) = s.split_at(i);
return (package, identifier.trim_matches('.'));
(package, identifier.trim_matches('.'))
}

#[cfg(test)]
Expand Down
Loading

0 comments on commit 0de56c4

Please sign in to comment.