Merge pull request #526 from zed-industries/json

Add basic JSON support
This commit is contained in:
Max Brunsfeld 2022-03-03 16:07:04 -08:00 committed by GitHub
commit 15312d0ac3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 327 additions and 73 deletions

11
Cargo.lock generated
View File

@ -5326,6 +5326,16 @@ dependencies = [
"tree-sitter",
]
[[package]]
name = "tree-sitter-json"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90b04c4e1a92139535eb9fca4ec8fa9666cc96b618005d3ae35f3c957fa92f92"
dependencies = [
"cc",
"tree-sitter",
]
[[package]]
name = "tree-sitter-markdown"
version = "0.0.1"
@ -5935,6 +5945,7 @@ dependencies = [
"toml",
"tree-sitter",
"tree-sitter-c",
"tree-sitter-json",
"tree-sitter-markdown",
"tree-sitter-rust",
"unindent",

View File

@ -6,7 +6,7 @@ pub mod proto;
#[cfg(test)]
mod tests;
use anyhow::{anyhow, Result};
use anyhow::{anyhow, Context, Result};
use client::http::{self, HttpClient};
use collections::HashSet;
use futures::{
@ -18,6 +18,7 @@ use highlight_map::HighlightMap;
use lazy_static::lazy_static;
use parking_lot::{Mutex, RwLock};
use serde::Deserialize;
use serde_json::Value;
use std::{
cell::RefCell,
ops::Range,
@ -61,10 +62,11 @@ pub trait ToLspPosition {
pub struct LspBinaryVersion {
pub name: String,
pub url: http::Url,
pub url: Option<http::Url>,
}
pub trait LspExt: 'static + Send + Sync {
pub trait LspAdapter: 'static + Send + Sync {
fn name(&self) -> &'static str;
fn fetch_latest_server_version(
&self,
http: Arc<dyn HttpClient>,
@ -73,16 +75,26 @@ pub trait LspExt: 'static + Send + Sync {
&self,
version: LspBinaryVersion,
http: Arc<dyn HttpClient>,
download_dir: Arc<Path>,
container_dir: PathBuf,
) -> BoxFuture<'static, Result<PathBuf>>;
fn cached_server_binary(&self, download_dir: Arc<Path>) -> BoxFuture<'static, Option<PathBuf>>;
fn cached_server_binary(&self, container_dir: PathBuf) -> BoxFuture<'static, Option<PathBuf>>;
fn process_diagnostics(&self, diagnostics: &mut lsp::PublishDiagnosticsParams);
fn label_for_completion(&self, _: &lsp::CompletionItem, _: &Language) -> Option<CodeLabel> {
None
}
fn label_for_symbol(&self, _: &str, _: lsp::SymbolKind, _: &Language) -> Option<CodeLabel> {
None
}
fn server_args(&self) -> &[&str] {
&[]
}
fn initialization_options(&self) -> Option<Value> {
None
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
@ -140,7 +152,7 @@ pub struct BracketPair {
pub struct Language {
pub(crate) config: LanguageConfig,
pub(crate) grammar: Option<Arc<Grammar>>,
pub(crate) lsp_ext: Option<Arc<dyn LspExt>>,
pub(crate) adapter: Option<Arc<dyn LspAdapter>>,
lsp_binary_path: Mutex<Option<Shared<BoxFuture<'static, Result<PathBuf, Arc<anyhow::Error>>>>>>,
}
@ -260,7 +272,7 @@ impl LanguageRegistry {
.ok_or_else(|| anyhow!("language server download directory has not been assigned"))
.log_err()?;
let lsp_ext = language.lsp_ext.clone()?;
let adapter = language.adapter.clone()?;
let background = cx.background().clone();
let server_binary_path = {
Some(
@ -269,7 +281,7 @@ impl LanguageRegistry {
.lock()
.get_or_insert_with(|| {
get_server_binary_path(
lsp_ext,
adapter.clone(),
language.clone(),
http_client,
download_dir,
@ -285,7 +297,14 @@ impl LanguageRegistry {
}?;
Some(cx.background().spawn(async move {
let server_binary_path = server_binary_path.await?;
let server = lsp::LanguageServer::new(&server_binary_path, &root_path, background)?;
let server_args = adapter.server_args();
let server = lsp::LanguageServer::new(
&server_binary_path,
server_args,
adapter.initialization_options(),
&root_path,
background,
)?;
Ok(server)
}))
}
@ -298,22 +317,29 @@ impl LanguageRegistry {
}
async fn get_server_binary_path(
lsp_ext: Arc<dyn LspExt>,
adapter: Arc<dyn LspAdapter>,
language: Arc<Language>,
http_client: Arc<dyn HttpClient>,
download_dir: Arc<Path>,
statuses: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
) -> Result<PathBuf> {
let container_dir = download_dir.join(adapter.name());
if !container_dir.exists() {
smol::fs::create_dir_all(&container_dir)
.await
.context("failed to create container directory")?;
}
let path = fetch_latest_server_binary_path(
lsp_ext.clone(),
adapter.clone(),
language.clone(),
http_client,
download_dir.clone(),
&container_dir,
statuses.clone(),
)
.await;
if path.is_err() {
if let Some(cached_path) = lsp_ext.cached_server_binary(download_dir).await {
if let Some(cached_path) = adapter.cached_server_binary(container_dir).await {
statuses
.broadcast((language.clone(), LanguageServerBinaryStatus::Cached))
.await?;
@ -328,10 +354,10 @@ async fn get_server_binary_path(
}
async fn fetch_latest_server_binary_path(
lsp_ext: Arc<dyn LspExt>,
adapter: Arc<dyn LspAdapter>,
language: Arc<Language>,
http_client: Arc<dyn HttpClient>,
download_dir: Arc<Path>,
container_dir: &Path,
lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
) -> Result<PathBuf> {
lsp_binary_statuses_tx
@ -340,14 +366,14 @@ async fn fetch_latest_server_binary_path(
LanguageServerBinaryStatus::CheckingForUpdate,
))
.await?;
let version_info = lsp_ext
let version_info = adapter
.fetch_latest_server_version(http_client.clone())
.await?;
lsp_binary_statuses_tx
.broadcast((language.clone(), LanguageServerBinaryStatus::Downloading))
.await?;
let path = lsp_ext
.fetch_server_binary(version_info, http_client, download_dir)
let path = adapter
.fetch_server_binary(version_info, http_client, container_dir.to_path_buf())
.await?;
lsp_binary_statuses_tx
.broadcast((language.clone(), LanguageServerBinaryStatus::Downloaded))
@ -369,7 +395,7 @@ impl Language {
highlight_map: Default::default(),
})
}),
lsp_ext: None,
adapter: None,
lsp_binary_path: Default::default(),
}
}
@ -414,8 +440,8 @@ impl Language {
Ok(self)
}
pub fn with_lsp_ext(mut self, lsp_ext: impl LspExt) -> Self {
self.lsp_ext = Some(Arc::new(lsp_ext));
pub fn with_lsp_adapter(mut self, lsp_adapter: impl LspAdapter) -> Self {
self.adapter = Some(Arc::new(lsp_adapter));
self
}
@ -442,19 +468,19 @@ impl Language {
}
pub fn process_diagnostics(&self, diagnostics: &mut lsp::PublishDiagnosticsParams) {
if let Some(processor) = self.lsp_ext.as_ref() {
if let Some(processor) = self.adapter.as_ref() {
processor.process_diagnostics(diagnostics);
}
}
pub fn label_for_completion(&self, completion: &lsp::CompletionItem) -> Option<CodeLabel> {
self.lsp_ext
self.adapter
.as_ref()?
.label_for_completion(completion, self)
}
pub fn label_for_symbol(&self, name: &str, kind: lsp::SymbolKind) -> Option<CodeLabel> {
self.lsp_ext.as_ref()?.label_for_symbol(name, kind, self)
self.adapter.as_ref()?.label_for_symbol(name, kind, self)
}
pub fn highlight_text<'a>(
@ -548,7 +574,7 @@ impl LanguageServerConfig {
Self {
fake_config: Some(FakeLanguageServerConfig {
servers_tx,
capabilities: Default::default(),
capabilities: lsp::LanguageServer::full_capabilities(),
initializer: None,
}),
disk_based_diagnostics_progress_token: Some("fakeServer/check".to_string()),

View File

@ -102,23 +102,28 @@ struct Error {
impl LanguageServer {
pub fn new(
binary_path: &Path,
args: &[&str],
options: Option<Value>,
root_path: &Path,
background: Arc<executor::Background>,
) -> Result<Arc<Self>> {
let mut server = Command::new(binary_path)
.current_dir(root_path)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()?;
let stdin = server.stdin.take().unwrap();
let stdout = server.stdout.take().unwrap();
Self::new_internal(stdin, stdout, root_path, background)
Self::new_internal(stdin, stdout, root_path, options, background)
}
fn new_internal<Stdin, Stdout>(
stdin: Stdin,
stdout: Stdout,
root_path: &Path,
options: Option<Value>,
executor: Arc<executor::Background>,
) -> Result<Arc<Self>>
where
@ -229,7 +234,7 @@ impl LanguageServer {
.spawn({
let this = this.clone();
async move {
if let Some(capabilities) = this.init(root_uri).log_err().await {
if let Some(capabilities) = this.init(root_uri, options).log_err().await {
*capabilities_tx.borrow_mut() = Some(capabilities);
}
@ -241,13 +246,17 @@ impl LanguageServer {
Ok(this)
}
async fn init(self: Arc<Self>, root_uri: Url) -> Result<ServerCapabilities> {
async fn init(
self: Arc<Self>,
root_uri: Url,
options: Option<Value>,
) -> Result<ServerCapabilities> {
#[allow(deprecated)]
let params = InitializeParams {
process_id: Default::default(),
root_path: Default::default(),
root_uri: Some(root_uri),
initialization_options: Default::default(),
initialization_options: options,
capabilities: ClientCapabilities {
text_document: Some(TextDocumentClientCapabilities {
definition: Some(GotoCapability {
@ -503,8 +512,16 @@ type FakeLanguageServerHandlers = Arc<
#[cfg(any(test, feature = "test-support"))]
impl LanguageServer {
pub fn full_capabilities() -> ServerCapabilities {
ServerCapabilities {
document_highlight_provider: Some(OneOf::Left(true)),
code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
..Default::default()
}
}
pub fn fake(cx: &mut gpui::MutableAppContext) -> (Arc<Self>, FakeLanguageServer) {
Self::fake_with_capabilities(Default::default(), cx)
Self::fake_with_capabilities(Self::full_capabilities(), cx)
}
pub fn fake_with_capabilities(
@ -527,6 +544,7 @@ impl LanguageServer {
stdin_writer,
stdout_reader,
Path::new("/"),
None,
cx.background().clone(),
)
.unwrap();

View File

@ -8,7 +8,7 @@ use language::{
proto::{deserialize_anchor, serialize_anchor},
range_from_lsp, Anchor, Bias, Buffer, PointUtf16, ToLspPosition, ToPointUtf16,
};
use lsp::DocumentHighlightKind;
use lsp::{DocumentHighlightKind, ServerCapabilities};
use std::{cmp::Reverse, ops::Range, path::Path};
#[async_trait(?Send)]
@ -17,6 +17,10 @@ pub(crate) trait LspCommand: 'static + Sized {
type LspRequest: 'static + Send + lsp::request::Request;
type ProtoRequest: 'static + Send + proto::RequestMessage;
fn check_capabilities(&self, _: &lsp::ServerCapabilities) -> bool {
true
}
fn to_lsp(
&self,
path: &Path,
@ -610,6 +614,10 @@ impl LspCommand for GetDocumentHighlights {
type LspRequest = lsp::request::DocumentHighlightRequest;
type ProtoRequest = proto::GetDocumentHighlights;
fn check_capabilities(&self, capabilities: &ServerCapabilities) -> bool {
capabilities.document_highlight_provider.is_some()
}
fn to_lsp(&self, path: &Path, _: &AppContext) -> lsp::DocumentHighlightParams {
lsp::DocumentHighlightParams {
text_document_position_params: lsp::TextDocumentPositionParams {

View File

@ -22,7 +22,7 @@ use language::{
};
use lsp::{DiagnosticSeverity, DocumentHighlightKind, LanguageServer};
use lsp_command::*;
use postage::watch;
use postage::{prelude::Stream, watch};
use rand::prelude::*;
use search::SearchQuery;
use sha2::{Digest, Sha256};
@ -1322,6 +1322,7 @@ impl Project {
cx: &mut ModelContext<Self>,
) -> Task<Result<Vec<DocumentHighlight>>> {
let position = position.to_point_utf16(buffer.read(cx));
self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
}
@ -1729,6 +1730,20 @@ impl Project {
range.end.to_point_utf16(buffer).to_lsp_position(),
);
cx.foreground().spawn(async move {
let mut capabilities = lang_server.capabilities();
while capabilities.borrow().is_none() {
capabilities.recv().await;
}
if !capabilities
.borrow()
.as_ref()
.map_or(false, |capabilities| {
capabilities.code_action_provider.is_some()
})
{
return Ok(Default::default());
}
Ok(lang_server
.request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
text_document: lsp::TextDocumentIdentifier::new(
@ -2251,6 +2266,21 @@ impl Project {
if let Some((file, language_server)) = file.zip(buffer.language_server().cloned()) {
let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
return cx.spawn(|this, cx| async move {
let mut capabilities = language_server.capabilities();
while capabilities.borrow().is_none() {
capabilities.recv().await;
}
if !capabilities
.borrow()
.as_ref()
.map_or(false, |capabilities| {
request.check_capabilities(&capabilities)
})
{
return Ok(Default::default());
}
let response = language_server
.request::<R::LspRequest>(lsp_params)
.await

View File

@ -92,6 +92,7 @@ tiny_http = "0.8"
toml = "0.5"
tree-sitter = "0.20.4"
tree-sitter-c = "0.20.1"
tree-sitter-json = "0.19.0"
tree-sitter-rust = "0.20.1"
tree-sitter-markdown = { git = "https://github.com/MDeiml/tree-sitter-markdown", rev = "330ecab87a3e3a7211ac69bbadc19eabecdb1cca" }
url = "2.2"

View File

@ -0,0 +1,3 @@
("[" @open "]" @close)
("{" @open "}" @close)
("\"" @open "\"" @close)

View File

@ -0,0 +1,3 @@
("[" @open "]" @close)
("{" @open "}" @close)
("\"" @open "\"" @close)

View File

@ -0,0 +1,10 @@
name = "JSON"
path_suffixes = ["json"]
brackets = [
{ start = "{", end = "}", close = true, newline = true },
{ start = "[", end = "]", close = true, newline = true },
{ start = "\"", end = "\"", close = true, newline = false },
]
[language_server]
disk_based_diagnostic_sources = []

View File

@ -0,0 +1,12 @@
(string) @string
(pair
key: (string) @property)
(number) @number
[
(true)
(false)
(null)
] @constant

View File

@ -0,0 +1,2 @@
(array "]" @end) @indent
(object "}" @end) @indent

View File

@ -0,0 +1,2 @@
(pair
key: (string (string_content) @name)) @item

View File

@ -7,22 +7,18 @@ use lazy_static::lazy_static;
use regex::Regex;
use rust_embed::RustEmbed;
use serde::Deserialize;
use serde_json::json;
use smol::fs::{self, File};
use std::{
borrow::Cow,
env::consts,
path::{Path, PathBuf},
str,
sync::Arc,
};
use std::{borrow::Cow, env::consts, path::PathBuf, str, sync::Arc};
use util::{ResultExt, TryFutureExt};
#[derive(RustEmbed)]
#[folder = "languages"]
struct LanguageDir;
struct RustLsp;
struct CLsp;
struct RustLspAdapter;
struct CLspAdapter;
struct JsonLspAdapter;
#[derive(Deserialize)]
struct GithubRelease {
@ -36,7 +32,11 @@ struct GithubReleaseAsset {
browser_download_url: http::Url,
}
impl LspExt for RustLsp {
impl LspAdapter for RustLspAdapter {
fn name(&self) -> &'static str {
"rust-analyzer"
}
fn fetch_latest_server_version(
&self,
http: Arc<dyn HttpClient>,
@ -67,7 +67,7 @@ impl LspExt for RustLsp {
.ok_or_else(|| anyhow!("no release found matching {:?}", asset_name))?;
Ok(LspBinaryVersion {
name: release.name,
url: asset.browser_download_url.clone(),
url: Some(asset.browser_download_url.clone()),
})
}
.boxed()
@ -77,18 +77,15 @@ impl LspExt for RustLsp {
&self,
version: LspBinaryVersion,
http: Arc<dyn HttpClient>,
download_dir: Arc<Path>,
container_dir: PathBuf,
) -> BoxFuture<'static, Result<PathBuf>> {
async move {
let destination_dir_path = download_dir.join("rust-analyzer");
fs::create_dir_all(&destination_dir_path).await?;
let destination_path =
destination_dir_path.join(format!("rust-analyzer-{}", version.name));
let destination_path = container_dir.join(format!("rust-analyzer-{}", version.name));
if fs::metadata(&destination_path).await.is_err() {
let response = http
.send(
surf::RequestBuilder::new(Method::Get, version.url)
surf::RequestBuilder::new(Method::Get, version.url.unwrap())
.middleware(surf::middleware::Redirect::default())
.build(),
)
@ -103,7 +100,7 @@ impl LspExt for RustLsp {
)
.await?;
if let Some(mut entries) = fs::read_dir(&destination_dir_path).await.log_err() {
if let Some(mut entries) = fs::read_dir(&container_dir).await.log_err() {
while let Some(entry) = entries.next().await {
if let Some(entry) = entry.log_err() {
let entry_path = entry.path();
@ -120,13 +117,10 @@ impl LspExt for RustLsp {
.boxed()
}
fn cached_server_binary(&self, download_dir: Arc<Path>) -> BoxFuture<'static, Option<PathBuf>> {
fn cached_server_binary(&self, container_dir: PathBuf) -> BoxFuture<'static, Option<PathBuf>> {
async move {
let destination_dir_path = download_dir.join("rust-analyzer");
fs::create_dir_all(&destination_dir_path).await?;
let mut last = None;
let mut entries = fs::read_dir(&destination_dir_path).await?;
let mut entries = fs::read_dir(&container_dir).await?;
while let Some(entry) = entries.next().await {
last = Some(entry?.path());
}
@ -292,7 +286,11 @@ impl LspExt for RustLsp {
}
}
impl LspExt for CLsp {
impl LspAdapter for CLspAdapter {
fn name(&self) -> &'static str {
"clangd"
}
fn fetch_latest_server_version(
&self,
http: Arc<dyn HttpClient>,
@ -323,7 +321,7 @@ impl LspExt for CLsp {
.ok_or_else(|| anyhow!("no release found matching {:?}", asset_name))?;
Ok(LspBinaryVersion {
name: release.name,
url: asset.browser_download_url.clone(),
url: Some(asset.browser_download_url.clone()),
})
}
.boxed()
@ -333,14 +331,9 @@ impl LspExt for CLsp {
&self,
version: LspBinaryVersion,
http: Arc<dyn HttpClient>,
download_dir: Arc<Path>,
container_dir: PathBuf,
) -> BoxFuture<'static, Result<PathBuf>> {
async move {
let container_dir = download_dir.join("clangd");
fs::create_dir_all(&container_dir)
.await
.context("failed to create container directory")?;
let zip_path = container_dir.join(format!("clangd_{}.zip", version.name));
let version_dir = container_dir.join(format!("clangd_{}", version.name));
let binary_path = version_dir.join("bin/clangd");
@ -348,7 +341,7 @@ impl LspExt for CLsp {
if fs::metadata(&binary_path).await.is_err() {
let response = http
.send(
surf::RequestBuilder::new(Method::Get, version.url)
surf::RequestBuilder::new(Method::Get, version.url.unwrap())
.middleware(surf::middleware::Redirect::default())
.build(),
)
@ -390,13 +383,10 @@ impl LspExt for CLsp {
.boxed()
}
fn cached_server_binary(&self, download_dir: Arc<Path>) -> BoxFuture<'static, Option<PathBuf>> {
fn cached_server_binary(&self, container_dir: PathBuf) -> BoxFuture<'static, Option<PathBuf>> {
async move {
let destination_dir_path = download_dir.join("clangd");
fs::create_dir_all(&destination_dir_path).await?;
let mut last_clangd_dir = None;
let mut entries = fs::read_dir(&destination_dir_path).await?;
let mut entries = fs::read_dir(&container_dir).await?;
while let Some(entry) = entries.next().await {
let entry = entry?;
if entry.file_type().await?.is_dir() {
@ -421,6 +411,126 @@ impl LspExt for CLsp {
fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
}
impl JsonLspAdapter {
const BIN_PATH: &'static str =
"node_modules/vscode-json-languageserver/bin/vscode-json-languageserver";
}
impl LspAdapter for JsonLspAdapter {
fn name(&self) -> &'static str {
"vscode-json-languageserver"
}
fn server_args(&self) -> &[&str] {
&["--stdio"]
}
fn fetch_latest_server_version(
&self,
_: Arc<dyn HttpClient>,
) -> BoxFuture<'static, Result<LspBinaryVersion>> {
async move {
#[derive(Deserialize)]
struct NpmInfo {
versions: Vec<String>,
}
let output = smol::process::Command::new("npm")
.args(["info", "vscode-json-languageserver", "--json"])
.output()
.await?;
if !output.status.success() {
Err(anyhow!("failed to execute npm info"))?;
}
let mut info: NpmInfo = serde_json::from_slice(&output.stdout)?;
Ok(LspBinaryVersion {
name: info
.versions
.pop()
.ok_or_else(|| anyhow!("no versions found in npm info"))?,
url: Default::default(),
})
}
.boxed()
}
fn fetch_server_binary(
&self,
version: LspBinaryVersion,
_: Arc<dyn HttpClient>,
container_dir: PathBuf,
) -> BoxFuture<'static, Result<PathBuf>> {
async move {
let version_dir = container_dir.join(&version.name);
fs::create_dir_all(&version_dir)
.await
.context("failed to create version directory")?;
let binary_path = version_dir.join(Self::BIN_PATH);
if fs::metadata(&binary_path).await.is_err() {
let output = smol::process::Command::new("npm")
.current_dir(&version_dir)
.arg("install")
.arg(format!("vscode-json-languageserver@{}", version.name))
.output()
.await
.context("failed to run npm install")?;
if !output.status.success() {
Err(anyhow!("failed to install vscode-json-languageserver"))?;
}
if let Some(mut entries) = fs::read_dir(&container_dir).await.log_err() {
while let Some(entry) = entries.next().await {
if let Some(entry) = entry.log_err() {
let entry_path = entry.path();
if entry_path.as_path() != version_dir {
fs::remove_dir_all(&entry_path).await.log_err();
}
}
}
}
}
Ok(binary_path)
}
.boxed()
}
fn cached_server_binary(&self, container_dir: PathBuf) -> BoxFuture<'static, Option<PathBuf>> {
async move {
let mut last_version_dir = None;
let mut entries = fs::read_dir(&container_dir).await?;
while let Some(entry) = entries.next().await {
let entry = entry?;
if entry.file_type().await?.is_dir() {
last_version_dir = Some(entry.path());
}
}
let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
let bin_path = last_version_dir.join(Self::BIN_PATH);
if bin_path.exists() {
Ok(bin_path)
} else {
Err(anyhow!(
"missing executable in directory {:?}",
last_version_dir
))
}
}
.log_err()
.boxed()
}
fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
fn initialization_options(&self) -> Option<serde_json::Value> {
Some(json!({
"provideFormatter": true
}))
}
}
pub fn build_language_registry() -> LanguageRegistry {
let mut languages = LanguageRegistry::new();
languages.set_language_server_download_dir(
@ -429,6 +539,7 @@ pub fn build_language_registry() -> LanguageRegistry {
.join(".zed"),
);
languages.add(Arc::new(c()));
languages.add(Arc::new(json()));
languages.add(Arc::new(rust()));
languages.add(Arc::new(markdown()));
languages
@ -446,7 +557,7 @@ fn rust() -> Language {
.unwrap()
.with_outline_query(load_query("rust/outline.scm").as_ref())
.unwrap()
.with_lsp_ext(RustLsp)
.with_lsp_adapter(RustLspAdapter)
}
fn c() -> Language {
@ -455,11 +566,28 @@ fn c() -> Language {
Language::new(config, Some(grammar))
.with_highlights_query(load_query("c/highlights.scm").as_ref())
.unwrap()
.with_brackets_query(load_query("c/brackets.scm").as_ref())
.unwrap()
.with_indents_query(load_query("c/indents.scm").as_ref())
.unwrap()
.with_outline_query(load_query("c/outline.scm").as_ref())
.unwrap()
.with_lsp_ext(CLsp)
.with_lsp_adapter(CLspAdapter)
}
fn json() -> Language {
let grammar = tree_sitter_json::language();
let config = toml::from_slice(&LanguageDir::get("json/config.toml").unwrap().data).unwrap();
Language::new(config, Some(grammar))
.with_highlights_query(load_query("json/highlights.scm").as_ref())
.unwrap()
.with_brackets_query(load_query("json/brackets.scm").as_ref())
.unwrap()
.with_indents_query(load_query("json/indents.scm").as_ref())
.unwrap()
.with_outline_query(load_query("json/outline.scm").as_ref())
.unwrap()
.with_lsp_adapter(JsonLspAdapter)
}
fn markdown() -> Language {
@ -481,7 +609,7 @@ fn load_query(path: &str) -> Cow<'static, str> {
mod tests {
use super::*;
use gpui::color::Color;
use language::LspExt;
use language::LspAdapter;
use theme::SyntaxTheme;
#[test]
@ -508,7 +636,7 @@ mod tests {
},
],
};
RustLsp.process_diagnostics(&mut params);
RustLspAdapter.process_diagnostics(&mut params);
assert_eq!(params.diagnostics[0].message, "use of moved value `a`");