Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LSP Server: Improvements #168

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 22 additions & 25 deletions compiler/server/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,29 @@ use crate::span::ToLocationExt;
use diagnostics::{Code, Highlight, LintCode, Role, Severity, UnboxedUntaggedDiagnostic};
use span::SourceMap;
use std::{collections::BTreeSet, default::default};
use tower_lsp::lsp_types::{
self, DiagnosticRelatedInformation, DiagnosticSeverity, DiagnosticTag, MessageType,
NumberOrString, OneOf, Range,
};
use tower_lsp::lsp_types as lsp;

const DIAGNOSTIC_SOURCE: &str = "source";

pub(crate) type LspMessage = (MessageType, String);
pub(crate) type LspMessage = (lsp::MessageType, String);

pub(crate) trait DiagnosticExt {
fn into_lsp_type(self, map: &SourceMap) -> OneOf<lsp_types::Diagnostic, LspMessage>;
fn into_lsp_type(self, map: &SourceMap) -> lsp::OneOf<lsp::Diagnostic, LspMessage>;
}

impl DiagnosticExt for UnboxedUntaggedDiagnostic {
fn into_lsp_type(self, map: &SourceMap) -> OneOf<lsp_types::Diagnostic, LspMessage> {
fn into_lsp_type(self, map: &SourceMap) -> lsp::OneOf<lsp::Diagnostic, LspMessage> {
// @Task explain the " "-hack
let message = self.message.unwrap_or_else(|| " ".into()).into();

match convert_highlights(self.highlights, map) {
Some((range, related_information)) => {
let tags = self.code.and_then(|code| {
(code == Code::Lint(LintCode::Deprecated))
.then(|| vec![DiagnosticTag::DEPRECATED])
.then(|| vec![lsp::DiagnosticTag::DEPRECATED])
});

OneOf::Left(lsp_types::Diagnostic {
lsp::OneOf::Left(lsp::Diagnostic {
range,
severity: Some(IntoLspType::into(self.severity)),
code: self.code.map(IntoLspType::into),
Expand All @@ -38,15 +35,15 @@ impl DiagnosticExt for UnboxedUntaggedDiagnostic {
..default()
})
}
None => OneOf::Right((IntoLspType::into(self.severity), message)),
None => lsp::OneOf::Right((IntoLspType::into(self.severity), message)),
}
}
}

fn convert_highlights(
highlights: BTreeSet<Highlight>,
map: &SourceMap,
) -> Option<(Range, Vec<DiagnosticRelatedInformation>)> {
) -> Option<(lsp::Range, Vec<lsp::DiagnosticRelatedInformation>)> {
let mut range = None;
let mut related_information = Vec::new();

Expand All @@ -56,7 +53,7 @@ fn convert_highlights(
// @Beacon @Bug we are ignoring the file assoc w/ the span!!!
range = Some(highlight.span.to_location(map).range);
} else {
related_information.push(DiagnosticRelatedInformation {
related_information.push(lsp::DiagnosticRelatedInformation {
location: highlight.span.to_location(map),
// @Task explain " "-hack
message: highlight.label.unwrap_or_else(|| " ".into()).into(),
Expand All @@ -71,28 +68,28 @@ trait IntoLspType<Output> {
fn into(self) -> Output;
}

impl IntoLspType<DiagnosticSeverity> for Severity {
fn into(self) -> DiagnosticSeverity {
impl IntoLspType<lsp::DiagnosticSeverity> for Severity {
fn into(self) -> lsp::DiagnosticSeverity {
match self {
Self::Bug | Self::Error => DiagnosticSeverity::ERROR,
Self::Warning => DiagnosticSeverity::WARNING,
Self::Debug => DiagnosticSeverity::INFORMATION,
Self::Bug | Self::Error => lsp::DiagnosticSeverity::ERROR,
Self::Warning => lsp::DiagnosticSeverity::WARNING,
Self::Debug => lsp::DiagnosticSeverity::INFORMATION,
}
}
}

impl IntoLspType<MessageType> for Severity {
fn into(self) -> MessageType {
impl IntoLspType<lsp::MessageType> for Severity {
fn into(self) -> lsp::MessageType {
match self {
Self::Bug | Self::Error => MessageType::ERROR,
Self::Warning => MessageType::WARNING,
Self::Debug => MessageType::INFO,
Self::Bug | Self::Error => lsp::MessageType::ERROR,
Self::Warning => lsp::MessageType::WARNING,
Self::Debug => lsp::MessageType::INFO,
}
}
}

impl IntoLspType<NumberOrString> for Code {
fn into(self) -> NumberOrString {
NumberOrString::String(self.to_string())
impl IntoLspType<lsp::NumberOrString> for Code {
fn into(self) -> lsp::NumberOrString {
lsp::NumberOrString::String(self.to_string())
}
}
92 changes: 48 additions & 44 deletions compiler/server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,7 @@ use std::{
path::Path,
sync::{Arc, RwLock},
};
use tower_lsp::{
jsonrpc,
lsp_types::{
DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
GotoDefinitionParams, GotoDefinitionResponse, InitializeParams, InitializeResult,
InitializedParams, MessageType, OneOf, ServerCapabilities, ServerInfo,
TextDocumentSyncKind, TextDocumentSyncOptions, Url,
},
Client,
};
use tower_lsp::{jsonrpc, lsp_types as lsp, Client};
use utilities::{ComponentIndex, FormatError, HashMap};

mod diagnostics;
Expand All @@ -46,7 +37,7 @@ pub async fn serve(map: Arc<RwLock<SourceMap>>) {
struct Server {
map: Arc<RwLock<SourceMap>>,
// @Beacon @Task remove this, we don't need this!! we have a frckin SourceMap here!!!
documents: RwLock<HashMap<Url, Arc<String>>>,
documents: RwLock<HashMap<lsp::Url, Arc<String>>>,
client: Client,
}

Expand All @@ -69,15 +60,8 @@ impl Server {
*self.map.write().unwrap() = default();
}

async fn validate_file(&self, uri: Url, version: i32, content: Arc<String>) {
let scheme = uri.scheme();
if scheme != "file" {
self.client
.log_message(
MessageType::ERROR,
format!("Unsupported URI scheme ‘{scheme}’"),
)
.await;
async fn validate_file(&self, uri: lsp::Url, version: i32, content: Arc<String>) {
if self.validate_uri(&uri).await.is_err() {
return;
}

Expand All @@ -99,14 +83,16 @@ impl Server {
self.report(diagnostics, uri, version).await;
}

async fn report(&self, diagnostics: BTreeSet<UntaggedDiagnostic>, uri: Url, version: i32) {
async fn report(&self, diagnostics: BTreeSet<UntaggedDiagnostic>, uri: lsp::Url, version: i32) {
let mut lsp_diagnostics = Vec::new();

for diagnostic in diagnostics {
let diagnostic = diagnostic.into_lsp_type(&self.map.read().unwrap());
match diagnostic {
OneOf::Left(diagnostic) => lsp_diagnostics.push(diagnostic),
OneOf::Right((type_, message)) => self.client.show_message(type_, message).await,
lsp::OneOf::Left(diagnostic) => lsp_diagnostics.push(diagnostic),
lsp::OneOf::Right((type_, message)) => {
self.client.show_message(type_, message).await
}
}
}

Expand All @@ -115,44 +101,60 @@ impl Server {
.publish_diagnostics(uri, lsp_diagnostics, Some(version))
.await;
}

async fn validate_uri(&self, uri: &lsp::Url) -> Result<(), ()> {
let scheme = uri.scheme();

if scheme != "file" {
self.client
.show_message(
lsp::MessageType::ERROR,
format!("unsupported URI scheme ‘{scheme}’"),
)
.await;
return Err(());
}

Ok(())
}
}

// @Task replace the async tower_lsp library with a sync server. async is not worth it
#[tower_lsp::async_trait]
impl tower_lsp::LanguageServer for Server {
async fn initialize(&self, _: InitializeParams) -> jsonrpc::Result<InitializeResult> {
Ok(InitializeResult {
capabilities: ServerCapabilities {
async fn initialize(&self, _: lsp::InitializeParams) -> jsonrpc::Result<lsp::InitializeResult> {
Ok(lsp::InitializeResult {
capabilities: lsp::ServerCapabilities {
text_document_sync: Some(
TextDocumentSyncOptions {
lsp::TextDocumentSyncOptions {
open_close: Some(true),
change: Some(TextDocumentSyncKind::FULL),
change: Some(lsp::TextDocumentSyncKind::FULL),
..default()
}
.into(),
),
definition_provider: Some(OneOf::Left(true)),
definition_provider: Some(lsp::OneOf::Left(true)),
..default()
},
server_info: Some(ServerInfo {
server_info: Some(lsp::ServerInfo {
name: NAME.into(),
// @Task supply version here (do what main.rs does)
version: None,
}),
})
}

async fn initialized(&self, _: InitializedParams) {
async fn initialized(&self, _: lsp::InitializedParams) {
self.client
.log_message(MessageType::INFO, "Language server initialized")
.log_message(lsp::MessageType::INFO, "Language server initialized")
.await;
}

async fn shutdown(&self) -> jsonrpc::Result<()> {
Ok(())
}

async fn did_open(&self, parameters: DidOpenTextDocumentParams) {
async fn did_open(&self, parameters: lsp::DidOpenTextDocumentParams) {
let content = Arc::new(parameters.text_document.text);

self.documents
Expand All @@ -165,7 +167,7 @@ impl tower_lsp::LanguageServer for Server {
.await;
}

async fn did_change(&self, mut parameters: DidChangeTextDocumentParams) {
async fn did_change(&self, mut parameters: lsp::DidChangeTextDocumentParams) {
// @Bug incredibly fragile!
let content = Arc::new(parameters.content_changes.swap_remove(0).text);

Expand All @@ -182,7 +184,7 @@ impl tower_lsp::LanguageServer for Server {
.await;
}

async fn did_close(&self, parameters: DidCloseTextDocumentParams) {
async fn did_close(&self, parameters: lsp::DidCloseTextDocumentParams) {
// @Task unless it's a workspace(?) (a package), get rid of any diagnostics
self.client
.publish_diagnostics(parameters.text_document.uri, Vec::new(), None)
Expand All @@ -191,17 +193,19 @@ impl tower_lsp::LanguageServer for Server {

async fn goto_definition(
&self,
parameters: GotoDefinitionParams,
) -> jsonrpc::Result<Option<GotoDefinitionResponse>> {
Ok((|| {
let uri = parameters.text_document_position_params.text_document.uri;
parameters: lsp::GotoDefinitionParams,
) -> jsonrpc::Result<Option<lsp::GotoDefinitionResponse>> {
let uri = parameters.text_document_position_params.text_document.uri;
if self.validate_uri(&uri).await.is_err() {
return Ok(None);
}

let path = Path::new(uri.path());
// @Task error on unsupported URI scheme!
let content = self.documents.read().unwrap().get(&uri).unwrap().clone();
let path = Path::new(uri.path());
let content = self.documents.read().unwrap().get(&uri).unwrap().clone();

self.reset_source_map();
self.reset_source_map();

Ok((|| {
let (session, component_roots) =
check_file(path, content, &self.map, Reporter::silent()).ok()?;

Expand All @@ -227,7 +231,7 @@ impl tower_lsp::LanguageServer for Server {
return None;
};

Some(GotoDefinitionResponse::Scalar(
Some(lsp::GotoDefinitionResponse::Scalar(
session[index]
.source
.span()
Expand Down
22 changes: 11 additions & 11 deletions compiler/server/src/span.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
use span::{ByteIndex, LocalByteIndex, SourceMap, Span};
use std::path::Path;
use tower_lsp::lsp_types::{Location, Position, Range, Url};
use tower_lsp::lsp_types as lsp;

pub(crate) trait ToLocationExt {
fn to_location(self, map: &SourceMap) -> Location;
fn to_location(self, map: &SourceMap) -> lsp::Location;
}

impl ToLocationExt for Span {
fn to_location(self, map: &SourceMap) -> Location {
fn to_location(self, map: &SourceMap) -> lsp::Location {
let lines = map.lines_with_highlight(self);

Location {
lsp::Location {
// @Beacon @Task handle anonymous SourceFiles smh!!!
uri: Url::from_file_path(lines.path.unwrap()).unwrap(),
range: Range {
start: Position {
uri: lsp::Url::from_file_path(lines.path.unwrap()).unwrap(),
range: lsp::Range {
start: lsp::Position {
line: lines.first.number - 1,
character: lines.first.highlight.start - 1,
},
end: match lines.last {
Some(line) => Position {
Some(line) => lsp::Position {
line: line.number - 1,
character: line.highlight.end - 1,
},
None => Position {
None => lsp::Position {
line: lines.first.number - 1,
character: lines.first.highlight.end - 1,
},
Expand All @@ -34,12 +34,12 @@ impl ToLocationExt for Span {
}

pub(crate) trait FromPositionExt {
fn from_position(position: Position, path: &Path, map: &SourceMap) -> Self;
fn from_position(position: lsp::Position, path: &Path, map: &SourceMap) -> Self;
}

impl FromPositionExt for ByteIndex {
// @Beacon @Note this is an abomination!!!
fn from_position(position: Position, path: &Path, map: &SourceMap) -> Self {
fn from_position(position: lsp::Position, path: &Path, map: &SourceMap) -> Self {
let file = map.file_by_path(path).unwrap();
let mut index = LocalByteIndex::new(0);

Expand Down