1923 lines · 60.0 KB · Rust
RawDownload
mod buffer;mod diagnostic_set;mod highlight_map;pub mod language_settings;mod outline;pub mod proto;mod syntax_map; #[cfg(test)]mod buffer_tests; use anyhow::{anyhow, Context, Result};use async_trait::async_trait;use collections::{HashMap, HashSet};use futures::{    channel::oneshot,    future::{BoxFuture, Shared},    FutureExt, TryFutureExt as _,};use gpui::{executor::Background, AppContext, AsyncAppContext, Task};pub use highlight_map::HighlightMap;use lazy_static::lazy_static;use lsp::{CodeActionKind, LanguageServerBinary};use parking_lot::{Mutex, RwLock};use postage::watch;use regex::Regex;use serde::{de, Deserialize, Deserializer};use serde_json::Value;use std::{    any::Any,    borrow::Cow,    cell::RefCell,    fmt::Debug,    hash::Hash,    mem,    ops::{Not, Range},    path::{Path, PathBuf},    str,    sync::{        atomic::{AtomicUsize, Ordering::SeqCst},        Arc,    },};use syntax_map::SyntaxSnapshot;use theme::{SyntaxTheme, Theme};use tree_sitter::{self, Query};use unicase::UniCase;use util::{http::HttpClient, paths::PathExt};use util::{post_inc, ResultExt, TryFutureExt as _, UnwrapFuture}; #[cfg(any(test, feature = "test-support"))]use futures::channel::mpsc; pub use buffer::Operation;pub use buffer::*;pub use diagnostic_set::DiagnosticEntry;pub use lsp::LanguageServerId;pub use outline::{Outline, OutlineItem};pub use syntax_map::{OwnedSyntaxLayerInfo, SyntaxLayerInfo};pub use text::LineEnding;pub use tree_sitter::{Parser, Tree}; pub fn init(cx: &mut AppContext) {    language_settings::init(cx);} thread_local! {    static PARSER: RefCell<Parser> = RefCell::new(Parser::new());} lazy_static! {    pub static ref NEXT_GRAMMAR_ID: AtomicUsize = Default::default();    pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(        LanguageConfig {            name: "Plain Text".into(),            ..Default::default()        },        None,    ));} pub trait ToLspPosition {    fn to_lsp_position(self) -> lsp::Position;} #[derive(Clone, Debug, PartialEq, Eq, Hash)]pub struct LanguageServerName(pub Arc<str>); /// Represents a Language Server, with certain cached sync properties./// Uses [`LspAdapter`] under the hood, but calls all 'static' methods/// once at startup, and caches the results.pub struct CachedLspAdapter {    pub name: LanguageServerName,    pub short_name: &'static str,    pub initialization_options: Option<Value>,    pub disk_based_diagnostic_sources: Vec<String>,    pub disk_based_diagnostics_progress_token: Option<String>,    pub language_ids: HashMap<String, String>,    pub adapter: Arc<dyn LspAdapter>,} impl CachedLspAdapter {    pub async fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {        let name = adapter.name().await;        let short_name = adapter.short_name();        let initialization_options = adapter.initialization_options().await;        let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources().await;        let disk_based_diagnostics_progress_token =            adapter.disk_based_diagnostics_progress_token().await;        let language_ids = adapter.language_ids().await;         Arc::new(CachedLspAdapter {            name,            short_name,            initialization_options,            disk_based_diagnostic_sources,            disk_based_diagnostics_progress_token,            language_ids,            adapter,        })    }     pub async fn fetch_latest_server_version(        &self,        delegate: &dyn LspAdapterDelegate,    ) -> Result<Box<dyn 'static + Send + Any>> {        self.adapter.fetch_latest_server_version(delegate).await    }     pub fn will_fetch_server(        &self,        delegate: &Arc<dyn LspAdapterDelegate>,        cx: &mut AsyncAppContext,    ) -> Option<Task<Result<()>>> {        self.adapter.will_fetch_server(delegate, cx)    }     pub fn will_start_server(        &self,        delegate: &Arc<dyn LspAdapterDelegate>,        cx: &mut AsyncAppContext,    ) -> Option<Task<Result<()>>> {        self.adapter.will_start_server(delegate, cx)    }     pub async fn fetch_server_binary(        &self,        version: Box<dyn 'static + Send + Any>,        container_dir: PathBuf,        delegate: &dyn LspAdapterDelegate,    ) -> Result<LanguageServerBinary> {        self.adapter            .fetch_server_binary(version, container_dir, delegate)            .await    }     pub async fn cached_server_binary(        &self,        container_dir: PathBuf,        delegate: &dyn LspAdapterDelegate,    ) -> Option<LanguageServerBinary> {        self.adapter            .cached_server_binary(container_dir, delegate)            .await    }     pub fn can_be_reinstalled(&self) -> bool {        self.adapter.can_be_reinstalled()    }     pub async fn installation_test_binary(        &self,        container_dir: PathBuf,    ) -> Option<LanguageServerBinary> {        self.adapter.installation_test_binary(container_dir).await    }     pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {        self.adapter.code_action_kinds()    }     pub fn workspace_configuration(&self, cx: &mut AppContext) -> BoxFuture<'static, Value> {        self.adapter.workspace_configuration(cx)    }     pub fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {        self.adapter.process_diagnostics(params)    }     pub async fn process_completion(&self, completion_item: &mut lsp::CompletionItem) {        self.adapter.process_completion(completion_item).await    }     pub async fn label_for_completion(        &self,        completion_item: &lsp::CompletionItem,        language: &Arc<Language>,    ) -> Option<CodeLabel> {        self.adapter            .label_for_completion(completion_item, language)            .await    }     pub async fn label_for_symbol(        &self,        name: &str,        kind: lsp::SymbolKind,        language: &Arc<Language>,    ) -> Option<CodeLabel> {        self.adapter.label_for_symbol(name, kind, language).await    }} pub trait LspAdapterDelegate: Send + Sync {    fn show_notification(&self, message: &str, cx: &mut AppContext);    fn http_client(&self) -> Arc<dyn HttpClient>;} #[async_trait]pub trait LspAdapter: 'static + Send + Sync {    async fn name(&self) -> LanguageServerName;     fn short_name(&self) -> &'static str;     async fn fetch_latest_server_version(        &self,        delegate: &dyn LspAdapterDelegate,    ) -> Result<Box<dyn 'static + Send + Any>>;     fn will_fetch_server(        &self,        _: &Arc<dyn LspAdapterDelegate>,        _: &mut AsyncAppContext,    ) -> Option<Task<Result<()>>> {        None    }     fn will_start_server(        &self,        _: &Arc<dyn LspAdapterDelegate>,        _: &mut AsyncAppContext,    ) -> Option<Task<Result<()>>> {        None    }     async fn fetch_server_binary(        &self,        version: Box<dyn 'static + Send + Any>,        container_dir: PathBuf,        delegate: &dyn LspAdapterDelegate,    ) -> Result<LanguageServerBinary>;     async fn cached_server_binary(        &self,        container_dir: PathBuf,        delegate: &dyn LspAdapterDelegate,    ) -> Option<LanguageServerBinary>;     fn can_be_reinstalled(&self) -> bool {        true    }     async fn installation_test_binary(        &self,        container_dir: PathBuf,    ) -> Option<LanguageServerBinary>;     fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}     async fn process_completion(&self, _: &mut lsp::CompletionItem) {}     async fn label_for_completion(        &self,        _: &lsp::CompletionItem,        _: &Arc<Language>,    ) -> Option<CodeLabel> {        None    }     async fn label_for_symbol(        &self,        _: &str,        _: lsp::SymbolKind,        _: &Arc<Language>,    ) -> Option<CodeLabel> {        None    }     async fn initialization_options(&self) -> Option<Value> {        None    }     fn workspace_configuration(&self, _: &mut AppContext) -> BoxFuture<'static, Value> {        futures::future::ready(serde_json::json!({})).boxed()    }     fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {        Some(vec![            CodeActionKind::EMPTY,            CodeActionKind::QUICKFIX,            CodeActionKind::REFACTOR,            CodeActionKind::REFACTOR_EXTRACT,            CodeActionKind::SOURCE,        ])    }     async fn disk_based_diagnostic_sources(&self) -> Vec<String> {        Default::default()    }     async fn disk_based_diagnostics_progress_token(&self) -> Option<String> {        None    }     async fn language_ids(&self) -> HashMap<String, String> {        Default::default()    }} #[derive(Clone, Debug, PartialEq, Eq)]pub struct CodeLabel {    pub text: String,    pub runs: Vec<(Range<usize>, HighlightId)>,    pub filter_range: Range<usize>,} #[derive(Clone, Deserialize)]pub struct LanguageConfig {    pub name: Arc<str>,    pub path_suffixes: Vec<String>,    pub brackets: BracketPairConfig,    #[serde(default, deserialize_with = "deserialize_regex")]    pub first_line_pattern: Option<Regex>,    #[serde(default = "auto_indent_using_last_non_empty_line_default")]    pub auto_indent_using_last_non_empty_line: bool,    #[serde(default, deserialize_with = "deserialize_regex")]    pub increase_indent_pattern: Option<Regex>,    #[serde(default, deserialize_with = "deserialize_regex")]    pub decrease_indent_pattern: Option<Regex>,    #[serde(default)]    pub autoclose_before: String,    #[serde(default)]    pub line_comment: Option<Arc<str>>,    #[serde(default)]    pub collapsed_placeholder: String,    #[serde(default)]    pub block_comment: Option<(Arc<str>, Arc<str>)>,    #[serde(default)]    pub scope_opt_in_language_servers: Vec<String>,    #[serde(default)]    pub overrides: HashMap<String, LanguageConfigOverride>,    #[serde(default)]    pub word_characters: HashSet<char>,} #[derive(Debug, Default)]pub struct LanguageQueries {    pub highlights: Option<Cow<'static, str>>,    pub brackets: Option<Cow<'static, str>>,    pub indents: Option<Cow<'static, str>>,    pub outline: Option<Cow<'static, str>>,    pub embedding: Option<Cow<'static, str>>,    pub injections: Option<Cow<'static, str>>,    pub overrides: Option<Cow<'static, str>>,} #[derive(Clone, Debug)]pub struct LanguageScope {    language: Arc<Language>,    override_id: Option<u32>,} #[derive(Clone, Deserialize, Default, Debug)]pub struct LanguageConfigOverride {    #[serde(default)]    pub line_comment: Override<Arc<str>>,    #[serde(default)]    pub block_comment: Override<(Arc<str>, Arc<str>)>,    #[serde(skip_deserializing)]    pub disabled_bracket_ixs: Vec<u16>,    #[serde(default)]    pub word_characters: Override<HashSet<char>>,    #[serde(default)]    pub opt_into_language_servers: Vec<String>,} #[derive(Clone, Deserialize, Debug)]#[serde(untagged)]pub enum Override<T> {    Remove { remove: bool },    Set(T),} impl<T> Default for Override<T> {    fn default() -> Self {        Override::Remove { remove: false }    }} impl<T> Override<T> {    fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {        match this {            Some(Self::Set(value)) => Some(value),            Some(Self::Remove { remove: true }) => None,            Some(Self::Remove { remove: false }) | None => original,        }    }} impl Default for LanguageConfig {    fn default() -> Self {        Self {            name: "".into(),            path_suffixes: Default::default(),            brackets: Default::default(),            auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),            first_line_pattern: Default::default(),            increase_indent_pattern: Default::default(),            decrease_indent_pattern: Default::default(),            autoclose_before: Default::default(),            line_comment: Default::default(),            block_comment: Default::default(),            scope_opt_in_language_servers: Default::default(),            overrides: Default::default(),            collapsed_placeholder: Default::default(),            word_characters: Default::default(),        }    }} fn auto_indent_using_last_non_empty_line_default() -> bool {    true} fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {    let source = Option::<String>::deserialize(d)?;    if let Some(source) = source {        Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))    } else {        Ok(None)    }} #[cfg(any(test, feature = "test-support"))]pub struct FakeLspAdapter {    pub name: &'static str,    pub initialization_options: Option<Value>,    pub capabilities: lsp::ServerCapabilities,    pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,    pub disk_based_diagnostics_progress_token: Option<String>,    pub disk_based_diagnostics_sources: Vec<String>,} #[derive(Clone, Debug, Default)]pub struct BracketPairConfig {    pub pairs: Vec<BracketPair>,    pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,} impl<'de> Deserialize<'de> for BracketPairConfig {    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>    where        D: Deserializer<'de>,    {        #[derive(Deserialize)]        pub struct Entry {            #[serde(flatten)]            pub bracket_pair: BracketPair,            #[serde(default)]            pub not_in: Vec<String>,        }         let result = Vec::<Entry>::deserialize(deserializer)?;        let mut brackets = Vec::with_capacity(result.len());        let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());        for entry in result {            brackets.push(entry.bracket_pair);            disabled_scopes_by_bracket_ix.push(entry.not_in);        }         Ok(BracketPairConfig {            pairs: brackets,            disabled_scopes_by_bracket_ix,        })    }} #[derive(Clone, Debug, Default, Deserialize, PartialEq)]pub struct BracketPair {    pub start: String,    pub end: String,    pub close: bool,    pub newline: bool,} pub struct Language {    pub(crate) config: LanguageConfig,    pub(crate) grammar: Option<Arc<Grammar>>,    pub(crate) adapters: Vec<Arc<CachedLspAdapter>>, 

Lines 1–500 of 1923.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t